Re: Standard class for time *period*?

2023-03-27 Thread Gary Herron
The Python standard library module datetime seems to be what you want.  
It has objects representing date/times, and deltatimes (i.e., 
durations).  These can be timezone aware or not as you wish.


Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology

On 3/27/23 6:00 AM, loris.benn...@fu-berlin.de wrote:

Hi,

I have been around long enough to know that, due to time-zones, daylight
saving and whatnot, time-related stuff is complicated.  So even if I
think something connected with time should exist, there may well be a
very good reason why it does not.

My problem:

   I need to deal with what I call a 'period', which is a span of time
   limited by two dates, start and end.  The period has a 'duration',
   which is the elapsed time between start and end.  The duration is
   essentially a number of seconds, but in my context, because the
   durations are usually hours or days, I would generally want to display
   the duration in a format such as "dd-hh:mm:ss"

My (possibly ill-founded) expectation:

   There is a standard class which encapsulates this sort of functionality.

My (possibly insufficiently researched) conclusion:

   Such a standard class does not exist.

What is at fault here?  My expectation or my conclusion?

Cheers,

Loris


--
https://mail.python.org/mailman/listinfo/python-list


Re: =- and -= snag

2023-03-13 Thread Gary Herron



On 3/13/23 2:26 PM, morp...@gmail.com wrote:

Hi.

I was working in Python today, and sat there scratching my head as the
numbers for calculations didn't add up.  It went into negative numbers,
when that shouldn't have been possible.

Turns out I had a very small typo, I had =- instead of -=.

Isn't it unpythonic to be able to make a mistake like that?

Regards,

Morten



These all mean the same thing, but I don't see a good way to designate 
the second or third as an error.



x = -5
x=-5
x =- 5


Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology

--
https://mail.python.org/mailman/listinfo/python-list


Re: Change first occurrence of character x in a string - how?

2021-02-14 Thread Gary Herron

The string type has a replace function that does what you want.
Except you can't change a string -- they are immutable -- so this 
creates a new string.



>>> s = 'linux-raid.vger.kernel.org'
>>> new_s = s.replace('.', '@', 1)
>>> new_s
'linux-r...@vger.kernel.org'



On 2/14/21 1:14 PM, c...@isbd.net wrote:

What's the easiest way to change the first occurrence of a specified
character in a string?

E.g. I want to change linux-raid.vger.kernel.org to
linux-r...@vger.kernel.org, it's a fairly general requirement of
needing to change '.' to '@'.

Alternatively is there an RE 'match' function that would test if
linux-r...@vger.kernel.org matches linux-raid.vger.kernel.org? I don't
really care if the '.' are all regarded as wild cards, the match will
be accurate enough.


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Calculations and Variables

2019-10-31 Thread Gary Herron


On 10/31/19 11:46 AM, ferzan...@gmail.com wrote:

The code below which I have written should print the result of 43.6 with the 
given values I have included at the end of this question, but for some odd 
reason I get the result of 44.44.


bill = (input("Enter the total cost of the meal: \n"))  
  
tip = (input("Enter how much the tip is: \n"))  
  
split = (input("Enter how many people there are: \n"))  
  
total = bill + (bill / tip) 


Don't you mean
 total = bill + (bill * tip) ?



eachPay = total / split 
print("Each person will have to pay %.2f" % eachPay)



I am aiming for the result of 43.6, but somehow get the result of 44.44.
(meal cost: 200) (Tip: 9) (people: 5)

I seem to do the calculation below, but get different results each time.
Total * Percentage Amount / 100


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Multiprocessing and memory management

2019-07-03 Thread Gary Herron


On 7/3/19 9:37 AM, ijbrews...@alaska.edu wrote:

I have a script that benefits greatly from multiprocessing (it’s generating a 
bunch of images from data). Of course, as expected each process uses a chunk of 
memory, and the more processes there are, the more memory used. The amount used 
per process can vary from around 3 GB (yes, gigabytes) to over 40 or 50 GB, 
depending on the amount of data being processed (usually closer to 10GB, the 
40/50 is fairly rare). This puts me in a position of needing to balance the 
number of processes with memory usage, such that I maximize resource 
utilization (running one process at a time would simply take WAY to long) while 
not overloading RAM (which at best would slow things down due to swap).

Obviously this process will be run on a machine with lots of RAM, but as I 
don’t know how large the datasets that will be fed to it are, I wanted to see 
if I could build some intelligence into the program such that it doesn’t 
overload the memory. A couple of approaches I thought of:

1) Determine the total amount of RAM in the machine (how?), assume an average 
of 10GB per process, and only launch as many processes as calculated to fit. 
Easy, but would run the risk of under-utilizing the processing capabilities and 
taking longer to run if most of the processes were using significantly less 
than 10GB



Try psutil to get information about memory (and cpu usage and lots 
more).  For example:


>>> import psutil
>>> psutil.virtual_memory()
svmem(total=16769519616, available=9151971328, percent=45.4, 
used=7031549952, free=4486520832, active=9026158592, 
inactive=2238566400, buffers=312815616, cached=4938633216, 
shared=234295296, slab=593375232)


Home page: https://github.com/giampaolo/psutil




2) Somehow monitor the memory usage of the various processes, and if one 
process needs a lot, pause the others until that one is complete. Of course, 
I’m not sure if this is even possible.

3) Other approaches?


---
Israel Brewster
Software Engineer
Alaska Volcano Observatory
Geophysical Institute - UAF
2156 Koyukuk Drive
Fairbanks AK 99775-7320
Work: 907-474-5172
cell:  907-328-9145


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: CAD Application

2019-05-06 Thread Gary Herron



On 5/5/19 10:23 PM, britt...@gmail.com wrote:

Hello All,

What are the frameworks available for developing a CAD application with
Python?


Regards
Britto


Well, there's PythonCadhttps://sourceforge.net/projects/pythoncad/

It seems to have stopped development about 5 years ago, but it's still 
available for download.



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: namedtuples anamoly

2018-10-18 Thread Gary Herron



On 10/17/2018 11:13 PM, me.vi...@gmail.com wrote:

Hi,

I tried using namedtuples and just found a behaviour which I am not able to
conclude as correct behaviour.

from collections import namedtuple

(n, categories) = (int(input()), input().split())
Grade = namedtuple('Grade', categories)
Grade.ID = 1
#print(Grade.ID)
ob = Grade(10, 50)
print(ob.ID)
print(ob.MARKS)
ob1 = Grade(20, 100)
print(ob1.ID)

2
ID MARKS
1
50
1
100


If we set GRADE.ID =1 ,


Whoa!  Don't do that.  The Grade object created with the namedtuple call 
is a class, and part of it's internal implementation is stored in 
Grade.ID.  Try these lines:


>>> print(Grade)

>>> print(Grade.ID)

>>>

By reassigning Grade.ID, you are sabotaging the internals of the class.  
Without looking at those internals, it's not really a surprise that 
things stop working after you destroy the   it so 
carefully stored in Grade.ID.



So now the real question is:  What were you trying to accomplish with 
the assignment?  Tell us, and let's see if we can find a way to 
accomplish yor goal without wrecking the internals of the Grade class.



Gary Herron



it has impact on all variables. Is this behaviour
just like class variable and it has global scope.
I expected ob.ID and ob1.ID to be 10.

Correct me if Iam wrong.
Appreciate any quick response.

Kind Rgds,
Vinu


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Advice on law firm

2018-10-18 Thread Gary Herron
This is a Python related forum, but your question has nothing to do with 
Python.  While you might get an answer here, I'm sure you could find a 
better place to post your question.



On 10/17/2018 07:36 PM, rj.amdphr...@gmail.com wrote:

Correction: specializing in warranty of merchantability, software licenses, and 
possibly class action suits.

Sent from Mail for Windows 10

From: Ryan Johnson
Sent: Wednesday, October 17, 2018 9:26 PM
To: python-list@python.org
Subject: Advice on law firm

Anyone know a good US based law firm that specializes in software licenses and 
class action suits?

Sent from Mail for Windows 10




--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: My python code has suddenly started to give me error. Please see code below**

2018-10-09 Thread Gary Herron
So, tell us the error and we'll see what we can do.  Give us something 
to work with:   Cut and past the full error message, trace back, 
whatever you can.


Also tell us what version of Python, what system you are running on, how 
you run this code, ...




On 10/08/2018 10:17 PM, upadhyay.kamay...@gmail.com wrote:

## Calculating the Lower Limits(LLi) and Upper Limit(ULi) for each Band, where 
i is 1,2,.10
LL1=0
print(LL1)

print(P2)
print(D2)

if(P2>25):
 UL1=D1
 print(UL1)

elif(UL1==D2):
 print(UL1)
 
LL2=UL1
 
if(P3>25):

 UL2=D2
 print(UL2)

elif(UL2==D3):
 print(UL2)
 
LL3=UL2


if(P4>25):
 UL3=D3
 print(UL3)

elif(UL3==D4):
 print(UL3)
  


LL4=UL3

if(P5>25):
 UL4=D4
 print(UL4)

elif(UL4==D5):
 print(UL4)
 
LL5=UL4


if(P6>25):
 UL5=D5
 print(UL5)

elif(UL5==D6):
 print(UL5)
 
LL6=UL5


if(P7>25):
 UL6=D6
 print(UL6)

elif(UL6==D7):
 print(UL6)
 
LL7=UL6


if(P8>25):
 UL7=D7
 print(UL7)

elif(UL7==D8):
 print(UL7)
 
LL8=UL7


if(P9>25):
 UL8=D8
 print(UL8)

elif(UL8==D9):
 print(UL8)
 
LL9=UL8


if(P10>25):
 UL9=D9
 print(UL9)

elif(UL9==D10):
 print(UL9)
 
LL10=UL9

UL10=("& Above")

print(UL10)



**
n1=int(UL1)
count=0
while (n1>0):
 count=count+1
 n1=n1//10
 
print(count)


B11=LL1
If((count)/2)==0:
B12=int((UL1)/(10**(count-2)))
B12
 elif(B12=int((UL1)/(10**(count-1)))):
B12
B1=(B11,"-",B12,"M")
B1


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Program to find Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1.

2018-10-02 Thread Gary Herron

On 10/02/2018 01:23 PM, tomusa...@gmail.com wrote:

  Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1.
DATA

31, 71, 73, 137, 211, 311, 419, 421, 647, 877, 1117, 1487, 1979, 2447, 3079, 
3547, 4027, 7307, 7309, 12211, 14243, 18911, 18913, 23557, 25439, 28729, 36683, 
37831, 46853, 50411, 53129, 55457, 57367, 60251, 67339, 70489, 74797, 89669, 
98909, 98911

EXAMPLE 

7*5 - 3 - 1 = 31

11*7 - 5 - 1 = 71

11*7 - 5 + 1 = 73

13*11 - 7 + 1 = 137

Can someone put this in a Python program and post?



No, sorry, but that's not how this works.  We're not here to do your 
homework for you, and you won't learn anything if we do.  You make an 
attempt at solving this, asking any specific Python related questions 
you need help with, and you'll find this to be prompt, friendly, and 
helpful group.



Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: import inspect error

2018-09-17 Thread Gary Herron
You appear to have a local file named keyword.py which is hiding a 
python installation file of the same name.



Gary Herron





On 09/17/2018 01:06 AM, jupiter@gmail.com wrote:

I have following errors running on Ubuntu 18, any insight how to fix it? Thank 
you.

Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import inspect

Traceback (most recent call last):
   File "", line 1, in 
   File "/usr/lib/python2.7/inspect.py", line 42, in 
 from collections import namedtuple
   File "/usr/lib/python2.7/collections.py", line 22, in 
 from keyword import iskeyword as _iskeyword
   File "keyword.py", line 3, in 
 from inspect import currentframe, getframeinfo
ImportError: cannot import name currentframe


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: trying to connect the setarrange and blendshape input target weight while running the script am getting error in the 8th line. (for each in lip_val_list: )

2018-09-13 Thread Gary Herron

Your indentation of that line is incorrect.

You also have indentation errors on lines 14 and 21.  (Possibly more, 
that's all the further I checked.)  Do you understand Python's 
indentation rules?



In the future, you can do a lot better to help us help you. First, tell 
us the error you got instead of just saying you got an error.  (Copy and 
paste the full error message.)  Also tell us what version of Python (2 
or 3), and what platform, in case any of that matters.   Your subject 
line contains lots of meaningless distractions:  What's a setarrange, 
what's a blendshape, what's an input target weight,  what does it mean 
to connect them?  Either none of that is important (as is the case in 
this simple indentation error), so don't include such distractions, or 
it does matter, so take the time to define those terms.



Gary Herron



On 09/13/2018 12:11 AM, christyso...@gmail.com wrote:

lf_main_attr = "head_icon.Lf_Sticky_Lips"
rt_main_attr = "head_icon.Rt_Sticky_Lips"
lip_val_list = [18, 14]
lip_name_list = ['upperLip', 'lowerLip']

name_counter = 0
  for each in lip_val_list:
  half_val = (each / 2) + 1
  total_val = each + 1
  div_val = 10.0 / half_val
  counter = 0
  while(counter   
    
   


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Probability

2018-09-11 Thread Gary Herron

On 09/11/2018 11:54 AM, end...@freemail.hu wrote:

Hello,

I am new to Python and I have an exercise which I struggle with.

The question is:
In the strategic board game called Risk, one player can attack up to three 
soldiers simultaneously, while the defending player can defend up to two. In 
the case of exactly three attackers and two defenders, the collision is as 
follows. An attacking player rolls three red dice while the defending player 
rolls two blue dice. Then they compare the bigest throws of the attacker and 
the defender. The lesser value loses a soldier, in the case of equal values the 
attacker loses one soldier. Then the second largest numbers are also compared 
in the same way. Thus, the battle has three outcomes: the attacker loses two 
soldiers, each side loses 1-1 soldiers, the defender loses two soldiers.
Simulate 1000 times the experiment and determine the relative frequency 
of the three events.Simulate 100 times the experiment and determine the 
relative frequency of the three events.Calculate the exact probability of the 
three outcomes by examining all possible cases. The probability is the ratio of 
the favorable cases and the total number of cases. Write these results with 5 
decimal places leaving 3 spaces between them! The output of the program looks 
like this (of course with other numbers)


 Attacker  Draw  Defender
1000 experiment 0.35222   0.4   0.20334
100 experiment  0.33988   0.43011   0.23001
Probability 0.34000   0.43000   0.23000



The aim of this task is to get acquainted with the classical probability field, 
the relative frequency and the relation of it to the probability.Programming 
goal: recalling the basic elements of Python programming and generating random 
numbers.Help: by loading the random package (import random) and calling 
random.random() one may get a random number between 0 and 1 (by uniform 
distribution). The code int(random.random()*6)+1 gives back an integer number 
between 1 and 6.

So I did like:
import random

def dice():
     attacker_dice=[random.randint(1,6) for _ in range(3)]
     defender_dice=[random.randint(1,6) for _ in range(2)]
     a=max(attacker_dice)
     b=max(defender_dice)
     for i in range(1000):
         F=0
         S=0
         T=0
         if a>b:
             F+=1
         if a==b:
             S+=1
         else:
             T+=1


Every time through this loop, you set F, S and T to zero.  If you want 
those variables to accumulate values, move the three initialization 
lines to before the loop:

F = 0
S = 0
T = 0
for ...
   if a>b:
 F += 1
   ... and so on ...

But you have another problem.  You simulate rolling the dice only once.  
For your 1000 trials, you need to roll the dice 1000 times. The first 
few lines that simulate the dice roll must be inside the loop so that 
each pass through the loop rolls the dice.






and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 
333. And to get 5digits after the zero i wanted to use "%.5f " %First.

Could you help me to finish this, and tell me what am I doing wrong?

Thank you



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Probability

2018-09-11 Thread Gary Herron

On 09/11/2018 11:54 AM, end...@freemail.hu wrote:

Hello,

I am new to Python and I have an exercise which I struggle with.

The question is:
In the strategic board game called Risk, one player can attack up to three 
soldiers simultaneously, while the defending player can defend up to two. In 
the case of exactly three attackers and two defenders, the collision is as 
follows. An attacking player rolls three red dice while the defending player 
rolls two blue dice. Then they compare the bigest throws of the attacker and 
the defender. The lesser value loses a soldier, in the case of equal values the 
attacker loses one soldier. Then the second largest numbers are also compared 
in the same way. Thus, the battle has three outcomes: the attacker loses two 
soldiers, each side loses 1-1 soldiers, the defender loses two soldiers.
Simulate 1000 times the experiment and determine the relative frequency 
of the three events.Simulate 100 times the experiment and determine the 
relative frequency of the three events.Calculate the exact probability of the 
three outcomes by examining all possible cases. The probability is the ratio of 
the favorable cases and the total number of cases. Write these results with 5 
decimal places leaving 3 spaces between them! The output of the program looks 
like this (of course with other numbers)


 Attacker  Draw  Defender
1000 experiment 0.35222   0.4   0.20334
100 experiment  0.33988   0.43011   0.23001
Probability 0.34000   0.43000   0.23000



The aim of this task is to get acquainted with the classical probability field, 
the relative frequency and the relation of it to the probability.Programming 
goal: recalling the basic elements of Python programming and generating random 
numbers.Help: by loading the random package (import random) and calling 
random.random() one may get a random number between 0 and 1 (by uniform 
distribution). The code int(random.random()*6)+1 gives back an integer number 
between 1 and 6.

So I did like:
import random

def dice():
     attacker_dice=[random.randint(1,6) for _ in range(3)]
     defender_dice=[random.randint(1,6) for _ in range(2)]
     a=max(attacker_dice)
     b=max(defender_dice)
     for i in range(1000):
         F=0
         S=0
         T=0
         if a>b:
             F+=1
         if a==b:
             S+=1
         else:
             T+=1


Every time through this loop, you set F, S and T to zero.  If you want 
those variables to accumulate values, move the three initialization 
lines to before the loop:

F = 0
S = 0
T = 0
for ...
   if a>b:
 F += 1
   ... and so on ...

But you have another problem.  You simulate rolling the dice only once.  
For your 1000 trials, you need to roll the dice 1000 times. The first 
few lines that simulate the dice roll must be inside the loop so that 
each pass through the loop rolls the dice.




and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 
333. And to get 5digits after the zero i wanted to use "%.5f " %First.

Could you help me to finish this, and tell me what am I doing wrong?

Thank you



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: curve_fit in scipy

2018-06-19 Thread Gary Herron
This is a Python forum, but what you are asking is not a Python 
question.  You might find a better source of answers on a scipy specific 
forum.


But here's my attempt at answers:



On 06/19/2018 08:26 AM, sharan.basa...@gmail.com wrote:

Hi All,

I am working out an exercise on curve_fit function available scipy package.

While I understand in general about curve_fit, I am unable to understand the 
following:

params, params_covariance = optimize.curve_fit(test_func, x_data, y_data,
p0=[2, 2])

Firstly, I don't understand why test_func is passed as an argument to cur_fit


You are trying to fit a curve to some data, right.  The curve_fit 
procedure needs to know what curve you are trying to fit.  Is it a 
linear curve, exponential, polynomial or ...?  In this example it's a 
sine function with parameters for regulating amplitude and frequency.  
But it could be any function with any parameters.  To be more precise, 
test_function is not a single function y=f(x), but a whole family of 
functions y=f(x; a,b) where a and b define a particular function.



Secondly, I don't understand how curve_fit knows the number of arguments that 
test_func takes.


Part of the dynamic nature of Python is that a function carries with it 
the number of parameters (as just one among many such properties).  We 
call it "introspection" when we examine such properties of objects.  The 
curve_fit function usees such an introspection to find that 
test_function has two parameters (a and b) defining the family of curves.




Full code is available below for reference:

import numpy as np

# Seed the random number generator for reproducibility
np.random.seed(0)

x_data = np.linspace(-5, 5, num=50)
y_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50)

# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data)

from scipy import optimize

def test_func(x, a, b):
 return a * np.sin(b * x)

params, params_covariance = optimize.curve_fit(test_func, x_data, y_data,
p0=[2, 2])

print(params)

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label='Data')
plt.plot(x_data, test_func(x_data, params[0], params[1]),
  label='Fitted function')

plt.legend(loc='best')

plt.show()


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: How can an int be '+' with a tuple?

2018-06-02 Thread Gary Herron
In fact, the value of *any* is *not* an integer.  The *any notation 
causes Python to pack all the arguments into a tuple. This feature is 
usually used when there are multiple (and an unknown number) of 
parameters, but it works perfectly well with a single parameter.


Here's an example:

>>> def progress(*any):
    print(any)

>>> progress(1)
(1,)
>>> progress(1,2,3)
(1, 2, 3)
>>>


On 06/02/2018 07:55 PM, jf...@ms4.hinet.net wrote:

The attached is a script which can run under Python 3.4/Windows Vista
correctly. One thing make me puzzled is that the "any + context" at line
18. The "any" was passed as an integer from line 43 and the "context"
was defined as a tuple at line 35. This concatenation works! how?

Best Regards,
Jach Fong





---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus




--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Numpy array

2018-05-20 Thread Gary Herron

The "indexing" page of the documentation might help you with this:

https://docs.scipy.org/doc/numpy-1.14.0/reference/arrays.indexing.html


On 05/18/2018 09:50 PM, sharan.basa...@gmail.com wrote:

This is regarding numpy array. I am a bit confused how parts of the array are 
being accessed in the example below.

1 import scipy as sp
2 data = sp.genfromtxt("web_traffic.tsv", delimiter="\t")
3 print(data[:10])
4 x = data[:,0]
5 y = data[:,1]

Apparently, line 3 prints the first 10 entries in the array
line 4 & 5 is to extract all rows but only 1st and second columns alone for x 
and y respectively.

I am confused as to how data[:10] gives the first 10 rows while data[:,0] gives 
all rows



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Weird side effect of default parameter

2018-05-03 Thread Gary Herron
This is a well known feature of Python.   It's a very common "gotcha" to 
new Python programmers.


Google "Mutable default parameters in Python" for long list of 
explanations and fixes.


In short, don't use a mutable object as a default parameter.


Gary Herron



On 05/03/2018 12:47 PM, python-list@python.org wrote:

Hello,

I don't understand the behavior of the code below. Why does the dict property
"a" of both objects contain the same keys? This is only if "a=dict" is in
the initializer. If I put self.a = dict() into the init function, I get two
separate dicts



class Foo(object):
 def __init__(self, x, a=dict()):
 self.x = x
 self.a = a
 self.a[x] = x


c = Foo(1)
d = Foo(2)

print(c.__dict__)
print(d.__dict__)


robert


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: specifying the same argument multiple times with argparse

2018-04-16 Thread Gary Herron

On 04/16/2018 02:31 PM, larry.mart...@gmail.com wrote:

Is there a way using argparse to be able to specify the same argument
multiple times and have them all go into the same list?

For example, I'd like to do this:

script.py -foo bar -foo baz -foo blah

and have the dest for foo have ['bar', 'baz', 'blah']



From the argparse web page 
(https://docs.python.org/3/library/argparse.html):


'append' - This stores a list, and appends each argument value to the 
list. This is useful to allow an option to be specified multiple times. 
Example usage:


>>>
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])


I hope that helps.


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Please Help

2018-01-26 Thread Gary Herron



On 01/26/2018 08:33 PM, mohammedfaraz...@gmail.com wrote:

import numpy as np
x=np.unit8([250)
print(x)
y=np.unit8([10])
print(y)
z=x+y
print(z)


output

[250]
[10]
[4]

My question how is z [4]


Despite all the typos in your post, you appear to be doing 8 bit 
unsigned arithmetic.  Do you know what that means?  The answer you might 
have expected (i.e. 260) does not fit in the 0 ... 255 range of 8 bits, 
and so the result has overflowed and "wrapped around" to produce 4.


Try this for a simpler example of the same:
>>> np.uint8(260)
4


Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: None is None but not working

2017-09-27 Thread Gary Herron

On 09/27/2017 01:05 PM, Sayth Renshaw wrote:

Hi

I have got a successful script setup to rotate through dates and download json 
data from the url.

As the api returns 200 whether successful I want to check if the file returned 
is not successful.

when a file doesn't exist the api returns
{'RaceDay': None, 'ErrorInfo': {'SystemId': 200, 'ErrorNo': 55013, 
'DisplayMessage': 'File Not Found.', 'ContactSupport': False, 
'SupportErrorReference': '200-55013'}, 'Success': False}

When I call data = r.json() it says its type is None if it is not successful so 
I thought it easier to check that.

However checking for None does not work the flow in my if else falls straight 
to else.

for dates in fullUrl:
 r = requests.get(dates)
 data = r.json()
 if data is None:
 print("Nothing here")
 else:
 print(data["RaceDay"])


Your data is not None, it's a full dictionary.

However, data["RaceDay"] *is* None as shown in your output.  Thus your 
test should be:

    if data["RaceDay"] is None: ...
rather than
    if data is None: ...






and I get output of

None
None
{'MeetingDate': '2017-01- ... and so on.

How can I actually get this to check?

If i use type(data) I also get None.

Cheers

Sayth



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: getting the center of mass of each part of a molecule

2017-05-15 Thread Gary Herron

On 05/15/2017 01:29 PM, qasimp...@gmail.com wrote:

Hi,

I need to get the center of mass (COM) of each half of the ligand shown in the 
figure (https://i.stack.imgur.com/dtdul.png). I get the main COM all the 
ligand, lets say it is close to C1 atom. In addition to the main COM of all the 
ligand, I need to find the COM of each half of the ligand. The atoms of the 
first part/half according to the main COM of the ligand are C2, C7, C8 and C9. 
As for the second part they are C3, C4, C5 and C6 atoms. The question is how 
can I divide the ligand in two parts according to the main COM and calculate 
the COM of each divided part (except for the atom closest to the main COM, C1)? 
By the way I have multiple ligands. The code should be user firendly.

A short part of the input file is here:

1LIG C11   4.434   5.366   1.780
1LIG C22   4.317   5.301   1.940
1LIG C33   4.430   5.286   1.888
1LIG C44   4.380   4.942   2.467
1LIG C55   4.148   4.929   2.443

A short snippet of the code used to get the main COM is here:

def heavy_atoms(atoms, xyz, ligand="LIG"):
 ids   = np.arange(len(atoms))
 names = [(i[10:15].strip(),i[5:10].strip()) for i,j in atoms]

 # Ligand atoms
 lig_atoms = np.array([ rname == ligand and not aname.startswith('H') for 
aname,rname in names ])
 lig_xyz = xyz[lig_atoms,:]

 # The main COM
 lig_com = xyz[lig_atoms, :].mean(axis=0)



You seem to be asking a chemistry or biochemistry question on this 
Python programming list.  We're a diverse group, but still, that seems 
to be a vast mismatch.   Do you have any hint of an algorithm that will 
do what you want?  Can you find one somewhere, or define one yourself?   
Once you have an algorithm, it would be appropriate to ask here for help 
in translating it into a Python program.



Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Write a function group(L).

2017-04-21 Thread Gary Herron

On 04/21/2017 01:01 PM, Mohammed Ahmed wrote:

Write a function group(L) that takes a list of integers. The function returns a 
list of
two lists one containing the even values and another containing the odd values.

it is a python question


In fact, this is *not* a question, Python or otherwise.

Welcome to python-list.  If you ask a Python question, it will probably 
get answered.  If you want someone to do your homework, it will probably 
not happen.



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Who are the "spacists"?

2017-03-18 Thread Gary Herron

On 03/18/2017 06:46 AM, Mikhail V wrote:

On 18 March 2017 at 03:09, Joel Goldstick <joel.goldst...@gmail.com> wrote:

On Fri, Mar 17, 2017 at 8:52 PM, Mikhail V <mikhail...@gmail.com> wrote:

So Python supports both spaces and tabs for indentation.

I just wonder, why not forbid spaces in the beginning of lines?
How would one come to the idea to use spaces for indentation at all?

Space is not even a control/format character, but a word separator.
And when editors will be proportional font based, indenting with
spaces will not make *any* sense so they are just annoyance.
Neither makes it sense in general case of text editing.
I think it would be a salvation to forbid spaces for indentation,
did such attemps take place?

This is not a useful conversation.  It has been had over and over in
the past.  Some people like tabs, some like spaces.  In python you can
use either, but you must stick to one or the other


Not to judge, but usually such opinions come from determined
spasists. And "stick to one or the other" is exactly what would make
life easier, but in literal sense of global preference.

On 18 March 2017 at 05:02, Ben Finney <ben+pyt...@benfinney.id.au> wrote:

Mikhail V <mikhail...@gmail.com> writes:


I just wonder, why not forbid spaces in the beginning of lines?

Because that would make countless lines of existing Python code illegal.

Yes, yes. And it is of course so hard to clean up spaces in existing code.


As a mater of fact, and despite the snark, that is true.  A quick count 
finds 46,209 .py files on my computer, spread across the OS, installed 
packages, and my own work.  I would strongly resist anything that needs 
that much re-installation and personal attention.



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: why this code loop forever after a draw a rectangle

2016-09-16 Thread Gary Herron
m to None with the line
im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2)
and the next pass through the loop hits the infinite loop:
while im is None:
time.sleep(1)


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: why this code loop forever after a draw a rectangle

2016-09-16 Thread Gary Herron

On 09/16/2016 04:24 AM, meInvent bbird wrote:

im = img.copy()
cntcounter = 0
for cnt in contours:
 epsilon = 0.1*cv2.arcLength(cnt,True)
 approx = cv2.approxPolyDP(cnt,epsilon,True)
 #peri = cv2.arcLength(cnt, True)
 #approx = cv2.approxPolyDP(c, 0.5 * peri, True)
 #print("len(approx)="+str(len(approx)))
 if len(approx) == 4:
 print("approx=" + str(approx))
 cntcounter = cntcounter + 1
 print("here1")
 x,y,w,h = cv2.boundingRect(cnt)
 print("here2")
 while im is None:
 time.sleep(1)
 if im is not None:
 print("here3")
 im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2)
 #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2)
 #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2)
 #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2)
 #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2)


cv2.imwrite(r'C:\Users\tester\Documents\masda.png',im)



These two lines:

  while im is None:
time.sleep(1)

are an infinite loop if im is None;


Since you haven't told us what im (or img, contours, cv2) are, I can't 
tell how im might become None, but it does look like you (confusingly) 
use im for two different things:  an img.copy() and a cv2.rectangle, 
whatever those may be.


Pure guesswork:  if cv2.rectangle draws a rectangle, what does it 
return?  If it doesn't return anything, the line

im = cv2.rectangle(...)
is how im gets the value of None.

--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: degrees and radians.

2016-08-23 Thread Gary Herron

On 08/23/2016 09:08 PM, murdocksgra...@gmail.com wrote:

On Saturday, May 4, 2002 at 3:37:07 AM UTC-4, Jim Richardson wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


I am trying to get the math module to deal with degrees rather than
radians. (that it deals with radians for the angular functions like
sin() isn't mentioned in the docs, which was sort of an eyeopener :)  I
can't find any info on doing this. I can convert from-to degrees in the
code calling the function, but that's a bit clunky. Any pointers to an
FM to R? :)

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE804+jd90bcYOAWPYRAt9KAKCuqeC4ozuXSaKZ5xY27Wv+k04QuQCcCrCZ
WyichPnKgXo+GaDdAebsaeU=
=h+vc
-END PGP SIGNATURE-

--
Jim Richardson
Anarchist, pagan and proud of it
http://www.eskimo.com/~warlock
Linux, from watches to supercomputers, for grandmas and geeks.

For what is is worth.. Electrical Engineers for the most part work in degrees 
NOT Radians for example try doing polar to rectangular or vice versa in polar.
I have never seen it done.

Also Borland C and C++ used Degrees and NOT Radians.. go look at the libraries

Just for what its worth.



Do you really need anything more complex than this?

>>> toRadians = math.pi/180.0

>>> math.sin(90*toRadians)
1.0

Perhaps I'm not understanding what you mean by "clunky",  but this seems 
pretty clean and simple to me.



Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: A strange list concatenation result

2016-08-11 Thread Gary Herron

On 08/11/2016 03:06 PM, Mok-Kong Shen wrote:


def test(list1,list2):
  list1+=[4,5,6]
  list2=list2+[4,5,6]
  print("inside ",list1,list2)
  return

# With

list1=list2=[1,2,3]
test(list1,list2)
print("outside",list1,list2)

# I got the following:
# inside  [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 4, 5, 6]
# outside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]

# With

list1=[1,2,3]
list2=[1,2,3]
test(list1,list2)
print("outside",list1,list2)

# I got the following:
# inside  [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
# outside [1, 2, 3, 4, 5, 6] [1, 2, 3]



I think the following shows the same issue in a much simpler fashion:

In this (and your first) example, there is only one list, although it 
has two names to reference it.


>>> list1 = list2 = [1,2,3]
>>> list1 += [4,5,6]
>>> print(list1, list2)
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]


In this next example, there are two separate lists:

>>> list1 = [1,2,3]
>>> list2 = [1,2,3]
>>> list1 += [4,5,6]
>>> print(list1, list2)
[1, 2, 3, 4, 5, 6] [1, 2, 3]


Does that help?


Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Operator precedence problem

2016-06-06 Thread Gary Herron

On 06/04/2016 11:53 PM, ICT Ezy wrote:

2 ** 3 ** 2

Answer is 512
Why not 64?
Order is right-left or left-right?


Evidently right to left, but you already figured that out.

Python 3.5.1+ (default, Mar 30 2016, 22:46:26)
[GCC 5.3.1 20160330] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 ** 3 ** 2
512
>>> 2 ** (3 ** 2)
512
>>> (2 ** 3) ** 2
64
>>>


Here's the relevant documentation page:
https://docs.python.org/3/reference/expressions.html
Look for "... except for exponentiation, which groups from right to left"

Gary Herron

--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Spreading a class over multiple files

2016-06-05 Thread Gary Herron

On 06/04/2016 11:55 PM, Mark Summerfield wrote:

Sometimes I want to spread a class over multiple files.


There’s and easy way to do this in Python using what's called a Mixin 
class and (multiple) inheritance:

  (See https://en.wikipedia.org/wiki/Mixin for more information.)

In one file, say extras.py

   class ExtraMethodsMixin:

  def extra_1(...):
  ...

  def extra_2(...):
  ...



In the main class file:

   from extras import ExtraMethodsMixin

   class MainClass(ExtraMethodsMixin):

  def __init__(...):
  ...
   # and so on


The result will be essentially the same as if all three methods were 
defined in MainCLass.



Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418





My primary use case is when I create a "Model" class to reflect an entire SQL 
database. I want a model instance to provide a single point of access to
  the database, but the database has many tables each requiring its own methods 
since they differ in their structure, purpose, validation needs, etc.

A secondary use case is when I create "MainWindow" classes in GUI programming 
and have lots of methods to reflect all the actions (e.g., menu options
and toolbar actions, plus interaction with the main widget(s)).

To meet these needs I've devised an approach that I think is easy to use and 
understand and which doesn't use any tricky or hard to maintain code.

My question is -- are there nicer/better ways to achieve this?

Here's a summary of my approach. A fuller discussion is on my website:
https://www.qtrac.eu/pyclassmulti.html

# Lib.py
# This provides the two functions (both decorators) used to support my approach
def add_methods_from(*modules):
 def decorator(Class):
 for module in modules:
 for method in getattr(module, "__methods__"):
 setattr(Class, method.__name__, method)
 return Class
 return decorator

def register_method(methods): # A decorator used purely for its side-effect
 def register_method(method):
 methods.append(method)
 return method # Unchanged and not strictly necessary
 return register_method

# Model.py
# This provides my model but some methods are in separate files
import Lib
import _ModelConfig
import _ModelOutput

@Lib.add_methods_from(_ModelConfig, _ModelOutput)
class Model:
 ...
 def small_method(self):
 ...

# _ModelConfig.py # _ModelOutput has the same structure so not shown
import Lib

__methods__ = [] # self is a Model
register_method = Lib.register_method(__methods__)

@register_method
def config(self):
 ...
So, that's the overall pattern of my solution.

Is there a nicer/better way? Could I cleanly avoid the explicit imports (e.g., 
import _ModelConfig), without resorting to stack frame hacks or similar?


--
https://mail.python.org/mailman/listinfo/python-list


Re: Image loading problem

2016-05-21 Thread Gary Herron

On 05/21/2016 08:22 AM, sweating_...@yahoo.com wrote:

Hi All,


I am working on an image project, and I can display my image in main(). I mean, 
I can load my image in my main(). Needless, it is awkward. I am trying to load 
my image with a function, but got an empty image window popped up, no image 
content loaded. Please take a look at code:



rom Tkinter import *

def load_img(win):  
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()

win = Tk()
load_img(win)
win.mainloop()

Somebody can help me out? Thanks!



I believe this the problem (However It's been long since I used Tkinter, 
so be warned ... ):


The function load_img creates a local variable named img which goes out 
of scope and is deleted immediately when the function returns. However, 
Tkinter needs you to keep that image around as long as the Label uses 
it.   So, some solutions are:


keep_me = [] #  Global for keeping references to images
def load_img(win):
img = PhotoImage(file="xxx.gif")
keep_me.append(img)
Label(win, image=img).pack()

or


def load_img(win):
img = PhotoImage(file="xxx.gif")
Label(win, image=img).pack()
return img

saved_img = load_img(win)
...


Gary Herron



--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: def __init__(self):

2016-04-26 Thread Gary Herron

On 04/26/2016 06:49 AM, Random832 wrote:

On Tue, Apr 26, 2016, at 03:34, Ben Finney wrote:

That's needlessly confusing: ‘__init__’ is not a constructor because it
does not construct the instance. The ‘__new__’ method is the constructor
for a class (and returns the new instance).

the __new__ method is the *allocator*. "constructor" is used in many
languages to name a method that initializes an object once it already
"exists". Saying you can't call it that in Python is needlessly
confusing.


Agreed.  For a newbie asking about __init__, I'll stick with my original 
answer (that it's the constructor),  and suggest ignoring the overly 
pedantic (and confusing) response to the contrary.


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: def __init__(self):

2016-04-26 Thread Gary Herron

On 04/25/2016 11:21 PM, San wrote:

Hi All,

Pls let me why
"
def __init__(self):

"
declaration required, what's the use of this one.Pls explain  me in details.

Thanks in advance.


If you understand object-oriented-programming, then this will make sense:

   The __init__ method is the constructor for instances of a class.  It
   is not required, but the situations in which a constructor is not
   needed are few and unusual.

If you don't know object-oriented-programming, then I'd suggest you put 
that high on your list of things to learn.  It's a valuable tool.


Gary Herron


--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: what is the difference between one-line-operation and 2-line-operation

2016-04-25 Thread Gary Herron

On 04/25/2016 07:13 AM, oyster wrote:

for a simple code
[code]
vexList = [1, 2, 3]
print('vexList', list(vexList))

vexList=map(lambda e: e+1, vexList)
print('vexList', list(vexList))

vexList = list(vexList)
print('vexList', list(vexList))

vexList=map(lambda e: e*2,vexList)
print('vexList', list(vexList))
[/code]


py27 says
[quote]
('vexList', [1, 2, 3])
('vexList', [2, 3, 4])
('vexList', [2, 3, 4])
('vexList', [4, 6, 8])
[/quote]

but py34 says
[quote]
vexList [1, 2, 3]
vexList [2, 3, 4]
vexList []
vexList []
[/quote]


The difference in behaviour between Python2 and Python3 is the map 
function.  In P2 it returned a list, while in P3 it returns an 
iterator.  Your code runs through that iterator twice with the list() 
function.  The first time it gets the elements of the list as expected, 
but the second time, the iterator is exhausted and returns no objects.


A simpler example: "b" is a map object (iterator), then list(b) is run 
twice.


>>> a = [1,2,3]
>>> b = map(lambda e: e+1, a)
>>> b

>>> list(b)
[2, 3, 4]
>>> list(b)
[]


I hope that helps.

Gary Herron

--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Exclude every nth element from list?

2016-03-26 Thread Gary Herron

On 03/26/2016 09:49 AM, beliavsky--- via Python-list wrote:

I can use x[::n] to select every nth element of a list. Is there a one-liner to 
get a list that excludes every nth element?


Yes:

>>> L=list(range(20))
>>> [x   for i,x in enumerate(L)   if i%3 != 0]
[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19]


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: PLEASE HELP -- TOTALLY NEW TO PYTHON

2016-03-26 Thread Gary Herron

On 03/25/2016 10:31 PM, Juan Dent wrote:

I am trying to run ‘python cppdep.py’ but get the following:


 I would guess that this code was written some time ago for Python2, 
but that you have downloaded and run it with Python3.


Try installing Python2 instead of Python3.   Or try talking whoever 
wrote it into converting it to Python3.


Or my guess is completely wrong and the code is buggy and won't run 
until fixed.  (Which brings up the questions: What is cppdep.py? Who 
wrote it?  How do you know that it runs?)



Gary Herron





analyzing dependencies among all components ...
Traceback (most recent call last):
   File "cppdep.py", line 675, in 
 main()
   File "cppdep.py", line 643, in main
 calculate_graph(digraph)
   File "cppdep.py", line 570, in calculate_graph
 (cycles, dict_node2cycle) = make_DAG(digraph, key_node)
   File "/Users/juandent/Downloads/cppdep-master/networkx_ext.py", line 79, in 
make_DAG
 for ind in range(len(subgraphs)-1, -1, -1):
TypeError: object of type 'generator' has no len()


Please, I know no python and am in a hurry to get this working… Please help


Regards,
Juan



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: Struggeling with collections

2016-03-07 Thread Gary Herron

On 03/07/2016 12:24 AM, Faling Dutchman wrote:

Hey folks,

I am just starting off in python, but have good knowledge of both Java and C#. 
Now is the problem that I need to have multiple instances of one dictionary, 
that is not a problem if you know how many, but now, it is an unknown amount.

Some background info:

I am making a library for an API. This library must be easy to use for the 
people who are going to use it. So I am making the models for the data, the 
connections and so on, so they just have to fill in the gaps. In C# and Java I 
did it with objects, but they do not work alike in python, or at least that is 
what I have found.

If I do this:

class Item:
 def __init__(self, id, productId, quantity, pageCount, files, option, 
metadata):
 self.id = id
 self.productId = productId
 self.quantity = quantity
 self.pageCount = pageCount
 self.files = files
 self.option = option
 self.metadata = metadata

itm = Item(1,None,1,1,'asdf',{'asdf': 3, 'ads': 55},None)
print(itm)

it prints: <__main__.Item object at 0x02EBF3B0>

So that is not usefull to me. There can be an infinite amount of objects of 
Item, and it needs to be easy accessable, just like
for i in items
 print(i)

and it has to show all the parameters of the class Item and not say "ive got an 
object  at this memory address, have a nice day"

I hope my question is clear.


It's not clear in the slightest.  In fact there isn't even a question 
here.  Ignoring everything about numbers of objects and libraries and 
access (of what?), it seems you want an object of type Item to be able 
to print itself nicely.Please correct me if I've got that wrong.


You can do so by defining a member __str__ (or __repr__).  Here's a 
small example.  The returned formatted string can be as simple or 
complex as you wish.


>>> class C:
...   def __init__(self, a, b):
... self.a = a
... self.b = b
...   def __str__(self):
... return "C(a={}, b={})".format(self.a, self.b)  # Modify to suit 
your needs.

...
>>> print(C(1,2))
C(a=1, b=2)
>>>


Gary Herron







--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: list reversal error

2016-03-03 Thread Gary Herron

On 03/03/2016 02:51 PM, vlyamt...@gmail.com wrote:

i have list of strings "data" and i am trying to build reverse list data1
data1 = []
for i in range(len(data)):
j = len(data) - i
data1.append(data[j])

but i have the following error:
data1.append(data[j])
IndexError: list index out of range
  
am i doing it wrong?

Thanks


Look at the values (say with a print) you get from your line
j = len(data) - i
You'll find that that produces (with a list of 4 elements for example) 
4,3,2,1 when in fact you want 3,2,1,0. Soo you really want

j = len(data) - i -1


Better yet, use more of Python with
data1 = list(reversed(data))

Or don't even make a new list, just reverse the original list in place
>>> L=[1,2,3]
>>> L.reverse()
>>> L
[3, 2, 1]

Or even better, if you simply want to iterate through the original list, 
but in reverse order:

for datum in reversed(data):
... whatever with datum ...
which wastes no time actually reversing the list, but simply loops 
through them back to front.



Gary Herron

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: problem with dateutil

2016-02-13 Thread Gary Herron

On 02/13/2016 09:58 AM, Tom P wrote:
I am writing a program that has to deal with various date/time formats 
and convert these into timestamps. It looks as if 
dateutil.parser.parse should be able to handle about any format, but 
what I get is:


datetimestr = '2012-10-22 11:22:33'
print(dateutil.parser.parse(datetimestr))
result: datetime.datetime(2012, 10, 22, 11, 22, 33)

However:
datetimestr = '2012:10:22 11:22:33'
print(dateutil.parser.parse(datetimestr))
result: datetime.datetime(2016, 2, 13, 11, 22, 33)

In other words, it's getting the date wrong when colons are used to 
separate :MM:DD. Is there a way to include this as a valid format?




Yes, there is a way to specify your own format.  Search the datetime 
documentation for

datetime.strptime(date_string, format)

Gary Herron

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: problem with dateutil

2016-02-13 Thread Gary Herron

On 02/13/2016 12:27 PM, Tom P wrote:

On 02/13/2016 07:13 PM, Gary Herron wrote:

On 02/13/2016 09:58 AM, Tom P wrote:

I am writing a program that has to deal with various date/time formats
and convert these into timestamps. It looks as if
dateutil.parser.parse should be able to handle about any format, but
what I get is:

datetimestr = '2012-10-22 11:22:33'
print(dateutil.parser.parse(datetimestr))
result: datetime.datetime(2012, 10, 22, 11, 22, 33)

However:
datetimestr = '2012:10:22 11:22:33'
print(dateutil.parser.parse(datetimestr))
result: datetime.datetime(2016, 2, 13, 11, 22, 33)

In other words, it's getting the date wrong when colons are used to
separate :MM:DD. Is there a way to include this as a valid format?



Yes, there is a way to specify your own format.  Search the datetime
documentation for
 datetime.strptime(date_string, format)

Gary Herron



Thanks.  I started out with datetime.strptime but AFAICS that means I 
have to go through try/except for every conceivable format. Are you 
saying that I can't use dateutil.parser?


Well now...  If by "every conceivable format" you are including formats 
that the author of dateutil.parser did not conceive of, then of course 
you cannot use dateutil.parser.   But you have the code for 
dateutil.parser -- perhaps you could modify it to accept whatever odd 
formats you care about.


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: import cannot be used inside eval

2016-02-04 Thread Gary Herron

On 02/03/2016 09:03 PM, 阎兆珣 wrote:

a = input("tell me which py to execute:  ")

print(a)

print('import '+a)

print(type('import'+a))

eval('print(a)')
Eval is meant to evaluate Python expressions.  The import is a 
statement, not an expression.  Also, it's a bad idea to use eval like 
this, and it's a *really* bad idea to use eval with user supplied 
input.  The user could inject *any* malicious code.


Instead, use the importlib module to programmatically import a module.

Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: 'string.join' is wrong in my Python console

2015-12-03 Thread Gary Herron

On 12/02/2015 10:55 PM, Robert wrote:

Hi,

I read the tutorial on "Why is join() a string method instead of a list
  or tuple method?"
at link:
https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls

I have a problem on running the last line:
---
If none of these arguments persuade you, then for the moment you can
  continue to use the join() function from the string module, which allows
  you to write

string.join(['1', '2', '4', '8', '16'], ", ")
---

My Python console is 2.7. It should be no problem because I see the tutorial
is 2.7 too.

The console has these display:

string.join(['1', '2', '4', '8', '16'], ", ")
---
NameError Traceback (most recent call last)
 in ()
> 1 string.join(['1', '2', '4', '8', '16'], ", ")

NameError: name 'string' is not defined


 From the context, I don't see string should be replaced by something else.

Could you tell me why I have such an error?


You are trying to use the *string* module without importing it, I'd guess.

Try:
import string
first then you should be able to access string.join without error.

Gary Herron







Thanks,



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: reading from a txt file

2015-11-26 Thread Gary Herron

On 11/26/2015 12:34 PM, vincentype...@gmail.com wrote:

Hey, I'm wondering how to read individual strings in a text file.  I can read a 
text file by lines with .readlines() ,
but I need to read specifically by strings, not including spaces.  Thanks in 
advance


Read the lines with readlines(), as you say, then split each line into 
whatever pieces you want with split (or with any of the many other 
string methods).


A minimal example (without readlines):
>>> lines = ['a b c', 'aa bb cc']
>>> for line in lines:
...   words = line.split()
...   print(words)
...
['a', 'b', 'c']
['aa', 'bb', 'cc']


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Why won't this run?

2015-11-16 Thread Gary Herron

On 11/15/2015 12:38 PM, jbak36 wrote:

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit 
(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.

#this program says hello and asks for my name
print:('Hello world!')

Hello world!



You are lying to us somehow.  That attempt to print (as you've written 
it) does not produce the the line of output you've indicated.  Instead 
it produces a syntax error, because Python does not use a colon in that 
situation.


So change your print:(...) lines to print(...) (without the colon) and 
try again.  If there is further trouble, ask another question, but 
please cut and paste the actual and *exact* results into the email.


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Should non-security 2.7 bugs be fixed?

2015-07-19 Thread Gary Herron

On 07/18/2015 04:36 PM, Terry Reedy wrote:

  I would like more viewpoints from 2.7 users.


I read that (incorrectly of course) and just had to ask:
   How do you intend to extract a viewpoint from that last 7/10 of a user?

With apologies,

Gary Herron




--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Can anybody explain the '-' in a 2-D creation code?

2015-06-26 Thread Gary Herron

On 06/25/2015 06:07 PM, fl wrote:

Hi,

I read Ned's tutorial on Python. It is very interesting. On its last
example, I cannot understand the '_' in:



board=[[0]*8 for _ in range(8)]


I know  '_' is the precious answer, but it is still unclear what it is
in the above line. Can you explain it to me?


Thanks,


He uses _ to indicate a variable whose name and value he does not care 
about, but it *is* a valid variable name.


He could have used
  ... for i in range ...
or
  ... for unused_variable in range ...

This is a valid, though probably unclear, use of that same name:

 _ = 123
 print(_)
123



Gary Herron



--
https://mail.python.org/mailman/listinfo/python-list


Re: Why this list of dictionaries doesn't work?

2015-06-18 Thread Gary Herron

On 06/18/2015 10:57 AM, Gilcan Machado wrote:

Hi,

I'm trying to write a list of dictionaries like:

people = (
 {'name':'john', 'age':12} ,
 {'name':'kacey', 'age':18}
)


I've thought the code below would do the task.

But it doesn't work.


Never say it doesn't work on this list.  Tell us what it did, and what 
you expected.  Provide a copy of the full error message. That's much 
more helpful than making us guess.




And if I print(people) what I get is not the organize data structure 
like above.


Thanks of any help!
[]s
Gilcan

#!/usr/bin/env python
from collections import defaultdict

person = defaultdict(dict)


If you want *two* different dictionaries, you'll have to create *two* of 
them.  You code creates only this one.



people = list()

person['name'] = 'jose'
person['age'] = 12

people.append(person)


Here's where you need to create the second one.



person['name'] = 'kacey'
person['age'] = 18

people.append(person)

for person in people:
print( person['nome'] )


Typo here:  'name', not 'nome'.








--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: So what's happening here?

2015-06-05 Thread Gary Herron

On 06/05/2015 06:11 AM, Paul Appleby wrote:

On Fri, 05 Jun 2015 14:55:11 +0200, Todd wrote:


Numpy arrays are not lists, they are numpy arrays. They are two
different data types with different behaviors.  In lists, slicing is a
copy.  In numpy arrays, it is a view (a data structure representing some
part of another data structure).  You need to explicitly copy the numpy
array using the copy method to get a copy rather than a view:

OK, thanks.  I see.

(I'd have thought that id(a[1]) and id(b[1]) would be the same if they
were the same element via different views, but the id's seem to change
according to rules that I can't fathom.)
Nope.  It's odder than that.  a[1] is still a view into the inderlying 
numpy array, and your id is the id of that view. Each such index 
produces a new such view object.  Check this out:


 import numpy
 a = numpy.array([1,2,3])
 id(a[1])
28392768
 id(a[1])
28409872

This produces two different view of the same underlying object.

Gary Herron





--
https://mail.python.org/mailman/listinfo/python-list


Re: So what's happening here?

2015-06-05 Thread Gary Herron

On 06/05/2015 06:39 AM, Todd wrote:
On Fri, Jun 5, 2015 at 3:23 PM, Gary Herron 
gary.her...@islandtraining.com 
mailto:gary.her...@islandtraining.com wrote:


On 06/05/2015 06:11 AM, Paul Appleby wrote:

On Fri, 05 Jun 2015 14:55:11 +0200, Todd wrote:

Numpy arrays are not lists, they are numpy arrays. They
are two
different data types with different behaviors.  In lists,
slicing is a
copy.  In numpy arrays, it is a view (a data structure
representing some
part of another data structure).  You need to explicitly
copy the numpy
array using the copy method to get a copy rather than a
view:

OK, thanks.  I see.

(I'd have thought that id(a[1]) and id(b[1]) would be the same
if they
were the same element via different views, but the id's seem
to change
according to rules that I can't fathom.)

Nope.  It's odder than that.  a[1] is still a view into the
inderlying numpy array, and your id is the id of that view. Each
such index produces a new such view object. Check this out:

 import numpy
 a = numpy.array([1,2,3])
 id(a[1])
28392768
 id(a[1])
28409872

This produces two different view of the same underlying object.


a[1] and b[1] are not views:

 a[1].flags['OWNDATA']
True
 b[1].flags['OWNDATA']
True
 a[1:2].flags['OWNDATA']
False


Right.  My bad.  Each execution of a[1] creates a new numpy.int64 object 
with the value from the array.


 type(a[1])
class 'numpy.int64'

Each execution of id(a[1]) creates an int64 object which is immediately 
used and then deleted.  Two successive executions of id(a[1]) may or may 
not reuse the same piece of memory, depending on what else is going on 
in memory.  Indeed when I produced the above example with id(a[1]), a 
third and fourth runs of id(a[1]) did indeed repeat 28409872, but they 
are all new creations of an int64 object which happen to use the same 
recently freed bit of memory.


Gary Herron












-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to inverse a particle emitter

2015-06-04 Thread Gary Herron

On 06/04/2015 04:15 PM, stephenpprane...@gmail.com wrote:

hey, i really need help, im a straight up beginner in scripting and i need to 
figure out how to make an inverted particle emitter using python in maya


Python is a programming language.
Maya is a modeling and animation application (or a Mesoamerican 
civilization).
An inverted particle emitter sounds like something you'd build in your 
backyard.


You are going to have to put in a *LOT* more time explaining how those 
three are connected in one project.


In truth, I can kind of guess what you want, (although I have no idea 
what inverse has to do with anything), but I won't waste my time doing 
so.  If you take the time to carefully explain what you want, then I'm 
sure you will find plenty of people here who will take the time to 
answer you.



Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Multiple thread program problem

2015-06-04 Thread Gary Herron

On 06/03/2015 01:41 PM, Mohan Mohta wrote:

Hello
I am trying to create multiple thread through the below program but I am 
getting an error

#! /usr/bin/python
import os
import subprocess
import thread
import threading
from thread import start_new_thread

def proc(f) :
 com1=ssh -B 
 com2=line.strip('\n')
 com3=  uname -a
 co=str(ssh -B )+ str(com2) + str( uname -a)
 subprocess.call(co,shell=True)
 print 
 return

f = open('/tmp/python/1')
for line in f:
 t=thread.start_new_thread(proc(f),())


You are calling the function f yourself, but what you want here is for 
the thread to call f once it's running.

So do

t=thread.start_new_thread(proc, (f,)) # Procedure to call and a 
tuple of args for it.



 t.start()


I don't think the thread has a start method.


f.close()
c = raw_input( Type anything to quit)


Execution output:
Linux abc.myhomenetwork.com 2.6.18-348.25.1.el5 #1 SMP Thu Apr 10 06:32:45 EDT 
2014 x86_64 x86_64 x86_64 GNU/Linux

Traceback (most recent call last):
   File ./readfile1.py, line 19, in module
 t=thread.start_new_thread(proc(f),())
TypeError: first arg must be callable


You should probably also consider using the higher-level threading 
module rather than the lower level thread module.


(Also consider using Python3 instead of Python2.)

Gary Herron





--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Keypress Input

2015-06-03 Thread Gary Herron

On 06/03/2015 11:22 AM, John McKenzie wrote:

  Hello.

  Very new to Python and looking for some basic help.

  Would like a set-up where something happens when a key is pressed. Not
propose a question, have the user type something, then hit return, then
something happens, but just the R key is pressed, something happens, then
something else happens if the B key is pressed, then a third thing
happens if the G key is pressed.

  My research only served to confuse me. Firstly, I do not understand how
it is possible for this to be a difficult thing not built into the system
for any scripting language made within the last few decades. More to the
point I am unclear on specific suggestions. Most of them seem to be for
Windows only and I want this working on a Raspberry Pi. Saw getch but I
am still confused if it is platform specific or not, or requires a module
to be installed or not. Just get errors if I try to install getch using
PIP.


If you are using Python through a CLI (command line interface i.e., a 
shell), then in fact your request doesn't really make sense.  CLIs by 
their nature don't support that kind of interaction.


BUT don't despair.  Nearly every GIU framework on the planet has a 
Python interface, and they all allow for a window to be opened with 
event processing of your choice.


This are some good places to start:
https://wiki.python.org/moin/GuiProgramming
https://wiki.python.org/moin/GUI%20Programming%20in%20Python

Several of these (Tkinter and the curses module) are distributed with 
Python, so you should already have them installed.


Gary Herron





  Other suggestions seemed to be overkill and confused me to due to my
beginner level knowledge and the fact these suggestions have other, more
complicated elements to them.

  I just want a button press on a device connected to a Raspberry Pi to
trigger an action. If anyone can give me some guidance on this I would
appreciate it.

  Thank you.




--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Keypress Input

2015-06-03 Thread Gary Herron

On 06/03/2015 11:22 AM, John McKenzie wrote:

  Hello.

  Very new to Python and looking for some basic help.

  Would like a set-up where something happens when a key is pressed. Not
propose a question, have the user type something, then hit return, then
something happens, but just the R key is pressed, something happens, then
something else happens if the B key is pressed, then a third thing
happens if the G key is pressed.

  My research only served to confuse me. Firstly, I do not understand how
it is possible for this to be a difficult thing not built into the system
for any scripting language made within the last few decades. More to the
point I am unclear on specific suggestions. Most of them seem to be for
Windows only and I want this working on a Raspberry Pi. Saw getch but I
am still confused if it is platform specific or not, or requires a module
to be installed or not. Just get errors if I try to install getch using
PIP.


If you are using Python through a CLI (command line interface i.e., a 
shell), then in fact your request doesn't really make sense.  CLIs by 
their nature don't support that kind of interaction.


BUT don't despair.  Nearly every GIU framework on the planet has a 
Python interface, and they all allow for a window to be opened with 
event processing of your choice.


This are some good places to start:
https://wiki.python.org/moin/GuiProgramming
https://wiki.python.org/moin/GUI%20Programming%20in%20Python

Several of these (Tkinter and the curses module) are distributed with 
Python, so you should already have them installed.


Gary Herron





  Other suggestions seemed to be overkill and confused me to due to my
beginner level knowledge and the fact these suggestions have other, more
complicated elements to them.

  I just want a button press on a device connected to a Raspberry Pi to
trigger an action. If anyone can give me some guidance on this I would
appreciate it.

  Thank you.




--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Please help on this sorted function

2015-06-03 Thread Gary Herron

On 06/02/2015 01:20 PM, fl wrote:

Hi,

I try to learn sorted(). With the tutorial example:





ff=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
ff

[1, 2, 3, 4, 5]



I don't see what sorted does in this dictionary, i.e. the sequence of
1..5 is unchanged. Could you explain it to me?


Thanks,


It's best to think of dictionaries as unordered collections of key/value 
pairs.  Dictionaries are not sequences, do not have any particular 
ordering, and in full generality *can't* be sorted in any sensible way.


For instance, this slightly odd (but perfectly legal) dictionary
 d = {'a':123, 456:'b'}
can't be sorted
 sorted(d)
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: unorderable types: int()  str()
because it doesn't make sense to order/compare the two keys 'a' and 456.

If your dictionary is a little better behaved, say
 d = {'a':123, 'b':456}
you may be able to sort the keys
 sorted(d)
['a', 'b']
or the values
 sorted(d.values())
[123, 456]
or the key/value tuples (called items)
 sorted(d.items())
[('a', 123), ('b', 456)]
but each of those attempts to sort could fail on a general dictionary if 
the individual keys or values are not sortable.


There is also an implementation of a type of dictionary that remembers 
the order in which the items are *inserted*.  It's in the collections 
module and called OrderedDict.



Gary Herron






--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Where is 'palindrome' defined?

2015-06-01 Thread Gary Herron

On 05/31/2015 09:46 PM, fl wrote:

Hi,

When I search solution of reverse a string/number, I came across a short
function online:


def palindrome(num):

return str(num) == str(num)[::-1]

I thought that it is a general function. And with the following variable:


No, this  function is not built into Python because  ...  Well it's hard 
to say why.  It's not very general, or not useful to many programmers, 
or nobody's thought about it or made a case for including it in Python, etc.


But that should be no problem.  You can define it yourself (by entering 
the two line you have above).  Then it will be defined, and calling

parlindrome('...')
will produce a result rather than an error.

Gary Herron





a

'1234_'


parlindrome(a)

Traceback (most recent call last):
   File pyshell#126, line 1, in module
 parlindrome(a)
NameError: name 'parlindrome' is not defined


Then, I find that parlindrome is a special checking mirrored word.
I use Python 2.7.9. Why does the error message show

name 'parlindrome' is not defined



Thanks,



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Returning a custom file object (Python 3)

2015-05-28 Thread Gary Herron

On 05/27/2015 10:29 PM, Marko Rauhamaa wrote:

Ben Finney ben+pyt...@benfinney.id.au:


It seems the existing ‘open’ implementation doesn't allow you to
override the type of object returned.

The question is, can you assign to the builtin namespace. I'm guessing
you can't.


Of course you can.

Python2:
 __builtins__.open = whatever


Python3:
 import builtins
 builtins.open = whatever


Of course doing so is like shooting yourself in the foot:  Any 
subsequent pain is your own fault and probably well deserved.


Gary Herron





Within a module, you can simply do:

open = MyFile

Also, in other modules, you can:

from myfile import open


Marko



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418


--
https://mail.python.org/mailman/listinfo/python-list


Re: Array of Functions

2015-05-26 Thread Gary Herron

On 05/26/2015 05:43 PM, richard_riehle wrote:

I realized that I mentioned earlier that I found a solution to my original 
question, but that I never posted an example of the solution.   So, here is a 
simplified example for anyone who is interested.

def fArray(fselect, fparm  = 1):
def A1(p = fparm):
if p == 1:
print(printing A1[1])
else:
print(printing A1[other])
def A2(p = fparm):
if p == 1:
print(printing A2[1])
else:
print(printing A2[other])
A = [A1, A2]
A[fselect]()


Nested functions are often confusing and unclear, and there is really no 
need for them here.   This does the same thing:



def A1(p):
print(printing,  A1[1] if p==1 else A1[other]))

def A2(p):
print(printing,  A2[1] if p==1 else A2[other]))

def fArray(fselect, fparm=1):
A = [A1,A2]
A[fselect](fparm)



In this example, I enclosed two functions within another function, and then put 
those two functions in a list.  Then, with appropriate parameters, I called one 
of the functions in the list, associated the formal parameter with the function 
in a call to the array, and presto, it performs the function.

The more advanced problem I wanted to solve, a two dimensional array of 
functions, once this example is understood, becomes trivial to implement.  In 
fact, the more interesting problem I wanted to solve involved a dictionary of 
functions in a two-dimensional array, and that too was easy to do in Python.

When I compare what this would require in C, C++, Java, or most other 
languages, I find Python to be really easy for solving this kind of problem.

Next, I plan to develop the solution using decorators and assertions to empower 
it with a greater level of portability and to make the functions more generic.

I hope someone finds this interesting.

Richard Riehle, PhD




--
https://mail.python.org/mailman/listinfo/python-list


Re: a more precise distance algorithm

2015-05-25 Thread Gary Herron

On 05/25/2015 12:21 PM, ravas wrote:

I read an interesting comment:

The coolest thing I've ever discovered about Pythagorean's Theorem is an 
alternate way to calculate it. If you write a program that uses the distance 
form c = sqrt(a^2 + b^2) you will suffer from the lose of half of your 
available precision because the square root operation is last. A more accurate 
calculation is c = a * sqrt(1 + b^2 / a^2). If a is less than b, you should 
swap them and of course handle the special case of a = 0.


Is this valid?



Does it apply to python?


This is a statement about floating point numeric calculations on a 
computer,.  As such, it does apply to Python which uses the underlying 
hardware for floating point calculations.


Validity is another matter.  Where did you find the quote?

Gary Herron



Any other thoughts? :D

My imagining:

def distance(A, B):
 
 A  B are objects with x and y attributes
 :return: the distance between A and B
 
 dx = B.x - A.x
 dy = B.y - A.y
 a = min(dx, dy)
 b = max(dx, dy)
 if a == 0:
 return b
 elif b == 0:
 return a
 else:
 return a * sqrt(1 + (b / a)**2)


--
https://mail.python.org/mailman/listinfo/python-list


Re: a more precise distance algorithm

2015-05-25 Thread Gary Herron

On 05/25/2015 09:13 PM, ravas wrote:

On Monday, May 25, 2015 at 8:11:25 PM UTC-7, Steven D'Aprano wrote:

Let's compare three methods.
...
which shows that:

(1) It's not hard to find mismatches;
(2) It's not obvious which of the three methods is more accurate.

Thank you; that is very helpful!

I'm curious: what about the sqrt() function being last is detrimental?
 From a point of ignorance it seems like we are just producing errors sooner,
and then multiplying them, with this alternative method.


It's probably not the square root that's causing the inaccuracies. In 
many other cases, and probably here also, it's the summing of two 
numbers that have vastly different values that loses precision.  A 
demonstration:


 big = 1.0
 small = 0.1
 (big+small)-big # Should produce a value =small, but gives an exact 
zero instead.

0.0

The squaring of the two values in x*x+y*y just makes the addition even 
more error prone since the squares make large values even larger and 
small values even smaller.



Gary Herron.

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: I do not have access to the right _hierarchy.py source file

2015-05-17 Thread Gary Herron

On 05/17/2015 09:18 AM, pegah Aliz wrote:

...

To solve this problem, I checked linkage() function and inside it I needed to check 
_hierarchy.linkage() method. I use pycharm text editor and when I asked for linkage 
source code, it opened up a python file namely _hierarchy.py inside the directory like 
the following:

.PyCharm40/system/python_stubs/-1247972723/scipy/cluster/_hierarchy.py
  
This python file doesn't have any definition for all included functions.

I am wondering what is the correct source of this function to revise it and 
solve my problem.
I would be appreciated if someone helps me to explore the correct source.

Thanks and Regards
Pegah


Please tell us:

 * What platform you are on;  Linux, Windows, ...
 * How you installed PyCharm
 * What contents that file currently has
 * Why you think it's incorrect.

I think it's far more likely that that file is correct, and you are 
somehow misinterpreting its contents, but we can't even begin to guess 
until you show us its current content.


Gary

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Rule of order for dot operators?

2015-05-16 Thread Gary Herron

On 05/16/2015 12:20 PM, C.D. Reimer wrote:

Greetings,

Noobie question regarding a single line of code that transforms a URL 
slug (this-is-a-slug) into a title (This Is A Slug).


title = slug.replace('-',' ').title()

This line also works if I switched the dot operators around.

title = slug.title().replace('-',' ')

I'm reading the first example as character replacement first and title 
capitalization second, and the second example as title capitalization 
first and character replacement second.


Does python perform the dot operators from left to right or according 
to a rule of order (i.e., multiplication/division before add/subtract)?


Yes, that's correct.

Gary Herron





Thank you,

Chris Reimer



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: use of subprocess module inside generator

2015-05-13 Thread Gary Herron

On 05/13/2015 12:43 PM, Peter wrote:


I'm using Python 3.4.3 on Windows 7 (with latest patches) to develop a 
sqlcmd module for accessing SQL Server (via Microsoft's sqlcmd.exe).  
My goal is to develop a 100% Python 3 module that's easy to use, 
flexible, and by design shifts the majority of future SQL Server 
Python database access maintenance to Microsoft.  So far, I've 
successfully and quickly converted a few of my Python pyodbc 
applications/tools to use this new module.  However, I recently ran 
into an apparent Python issue which cost me a few hours to diagnose 
and work around.


I doubt that you've hit a bug -- we've all done this kind of thing many 
times, and there's certainly no restriction on making procedure calls 
within a generator -- so that's probably not the problem either.


My guess is that you've misinterpreted the failure of the original 
code.  I don't know how that might be, but I do spot one oddity in your 
original code which may be responsible.  See below ...




I'm hoping that someone might know what the root cause of my issue 
was.  Perhaps I've hit a bug/restriction with Python generators?


My original generator function looked like this:

def _raw_data(cl, stdout, *, opath=None, timeout=timeout):
stdout = subprocess.check_output(cl, universal_newlines=True, 
timeout=timeout)


This seems muddled -- you pass in a parameter, stdout, only to 
immediately overwrite its value with the output of check_output. What 
was in stdout originally, and more importantly, did you expect the newly 
assigned value from check_output to be returned to the calling 
procedure?  If so, that's your bug, because parameters in function calls 
don't work that way.


This makes sense with your workaround, since the assignment to stdout is 
preserved when done outside the function.


I hope that helps.

Gary Herron





if opath is None:
for line in stdout.splitlines():
yield line.strip()
else:
with open(opath) as f:
for line in f:
yield line.strip()

The above function appeared to work fine, if the command line directed 
sqlcmd.exe to send its output to stdout.  However, if the command line 
directed sqlcmd.exe to send its output to a file, 
subprocess.check_output would never be called when next was called on 
the returned generator.  I verified this behavior with print 
statements inside my code, as well as, inside the subprocess module.


My work around was to simply move the call to subprocess.check_output 
outside of the generator function (see below) to its caller (a 
non-generator function).  With this minor change, everything appears 
to work as expected.  OK, so am I missing something here?


def _raw_data(stdout, *, opath=None):
if opath is None:
for line in stdout.splitlines():
yield line.strip()
else:
with open(opath) as f:
for line in f:
yield line.strip()

Thank you in advance for your assistance.

Peter Santoro



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: anomaly

2015-05-12 Thread Gary Herron

On 05/12/2015 04:55 AM, Antoon Pardon wrote:

Op 11-05-15 om 16:13 schreef Chris Angelico:


Why does Python have most built-ins as simply looked-up names that can
be overridden? Because otherwise, there would be a veritable ton of
keywords:

But that doesn't answer the question why the developers chose True to be a
keyword and int to be a looked-up name.

and pretending to justify that choice by stating that the python thought
is: We're all adults here, if you want to override a builtin, who are we
to stop you. That is disingenuous.



Bull.   Some design decisions were made with the knowledge that

 * they provide a freedom which may be useful but can be misused (e.g.,
   shadowing builtins), versus
 * they would be too disruptive of abusable (e.g. shadowing keywords)

Python tends to use the first category more than C family languages, and 
that's where the We're all adults argument applies.  You may argue 
about which category any particular feature ought to fall into, and in 
fact several things (shadowing None, True, and False) have changed 
category during the evolution of Python.  But to imply that the adult 
argument should drive *all* decisions is foolish. And disingenuous.


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: anomaly

2015-05-10 Thread Gary Herron

On 05/10/2015 05:48 PM, zipher wrote:

On Sunday, May 10, 2015 at 11:44:36 AM UTC-5, Ian wrote:

On Sun, May 10, 2015 at 10:34 AM, Mark Rosenblitt-Janssen
dreamingforw...@gmail.com wrote:

Here's something that might be wrong in Python (tried on v2.7):


class int(str): pass

This defines a new class named int that is a subclass of str. It has
no relation to the builtin class int.


int(3)

'3'

This creates an instance of the above int class, which is basically
equivalent to calling str(3).

Were you expecting a different result?

Sorry, yes.  If you're going to define a concept called keywords, I don't 
think you should allow them to be shadowed by a class definition.

Mark


Huh?   Python has plenty of keywords, and indeed, none of them can be 
redefined or shadowed.But you would gain nothing (and lose a bit or 
dynamic-language freedom) by making int a keyword.


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: anomaly

2015-05-10 Thread Gary Herron

On 05/10/2015 09:48 AM, Rustom Mody wrote:

On Sunday, May 10, 2015 at 10:14:36 PM UTC+5:30, Ian wrote:

On Sun, May 10, 2015 at 10:34 AM, Mark Rosenblitt-Janssen wrote:

Here's something that might be wrong in Python (tried on v2.7):


class int(str): pass

This defines a new class named int that is a subclass of str. It has
no relation to the builtin class int.


int(3)

'3'

This creates an instance of the above int class, which is basically
equivalent to calling str(3).

Were you expecting a different result?

In C (family) languages int is a keyword
 From that pov this is completely bizarre


Not really.  Expecting Python to act like C family languages *is* bizarre.

Common Python thought::  We're all adults here.If you want to 
override a builtin within your own namespace, who are we to stop you?
Besides, it's still available as __builtins__.int  (unless you've also 
overridden that).


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Try Except Specific Error Messages

2015-05-02 Thread Gary Herron

On 04/30/2015 04:27 PM, brandon wallace wrote:

Hi,
  
I am try to get more specific error messages using try/except.

I ran this code with the cable unplugged to see the error message. I got

#!/usr/bin/env python3

import urllib.request

webpage = urllib.request.urlopen(http://fakewebsite.com/;)
text = webpage.read().decode(utf8)


I got two errors. This:
[]
socket.gaierror: [Errno -2] Name or service not known

and this:
[]
urllib.error.URLError: urlopen error [Errno -2] Name or service not known


Note the error message here.  The exception is named 
urllib.error.URLError NOT URLError as you use in the next bit of code.


You could import that specific error if you wanted to access it that way:
 from urllib.error import URLError
otherwise you should use the fully qualified name urllib.error.URLError.



I tried this but got more error messages.
As a side note, that is never a useful thing to say in this group. Take 
the time to tell is the actual errors message you got.  That way I don't 
have to waste my time running your code to see what error message you 
are getting.




try:
 webpage = urllib.request.urlopen(http://fakewebsite.com/;)
 text = webpage.read().decode(utf8)
except URLError as err:
 print(URLError:  + str(err))

How do I wrap urllib.request with try/except?



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: l = range(int(1E9))

2015-04-30 Thread Gary Herron

On 04/30/2015 09:06 AM, Cecil Westerhof wrote:

If I execute:
 l = range(int(1E9)

The python process gobbles up all the memory and is killed. The
problem is that after this my swap is completely used, because other
processes have swapped to it. This make those programs more slowly. Is
there a way to circumvent Python claiming all the memory?

By the way: this is CPython 2.7.8.


Well, that could be considered the problem.   In Python3, the range 
function returns a range object which takes up almost no resources, 
while in Python2 it produces a list.  Both can be iterated over, so they 
produce the same result in the most common use case (i.e., iteration), 
but the Python3 version generates the elements only as needed.


If you really *wanted* the list (but WHY?) in Python3, do 
list(range(...)), but then you get what you deserve. :-)


Python3:

 l = range(int(1E9))
 l
range(0, 10)


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Best GUI for Python

2015-04-26 Thread Gary Herron

On 04/26/2015 11:07 AM, Cecil Westerhof wrote:

Op Sunday 26 Apr 2015 19:12 CEST schreef Gary Herron:


On 04/26/2015 09:32 AM, Cecil Westerhof wrote:

Op Sunday 26 Apr 2015 17:09 CEST schreef Steven D'Aprano:


On Sun, 26 Apr 2015 11:02 pm, Cecil Westerhof wrote:


I want to use a GUI for Python. When searching I found (beside
some others) Tkinter and wxPython. From what I found it looks
like Tkinter is slightly better. What would be the pros/cons of
these two? Would there be a compelling reason to use another GUI?

Tkinter is easier to use, as it is standard with Python. So long
as you have Tk/Tcl installed on your computer, Tkinter should work
fine.

However, Tkinter probably looks a bit more old fashioned.

wxPython probably looks a bit more modern and may be a bit more
powerful, but it will require a large extra library. It's also a
lot harder to learn to use wxPython unless you are comfortable
with C++ programming.

Well, I did my share of C++ programming. ;-)



Have you seen this?

https://wiki.python.org/moin/GuiProgramming

Dabo looks interesting, but also a little bit dead. Well, maybe I
just should evaluate Tkinter and wxPython both. Now wxPython looks
more interesting. But it is easier to make a reasonable decision
when I have a little more information. :-D

For the moment I limit it to Tkinter and wxPython.

I wouldn't recommend limiting yourself like that. I've used both
successively (years ago), then pyGTK for a batch of projects,
followed by pyglet for some years and many projects, and most
recently PyQt. They are all worthy GUI programming libraries, and
each of them is cross platform (as I required to develop on Linux,
but deploy occasionally on Windows).

I did say for the moment. ;-)

But just curious: what is the reason you use five different kinds of
GUI? It seems like it makes think difficult for you. I mean the
question as enlightenment for myself.



Yikes,  Stated like that it does sound excessive but in reality it's 
spread over about 20 years of Python and graphics/GUI programming. 
Experimenting with a new GUI every 5 years or so  just keeps the 
interest levels up.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Best GUI for Python

2015-04-26 Thread Gary Herron

On 04/26/2015 09:32 AM, Cecil Westerhof wrote:

Op Sunday 26 Apr 2015 17:09 CEST schreef Steven D'Aprano:


On Sun, 26 Apr 2015 11:02 pm, Cecil Westerhof wrote:


I want to use a GUI for Python. When searching I found (beside some
others) Tkinter and wxPython. From what I found it looks like
Tkinter is slightly better. What would be the pros/cons of these
two? Would there be a compelling reason to use another GUI?

Tkinter is easier to use, as it is standard with Python. So long as
you have Tk/Tcl installed on your computer, Tkinter should work
fine.

However, Tkinter probably looks a bit more old fashioned.

wxPython probably looks a bit more modern and may be a bit more
powerful, but it will require a large extra library. It's also a lot
harder to learn to use wxPython unless you are comfortable with C++
programming.

Well, I did my share of C++ programming. ;-)



Have you seen this?

https://wiki.python.org/moin/GuiProgramming

Dabo looks interesting, but also a little bit dead. Well, maybe I just
should evaluate Tkinter and wxPython both. Now wxPython looks more
interesting. But it is easier to make a reasonable decision when I
have a little more information. :-D

For the moment I limit it to Tkinter and wxPython.


I wouldn't recommend limiting yourself like that.  I've used both 
successively (years ago),  then pyGTK for a batch of projects, followed 
by pyglet for some years and many projects, and most recently PyQt.
They are all worthy GUI programming libraries, and each of them is cross 
platform (as I required to develop on Linux, but deploy occasionally on 
Windows).





--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: xlwt 1.0.0 released!

2015-04-15 Thread Gary Herron

On 04/15/2015 02:51 PM, Chris Withers wrote:

Hi All,

I'm pleased to announce the release of xlwt 1.0.0.


What a curiously incomplete announcement.  Could you tell us what xlwt 
is?  I see no hint here.


Gary Herron




This release contains the following:

- Python 3 support.

- An initial set of unit tests.

- An initial set of Sphinx documentation.

- Move to setuptools for packaging.

- Wire up Travis, Coveralls and ReadTheDocs.

- Allow longs as row indexes.

Big thanks to Thomas Kluyver for his work on Python 3 support, Manfred 
Moitzi

for donating his unit tests.

Belated thanks to Landon Jurgens for his help on converting the 
documentation

to Sphinx.

If you find any problems, please ask about them on the 
python-ex...@googlegroups.com list, or submit an issue on GitHub:


https://github.com/python-excel/xlwt/issues

There's also details of all things Python and Excel related here:

http://www.python-excel.org/

NB: This is likely the last new feature release of xlwt. If there 
are bugs, we will try and fix them, but it may be a slow process. If 
you're starting a new project, you should probably consider openpyxl 
or xlsxwriter instead.


cheers,

Chris



--
https://mail.python.org/mailman/listinfo/python-list


Re: Supply condition in function call

2015-03-25 Thread Gary Herron

On 03/25/2015 10:29 AM, Manuel Graune wrote:

Hi,

I'm looking for a way to supply a condition to an if-statement inside a
function body when calling the function. I can sort of get what I want
with using eval (see code below) but I would like to achieve this in a
safer way. If there is a solution which is safer while being
less flexible, that would be fine. Also, supplying the condition as a
string is not necessary. What I want to do is basically like this:

def test1(a, b, condition=True):
 for i,j in zip(a,b):
 c=i+j
 if eval(condition):
print(Foo)

test1([0,1,2,3],[1,2,3,4],i+j 4)
print(Bar)
test1([0,1,2,3],[1,2,3,4],c 4)
print(Bar)
test1([0,1,2,3],[1,2,3,4],a[i] 2)
print(Bar)
test1([0,1,2,3],[1,2,3,4])




This is nicely done with lambda expressions:

To pass in a condition as a function:
   test1([0,1,2,3],[1,2,3,4], lambda i,j: i+j4)

To check the condition in the function:
if condition(i,j):

To get the full range of conditions, you will need to include all the variables 
needed by any condition you can imagine.  So the above suggestions may need to 
be expanded to:
 ... lambda i,j,a,b: ... or whatever

and
  ... condition(i,j,a,b) ... or whatever

If any of your conditions gets too long/complex for a lambda (or you just don't 
like Python's lambda expressions), then just create a function for your 
condition:

  def cond1(i,j,a,b):
  return i+j4

and do
   test1(..., cond1)
and
if condition(i,j,a,b):




--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: PIL(LOW) - What am I missing?

2015-03-25 Thread Gary Herron

On 03/25/2015 08:54 PM, kai.pet...@gmail.com wrote:

I create an image as per:

 img  = Image.new('1', (1024, 1280), 1)

I then draw on it and do:

 imagedata = list(img.getdata())
 print len(imagedata)

This gives me 1228800 instead of the expected 1310720 (1024 * 1280) 
- any ideas what I am missing?

As always, any help much appreciated.

Kai


Are you sure?

Both Python2 and Python3 give me the expected 1310720,

I'm running PILLOW version 2.6.1 on Linux (with both Python 3.4.2 and 
Python 2.7.8).


 from PIL import Image
 img  = Image.new('1', (1024, 1280), 1)
 imagedata = list(img.getdata())
 print len(imagedata)
1310720



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Daylight savings time question

2015-03-24 Thread Gary Herron

On 03/24/2015 03:24 PM, Dan Stromberg wrote:

Is there a way of adding 4 hours and getting a jump of 5 hours on
March 8th, 2015 (due to Daylight Savings Time), without hardcoding
when to spring forward and when to fall back?  I'd love it if there's
some library that'll do this for me.

#!/usr/bin/python

import pytz
import datetime

def main():
 # On 2015-03-08, 2:00 AM to 2:59AM Pacific time does not exist -
the clock jumps forward an hour.
 weird_naive_datetime = datetime.datetime(2015, 3, 8, 1, 0,
0).replace(tzinfo=pytz.timezone('US/Pacific'))
 weird_tz_aware_datetime =
weird_naive_datetime.replace(tzinfo=pytz.timezone('US/Pacific'))
 print(weird_tz_aware_datetime)
 four_hours=datetime.timedelta(hours=4)
 print('Four hours later is:')
 print(weird_tz_aware_datetime + four_hours)
 print('...but I want numerically 5 hours later, because of
Daylight Savings Time')

main()


Thanks!


The pyzt module (which you've imported) has lots to say about this. Look 
at its procedures localize' and 'normalize' and all the rest of the 
pyzt documentation.




--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Regex Python Help

2015-03-24 Thread Gary Herron

On 03/24/2015 11:13 AM, gdot...@gmail.com wrote:

I am creating a tool to search a filesystem for one simple string.
I cannot get the syntax correct.
Thank you in advance for your help.

import sys
import re
import os
path='/'
viewfiles=os.listdir(path)
for allfiles in viewfiles:
 file= os.path.join(path, allfiles)
text=open(file, r)
for line in text:
 if re.match(DECRYPT_I, line):
 print line,

--
This should search every file for the simple regex DECRYPT_I
This is from the root down.

The error is:

SyntaxError: Missing parentheses in call to 'print'

Please help.
Gregg Dotoli


You appear to be using Python3, but have written code for Python2.

There are a number of differences between the two, but your particular 
error runs into the different syntax for prints.


Python2: print line # This is a statement
Python3  print(line)  # This is a procedure call



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: id() and is operator

2015-02-22 Thread Gary Herron

On 02/22/2015 09:53 AM, LJ wrote:

Hi everyone. Quick question here. Lets suppose if have the following numpy 
array:

b=np.array([[0]*2]*3)

and then:


id(b[0])

4582

id(b[1])

45857512

id(b[2])

4582

Please correct me if I am wrong, but according to this b[2] and b[0] are the 
same object. Now,


b[0] is b[2]

False


Any clarification is much appreciated.

Cheers,



In fact, b[0] and b[2] are different objects as can be seen here:
 import numpy as np
 b=np.array([[0]*2]*3)
 b[0]=1 // broadcast into both ints in row 0
 b[1]=2 // ... row 1
 b[2]=3 // ... row 2
 b
array([[1, 1],
   [2, 2],
   [3, 3]])

When you extracted b[0], you got a newly created python/numpy object 
(1x2 array of ints) briefly stored at location  4582 but then 
deleted immediately after that use.  A little later, the extraction of 
b[2] used the same bit of memory.  The id of a temporarily created value 
is meaningless, and apparently misleading.


As a separate issue, each of b, b[0], b[1], and b[2] do *all* refer to 
the same underlying array of ints as can be seen here:

 r = b[0]
 r[0] = 123
 b
array([[123,   1],
   [  2,   2],
   [  3,   3]])


but the Python/numpy objects that wrap portions of that underlying array 
of ints are all distinct.



Gary Herron



--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: id() and is operator

2015-02-22 Thread Gary Herron

On 02/22/2015 10:02 PM, Terry Reedy wrote:

On 2/22/2015 4:25 PM, Marko Rauhamaa wrote:

LJ luisjoseno...@gmail.com:


id(b[0])

4582

[...]

id(b[2])

4582



Please correct me if I am wrong, but according to this b[2] and b[0]
are the same object. Now,


b[0] is b[2]

False


This is a true statement:

If X is Y, then id(X) == id(Y).

However, this is generally not a true statement:

If X is Y, then id(X) is id(Y).


If X and Y exist at the *same time*, then (X is Y) == (id(X) is 
id(Y)).  Since X and Y in the example above do not exist at the same 
time, it is nonsensical to compare them.


Not quite.  You've been bitten by the is versus == trap.   You could use
id(X)==id(Y)
but not
id(X) is id(Y)
not even if X and Y are the same object.   Simple examples:

 a=3
 id(a) is id(a)
False

 a=3
 b=a
 id(a) is id(b)
False

The explanation is that each call to id() makes its own independent 
Python integer object containing the large integer (10771264 in this 
case).  The two integer objects satisfy ==, but they are separate 
Python objects so they do not satisfy is.


As a side note,  It is an implementation detail whether two Python 
integer objects created independently but with the same value are 
separate objects or references to a single object.   CPython caches 
small integers so that only one integer object of each value exists, but 
not so for large integers.  You can experiment with the cutoff on your 
particular flavor of Python.  On mine (Python 3.4.2 (default, Oct  8 
2014, 13:08:17) ;[GCC 4.9.1] on linux)

it's somewhere between 200 and 300:

 201 is 1+200
True
 301 is 1+300
False

Gary Herron







--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Delegation in Python

2015-01-24 Thread Gary Herron

On 01/24/2015 03:22 PM, Chris Angelico wrote:

On Sun, Jan 25, 2015 at 9:57 AM, Brian Gladman no...@nowhere.net wrote:

But I am not clear on how to delegate from my new class to the existing
Fraction class.  This is what I have:

--
class RF(Fraction):

   def __new__(self, x, y):
 super().__new__(self, x, y)

   def is_integer(self):
 return self.numerator % self.denominator == 0

   def __getattr__(self, attr):
 return getattr(self, attr)

If you just drop everything but your new method, it should work just fine.

class RF(Fraction):
 def is_integer(self):
return self.numerator % self.denominator == 0

However, this doesn't ensure that operations on RFs will return more
RFs - they'll often return Fractions instead. There's no easy fix for
that, sorry.

ChrisA


You can always monkey-path the Fraction class on the fly to add a new 
method to it.  I think most would consider this a bad idea, but it does 
work.

Try this:

 from fractions import Fraction
 def is_integer(self):
... return self.numerator % self.denominator == 0
...
 Fraction.is_integer = is_integer # Monkey-patch Fraction

 Fraction(1,2).is_integer()
False
 Fraction(2,1).is_integer()
True


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Delegation in Python

2015-01-24 Thread Gary Herron

On 01/24/2015 03:38 PM, Brian Gladman wrote:

On 24/01/2015 23:22, Chris Angelico wrote:

class RF(Fraction):
 def is_integer(self):
return self.numerator % self.denominator == 0

Thanks for your help on this.  I must admit that nowhere in a lot of
searching did I find that delegation is achieved by doing nothing!

Brian


That's *not* doing nothing.   And it's not even really delegation.  
It's just sub-classing Fraction to add one new method and inherit all 
other methods.


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: MS-DOS Commands

2015-01-11 Thread Gary Herron

On 01/11/2015 02:13 PM, Jenacee Owens wrote:

I'm new to python and every time i type a command into the MS-DOS Commands it 
looks like this.


strings

Tracebackmost recent call last:
file stdin;line 1 in module
name error:name strings'is not defined

how can i fix this?


What where you trying to accomplish, and what did you expect that to 
do?  It's not a valid Python statement, so an error message that says as 
much is to be expected.


You really should start with a Python tutorial.

More comments:

 * You did not type that into the MS-DOS Commands, but rather to
   Python (or more accurately, to the Python interpreter).
 * Python does not have commands, but rather statements.
 * There is a module named strings, and you could import it (to use
   Python's terminology) with the import strings statement, but
   there's probably not much need to do so.  But then the strings
   statement you typed would not produce an error message, but would
   just print out a line informing you that strings is a module -- not
   very useful.
 * Rather than using Python in an MS-DOS window, you should consider
   trying statements and programs in Idle -- A reasonable GUI
   environment to experiment with Python.  It came with your
   installation of Python.
 * In the future, questions should be accompanied with information
   about your version of Python (Python2 or Python3) and the platform
   you are running it on. (Apparently Windows in your case.)

Gary Herron





-- 
https://mail.python.org/mailman/listinfo/python-list


Re: surprise - byte in set

2015-01-03 Thread Gary Herron

On 01/03/2015 10:50 AM, patrick vrijlandt wrote:

Hello list,

Let me first wish you all the best in 2015!

Today I was trying to test for occurrence of a byte in a set ...

 sys.version
'3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600 32 bit 
(Intel)]'

 'b' in 'abc'
True
 b'b' in b'abc'
True
 'b' in set('abc')
True
 b'b' in set(b'abc')
False

I was surprised by the last result. What happened?
(Examples simplified; I was planning to manipulate the set)


The surprise is really that the 3rd test is True not that the fourth is 
False.


First, as should be expected, a byte string is a sequence of (small) 
ints.  So b'b' is a (short) byte string and the set set(b'abc') is 
composed of three ints.  You should not expect your inclusion test to 
return True when testing for a bytes-type object in a set of int-type 
objects.  And that explains your False result in the 4th test.


 type(b'abc')
class 'bytes'
 type(b'abc'[0])
class 'int'


But things are different for strings.  You might think a string is a 
sequence of characters, but Python does not have a character type. In 
fact the elements of a string are just 1 char long strings:


 type('abc')
class 'str'
 type('abc'[0])
class 'str'

You would not logically expect to find a string 'b' in a set of 
characters in, say C++,  where the two types are different.  But that's 
not the Python way.  In Python a set of characters set('abc') is really 
a set of (short) strings, and the character 'b' is really a (short) 
string, so the inclusion test works.


Python's way of returning a 1-byte string when indexing a string 
(instead of returning an element of type character) allows this 
surprising result.


 'abc'[0]
'a'
 'abc'[0][0]
'a'
 'abc'[0][0][0]
'a'
 'abc'[0][0][0][0]
'a'
...


I've never considered this a problem, but a infinitely indexable object 
*is* a bit of an oddity.







Patrick

---
Dit e-mailbericht is gecontroleerd op virussen met Avast 
antivirussoftware.

http://www.avast.com




--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: problems with Methods in Python 3.4.2

2014-12-18 Thread Gary Herron

On 12/18/2014 09:27 AM, Marcus Lütolf wrote:


Hello Dears,

1)I am trying to do this:

 dir(_builtins_)



It's __builtins__ not _builtins_  (double underscores at each end not 
single underscores)


I am getting this:

Traceback (most recent call last):

File pyshell#0, line 1, in module

dir(_builtins_)

NameError: name '_builtins_' is not defined

2)I am trying to do this:

 'TTA',_add_('GGA')



To call a method use . not ,.   And the method you are trying to 
call is __add__ not _add_.  But why... just do TTA+GGA


I’am getting this :

Traceback (most recent call last):

File pyshell#0, line 1, in module

'TTA',_add_('GGA')

NameError: name '_add_' is not defined

3)I am trying to do this:

 -3  .abs()



abs is a function not a method.  do: abs(-3)


I’am getting this

Traceback (most recent call last):

  File pyshell#1, line 1, in module

-3 .abs()

AttributeError: 'int' object has no attribute 'abs'

4) finally, after printing

abs._doc_()



Again, use double underscores abs.__doc__()


I am getting this (and so on) :

Traceback (most recent call last):

  File pyshell#2, line 1, in module

abs._doc_()

AttributeError: 'builtin_function_or_method' object has no attribute 
'_doc_'


What did I do wrong ? Thanks for help, Marcus Luetolf, M.D., 90 
Bondastreet, CH-7000 Chur, Switzerland.





--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question on lambdas

2014-12-08 Thread Gary Herron

On 12/08/2014 03:43 PM, memilanuk wrote:


So... I was browsing some questions on reddit, and one of them 
involved tkinter and lambdas.  Managed to help the person out, but in 
the process ended up with more questions of my own :/


My basic confusion revolves around this: in one instance I see things 
like the following:


R1 = tk.Radiobutton(root, text='A', value=100, variable=var,
command=lambda: update_label2('A', 100))

and in another example I see things like this:

class MyText(Text):
def __init__(self, master, **kw):
apply(Text.__init__, (self, master), kw)
self.bind(Return, lambda e: break)


What I'm having trouble finding a concrete answer to is the difference 
between:


lambda: some_func

A function to be called with no parameters



lambda e: some_func

A function to be called with one parameter



lambda e=e: some_func
A function to be called with one or zero parameters.  In the case of a 
call with no parameters, a default value has been supplied.  The e=e may 
be slightly confusing, because 'e' is used in two contexts, one for the 
name of the parameter inside the function, and the other the name of the 
supplied default value (from the outer scope).


Any help would be greatly appreciated.

TIA,

Monte



Hope that helps,

Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: help with processing text file

2014-12-04 Thread Gary Herron

On 12/04/2014 08:46 PM, C. Ng wrote:

Hi,

Given the sample text file below (where the gibberish represent the irrelevant 
portions) :


abcddsdfffgfg
ggfhghghgfhghgh   round 5 xccdcxcfd
sdfdffdfbcvcvbbvnghg score = 0.4533
abcddsdfffgfg round 5 level = 0.15
ggfhghghgfhghgh   round 10 dfsdfdcdsd
sdfdffdfbcvcvbbvnghg score = 0.4213
sdsdaawsdsround 10 level = 0.13
..and so on


I would like to extract the values for round, score and level:
5 0.4533 0.15
10 0.4213 0.13
and so on...

Please advise me how it can be done, and what Python functions are useful.

Thanks.


I would use regular expressions.  See 
https://docs.python.org/3/library/re.html


Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Using Python for date calculations

2014-11-21 Thread Gary Herron

On 11/21/2014 12:35 AM, Steve Hayes wrote:

I've finally found a use for Python.

When, in the course of my genealogy research, I look at census or burial
records, I often want to work out a person's date of birth from their age.
It's a simple matter of mental arithmetic, but I sometimes get it wrong, and
mislead myself. There are calculators and date calculation programs, but they
are usually too complicated and try to do too much, so by the time you've
worked out what to do it takes much longer.

This Python script does it for me.

year = input(Year: )
age = input(Age: )
born = year-age
print 'Year of birth:', born

It's so simple, so elementary, that it's not really worth writing about,
except for the fact that it illustrates the KISS principle.

It is sometimes better to have a simple program that does one thing well than
a complex one that does lots of things, but none of them very efficiently.

The average hand calculator can do the same job, but you have to pick it up
and put it down, and you can't easily see if you've made a typo.

Having said that, however, yes, I would perhaps like to use Python for more
complicated date processing routines, namely to convert the kinds of dates
produced by genealogy programs to a simple -mm-dd that computer database
programs can understand, so that Abt May 1677 would be rendered as
1677-05-00

Has anyone done something like that in Python?





The datetime module has lots of capabilities including the several you 
mention.


See  https://docs.python.org/2/library/datetime.html

Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: Error when trying to open an image

2014-11-16 Thread Gary Herron

On 11/16/2014 11:37 AM, Abdul Abdul wrote:

Hello,

I'm trying to open an image using the `Python Imaging Library` as follows:

from PIL import Image
img = Image.open('xyz.jpg')

But, got the following error:

File C:/Users/abc/PycharmProjects/untitled/open_image.py, line 2, in 
module

from PIL import Image
  File C:\Python34\lib\site-packages\PIL\Image.py, line 62, in module
from PIL import _imaging as core
ImportError: DLL load failed: %1 is not a valid Win32 application.

Why is that? How can I solve this issue?


... To be clearer, your problem is not with *opening* an image, but (if 
you look at the error message) its with importing PIL.


Gary Herron
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Brython 3.0.0 relased

2014-11-16 Thread Gary Herron

On 11/16/2014 12:54 AM, Pierre Quentel wrote:

Hi,

Version 3.0.0 of Brython has been released recently

Brython is an implementation of Python 3 running in the browser, with an 
interface to DOM elements and events. It allows writing web client applications 
with Python instead of Javascript.

Python programs are inserted in the HTML page inside tags script 
type=text/python. The code is translated into Javascript on the fly and 
executed, without any pre-compilation step.

Brython is *real* Python, supporting most of the Python syntax including 
comprehensions, generators, descriptors, classes with multiple inheritance, 
metaclasses etc. Dozens of modules from the Python standard distribution are 
included unmodified in the Brython distribution.


I just recently started experimenting with Brython to create WebGL apps.  I've 
done straight OpenGL via Python for *years* and wanted to leverage that 
knowledge and code for WebGL without getting any deeper into Javascript than 
necessary.

I'm happy to report that Brython worked perfectly, seamlessly providing Python 
calls to (the JavaScript API) WebGL.  Amazingly well done!

Gary Herron

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Help with Python Multiprocessing

2014-11-13 Thread Gary Herron

On 11/13/2014 10:07 AM, Anurag wrote:

I am having trouble understanding the Multiprocessing module.
I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at 
once. Currently I am doing this :

from multiprocessing import Process

import Worker1.py
import Worker2.py
import Worker3.py



p1 = Process(target=Worker1.py)
p1.start()
p2 = Process(target=Worker2.py)
p2.start()
p3 = Process(target=Worker3.py)
p3.start()

But this will only start the 'Worker1'. How do I execute all the three files at 
once?

Thanks


I doubt that is your actual code.  Python imports do not include .py 
extension.  Please show us your actual code.  (Use cut and paste 
please.)  And then take the time to tell us how you determine only the 
first is started.  Then we can probably help.


As an aside: To be sure, one could make the above imports work by having 
files named py.py and __init__.py in a directory named Worker1 (and the 
same for directories Worker2 and Worker3).   I think it's more likely 
that you miss-typed the above code.


Gary Herron
--
https://mail.python.org/mailman/listinfo/python-list


Re: Combining lists to dictionary

2014-11-11 Thread Gary Herron

On 11/11/2014 12:43 PM, Denis McMahon wrote:

Hi

Given x,y are a lists of keys and value that I wish to combine to a
dictionary, such that x[n] is the key for value y[n], which is preferred:

z = {a:b for (a,b) in zip(x,y)}
z = {x[n]:y[n] for n in range(min(len(x),len(y)))}

The zip feels more elegant, but it seems clunky to use the zip method to
create a list of tuples just to split them up into key:value pairs.
However the zip method handles the inequal length list problem. Granted
it would probably be advisable to check that x and y are the same length
before starting anyway.



Are you using python 2 or 3.  (It ought to be 3 :-) .)

In Python3, zip does not create a list, but rather an iterator which 
returns tuples.  Not clunky at all, but rather an efficient 
implementation of the loop which you hand coded in your other example.


From help(zip):

class zip(object)
 |  zip(iter1 [,iter2 [...]]) -- zip object
 |
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The 
.__next__()

 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.

...


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a counter

2014-10-15 Thread Gary Herron

On 10/15/2014 11:39 AM, Shiva wrote:

Hi,

I am trying to search a string through files in a directory - however while
Python script works on it and writes a log - I want to present the user with
count of number of strings found. So it should increment for each string found.

How do I implement it?

If I use a print() within a if condition statement - and execute the script
in terminal - for each find, the print() prints in new line instead of a
constantly incrementing counter.

Thanks,
Shiva



The question seems confuse the word increment.

If you are asking how to count, plenty of responders have answered
count = count+1
and similar.

However, the second paragraphs seems to use the word increment to mean 
displaying the counter on a single line overwriting itself instead of a 
scrolling list of values one-per-line.  The solution may depend on what 
is displaying the value as you write it out, but if it's a 
terminal/command-prompt /console-window, then you want the write to 
finish with a carriage-return alone instead of a 
carriage-return/new-line combination.  In Python that is represented 
with a \r instead of a \n.


Python2:
  print counter, '\r', # The ending comma means do NOT output the usual \n

Python3:
  print(counter, end='\r')

Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: How to select every other line from a text file?

2014-10-13 Thread Gary Herron

On 10/13/2014 10:38 AM, Rff wrote:

Hi,
I have a text file. Now it is required to select every other line of that text 
to
  generate a new text file. I have read through Python grammar, but still lack 
the
  idea at the beginning of the task. Could you tell me some methods to get this?


Thanks,


Read in your lines, keeping a counter as you go.  Select those lines 
whose counter is even (or odd -- you didn't say which you wanted).


So now some questions for you:

 * Do you know how to open a file and read in all the lines?
 * Do you know how to count as you do so?
 * Do you know how to test for evenness?   (Use count%2 will be zero
   for even count values.)
 * Do you know how to write lines to an output file?

Gary Herron

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to parse standard algebraic notation

2014-09-30 Thread Gary Herron

On 09/30/2014 01:53 PM, math math wrote:

Hi,

I am trying to learn Python while solving exercises.

I want to basically write a program that inputs a polynomial in standard 
algebraic notation and outputs its derivative.

I know that I need to get the exponent somehow, but I am not sure how to 
accomplish this in python (3.3)

Do you have any ideas or suggestions? I don't want to use existing modules as 
this is meant to be a didactic experience.

Regards


This depends on things you have not yet told us.

In particular -- what standard algebraic notation?  For x-squared: 
x**2 ?  or perhaps  x^2 ?  or something else like some Unicode 
characters or HTML to get a small superscript 2 above an x.


Once you give an example of what your input looks like, we can start 
hashing out how to read it.


Gary Herron

--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list


Re: face detection

2014-09-22 Thread Gary Herron

On 09/22/2014 02:59 AM, narayan naik wrote:

good evening sir,
I am doing my M.Tech project on face 
detection,I am confused with the face detection algorithm,can you 
please tell me the simple and best algorithm.



No, sorry, but this newsgroup is about Python (a programming language).  
I'm not sure where you would find information about face detection, but 
I'm sure you could find a better forum with a little searching.


Gary Herron


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Convert 3d NumPy array into 2d

2014-08-27 Thread Gary Herron

On 08/27/2014 08:08 AM, phinn stuart wrote:
Hi everyone, how can I convert (1L, 480L, 1440L) shaped numpy array 
into (480L, 1440L)?


Thanks in the advance.

phinn




A simple assignment into the arrays shape does it:
 a = numpy.zeros((1,480,1440))
 a.shape
(1, 480, 1440)
 a.shape = (480,1440)
 a.shape
(480, 1440)

Gary Herron


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Challenge to convert a simple IDL code into Python

2014-08-24 Thread Gary Herron

On 08/24/2014 08:38 AM, Cleo Drakos wrote:


Here is IDL code:

|pro read_binary_file

file=  3B42RT.2014010318.7.bin

num_lon=  1440
num_lat=  480

data=  {header:  bytarr(num_lon*2),  precip:  intarr(num_lon,num_lat),  
precip_error:  intarr(num_lon,num_lat),  $
   source_of_estimate:  bytarr(num_lon,num_lat),  precip_uncal:  
intarr(num_lon,num_lat)}

close,  1
openr,  1,  file
readu,  1,  data
close,  1 
precip=  swap_endian(data.precip)


print,  precip
end|

My attempt in Python is here:

|fname=  '3B42RT.2014010318.7.bin'

num_lon=  1440
num_lat=  480

with  open(fname,  'rb')  as  fi:
 contents=  fi.read()
 precip=  struct.unpack_from(''+str(num_lon*num_lat)+'I',  contents,  
offset=  num_lon*2)

 precip=  np.array(data,dtype=int)
 precip data|

But, the results obtained from two codes above are not same. The IDL 
code is correct, but what is wrong with my python code?




You are not giving us much to go on here.

First that's not legal Python .  The |last line was probably meant to be 
a print|||, but if you expect us to examine your code, you absolutely 
*must* give us the actual code.  Please cut and paste.


Second, saying it doesn't work us useless.  Please tell us what the code 
is supposed to do, and what it actually does, what you expected...  If 
there is output, cut and paste it.  If there is an error traceback, cut 
and paste it.


While you are at it, tell us what the IDL code does and cut and paste 
it's output.


Gary Herron


Here is binary file I was working 
with:ftp://trmmopen.gsfc.nasa.gov/pub/merged/3B42RT/3B42RT.2014010318.7.bin.gz



cleo




-- 
https://mail.python.org/mailman/listinfo/python-list


Re: reading text files with indentation

2014-07-28 Thread Gary Herron

On 07/27/2014 11:25 PM, Noah wrote:

Hi there,

The following code I am using to read in lines from a text file. The 
indentation of the text is getting lost.  How can I correct that?



for file in files:
  with open (file, r) as file:
lines = file.readlines()

for line in lines:
line = re.sub(#.*, , line)
line = line.strip()


The *strip* method on strings removes all whitespace from both ends.  
There goes your indentation.



policy_lines.append(line)
print line

Cheers


Example:

abc   .strip()
'abc'


Gary Herron

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What meaning of this hello %s you are %s years old % x

2014-07-27 Thread Gary Herron

On 07/27/2014 11:49 AM, fl wrote:

Hi,

I get a post on tuple, see below please, on line. It seems that something is
missing. I want to learn tuple from this example as well.

Could you explain it to me (a tuple % another tuple)?


Thanks,






http://stackoverflow.com/questions/1708510/python-list-vs-tuple-when-to-use-each

In Python, when should you use lists and when tuples?

Sometimes you don't have a choice, for example if you have

hello %s you are %s years old % x
then x must be a tuple.

But if I am the one who designs the API and gets to choose the data types, then
what are the guidelines?


That's not tuple%tuple, but rather string%tuple.  And string%tuple is 
the older method of formatting an output string from a template and a 
tuple of values.  See 
https://docs.python.org/2/library/stdtypes.html#string-formatting for 
details.


However, if you are just learning Python, you should probably use the 
*newer* formatting operations.  See 
https://docs.python.org/3.3/library/string.html#formatspec for details 
of that.


Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: Distributing python applications as a zip file

2014-07-22 Thread Gary Herron

On 07/22/2014 09:23 PM, Steven D'Aprano wrote:

A little known feature of Python: you can wrap your Python application in
a zip file and distribute it as a single file. The trick to make it
runnable is to put your main function inside a file called __main__.py
inside the zip file. Here's a basic example:

steve@runes:~$ cat __main__.py
print(NOBODY expects the Spanish Inquisition!!!)

steve@runes:~$ zip appl __main__.py
   adding: __main__.py (stored 0%)
steve@runes:~$ rm __main__.py
steve@runes:~$ python appl.zip
NOBODY expects the Spanish Inquisition!!!


On Linux, you can even hack the zip file to include a shebang line!


steve@runes:~$ cat appl
#!/usr/bin/env python
# This is a Python application stored in a ZIP archive.
steve@runes:~$ cat appl.zip  appl
steve@runes:~$ chmod u+x appl
steve@runes:~$ ./appl
NOBODY expects the Spanish Inquisition!!!


It's not quite self-contained, as you still need to have Python
installed, but otherwise it's a good way to distribute a Python
application as a single file that users can just copy and run.





Really!  20 years of Pythoning, and I'd never seen this!  When was this 
introduced?


Gary Herron

--
https://mail.python.org/mailman/listinfo/python-list


Re: ISO8583

2014-07-15 Thread Gary Herron

On 07/15/2014 08:56 PM, barontro...@gmail.com wrote:

Hi,

I'm very new to python programming.
I would like to ask how come when I send ISO8583 to the server, I didn't get 
any response back.


This is not really a Python question, but should rather be asked of 
whoever created the ISO8583 module.

Do you know how to contact the developers of the ISO8583 package?

Gary Herron





If I send it incorrect parameter, the server will reply but if I send it 
correctly, the server didn't response.

The original client is in java using ISOMUX, I have been trying to use the 
pyMux.py that on the ISO8583 module but didn't succeed also.

Right now i'm just using normal python socket and ISO8583 module.

The original java ISOMUX code:

 ISOMUX isoMux = new ISOMUX(channel)
 {
   protected String getKey(ISOMsg m)
 throws ISOException
   {
 return m.getMTI().substring(0, 2) + m.getString(32) + m.getString(12);
   }
 };

Could someone give me example whether python have other method similar to 
ISOMUX?

Thank you.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Multiprocessing question

2014-07-13 Thread Gary Herron

On 07/13/2014 04:53 PM, Paul LaFollette wrote:

Kind people,
I have thrown together a little C/UNIX program that forks a child 
process, then proceeds to let the child and parent alternate.  Either 
can run until it pauses itself and wakes the other.


I would like to know if there be a way to create the same behavior in 
Python 3, preferably in a non-platform dependent fashion.  I would 
prefer to use processes rather than threads, but could live with 
threads if I had to.  I've studied the documentation for the 
multiprocessing and thread modules, but I can't see an easy way to do 
what I want to do.  I need minimal communication between processes 
beyond what i have described, so creating queues or pipes seems like 
overkill.  Unlike what I have written here, I will want to exec the 
child rather than write the whole thing in the else clause.  Is there 
a reasonably simple way to do this?  A reference to useful 
documentation would be appreciated.  Sample code even more so, of course.

Thank you
Paul


There is a quite reasonable way to do what you want,  but that involves 
the multiprocessing and queue modules, both of which you have eliminated 
from consideration.


So you have to ask yourself:  What do you gain from using Python if you 
eliminate all the tools Python provides?


Gary Herron






-
Paul S. LaFollette, Jr
CIS Department
Temple University
+1 215 204 6822
paul.lafolle...@temple.edu mailto:paul.lafolle...@temple.edu
http://knight.cis.temple.edu/~lafollet 
http://knight.cis.temple.edu/%7Elafollet


#include stdlib.h
#include stdio.h
#include unistd.h
#include sys/types.h
#include signal.h
#include errno.h

int main(int argc, char **argv)
{
  void handler(int);
  pid_t pid;

  signal(SIGCONT, handler);

  pid = fork();
  if (pid  0) //failure
  {
printf(Unable to fork\n);
exit(1);
  }
  else if (pid  0) // parent
  {
while (1)
{
  printf(Parent waiting for child to do something\n);
  pause();
  printf(Parent doing nifty stuff.\n);
  sleep(1);
  printf(Parent waking child\n);
  errno = 0;
  if (kill(pid, SIGCONT)  0)
perror(Parent failed to SIGCONT child.);
}
  }
  else //pid == 0 so child
  {
while (1)
{
  printf (Child doing useful 
work.\n);

  sleep(1);
  printf( Child waking 
parent\n);

  if (kill(getppid(), SIGCONT)  0)
perror(Child failed to SIGCONT parent.);
  printf( Child waiting for 
parent to do something\n);

  pause();
}
  }
}

void handler(int signum)
{
}
===
Output:
Parent waiting for child to do something
Child doing useful work.
 Child waking parent
 Child waiting for parent to do 
something

Parent doing nifty stuff.
Parent waking child
Parent waiting for child to do something
Child doing useful work.
 Child waking parent
 Child waiting for parent to do 
something

Parent doing nifty stuff.
Parent waking child
Parent waiting for child to do something
Child doing useful work.
 Child waking parent
 Child waiting for parent to do 
something






-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python 3.44 float addition bug?

2014-06-20 Thread Gary Herron



On 06/20/2014 05:57 PM, FraserL wrote:

I think I found a strange bug in python 3.4.1,



No, this is not a bug in Python.  There is a limitation of floating 
point arithmetic in *all* languages, on *all* computers.   Python 3 may 
be the first to let you see this limitation, but it's always been there.


See https://docs.python.org/2/tutorial/floatingpoint.html for more details.

Gary Herron





fresh install of

  https://www.python.org/ftp/python/3.4.1/python-3.4.1.amd64.msi

and a fresh install of
https://www.python.org/ftp/python/2.7.7/python-2.7.7.amd64.msi
to compare it to.

#test code
z = 0.01
p = 0.0
for x, y in enumerate(range(1, 20)):
 p += z
 print(p)
#end


3.4.1 output:

0.01
0.02
0.03
0.04
0.05
0.060005
0.07
0.08
0.09
0.0
0.10999
0.11998
0.12998
0.13999
0.15
0.16
0.17
0.18002
0.19003


2.7.7 output:

0.01
0.02
0.03
0.04
0.05
0.06
0.07
0.08
0.09
0.1
0.11
0.12
0.13
0.14
0.15
0.16
0.17
0.18
0.19


I'm not hugely accustomed to Python, but this seems crazy to me.


--
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   >