Re: pylint or similar to test version-specific language constructs?

2013-01-11 Thread The Night Tripper
Gisle Vanem wrote:

> "jkn"  wrote:
> 
>>I have to write python code which must run on an old version of
>> python (v2.4) as well as a newer (v2.7). I am using pylint and would
>> like to check if is possible to check with pylint the use of operators
>> etc. which are not present in 2.4; the ternary operator springs to
>> mind.
> 
> No idea about PyLint. Why not install Python 2.4 and test
> with that? Sounds safer IMHO.

I do have Python 2.4 installed; but I would like a checker that warned me 
beforehand about trying to use constructs (like the ternary operator, 
decorators) which are version-specific.

J^n


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


Re: pylint or similar to test version-specific language constructs?

2013-01-11 Thread thenault
On Thursday, January 10, 2013 12:45:32 AM UTC+1, jkn wrote:
> Hi all
> 
> I have to write python code which must run on an old version of
> 
> python (v2.4) as well as a newer (v2.7). I am using pylint and would
> 
> like to check if is possible to check with pylint the use of operators
> 
> etc. which are not present in 2.4; the ternary operator springs to
> 
> mind.
> 
> 
> 
> I haven't found anything in pylint which indicates it can do this sort
> 
> of check; am I missing anything? Other suggestions for this kind of
> 
> checking welcome.


Hi,

there is no such checker in pylint yet, though it should be fairly easy to 
build one. The longer part being to identify all constructs that should be 
detected and their representation in the ast. Then pylint checkers are simple 
visitors. You'll get some help from the project mailing list 
([email protected]) if you go that way.

Regards,

-- 
Sylvain
-- 
http://mail.python.org/mailman/listinfo/python-list


please i need explanation

2013-01-11 Thread kwakukwatiah
def factorial(n):
if n<2:
 return 1
f = 1
while n>= 2:
f *= n
f -= 1
return f
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please i need explanation

2013-01-11 Thread K. Elo

Hi!

Since there is no stated question, I need to guess:

n -= 1 (instead of "f -= 1")

should work.

Or maybe the question was a totally different one...

-Kimmo

11.01.2013 17:35, [email protected] wrote:

def factorial(n):
 if n<2:
  return 1
 f = 1
 while n>= 2:
 f *= n
 f -= 1
 return f





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


Re: please i need explanation

2013-01-11 Thread Karim

On 11/01/2013 16:35, [email protected] wrote:

def factorial(n):
if n<2:
 return 1
f = 1
while n>= 2:
f *= n
f -= 1
return f



What explanation this a function representing the math factorial.

You provide a parameter n:

if n est lower than 2 the factorial is 1 (return by the function).
in other case you multiply previous factoriel value by n (f *= n <=> f = 
f *n).

And you decrement n by 1 (f -=1 <=> f = f - 1).
This gives n*(n-)*(n-2) general formula for factorial.

Regards
Karim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please i need explanation

2013-01-11 Thread Vincent Vande Vyvre
Le 11/01/13 16:35, [email protected] a écrit :
> def factorial(n):
> if n<2:
>  return 1
> f = 1
> while n>= 2:
> f *= n
> f -= 1
> return f
>  
>
>
I guess you mean:
f = 1
while n>= 2:
f *= n
n -= 1
return f

Try it.



-- 
Vincent V.V.
Oqapy  . Qarte
 . PaQager 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please i need explanation

2013-01-11 Thread kwakukwatiah



-Original Message- 
From: K. Elo

Sent: Friday, January 11, 2013 3:56 AM
To: [email protected]
Subject: Re: please i need explanation

Hi!

Since there is no stated question, I need to guess:

n -= 1 (instead of "f -= 1")

should work.

Or maybe the question was a totally different one...

-Kimmo

11.01.2013 17:35, [email protected] wrote:

def factorial(n):
 if n<2:
  return 1
 f = 1
 while n>= 2:
 f *= n
 f -= 1
 return f




please it works.but don’t get why the return 1 and the code below.

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


Re: please i need explanation

2013-01-11 Thread Karim

On 11/01/2013 17:33, [email protected] wrote:



-Original Message- From: K. Elo
Sent: Friday, January 11, 2013 3:56 AM
To: [email protected]
Subject: Re: please i need explanation

Hi!

Since there is no stated question, I need to guess:

n -= 1 (instead of "f -= 1")

should work.

Or maybe the question was a totally different one...

-Kimmo

11.01.2013 17:35, [email protected] wrote:

def factorial(n):
if n<2:
return 1
f = 1
while n>= 2:
f *= n
f -= 1
return f




please it works.but don’t get why the return 1 and the code below.

factorial or n! = n*(n-1)*(n-2) for n > 1. For n = 0, 1 the 
factorial is 1 the reason for the 'return 1'.


f *= n <=> f = f* n
f -= 1 <=> f = f - 1 but sure this is not correct as Kimmo said n = n - 
1 or n -= 1


Regards
Karim
--
http://mail.python.org/mailman/listinfo/python-list


Re: Interpolating/crossfading a stack of matrices

2013-01-11 Thread raphael
>> Hi,
>>
>> I want to interpolate (with quadratic splines) a stack of 2D-arrays/matrices
>> y1, y2, y3, ... in a third dimension (which I call x) e.g. for crossfading 
>> images. I already have a working code which unfortunately still contains two 
>> explicit loops over the rows and colums of the matrices. Inside these loops 
>> I 
>> simply use 'interp1d' from scipy suitable for 1D-interpolations. Is anybody 
>> here aware of a better, more efficient solution of my problem? Maybe 
>> somewhere out there a compiled routine for my problem already exists in a 
>> python library... :-) 

> Since numpy arrays make it so easy to form linear combinations of
> arrays without loops I would probably eliminate the loops and just 
> form the appropriate combinations of the image arrays. For example, to 
> use linear interpolation you could do:
> 
> 
> 
> def interp_frames_linear(times, frames, t):
> 
> '''times is a vector of floats
> 
> frames is a 3D array whose nth page is the image for time t[n]
> 
> t is the time to interpolate for
> 
> '''
> 
> # Find the two frames to interpolate between
> 
> # Probably a better way of doing this
> 
> for n in range(len(t)-1):
> 
> if times[n] <= t < times[n+1]:
> 
> break
> 
> else:
> 
> raise OutOfBoundsError
> 
> 
> 
> # Interpolate between the two images
> 
> alpha = (t - times[n]) / (times[n+1] - times[n])
> 
> return (1 - alpha) * frames[:, :, n] + alpha * frames[:, :, n+1]
> 
> 
> 
> I'm not really sure how quadratic interpolation is supposed to work
> (I've only ever used linear and cubic) but you should be able to do
> the same sort of thing.
> 
> Oscar

Indeed, the 'manual' reimplementation of the interpolation formula using numpy 
arrays significantly sped up the code. The numexpr package made it even faster. 
Thanks a lot for your advice!

Raphael
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please i need explanation

2013-01-11 Thread Jussi Piitulainen
[email protected] writes:
> 11.01.2013 17:35, [email protected] wrote:
> > def factorial(n):
> >  if n<2:
> >   return 1
> >  f = 1
> >  while n>= 2:
> >  f *= n
> >  f -= 1
> >  return f
>
> please it works.but don’t get why the return 1 and the code below.

Ignoring the error that has been pointed out, this code seems to be
"optimized" to avoid multiplication by 1. I doubt if the difference is
measurable. If anyone cares enough to measure:

def fast_factorial(n):
   if n < 2: return 1
   f = 1
   while n > 1:
 f *= n
 n -= 1
   return f

def slow_factorial(n):
   f = 1
   while n != 0:
 f *= n
 n -= 1
   return f

(Untested, and just kidding. For fast factorial routines, search for a
paper by Richard Fateman on the web. They're in Common Lisp, but the
branching techniques should be generally applicable.)

Additionally, your code produces nonsense quietly when called with
(real) numbers outside its intended domain (negative integers and
non-integers are outside). Not a good idea. (My version will loop
indefinitely instead. Better than a wrong answer but also not very
good. Caller beware. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please i need explanation

2013-01-11 Thread Thomas Rachel

Am 11.01.2013 17:33 schrieb [email protected]:


def factorial(n):
 if n<2:
  return 1
 f = 1
 while n>= 2:
 f *= n
 f -= 1
 return f




please it works.


I doubt this.

If you give n = 4, you run into an endless loop.



but don’t get why the return 1 and the code below.


The "if n < 2: return 1" serves to shorten the calculation process 
below. It is redundant, as you have a "f = 1" and a "return f" for n < 2.


The code below first sets f, which holds the result, to 1 and then 
multiplies it by n in each step. As the loop should contain a 'n -= 1', 
n decreases by 1 every step, turning it into f = n * (n-1) * (n-2) * ... 
* 2 and then, as n is not >= 2 any longer, stops the loop, returning f.


HTH,

Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Import resolution order

2013-01-11 Thread Terry Reedy

On 1/11/2013 1:13 AM, Rick Johnson wrote:


Python's import resolution order is terrible.[1]

The fact that Python looks in the stdlib _first_ is not a good idea.


And the fact is that it does not do so. The order depends on sys.path, 
and '' is the first entry.



It would seem more intuitive for a custom "math" module (living in
the current directory) to /override/ the stlib "math" module.


Try it.

This is a nuisance though, when not intended. Someone writes a 
random.py, and a year later in the same directory, an unrelated 
hopscotch.py, which tries to import random.exponential. The import fails 
and they post here, having forgotten about their own random.py, which 
does not have such a function. Posts like this happen a few times a year.


--
Terry Jan Reedy

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


Re: pylint or similar to test version-specific language constructs?

2013-01-11 Thread Terry Reedy

On 1/11/2013 3:29 AM, The Night Tripper wrote:

Gisle Vanem wrote:


"jkn"  wrote:


I have to write python code which must run on an old version of
python (v2.4) as well as a newer (v2.7). I am using pylint and would
like to check if is possible to check with pylint the use of operators
etc. which are not present in 2.4; the ternary operator springs to
mind.


No idea about PyLint. Why not install Python 2.4 and test
with that? Sounds safer IMHO.


I do have Python 2.4 installed; but I would like a checker that warned me
beforehand about trying to use constructs (like the ternary operator,
decorators) which are version-specific.


Search each chapter of the reference manual (about 7) for 'version changed'.

--
Terry Jan Reedy

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


help

2013-01-11 Thread kwakukwatiah
pls this is a code to show the pay of two people.bt I want each of to be able 
to get a different money when they enter their user name,and to use it for 
about six people.
database = [
['Mac'],
['Sam'],
]
pay1 = 1000
pay2 = 2000

name = raw_input('Enter your name: ')
if [name] in database:print "your pay is $",pay-- 
http://mail.python.org/mailman/listinfo/python-list


Multiple disjoint sample sets?

2013-01-11 Thread Roy Smith
I have a list of items.  I need to generate n samples of k unique items 
each.  I not only want each sample set to have no repeats, but I also 
want to make sure the sets are disjoint (i.e. no item repeated between 
sets).

random.sample(items, k) will satisfy the first constraint, but not the 
second.  Should I just do random.sample(items, k*n), and then split the 
resulting big list into n pieces?  Or is there some more efficient way?

Typical values:

len(items) = 5,000,000
n = 10
k = 100,000
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help

2013-01-11 Thread Matt Jones
Pay isn't linked to the "people" in any way.  A dictionary would serve this
purpose better (at least in this simple example).

database = {
'Mac' : 1000,
'Sam' : 2000
}

name = raw_input('Enter your name:')
if name in database.keys(): print "your pay is $", database[name]

*Matt Jones*


On Thu, Jan 10, 2013 at 12:35 PM,  wrote:

>   pls this is a code to show the pay of two people.bt I want each of to
> be able to get a different money when they enter their user name,and to use
> it for about six people.
> database = [
> ['Mac'],
> ['Sam'],
> ]
> pay1 = 1000
> pay2 = 2000
>
> name = raw_input('Enter your name: ')
> if [name] in database:print "your pay is $",pay
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple disjoint sample sets?

2013-01-11 Thread MRAB

On 2013-01-11 14:15, Roy Smith wrote:

I have a list of items.  I need to generate n samples of k unique items
each.  I not only want each sample set to have no repeats, but I also
want to make sure the sets are disjoint (i.e. no item repeated between
sets).

random.sample(items, k) will satisfy the first constraint, but not the
second.  Should I just do random.sample(items, k*n), and then split the
resulting big list into n pieces?  Or is there some more efficient way?

Typical values:

len(items) = 5,000,000
n = 10
k = 100,000


I don't know how efficient it would be, but couldn't you shuffle the
list and then use slicing to get the samples?
--
http://mail.python.org/mailman/listinfo/python-list


Re: pylint or similar to test version-specific language constructs?

2013-01-11 Thread Dave Angel
On 01/11/2013 03:29 AM, The Night Tripper wrote:
> Gisle Vanem wrote:
>
>> "jkn"  wrote:
>>
>>>I have to write python code which must run on an old version of
>>> python (v2.4) as well as a newer (v2.7). I am using pylint and would
>>> like to check if is possible to check with pylint the use of operators
>>> etc. which are not present in 2.4; the ternary operator springs to
>>> mind.
>> No idea about PyLint. Why not install Python 2.4 and test
>> with that? Sounds safer IMHO.
> I do have Python 2.4 installed; but I would like a checker that warned me 
> beforehand about trying to use constructs (like the ternary operator, 
> decorators) which are version-specific.
>
> J^n
>

Not sure what you mean by beforehand.  Don't you run all your unit tests
before putting each revision of your code into production?  So run those
tests twice, once on 2.7, and once on 2.4.  A unit test that's testing
code with a ternary operator will fail, without any need for a separate
test.

if it doesn't, then you've got some coverage gaps in your unit tests.



-- 

DaveA

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


Re: Multiple disjoint sample sets?

2013-01-11 Thread Dave Angel
On 01/11/2013 09:36 AM, MRAB wrote:
> On 2013-01-11 14:15, Roy Smith wrote:
>> I have a list of items.  I need to generate n samples of k unique items
>> each.  I not only want each sample set to have no repeats, but I also
>> want to make sure the sets are disjoint (i.e. no item repeated between
>> sets).
>>
>> random.sample(items, k) will satisfy the first constraint, but not the
>> second.  Should I just do random.sample(items, k*n), and then split the
>> resulting big list into n pieces?  Or is there some more efficient way?
>>
>> Typical values:
>>
>> len(items) = 5,000,000
>> n = 10
>> k = 100,000
>>
> I don't know how efficient it would be, but couldn't you shuffle the
> list and then use slicing to get the samples?

I like that answer best, but just to offer another choice...

You start with a (presumably unique) list of items.  After collecting
your first sample, you could subtract them from the list, and use the
smaller list for the next sample.

One way is to convert list to set, subtract, then convert back to list.



-- 

DaveA

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


Re: pylint or similar to test version-specific language constructs?

2013-01-11 Thread Steven D'Aprano
On Fri, 11 Jan 2013 10:06:30 -0500, Dave Angel wrote:

> On 01/11/2013 03:29 AM, The Night Tripper wrote:
>> Gisle Vanem wrote:
>>
>>> "jkn"  wrote:
>>>
I have to write python code which must run on an old version of
 python (v2.4) as well as a newer (v2.7). I am using pylint and would
 like to check if is possible to check with pylint the use of
 operators etc. which are not present in 2.4; the ternary operator
 springs to mind.
>>> No idea about PyLint. Why not install Python 2.4 and test with that?
>>> Sounds safer IMHO.
>> I do have Python 2.4 installed; but I would like a checker that warned
>> me beforehand about trying to use constructs (like the ternary
>> operator, decorators) which are version-specific.

Decorators work fine in Python 2.4.


> Not sure what you mean by beforehand.  Don't you run all your unit tests
> before putting each revision of your code into production?  So run those
> tests twice, once on 2.7, and once on 2.4.  A unit test that's testing
> code with a ternary operator will fail, without any need for a separate
> test.

You don't even need tests for the code that includes the ternary 
operator. The module simply won't compile in Python 2.4, you get a 
SyntaxError when you try to import it or run it.

You don't need PyLint to check for *illegal syntax*. Python already does 
that.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Offtopic] Line fitting [was Re: Numpy outlier removal]

2013-01-11 Thread Alan Spence

On 09 Jan 2013, at 00:02:11 Steven D'Aprano  wrote:

> The point I keep making, that everybody seems to be ignoring, is that 
> eyeballing a line of best fit is subjective, unreliable and impossible to 
> verify. How could I check that the line you say is the "best fit" 
> actually *is* the *best fit* for the given data, given that you picked 
> that line by eye? Chances are good that if you came back to the data a 
> month later, you'd pick a different line!

It might bring more insight to the debate if you talk about parameter error and 
model error.  Steven is correct if you consider only parameter error.  However 
model error is often the main problem, and here using visual techniques might 
well improve your model selection even if it's not a real model but a visually 
based approximation to a model.  However, if you only do it by eye, you end up 
in a space which is not rigorous from a modelling perspective and other issues 
can arise from this.  Visual techniques might also help deal with outliers but 
again in an unrigorous manner.  Visual techniques can also bring in real world 
knowledge (but this is really the same point as model selection).

With regard to the original post on outliers, Steven made a lot of excellent 
points.  However there are at least two important issues which he didn't 
mention. (1) You must think carefully and hard about the outliers. For example, 
can they recur, or have actions in the real world been taken that mean they 
can't happen again?  Are they actually data errors?  How you deal with them 
might be changed by these types of consideration.  (2) It is best to fit your 
model with and without the outliers and see what impact it has on the real 
world application you're doing the analysis for.  It's also good to try more 
than one set of excluded outliers to see just how stable the results are 
depending on how many outliers you remove. If the results change much, be very 
careful how you use the results.

Alan

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


Re: PyWart: Module access syntax

2013-01-11 Thread Steven D'Aprano
On Thu, 10 Jan 2013 22:01:37 -0800, Rick Johnson wrote:

> Python's module/package access uses dot notation.
> 
>   mod1.mod2.mod3.modN
> 
> Like many warts of the language, this wart is not so apparent when first
> learning the language. The dot seems innocently sufficient, however, in
> truth it is woefully inadequate! Observe:
> 
>  name1.name2.name3.name4.name5
> 
> Can you tell me which names are modules, which are classes, and which
> are methods/functions? Wait, i know the argument you'll use:
> 
>   """I can decipher from spelling! Modules use all lowercase, classes
>   use initial uppercase, and methods use words_sep_by_underscore. I'm so
>   smart!"""

Wrong. My answer is... 

Who cares? Why do you care which names are modules, classes, etc? This is 
Python, and duck-typing rules!

Today I have:

x = mylib.stuff.spam().parrot.speak()

where:

- mylib is a module
- stuff is a separate module imported into mylib
- spam is a class
- parrot a data attribute
- and speak a method. 

But then tomorrow I re-factor the code and turn:

- mylib into a package
- stuff into a module of the package
- spam into a factory function
- parrot into a property
- and speak into a dynamically generated static method created using 
__getattr__.

How do I write this new code? Exactly the same as the old code -- no 
changes are required!

x = mylib.stuff.spam().parrot.speak()

*It doesn't matter* what kind of entity each of the dotted names 
represent, so long as they have the expected interface.


> The solution is obvious by using proper syntax.

Solution to what? You can only have a solution once you have identified a 
problem. You have not identified a problem. In any case, your suggestion 
is *not* obvious.

>  import lib:gui:tkinter:dialogs.SimpleDialog as Blah

Which names are packages, modules, classes, methods, functions, or other 
objects?

Why do you have lib:gui but dialogs.SimpleDialog? Is the rule "classes 
should always be preceded by a dot?"

Following this import:

import lib:gui

how do I access attributes of that module? 

x = lib:gui:function() perhaps? Now I have to remember which attribute 
access uses dot operator and which uses colon operator.

Does this mean there needs to four new be special methods:

__getcolonattribute__
__getcolonattr__
__setcolonattr__ 
__delcolonattr__ 

to match the regular dot operator methods

__getattribute__
__getattr__ 
__setattr__ 
__delattr__ 

? Or do you think that the Python compiler should special-case attribute 
access from modules?


> You /could/ use two colons:
>  
>  import lib::gui::tkinter::dialogs.SimpleDialog as Blah

Before thinking about the syntax, you need to think about the behaviour, 
identify what actual problem you hope to solve, and how you hope to solve 
it. Not just throw random syntax around and hope that it's "obvious".



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint or similar to test version-specific language constructs?

2013-01-11 Thread Dave Angel
On 01/11/2013 10:37 AM, Steven D'Aprano wrote:
> On Fri, 11 Jan 2013 10:06:30 -0500, Dave Angel wrote:
>
>> 
>
>> Not sure what you mean by beforehand.  Don't you run all your unit tests
>> before putting each revision of your code into production?  So run those
>> tests twice, once on 2.7, and once on 2.4.  A unit test that's testing
>> code with a ternary operator will fail, without any need for a separate
>> test.
> You don't even need tests for the code that includes the ternary 
> operator. The module simply won't compile in Python 2.4, you get a 
> SyntaxError when you try to import it or run it.
>
> You don't need PyLint to check for *illegal syntax*. Python already does 
> that.
>

You're right of course.  But I can weasel out of it by saying that
Python will only check it if the particular module is imported.  I've
seen equivalent bugs in real projects, where a release went out with one
of its dynamic libraries not even present.

Another thing that can stop Python from checking is if some naive
programmer uses a bare except in production code.

Both of these would show up in the simplest of unit testing code.



-- 

DaveA

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


Re: Probabilistic unit tests?

2013-01-11 Thread Alister
On Thu, 10 Jan 2013 17:59:05 -0800, Nick Mellor wrote:

> Hi,
> 
> I've got a unit test that will usually succeed but sometimes fails. An
> occasional failure is expected and fine. It's failing all the time I
> want to test for.
> 
> What I want to test is "on average, there are the same number of males
> and females in a sample, give or take 2%."
> 
> Here's the unit test code:
> import unittest from collections import counter
> 
> sex_count = Counter()
> for contact in range(self.binary_check_sample_size):
> p = get_record_as_dict()
> sex_count[p['Sex']] += 1
> self.assertAlmostEqual(sex_count['male'],
>sex_count['female'], delta=sample_size * 2.0 /
>100.0)
> 
> My question is: how would you run an identical test 5 times and pass the
> group *as a whole* if only one or two iterations passed the test?
> Something like:
> 
> for n in range(5):
> # self.assertAlmostEqual(...)
> # if test passed: break
> else:
> self.fail()
> 
> (except that would create 5+1 tests as written!)
> 
> Thanks for any thoughts,
> 
> Best wishes,
> 
> Nick

unit test are for testing your code, not checking if input data is in the 
correct range so unless you are writing a program intended to generate 
test data I don't see why unit test are appropriate in this case.





-- 
Under capitalism, man exploits man.  Under communism, it's just the 
opposite.
-- J.K. Galbraith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Probabilistic unit tests?

2013-01-11 Thread Steven D'Aprano
On Fri, 11 Jan 2013 16:26:20 +, Alister wrote:

> On Thu, 10 Jan 2013 17:59:05 -0800, Nick Mellor wrote:
> 
>> Hi,
>> 
>> I've got a unit test that will usually succeed but sometimes fails. An
>> occasional failure is expected and fine. It's failing all the time I
>> want to test for.
>> 
>> What I want to test is "on average, there are the same number of males
>> and females in a sample, give or take 2%."
[...]

> unit test are for testing your code, not checking if input data is in
> the correct range so unless you are writing a program intended to
> generate test data I don't see why unit test are appropriate in this
> case.

I don't believe Nick is using unittest to check input data. As I 
understand it, Nick has a program which generates random values. If his 
program works correctly, it should generate approximately equal numbers 
of "male" and "female" values. So he writes a unit test to check that the 
numbers are roughly equal.

This is an appropriate test, although as I already suggested earlier, 
unit tests are not well suited for non-deterministic testing.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Import resolution order

2013-01-11 Thread Michael Torrie
On 01/10/2013 11:13 PM, Rick Johnson wrote:
> 
> Python's import resolution order is terrible.[1]
> 
> The fact that Python looks in the stdlib _first_ is not a good idea.

Whether or not the default behavior is desirable or not, sys.path is set
by default to look in the current directory first on any Python
distribution I have looked at.  As Terry says, this fact causes a lot of
problems for newbies who accidentally override standard library modules
with their own python files and chaos ensues.

If your python installation does not search the current directory first,
then you must have changed sys.path.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Probabilistic unit tests?

2013-01-11 Thread duncan smith

On 11/01/13 01:59, Nick Mellor wrote:

Hi,

I've got a unit test that will usually succeed but sometimes fails. An 
occasional failure is expected and fine. It's failing all the time I want to 
test for.

What I want to test is "on average, there are the same number of males and females 
in a sample, give or take 2%."

Here's the unit test code:
import unittest
from collections import counter

sex_count = Counter()
for contact in range(self.binary_check_sample_size):
 p = get_record_as_dict()
 sex_count[p['Sex']] += 1
self.assertAlmostEqual(sex_count['male'],
sex_count['female'],
delta=sample_size * 2.0 / 100.0)

My question is: how would you run an identical test 5 times and pass the group 
*as a whole* if only one or two iterations passed the test? Something like:

 for n in range(5):
 # self.assertAlmostEqual(...)
 # if test passed: break
 else:
 self.fail()

(except that would create 5+1 tests as written!)

Thanks for any thoughts,

Best wishes,

Nick



The appropriateness of "give or take 2%" will depend on sample size. 
e.g. If the proportion of males should be 0.5 and your sample size is 
small enough this will fail most of the time regardless of whether the 
proportion is 0.5.


What you could do is perform a statistical test. Generally this involves 
generating a p-value and rejecting the null hypothesis if the p-value is 
below some chosen threshold (Type I error rate), often taken to be 0.05. 
Here the null hypothesis would be that the underlying proportion of 
males is 0.5.


A statistical test will incorrectly reject a true null in a proportion 
of cases equal to the chosen Type I error rate. A test will also fail to 
reject false nulls a certain proportion of the time (the Type II error 
rate). The Type II error rate can be reduced by using larger samples. I 
prefer to generate several samples and test whether the proportion of 
failures is about equal to the error rate.


The above implies that p-values follow a [0,1] uniform density function 
if the null hypothesis is true. So alternatively you could generate many 
samples / p-values and test the p-values for uniformity. That is what I 
generally do:



p_values = []
for _ in range(numtests):
values = data generated from code to be tested
p_values.append(stat_test(values))
test p_values for uniformity


The result is still a test that will fail a given proportion of the 
time. You just have to live with that. Run your test suite several times 
and check that no one test is "failing" too regularly (more often than 
the chosen Type I error rate for the test of uniformity). My experience 
is that any issues generally result in the test of uniformity being 
consistently rejected (which is why a do that rather than just 
performing a single test on a single generated data set).


In your case you're testing a Binomial proportion and as long as you're 
generating enough data (you need to take into account any test 
assumptions / approximations) the observed proportions will be 
approximately normally distributed. Samples of e.g. 100 would be fine. 
P-values can be generated from the appropriate normal 
(http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval), 
and uniformity can be tested using e.g. the Kolmogorov-Smirnov or 
Anderson-Darling test 
(http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm).


I'd have thought that something like this also exists somewhere. How do 
people usually test e.g. functions that generate random variates, or 
other cases where deterministic tests don't cut it?


Duncan
--
http://mail.python.org/mailman/listinfo/python-list


Re: help

2013-01-11 Thread Mitya Sirenef

On 01/11/2013 09:24 AM, Matt Jones wrote:
Pay isn't linked to the "people" in any way.  A dictionary would serve 
this purpose better (at least in this simple example).


database = {
'Mac' : 1000,
'Sam' : 2000
}

name = raw_input('Enter your name:')
if name in database.keys(): print "your pay is $", database[name]



This can be simplified a bit as:

database = dict(Mac=1000, Sam=2000)
name = raw_input('Enter your name: ')
if name in database:
  print "your pay is $", database[name]



 -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


ANN: Python Meeting Düsseldorf - 22.01.2013 (Erinnerung/Reminder)

2013-01-11 Thread eGenix Team: M.-A. Lemburg
[This announcement is in German since it targets a local user group
 meeting in Düsseldorf, Germany]


ANKÜNDIGUNG / ERINNERUNG

 Python Meeting Düsseldorf

 http://pyddf.de/

   Ein Treffen von Python Enthusiasten und Interessierten
in ungezwungener Atmosphäre.

  Dienstag, 22.01.2013, 18:00 Uhr
Clara Schumann Raum
  DJH Düsseldorf


Diese Nachricht können Sie auch online lesen:
http://www.egenix.com/company/news/Python-Meeting-Duesseldorf-2013-01-22


EINLEITUNG

Das Python Meeting Düsseldorf (http://pyddf.de/) ist eine neue
lokale Veranstaltung in Düsseldorf, die sich an Python Begeisterte
in der Region wendet.

Wir starten bei den Treffen mit einer kurzen Einleitung und gehen
dann zu einer Reihe Kurzvorträgen (Lightning Talks) über, bei denen
die Anwesenden über neue Projekte, interessante Probleme und
sonstige Aktivitäten rund um Python berichten können.

Anschließend geht es in eine Gaststätte, um die Gespräche zu
vertiefen.

Einen guten Überblick über die Vorträge bietet unser YouTube-Kanal,
auf dem wir die Vorträge nach den Meetings veröffentlichen:

   http://www.youtube.com/pyddf/

Daneben haben wir auch eine Mailing Liste für Python-
Interessierte aus dem Ruhrgebiet und Meeting-Teilnehmer:

   https://www.egenix.com/mailman/listinfo/pyddf

Für Ankündigungen gibt es zusätzlich folgende Kanäle:

   Twitter: https://twitter.com/pyddf
   Facebook Seite: https://www.facebook.com/PythonMeetingDusseldorf
   Facebook Gruppe: https://www.facebook.com/groups/397118706993326/

Veranstaltet wird das Meeting von der eGenix.com GmbH, Langenfeld,
in Zusammenarbeit mit Clark Consulting & Research, Düsseldorf:

 * http://www.egenix.com/
 * http://www.clark-consulting.eu/


ORT

Für das Python Meeting Düsseldorf haben wir den Clara Schumann
Raum in der modernen Jugendherberge Düsseldorf angemietet:

Jugendherberge Düsseldorf
Düsseldorfer Str. 1
40545 Düsseldorf
Telefon: +49 211 557310
http://www.duesseldorf.jugendherberge.de

Die Jugendherberge verfügt über eine kostenpflichtige Tiefgarage (EUR
2,50 pro Stunde, maximal EUR 10,00). Es ist aber auch möglich per
Bus und Bahn anzureisen. Der Raum befindet sich im 1.OG links.


PROGRAMM

Das Python Meeting Düsseldorf nutzt eine Mischung aus Open Space
und Lightning Talks:

Die Treffen starten mit einer kurzen Einleitung. Danach geht es
weiter mit einer Lightning Talk Session, in der die Anwesenden
Kurzvorträge von fünf Minuten halten können.

Hieraus ergeben sich dann meisten viele Ansatzpunkte für
Diskussionen, die dann den Rest der verfügbaren Zeit in Anspruch
nehmen können.

Für 19:45 Uhr haben wir in einem nahegelegenen Restaurant Plätze
reserviert, damit auch das leibliche Wohl nicht zu kurz kommt.

Lightning Talks können vorher angemeldet werden, oder auch
spontan während des Treffens eingebracht werden. Ein Beamer mit
XGA Auflösung steht zur Verfügung. Folien bitte als PDF auf USB
Stick mitbringen.

Lightning Talk Anmeldung bitte formlos per EMail an [email protected]


KOSTENBETEILIGUNG

Das Python Meeting Düsseldorf wird von Python Nutzern für Python
Nutzer veranstaltet.

Da Tagungsraum, Beamer, Internet und Getränke Kosten produzieren,
bitten wir die Teilnehmer um einen Beitrag in Höhe von EUR 10,00
inkl. 19% Mwst.

Wir möchten alle Teilnehmer bitten, den Betrag in bar mitzubringen.


ANMELDUNG

Da wir nur für ca. 20 Personen Sitzplätze haben, möchten wir
bitten, sich per EMail anzumelden. Damit wird keine Verpflichtung
eingegangen. Es erleichtert uns allerdings die Planung.

Meeting Anmeldung bitte formlos per EMail an [email protected]


WEITERE INFORMATIONEN

Weitere Informationen finden Sie auf der Webseite des Meetings:

http://pyddf.de/

Mit freundlichen Grüßen,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Dec 28 2012)
>>> Python Projects, Consulting and Support ...   http://www.egenix.com/
>>> mxODBC.Zope/Plone.Database.Adapter ...   http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2013-01-22: Python Meeting Duesseldorf ... 25 days to go

: Try our mxODBC.Connect Python Database Interface for free ! ::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lembur

String concatenation benchmarking weirdness

2013-01-11 Thread Rotwang

Hi all,

the other day I 2to3'ed some code and found it ran much slower in 3.3.0 
than 2.7.2. I fixed the problem but in the process of trying to diagnose 
it I've stumbled upon something weird that I hope someone here can 
explain to me. In what follows I'm using Python 2.7.2 on 64-bit Windows 
7. Suppose I do this:


from timeit import timeit

# find out how the time taken to append a character to the end of a byte
# string depends on the size of the string

results = []
for size in range(0, 1001, 10):
results.append(timeit("y = x + 'a'",
setup = "x = 'a' * %i" % size, number = 1))

If I plot results against size, what I see is that the time taken 
increases approximately linearly with the size of the string, with the 
string of length 1000 taking about 4 milliseconds. On the other 
hand, if I replace the statement to be timed with "x = x + 'a'" instead 
of "y = x + 'a'", the time taken seems to be pretty much independent of 
size, apart from a few spikes; the string of length 1000 takes about 
4 microseconds.


I get similar results with strings (but not bytes) in 3.3.0. My guess is 
that this is some kind of optimisation that treats strings as mutable 
when carrying out operations that result in the original string being 
discarded. If so it's jolly clever, since it knows when there are other 
references to the same string:


timeit("x = x + 'a'", setup = "x = y = 'a' * %i" % size, number = 1)
# grows linearly with size

timeit("x = x + 'a'", setup = "x, y = 'a' * %i", 'a' * %i"
% (size, size), number = 1)
# stays approximately constant

It also can see through some attempts to fool it:

timeit("x = ('' + x) + 'a'", setup = "x = 'a' * %i" % size, number = 1)
# stays approximately constant

timeit("x = x*1 + 'a'", setup = "x = 'a' * %i" % size, number = 1)
# stays approximately constant

Is my guess correct? If not, what is going on? If so, is it possible to 
explain to a programming noob how the interpreter does this? And is 
there a reason why it doesn't work with bytes in 3.3?



--
I have made a thing that superficially resembles music:

http://soundcloud.com/eroneity/we-berated-our-own-crapiness
--
http://mail.python.org/mailman/listinfo/python-list


Move modules to submodules question

2013-01-11 Thread joshua . kimball
I have a set of utility modules that were all added to a folder called 
(util_mods). Recently the set of modules grew to be too large and I've been 
working on splitting it up into sets of sub modules, for example, 
util_mods\set_a. The issue is that if I start moving modules to sub folders I 
have to go through and update literally thousands of scripts that import the 
module from util_mods. I was wondering if there was a way to move these modules 
into submodules while still maintaining the imports. For example "import 
util_mods.moda " would actually import as "util_mods.set_a.moda".

My longterm goal is to update the scripts to point to the correct 
submodule/module however I was hoping for a short term solution to this so I 
can make the change immediately and update the other scripts over time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please i need explanation

2013-01-11 Thread Steve Simmons
I read the question as "I've got this function and it does what I expect 
but I don't understand the code".

On that basis...

The function creates a factorialfor the input number 'n' (i.e. 
1*2*3*4.*n)


The first 2 lines checks to see that the input is less than 2 and, if 
so, returns a value of 1
The rest of the code counts down from n to 1 multiplying f by n at each 
iteration.


If I guessed the right question, reply to the post for further 
clarification.


Steve

On 11/01/2013 16:33, [email protected] wrote:



-Original Message- From: K. Elo
Sent: Friday, January 11, 2013 3:56 AM
To: [email protected]
Subject: Re: please i need explanation

Hi!

Since there is no stated question, I need to guess:

n -= 1 (instead of "f -= 1")

should work.

Or maybe the question was a totally different one...

-Kimmo

11.01.2013 17:35, [email protected] wrote:

def factorial(n):
 if n<2:
  return 1
 f = 1
 while n>= 2:
 f *= n
 f -= 1
 return f




please it works.but don’t get why the return 1 and the code below.



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


Re: How to call ltm function using rpy package in python

2013-01-11 Thread Piet van Oostrum
Mohit Khanna  writes:

> I am trying the following code--
>
> from rpy import *
> r.library("ltm")
>
> dat= #some data frame or matrix
> r.ltm(r('dat~z1'))
>
> error coming is---
> RPy_RException: Error in eval(expr, envir, enclos) : object 'dat' not found
>
> Please tell me the right way to call ltm function using rpy library

Your problem is that the 'dat' object is in the Python world but not in
the R world. However, the expression r('dat~z1') is looking for a 'dat'
object in the R world. So you must copy the Python object to the R
world.

I don't know if this will work in rpy, but it does work in rpy2. Rpy2
has much better possibilities than rpy. But just try it:

r['=']('dat', dat)
r.ltm(r('dat~z1'))
-- 
Piet van Oostrum 
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String concatenation benchmarking weirdness

2013-01-11 Thread Ian Kelly
On Fri, Jan 11, 2013 at 12:03 PM, Rotwang  wrote:
> Hi all,
>
> the other day I 2to3'ed some code and found it ran much slower in 3.3.0 than
> 2.7.2. I fixed the problem but in the process of trying to diagnose it I've
> stumbled upon something weird that I hope someone here can explain to me. In
> what follows I'm using Python 2.7.2 on 64-bit Windows 7. Suppose I do this:
>
> from timeit import timeit
>
> # find out how the time taken to append a character to the end of a byte
> # string depends on the size of the string
>
> results = []
> for size in range(0, 1001, 10):
> results.append(timeit("y = x + 'a'",
> setup = "x = 'a' * %i" % size, number = 1))
>
> If I plot results against size, what I see is that the time taken increases
> approximately linearly with the size of the string, with the string of
> length 1000 taking about 4 milliseconds. On the other hand, if I replace
> the statement to be timed with "x = x + 'a'" instead of "y = x + 'a'", the
> time taken seems to be pretty much independent of size, apart from a few
> spikes; the string of length 1000 takes about 4 microseconds.
>
> I get similar results with strings (but not bytes) in 3.3.0. My guess is
> that this is some kind of optimisation that treats strings as mutable when
> carrying out operations that result in the original string being discarded.
> If so it's jolly clever, since it knows when there are other references to
> the same string:
>
> timeit("x = x + 'a'", setup = "x = y = 'a' * %i" % size, number = 1)
> # grows linearly with size
>
> timeit("x = x + 'a'", setup = "x, y = 'a' * %i", 'a' * %i"
> % (size, size), number = 1)
> # stays approximately constant
>
> It also can see through some attempts to fool it:
>
> timeit("x = ('' + x) + 'a'", setup = "x = 'a' * %i" % size, number = 1)
> # stays approximately constant
>
> timeit("x = x*1 + 'a'", setup = "x = 'a' * %i" % size, number = 1)
> # stays approximately constant
>
> Is my guess correct? If not, what is going on? If so, is it possible to
> explain to a programming noob how the interpreter does this?

Basically, yes.  You can find the discussion behind that optimization at:

http://bugs.python.org/issue980695

It knows when there are other references to the string because all
objects in CPython are reference-counted.  It also works despite your
attempts to "fool" it because after evaluating the first operation
(which is easily optimized to return the string itself in both cases),
the remaining part of the expression is essentially "x = TOS + 'a'",
where x and the top of the stack are the same string object, which is
the same state the original code reaches after evaluating just the x.

The stated use case for this optimization is to make repeated
concatenation more efficient, but note that it is still generally
preferable to use the ''.join() construct, because the optimization is
specific to CPython and may not exist for other Python
implementations.

> And is there a reason why it doesn't work with bytes in 3.3?

No idea. Probably just never got implemented due to a lack of demand.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Move modules to submodules question

2013-01-11 Thread Peter Otten
[email protected] wrote:

> I have a set of utility modules that were all added to a folder called
> (util_mods). Recently the set of modules grew to be too large and I've
> been working on splitting it up into sets of sub modules, for example,
> util_mods\set_a. The issue is that if I start moving modules to sub
> folders I have to go through and update literally thousands of scripts
> that import the module from util_mods. I was wondering if there was a way
> to move these modules into submodules while still maintaining the imports.
> For example "import util_mods.moda " would actually import as
> "util_mods.set_a.moda".
> 
> My longterm goal is to update the scripts to point to the correct
> submodule/module however I was hoping for a short term solution to this so
> I can make the change immediately and update the other scripts over time.

Put

from .set_a import moda

into util_mods/__init__.py

Alternatively create an additional

util_mods/moda.py

containing nothing but

from .set_a.moda import *

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


Re: String concatenation benchmarking weirdness

2013-01-11 Thread Rotwang

On 11/01/2013 20:16, Ian Kelly wrote:

On Fri, Jan 11, 2013 at 12:03 PM, Rotwang  wrote:

Hi all,

the other day I 2to3'ed some code and found it ran much slower in 3.3.0 than
2.7.2. I fixed the problem but in the process of trying to diagnose it I've
stumbled upon something weird that I hope someone here can explain to me.

[stuff about timings]

Is my guess correct? If not, what is going on? If so, is it possible to
explain to a programming noob how the interpreter does this?


Basically, yes.  You can find the discussion behind that optimization at:

http://bugs.python.org/issue980695

It knows when there are other references to the string because all
objects in CPython are reference-counted.  It also works despite your
attempts to "fool" it because after evaluating the first operation
(which is easily optimized to return the string itself in both cases),
the remaining part of the expression is essentially "x = TOS + 'a'",
where x and the top of the stack are the same string object, which is
the same state the original code reaches after evaluating just the x.


Nice, thanks.



The stated use case for this optimization is to make repeated
concatenation more efficient, but note that it is still generally
preferable to use the ''.join() construct, because the optimization is
specific to CPython and may not exist for other Python
implementations.


The slowdown in my code was caused by a method that built up a string of 
bytes by repeatedly using +=, before writing the result to a WAV file. 
My fix was to replaced the bytes string with a bytearray, which seems 
about as fast as the rewrite I just tried with b''.join. Do you know 
whether the bytearray method will still be fast on other implementations?



--
I have made a thing that superficially resembles music:

http://soundcloud.com/eroneity/we-berated-our-own-crapiness
--
http://mail.python.org/mailman/listinfo/python-list


Problem with importing in Python

2013-01-11 Thread su29090
I'm trying to import a python file it keeps saying:

ImportError: cannot import name Circle

Here is the file I'm trying to import:

Circle.py

import math

class circle:
#Construct a circle object
def __init__(self, radius = 1):
self.radius = radius

def getPerimeter(self):
return 2 * self.radius * math.pi

def getArea(self):
return self.radius * self.radius * math.pi

def setRadius(self, radius):
self.radius = radius

from Circle import Circle

def main():
#Create a circle with a radius 1
circle1 = Circle()
print("The area of the circle of radius",
  circle1.radius, "is" , circle1.getArea())

#Create a circle with a radius 25
circle2 = Circle(25)
print("The area of the circle of radius",
  circle2.radius, "is" , circle2.getArea())

#Create a circle with a radius 125
circle3 = Circle(125)
print("The area of the circle of radius",
  circle3.radius, "is" , circle3.getArea())

#Modify circle radius 
circle2.radius = 100 # or Circle2.setRadius(100)
print("The area of the circle of radius",
  circle2.radius, "is" , circle2.getArea())

main() # Call the main function

How can I solve this problem?

Thanks in advance.

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


Re: Problem with importing in Python

2013-01-11 Thread Adnan Sadzak
Python is case sensitive.
Circle and circle is not same.




/* sent from android */
On Jan 11, 2013 11:22 PM, "su29090" <[email protected]> wrote:

> I'm trying to import a python file it keeps saying:
>
> ImportError: cannot import name Circle
>
> Here is the file I'm trying to import:
>
> Circle.py
>
> import math
>
> class circle:
> #Construct a circle object
> def __init__(self, radius = 1):
> self.radius = radius
>
> def getPerimeter(self):
> return 2 * self.radius * math.pi
>
> def getArea(self):
> return self.radius * self.radius * math.pi
>
> def setRadius(self, radius):
> self.radius = radius
>
> from Circle import Circle
>
> def main():
> #Create a circle with a radius 1
> circle1 = Circle()
> print("The area of the circle of radius",
>   circle1.radius, "is" , circle1.getArea())
>
> #Create a circle with a radius 25
> circle2 = Circle(25)
> print("The area of the circle of radius",
>   circle2.radius, "is" , circle2.getArea())
>
> #Create a circle with a radius 125
> circle3 = Circle(125)
> print("The area of the circle of radius",
>   circle3.radius, "is" , circle3.getArea())
>
> #Modify circle radius
> circle2.radius = 100 # or Circle2.setRadius(100)
> print("The area of the circle of radius",
>   circle2.radius, "is" , circle2.getArea())
>
> main() # Call the main function
>
> How can I solve this problem?
>
> Thanks in advance.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Dependency management in Python?

2013-01-11 Thread Adelbert Chang
Hi all,

I've been using Python for a while now but one of my concerns is if it is 
possible to have some sort of dependency management (not sure if right term) 
for Python? 

In the Scala language there is the Simple Build Tool that lets me specify on a 
project-by-project basis which libraries I want to use (provided they are in a 
central repository somewhere) and it will download them for me. Better yet, 
when a new version comes out I need only change the SBT configuration file for 
that project and it will download it for me.

Is there something like this for Python. I am typically wary of downloading 
Python modules I use like NumPy, SciPy, NetworkX, etc because I want to be able 
to upgrade at any time and doing so seems to be a hassle - in fact, I am not 
entirely sure how to "upgrade".

Thank you and regards,
-Adelbert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread Chris Angelico
On Sat, Jan 12, 2013 at 9:17 AM, su29090 <[email protected]> wrote:
> Circle.py
>
> class circle:
>
> from Circle import Circle

Inside the Circle module is a class named circle. You can't import
Circle from that.

But Python isn't Java. You don't have to put each class into its own
file. Just put class circle (or class Circle to follow Python naming
convention) into the other file, whose name you haven't given.

If they're already in the same file, then just drop the import. Easy!

By the way:
>main() # Call the main function
You'll need to put that flush left. At the moment, that call is part
of the definition of main().

Hope that helps!

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dependency management in Python?

2013-01-11 Thread Rodrick Brown
On Fri, Jan 11, 2013 at 5:23 PM, Adelbert Chang  wrote:

> Hi all,
>
> I've been using Python for a while now but one of my concerns is if it is
> possible to have some sort of dependency management (not sure if right
> term) for Python?
>
> In the Scala language there is the Simple Build Tool that lets me specify
> on a project-by-project basis which libraries I want to use (provided they
> are in a central repository somewhere) and it will download them for me.
> Better yet, when a new version comes out I need only change the SBT
> configuration file for that project and it will download it for me.
>
> Is there something like this for Python. I am typically wary of
> downloading Python modules I use like NumPy, SciPy, NetworkX, etc because I
> want to be able to upgrade at any time and doing so seems to be a hassle -
> in fact, I am not entirely sure how to "upgrade".
>
>
Checkout PIP/setuptools and virtualenv



> Thank you and regards,
> -Adelbert
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread su29090
On Friday, January 11, 2013 5:25:24 PM UTC-5, Adnan Sadzak wrote:
> Python is case sensitive.
> 
> Circle and circle is not same.
> 
> 
> 
> 
> 
> 
> /* sent from android */
> 
> On Jan 11, 2013 11:22 PM, "su29090" <[email protected]> wrote:
> 
> I'm trying to import a python file it keeps saying:
> 
> 
> 
> ImportError: cannot import name Circle
> 
> 
> 
> Here is the file I'm trying to import:
> 
> 
> 
> Circle.py
> 
> 
> 
> import math
> 
> 
> 
> class circle:
> 
>     #Construct a circle object
> 
>     def __init__(self, radius = 1):
> 
>         self.radius = radius
> 
> 
> 
>     def getPerimeter(self):
> 
>         return 2 * self.radius * math.pi
> 
> 
> 
>     def getArea(self):
> 
>         return self.radius * self.radius * math.pi
> 
> 
> 
>     def setRadius(self, radius):
> 
>         self.radius = radius
> 
> 
> 
> from Circle import Circle
> 
> 
> 
> def main():
> 
>     #Create a circle with a radius 1
> 
>     circle1 = Circle()
> 
>     print("The area of the circle of radius",
> 
>           circle1.radius, "is" , circle1.getArea())
> 
> 
> 
>     #Create a circle with a radius 25
> 
>     circle2 = Circle(25)
> 
>     print("The area of the circle of radius",
> 
>           circle2.radius, "is" , circle2.getArea())
> 
> 
> 
>     #Create a circle with a radius 125
> 
>     circle3 = Circle(125)
> 
>     print("The area of the circle of radius",
> 
>           circle3.radius, "is" , circle3.getArea())
> 
> 
> 
>     #Modify circle radius
> 
>     circle2.radius = 100 # or Circle2.setRadius(100)
> 
>     print("The area of the circle of radius",
> 
>           circle2.radius, "is" , circle2.getArea())
> 
> 
> 
>     main() # Call the main function
> 
> 
> 
> How can I solve this problem?
> 
> 
> 
> Thanks in advance.
> 
> 
> 
> --
> 
> http://mail.python.org/mailman/listinfo/python-list

It still keeps showing the same message.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread su29090
On Friday, January 11, 2013 5:27:21 PM UTC-5, Chris Angelico wrote:
> On Sat, Jan 12, 2013 at 9:17 AM, su29090  wrote:
> 
> > Circle.py
> 
> >
> 
> > class circle:
> 
> >
> 
> > from Circle import Circle
> 
> 
> 
> Inside the Circle module is a class named circle. You can't import
> 
> Circle from that.
> 
> 
> 
> But Python isn't Java. You don't have to put each class into its own
> 
> file. Just put class circle (or class Circle to follow Python naming
> 
> convention) into the other file, whose name you haven't given.
> 
> 
> 
> If they're already in the same file, then just drop the import. Easy!
> 
> 
> 
> By the way:
> 
> >main() # Call the main function
> 
> You'll need to put that flush left. At the moment, that call is part
> 
> of the definition of main().
> 
> 
> 
> Hope that helps!
> 
> 
> 
> ChrisA

 It worked! Thanks so much! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread Dave Angel
On 01/11/2013 05:17 PM, su29090 wrote:
> I'm trying to import a python file it keeps saying:
>
> ImportError: cannot import name Circle
>
> Here is the file I'm trying to import:
>
> Circle.py
>
> import math
>
> class circle:
> #Construct a circle object
> def __init__(self, radius = 1):
> self.radius = radius
>
> def getPerimeter(self):
> return 2 * self.radius * math.pi
>
> def getArea(self):
> return self.radius * self.radius * math.pi
>
> def setRadius(self, radius):
> self.radius = radius
>
> from Circle import Circle
>
> def main():
> #Create a circle with a radius 1
> circle1 = Circle()
> print("The area of the circle of radius",
>   circle1.radius, "is" , circle1.getArea())
>
> #Create a circle with a radius 25
> circle2 = Circle(25)
> print("The area of the circle of radius",
>   circle2.radius, "is" , circle2.getArea())
>
> #Create a circle with a radius 125
> circle3 = Circle(125)
> print("The area of the circle of radius",
>   circle3.radius, "is" , circle3.getArea())
>
> #Modify circle radius 
> circle2.radius = 100 # or Circle2.setRadius(100)
> print("The area of the circle of radius",
>   circle2.radius, "is" , circle2.getArea())
>
> main() # Call the main function
>
> How can I solve this problem?
>
> Thanks in advance.
>

As Adnan has pointed out, Python is case insensitive.  You're apparently
trying to refer to the class Circle by the name circle, or the other way
around.

Some comments on asking clear questions:

1) Specify the Python version.  I presume 3.3It probably doesn't
matter here, but it might have.
2) When showing two source files, identify where each starts and ends,
and what the second one is called.
3) When showing an error, include the entire traceback, not just the
last line.

Now, there are conventions to follow as well (see Pep8).  One is that
modules should use all lowercase, and classes should begin with a
capital.  So the source file of your module should be named  
circle.py   and the class  Circle.  When you imported and instantiated
the class, you assumed it was called Circle, but when you defined it,
you mistakenly called it circle.

The next error is the accidental indentation of the call to main().  As
it stands now, it's a recursive call to itself.  And main() will never
be called, because there's no call at top-level.





-- 

DaveA

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


Re: Dependency management in Python?

2013-01-11 Thread Ian Foote

On 11/01/13 22:34, Rodrick Brown wrote:

On Fri, Jan 11, 2013 at 5:23 PM, Adelbert Chang mailto:[email protected]>> wrote:

Hi all,

I've been using Python for a while now but one of my concerns is if
it is possible to have some sort of dependency management (not sure
if right term) for Python?

In the Scala language there is the Simple Build Tool that lets me
specify on a project-by-project basis which libraries I want to use
(provided they are in a central repository somewhere) and it will
download them for me. Better yet, when a new version comes out I
need only change the SBT configuration file for that project and it
will download it for me.

Is there something like this for Python. I am typically wary of
downloading Python modules I use like NumPy, SciPy, NetworkX, etc
because I want to be able to upgrade at any time and doing so seems
to be a hassle - in fact, I am not entirely sure how to "upgrade".


Checkout PIP/setuptools and virtualenv

Thank you and regards,
-Adelbert
--
http://mail.python.org/mailman/listinfo/python-list



pip and virtualenv is a great combination. I also like to use 
virtualenvwrapper for convenience, but it isn't necessary.


Ian F
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread su29090
On Friday, January 11, 2013 5:43:10 PM UTC-5, Dave Angel wrote:
> On 01/11/2013 05:17 PM, su29090 wrote:
> 
> > I'm trying to import a python file it keeps saying:
> 
> >
> 
> > ImportError: cannot import name Circle
> 
> >
> 
> > Here is the file I'm trying to import:
> 
> >
> 
> > Circle.py
> 
> >
> 
> > import math
> 
> >
> 
> > class circle:
> 
> > #Construct a circle object
> 
> > def __init__(self, radius = 1):
> 
> > self.radius = radius
> 
> >
> 
> > def getPerimeter(self):
> 
> > return 2 * self.radius * math.pi
> 
> >
> 
> > def getArea(self):
> 
> > return self.radius * self.radius * math.pi
> 
> >
> 
> > def setRadius(self, radius):
> 
> > self.radius = radius
> 
> >
> 
> > from Circle import Circle
> 
> >
> 
> > def main():
> 
> > #Create a circle with a radius 1
> 
> > circle1 = Circle()
> 
> > print("The area of the circle of radius",
> 
> >   circle1.radius, "is" , circle1.getArea())
> 
> >
> 
> > #Create a circle with a radius 25
> 
> > circle2 = Circle(25)
> 
> > print("The area of the circle of radius",
> 
> >   circle2.radius, "is" , circle2.getArea())
> 
> >
> 
> > #Create a circle with a radius 125
> 
> > circle3 = Circle(125)
> 
> > print("The area of the circle of radius",
> 
> >   circle3.radius, "is" , circle3.getArea())
> 
> >
> 
> > #Modify circle radius 
> 
> > circle2.radius = 100 # or Circle2.setRadius(100)
> 
> > print("The area of the circle of radius",
> 
> >   circle2.radius, "is" , circle2.getArea())
> 
> >
> 
> > main() # Call the main function
> 
> >
> 
> > How can I solve this problem?
> 
> >
> 
> > Thanks in advance.
> 
> >
> 
> 
> 
> As Adnan has pointed out, Python is case insensitive.  You're apparently
> 
> trying to refer to the class Circle by the name circle, or the other way
> 
> around.
> 
> 
> 
> Some comments on asking clear questions:
> 
> 
> 
> 1) Specify the Python version.  I presume 3.3It probably doesn't
> 
> matter here, but it might have.
> 
> 2) When showing two source files, identify where each starts and ends,
> 
> and what the second one is called.
> 
> 3) When showing an error, include the entire traceback, not just the
> 
> last line.
> 
> 
> 
> Now, there are conventions to follow as well (see Pep8).  One is that
> 
> modules should use all lowercase, and classes should begin with a
> 
> capital.  So the source file of your module should be named  
> 
> circle.py   and the class  Circle.  When you imported and instantiated
> 
> the class, you assumed it was called Circle, but when you defined it,
> 
> you mistakenly called it circle.
> 
> 
> 
> The next error is the accidental indentation of the call to main().  As
> 
> it stands now, it's a recursive call to itself.  And main() will never
> 
> be called, because there's no call at top-level.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> 
> 
> DaveA

Thanks for explanation which was very clear! 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help

2013-01-11 Thread Hans Mulder
On 10/01/13 19:35:40, [email protected] wrote:
> pls this is a code to show the pay of two people.bt I want each of to be
> able to get a different money when they enter their user name,and to use
> it for about six people.
> database = [
> ['Mac'],
> ['Sam'],
> ]
> pay1 = 1000
> pay2 = 2000
>  
> name = raw_input('Enter your name: ')
> if [name] in database:print "your pay is $",pay

How about:

database = dict(Mac=1000, Sam=2000, Eric=3000, Terry=4000, Graham=5000)

name = raw_input('Enter your name: ')
if name in database: print "Your pay is ${}".format(database[name])


Hope this helps,

-- HansM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please i need explanation

2013-01-11 Thread Hans Mulder
On 11/01/13 16:35:10, [email protected] wrote:
> def factorial(n):
> if n<2:
>  return 1
> f = 1
> while n>= 2:
> f *= n
> f -= 1

U think this line should have been:

  n -= 1

> return f


Hope this helps,

-- HansM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dependency management in Python?

2013-01-11 Thread Adelbert Chang
Perfect, PIP and virtualenv look great.

Another question - how do we then get PIP to the latest version? Or is it 
relatively easy to uninstall/reinstall PIP?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread Terry Reedy

On 1/11/2013 5:17 PM, su29090 wrote:


Circle.py

import math

class circle:


By current convention, you should call the file 'circle.py' and the 
class 'Circle'. Using all lower case for module filenames is the sanest 
thing to do in a world where different filesystems do different things 
with casing.


--
Terry Jan Reedy

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


Fundamentals of Materials Science and Engineering- An Integrated Approach, 3rd Ed by Callister

2013-01-11 Thread reganrexman
I have solutions manuals to all problems and exercises in these textbooks. To 
get one in an electronic format contact me at: reganrexman(at)gmail(dot)com and 
let me know its title, author and edition. Please this service is NOT free.

SOLUTIONS MANUAL TO Field and Wave Electromagnetics 2nd Ed by David K. Cheng
SOLUTIONS MANUAL TO Financial Accounting 6th E with Annual Report by Libby, 
Short
SOLUTIONS MANUAL TO Financial Accounting 6th Ed by Harrison
SOLUTIONS MANUAL TO Financial Accounting An Integrated Approach, 6th Ed by 
Gibbins 
SOLUTIONS MANUAL TO Financial Management- Principles and Applications, 10th Ed 
by Keown, Scott
SOLUTIONS MANUAL TO Financial Management- Theory and Practice 12 th ED by 
Brigham, Ehrhardt
SOLUTIONS MANUAL TO Financial Reporting and Analysis Using Financial Accounting 
Information 10th Ed by Gibson
SOLUTIONS MANUAL TO Financial Reporting and Analysis, 3E by Revsine, Collins, 
Johnson
SOLUTIONS MANUAL TO Finite Element Techniques in Structural Mechanics Ross
SOLUTIONS MANUAL TO First Course in Abstract Algebra, 3rd Ed by Joseph J. Rotman
SOLUTIONS MANUAL TO First Course in Probability (7th Ed., Sheldon Ross)
SOLUTIONS MANUAL TO Fluid Mechanics (5th Ed., White)
SOLUTIONS MANUAL TO Fluid Mechanics 4th Ed by Cohen, Kundu
SOLUTIONS MANUAL TO Fluid Mechanics 4th Edition by Frank M. White
SOLUTIONS MANUAL TO Fluid Mechanics and Thermodynamics of Turbomachinery (5th 
Ed., S.L. Dixon)
SOLUTIONS MANUAL TO Fluid Mechanics by CENGEL
SOLUTIONS MANUAL TO Fluid Mechanics Egon Krause
SOLUTIONS MANUAL TO Fluid Mechanics Fundamentals and Applications by Cengel & 
Cimbala
SOLUTIONS MANUAL TO Fluid Mechanics with Engineering Applications, 10th 
Edition, by Finnemore
SOLUTIONS MANUAL TO Foundations of Applied Combinatorics by Bender, Williamson
SOLUTIONS MANUAL TO Foundations of Colloid Science 2e , Hunter
SOLUTIONS MANUAL TO Foundations of Electromagnetic Theory by John R. Reitz, 
Frederick J. Milford
SOLUTIONS MANUAL TO Foundations of Modern Macroeconomics 2nd  Ed by Heijdra,  
Reijnders, Romp
SOLUTIONS MANUAL TO Fourier and Laplace Transform - Antwoorden
SOLUTIONS MANUAL TO Fractal Geometry Mathematical Foundations and Applications, 
2nd Ed Kenneth Falcone
SOLUTIONS MANUAL TO fracture mechanics ; fundamentals and applications, 2E, by 
T.L. Anderson
SOLUTIONS MANUAL TO From Polymers to Plastics By A.K. van der Vegt
SOLUTIONS MANUAL TO Fundamental Methods of Mathematical Economics 4th E by 
Chiang,Wainwright
SOLUTIONS MANUAL TO Fundamental Quantum Mechanics for Engineers by Leon van 
Dommelen
SOLUTIONS MANUAL TO Fundamentals of Advanced Accounting By Fischer, Taylor
SOLUTIONS MANUAL TO Fundamentals of Aerodynamics ( 3 Ed., Anderson)
SOLUTIONS MANUAL TO Fundamentals of Aerodynamics (2 Ed., Anderson)
SOLUTIONS MANUAL TO Fundamentals of Aircraft Structural Analysis by Howard D. 
Curtis
SOLUTIONS MANUAL TO Fundamentals of Applied Electromagnetics (5th Ed., Fawwaz 
T. Ulaby)
SOLUTIONS MANUAL TO Fundamentals of Chemical Reaction Engineering by Davis
SOLUTIONS MANUAL TO Fundamentals of Complex Analysis ( 3rd Ed., E. Saff & 
Arthur Snider )
SOLUTIONS MANUAL TO Fundamentals of Computer Organization and Architecture by 
Abd-El-Barr, El-Rewini 
SOLUTIONS MANUAL TO Fundamentals of Corporate Finance 8th edition by Ross
SOLUTIONS MANUAL TO Fundamentals of Corporate Finance 9th edition by Ross
SOLUTIONS MANUAL TO Fundamentals of Corporate Finance, 4th Edition (Brealey, 
Myers, Marcus)
SOLUTIONS MANUAL TO Fundamentals of Differential Equations 7E Kent Nagle, B. 
Saff, Snider
SOLUTIONS MANUAL TO Fundamentals of Differential Equations and Boundary Value 
Problems, 6th Ed by Nagle ,Saff, Snider
SOLUTIONS MANUAL TO Fundamentals of Digital Logic with VHDL Design (1st Ed., 
Stephen Brown Vranesic)
SOLUTIONS MANUAL TO Fundamentals of Digital Signal Processing Using Matlab 2nd 
Edition by Robert J. Schilling, Sandra L. Harris
SOLUTIONS MANUAL TO Fundamentals of Electric Circuits (2nd.ed.) by 
C.K.Alexander M.N.O.Sadiku
SOLUTIONS MANUAL TO Fundamentals of Electric Circuits (4E., Charles Alexander & 
Matthew Sadiku)
SOLUTIONS MANUAL TO Fundamentals of Electromagnetics with Engineering 
Applications (Stuart Wentworth)
SOLUTIONS MANUAL TO Fundamentals of Electronic Circuit Design , Comer
SOLUTIONS MANUAL TO Fundamentals of Engineering Economics 2nd E by Chan S. Park
SOLUTIONS MANUAL TO FUNDAMENTALS OF ENGINEERING ELECTROMAGNETICS, by DAVID CHENG
SOLUTIONS MANUAL TO Fundamentals of Engineering Thermodynamics, 5th Ed (Michael 
J. Moran, Howard N. Shapiro)
SOLUTIONS MANUAL TO Fundamentals of Engineering Thermodynamics, 6th Ed (Michael 
J. Moran, Howard N. Shapiro)
SOLUTIONS MANUAL TO Fundamentals of Financial Management 12th edition James C. 
Van Horne, Wachowicz
SOLUTIONS MANUAL TO Fundamentals of Fluid Mechanics 5th Ed Munson Young Okiishi
SOLUTIONS MANUAL TO Fundamentals of Fluid Mechanics 6th Ed by Munson
SOLUTIONS MANUAL TO Fundamentals of Fluid Mechanics, 4E (Bruce R. Munson, 
Donald F. Young, Theodore H.)
SOLUTIONS MA

Re: PyWart: Module access syntax

2013-01-11 Thread Rick Johnson

On Friday, 1-11-2013 10:02:34 AM, Steven D'Aprano wrote:
> Solution to what? You can only have a solution once you have identified a 
> problem. You have not identified a problem. In any case, your suggestion 
> is *not* obvious.

The problem is that by using the dot ubiquitously we are obfuscating the path 
to an identifier. 

> >  import lib:gui:tkinter:dialogs.SimpleDialog as Blah
> 
> Which names are packages, modules, classes, methods, functions, or other 
> objects?
> 
> Why do you have lib:gui but dialogs.SimpleDialog? Is the rule "classes 
> should always be preceded by a dot?"

No the rules are: 
* "Colon" must be used to access a "module" (or a package).
* "Dot" must be used to access a "module member".

In the line "lib:gui:tkinter:dialogs.SimpleDialog", "lib", "gui", "tkinter", 
and "dialogs" are all packages (or modules: same thing as far as paths are 
concerned). "SimpleDialog" however is a class, who's identifier is a member of 
the module "lib:gui:tkinter:dialogs". 

> Following this import:
> 
> import lib:gui
> 
> how do I access attributes of that module? 
> 
> x = lib:gui:function() perhaps? Now I have to remember which attribute 
> access uses dot operator and which uses colon operator.

It's simple: MODULES&PACKAGES use colon, MODULE MEMBERS use dot. How many times 
must i explain these simple rules?

If you don't know which names are modules and which names are members then how 
could a programmer possibly use the API in an intelligent way Steven? This 
syntax does not help the programmer much. Well, it can be beneficial to the 
programmer if he gets a *PathError* because he foolishly tried to instance a 
module named "simpledialog" when he actually meant to instance the object 
"simpledialog.SimpleDialog". (notice i did not use the word class!)

Traceback (most recent call last):
  File "", line 1, in 
dlg = lib:gui:tkinter:dialogs.simpledialog()
PathError: name 'simpledialog' is a module NOT a object!

But that is not the reason for this syntax Steven, it is just a pleasant side 
effect.

> Does this mean there needs to four new be special methods:
> 
> __getcolonattribute__
> __getcolonattr__
> __setcolonattr__ 
> __delcolonattr__ 

Gawd no. getattr, setattr, and delattr will remain unchanged. The only change 
is how a /path/ to an identifier is "formed".

> to match the regular dot operator methods
> 
> __getattribute__
> __getattr__ 
> __setattr__ 
> __delattr__ 
> 
> ? Or do you think that the Python compiler should special-case attribute 
> access from modules?

There is no "special casing" needed. Python could happily replace all colons in 
a path with dots and interpret the path internally just as it does today.

> Before thinking about the syntax, you need to think about the behaviour, 
> identify what actual problem you hope to solve, and how you hope to solve 
> it. Not just throw random syntax around and hope that it's "obvious".

*The problem:*
... is readability. The current dot syntax used ubiquitously in paths is not 
conveying the proper information to the reader, and in-fact obfuscating the 
code.

*Method to solve the problem:*
... by introducing a new syntax that requires all module access to use the 
colon and all module members to use the dot.

*The syntax:*
... is perfect. Of course we could argue over /which/ char to use, but no 
matter which char prevails, we are gaining explicitness at zero overhead to the 
programmer because we are replacing one single char(dot) for one single  
char(colon). The maintainer is the real winner. This is a win-win all around. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread Tim Roberts
Dave Angel  wrote:
>
>As Adnan has pointed out, Python is case insensitive. 

That's not really what you meant to say...
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Module access syntax

2013-01-11 Thread Chris Angelico
On Sat, Jan 12, 2013 at 3:34 PM, Rick Johnson
 wrote:
> *The problem:*
> ... is readability. The current dot syntax used ubiquitously in paths is not 
> conveying the proper information to the reader, and in-fact obfuscating the 
> code.

Please explain how this is a problem. As Steven said, there is NO
useful difference. I don't *care* whether it's a package, a module, or
whatever. Module with class with static member? Fine. Package with
module with class? Also fine. Imported special object that uses dunder
methods to simulate either of the above? What's it matter to me, as
long as I get my final result!

Syntactic salt is seldom helpful.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


async fuction

2013-01-11 Thread aleksey
Hello.

Can someone help me to resolv error.

code:


import threading

class TimeoutError(RuntimeError):
pass

class AsyncCall(object):
def __init__(self, fnc, callback = None):
self.Callable = fnc
self.Callback = callback

def __call__(self, *args, **kwargs):
self.Thread = threading.Thread(target = self.run, name = 
self.Callable.__name__, args = args, kwargs = kwargs)
self.Thread.start()
return self

def wait(self, timeout = None):
self.Thread.join(timeout)
if self.Thread.isAlive():
raise TimeoutError()
else:
return self.Result

def run(self, *args, **kwargs):
self.Result = self.Callable(*args, **kwargs)
if self.Callback:
self.Callback(self.Result)

class AsyncMethod(object):
def __init__(self, fnc, callback=None):
self.Callable = fnc
self.Callback = callback

def __call__(self, *args, **kwargs):
return AsyncCall(self.Callable, self.Callback)(*args, **kwargs)

def Async(fnc = None, callback = None):
if fnc == None:
def AddAsyncCallback(fnc):
return AsyncMethod(fnc, callback)
return AddAsyncCallback
else:
return AsyncMethod(fnc, callback)








@Async
def fnc(pi, pp):

print "fnc-"
i=pi
while ( i < 1000 ) :
i=i+1
print "fnc+"
pass

@Async
def fnc1(pp):
print "fnc1-",pp


@Async
def fnc2():
print "fnc2-"
i=0
while ( i < 10 ) :
i=i+1
print "fnc2+"
pass

fnc(i=0,pp="123123")
fnc1()


error:

Exception in thread fnc1:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
self.run()
  File "C:\Python27\lib\threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
  File "C:/Users/rootiks/YandexDisk/py/myftpbackup/asynclib.py", line 26, in run
self.Result = self.Callable(*args, **kwargs)
TypeError: fnc1() takes exactly 1 argument (0 given)

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


Re: async fuction

2013-01-11 Thread Chris Angelico
On Sat, Jan 12, 2013 at 3:43 PM,   wrote:
> def fnc1(pp):
> print "fnc1-",pp
>
> fnc1()

Like the message says, the function has been defined to take one
argument, and you're giving it none. Try giving it an argument:

fnc1("five-minute")

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread Chris Angelico
On Sat, Jan 12, 2013 at 3:37 PM, Tim Roberts  wrote:
> Dave Angel  wrote:
>>
>>As Adnan has pointed out, Python is case insensitive.
>
> That's not really what you meant to say...

UNinsensitive, your Majesty means, of course. UNinsensitive, of course, I meant.

*watches the jurors write it down, some each way*

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Import resolution order

2013-01-11 Thread Rick Johnson
On Friday, January 11, 2013 7:35:37 AM UTC-6, Terry Reedy wrote:
> On 1/11/2013 1:13 AM, Rick Johnson wrote:
> > The fact that Python looks in the stdlib _first_ is not a good idea.
> 
> And the fact is that it does not do so. The order depends on sys.path, 
> and '' is the first entry.
> 
> > It would seem more intuitive for a custom "math" module (living in
> > the current directory) to /override/ the stlib "math" module.
>
> This is a nuisance though, when not intended. Someone writes a 
> random.py, and a year later in the same directory, an unrelated 
> hopscotch.py, which tries to import random.exponential. The import fails 
> and they post here, having forgotten about their own random.py, which 
> does not have such a function. Posts like this happen a few times a year.

That's why i also mentioned the failure of Python to wrap stdlib modules in a 
package. If we would protect all built-in modules by placing them in a package 
(lib or py) then this problem would never happen. 

Of course many people will piss and moan about the extra typing. I say, you 
have a choice: a few extra chars or multitudes of extra headaches -- I choose 
the first option.

Since more time is spent /maintaining/ code bases than /writing/ them, the 
explicit path is always the correct path to choose. Anyone who says otherwise 
is either careless or selfish (aka: seeking job security).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with importing in Python

2013-01-11 Thread Dave Angel
On 01/11/2013 11:37 PM, Tim Roberts wrote:
> Dave Angel  wrote:
>> As Adnan has pointed out, Python is case insensitive. 
> That's not really what you meant to say...
Nope.  I meant Python is case sensitive.

Thanks for the catch.  I think the rest of my discourse made it clear
that case matters.



-- 

DaveA

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


Re: PyWart: Import resolution order

2013-01-11 Thread Rick Johnson
On Friday, January 11, 2013 12:30:27 AM UTC-6, Chris Angelico wrote:
> Why is it better to import from the current directory first?

Opps. I was not explicit enough with my explanation :). I meant, "look in the 
current directory FIRST when in a package". Since many times (most all times) 
packages will contain many sub-modules that need to be imported into the 
package's main.py module, and sometimes these modules will have the same name 
as a stdlib module, then looking in the package FIRST makes sense.


But the real solution is not to change the default resolution order. The real 
solution is to wrap all builtin modules into a package and use full paths to 
access every module. But wait, i have an even better idea... read below!

> Windows
> has that policy for executable commands; Unix, on the other hand,
> requires that you put an explicit path for anything that isn't in the
> standard search path. Which of these options is the more likely to
> produce security holes and/or unexpected behaviour?

I prefer the latter of course :). 

I think if python where *strict* about full paths for non-builtins, then we 
would be in a better place. But there is an even better solution! Force all 
python users to wrap THEIR modules in a toplevel package. Maybe even create the 
package for them. YES!. Call it "lib". Any "naked" modules (meaning modules 
that are not in a package)  would have to be accessed starting from "lib". Of 
course professionals like you and i are already using packages to properly nest 
out modules, but the newbie's won't realize the power of packaging modules for 
some time, so create the default "lib" package for them.

For instance you could create a package named "chris" and then have a module 
named math exist inside. Alternatively if you choose to be a non-professional 
and create a math module without a containing package, python would throw the 
module into the default "lib" package. The only way you could access your math 
module now would be by using the path "lib.math". 

So the conclusion is:

 * We encourage python programmers to use packages so they avoid any name 
clashes with built-in modules. 
 
 * if they refuse fine, any "naked" modules they create will be packaged in a 
default package (call it "lib", "userlib", or whatever) and will require them 
to prefix the module name with "lib." -- or "lib:" if i get my way!
 
By doing this we solve the many problems related to module name resolution 
orders and we create cleaner code bases. Damn i am full of good ideas!

> Welcome back to the list, Rick. Got any demonstrable code
> for Python 4000 yet?

I am working on it. Stay tuned. Rick is going to rock your little programming 
world /very/ soon.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Module access syntax

2013-01-11 Thread Rick Johnson
On Friday, January 11, 2013 10:40:36 PM UTC-6, Chris Angelico wrote:
> On Sat, Jan 12, 2013 at 3:34 PM, Rick Johnson

> > *The problem:*
> > ... is readability. The current dot syntax used ubiquitously in paths is 
> > not conveying the proper information to the reader, and in-fact obfuscating 
> > the code.
> 
> Please explain how this is a problem. 


What is this importing?

   "import lib.gui.simpledialog"
 
...is that the "simpledialog module" or "SimpleDialog object"? Since naming 
conventions are not ENFORCED, we can NEVER be sure if an identifier is a object 
or module. And since object definitions (aka: classes) are often placed into a 
module with the same name, how are we to know? Why should we be forced to open 
source files to find out a small detail that proper syntax can easily provide?

This is a matter of READABILITY, Christopher. It's one or the other (or the 
status quo):

1. Enforce naming conventions.
2. Enforce path syntax.
3. Continue to obfuscate code.

The choice is yours.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Module access syntax

2013-01-11 Thread Chris Angelico
On Sat, Jan 12, 2013 at 4:46 PM, Rick Johnson
 wrote:
> This is a matter of READABILITY, Christopher. It's one or the other (or the 
> status quo):
>
> 1. Enforce naming conventions.
> 2. Enforce path syntax.
> 3. Continue to duck type, like Python is good at.
>
> The choice is yours.

FTFY.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Import resolution order

2013-01-11 Thread Chris Angelico
On Sat, Jan 12, 2013 at 4:28 PM, Rick Johnson
 wrote:
> On Friday, January 11, 2013 12:30:27 AM UTC-6, Chris Angelico wrote:
>> Welcome back to the list, Rick. Got any demonstrable code
>> for Python 4000 yet?
>
> I am working on it. Stay tuned. Rick is going to rock your little programming 
> world /very/ soon.

So all I have to do is paper my programming world and I win?

Sorry, can't hang around arguing about module search paths and your
recommendations to add piles of syntactic salt. Gotta finish building
and playing with today's Linux kernel (3.2.7, it's looking good so
far).

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Query windows event log with python

2013-01-11 Thread robey . lawrence
Hi,

I am looking to write a short program to query the windows event log.

It needs to ask the user for input for The event type (Critical, Error, and 
Information), and the user needs to be able to specify a date since when they 
want to view results.

I understand I will need the pywin32 extension, which i already have installed.

I found this piece of code to start from,


import win32evtlog # requires pywin32 pre-installed

server = 'localhost' # name of the target computer to get event logs
logtype = 'System' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
total = win32evtlog.GetNumberOfEventLogRecords(hand)

while True:
events = win32evtlog.ReadEventLog(hand, flags,0)
if events:
for event in events:
print 'Event Category:', event.EventCategory
print 'Time Generated:', event.TimeGenerated
print 'Source Name:', event.SourceName
print 'Event ID:', event.EventID
print 'Event Type:', event.EventType
data = event.StringInserts
if data:
print 'Event Data:'
for msg in data:
print msg
print


Thanks for any help.
Robey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Module access syntax

2013-01-11 Thread Steven D'Aprano
On Fri, 11 Jan 2013 20:34:20 -0800, Rick Johnson wrote:


>> >  import lib:gui:tkinter:dialogs.SimpleDialog as Blah
>> 
>> Which names are packages, modules, classes, methods, functions, or
>> other objects?
>> 
>> Why do you have lib:gui but dialogs.SimpleDialog? Is the rule "classes
>> should always be preceded by a dot?"
> 
> No the rules are:
> * "Colon" must be used to access a "module" (or a package).
> * "Dot" must be used to access a "module member".

So what do you do for, say, os.path? According to the first rule, you 
must write it as os:path because path is a module; according to the 
second rule, you must write it as os.path because path is a member of os. 
So which rule wins?

If I do this:

import math
import string
math.string = string


is that legal, or do I have to write "math:string = string"?



Suppose I do this:


import random
if random.random() < 0.5:
math.string = "NOBODY expects the Spanish Inquisition!"
else:
math.string = string  # assuming this actually is allowed


How do I access the string member?

try:
print math.string  # only works if string is a str object
except SomeException:
print math:string  # only works if string is a module object


That would suck *and* blow at the same time. I don't need to know the 
type of any other member object in order to look it up, why should I have 
to care whether it is a module?

Now, suppose I then do this:

class Blob: pass

blob = Blob()
blob.math = math  # or should that be blob:math ?

Now do I have to write this?

blob.math:string.letters

(assuming that math:string is a module, not a str object).


[...]
> It's simple: MODULES&PACKAGES use colon, MODULE MEMBERS use dot. How
> many times must i explain these simple rules?

At the time I asked the question, you hadn't explained it *at all*.


[...]
> This syntax does not help the programmer much. Well, it can be
> beneficial to the programmer if he gets a *PathError* because he
> foolishly tried to instance a module named "simpledialog" when he
> actually meant to instance the object "simpledialog.SimpleDialog".
> (notice i did not use the word class!)

"Instance" is a noun. The verb you are looking for is "instantiate".


> Traceback (most recent call last):
>   File "", line 1, in 
> dlg = lib:gui:tkinter:dialogs.simpledialog()
> PathError: name 'simpledialog' is a module NOT a object!

Of course it is an object. *Everything* in Python is an object. Modules 
are objects. Strings are objects. Types and classes are objects. None is 
an object. Metaclasses are objects. Properties are objects. Exceptions 
are objects. Have I made it clear yet?


[...]
> *The problem:*
> ... is readability. The current dot syntax used ubiquitously in paths is
> not conveying the proper information to the reader, and in-fact
> obfuscating the code.

So you say. I think you are caring too much about the type of members and 
not enough about what interface they provide. Why do you care if I grab 
module.my_singleton_object and replace my_singleton_object with a module?

Modules are singletons in Python, in the sense that every[1] time you 
import a module you get the same object. Using modules as members for 
their singleton properties, not for their importability, is a common 
technique. With your proposal, I need to know whether a member is a 
module, or any other type, before I can access it. That is a really 
shitty design. Instead of having one syntax for *all* attribute access, 
now you have two, and we have to care whether a member is a module or 
not, which we never did before.

Worse, you couple the syntax to implementation: if I use a module as a 
singleton, I need to use one syntax; if I use a custom type as a 
singleton, I have to use different syntax. Whichever choice I make 
*today*, if the implementation changes, the required syntax changes and 
my code will break.




[1] Well, almost. There are ways to accidentally or deliberately confuse 
the import machinery.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Module access syntax

2013-01-11 Thread Steven D'Aprano
On Fri, 11 Jan 2013 21:46:36 -0800, Rick Johnson wrote:

> On Friday, January 11, 2013 10:40:36 PM UTC-6, Chris Angelico wrote:
>> On Sat, Jan 12, 2013 at 3:34 PM, Rick Johnson
> 
>> > *The problem:*
>> > ... is readability. The current dot syntax used ubiquitously in paths
>> > is not conveying the proper information to the reader, and in-fact
>> > obfuscating the code.
>> 
>> Please explain how this is a problem.
> 
> 
> What is this importing?
> 
>"import lib.gui.simpledialog"
>  
> ...is that the "simpledialog module" or "SimpleDialog object"? 

It has to be the first, because:

- you can't import members of modules directly using dot syntax

  ("import math.cos" will fail)

- and it can't be SimpleDialog, because Python is case-sensitive and you 
wrote simpledialog.


But ignoring the import, and just looking at the dotted name:

lib.gui.simpledialog

who cares what simpledialog happens to be? So long as you know the 
expected interface (say, "it's a callable object that takes three 
arguments"), you can use it the same way whether it is a function, a 
method, a class or something else. The implementation could change, and 
you need not care.

If you actually do care what the type of simpledialog is, you can find 
out easily:

type(lib.gui.simpledialog)



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Module access syntax

2013-01-11 Thread Ian Kelly
On Fri, Jan 11, 2013 at 9:34 PM, Rick Johnson
 wrote:
> No the rules are:
> * "Colon" must be used to access a "module" (or a package).
> * "Dot" must be used to access a "module member".

What about module a that does not natively contain module b, but
imports it as a member like so?

a.py:
import b

Must this be accessed as a:b or a.b?

What about a module that is referenced by some other object that is
not a module?  Should it be "my_object.pickle_module" or
"my_object:pickle_module"?

> It's simple: MODULES&PACKAGES use colon, MODULE MEMBERS use dot. How many 
> times must i explain these simple rules?

Since you didn't actually explain them at all in your initial post, I
would have to say that once is enough.

> If you don't know which names are modules and which names are members then 
> how could a programmer possibly use the API in an intelligent way Steven?

You might start by reading the documentation.

> This syntax does not help the programmer much. Well, it can be beneficial to 
> the programmer if he gets a *PathError* because he foolishly tried to 
> instance a module named "simpledialog" when he actually meant to instance the 
> object "simpledialog.SimpleDialog". (notice i did not use the word class!)

The problem here is bad naming on the part of the library designer,
not bad syntax.  Why is SimpleDialog confusingly contained in a module
also named simpledialog?  This is not Java; there is no absurd
requirement of one class per file.  A clearer path to SimpleDialog
would just be "lib.gui.tkinter.dialogs.SimpleDialog".

> Traceback (most recent call last):
>   File "", line 1, in 
> dlg = lib:gui:tkinter:dialogs.simpledialog()
> PathError: name 'simpledialog' is a module NOT a object!

See, here is the thing that seems to be eluding you.  In Python,
modules *are* objects.  You can bind names to them, just like any
other object.  You can add them to collections.  You can introspect
them.  Hell, you can even subclass ModuleType and create modules that
can be called or multiplied or iterated over or any crazy thing you
can think of.  Your : syntax is trying to treat modules as being
somehow special, but the fact is that they're *not* special, which is
why I think it's a bad idea.

>> Does this mean there needs to four new be special methods:
>>
>> __getcolonattribute__
>> __getcolonattr__
>> __setcolonattr__
>> __delcolonattr__
>
> Gawd no. getattr, setattr, and delattr will remain unchanged. The only change 
> is how a /path/ to an identifier is "formed".

Then how is ModuleType.__getattr__ supposed to know whether to raise a
"PathError" or not, after it determines whether the requested object
turned out to be a module or not?  It has no way of knowing whether it
was invoked by '.' or by ':' or by getattr or by direct invocation.

Or are you instead proposing a new bytecode "LOAD_COLON_ATTR" to
complement "LOAD_ATTR", and that every single occurrence of LOAD_ATTR
in every program would then have to check whether the loaded object
turned out to be a module and whether the object it was loaded from
also happened to be a module, all just to raise an exception in that
case instead of just giving the programmer what he wants?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problems importing from /usr/lib/pyshared/

2013-01-11 Thread Dieter Maurer
Harold  writes:

> I recently upgraded my system from ubuntu 11.4 to 12.4 and since run into an 
> issue when trying to import several packages in python2.7, e.g.
>
> harold@ubuntu:~$ python -c 'import gtk'
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py", line 30, 
> in 
> import gobject as _gobject
>   File "/usr/share/pyshared/gobject/__init__.py", line 26, in 
> from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, 
> \
>   File "/usr/share/pyshared/glib/__init__.py", line 22, in 
> from glib._glib import *
> ImportError: No module named _glib

Ubuntu 12 has introduced important changes with respect to "glib" (and
depending packages). In fact, there are now two quite incompatible
implementations - the old "static" one and a new "dynamic" one.
It looks as if in your case, old and new implementations were mixed.

I had a similar problem when upgrading to "Ubuntu 12.4". In my case,
it turned out that my (custom) "PYTHONPATH" setting was responsible for
getting into the incompatibility.


The new way to use "gtk" is via the "gi" (probable "gnome interface")
module. It looks like:

from gi.repository import Gtk,GdkPixbuf,GObject,Pango,Gdk,Gio

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


Re: Dependency management in Python?

2013-01-11 Thread Dieter Maurer
Adelbert Chang  writes:

> In the Scala language there is the Simple Build Tool that lets me specify on 
> a project-by-project basis which libraries I want to use (provided they are 
> in a central repository somewhere) and it will download them for me. Better 
> yet, when a new version comes out I need only change the SBT configuration 
> file for that project and it will download it for me.

You might also have a look at "zc.buildout" (--> on "PyPI").

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


Re: PyWart: Import resolution order

2013-01-11 Thread Ian Kelly
On Fri, Jan 11, 2013 at 10:28 PM, Rick Johnson
 wrote:
> On Friday, January 11, 2013 12:30:27 AM UTC-6, Chris Angelico wrote:
>> Why is it better to import from the current directory first?
>
> Opps. I was not explicit enough with my explanation :). I meant, "look in the 
> current directory FIRST when in a package". Since many times (most all times) 
> packages will contain many sub-modules that need to be imported into the 
> package's main.py module, and sometimes these modules will have the same name 
> as a stdlib module, then looking in the package FIRST makes sense.

And again, in Python 2.x this is already the case.  When importing in
a package, it tries to do a relative import before it even looks at
sys.path.

> I think if python where *strict* about full paths for non-builtins, then we 
> would be in a better place.

And again, in Python 3, where implicit relative imports have been
removed from the language, it already is strict about using full
paths.  You can still do relative imports, but you have to be explicit
about them.

> For instance you could create a package named "chris" and then have a module 
> named math exist inside. Alternatively if you choose to be a non-professional 
> and create a math module without a containing package, python would throw the 
> module into the default "lib" package. The only way you could access your 
> math module now would be by using the path "lib.math".

What if I create a package named "math"?  Does that also automatically
get renamed to "lib.math"?  How is it decided what package names are
proper; is it just because it happens to clash with a stdlib name that
the package gets magically renamed?

What if I create a package, and then later a module with the same name
happens to be added to the stdlib?  My program that uses the package
just breaks because it no longer imports the correct thing?

> Damn i am full of good ideas!

Your ideas might be better if you first spent some time gaining a
better understanding of how the language works as is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dependency management in Python?

2013-01-11 Thread alex23
On 12 Jan, 17:14, Dieter Maurer  wrote:
> Adelbert Chang  writes:
> > In the Scala language there is the Simple Build Tool that lets me specify 
> > on a project-by-project basis which libraries I want to use (provided they 
> > are in a central repository somewhere) and it will download them for me. 
> > Better yet, when a new version comes out I need only change the SBT 
> > configuration file for that project and it will download it for me.
>
> You might also have a look at "zc.buildout" (--> on "PyPI").

+1 for zc.buildout

I find virtualenv is great for setting up quick prototyping
environments, while zc.buildout recipes are a much better approach for
group development.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Module access syntax

2013-01-11 Thread alex23
On 12 Jan, 14:34, Rick Johnson  wrote:
> If you don't know which names are modules and which names are members
> then how could a programmer possibly use the API in an intelligent way

Your initial argument is that with import's current dot notation, it's
not obvious which is a module or not without accessing the
documentation.

You then say it's necessary to know which is which in order to use
your suggested dot/colon notation.

So what are you trying to achieve here? Your 'solution' requires
someone to look up the documentation and know what is what, whereas
the current approach _doesn't_. Anything can be imported into the
current scope, and interrogated there without recourse to
documentation. Your approach places onerous requirements on everyone
just to satisfy some arbitrary rule-set you've pulled out of your
rectum.

It's not up to _my_ code to identify how _supporting libraries_ are
structured. It just wants to import and use them. Which is, you know,
the pragmatic, get-things-done-over-endless-wanking-on-the-mailing-
list approach that Python is famous for.

You're trolling again, plain & simple.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Import resolution order

2013-01-11 Thread alex23
On 12 Jan, 14:50, Rick Johnson  wrote:
> Of course many people will piss and moan about the extra typing.

You just ignored the fact that your original claim was incorrect and
kept going on with your rant anyway.

> Since more time is spent /maintaining/ code bases than /writing/ them

In your case, more time is actually spent on insisting _other_ people
maintain code bases.

Everyone: PLEASE STOP FEEDING THE TROLL
-- 
http://mail.python.org/mailman/listinfo/python-list