Training in Python for Science: NYC in May, Austin in June

2009-04-21 Thread Janet Swisher

Enthought, Inc., is offering two upcoming open training classes on using
Python for scientific computing:

* Python for Science, Engineering, and Financial Analysis,
  New York City, May 18 to 21, 2009:
  http://www.enthought.com/training/python_nyc_0905.php

* Introduction to Scientific Computing with Python,
  Austin TX, June 15 to 19, 2009:
  http://www.enthought.com/training/intro_to_sci_comp.php

Both courses are intended for scientists, engineers, and financial
analysts who want to effectively use Python for their day-to-day
computational tasks. Programming experience with some language (e.g.,
C, C++, VB, Fortran, Matlab) is required; object-oriented programming
skills are helpful but not required.

Topics include:

* Introduction to the Python
* Array calculations with NumPy
* Numeric algorithms with SciPy
* Interfacing Python with other languages
* 2D visualization with Matplotlib and Chaco

See http://www.enthought.com/training/ for prices and details.

--
Janet Swisher, swis...@enthought.com
Enthought, Inc., http://www.enthought.com

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

   Support the Python Software Foundation:
   http://www.python.org/psf/donations.html


Python Bootcamp - Last 2 weeks to Register (May 11-15, 2009)

2009-04-21 Thread Chander Ganesan
Just a reminder that there are only 2 weeks remaining to register for 
the Open Technology Group's Python Bootcamp, a 5 day hands-on, 
intensive, in-depth introduction to Python.  This course is confirmed 
and guaranteed to run.


Worried about the costs of air and hotel to travel for training?  Don't! 
 Our All-Inclusive Packages provide round-trip airfare and hotel 
accommodations and are available for all students attending from the 
Continental US, Canada, and Europe!  Best of all, these packages can be 
booked up to May 10, 2009!


For complete course outline/syllabus, or to enroll, call us at
877-258-8987 or visit our web site at:
http://www.otg-nc.com/python-bootcamp

OTG's Python Bootcamp is a 5 day intensive course that teaches
programmers how to design, develop, and debug applications using the
Python programming language.  Over a 5 day period, through a set of
lectures, demonstrations, and hands-on exercises students will learn how
to develop powerful applications using Python and integrate their new
found Python skills in their day-to-day job activities.  Students will
also learn how to utilize Python's Database API to interface with
relational databases.

This Python course is available for on-site delivery world-wide (we
bring the class to you) for a group as small as 3, for as little as
$8,000 (including instructor travel  per-diem)!

Our course is guaranteed to run, regardless of enrollment, and available
in an all inclusive package that includes round-trip airfare, 5 nights
of hotel accommodation, shuttle services (to/from the airport, to/from
our facility, and to/from local eateries/shopping), and our training.
All-inclusive packages are priced from $2,495 for the 5 day course 
(course only is $2,295).


For more information - or to schedule an on-site course, please contact
us at 877-258-8987 .

The Open Technology Group is the world leader in the development and
delivery of training solutions focused around Open Source technologies.

--
Chander Ganesan
Open Technology Group, Inc.
One Copley Parkway, Suite 210
Morrisville, NC  27560
919-463-0999/877-258-8987
http://www.otg-nc.com



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

   Support the Python Software Foundation:
   http://www.python.org/psf/donations.html


ANN: Python-on-a-chip releases PyMite r08

2009-04-21 Thread dwhall

Python-on-a-chip

Featuring the PyMite VM
===


:Author: Dean Hall
:Copyright: Copyright 2002 Dean Hall.  All rights reserved.
PyMite is offered through one of two licenses:
commercial or open-source.  See the LICENSE file
at the root of the package for licensing details.
:Release: 08
:Site: http://www.pythononachip.org


The Python-on-a-chip Project is pleased to announce
the eighth release of PyMite.

PyMite is a flyweight Python VM written from scratch
to execute on 8-bit and larger microcontrollers with
resources as limited as 64 KB of program memory (flash)
and 4 KB of RAM.  PyMite supports a subset of the
Python 2.5 syntax and can execute a subset of the
Python 2.5 bytecodes.  PyMite can also be compiled,
tested and executed on a desktop computer.

Here are the important new features in this release:

- Fixed a float endian issue
- Fixed gc bug during ipm
- Fixed segfault when num args is fewer than expected
- Implemented plat module for mbed platform
- Created porting document
- Added scons build capability

!!Dean

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: iterate to make multiple variables?

2009-04-21 Thread john
On Apr 19, 11:11 pm, Tairic ala...@gmail.com wrote:
 Hi, I'm somewhat new to programming and especially to python. Today I
 was attempting to make a sudoku-solver, and I wanted to put numbers
 into sets call box1, box2, ... box9, so that I could check new values
 against the boxes

 I ended up declaring the boxes like this
 box1 = set([])
 box2 = set([])
 ..
 ..
 box9 = set([])

 Is there a way for me instead to generate these variables (box1 to
 box9) as empty sets instead of just writing them all out? Some way to
 iterate and generate them?

 Sorry if this is confusing, thanks in advance.

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


Re: iterate to make multiple variables?

2009-04-21 Thread john
On Apr 19, 11:11 pm, Tairic ala...@gmail.com wrote:
 Hi, I'm somewhat new to programming and especially to python. Today I
 was attempting to make a sudoku-solver, and I wanted to put numbers
 into sets call box1, box2, ... box9, so that I could check new values
 against the boxes

 I ended up declaring the boxes like this
 box1 = set([])
 box2 = set([])
 ..
 ..
 box9 = set([])

 Is there a way for me instead to generate these variables (box1 to
 box9) as empty sets instead of just writing them all out? Some way to
 iterate and generate them?

 Sorry if this is confusing, thanks in advance.

There's a key to answering you.  You pointed it out in your question,
when you say '...if
this is confusing, ...'.  Most of programming involves writing down
the stuff we need so that
we see it in less-confusing ways.  It's called stepwise refinement
by the book publishers.
What it means is that you try to think about your problem, mess about
with the tools at hand,
(lists [], sets ()  , sequences () ,strings   , and dictionaries
{ : }), and see what might
do for the job.  How are they different.  You ought to monkey around
with each of them, on your own--don't ask for help, because we can't
help as much as you can help yourself.  You'll understand much more,
in the end, besides.  Then, when you come back, with some code, even
some code that doesn't work worth a damn, if it's halfway reasonable,
we'll be able to show you where your slight misstep was--but often,
you'll get stuff working, and it's really important that you start to
do it.  Mess with the effing interpreter, mess with it often, and look
at different examples, and try them all out.  Truly.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Failure of running a second script in same interactive session

2009-04-21 Thread Steven D'Aprano
On Mon, 20 Apr 2009 23:52:39 -0500, pdlemper wrote:

 When I open python.exe to the console or interactive window and
 import/run a script I am frustrated trying to import and run another
 script in the same session.  eg I run the script alphasort once fine :
 import alphasort  it runs 

You are confused by the difference between *importing* a module and 
*running* a script. They are not necessarily the same thing, although 
some modules may be usable as scripts.


Try creating a script with this single line:

print(This runs once.)


Now import that file. The *first* time you import it, the module has to 
be executed, and it will print This runs once. as you expect. But the 
next time you import it, the module is already initialized and stored in 
the cache and nothing will print. This is by design.

To run the module again, you can:

* exit the interpreter, clearing the cache, and then start again.

* or you can run by giving it as an argument to python.exe

(On Linux I'd say python name_of_script.py but I'm not sure how you 
would do that under Windows.)


The best way to do what you want to do is when you write a script, create 
a main function. Here's an example:


print(Initialization code is here)

def main():
print(Doing stuff here)


Everything outside of main() will be run *once* only, the first time you 
import it. To run the script, do this:

 import script
Initialization code is here
 script.main()
Doing stuff here
 import script  # not necessary, because it is already imported
 script.main()
Doing stuff here



Notice that there is nothing special about the name main. You can call 
it anything you like.


Now for the special Python magic: when you run a Python script from the 
regular Linux or Windows command line (not the Python interpreter), it 
does something special. You can add this to the bottom of your script:

if __name__ == '__main__':
main()


and now it will automatically call main() whenever you run the script.

Hope this helps.



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


Re: sorting two corresponding lists?

2009-04-21 Thread Peter Otten
Esmail wrote:

 I wonder if someone could help me with sorting two corresponding lists.
 
 For instance the first list contains some items, and the second list
 contains their value (higher is better)
 
 items = [apple, car, town, phone]
 values = [5, 2, 7, 1]
 
 I would like to sort the 'items' list based on the 'values' list so
 that I end up with the following two list:
 
 items = [town, apple, car, phone]
 values = [7, 5, 2, 1]


An exotic option:

 values = [5, 2, 7, 1]
 items = [apple, car, town, phone]
 items.sort(key=lambda item, next=iter(values).next: next(),
reverse=True)
 values.sort(reverse=True)
 items
[town, apple, car, phone]
 values
[7, 5, 2, 1]

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


Re: Python interpreter speed

2009-04-21 Thread Stefan Behnel
Tim Roberts wrote:
 The Python you're thinking of (CPython) is compiled to an intermediate
 language, which is then interpreted by an interpreter loop, somewhat
 remeniscent of Forth.  It takes more cycles per instruction to run that
 interpreter loop than it does to run the machine language, but not by much.
 Java is not that much faster than CPython.
 
 There is another implementation (Jython) which compiled Python to the Java
 intermediate language, which can then be JIT compiled, exactly like Java.
 
 There is also IronPython, which is Python for the .NET framework.  It
 compiles to a different intermediate language, which is also compiled at
 execution time to machine code.

Not to forget PyPy, which uses an optimising JIT to compile things to
native code.

There's also Cython, where the intermediate language is (optimised) C, and
the compilation to machine code happens at build time (or JIT-like at
import time if you use pyximport).

Regarding this:

 Java is not that much faster than CPython.

That is a rather simplified statement. To be a tiny bit more accurate, Java
is faster for some applications and slower for others.

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


How to save clipboard data as bmp file

2009-04-21 Thread gopal mishra

I have used ImageGrab.grabclipboard() to get the clipboard image data, it
returns None. This function only supports if the clipboard data format is
CF_BITMAP.

Is there any way to save clipboard data format CF_ENHMETAFILE to bitmap file
using win32 programming.

--
Gopal

 I am trying to save my clipboard data (format is CF_ENHMETAFILE) as BitMap
 file (.BMP).

Have a look at PIL's ImageGrab module:

  http://www.pythonware.com/library/pil/handbook/imagegrab.htm

I'm not sure if the current version supports metafiles, but
it's easy enough to try.

TJG


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


Re: generating random tuples in python

2009-04-21 Thread Paul Rubin
per perfr...@gmail.com writes:
 to be more formal by very different, i would be happy if they were
 maximally distant in ordinary euclidean space... 

In that case you want them placed very carefully, not even slightly
random.  So you are making conflicting requests.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and GMP.

2009-04-21 Thread Paul Rubin
casevh cas...@gmail.com writes:
 Python 3.1 is significantly faster than Python 2.x on 64-bit
 platforms. The following times are for multiplication with 2, 30 and
 300 decimal digits.

Could you test pow(a,b,c) where a,b,c are each 300 decimal digits?
This is an important operation in cryptography, that GMP is carefully
optimized for.  Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


problem with PyMapping_SetItemString()

2009-04-21 Thread rahul
i have a c extension

tatic PyObject *upadteCheck(PyObject *self,PyObject *args){
PyObject *var_pyvalue=NULL,*newVar_pyvalue=NULL,*dict=NULL;
char *varName;

if (!PyArg_ParseTuple(args, s, varName)){
return NULL;
  }
  dict=PyEval_GetLocals();
  var_pyvalue=PyMapping_GetItemString(dict,varName);

  if(inObject==NULL){
dict=PyEval_GetGlobals();
var_pyvalue=PyMapping_GetItemString(dict,varName);
  }

  printf(\n input value for variable %s is :  %s
\n,varName,PyString_AsString(var_pyvalue))

  newVar_pyvalue=Py_BuildValue(s,value changed);

  PyMapping_SetItemString(dict,varname,newVar_pyvalue);

  return Py_BuildValue();
}



and i have three  test cases for this extension

1.(name test1.py)
 import upadteCheck
 var1= abcd

 func1():
 updateCheck.updateCheck(var1)
 print var1


2.(name test2.py)
import upadteCheck
 var1= abcd
 updateCheck.updateCheck(var1)
 print var1

3.(name test3.py)
 import upadteCheck

 func1():
 var1= abcd
 updateCheck.updateCheck(var1)
 print var1

if i run these three test cases like
 1.   import test1
   test1.fun1()

 2.   python test2

 3. import test3
 test3.func1()

than first two test cases runs correctly and gives result for var1
value changed  but 3rd test case not gives correct result and value
of var1 remains abcd


why this happen and how i correct it ??
--
http://mail.python.org/mailman/listinfo/python-list


Re: generating random tuples in python

2009-04-21 Thread Aaron Brady
On Apr 20, 11:04 pm, per perfr...@gmail.com wrote:
 On Apr 20, 11:08 pm, Steven D'Aprano



 ste...@remove.this.cybersource.com.au wrote:
  On Mon, 20 Apr 2009 11:39:35 -0700, per wrote:
   hi all,

   i am generating a list of random tuples of numbers between 0 and 1 using
   the rand() function, as follows:

   for i in range(0, n):
     rand_tuple = (rand(), rand(), rand()) mylist.append(rand_tuple)

   when i generate this list, some of the random tuples might be very close
   to each other, numerically. for example, i might get:
  [...]
   how can i maximize the amount of numeric distance between the elements
   of
   this list, but still make sure that all the tuples have numbers strictly
   between 0 and 1 (inclusive)?

  Well, the only way to *maximise* the distance between the elements is to
  set them to (0.0, 0.5, 1.0).

   in other words i want the list of random numbers to be arbitrarily
   different (which is why i am using rand()) but as different from other
   tuples in the list as possible.

  That means that the numbers you are generating will no longer be
  uniformly distributed, they will be biased. That's okay, but you need to
  describe *how* you want them biased. What precisely do you mean by
  maximizing the distance?

  For example, here's one strategy: you need three random numbers, so
  divide the complete range 0-1 into three: generate three random numbers
  between 0 and 1/3.0, called x, y, z, and return [x, 1/3.0 + y, 2/3.0 + z].

  You might even decide to shuffle the list before returning them.

  But note that you might still happen to get (say) [0.332, 0.334, 0.668]
  or similar. That's the thing with randomness.

  --
  Steven

 i realize my example in the original post was misleading. i dont want
 to maximize the difference between individual members of a single
 tuple -- i want to maximize the difference between distinct tuples. in
 other words, it's ok to have (.332, .334, .38), as long as the other
 tuple is, say, (.52, .6, .9) which is very difference from (.332, .
 334, .38).  i want the member of a given tuple to be arbitrary, e.g.
 something like (rand(), rand(), rand()) but that the tuples be very
 different from each other.

 to be more formal by very different, i would be happy if they were
 maximally distant in ordinary euclidean space... so if you just plot
 the 3-tuples on x, y, z i want them to all be very different from each
 other.  i realize this is obviously biased and that the tuples are not
 uniformly distributed -- that's exactly what i want...

 any ideas on how to go about this?

 thank you.

Two ideas.  One, start with a square grid and jitter the individual
points by a small random amount.  Two, start with one point, and move
from it by a random large distance: a2= a1+ .5+ rand( ), then %1.
--
http://mail.python.org/mailman/listinfo/python-list


problem with PyMapping_SetItemString()

2009-04-21 Thread rahul
i have a c extension

tatic PyObject *upadteCheck(PyObject *self,PyObject *args){
PyObject *var_pyvalue=NULL,*newVar_pyvalue=NULL,*dict=NULL;
char *varName;

if (!PyArg_ParseTuple(args, s, varName)){
return NULL;
  }
  dict=PyEval_GetLocals();
  var_pyvalue=PyMapping_GetItemString(dict,varName);

  if(inObject==NULL){
dict=PyEval_GetGlobals();
var_pyvalue=PyMapping_GetItemString(dict,varName);
  }

  printf(\n input value for variable %s is :  %s
\n,varName,PyString_AsString(var_pyvalue))

  newVar_pyvalue=Py_BuildValue(s,value changed);

  PyMapping_SetItemString(dict,varname,newVar_pyvalue);

  return Py_BuildValue();

}

and i have three  test cases for this extension

1.(name test1.py)
 import upadteCheck
 var1= abcd

 func1():
 updateCheck.updateCheck(var1)
 print var1

2.(name test2.py)
import upadteCheck
 var1= abcd
 updateCheck.updateCheck(var1)
 print var1

3.(name test3.py)
 import upadteCheck

 func1():
 var1= abcd
 updateCheck.updateCheck(var1)
 print var1

if i run these three test cases like
 1.   import test1
   test1.fun1()

 2.   python test2

 3. import test3
 test3.func1()

than first two test cases runs correctly and gives result for var1
value changed  but 3rd test case not gives correct result and value
of var1 remains abcd

why this happen and how i correct it ??
--
http://mail.python.org/mailman/listinfo/python-list


Self-intro and possible offtopic: creation of group integrating translators and experts in the fields they translate

2009-04-21 Thread vocabulo
Dear Owner,
This is a message announcing the creation of a google translation
project group (I appologize if 's against the rules).
Thank you,
Marco


Dear Members,

My name is Marco Juliano e Silva, and I'm basically a technical
translator.

This is to let you know that I just created the google group
tecschange (technical exchange), dedicated to facilitating the
interaction between translators and those who are both professionals
of the areas of the texts they are translating and native speakers of
its target language.

To those who might be interested in participating, I would ask as a
first step that they just join the group and state their field of
expertise and native language.

People of any level of study are invited, whether it be college level
or undergraduate, or even those who never graduated in any thing, the
sole criterion being that they have a de facto expertise in something,
and therefore master its terminology.

Needless to say, people of all languages, countries, religions, or
ethnic origin are equally welcome.

Thank you,

Marco Juliano
www.marcjultrad.com.br
tecscha...@googlegroups.com

PS: I’ve also created a yahoo group by the name texchange, with the
same purpose. The reason I created one group at google’s and another
at yahoo’s is because people tend to polarize between these two
vehicles, and also because I’m deciding which one is better for my
purpose. For the moment, I’ll run the two groups – this is doable,
since for the time being the main task is to just invite people - but
eventually I intend to unify them. There is no need, but should you
feel like joining both groups, you’re welcome.


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


Re: PEP 401

2009-04-21 Thread alessiogiovanni . baroni
On 19 Apr, 21:28, Stefan Behnel stefan...@behnel.de wrote:
 alessiogiovanni.bar...@gmail.com wrote:
  Are 19 days that I read this PEP; it's all true?

 Yep. Actually, the Cython project was lucky that the FLUFL did not
 recognise it as an alternative implementation of Python. That way, we can
 easily finish up world domination, say, 10-20 years before Python on Parrot
 reaches 2.7 feature completeness.

 Stefan

mm .. I noticed some inconsistencies in PEP, and I suspected
of a joke,
but ... only now I realize the Status :-( ... Excuse me  At least
the heart
will not blow up to someone else . :-D
--
http://mail.python.org/mailman/listinfo/python-list


Re: generating random tuples in python

2009-04-21 Thread Steven D'Aprano
On Mon, 20 Apr 2009 21:04:25 -0700, per wrote:

 i realize my example in the original post was misleading. i dont want to
 maximize the difference between individual members of a single tuple --
 i want to maximize the difference between distinct tuples. in other
 words, it's ok to have (.332, .334, .38), as long as the other tuple is,
 say, (.52, .6, .9) which is very difference from (.332, . 334, .38).  i
 want the member of a given tuple to be arbitrary, e.g. something like
 (rand(), rand(), rand()) but that the tuples be very different from each
 other.
 
 to be more formal by very different, i would be happy if they were
 maximally distant in ordinary euclidean space... so if you just plot the
 3-tuples on x, y, z i want them to all be very different from each
 other.  i realize this is obviously biased and that the tuples are not
 uniformly distributed -- that's exactly what i want...


If you *really* mean maximally distant, the maximal distance in a 1x1x1 
cube is sqrt(3). Clearly you can't move sqrt(3) away in an arbitrary 
direction from an arbitrary point and remain inside the cube, but you 
could probably do something like this:

* generate a random point (a, b, c);
* work out what's the furthest you can go from there and still remain 
inside the cube;
* return that point as the second point.

Problem is that one out of every two points will be on the edge of the 
cube. This will be *seriously* biase, and obviously so.


Here's another strategy: given the first point, generated randomly, 
reflect it around the centre point (0.5, 0.5, 0.5) in some plane to give 
the second point. You'll need to do some geometry to determine what plane 
to use. Disadvantage: the points will have a very strong symmetry.


Third strategy: divide the cube into eight half-cubes. Label then A 
through H:

A: 0.0 = x = 0.5, 0.0 = y = 0.5, 0.0 = z = 0.5
B: 0.5   x = 1.0, 0.0 = y = 0.5, 0.0 = z = 0.5
C: 0.0 = x = 0.5, 0.5   y = 1.0, 0.0 = z = 0.5
D: 0.5   x = 1.0, 0.5   y = 1.0, 0.0 = z = 0.5

(E, F, G, H are the same but with 0.5  z = 1.0)

Generate a point in one half of the cube, A-D. If the point is in A, then 
the second point needs to be in H; if the first point is in B, the second 
should be in G; if the first point is in C, then generate your second 
point in F, and if in D, generate a point in E.

This will give you points which are still random-ish, but on average they 
should be sqrt(3)/2 apart, which is probably about as far as you can 
reasonably expect. There will be some symmetry, *on average*, but 
individual points shouldn't have a mirror image (except by some fluke).



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


Re: Python and GMP.

2009-04-21 Thread alessiogiovanni . baroni
On 21 Apr, 09:11, Paul Rubin http://phr...@nospam.invalid wrote:
 casevh cas...@gmail.com writes:
  Python 3.1 is significantly faster than Python 2.x on 64-bit
  platforms. The following times are for multiplication with 2, 30 and
  300 decimal digits.

 Could you test pow(a,b,c) where a,b,c are each 300 decimal digits?
 This is an important operation in cryptography, that GMP is carefully
 optimized for.  Thanks.

Ok, thanks for your answers. I understand the problems of licensing,
but
we could to learn from GMP's source code to improve the Python's int
implementation,
mainly because, GMP is very fast. We could violate the GPL?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming in Python with a view to extending in C at a later date.

2009-04-21 Thread Carl Banks
On Apr 20, 11:57 am, dug.armad...@googlemail.com
dug.armad...@googlemail.com wrote:
 Say you set out to program in Python knowing that you will be
 converting parts of it into C ( or maybe C++) at a later date, but you
 do not know which parts.

 Can you give any general Python structure / syntax advice that if
 implemented from the start, will make this future task less painful.
 In addition, advice that will make this easier for automatic tools
 will be good too.

I'd just avoid things that don't have a straightforward translation to
C (such as clever metaprogramming, overdependence on keyword
arguments, nested scopes and closures, and yes, generators).  Most
things in Python do correspond pretty well to things in C.

However, don't avoid objects that might be difficult to implement in C
(such as dicts and sets); fact is, code that uses these objects a lot
probably won't benefit much from translation to C.  OTOH, if you need
dict-like behavior in an otherwise static computation, it's probably
because there's no other easy way to do the computation, so you'll
have to tackle the problem in C anyway.

Also, don't avoid regular exception handling.  When you rewrite
something in C you'll find that it is farily obvious how to write the
C code so that it returns errors in a similar way.

If you do a lot of OO stuff I strongly recommend that you study up on
the right way to implement new-style types from C, such that they can
serve as a base for Python classes.  That way, if you have a class and
you want to implement a few methods in C while leaving the rest in
Python, you can factor out all the C methods into a base class written
in C.


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


Re: generating random tuples in python

2009-04-21 Thread Steven D'Aprano
On Tue, 21 Apr 2009 07:53:29 +, Steven D'Aprano wrote:

 Third strategy: divide the cube into eight half-cubes. Label then A
 through H:

Sheesh. Obviously they're not *half* cubes if there are eight of them. 
What I meant was that their edges are half as long as the edge of the 
1x1x1 cube.

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


Re: out of memory with processing module

2009-04-21 Thread alessiogiovanni . baroni
On 20 Apr, 18:32, Brian knair...@yahoo.com wrote:
 On Apr 20, 9:18 am, alessiogiovanni.bar...@gmail.com wrote:



  On 20 Apr, 17:03, Brian knair...@yahoo.com wrote:

   I'm using the third-party processing module in Python 2.5, which may
   have become the multiprocessing module in Python 2.6, to speed up
   the execution of a computation that takes over a week to run. The
   relevant code may not be relevant, but it is:

               q1, q2 = processing.Queue(), processing.Queue()
               p1 = processing.Process(target=_findMaxMatch, args=
   (reciprocal, user, clusters[1:(numClusters - 1)/2], questions,
   copy.copy(maxMatch), q1))
               p2 = processing.Process(target=_findMaxMatch, args=
   (reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy
   (maxMatch), q2))
               p1.start()
               p2.start()
               maxMatch1 = q1.get()[0]
               maxMatch2 = q2.get()[0]
               p1.join()
               p2.join()
               if maxMatch1[1]  maxMatch2[1]:
                   maxMatch = maxMatch1
               else:
                   maxMatch = maxMatch2

   This code just splits up the calculation of the cluster that best
   matches 'user' into two for loops, each in its own process, rather
   than one. (It's not important what the cluster is.)

   The error I get is:

   [21661.903889] Out of memory: kill process 14888 (python) score 610654
   or a child
   [21661.903930] Killed process 14888 (python)
   Traceback (most recent call last):
   ...etc. etc. ...

   Running this process from tty1, rather than GNOME, on my Ubuntu Hardy
   system allowed the execution to get a little further than under GNOME.

   The error was surprising because with just 1 GB of memory and a single
   for loop I didn't run into the error, but with 5 GB and two processes,
   I do. I believe that in the 1 GB case there was just a lot of
   painfully slow swapping going on that allowed it to continue.
   'processing' appears to throw its hands up immediately, instead.

   Why does the program fail with 'processing' but not without it? Do you
   have any ideas for resolving the problem? Thanks for your help.

  If your program crashes with more of one process, maybe you handle the
  Queue objects
  not properly? If you can, post the code of _findMaxMatch.

 Thanks for your interest. Here's _findMaxMatch:

 def _findMaxMatch(reciprocal, user, clusters, sources, maxMatch,
 queue):
     for clusternumminusone, cluster in enumerate(clusters):
         clusterFirstData, clusterSecondData = cluster.getData(sources)
         aMatch = gum.calculateMatchGivenData(user.data, None, None,
 None, user2data=clusterSecondData)[2]
         if reciprocal:
             maxMatchB = gum.calculateMatchGivenData(clusterFirstData,
 None, None, None, user2data=user.secondUserData)[2]
             aMatch = float(aMatch + maxMatchB) / 2
         if aMatch  maxMatch[1]:
             maxMatch = [clusternumminusone + 1, aMatch]
     queue.put([maxMatch])

You can post the entire error message + full traceback?
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Special Thanks

2009-04-21 Thread Nick Craig-Wood
norseman norse...@hughes.net wrote:
  I'm one of those that tries to get an outline of the project and then 
  puts in code as things become clear. Once the basics are working 
  reasonably I go back and organize the thing for maintainability. Then 
  finish flushing it out. It is the one stage I dread the most.
 
  Why not organize it up front?  Because I don't always have the whole pie 
  at the outset.
 
  In changing to Python I had a bigger learning curve than I realized at 
  the start.  When I finally got my pieces accomplishing what I wanted 
  it became time to start looking at its structure.
 
  I did the cut and paste into a followable form and ran the basic to 
  check for the usual errors, omissions and outright flaws. This was a 
  major reorganization.
 
  IT RAN FLAWLESSLY THE FIRST TRY!  UNBELIEVABLE! (at least for me)

Python has a well deserved reputation for being executable
pseudo-code.  It is the only language I've ever used where when you
write the program it is quite likely to work the first time.

Python also converted me to using unit tests.  If you add unit tests
into your methodology above then when you re-organize (or refactor to
use the modern jargon) the code you can be 100% sure that you didn't
break anything which is a wonderful feeling.

-- 
Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


who is calling the base class __new__ method

2009-04-21 Thread Andreas Otto
Hi,

  I have the following example:

  1. I create a new type in C with it's own tp_new called PyMqS_new
  2. I use this type as basis-class for a python class called Server.

class Server(pymsgque.MqS):

- I checked: self.__class__.__bases__: (class 'pymsgque.PyMqS',)
from a Server startup code and the base is available


  3. A object of Server should create a new object of class Server in
the C code of MqS using the following statement

context-self = PyObject_GC_New(PyObject,(PyTypeObject*)context-class);

class is the Server but the PyMqS_new is *not* called as expected

- Why ?

  4. I checked the code with a debugger and I find out that the python
ServerObject create with PyObject_GC_New has the right pointer

- ServerObject-ob_type-tp_new has a pointer to PyMqS_new

- this seems to be fine


I checked the tp_basicsize and this has a size of 40 seems ok

from: http://docs.python.org/3.0/extending/newtypes.html
If you want your type to be subclassable from Python, and your type has the
same tp_basicsize as its base type, you may have problems with multiple
inheritance. A Python subclass of your type will have to list your type
first in its __bases__, or else it will not be able to call your type’s
__new__() method without getting an error. You can avoid this problem by
ensuring that your type has a larger value for tp_basicsize than its base
type does. Most of the time, this will be true anyway, because either your
base type will be object, or else you will be adding data members to your
base type, and therefore increasing its size.

An other aspect from your docu (same link as above): 

If you are creating a co-operative tp_new (one that calls a base type’s
tp_new or __new__()), you must not try to determine what method to call
using method resolution order at runtime. Always statically determine what
type you are going to call, and call its tp_new directly, or via
type-tp_base-tp_new. If you do not do this, Python subclasses of your
type that also inherit from other Python-defined classes may not work
correctly. (Specifically, you may not be able to create instances of such
subclasses without getting a TypeError.)


This I don't understand because the  tp_base of MqS is Object
and if I call the Object tp_new from my new

static PyObject *
PyMqS_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
M0
  ?? type-tp_base-tp_new(
  PyMqS_Obj *self = (PyMqS_Obj *)type-tp_alloc(type, 0);
  self-msgque = NULL;
  return (PyObject *)self;
}



mfg

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


Problem with COM and variants

2009-04-21 Thread Simon Carter
Hullo! I'm having a problem interfacing with a proprietary COM library on 
Windows, and I was hoping someone could help. I'm no COM guru, so apologies 
in advance if my terminology gets a little muddled...


I'm accessing the COM library via gencache.EnsureModule. It was all working 
as expected until I needed to access a property of a COM interface that 
returns a variant. So:


   my_object.SomeMethod() # works fine
   val = my_object.RunningProcessInfo #throws a 'The parameter is 
incorrect' com_error
   val = my_object.RunningProcessInfo() #tried that just in case, but it 
also throws a 'The parameter is incorrect' com_error
   val = my_object.get_RunningProcessInfo() #nope, object has no attribute 
'get_RunningProcessInfo()'


Looking at the generated interface python file, although RunningProcessInfo 
exists, there is no reference to the PROCESS_INFO structure it is meant to 
return. If I browse the library using the pythonwin COM browser I can see 
that the relevant structure exists, flagged as a 'Record' in the browser, 
although I can't inspect its members.


Thinking that maybe structures are generated on the fly, I tried forcing the 
creation of the given record type:


   val = win32com.client.Record(PROCESS_INFO, my_object) #The structure 
PROCESS_INFO is not defined in the module module win32com.gen_py.


As such, from my point of view of almost total ignorance, it seems that my 
problem is being caused by the PROCESS_INFO structure not being 
generated/accessible. More likely, of course, it that I'm being an arse and 
doing it wrong.


Some other notes:
- I've tried similar things using the late binding 'Dispatch' interface, but 
without any luck.
- I've tried the same thing with various other properties that return 
structures, with the same result.
- It may not be related, but I've also had a look at some other libraries, 
such as the DirectX Transforms Core Type Library, and there are lots of 
structures in there that appear in the COM browser, but don't appear in the 
generated interface file.

- I'm running 32bit python 2.6 and pywin32 build 213, on Vista 64.

Any help much appreciated.

Thanks!

Simon 


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


Re: The Python standard library and PEP8

2009-04-21 Thread Lawrence D'Oliveiro
In message pan.2009.04.21.03.12...@remove.this.cybersource.com.au, Steven 
D'Aprano wrote:

 Everybody understands what you mean when you say something is tasty, even
 though everyone's understanding of tasty is different. You don't need to
 agree on what tasty *is* to agree that something *isn't* tasty 

But you do if you want to describe something as purely tasty.

 We don't need to agree on what OO means to know that Python isn't purely
 OO.

We don't need to agree on what OO means to know that Python has OO. But we 
do need to agree if we want to say it's purely OO or not.

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


Re: How to save clipboard data as bmp file

2009-04-21 Thread Tim Golden

gopal mishra wrote:

I have used ImageGrab.grabclipboard() to get the clipboard image data, it
returns None. This function only supports if the clipboard data format is
CF_BITMAP.

Is there any way to save clipboard data format CF_ENHMETAFILE to bitmap file
using win32 programming.


Well I'm sympathetic to the query, although I don't know the answer
myself. However, you will gain a bit more support (and maybe even the
answer) if you were to put something like:

 save clipboard CF_ENHMETAFILE to file

or some similar search string into your search engine of choice,
and try out some of the solutions which appear. Feel free to
come back if you're not sure how to implement them in Python,
but showing that you've made some effort will gain you more
traction than coming empty-handed for a solution, methinks.

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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-21 Thread Ivan Illarionov
On Apr 18, 3:39 pm, BJörn Lindqvist bjou...@gmail.com wrote:
 I first started programming basic and i don't think it has hurt me much.

 I can somewhat sympathise with the op, neither python nor any other
 mainstream language can still do this:

 SCREEN 13
 PSET 160,100,255

This is not true. It's trivial with pygame or equivalent SDL
bindings in other mainstream languages:

basic.py:
---
import sys
import pygame

class BasicInterpreter:
def SCREEN(self, x):
self.surface = pygame.display.set_mode(
(320, 200), pygame.FULLSCREEN, 8)

def PSET(self, x, y, c):
self.surface.set_at((x, y), c)
pygame.display.flip()

if __name__ == '__main__' and len(sys.argv)  1:
basic = BASIC()
with open(sys.argv[1]) as bas:
for line in bas:
eval(basic.%s(%s) % tuple(x.strip() for x in line.split
(' ', 1)))
while True:
for event in pygame.event.get():
if event.type in (pygame.QUIT, pygame.KEYDOWN):
sys.exit(0)

---

This will execute your BASIC program.

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


Re: Python and GMP.

2009-04-21 Thread bearophileHUGS
casevh:
 Testing 2 digits. This primarily measures the overhead for call GMP
 via an extension module.
 ...

Thank you for adding some actual data to the whole discussion :-)
If you perform similar benchmarks with Bigints of Java you will see
how much slower they are compared to the Python ones.


Mark Dickinson:
Apart from that, I'm not sure there's much snot left to be optimized out, as 
they say...

Using inline ASM in Python sources isn't an option.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: who is calling the base class __new__ method

2009-04-21 Thread Andreas Otto


Hi,

  found a solution 

  - PyObject_GC_New seems not to be *not* the right function to
create a new Python object with a base class included

  - PyType_GenericNew is the right one ...
but this one is not documented 

from: http://docs.python.org/3.0/c-api/type.html
=
PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject
*kwds)¶
Return value: New reference.

XXX: Document.
=

   Question: What is the difference between these both functions
and why is one working and the other not ?

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


Re: sorting two corresponding lists?

2009-04-21 Thread Esmail

Esmail wrote:


items = [apple, car, town, phone]
values = [5, 2, 7, 1]

I would like to sort the 'items' list based on the 'values' list so
that I end up with the following two list:

items = [town, apple, car, phone]
values = [7, 5, 2, 1]


Hello all,

thanks for all the great suggestions. I used Diez's post as an
opportunity to learn about zip and this this is the code I
ended up drafting:

  li=zip(*sorted(zip(values, items), reverse=True))
  new_items=list(li[1])
  new_vals=list(li[0])

seems to work :-)

Esmail

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


Re: Python and GMP.

2009-04-21 Thread Mark Dickinson
On Apr 21, 12:04 pm, bearophileh...@lycos.com wrote:
 Using inline ASM in Python sources isn't an option.

Except when it is. :)

There's a tiny amount of inline assembler in the
sources already:  see Python/pymath.c and
Python/ceval.c.  Not surprisingly, there's some
in the ctypes module as well.

There *are* places where it's very tempting to
add a little (optional, removable, carefully
tested, etc.) assembler to the long implementation:
one main reason that using 30-bit digits for longs
is slower (for some benchmarks) than using 15-bit
digits on 32-bit platforms is that there's no way
to tell C to do a 64-bit by 32-bit division, in cases
where you know (from understanding of the algorithm)
that the quotient fits into 32 bits.

On x86, replacing just two of the divisions
in Objects/longsobject.c by the appropriate 'divl'
inline assembler got me 10% speedups on some
benchmarks.

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


Re: python-magic with python2.6

2009-04-21 Thread Gabriel

Gabriel wrote:
Is there any way to use 
python-magic(http://pypi.python.org/pypi/python-magic/0.1) with 
python2.6?

Or do somebody know something similar to this what is running on 2.6?


If somebody care .. .)
I have found sources of python-magic here:
http://wiki.python.org/moin/HowTo/FileMagic?action=AttachFiledo=viewtarget=LARZ-python-magic-v0.1-c112ac064b7f.zip

and it works fine with 2.6.

--
Gabriel

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


ANN: PyGUI 2.0.4

2009-04-21 Thread Greg Ewing

PyGUI 2.0.4 is available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

Fixes a few more bugs and hopefully improves things
on Windows, although I can't be sure it will fix all
the Windows problems people are having, because I
haven't been able to reproduce some of them.


What is PyGUI?
--

PyGUI is a cross-platform GUI toolkit designed to be lightweight
and have a highly Pythonic API.

--
Gregory Ewing
greg.ew...@canterbury.ac.nz
http://www.cosc.canterbury.ac.nz/greg.ewing/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and GMP.

2009-04-21 Thread Mark Dickinson
On Apr 21, 8:57 am, alessiogiovanni.bar...@gmail.com wrote:
 Ok, thanks for your answers. I understand the problems of licensing,
 but
 we could to learn from GMP's source code to improve the Python's int
 implementation,
 mainly because, GMP is very fast. We could violate the GPL?

Suggestions for ways to improve Python's int implementation are
very welcome.  But note that Python favours portability (and also
readability and maintainability of source code) over speed here:
at least some of GMP's speed comes from using hand-crafted
assembler for common platforms, and that's really a no-go
area for Python.

There's at least one more optimization (to multiplication, as it
happens) that I plan to get in before 3.1.  See

http://bugs.python.org/issue3944

Apart from that, I'm not sure there's much snot left to be
optimized out, as they say...

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


Re: the correct way to install python packages as non root user in non default path

2009-04-21 Thread News123
Hi Alex,


Thanks a lot. Reading the description this sounds to be the right thing.


But now I'm stuck installing virtualenv as a user as this seems to be no
ubunbtu package:


export PYTHONPATH=/opt/newpymod/lib/python2.5/site-packages
mkdir -p $PYTHONPATH
easy_install --prefix /opt/newpymod install virtualenv

 Creating /opt/newpymod/lib/python2.5/site-packages/site.py
 Searching for install
 Reading http://pypi.python.org/simple/install/
 Couldn't find index page for 'install' (maybe misspelled?)
 Scanning index of all packages (this may take a while)
 Reading http://pypi.python.org/simple/
 No local packages or download links found for install
 error: Could not find suitable distribution for Requirement.parse('install')


So back to question 1 :-(
How do I install non Ubuntu python packages in a local directory?



alex23 wrote:
 On Apr 21, 8:32 am, News123 news...@free.fr wrote:
 I'm having an Ubuntu host, but want to (experimentally)
 install some modules, which are newer than the Ubuntu ones
 (distros lag always a little behind and some tools need newer versions.)

 What would be a clean way to do this?
 
 I think virtualenv will help you here: http://pypi.python.org/pypi/virtualenv
 
 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with COM and variants

2009-04-21 Thread John Machin
On Apr 21, 7:37 pm, Simon Carter bbbscar...@gmail.com wrote:
 Hullo! I'm having a problem interfacing with a proprietary COM library on
 Windows, and I was hoping someone could help. I'm no COM guru, so apologies
 in advance if my terminology gets a little muddled...

[snip]

 - I'm running 32bit python 2.6 and pywin32 build 213, on Vista 64.

You may like to ask on the python-win32 mailing list
python-wi...@python.org
http://mail.python.org/mailman/listinfo/python-win32

Cheers,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and GMP.

2009-04-21 Thread casevh
On Apr 21, 12:11 am, Paul Rubin http://phr...@nospam.invalid wrote:
 casevh cas...@gmail.com writes:
  Python 3.1 is significantly faster than Python 2.x on 64-bit
  platforms. The following times are for multiplication with 2, 30 and
  300 decimal digits.

 Could you test pow(a,b,c) where a,b,c are each 300 decimal digits?
 This is an important operation in cryptography, that GMP is carefully
 optimized for.  Thanks.

$ py25 -m timeit -s  a=long('23'*150);b=long('47'*150);m=long
('79'*150) c=pow(a,b,m)
10 loops, best of 3: 52.7 msec per loop
$ py31 -m timeit -s  a=int('23'*150);b=int('47'*150);m=int('79'*150)
c=pow(a,b,m)
100 loops, best of 3: 8.85 msec per loop
$ py25 -m timeit -s  import gmpy;a=gmpy.mpz('23'*150);b=gmpy.mpz
('47'*150);m=gmpy.mpz('79'*150) c=pow(a,b,m)
1000 loops, best of 3: 1.26 msec per loop

casevh

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


Re: Python and GMP.

2009-04-21 Thread Paul Rubin
alessiogiovanni.bar...@gmail.com writes:
  Could you test pow(a,b,c) where a,b,c are each 300 decimal digits?
  This is an important operation in cryptography, that GMP is carefully
  optimized for.  Thanks.
 
 Ok, thanks for your answers. I understand the problems of licensing,
 but we could to learn from GMP's source code to improve the Python's
 int implementation, mainly because, GMP is very fast. 

GMP is a lot more complicated than Python bigint arithmetic.  It's
optimized separately for many different cases and operations.  It uses
assembly language for innder loops.  And the modular exponential
operation pow(a,b,c) is especially carefully tuned in complicated
ways.  Python tries to just have straightforward, reasonably portable
bigints.

I did something like

   try:
 import gmpy
 pow=gmpy.modexp # or whatever it was called
   except ImportError: 
 pass

in an application a while back, so that it would use gmpy if possible
and Python longs otherwise.  That worked pretty well.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and GMP.

2009-04-21 Thread Paul Rubin
casevh cas...@gmail.com writes:
  Could you test pow(a,b,c) where a,b,c are each 300 decimal digits?
 
 $ py25 -m timeit -s  a=long('23'*150);b=long('47'*150);m=long
 ('79'*150) c=pow(a,b,m)
 10 loops, best of 3: 52.7 msec per loop
 $ py31 -m timeit -s 
 100 loops, best of 3: 8.85 msec per loop
 $ py25 -m timeit -s  ...import gmpy ...
 1000 loops, best of 3: 1.26 msec per loop

Wow, thanks.  gmpy = 40x faster than py2.5.  Ouch.
--
http://mail.python.org/mailman/listinfo/python-list


Re: not homework... something i find an interesting problem

2009-04-21 Thread Trip Technician
Thank you Dave. This does it but slowly. takes every subset of the
list a of squares, and then gets a 'partition' that will work, many
are very inefficient (with lots of 1s).

any hints about how to speed up ?


def subset(x):
for z in range(1,2**len(x)):
q=bin(z)
subs=[]
for dig in range(len(q)):
if q[dig]=='1':
subs.append(x[dig])
yield subs

def bin(x):
  q=
  while x=1:
q+=str(x%2)
x//=2
  return q



def squ(z,b):
if z==0:
return 0
for x in b:
if z=x:
return x,squ(z-x,b)


def flatten(lst):
for elem in lst:
if type(elem) in (tuple, list):
for i in flatten(elem):
yield i
else:
yield elem



sizelim=150

a=[x**2 for x in range(int(sizelim**0.5),1,-1)]

q,r=[],[]

for aa in range(sizelim):
r.append([])


for xx in range(1,sizelim):
for z in subset(a):
q=[]
z.append(1)
for rr in flatten(squ(xx,z)):
if rr !=0:
q.append(rr)
item=[len(q),q]
if item not in r[xx]:
r[xx].append(item)
r[xx].sort()

for eee in r:
if eee:
print r.index(eee),eee[0:3]

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


Re: Programming in Python with a view to extending in C at a later date.

2009-04-21 Thread bobicanprogram
On Apr 20, 2:57 pm, dug.armad...@googlemail.com
dug.armad...@googlemail.com wrote:
 Hi,

 Say you set out to program in Python knowing that you will be
 converting parts of it into C ( or maybe C++) at a later date, but you
 do not know which parts.

 Can you give any general Python structure / syntax advice that if
 implemented from the start, will make this future task less painful.
 In addition, advice that will make this easier for automatic tools
 will be good too.

 This advice might include stuff like avoid using Python yield
 as 

 Thank you in advance,

 Douglas


Actually you can have your cake and eat it too.  We've used the SIMPL
toolkit (http://www.icanprogram.com/simpl) and its ultra lightweight
toolkit to join Python programs to those written in other languages
(C,C++,Tcl/Tk or JAVA).   That way you can keep the parts that Python
is good at in Python and keep the parts that C or C++ are good at
written in those languages and join the lot together seamlessly.
SIMPL will even allow those parts to be deployed on separate network
nodes often without any code change or recompile.

There is an onlime tutorial/course with lots of examples at:

http://www.icanprogram.com/06py/main.html

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


Re: the correct way to install python packages as non root user in non default path

2009-04-21 Thread Diez B. Roggisch
News123 wrote:

 Hi Alex,
 
 
 Thanks a lot. Reading the description this sounds to be the right thing.
 
 
 But now I'm stuck installing virtualenv as a user as this seems to be no
 ubunbtu package:
 
 
 export PYTHONPATH=/opt/newpymod/lib/python2.5/site-packages
 mkdir -p $PYTHONPATH
 easy_install --prefix /opt/newpymod install virtualenv

Just because apt-get uses install as command doesn't mean everything else
does. And easy_install is one of those which doesn't. Remove the install,
and things should work.

Additionally, I don't see any problem with installing virtualenv into the
system-python. It's an addon, not a replacement, thus it shouldn't collide
with package management (unless you are going to remove python)

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


[no subject]

2009-04-21 Thread karlos barlos
hello to everybody...

having problem withe this code :

dom = raw_input(The Domain name..:)
  ad_user.Put('userPrincipalName',user['login']+'@(['dom'])

but it wont change whay ?



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


[no subject]

2009-04-21 Thread karlos barlos
hello to everybody...

having problem withe this code :

dom = raw_input(The Domain name..:)
  ad_user.Put('userPrincipalName',user['login']+'@(['dom'])

but it wont change whay ?



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


Re: Problem with COM and variants

2009-04-21 Thread Simon Carter

Doh!

Ta.

Simon

John Machin sjmac...@lexicon.net wrote in message 
news:023fcc82-6e98-4ddd-9977-06d95ab44...@c18g2000prh.googlegroups.com...

On Apr 21, 7:37 pm, Simon Carter bbbscar...@gmail.com wrote:

Hullo! I'm having a problem interfacing with a proprietary COM library on
Windows, and I was hoping someone could help. I'm no COM guru, so 
apologies

in advance if my terminology gets a little muddled...


[snip]


- I'm running 32bit python 2.6 and pywin32 build 213, on Vista 64.


You may like to ask on the python-win32 mailing list
python-wi...@python.org
http://mail.python.org/mailman/listinfo/python-win32

Cheers,
John 


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


Re: Python and GMP.

2009-04-21 Thread casevh
On Apr 21, 5:47 am, Paul Rubin http://phr...@nospam.invalid wrote:
 casevh cas...@gmail.com writes:
   Could you test pow(a,b,c) where a,b,c are each 300 decimal digits?

  $ py25 -m timeit -s  a=long('23'*150);b=long('47'*150);m=long
  ('79'*150) c=pow(a,b,m)
  10 loops, best of 3: 52.7 msec per loop
  $ py31 -m timeit -s 
  100 loops, best of 3: 8.85 msec per loop
  $ py25 -m timeit -s  ...import gmpy ...
  1000 loops, best of 3: 1.26 msec per loop

 Wow, thanks.  gmpy = 40x faster than py2.5.  Ouch.

Remember this is on a 64-bit platform using the latest versions of
MPIR or GMP. The ratio would be less for older versions or 32-bit
versions.

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


Re:

2009-04-21 Thread Tim Golden

karlos barlos wrote:

hello to everybody...

having problem withe this code :

dom = raw_input(The Domain name..:)
  ad_user.Put('userPrincipalName',user['login']+'@(['dom'])

but it wont change whay ?



Some more context would help, including a code fragment and
traceback if there is any (or the fact that there isn't).

I can of course guess that you're trying to set attributes
on an Active Directory user, but that's only because I'm
a Windows user (and the author of a module for that purpose
which you may or more not be using...).

*Please* have a little thought before you throw such a
question out onto a public list. I'm sure people are
willing to help you out (I know I am) but you have to
meet us at least halfway. :)

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


Problem updating AD user [was: Re:]

2009-04-21 Thread Tim Golden

[... snip vague question re AD user update ...]

... and please add a (useful) subject line

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


Re:

2009-04-21 Thread karlos barlos
ok sorry TIM 

I just took some piece of code  that ADDs users to AD 

CODE
 import win32com,win32com.client
    def add_acct(location,account):
  ad_obj=win32com.client.GetObject(location)

  ad_user=ad_obj.Create('user','cn='+user['login'])
  ad_user.Put('sAMAccountName',user['login'])
  ad_user.Put('userPrincipalName',user['login']+'@email.address.com')
  ad_user.Put('DisplayName',user['last']+' '+user['first']) #fullname
  ad_user.Put('givenName',user['first'])
  ad_user.Put('sn',user['last'])
  ad_user.Put('description','regular account')
  ad_user.Put('physicalDeliveryOfficeName','office 1')
  ad_user.Put('HomeDirectory',r'\\server1\ '[:-1]+user['login']) 
  ad_user.Put('HomeDrive','H:')
  ad_user.SetInfo();ad_user.GetInfo()
  ad_user.LoginScript='login.bat'
  ad_user.AccountDisabled=0
  pas = raw_input(\nChoose PaSSword..:)
  ad_user.setpassword(pas)
  ad_user.Put('pwdLastSet',0) #-- force reset of password
  ad_user.SetInfo()

    very = raw_input(\nWhat OU To Place User...?:)
    location=(LDAP://ou=%s,dc=shay,dc=com %  very)
    name = raw_input(\nEnter The First Name...:)
    last = raw_input(\nEnter The Last Name:)
    log = raw_input(\nEnter LOGON na...@...:)
    user={'first':(name),'last':(last),'login':(log)}
    add_acct(location,user)

    

I HAVE been playing around setting up input fields for the user to fill out

im just having problems withe
dom = raw_input(the domain name)
 ad_user.Put('userPrincipalName',user['login']+'@ [(dom]')

can you point to a good ref ?
PS  i think this uses the com moudle




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


Re: not homework... something i find an interesting problem

2009-04-21 Thread MRAB

Trip Technician wrote:

Thank you Dave. This does it but slowly. takes every subset of the
list a of squares, and then gets a 'partition' that will work, many
are very inefficient (with lots of 1s).

any hints about how to speed up ?


def subset(x):
for z in range(1,2**len(x)):
q=bin(z)
subs=[]
for dig in range(len(q)):
if q[dig]=='1':
subs.append(x[dig])
yield subs

def bin(x):
  q=
  while x=1:
q+=str(x%2)
x//=2
  return q



def squ(z,b):
if z==0:
return 0
for x in b:
if z=x:
return x,squ(z-x,b)


def flatten(lst):
for elem in lst:
if type(elem) in (tuple, list):
for i in flatten(elem):
yield i
else:
yield elem



sizelim=150

a=[x**2 for x in range(int(sizelim**0.5),1,-1)]

q,r=[],[]

for aa in range(sizelim):
r.append([])


for xx in range(1,sizelim):
for z in subset(a):
q=[]
z.append(1)
for rr in flatten(squ(xx,z)):
if rr !=0:
q.append(rr)
item=[len(q),q]
if item not in r[xx]:
r[xx].append(item)
r[xx].sort()

for eee in r:
if eee:
print r.index(eee),eee[0:3]


Even this code doesn't find them all! For 135 it finds [49, 49, 36, 1],
[81, 25, 25, 4] and [81, 36, 9, 9], but not [121, 9, 4, 1].
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyGUI 2.0.4

2009-04-21 Thread Kent Johnson
On Apr 21, 8:05 am, Greg Ewing greg.ew...@canterbury.ac.nz wrote:
 PyGUI 2.0.4 is available:

    http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

 Fixes a few more bugs and hopefully improves things
 on Windows, although I can't be sure it will fix all
 the Windows problems people are having, because I
 haven't been able to reproduce some of them.

There is still a problem with unhandled WM_MOUSELEAVE events on WinXP/
Python 2.5. For example,
- run blobedit.py
- add a blob
- quit the app; the Save Changes dialog appears
- mouse over one of the buttons, then off the button to get this
error:

Traceback (most recent call last):
  File C:\Downloads\PyGUI-2.0.4\GUI\Win32\Components.py, line 208,
in _win_event_message
event = win_message_to_event(message, self)
  File C:\Downloads\PyGUI-2.0.4\GUI\Win32\Events.py, line 65, in
win_message_to_event
kind, button = win_message_map[msg]
KeyError: 675

Adding this line to win_message_map in GUI/Win32/Events.py seems to
fix it:
wc.WM_MOUSELEAVE: ('mouse_leave', None),

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


Re: and [True,True] -- [True, True]?????

2009-04-21 Thread Grant Edwards
On 2009-04-21, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote:

 No matter what x is (excluding buggy classes), if x means
 test whether x is true in a boolean context.

 If x happens to be a list, that means x is empty. If x is a
 float, it means x is positive or negative zero.

I think you've got your true/false cases flipped...

-- 
Grant Edwards   grante Yow! I want my nose in
  at   lights!
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Special Thanks

2009-04-21 Thread Aahz
In article slrnguqvne.eol.n...@irishsea.home.craig-wood.com,
Nick Craig-Wood  n...@craig-wood.com wrote:

Python also converted me to using unit tests.  If you add unit tests
into your methodology above then when you re-organize (or refactor to
use the modern jargon) the code you can be 100% sure that you didn't
break anything which is a wonderful feeling.

Not quite: you can be 100% sure you didn't break anything you had
appropriate tests for.  If you use pure TDD (test-driven development),
you can be pretty close to 100% comfortable, but my impression is that
few people do pure TDD.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: sorting two corresponding lists?

2009-04-21 Thread 邓弈龙
solution by 
jadec.se...@gmail.commhtml:{154E1F55-D942-4CE9-9B8C-82060E1E80CE}mid://0047/!x-usc:mailto:jadec.se...@gmail.com,
China

values,items = zip( *sorted( zip (values,items)))

- Original Message -
From: Esmail 
ebo...@hotmail.commhtml:{154E1F55-D942-4CE9-9B8C-82060E1E80CE}mid://0047/!x-usc:mailto:ebo...@hotmail.com

To: 
python-list@python.orgmhtml:{154E1F55-D942-4CE9-9B8C-82060E1E80CE}mid://0047/!x-usc:mailto:python-list@python.org

Sent: Tuesday, April 21, 2009 12:10 AM
Subject: sorting two corresponding lists?


 Hello all,

 I wonder if someone could help me with sorting two corresponding lists.

 For instance the first list contains some items, and the second list
 contains their value (higher is better)

 items = [apple, car, town, phone]
 values = [5, 2, 7, 1]

 I would like to sort the 'items' list based on the 'values' list so
 that I end up with the following two list:

 items = [town, apple, car, phone]
 values = [7, 5, 2, 1]

 So I would like to keep the corresponding value still corresponding
 after the sorting.

 Is there an easy/nice/Pythonic way to do this?

 Thanks,
 Esmail

 --
 http://mail.python.org/mailman/listinfo/python-listmhtml:{154E1F55-D942-4CE9-9B8C-82060E1E80CE}mid://0047/!x-usc:http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Re: not homework... something i find an interesting problem

2009-04-21 Thread Trip Technician
On 21 Apr, 14:46, MRAB goo...@mrabarnett.plus.com wrote:
 Trip Technician wrote:
  Thank you Dave. This does it but slowly. takes every subset of the
  list a ofsquares, and then gets a 'partition' that will work, many
  are very inefficient (with lots of 1s).

  any hints about how to speed up ?

  def subset(x):
      for z in range(1,2**len(x)):
          q=bin(z)
          subs=[]
          for dig in range(len(q)):
              if q[dig]=='1':
                  subs.append(x[dig])
          yield subs

  def bin(x):
    q=
    while x=1:
      q+=str(x%2)
      x//=2
    return q

  def squ(z,b):
      if z==0:
          return 0
      for x in b:
          if z=x:
              return x,squ(z-x,b)

  def flatten(lst):
      for elem in lst:
          if type(elem) in (tuple, list):
              for i in flatten(elem):
                  yield i
          else:
              yield elem

  sizelim=150

  a=[x**2 for x in range(int(sizelim**0.5),1,-1)]

  q,r=[],[]

  for aa in range(sizelim):
      r.append([])

  for xx in range(1,sizelim):
      for z in subset(a):
          q=[]
          z.append(1)
          for rr in flatten(squ(xx,z)):
              if rr !=0:
                  q.append(rr)
          item=[len(q),q]
          if item not in r[xx]:
              r[xx].append(item)
              r[xx].sort()

  for eee in r:
      if eee:
              print r.index(eee),eee[0:3]

 Even this code doesn't find them all! For 135 it finds [49, 49, 36, 1],
 [81, 25, 25, 4] and [81, 36, 9, 9], but not [121, 9, 4, 1].- Hide quoted text 
 -

 - Show quoted text -

blowed if i know why that is !
--
http://mail.python.org/mailman/listinfo/python-list


Re: and [True,True] -- [True, True]?????

2009-04-21 Thread Peter Pearson
On 21 Apr 2009 03:06:40 GMT, Steven D'Aprano wrote:
 On Mon, 20 Apr 2009 15:53:41 +, Peter Pearson wrote:

 Like Gerhard, I prefer the construction that explicitly says, This is a
 list, and this is what I'll do if it's not empty.  To me, and I suspect
 to a great many programmers, if x: does *not* mean if x is not
 empty, it means if x is (in some sense) True, including the
 possibility that x is an object from which a True or False value must be
 extracted by means that might not be at all obvious.

 That's *exactly* what it means. This is a feature, not a bug.

 No matter what x is (excluding buggy classes), if x means test whether 
 x is true in a boolean context.

 If x happens to be a list, that means x is empty. If x is a float, it 
 means x is positive or negative zero. If x is a phlange, it means the 
 doofer is unset or it has more than three frobs.

 You shouldn't care exactly why x is true or false, only that it is. Why 
 should you have to manually count the frobs when the class can do it for 
 you?

That whimsical example is surprisingly persuasive for me.


 For an object
 lesson in the perils of said extraction, see the recent thread on
 [False,True] and [True,True] == [True,True].

 That would be this thread :)

Oh, dear.  Indeed, it is exactly this increasing scarcity of
at-hand working memory that makes me resist non-obvious features
in programming languages.  Perhaps it's time to take up golf.

-- 
To email me, substitute nowhere-spamcop, invalid-net.
--
http://mail.python.org/mailman/listinfo/python-list


Export variables

2009-04-21 Thread msolem
Hello,

I want to make a certain subset of public attributes available through
an interface.

The client should not need to know the names of the attributes.

Here is some code with the important parts missing.  Anyone care to
fill in the missing parts?


class C:
def __init__(self):
self.a = 4
self.b = 6
self.c = 8
self._set_vars([self.a, self.b])  # This call might need to be
done differently

def get_vars(self):
# add code here...

def _set_vars(self, vars):
# add code here...


c = C()
print c.get_vars()
c.a = 9
print c.get_vars()


This is the desired output
[4, 6]   # Values of c.a and c.b
[9, 6]   # Values of c.a and c.b

The important part is that the change to c.a is reflected in the call
to get_vars().  get_vars() and _set_vars() might be moved to a base
class,
and therefore should not have attribute names hard coded in them.

I don't have a specific problem that I'm trying to solve.  I would
just like
to know how this sort of thing could be done.

Thanks,
Mike
--
http://mail.python.org/mailman/listinfo/python-list


execfile (exec?) create non consistent locals() state

2009-04-21 Thread Doron Tal
Hi,

Recently I tried to execute a python file using execfile (exec performed
just the same for that reason).
I encountered the behavior below:


$ cat execme.py
a = 2
$ python
Python 2.4.3 (#1, May 24 2008, 13:57:05)
[GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
Type help, copyright, credits or license for more information.
 def execfile_func():
... execfile('execme.py')
... print 'locals() = %s' % str(locals())
... print a
...
 execfile_func()
locals() = {'a': 2}
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 4, in execfile_func
NameError: global name 'a' is not defined



After execfile, the a variable can be found in locals(), however any direct
reference (e.g., print a) fails.
Is it expected?

Thanks,
Doron
--
http://mail.python.org/mailman/listinfo/python-list


Re: sorting two corresponding lists?

2009-04-21 Thread tiefeng wu

 Esmail wrote:

  items = [apple, car, town, phone]
  values = [5, 2, 7, 1]
 
  I would like to sort the 'items' list based on the 'values' list so
  that I end up with the following two list:
 
  items = [town, apple, car, phone]
  values = [7, 5, 2, 1]


My solution, I know the 'zip' version is more elegant, this is just for
fun:)

 items = ['apple', 'car', 'town', 'phone']
 values = [5, 2, 7, 1]
 new_values = sorted(values, reverse = True)
 new_items = [items[x] for x in [i for i in map(values.index,
new_values)]]
 print(new_values)
[7, 5, 2, 1]
 print(new_items)
['town', 'apple', 'car', 'phone']


cheers!

tiefeng wu
2009-04-22
--
http://mail.python.org/mailman/listinfo/python-list


Re:

2009-04-21 Thread Tim Golden

karlos barlos wrote:
ok sorry TIM 

I just took some piece of code  that ADDs users to AD 


CODE
 import win32com,win32com.client
def add_acct(location,account):
  ad_obj=win32com.client.GetObject(location)

  ad_user=ad_obj.Create('user','cn='+user['login'])
  ad_user.Put('sAMAccountName',user['login'])
  ad_user.Put('userPrincipalName',user['login']+'@email.address.com')
  ad_user.Put('DisplayName',user['last']+' '+user['first']) #fullname
  ad_user.Put('givenName',user['first'])
  ad_user.Put('sn',user['last'])
  ad_user.Put('description','regular account')
  ad_user.Put('physicalDeliveryOfficeName','office 1')
  ad_user.Put('HomeDirectory',r'\\server1\ '[:-1]+user['login']) 
  ad_user.Put('HomeDrive','H:')

  ad_user.SetInfo();ad_user.GetInfo()
  ad_user.LoginScript='login.bat'
  ad_user.AccountDisabled=0
  pas = raw_input(\nChoose PaSSword..:)
  ad_user.setpassword(pas)
  ad_user.Put('pwdLastSet',0) #-- force reset of password
  ad_user.SetInfo()


Get hold of this:

 http://timgolden.me.uk/python/active_directory.html

and then try something like this:

code
import active_directory

ad = active_directory.AD ()
ou = ad.find_ou (it) # or wherever

user = active_directory.AD_object (ou.Create (user, cn='tjg')
user.sAMAccountname = timgolden
user.givenName = Tim
#
# etc.
#

#
# or
#
user.set (
 sAMAccountName = timgolden,
 givenName = Tim,
 # etc.
)

/code



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


Python winappdbg module v1.0 is out!

2009-04-21 Thread Mario Alejandro Vilas Jerez
What is winappdbg?
==

The winappdbg python module allows developers to quickly code
instrumentation scripts in Python under a Windows environment.

It uses ctypes to wrap many Win32 API calls related to debugging, and
provides an object-oriented abstraction layer to manipulate threads,
libraries and processes, attach your script as a debugger, trace
execution, hook API calls, handle events in your debugee and set
breakpoints of different kinds (code, hardware and memory).
Additionally it has no native code at all, making it easier to
maintain or modify than other debuggers on Windows.

The intended audience are QA engineers and software security auditors
wishing to test / fuzz Windows applications with quickly coded Python
scripts. Several ready to use utilities are shipped and can be used
for this purposes.

Current features also include disassembling x86 native code (using the
open source diStorm project, see http://ragestorm.net/distorm/),
debugging multiple processes simultaneously and produce a detailed log
of application crashes, useful for fuzzing and automated testing.


Where can I find winappdbg?
===

The winappdbg project is currently hosted at Sourceforge, and can be found at:

    http://winappdbg.sourceforge.net/
--
http://mail.python.org/mailman/listinfo/python-list


SqlAlchemy and mssqlserver

2009-04-21 Thread Stefano

Using sqlalchemy with pyodbc and mssqlserver
Why sa always generate identity ?

many thanks here the sample

tb = Table('prova',meta,Column('chiave', Integer, primary_key=True))
tb.create()

CREATE TABLE prova (
chiave INTEGER NOT NULL IDENTITY(1,1), 
PRIMARY KEY (chiave)

)


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


Re: Export variables

2009-04-21 Thread Diez B. Roggisch
mso...@linuxmail.org wrote:

 Hello,
 
 I want to make a certain subset of public attributes available through
 an interface.
 
 The client should not need to know the names of the attributes.
 
 Here is some code with the important parts missing.  Anyone care to
 fill in the missing parts?
 
 
 class C:
 def __init__(self):
 self.a = 4
 self.b = 6
 self.c = 8
 self._set_vars([self.a, self.b])  # This call might need to be
 done differently
 
 def get_vars(self):
 # add code here...
 
 def _set_vars(self, vars):
 # add code here...
 
 
 c = C()
 print c.get_vars()
 c.a = 9
 print c.get_vars()
 
 
 This is the desired output
 [4, 6]   # Values of c.a and c.b
 [9, 6]   # Values of c.a and c.b
 
 The important part is that the change to c.a is reflected in the call
 to get_vars().  get_vars() and _set_vars() might be moved to a base
 class,
 and therefore should not have attribute names hard coded in them.
 
 I don't have a specific problem that I'm trying to solve.  I would
 just like
 to know how this sort of thing could be done.

I'd do it roughly like this:

class Base(object):

EXPORTED_VARIABLES = []


def get_vars(self):
all_variables = set(sum((getattr(cls, EXPORTED_VARIABLES, []) for
cls in self.__class__.mro()), []))
for varname in all_variables:
yield getattr(self, varname)


class A(Base):

EXPORTED_VARIABLES = [a]

a = A!


class B(Base):

EXPORTED_VARIABLES = [b]

b = B!


class C(A,B):
pass


a = A()
b = B()
c = C()

print list(a.get_vars())
print list(b.get_vars())
print list(c.get_vars())

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


Re: sorting two corresponding lists?

2009-04-21 Thread nathanielpeterson08

From http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys, using the 
Decorate-Sort-Undecorate (aka Schwartzian transform) idiom:

#!/usr/bin/env python
items = ['apple', 'car', 'town', 'phone']
values = [5, 2, 7, 1]
zipped=zip(values,items)
zipped.sort(reverse=True)
values_sorted,items_sorted=zip(*zipped)
print values_sorted
# (7, 5, 2, 1)
print items_sorted
# ('town', 'apple', 'car', 'phone')
--
http://mail.python.org/mailman/listinfo/python-list


using python logo at startup

2009-04-21 Thread Dhruv
Is there a way to display/flash python powered logo for like 2
seconds at startup of a helloworld application?

Well actually I have an application that takes data from an excel file
and generates a kml file and opens it up with google earth. All this
is compiled in an exe file using py2exe. Now I just want to display
the python logo before the actual script starts. Just for the sake of
informing the user that this application was made using python.

Is this possible?
--
http://mail.python.org/mailman/listinfo/python-list


Re: not homework... something i find an interesting problem

2009-04-21 Thread MRAB

Trip Technician wrote:

On 21 Apr, 14:46, MRAB goo...@mrabarnett.plus.com wrote:

Trip Technician wrote:

Thank you Dave. This does it but slowly. takes every subset of the
list a ofsquares, and then gets a 'partition' that will work, many
are very inefficient (with lots of 1s).
any hints about how to speed up ?
def subset(x):
for z in range(1,2**len(x)):
q=bin(z)
subs=[]
for dig in range(len(q)):
if q[dig]=='1':
subs.append(x[dig])
yield subs
def bin(x):
  q=
  while x=1:
q+=str(x%2)
x//=2
  return q
def squ(z,b):
if z==0:
return 0
for x in b:
if z=x:
return x,squ(z-x,b)
def flatten(lst):
for elem in lst:
if type(elem) in (tuple, list):
for i in flatten(elem):
yield i
else:
yield elem
sizelim=150
a=[x**2 for x in range(int(sizelim**0.5),1,-1)]
q,r=[],[]
for aa in range(sizelim):
r.append([])
for xx in range(1,sizelim):
for z in subset(a):
q=[]
z.append(1)
for rr in flatten(squ(xx,z)):
if rr !=0:
q.append(rr)
item=[len(q),q]
if item not in r[xx]:
r[xx].append(item)
r[xx].sort()
for eee in r:
if eee:
print r.index(eee),eee[0:3]

Even this code doesn't find them all! For 135 it finds [49, 49, 36, 1],
[81, 25, 25, 4] and [81, 36, 9, 9], but not [121, 9, 4, 1].- Hide quoted text -

- Show quoted text -


blowed if i know why that is !


I think I might have cracked it:

import math

def sumsq(n):
if n == 0:
return [[]]
root = int(math.sqrt(n))
square = root ** 2
sums = [[square] + s for s in sumsq(n - square)]
while root  1:
root -= 1
square = root ** 2
if square  n // len(sums[0]):
break
more_sums = [[square] + s for s in sumsq(n - square)]
if len(more_sums[0]) == len(sums[0]):
sums.extend(more_sums)
return sums

for n in range(1, 150):
# Find all the possible sums.
sums = sumsq(n)
# Create a set of the unique combinations.
sums = set(tuple(sorted(s, reverse=True)) for s in sums)
# Convert back to a list of lists.
sums = [list(s) for s in sorted(sums, reverse=True)]
print n, sums

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


Re:

2009-04-21 Thread Andre Engels
On Tue, Apr 21, 2009 at 3:00 PM, karlos barlos karlosbar...@yahoo.com wrote:
 hello to everybody...

 having problem withe this code :

 dom = raw_input(The Domain name..:)
   ad_user.Put('userPrincipalName',user['login']+'@(['dom'])

 but it wont change whay ?

Well, you don't tell what ad_user is, and its Put method, but what I
do see is that there are 7 single quotes in this line - given that
each single quote seems to be starting or ending a string, there
should be an even number of them.



-- 
André Engels, andreeng...@gmail.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python and Basic?

2009-04-21 Thread Mensanator
On Apr 21, 5:37 am, Ivan Illarionov ivan.illario...@gmail.com wrote:
 On Apr 18, 3:39 pm, BJörn Lindqvist bjou...@gmail.com wrote:

  I first started programming basic and i don't think it has hurt me much.

  I can somewhat sympathise with the op, neither python nor any other
  mainstream language can still do this:

  SCREEN 13
  PSET 160,100,255

 This is not true. It's trivial with pygame or equivalent SDL
 bindings in other mainstream languages:

 basic.py:
 ---­
 import sys
 import pygame

 class BasicInterpreter:
     def SCREEN(self, x):
         self.surface = pygame.display.set_mode(
             (320, 200), pygame.FULLSCREEN, 8)

     def PSET(self, x, y, c):
         self.surface.set_at((x, y), c)
         pygame.display.flip()

 if __name__ == '__main__' and len(sys.argv)  1:
     basic = BASIC()
     with open(sys.argv[1]) as bas:
         for line in bas:
             eval(basic.%s(%s) % tuple(x.strip() for x in line.split
 (' ', 1)))
     while True:
         for event in pygame.event.get():
             if event.type in (pygame.QUIT, pygame.KEYDOWN):
                 sys.exit(0)

 ---­

 This will execute your BASIC program.

And you did it without Goto? Wow.


 --
 Ivan

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


Re: Python interpreter speed

2009-04-21 Thread Fabio Zadrozny
 Further, I have an accounting software which was previously in java, but
 now in python and the performance gain is ausom.

 Yes it depends on how we write the code but comparing the 2 at least at
 the middle layer and front-end (pygtk) python is faster than java.
 Infact I am most certain that swing is not even 50% as fast as pygtk or
 pyqt.

Actually, pygtk and pyqt are mostly wrappers for c/c++ code (wrapping
c/c++ is much easier in python than in java... so, that example ends
up comparing java to c/c++ and not python).

Java is usually faster in general (because of the many optimizations
SUN did in the Java VM through many JIT techniques), although it has a
slower startup time (which is a drawback of that same JIT), so, some
applications can actually be faster in python just because of the
faster startup time (like command line utilities), but for
applications that keep running for more time, Java is usually faster
-- even more if you don't  use a mix of python and c/c++.

Still, as you noted, if you take into account that you can rewrite
your slow parts of the application in a faster language and just make
python bindings for it, that advantage is largely diminished (while
still having a fast startup time), and as you profile you can see that
it's usually just 1% of the application that takes up 90% of the time.
So, it's not a major drawback, and if you develop faster in python
then it's worth it... (but I'd hardly say that rewriting from java to
python will make it faster... if it becomes faster it's because you
used better algorithms).

Anyways, a program is usually faster/slower because of your choice of
program structure and algorithms and not because of the speed of the
language anyways.

Cheers,

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


Re: who is calling the base class __new__ method

2009-04-21 Thread Aahz
In article gskaq4$uhp$0...@news.t-online.com,
Andreas Otto  aotto1...@onlinehome.de wrote:

   Question: What is the difference between these both functions
and why is one working and the other not ?

If you don't get an answer here, try capi-sig.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: using python logo at startup

2009-04-21 Thread Mike Driscoll
On Apr 21, 11:46 am, Dhruv dhruv.howud...@gmail.com wrote:
 Is there a way to display/flash python powered logo for like 2
 seconds at startup of a helloworld application?

 Well actually I have an application that takes data from an excel file
 and generates a kml file and opens it up with google earth. All this
 is compiled in an exe file using py2exe. Now I just want to display
 the python logo before the actual script starts. Just for the sake of
 informing the user that this application was made using python.

 Is this possible?

Sure. You just need to pick a GUI toolkit and have it display a
picture for a few seconds and then disappear. wxPython has a built-in
splash screen widget made for just this purpose. Tkinter may too, or
you could just roll your own in it.

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


Re: not homework... something i find an interesting problem

2009-04-21 Thread bearophileHUGS
MRAB:
 I think I might have cracked it:
 ...
      print n, sums

Nice.
If you don't want to use dynamic programming, then add a @memoize
decoration before the function, using for example my one:
http://code.activestate.com/recipes/466320/

And you will see an interesting speed increase, even if you don't use
Psyco ;-)

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Python, MS SQL, and batch inserts

2009-04-21 Thread ericwoodworth
Hi,
 I have a python script I'm writing that grabs some data from a
com object, does a little formatting, and then inserts that data into
a MS SQL 2003 DB.  Because I'm using COM objects I'm importing
win32com.client.  That also allows me to use ADODB.connection and
ADODB.command objects for working with SQL.

 The program works fine but it's a little slow.  Inserting ~5500
rows of data takes about 10 seconds using a DB that is on the same
machine running the script.

 I've done some general searches on how to speed this up and in
other languages people suggest sending batches of inserts off at a
time instead of executing 1 insert at a time.  For java and .net
people recommend using a stringbuilder function to create strings
quickly.  I don't know of such a function in python s I tried grouping
my inserts into a single string using string += syntax.  I knew that
would be terrible but I wanted to see how terrible.  Final reults: It
was pretty terrible.  Script went from taking ~18sec to taking
240sec.  The overhead for recreating the strings was monster.  No real
surprise there.

 So I then loaded up the commands into a list and at the end I
used the strong join method to create the string.  This was far faster
than using += to create my strings but still took twice as long as
just running my inserts one at a time.  So I'm looking for
suggestions.

 Basically I have 5000 SQL inserts that I want to do as quickly as
possible.  This is purely academic as I can live with the 18 seconds
the script needs to run (9 to talk to the com object and format the
data and 10 to write to SQL) but I'm still curious how to improve on
what I have running.

Thanks in advance for any help,
Eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: execfile (exec?) create non consistent locals() state

2009-04-21 Thread Chris Rebert
On Tue, Apr 21, 2009 at 9:08 AM, Doron Tal doron.tal.l...@gmail.com wrote:
 Hi,

 Recently I tried to execute a python file using execfile (exec performed
 just the same for that reason).
 I encountered the behavior below:

 
 $ cat execme.py
 a = 2
 $ python
 Python 2.4.3 (#1, May 24 2008, 13:57:05)
 [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
 Type help, copyright, credits or license for more information.
 def execfile_func():
 ... execfile('execme.py')
 ... print 'locals() = %s' % str(locals())
 ... print a
 ...
 execfile_func()
 locals() = {'a': 2}
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File stdin, line 4, in execfile_func
 NameError: global name 'a' is not defined

 

 After execfile, the a variable can be found in locals(), however any direct
 reference (e.g., print a) fails.
 Is it expected?

Yes. See http://docs.python.org/library/functions.html#locals (emphasis mine):

locals()
[...]
Warning: The contents of this dictionary should not be modified;
***changes may not affect the values of local variables used by the
interpreter***.
[...]

Cheers,
Chris
-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python, MS SQL, and batch inserts

2009-04-21 Thread Philip Semanchuk


On Apr 21, 2009, at 2:02 PM, ericwoodwo...@gmail.com wrote:


Hi,
I have a python script I'm writing that grabs some data from a
com object, does a little formatting, and then inserts that data into
a MS SQL 2003 DB.  Because I'm using COM objects I'm importing
win32com.client.  That also allows me to use ADODB.connection and
ADODB.command objects for working with SQL.

The program works fine but it's a little slow.  Inserting ~5500
rows of data takes about 10 seconds using a DB that is on the same
machine running the script.

I've done some general searches on how to speed this up and in
other languages people suggest sending batches of inserts off at a
time instead of executing 1 insert at a time.  For java and .net
people recommend using a stringbuilder function to create strings
quickly.  I don't know of such a function in python s I tried grouping
my inserts into a single string using string += syntax.  I knew that
would be terrible but I wanted to see how terrible.  Final reults: It
was pretty terrible.  Script went from taking ~18sec to taking
240sec.  The overhead for recreating the strings was monster.  No real
surprise there.

So I then loaded up the commands into a list and at the end I
used the strong join method to create the string.  This was far faster
than using += to create my strings but still took twice as long as
just running my inserts one at a time.  So I'm looking for
suggestions.

Basically I have 5000 SQL inserts that I want to do as quickly as
possible.  This is purely academic as I can live with the 18 seconds
the script needs to run (9 to talk to the com object and format the
data and 10 to write to SQL) but I'm still curious how to improve on
what I have running.


Are you sure your logjam is in Python? Inserting 5500 rows can take a  
few seconds if you're COMMITting after each INSERT. Wrap the whole  
thing in an explicit transaction and see if that helps.


Also, toss in a few print statements containing timestamps so you know  
more about where the script is spending time.



bye
Philip

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


Re: execfile (exec?) create non consistent locals() state

2009-04-21 Thread Doron Tal
On Tue, Apr 21, 2009 at 9:13 PM, Chris Rebert c...@rebertia.com wrote:

 On Tue, Apr 21, 2009 at 9:08 AM, Doron Tal doron.tal.l...@gmail.com
 wrote:
  Hi,
 
  Recently I tried to execute a python file using execfile (exec performed
  just the same for that reason).
  I encountered the behavior below:
 
  
  $ cat execme.py
  a = 2
  $ python
  Python 2.4.3 (#1, May 24 2008, 13:57:05)
  [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  Type help, copyright, credits or license for more information.
  def execfile_func():
  ... execfile('execme.py')
  ... print 'locals() = %s' % str(locals())
  ... print a
  ...
  execfile_func()
  locals() = {'a': 2}
  Traceback (most recent call last):
File stdin, line 1, in ?
File stdin, line 4, in execfile_func
  NameError: global name 'a' is not defined
 
  
 
  After execfile, the a variable can be found in locals(), however any
 direct
  reference (e.g., print a) fails.
  Is it expected?

 Yes. See http://docs.python.org/library/functions.html#locals (emphasis
 mine):

 locals()
[...]
Warning: The contents of this dictionary should not be modified;
 ***changes may not affect the values of local variables used by the
 interpreter***.
[...]

 Cheers,
 Chris
 --
 I have a blog:
 http://blog.rebertia.com

(Chris - sorry for the multiple replies, I forgot to reply all)

I actually did not attempt to modify this dictionary (the one which locals()
returns) explicitly.
The simplest assignment command, such as 'a = 2' modifies this dictionary
implicitly, and it's working perfectly well.
I expected exec to work the same, but apparently I was wrong. Is there is a
way to exec a file more correctly? thus avoid the need to resort to
awkward solutions such as using the locals() dictionary?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python, MS SQL, and batch inserts

2009-04-21 Thread ericwoodworth
On Apr 21, 2:15 pm, Philip Semanchuk phi...@semanchuk.com wrote:
 On Apr 21, 2009, at 2:02 PM, ericwoodwo...@gmail.com wrote:



  Hi,
      I have a python script I'm writing that grabs some data from a
  com object, does a little formatting, and then inserts that data into
  a MS SQL 2003 DB.  Because I'm using COM objects I'm importing
  win32com.client.  That also allows me to use ADODB.connection and
  ADODB.command objects for working with SQL.

      The program works fine but it's a little slow.  Inserting ~5500
  rows of data takes about 10 seconds using a DB that is on the same
  machine running the script.

      I've done some general searches on how to speed this up and in
  other languages people suggest sending batches of inserts off at a
  time instead of executing 1 insert at a time.  For java and .net
  people recommend using a stringbuilder function to create strings
  quickly.  I don't know of such a function in python s I tried grouping
  my inserts into a single string using string += syntax.  I knew that
  would be terrible but I wanted to see how terrible.  Final reults: It
  was pretty terrible.  Script went from taking ~18sec to taking
  240sec.  The overhead for recreating the strings was monster.  No real
  surprise there.

      So I then loaded up the commands into a list and at the end I
  used the strong join method to create the string.  This was far faster
  than using += to create my strings but still took twice as long as
  just running my inserts one at a time.  So I'm looking for
  suggestions.

      Basically I have 5000 SQL inserts that I want to do as quickly as
  possible.  This is purely academic as I can live with the 18 seconds
  the script needs to run (9 to talk to the com object and format the
  data and 10 to write to SQL) but I'm still curious how to improve on
  what I have running.

 Are you sure your logjam is in Python? Inserting 5500 rows can take a  
 few seconds if you're COMMITting after each INSERT. Wrap the whole  
 thing in an explicit transaction and see if that helps.

 Also, toss in a few print statements containing timestamps so you know  
 more about where the script is spending time.

 bye
 Philip

I'm not 100% sure it's python and not SQL but I do suspect there's a
better way to do this than just serial inserts.  I could be wrong
about that which is what i'm trying to explore.
I already do use the time stamps and this is what I see:
at 9 secs in I've gotten my data, formatted it, and placed it on the
list
at 9.047 secs in the string.join() is done and I have my command
string
at 35 secs the program ends.  So somehow my SQL is taking a lot longer
when I format it as single string.

How would I make the whole thing one transaction?  Just insert BEGIN
TRANSACTION at the start and COMMIT at the end?  Is that enough to do
it?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python interpreter speed

2009-04-21 Thread Terry Reedy

Fabio Zadrozny wrote:

Further, I have an accounting software which was previously in java, but
now in python and the performance gain is ausom.

Yes it depends on how we write the code but comparing the 2 at least at
the middle layer and front-end (pygtk) python is faster than java.
Infact I am most certain that swing is not even 50% as fast as pygtk or
pyqt.


Actually, pygtk and pyqt are mostly wrappers for c/c++ code (wrapping
c/c++ is much easier in python than in java... so, that example ends
up comparing java to c/c++ and not python).


Well, in CPython, the whole builtin module is a wrapper for a bunch of C 
 coded functions, so one could say much the same thing about any Python 
program.  The real point to me is that one cannot compare the running 
speed of abstract languages, only that of concrete implementations.  One 
can, however, compare the speed of writing equivalent code in various 
languages.


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


Re: execfile (exec?) create non consistent locals() state

2009-04-21 Thread Chris Rebert
On Tue, Apr 21, 2009 at 11:25 AM, Doron Tal doron.tal.l...@gmail.com wrote:
 On Tue, Apr 21, 2009 at 9:13 PM, Chris Rebert c...@rebertia.com wrote:

 On Tue, Apr 21, 2009 at 9:08 AM, Doron Tal doron.tal.l...@gmail.com
 wrote:
  Hi,
 
  Recently I tried to execute a python file using execfile (exec performed
  just the same for that reason).
  I encountered the behavior below:
 
  
  $ cat execme.py
  a = 2
  $ python
  Python 2.4.3 (#1, May 24 2008, 13:57:05)
  [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  Type help, copyright, credits or license for more information.
  def execfile_func():
  ... execfile('execme.py')
  ... print 'locals() = %s' % str(locals())
  ... print a
  ...
  execfile_func()
  locals() = {'a': 2}
  Traceback (most recent call last):
    File stdin, line 1, in ?
    File stdin, line 4, in execfile_func
  NameError: global name 'a' is not defined
 
  
 
  After execfile, the a variable can be found in locals(), however any
  direct
  reference (e.g., print a) fails.
  Is it expected?

 Yes. See http://docs.python.org/library/functions.html#locals (emphasis
 mine):

 locals()
    [...]
    Warning: The contents of this dictionary should not be modified;
 ***changes may not affect the values of local variables used by the
 interpreter***.
    [...]

 Cheers,
 Chris
 --
 I have a blog:
 http://blog.rebertia.com

 (Chris - sorry for the multiple replies, I forgot to reply all)

 I actually did not attempt to modify this dictionary (the one which locals()
 returns) explicitly.

Well, it can be reasonably inferred that execfile() does.

 The simplest assignment command, such as 'a = 2' modifies this dictionary
 implicitly, and it's working perfectly well.

While the exec'd file may run fine using the locals() dict (or any
dict for that matter), that doesn't say anything about whether the
changes to locals() will actually be reflected in the local namespace
it came from, which indeed, as documented, it's not. execfile() may
use the locals() dict for all its variable lookups, but the plain
toplevel interpreter is allowed not to.

 I expected exec to work the same, but apparently I was wrong. Is there is a
 way to exec a file more correctly? thus avoid the need to resort to
 awkward solutions such as using the locals() dictionary?

I don't know personally. Perhaps a kind soul will chime in.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Best Python Web Framework ?

2009-04-21 Thread SKYLAB
Greetings..

First , my english is not good .

I heard that was written in python ( Youtube Programming Language :
PYTHON :S ) Correct ?

That's not correct ? Then youtube is PHP application ?

That's correct ; Which python web framework in friendfeed ? Web.py ?
Django ? web2py ?

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


Re: Python, MS SQL, and batch inserts

2009-04-21 Thread Philip Semanchuk


On Apr 21, 2009, at 2:30 PM, ericwoodwo...@gmail.com wrote:



I'm not 100% sure it's python and not SQL but I do suspect there's a
better way to do this than just serial inserts.  I could be wrong
about that which is what i'm trying to explore.


I don't think the SQL standard provides a way to do bulk inserts and  
as a result most DB vendors have extended the standard to address this  
common need (e.g. the COPY command in Postgres).


If you're doing a mass insert to populate a blank table it also often  
helps to postpone index creation until after the table is populated.




I already do use the time stamps and this is what I see:
at 9 secs in I've gotten my data, formatted it, and placed it on the
list
at 9.047 secs in the string.join() is done and I have my command
string


You said you're inserting ~5500 rows, so are you calling .join() on a  
list of 5500 items? If so, 9 seconds seems painfully slow unless  
you're on old hardware.




at 35 secs the program ends.  So somehow my SQL is taking a lot longer
when I format it as single string.

How would I make the whole thing one transaction?  Just insert BEGIN
TRANSACTION at the start and COMMIT at the end?  Is that enough to do
it?


That's the basic idea, but your database adapter (i.e. the Python  
wrapper that talks to SQLServer)  might want you to do it another way.  
For instance, the connection object has a .commit() method and using  
that is probably a better ideal than calling cursor.execute(COMMIT).


Per the Python DB API, your connection should be opened in  
transactional mode by default. (Note that if the database supports an  
auto-commit feature, this must be initially off.)

http://www.python.org/dev/peps/pep-0249/

In other words, if you adapter is DB-API compliant then the only  
reason you're not using a transaction is because you're explicitly  
turning them off.




bye
P


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


Re: problem with PyMapping_SetItemString()

2009-04-21 Thread Stefan Behnel
rahul wrote:
 tatic PyObject *upadteCheck(PyObject *self,PyObject *args){
   PyObject *var_pyvalue=NULL,*newVar_pyvalue=NULL,*dict=NULL;
   char *varName;
 
   if (!PyArg_ParseTuple(args, s, varName)){
 return NULL;
   }
 dict=PyEval_GetLocals();
 var_pyvalue=PyMapping_GetItemString(dict,varName);
 
 if(inObject==NULL){
   dict=PyEval_GetGlobals();
   var_pyvalue=PyMapping_GetItemString(dict,varName);
 }

what's inObject?

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


Re: Best Python Web Framework ?

2009-04-21 Thread Stefan Behnel
Hi,

SKYLAB wrote:
 First , my english is not good .

Note that there are many python news groups and mailing lists. There may
also be one in your native language.

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


Please help me grok: webserver python

2009-04-21 Thread Phillip B Oldham
I'm having trouble grok'ing how to get python talking through a
webserver. I've got a lot of experience working with nginx+php-fcgi
(via a unix socket) and I'd like to know what would be the bare
minimum to get python talking in the same way.

Now, I've looked at modules like CherryPy but they're all a little
high level and talk via http. I'd like to know how to mimic the php
setup I'm used to; I've no specific goal other than to become
aquainted with the python environment.

Any examples would be great!
--
http://mail.python.org/mailman/listinfo/python-list


Re: generating random tuples in python

2009-04-21 Thread Robert Kern

On 2009-04-20 23:04, per wrote:


to be more formal by very different, i would be happy if they were
maximally distant in ordinary euclidean space... so if you just plot
the 3-tuples on x, y, z i want them to all be very different from each
other.  i realize this is obviously biased and that the tuples are not
uniformly distributed -- that's exactly what i want...

any ideas on how to go about this?


Perhaps it would help if you told us what application you are going to use them 
for? You can straightforwardly make a regular tetrahedral grid of points that 
fit in your box at whatever density you like. Which is more important: maximal 
(average) distance between neighbors or avoiding regularity? If you need to 
strike a balance between them, then you may want to look into low-discrepancy 
sequences:


  http://en.wikipedia.org/wiki/Low-discrepancy_sequence

--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: Python, MS SQL, and batch inserts

2009-04-21 Thread Scott David Daniels

Philip Semanchuk wrote:
... If you're doing a mass insert to populate a blank table it also often 
helps to postpone index creation until after the table is populated


I forget the name of the SQL Server bulk loader, but for large loads, I
used to populate a fresh table with the bulk data, then do UPDATEs and
INSERTs to get the data spread out into the main tables.  You (the OP)
might try a scheme like that.

--Scott David Daniels
scott.dani...@acm.org

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


Re: Best Python Web Framework ?

2009-04-21 Thread Wes James
On Tue, Apr 21, 2009 at 12:46 PM, SKYLAB zky...@gmail.com wrote:
 Greetings..

 First , my english is not good .

 I heard that was written in python ( Youtube Programming Language :
 PYTHON :S ) Correct ?

 That's not correct ? Then youtube is PHP application ?

 That's correct ; Which python web framework in friendfeed ? Web.py ?
 Django ? web2py ?



You'll need to do some homework to see what fits.

Here's a starter point:

http://wiki.python.org/moin/WebFrameworks

Try some or all.

I used perl for a long time, went looking for a framework, tried
django for a few days then found web2py and web2py fits for me.

good luck

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


Re: Passing all extra commandline arguments to python program, Optparse raises exception

2009-04-21 Thread Robert Kern

On 2009-04-16 19:32, Saptarshi wrote:

Saptarshi

Preprocess the sys.args before calling optparse.
Simply search sys.args for the string start and the string stop, and
note whichever comes first.  Then use slice operators to peel the extra
arguments off of sys.args.


Thanks, i implemented your logic. I thought there was a Optparse
feature to handle this.


There is:

  parser.allow_interspersed_args = False

This means that as soon as the parser hits start|stop, it assumes that 
everything following it is an argument and not an option that it needs to try to 
parse.


--
Robert Kern

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: Best Python Web Framework ?

2009-04-21 Thread SKYLAB
Thanks all post.

my english is not good . But techincal english very good. Anyway , i
understand english documents. That's not problem.


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


Re: Python, MS SQL, and batch inserts

2009-04-21 Thread ericwoodworth
On Apr 21, 3:36 pm, Scott David Daniels scott.dani...@acm.org wrote:
 Philip Semanchuk wrote:
  ... If you're doing a mass insert to populate a blank table it also often
  helps to postpone index creation until after the table is populated

 I forget the name of the SQL Server bulk loader, but for large loads, I
 used to populate a fresh table with the bulk data, then do UPDATEs and
 INSERTs to get the data spread out into the main tables.  You (the OP)
 might try a scheme like that.

 --Scott David Daniels
 scott.dani...@acm.org

Hmm..I think I'm going to move my question over to a SQL forum because
this is starting to feel like a SQL, rather than a python issue to me.

Three times now after letting the system rest where I go off an do
other things and then run my script it completes in 10 seconds.  If I
drop tables and start fresh immediately after that it takes 35
seconds.  If I drop the tables and wait an hour and then run the
script it'll finish in 10 seconds again.

That makes me think it's a SQL config or optimization issue more than
a python issue.

oh and the times I listed above were totals from the start of
execution so the string.join() was taking 0.047 seconds to run.  It
was taking 9 seconds to get my data from the com object and format it
but the join was quite fast.
--
http://mail.python.org/mailman/listinfo/python-list


Accessing items in nested tuples

2009-04-21 Thread alex
Hello everybody
I am able to access the data in a tuple via a for loop (see example
below).


#!/usr/bin/env python

class Test():
def Data(self):
return (aa, bb, cc, dd, ee, ff, gg, hh)
#return ((aa, (bb, cc, dd)), (ee, (ff, gg,
hh)), (ii, (jj, kk, ll)))

def Process(self):
for eachData in self.Data():
print Printing %s % eachData


def main():
print Start processing data
prtData=Test()
prtData.Process()
print Stop processing data


if __name__ == '__main__':
main()


However I do not find out how to access data items in a nested tuple
of
the type ((aa, (bb, cc, dd)), (ee, (ff, gg, hh)),...).
In fact I am trying to refactor a simple GUI basing on an example
in wxPython In Action, Listing 5.5 A refactored example where the
menues
are described in the way


def menuData(self):
return ((File,
(Open, Open in status bar, self.OnOpen),
(Quit, Quit, self.OnCloseWindow)),
(Edit,
(Copy, Copy, self.OnCopy),
(Cut, Cut, self.OnCut),
 ...)))

etc...


But I can not get the example running and I can't reprogram the
example to get it running for my case.

In IDLE I can print the individual tuples but not the items within.

IDLE 1.2.1
 data=((aa, (bb, cc, dd)), (ee, (ff, gg, hh)), (ii, (jj, 
 kk, ll)))
 print data[0]
('aa', ('bb', 'cc', 'dd'))
 print data[1]
('ee', ('ff', 'gg', 'hh'))
 etc...


I would like to be able to access the dataitem aa or bb, cc,
dd individualy.
For sure I am most probably missing something which is evident, maybe
can anybody help?
Thanks Alex

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


Re: Python, MS SQL, and batch inserts

2009-04-21 Thread ericwoodworth
On Apr 21, 4:01 pm, ericwoodwo...@gmail.com wrote:
 On Apr 21, 3:36 pm, Scott David Daniels scott.dani...@acm.org wrote:

  Philip Semanchuk wrote:
   ... If you're doing a mass insert to populate a blank table it also often
   helps to postpone index creation until after the table is populated

  I forget the name of the SQL Server bulk loader, but for large loads, I
  used to populate a fresh table with the bulk data, then do UPDATEs and
  INSERTs to get the data spread out into the main tables.  You (the OP)
  might try a scheme like that.

  --Scott David Daniels
  scott.dani...@acm.org

 Hmm..I think I'm going to move my question over to a SQL forum because
 this is starting to feel like a SQL, rather than a python issue to me.

 Three times now after letting the system rest where I go off an do
 other things and then run my script it completes in 10 seconds.  If I
 drop tables and start fresh immediately after that it takes 35
 seconds.  If I drop the tables and wait an hour and then run the
 script it'll finish in 10 seconds again.

 That makes me think it's a SQL config or optimization issue more than
 a python issue.

 oh and the times I listed above were totals from the start of
 execution so the string.join() was taking 0.047 seconds to run.  It
 was taking 9 seconds to get my data from the com object and format it
 but the join was quite fast.

Also if I restart SQL it will respond very quickly as well...down to
10 secs again.  Not sure why.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing items in nested tuples

2009-04-21 Thread Tim Chase

IDLE 1.2.1

data=((aa, (bb, cc, dd)), (ee, (ff, gg, hh)), (ii, (jj, kk, 
ll)))
print data[0]

('aa', ('bb', 'cc', 'dd'))

print data[1]

('ee', ('ff', 'gg', 'hh'))

etc...



I would like to be able to access the dataitem aa or bb, cc,
dd individualy.


You're so close:

   print data[0][0]
  'aa'
   print data[1][0]
  'ee'

-tkc


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


Re: SqlAlchemy and mssqlserver

2009-04-21 Thread Mike Driscoll
On Apr 21, 11:22 am, Stefano stef...@vulcanos.it wrote:
 Using sqlalchemy with pyodbc and mssqlserver
 Why sa always generate identity ?

 many thanks here the sample

 tb = Table('prova',meta,Column('chiave', Integer, primary_key=True))
 tb.create()

 CREATE TABLE prova (
  chiave INTEGER NOT NULL IDENTITY(1,1),
  PRIMARY KEY (chiave)
 )

 Stefano

Try re-posting to the SqlAlchemy mailing list. They'll be able to tell
you.

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


Re: not homework... something i find an interesting problem

2009-04-21 Thread MRAB

bearophileh...@lycos.com wrote:

MRAB:

I think I might have cracked it:
...
 print n, sums


Nice.
If you don't want to use dynamic programming, then add a @memoize
decoration before the function, using for example my one:
http://code.activestate.com/recipes/466320/

And you will see an interesting speed increase, even if you don't use
Psyco ;-)


I discovered I hadn't got it quite right (it still missed some). Here's
the fixed code:

import math

def sumsq(n, depth=0):
if n == 0:
return [[]]
root = int(math.sqrt(n))
square = root ** 2
sums = [[square] + s for s in sumsq(n - square, depth + 1)]
while root  0:
square = root ** 2
if square * len(sums[0])  n:
break
more_sums = [[square] + s for s in sumsq(n - square, depth + 1)]
if len(more_sums[0]) == len(sums[0]):
sums.extend(more_sums)
elif len(more_sums[0])  len(sums[0]):
sums = more_sums
root -= 1
sums = set(tuple(sorted(s, reverse=True)) for s in sums)
sums = [list(s) for s in sorted(sums, reverse=True)]
return sums

for n in range(1, 150):
print n, sumsq(n)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing items in nested tuples

2009-04-21 Thread Mensanator
On Apr 21, 3:03 pm, alex ale...@bluewin.ch wrote:
 Hello everybody
 I am able to access the data in a tuple via a for loop (see example
 below).

 #!/usr/bin/env python

 class Test():
     def Data(self):
         return (aa, bb, cc, dd, ee, ff, gg, hh)
 #        return ((aa, (bb, cc, dd)), (ee, (ff, gg,
 hh)), (ii, (jj, kk, ll)))

     def Process(self):
         for eachData in self.Data():
             print Printing %s % eachData

 def main():
     print Start processing data
     prtData=Test()
     prtData.Process()
     print Stop processing data

 if __name__ == '__main__':
     main()

 However I do not find out how to access data items in a nested tuple
 of
 the type ((aa, (bb, cc, dd)), (ee, (ff, gg, hh)),...).
 In fact I am trying to refactor a simple GUI basing on an example
 in wxPython In Action, Listing 5.5 A refactored example where the
 menues
 are described in the way

     def menuData(self):
         return ((File,
                 (Open, Open in status bar, self.OnOpen),
                 (Quit, Quit, self.OnCloseWindow)),
                 (Edit,
                 (Copy, Copy, self.OnCopy),
                 (Cut, Cut, self.OnCut),
                  ...)))

     etc...

 But I can not get the example running and I can't reprogram the
 example to get it running for my case.

 In IDLE I can print the individual tuples but not the items within.

 IDLE 1.2.1 data=((aa, (bb, cc, dd)), (ee, (ff, gg, hh)), 
 (ii, (jj, kk, ll)))
  print data[0]

 ('aa', ('bb', 'cc', 'dd')) print data[1]

 ('ee', ('ff', 'gg', 'hh'))

  etc...

 I would like to be able to access the dataitem aa or bb, cc,
 dd individualy.
 For sure I am most probably missing something which is evident, maybe
 can anybody help?

 for i in data:
print i[0],
for j in i[1]:
print j,


aa bb cc dd ee ff gg hh ii jj kk ll

 print data[0]
('aa', ('bb', 'cc', 'dd'))
 print data[0][0]
aa
 print data[0][1][0]
bb
 print data[0][1][1]
cc



 Thanks Alex

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


question about wxpython CtrlList event binder: wx.EVT_LIST_ITEM_RIGHT_CLICK

2009-04-21 Thread Kent
Hi there,

I wrote a desktop application with wxPython2.8. And got a problem.
Hope here someone can give some hint. Thanks in advance.

There was a ListCtrl (lc) in my GUI, and it was a bit long, so that
there would be some blank space below (empty area) in case there
were only a few items.

I bind a function on the event wx.EVT_LIST_ITEM_RIGHT_CLICK, when user
rightclick on the lc item, my function was triggered, and open a popup
menu.

Depends on the item user clicked, the menu items can be different. I
checked the event.getData(), to decide which menu item will show to
user. That is, if user right click on the empty area, the
event.getData() will be 0. I wrote the appl. under Linux, and tested,
it worked as what I expected.

However, today someone reported a bug, said, under Windows XP, right
clicking on the items of lc, it works fine, but if on the empty area
of the lc, nothing happened, no popup menu. I tested under WINXP, the
function was not triggered at all when I right-clicked on the empty
area.

I tried to bind wx.EVT_RIGHT_DOWN(UP) to the lc, but the function
cannot be triggered under Linux.  any suggestion?

Thanks

regards,

Kent


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


Re: Best Python Web Framework ?

2009-04-21 Thread laplacia...@gmail.com
On Apr 21, 2:46 pm, SKYLAB zky...@gmail.com wrote:
 Greetings..

 First , my english is not good .

 I heard that was written in python ( Youtube Programming Language :
 PYTHON :S ) Correct ?

 That's not correct ? Then youtube is PHP application ?

 That's correct ; Which python web framework in friendfeed ? Web.py ?
 Django ? web2py ?

 Thanks..

There may not be a best web framework -- only one that is best for
you and what you need to do with it.

If you want a large and feature-rich framework, try django.

If you want something smaller and simpler, maybe try Karrigell. Also,
Werkzeug http://werkzeug.pocoo.org/ seems actively developed and well-
documented.

Dunno what youtube or friendfeed use. Google might tell you.

Enjoy experimenting. :)
--
http://mail.python.org/mailman/listinfo/python-list


cx_oracle

2009-04-21 Thread gita ziabari
Hello everyone,

1. I installed Oracle client on my linux x86_64 machine.
2. Set oracle home and LD_LIBRARY_PATH
3. Installed cx_oracle using rpm for python 2.5
- It's installed and the following file exists:
 /usr/local/lib/python2.5/site-packages/cx_Oracle.so
- When I run python -c 'import cx_Oracle' it returns the following error:
ImportError: /usr/local/lib/python2.5/site-packages/cx_Oracle.so: cannot
open shared object file: No such file or directory

path /usr/local/lib/python2.5/site-packages is included in sys.path list

Any comment?
--
http://mail.python.org/mailman/listinfo/python-list


Re: the correct way to install python packages as non root user in non default path

2009-04-21 Thread News123
Danke Diez,

easy_install without 'install' works better :-) .

As as you indicated: Virtualenv installs cleanly in a separate directory
named virtualenv-1.3.3-py2.5.egg,

So I removed the --prefix option and installed it in the default path.

By the way: Adding the word 'install' wasn't inspired by apt-get, but by
python ./setup.py, which also seems to want a 'command'

bye

N

Diez B. Roggisch wrote:
 News123 wrote:
 
 Hi Alex,


 Thanks a lot. Reading the description this sounds to be the right thing.


 But now I'm stuck installing virtualenv as a user as this seems to be no
 ubunbtu package:


 export PYTHONPATH=/opt/newpymod/lib/python2.5/site-packages
 mkdir -p $PYTHONPATH
 easy_install --prefix /opt/newpymod install virtualenv
 
 Just because apt-get uses install as command doesn't mean everything else
 does. And easy_install is one of those which doesn't. Remove the install,
 and things should work.
 
 Additionally, I don't see any problem with installing virtualenv into the
 system-python. It's an addon, not a replacement, thus it shouldn't collide
 with package management (unless you are going to remove python)
 
 Diez
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >