Re: Have a variable column length in printf

2009-05-31 Thread Emile van Sebille

On 5/30/2009 10:58 PM Cameron Pulsford said...

Hello all, I'm trying to pretty print a list, so I am doing something like

print '%3d' % integer

only I would like that 3 to be a variable, instead of hardcoded. Is this 
possible, or are there any other ways to accomplish this? Thanks!




>>> integer = 12
>>> for lenvar in (4,5,6,7):
... print ("%%%sd" % lenvar) % integer
...
  12
   12
12
 12
>>>


Emile

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


Re: How do I sample randomly based on some probability(wightage)?

2009-05-31 Thread Sumitava Mukherjee
On May 28, 3:52 pm, Antoon Pardon  wrote:
> Op 2009-05-26, Arnaud Delobelle schreef :
>
>
>
> > Sumitava Mukherjee  writes:
>
> >> On May 26, 11:39 pm, Sumitava Mukherjee  wrote:
> >>> Hi all,
> >>> I need to randomly sample from a list where all choices have weights
> >>> attached to them. The probability of them being choosen is dependent
> >>> on the weights.
> >>> If say Sample list of choices are [A,B,C,D,E] and weights of the same
> >>> are [0.895,0.567,0.765,0.890,0.60] when I draw (say 2) samples then I
> >>> want the likeliness of them being chosen be in the order : D>A>C>E>B
>
> > You mean A > D > C > E > B
>
> >>> In short I mean if prob of a H is .9 and probability of T be 0.1 then
> >>> if I draw 10 samples, 9 should be H and 1 should be T.
>
> >>> I coudn't find a function in the module random that does so.
> >>> Please can someone guide me how the above could be implemented [either
> >>> through some function which exists and I don't know or pointers to
> >>> some code snippets which does so]?
>
> >> [Oh, I forgot to mention. I am looking for sampling without 
> >> replacement.]
>
> > If you do sampling without replacement, you need to know the exact
> > number of each of A, B, C, D, E in the sample, not just their relative
> > frequency.
>
> As far as I understand, you are given the exact number of each. It is one.
> The numbers given are not relative frequencies of appearance but weights
> to be attributed for picking them.
>
> --
> Antoon Pardon

Yes, the numbers are weights attributed for picking them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I sample randomly based on some probability(wightage)?

2009-05-31 Thread Sumitava Mukherjee
On May 27, 8:08 pm, Scott David Daniels  wrote:
> Sumitava Mukherjee wrote:
> > I need to randomly sample from a list where all choices have weights
> > attached to them. The probability of them being choosen is dependent
> > on the weights.
>
> I am not sure why everybody is normalizing by dividing the weights.
> This isa possibility (I had fun writing it).
>
> def sample_without_replacement(choices, weights):
>      '''Yield elements sampled w/o replacement by weighting'''
>      if len(weights) != len(choices):
>          raise ValueError('%d choices, but %d weights?' % (
>              len(choices), len(weights)))
>      if min(weights) < 0:
>          raise ValueError('Negative weights?: %s' % (
>                      [(i, w) for i, w in enumerate(weights) if w < 0]))
>
>      # look at only non-zero probabilities
>      combined = [(w, v) for w, v in zip(weights, choices) if w > 0]
>
>      # Go from highest probability down to reduce expected traversal
>      combined.sort(key=operator.itemgetter(0), reverse=True)
>
>      total = sum(w for w, v in combined) # sum(weights) also works
>      while combined:
>          spot = sample = random.random() * total
>          for n, (weight, choice) in enumerate(combined):
>              spot -= weight
>              if spot <= 0:
>                  break
>          else:
>              # n, (weight, choice) = 0, combined[0] # Highest probability
>              raise ValueError('%f left after choosing %f/%f?: %s' % (
>                                  spot, sample, total, combined))
>          yield choice
>          total -= weight
>          if weight > total * 256: # arbitrary choice for recalculation
>              # precision affected, rebuild
>              total = sum(w for w, v in combined)
>          del combined[n]
>      raise ValueError('Samplng more than %d without replacement?' % (
>                        sum(1 for w in weights if w > 0)))
>
> for n in range(10):
>      gen = sample_without_replacement('abcdef', [32,16,8,4,2,1])
>      print gen.next(), gen.next(), gen.next()
>
> --Scott David Daniels
> [email protected]

Among all the help (all of which I really appreciate), I found your
solution closest to what I was expecting. Thanks a lot Scott.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Metaclass mystery

2009-05-31 Thread Arnaud Delobelle
LittleGrasshopper  writes:

> On May 30, 6:15 pm, Carl Banks  wrote:
>> On May 30, 5:32 pm, LittleGrasshopper  wrote:
>>
>>
>>
>> > On May 30, 4:01 pm, LittleGrasshopper  wrote:
>>
>> > > I am experimenting with metaclasses, trying to figure out how things
>> > > are put together.

Have you read Guido's 'Unifying types and classes in Python 2.2' [1]?  I
read it a long time ago but I remember it being very enlightening.

[1] http://www.python.org/download/releases/2.2.3/descrintro/

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


Re: Have a variable column length in printf

2009-05-31 Thread Gary Herron

Cameron Pulsford wrote:
Hello all, I'm trying to pretty print a list, so I am doing something 
like


print '%3d' % integer

only I would like that 3 to be a variable, instead of hardcoded. Is 
this possible, or are there any other ways to accomplish this? Thanks!


Use a '*' instead of fixed width, and then supply the actual width as a 
separate parameter:


>>> print '%*d' % (5,123)
 123

Gary Herron


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


Re: Have a variable column length in printf

2009-05-31 Thread Steven D'Aprano
Apologies for breaking threading, the original post to this thread is not 
on my newserver.


Cameron Pulsford wrote:

> Hello all, I'm trying to pretty print a list, so I am doing something
> like
>
> print '%3d' % integer


Instead of re-inventing the wheel, have you looked at the pretty-print 
module? import pprint may do what you want.

If you still need your own custom pretty-print function, then there are a 
couple of ways to accomplish what you ask:

>> only I would like that 3 to be a variable, instead of hardcoded. Is
>> this possible, or are there any other ways to accomplish this?

As others have said, you can use '*' instead of the width. Another 
alternative, for even more flexibility, is to construct the format string 
programmatically:


>>> fmt = '%%0%dd' % 7
>>> print fmt % 3
003



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


Re: try except inside exec

2009-05-31 Thread Michele Petrazzo

Emile van Sebille wrote:

Write the string out to a .py file and import it?



I don't think that it's possible. I want to create an env that are
accessible only from that peace of code and not from the code that
"execute" the third-party one.


Emile



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


Re: try except inside exec

2009-05-31 Thread Michele Petrazzo

David Stanek wrote:

Is the thirdparty function the entire STR or just the a_funct part?



Just the a_funct. Only for try and for see if it's possible to catch all
the (possible) exception(s), I add the "try/except" clause that include
the a_funct external code.

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


Re: How to reuse TCP listening socket immediately after it was connected at least once?

2009-05-31 Thread Lawrence D'Oliveiro
In message , Thomas Bellman wrote:

> We weren't exactly keen on rebooting the machine, but it was the
> fastest way of getting out of that situation that we could figure
> out.  How *should* we have dealt with it in your opinion?

Remember, the timed_wait timeout is there for a reason, and trying to defeat 
it could reduce the reliability of your application--that's why cutting 
corners is a bad idea.

If you want to minimize the effect of the timeout, then just use different 
ports, and have the clients find them via DNS SRV records.

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


Re: hash and __eq__

2009-05-31 Thread Steven D'Aprano
On Sun, 31 May 2009 07:24:09 +0100, Arnaud Delobelle wrote:

> AFAIK, 'complexity' means 'worst case complexity' unless otherwise
> stated.

No, it means "average or typical case" unless otherwise specified. 
Consult almost any comp sci text book and you'll see hash tables with 
chaining (like Python dicts) described as O(1) rather than O(N), 
Quicksort as O(N log N) instead of O(N**2), and similar. If the default 
was "worst case unless otherwise specified", then Quicksort would be 
called "Slower than Bubblesort Sort".

(Both are O(N**2), but Quicksort does more work.)

Here's a quote on-line:

"You should be clear about which cases big-oh notation describes. By 
default it usually refers to the average case, using random data. 
However, the characteristics for best, worst, and average cases can be 
very different..."

http://leepoint.net/notes-java/algorithms/big-oh/bigoh.html


It is simply misleading to describe dicts as O(N) without the 
qualification "if the data is chosen maliciously, or otherwise by an 
incredible fluke". And even if it isn't, Piet explicitly said he was 
talking about the average behaviour, not worst.



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


Re: decoding keyboard input when using curses

2009-05-31 Thread Arnaud Delobelle
Chris Jones  writes:

Hi Chris, thanks for your detailed reply.

> On Sat, May 30, 2009 at 04:55:19PM EDT, Arnaud Delobelle wrote:
>
>> Hi all,
>
> Disclaimer: I am not familiar with the curses python implementation and
> I'm neither an ncurses nor a "unicode" expert by a long shot.
>
> :-)
>
>> I am looking for advice on how to use unicode with curses.  First I will
>> explain my understanding of how curses deals with keyboard input and how
>> it differs with what I would like.
>> 
>> The curses module has a window.getch() function to capture keyboard
>> input.  This function returns an integer which is more or less:
>> 
>> * a byte if the key which was pressed is a printable character (e.g. a,
>>   F, &);
>> 
>> * an integer > 255 if it is a special key, e.g. if you press KEY_UP it
>>   returns 259.
>
> The getch(3NCURSES) function returns an integer. Provide it's large
> enough to accomodate the highest possible value, the actual size in
> bytes of the integer should be irrelevant.

Sorry I was somehow mixing up what happens in general and what happens
with utf-8 (probably because I have only done test with utf-8), where
the number of bytes used to encode a character varies.

>> As far as I know, curses is totally unicode unaware, 
>
> My impression is that rather than "unicode unaware", it is "unicode
> transparent" - or (nitpicking) "UTF8 transparent" - since I'm not sure
> other flavors of unicode are supported.

>> so if the key pressed is printable but not ASCII, 
>
> .. nitpicking again, but ASCII is a 7-bit encoding: 0-127.
>
>> the getch() function will return one or more bytes depending on the
>> encoding in the terminal.
>
> I don't know about the python implementation, but my guess is that it
> should closely follow the underlying ncurses API - so the above is
> basically correct, although it's not a question of the number of bytes
> but rather the returned range of integers - if your locale is en.US then
> that should be 0-255.. if it is en_US.utf8 the range is considerably
> larger.

In my tests, my locale is en_GB.utf8 and the python getch() function
does return a number of bytes - see below.

>> E.g. given utf-8 encoding, if I press the key 'é' on my keyboard (which
>> encoded as '\xc3\xa9' in utf-8), I will need two calls to getch() to get
>> this: the first one will return 0xC3 and the second one 0xA9.
>
> No. A single call to getch() will grab your " é" and return 0xc3a9,
> decimal 50089.

It is the case though that on my machine, if I press 'é' then call
getch() it will return 0xC3.  A further call to getch() will return
0xA9.  This I was I was talking about getch() returning bytes: to me it
behaves as if it returns the encoded characters byte by byte.

>> Instead of getting a stream of bytes and special keycodes (with value >
>> 255) from getch(), what I want is a stream of *unicode characters* and
>> special keycodes.
>
> This is what getch(3NCURSES) does: it returns the integer value of one
> "unicode character".

It is not what happens in my tests.  I have made a simple testing
script, see below.

> Likewise, I would assume that looping over the python equivalent of
> getch() will not return a stream of bytes but rather a "stream" of
> integers that map one to one to the "unicode characters" that were
> entered at the terminal.



> Note: I am only familiar with languages such as English, Spanish,
> French, etc. where only one terminal cell is used for each glyph. My
> understanding is that things get somewhat more complicated with
> languages that require so-called "wide characters" - two terminal cells
> per character, but that's a different issue.
>
>> So, still assuming utf-8 encoding in the terminal, if I type:
>> 
>> Té[KEY_UP]ça
>> 
>> iterating call to the getch() function will give me this sequence of
>> integers:
>> 
>> 84, 195, 169, 259,   195, 167, 97
>> T-  é---  KEY_UP ç---  a-
>> 
>> But what I want to get this stream instead:
>> 
>> u'T', u'é', 259, u'ç', u'a'
>
> No, for the above, getch() will return:
>
>  84, 50089, 259, 50087, 97
>
> .. which is "functionally" equivalent to:
>
>  u'T', u'é', 259, u'ç', u'a'
>
> [..]
>
> So shouldn't this issue boil down to just a matter of casting the
> integers to the "u" data type?
>
> This short snippet may help clarify the above:
>
> ---
> #include 
> #include 
> #include 
> #include 
> #include 
>
> int unichar;
>
> int main(int argc, char *argv[])
> {
>   setlocale(LC_ALL, "en_US.UTF.8");/* make sure UTF8   */
>   initscr();   /* start curses mode*/
>   raw();
>   keypad(stdscr, TRUE);/* pass special keys*/
>   unichar = getch();   /* read terminal*/
>
>   mvprintw(24, 0, "Key pressed is = %4x ", unichar);
>
>   refresh();
>   getch(); /* wait */
>   endwin();   

Re: Only run one specific test

2009-05-31 Thread Yinon Ehrlich

>
> Yes, that works indeed. But in practice the modules_to_import list is
> filled by parsing the contents of a test/*.py directory. That's why I
> import dynamically with __import__.
>
> Nevertheless, you got me on the right track. After I explicitly added
> the modules to the global namespace (globals()["mytest"] =
> __import__("mytest")), it works fine. Thx!

Another way to do it is using imp.load_source,
see http://waf.googlecode.com/svn/trunk/test/Test.py
  Yinon
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: try except inside exec

2009-05-31 Thread Michele Petrazzo

Aaron Brady wrote:

Exceptions are only caught when raised in a 'try' statement.  If you
 don't raise the exception in a try statement, it won't be caught.

The function you posted will raise an exception.  If you are making 
the call yourself, that is, if only the definition is foreign, then 
simply catch exceptions when so.




Seeing my code and reading you post I found that... yes, are a my fault!
I'm catching only an exception in a code/function definition, no its
execution!

Just modified my code to catch the exception *inside* the def and not
before and... now work!

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


Re: Optimizing math functions

2009-05-31 Thread Beni Cherniavsky
On May 23, 4:22 pm, Esmail  wrote:
>
> Is there some sort of simple Python module that would allow me to
> evaluate this type of function?
>
> In this particular instance I am interested in the minimum of
>
>    x * sin(4*x) + 1.1 * sin(2*y), where x,y in range 0-10
>
> though in other problems the range may not be identical for x and y.

Take a look at http://openopt.org (python-scikits-openopt on debian/
ubuntu) - a lot of optimization engines under one interface, so you
can try different engines easily and without learning many interfaces.

>>> import openopt
>>> from numpy import *
# openopt passes parameters as single vector.
>>> def f((x,y)):
return x * sin(4*x) + 1.1 * sin(2*y)
# GLP finds global minimum - can be hard, but let's try.
# I'm not constraining the effort in hope it will converge quickly.
>>> opt = openopt.GLP(f, lb=array([0, 0]), ub=array([10, 10]))
# 'galileo' is one of the supported GLP solvers, included out of the
box.
>>> sol = opt.solve('galileo', plot=True)
-
solver: galileo   problem: unnamed
 iterobjFunVal
0  3.966e+00
   10  -6.190e+00
   20  -7.613e+00
   30  -7.613e+00
   35  -7.613e+00
istop:  11 (Non-Success Number > maxNonSuccess = 15)
Solver:   Time Elapsed = 0.78   CPU Time Elapsed = 0.24
Plotting: Time Elapsed = 8.04   CPU Time Elapsed = 2.21
objFunValue: -7.6132332 (feasible, max constraint =  0)
### here you need to close the runtime-value graph to continue ###
>>> sol.ff
-7.6132331733254421
>>> sol.xf
array([ 7.3418726 ,  5.44153445])

That is x=7.3418726, y=5.44153445 gives f=-7.6132331733254421.
Makes sense?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Optimizing math functions

2009-05-31 Thread Beni Cherniavsky
On May 31, 12:41 pm, Beni Cherniavsky 
wrote:
>
> Take a look athttp://openopt.org(python-scikits-openopt on debian/
> ubuntu) - a lot of optimization engines under one interface, so you
> can try different engines easily and without learning many interfaces.
>
Correction: don't use the debian package, it uses an old snapshot of
openopt.
Install from svn, it's very easy (checkout, setup.py).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Have a variable column length in printf

2009-05-31 Thread Terry Reedy

Gary Herron wrote:

Cameron Pulsford wrote:
Hello all, I'm trying to pretty print a list, so I am doing something 
like


print '%3d' % integer

only I would like that 3 to be a variable, instead of hardcoded. Is 
this possible, or are there any other ways to accomplish this? Thanks!


Use a '*' instead of fixed width, and then supply the actual width as a 
separate parameter:


 >>> print '%*d' % (5,123)
 123


In the new string formating, fields can be nested withing fields.  For 
3.1, with auto field numbering:

>>> "{:{}d}".format(12,4)
'  12'

Otherwise, {0:{1}d}

tjr

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


Re: hash and __eq__

2009-05-31 Thread Arnaud Delobelle
Steven D'Aprano  writes:

> On Sun, 31 May 2009 07:24:09 +0100, Arnaud Delobelle wrote:
>
>> AFAIK, 'complexity' means 'worst case complexity' unless otherwise
>> stated.
>
> No, it means "average or typical case" unless otherwise specified. 
> Consult almost any comp sci text book and you'll see hash tables with 
> chaining (like Python dicts) described as O(1) rather than O(N), 
> Quicksort as O(N log N) instead of O(N**2), and similar. If the default 
> was "worst case unless otherwise specified", then Quicksort would be 
> called "Slower than Bubblesort Sort".
>
> (Both are O(N**2), but Quicksort does more work.)

OK.  I remember from my student years when studying complexity theory
that complexity implicitely referred to worst case complexity.  I
assumed this was a widely used convention - I don't have any evidence
that it is so you may very well be correct.

Anyway, it's good to know that quicksort is O(n^2) in the worst case -
and that this worst case can crop up very easily in some situations,
especially if not too much care has been taken implementing it.

[...]

> It is simply misleading to describe dicts as O(N) without the 
> qualification "if the data is chosen maliciously, or otherwise by an 
> incredible fluke". And even if it isn't, Piet explicitly said he was 
> talking about the average behaviour, not worst.

But the OP only mentioned 'complexity', not 'average complexity', and I
imagine that he knows the average case complexity of accessing a key in
a hashtable.

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


Re: which database is suitable for small applications

2009-05-31 Thread Lawrence D'Oliveiro
In message <52801358-c037-458d-8857-
[email protected]>, Ankit wrote:

> If your application does not require you to add very heavy data then
> you can also use flat files to do your stuff.
> Its always a better to use Databases ...

It's not always better to use databases. By definition, data for a “small” 
application is bound to fit entirely in RAM. So certainly the simplest thing 
to do is read a whole data file in at the start, and write the entire 
updated data structure back out again at the end.

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


Re: Q: finding distance between 2 time's

2009-05-31 Thread martin
On May 30, 4:10 pm, Steven D'Aprano  wrote:
> On Sat, 30 May 2009 12:06:55 +0200, jkv wrote:
> > I added a few lines to your script, and now it ought to only print files
> > newer than 3601 seconds (3600 seconds is one hour).
> ...
> >     #if file newer than one hour print a line
> >     if time_difference < 3601:
>
> That's a potential off-by-one error. That may print files that are older
> than one hour. Admittedly, they'll be off by less than one second, but if
> you're going to write code, write correct code. The right test is:
>
>     if time_difference <= 3600:
>
> (and you may even want to deal with files that have a *negative* time
> difference, e.g. they were created apparently in the future).
>
> This is particularly necessary if you use time.time() to generate the
> current time, since that returns fractions of a second. But even if you
> don't, it's still the right thing to do: it's defensive programming.
> Rather than assume that all file systems store timestamps accurate only
> to a second, assume that some file system, somewhere, will be accurate to
> fractions of a second, and code accordingly.
>
> That way, no matter what the file system does, your code will still do
> the right thing, and (in this case) it doesn't even cost you anything.
>
> --
> Steven

Hi Steve thanks for your comment.
But I only need it to re-run some test scripts in case there seems to
be hick-up in our live download of satellite images. It's not critical
within seconds, not even within minutes...
But in principel the potential error could of cause be important - in
other context.

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


Re: Q: finding distance between 2 time's

2009-05-31 Thread martin
On May 30, 11:37 pm, jkv  wrote:
> [email protected] wrote:
> > Thanks both
>
> > The first answer is quite instuctive, the other one might be the one
> > I'll use in t
>
> I didn't receive the other answer, could you please forward it to me?> So 2x 
> thanks.
>
> You are welcome.
>
> I took another look at your code, and you can compress it all to a if
> "oneliner":
> (and thanks to Steven for the <= reminder)
>
>         if os.path.isfile(x):
>             nSize = os.path.getsize(x)
>             #if oneliner
>             if time.mktime(time.localtime()) -
> time.mktime(time.localtime(os.path.getmtime(x))) <= 3600:
>               print ('HT fil -> %s %d @ %s') % (x, nSize, time.asctime)

I encurrage both Clarity and Brevity, but usually in that order.
In other words, I don't mind to split a statement in two (or three)
sub-sentenses, if it increases Clarity. As long as it dosn't so large
that I loose the overview, and as long as it dosn't affect runtime
performance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Q: finding distance between 2 time's

2009-05-31 Thread martin
>
> http://en.wikipedia.org/wiki/Subtraction
>


Only one problem, wise arse:
TypeError: unsupported operand type(s) for -: 'time.struct_time' and
'time.struct_time'

Like I didn't try that...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Q: finding distance between 2 time's

2009-05-31 Thread John Machin
On May 31, 10:19 pm, [email protected] wrote:
> >http://en.wikipedia.org/wiki/Subtraction
>
> Only one problem, wise arse:
> TypeError: unsupported operand type(s) for -: 'time.struct_time' and
> 'time.struct_time'
>
> Like I didn't try that...

The point being that you can subtract them in other ways than by
shoving a - between them and throwing the result at Python. What you
were doing was like saying "I was born in January MCMLXXXIX and it's
now MMIX; how do I work out how old I am?" when you *already* had the
relevant numbers in a easily-subtractable form.
-- 
http://mail.python.org/mailman/listinfo/python-list


Class Methods help

2009-05-31 Thread bdsatish
Hi,

I have a question regarding the difference b/w "class methods" and
"object methods". Consider for example:

class  MyClass:
x = 10

Now I can access MyClass.x -- I want a similar thing for functions. I
tried

class MyClass:
def  some_func(x):
return x+2

When I call MyClass.some_func(10) -- it fails, with error message:


TypeError: unbound method some_func() must be called with MyClass
instance as first argument (got int instance instead)

OK. I figured out that something like this works:
obj = MyClass()
y = obj.some_func(10)

BUT, this means that we have functions applying for instances. That is
we have "instance method". Now, how do I implement some function which
I can invoke with the class name itself ? Instead of creating a dummy
object & then calling In short, how exactly do I create "class
methods" ??







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


Re: Class Methods help

2009-05-31 Thread Tim Chase

class MyClass:
def  some_func(x):
return x+2

When I call MyClass.some_func(10) -- it fails, with error message:


TypeError: unbound method some_func() must be called with MyClass
instance as first argument (got int instance instead)

OK. I figured out that something like this works:
obj = MyClass()
y = obj.some_func(10)

BUT, this means that we have functions applying for instances. That is
we have "instance method". Now, how do I implement some function which
I can invoke with the class name itself ? Instead of creating a dummy
object & then calling In short, how exactly do I create "class
methods" ??


You mean the classmethod decorator? :)

  class MyClass:
@classmethod
def some_func(cls, x):
  return x+2

  MyClass.some_func(42)

(the decorator syntax was added in 2.4, so if you need it in 
pre-2.4, you'd have to do


  class MyClass:
def some_func(cls, x):
  return x+2
some_func = classmethod(some_func)

to get the same behavior)

-tkc


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


Re: Class Methods help

2009-05-31 Thread Lie Ryan
bdsatish wrote:
> Hi,
> 
> I have a question regarding the difference b/w "class methods" and
> "object methods". Consider for example:
> 
> class  MyClass:
> x = 10
> 
> Now I can access MyClass.x -- I want a similar thing for functions. I
> tried
> 
> class MyClass:
> def  some_func(x):
> return x+2
> 
> When I call MyClass.some_func(10) -- it fails, with error message:
> 
> 
> TypeError: unbound method some_func() must be called with MyClass
> instance as first argument (got int instance instead)
> 
> OK. I figured out that something like this works:
> obj = MyClass()
> y = obj.some_func(10)
> 
> BUT, this means that we have functions applying for instances. That is
> we have "instance method". Now, how do I implement some function which
> I can invoke with the class name itself ? Instead of creating a dummy
> object & then calling In short, how exactly do I create "class
> methods" ??
with staticmethod decorator:

>>> class MyClass:
... @staticmethod
... def some_func(x):
... return x+2
...
>>> MyClass.some_func(10)
12

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


Re: Class Methods help

2009-05-31 Thread bd satish
Thanks to Tim Chase & Lie Ryan !!  That was exactly what I was looking for !!

It's time for me to now read the documentation of "decorators" and
@classmethod and also @staticmethod.

I'm quite new to decorators...


-- Satish BD


On Sun, May 31, 2009 at 4:44 PM, Lie Ryan  wrote:
> bdsatish wrote:
>> Hi,
>>
>>     I have a question regarding the difference b/w "class methods" and
>> "object methods". Consider for example:
>>
>> class  MyClass:
>>     x = 10
>>
>> Now I can access MyClass.x -- I want a similar thing for functions. I
>> tried
>>
>> class MyClass:
>>     def  some_func(x):
>>         return x+2
>>
>> When I call MyClass.some_func(10) -- it fails, with error message:
>>
>>
>> TypeError: unbound method some_func() must be called with MyClass
>> instance as first argument (got int instance instead)
>>
>> OK. I figured out that something like this works:
>> obj = MyClass()
>> y = obj.some_func(10)
>>
>> BUT, this means that we have functions applying for instances. That is
>> we have "instance method". Now, how do I implement some function which
>> I can invoke with the class name itself ? Instead of creating a dummy
>> object & then calling In short, how exactly do I create "class
>> methods" ??
> with staticmethod decorator:
>
 class MyClass:
> ...     @staticmethod
> ...     def some_func(x):
> ...         return x+2
> ...
 MyClass.some_func(10)
> 12
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I sample randomly based on some probability(wightage)?

2009-05-31 Thread Scott David Daniels

Sumitava Mukherjee wrote:

On May 27, 8:08 pm, Scott David Daniels  wrote:

Sumitava Mukherjee wrote:

I need to randomly sample from a list where all choices have weights
attached to them. The probability of them being choosen is dependent
on the weights.

I am not sure why everybody is normalizing by dividing the weights.
This isa possibility (I had fun writing it).

def sample_without_replacement(choices, weights):
...  combined = [(w, v) for w, v in zip(weights, choices) if w > 0]
...  total = sum(w for w, v in combined) # sum(weights) also works
 while combined:
...
 yield choice
 total -= weight
 if weight > total * 256: # arbitrary choice for recalculation
 # precision affected, rebuild
 total = sum(w for w, v in combined)
 del combined[n]
 raise ValueError('Samplng more than %d without replacement?' % (
   sum(1 for w in weights if w > 0)))
...

Should be:
   total -= weight
   yield choice
   del combined[n]
   if weight > total * 256: # arbitrary choice for recalculation
# precision affected, rebuild
total = sum(w for w, v in combined)
   raise ValueError('Samplng more than %d without replacement?' % (
  sum(1 for w in weights)))
There were two mistakes, both related to the definition of combined:
 (1) Combined only holds positive values, so testing in sum is silly.
 (2) Total is meant to track the sum of weights in combined, and the
 update was misplaced with respect to the delete.


Among all the help (all of which I really appreciate), I found your
solution closest to what I was expecting. Thanks a lot Scott.


You are welcome (presuming I didn't simply do your homework).  I only
noticed the problems above while scanning your reply.  The failures I
noticed should have been caught with good tests or a pair programming
partner.  Of course, in this environment, I didn't have either high
quality tests or a partner (I did simple hand testing and eyeball
analysis).

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: hash and __eq__

2009-05-31 Thread Scott David Daniels

Arnaud Delobelle wrote:

Steven D'Aprano  writes:


On Sun, 31 May 2009 07:24:09 +0100, Arnaud Delobelle wrote:


AFAIK, 'complexity' means 'worst case complexity' unless otherwise
stated.
No, it means "average or typical case" unless otherwise specified. 


I think you both are standing on opposite sides of a shift in notation.
Mathematics changes notations all the time, and new students are
presented notation as if it were a fixed thing.  What I think is
happening is that O-notation was a very technical notation used
for comparing abstract algorithms (providing an analysis that would
survive centuries of engineering improvement of the machines).  More
recently we have seen more use of average-case performance analysis,
in service of shorter-term accuracy (I guess).  Certainly this has
given us some data structures that would be hard to justify on a
worst-case analysis.  I suspect the default is shifting towards
average case (although it may already be there).  Certainly best
practice for the next couple of decades would be to be explicit
about the meaning

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I sample randomly based on some probability(wightage)?

2009-05-31 Thread Peter Otten
Scott David Daniels wrote:

> raise ValueError('Samplng more than %d without replacement?' % (
> sum(1 for w in weights)))

That would be len(weights)

> There were two mistakes, both related to the definition of combined:
> (1) Combined only holds positive values, so testing in sum is silly.
 
but I think your first version was correct; I don't see were you remove the 
0-items from weights.

Peter

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


Re: Metaclass mystery

2009-05-31 Thread LittleGrasshopper
On May 31, 12:19 am, Arnaud Delobelle  wrote:
> LittleGrasshopper  writes:
> > On May 30, 6:15 pm, Carl Banks  wrote:
> >> On May 30, 5:32 pm, LittleGrasshopper  wrote:
>
> >> > On May 30, 4:01 pm, LittleGrasshopper  wrote:
>
> >> > > I am experimenting with metaclasses, trying to figure out how things
> >> > > are put together.
>
> Have you read Guido's 'Unifying types and classes in Python 2.2' [1]?  I
> read it a long time ago but I remember it being very enlightening.
>
> [1]http://www.python.org/download/releases/2.2.3/descrintro/
>
> --
> Arnaud

I haven't actually read it, but I will now. Thanks for pointing it
out, Arnaud.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Have a variable column length in printf

2009-05-31 Thread Cameron Pulsford
Thanks all, I think I'l stick with the '*' method because this is just a one
time thing for a __repr__ function and it seems easiest.

On Sun, May 31, 2009 at 6:32 AM, Terry Reedy  wrote:

> Gary Herron wrote:
>
>> Cameron Pulsford wrote:
>>
>>> Hello all, I'm trying to pretty print a list, so I am doing something
>>> like
>>>
>>> print '%3d' % integer
>>>
>>> only I would like that 3 to be a variable, instead of hardcoded. Is this
>>> possible, or are there any other ways to accomplish this? Thanks!
>>>
>>
>> Use a '*' instead of fixed width, and then supply the actual width as a
>> separate parameter:
>>
>>  >>> print '%*d' % (5,123)
>>  123
>>
>
> In the new string formating, fields can be nested withing fields.  For 3.1,
> with auto field numbering:
> >>> "{:{}d}".format(12,4)
> '  12'
>
> Otherwise, {0:{1}d}
>
> tjr
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decoding keyboard input when using curses

2009-05-31 Thread Chris Jones
On Sun, May 31, 2009 at 04:05:20AM EDT, Arnaud Delobelle wrote:

[..]

> Thanks for this.  When I test it on my machine (BTW it is MacOS 10.5.7),
> if I type an ASCII character (e.g. 'A'), I get its ASCII code (0x41),
> but if I type a non-ascii character (e.g. '§') I get back to the prompt
> immediately.  It must be because two values are queued for getch.  I
> should try it on a Linux machine, but I don't have one handy at the
> moment.

Well so much for transparency :-(

Try this:

#include 
#include 
#include 
#include 
#include 

int ct;
wint_t unichar;

int main(int argc, char *argv[])
{
  setlocale(LC_ALL, ""); /* make sure UTF8   */
  initscr();
  raw();
  keypad(stdscr, TRUE);
  ct = get_wch(&unichar);/* read character   */
  mvprintw(24, 0, "Key pressed is = %4x ", unichar);

  refresh();
  get_wch();
  endwin();
  return 0;
}

gcc -lncursesw uni10.c -o uni10 # different lib..
 ^

Seems there's more to it than my assupmtion that the python wrapper was
not wrapping as transparaently as it should.. here I'm using wide
characters.. not sure how this translates to python.

CJ


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


problem with python com and python extensions

2009-05-31 Thread tristan625
hi all,
Here is my problem,i have developed a python extension using
vs2003 ,iam using python 2.5.2,the extension enumerates the
certificates in the windows certificate store and returns a list of
tuples containing a tuple for each certificate found containing the
certificates display name,subject and issuer,everything works fine
when  i run the code through the interpreter,the problem comes when i
create a python com object that imports this extensions
functionality,the com dll is created successfully but i am unable to
access any of the functions in it .



any help will be great
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decoding keyboard input when using curses

2009-05-31 Thread Arnaud Delobelle
Chris Jones  writes:
[...]
> Try this:
>
> #include 
> #include 
> #include 
> #include 
> #include 

/* Here I need to add the following include to get wint_t on macOS X*/

#include 

>
> int ct;
> wint_t unichar;
>
> int main(int argc, char *argv[])
> {
>   setlocale(LC_ALL, ""); /* make sure UTF8   */
>   initscr();
>   raw();
>   keypad(stdscr, TRUE);
>   ct = get_wch(&unichar);/* read character   */
>   mvprintw(24, 0, "Key pressed is = %4x ", unichar);
>
>   refresh();
>   get_wch();
>   endwin();
>   return 0;
> }
>
> gcc -lncursesw uni10.c -o uni10 # different lib..
>  ^

My machine doesn't know about libncursesw:

marigold:c arno$ ls /usr/lib/libncurses*
/usr/lib/libncurses.5.4.dylib
/usr/lib/libncurses.dylib
/usr/lib/libncurses.5.dylib

So I've compiled it with libncurses as before and it works.

This is what I get:

If I run the program and type 'é', I get a code of 'e9'.

In python:

>>> print '\xe9'.decode('latin1')
é

So it has been encoded using isolatin1.  I really don't understand why.
I'll have to investigate this further.

If I change the line:

   setlocale(LC_ALL, ""); /* make sure UTF8   */

to

   setlocale(LC_ALL, "en_GB.UTF-8");   /* make sure UTF8   */

then the behaviour is the same as before (i.e. get_wch() gets called
twice instantly).

I'll do some more investigating (when I can think of *what* to
investigate) and I will tell you my findings.

Thanks

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


automated web with python?

2009-05-31 Thread CoolGenie
Hello,
Recently my company changed the system. It is better for the
management, but for us workers it is a nightmare. For example, we are
required to enter a huge database (nested) using a web form! Make one
mistake and you have to edit it and then use 4 mouse clicks, not
counting the time it takes to load every web page.
My question is: can Python somewhat relieve this pain? Maybe this web
browser stuff could be somewhat automated... At first check it doesn't
seem easy, since it uses authorization methods, aspx, and so on... And
we don't have access to the underlying database, only this stupid web
form.
I'll appreciate any help.
Best regards,
Przemek
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I sample randomly based on some probability(wightage)?

2009-05-31 Thread Scott David Daniels

Peter Otten wrote:

Scott David Daniels wrote:
 [a real correction and a bogus one]

raise ValueError('Samplng more than %d without replacement?' % (
sum(1 for w in weights)))

That would be len(weights)

Yup, probably I should have just saved len(combined).

but I think your first version was correct; I don't see were you remove the 
0-items from weights.


You are right.  I thought I was looking at combined on the second,
realized my mistake, and thought, Oh well, it'll work out later.
The other mistake wasn't too bad either, as all that would happen
is that an internal exception would get raised, any answers delivered
are delivered with the correct probabilities.

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Q: finding distance between 2 time's

2009-05-31 Thread Anders J. Munch

jkv wrote:

Hi Martin,

What i usally do is to convert the two times to seconds since epoch and
compare the two values in seconds. You can use time.mktime to convert
localtime to seconds since epoch.


There's no need to convert - simply retrieve the times as absolute times to 
begin with:


  file_age_in_seconds = time.time() - os.path.getmtime(filename)

Only convert to local time for presentation.

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


Re: automated web with python?

2009-05-31 Thread MRAB

CoolGenie wrote:

Hello,
Recently my company changed the system. It is better for the
management, but for us workers it is a nightmare. For example, we are
required to enter a huge database (nested) using a web form! Make one
mistake and you have to edit it and then use 4 mouse clicks, not
counting the time it takes to load every web page.
My question is: can Python somewhat relieve this pain? Maybe this web
browser stuff could be somewhat automated... At first check it doesn't
seem easy, since it uses authorization methods, aspx, and so on... And
we don't have access to the underlying database, only this stupid web
form.
I'll appreciate any help.
Best regards,
Przemek


Have a look at Mechanize:

http://wwwsearch.sourceforge.net/mechanize/

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


Generating all combinations

2009-05-31 Thread Johannes Bauer
Hello group,

I'm trying to write a function in Python which does the following: For a
number of arguments which are all lists, return a list (or generator)
which yields all tuples of combination. E.g:

foofunction()
# returns [ ]

foofunction([1, 2, 3])
# returns [ (1), (2), (3) ]

foofunction([1, 2, 3], ["a", "b"], ["x"])
# returns [ (1, "a", "x"), (1, "b", "x"),
(2, "a", "x"), (2, "b", "x"),
(3, "a", "x"), (3, "b", "x") ]

I must admit that I have no clue on how to do that efficiently (and more
importantly: in a variadic manner) in Python. Any help is appreciated!

Kind regards,
Johannes

-- 
"Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit,
verlästerung von Gott, Bibel und mir und bewusster Blasphemie."
 -- Prophet und Visionär Hans Joss aka HJP in de.sci.physik
 <[email protected]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating all combinations

2009-05-31 Thread Scott David Daniels

Johannes Bauer wrote:

Hello group,

I'm trying to write a function in Python which does the following: For a
number of arguments which are all lists, return a list (or generator)
which yields all tuples of combination. E.g:


Look here:
  http://docs.python.org/library/itertools.html#itertools.product

(new in 2.6, but code works in lower versions).

--Scott David Daniels
[email protected]


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


Re: Metaclass mystery

2009-05-31 Thread LittleGrasshopper
On May 31, 9:24 am, LittleGrasshopper  wrote:
> On May 31, 12:19 am, Arnaud Delobelle  wrote:
>
>
>
> > LittleGrasshopper  writes:
> > > On May 30, 6:15 pm, Carl Banks  wrote:
> > >> On May 30, 5:32 pm, LittleGrasshopper  wrote:
>
> > >> > On May 30, 4:01 pm, LittleGrasshopper  wrote:
>
> > >> > > I am experimenting with metaclasses, trying to figure out how things
> > >> > > are put together.
>
> > Have you read Guido's 'Unifying types and classes in Python 2.2' [1]?  I
> > read it a long time ago but I remember it being very enlightening.
>
> > [1]http://www.python.org/download/releases/2.2.3/descrintro/
>
> > --
> > Arnaud
>
> I haven't actually read it, but I will now. Thanks for pointing it
> out, Arnaud.

I'm about 2/3 of the way through this paper (although I don't claim to
understand all of it.) There is some heavy duty material in there,
enough to make me feel really stupid and frustrated at times. I'm
making connections as I go though, hopefully everything will sink in
eventually.

The discussion on super(), especially the python code implementation,
clarified some of the doubts I had about how it is implemented
(including "unbound" super objects, which involve the descriptor
mechanism on the super object itself.)

Is this stuff actually tough, or am I just a dummy?
-- 
http://mail.python.org/mailman/listinfo/python-list


RFID and Python

2009-05-31 Thread Ronn Ross
I'm looking to play around with RFID and Python. Can anyone offer any
suggestions on the cheap? I'm possibly looking for a starter kit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Metaclass mystery

2009-05-31 Thread Aahz
In article ,
LittleGrasshopper   wrote:
>> On May 31, 12:19=A0am, Arnaud Delobelle  wrote:
>>>
>>> [1]http://www.python.org/download/releases/2.2.3/descrintro/
>
>I'm about 2/3 of the way through this paper (although I don't claim to
>understand all of it.) There is some heavy duty material in there,
>enough to make me feel really stupid and frustrated at times. I'm
>making connections as I go though, hopefully everything will sink in
>eventually.
>
>Is this stuff actually tough, or am I just a dummy?

Definitely tough!  Metaclasses can cause dain bramage.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

my-python-code-runs-5x-faster-this-month-thanks-to-dumping-$2K-
on-a-new-machine-ly y'rs  - tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating all combinations

2009-05-31 Thread Mark Dickinson
On May 31, 9:23 pm, Johannes Bauer  wrote:
> I'm trying to write a function in Python which does the following: For a
> number of arguments which are all lists, return a list (or generator)
> which yields all tuples of combination. E.g:
>
> foofunction()
> # returns [ ]

Are you sure that's what you want?  I'd expect [()] here (on the
basis that the empty product is a one-element set).  And
indeed that's what itertools.product gives:

>>> import itertools
>>> list(itertools.product())
[()]

> foofunction([1, 2, 3])
> # returns [ (1), (2), (3) ]

Presumably you mean [(1,), (2,), (3,)] here?

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


Re: PyOpenGL Installation

2009-05-31 Thread Mike C. Fletcher
Roastie wrote:
> The web info I have found for downloading/installing PyOpenGL and
> its dependencies for Windows is a nightmare.  Is there a place where
> all of
> the endless dependencies are packaged nicely with PyOpenGL?
>   
Hmm, "endless"?

* Python (with ctypes, standard on everything >= 2.5)
* OpenGL (standard on almost every Win32 machine save old Win95 boxes)

Possibly I'm missing something here?  If you just want PyOpenGL you only
need one file (the PyOpenGL package) + Python.  If you want to use it
with Numpy, you need to have numpy on the machine, same for GLUT, GLE
and the like, but they aren't required unless you want to use them. 
Heck, if you want you can even easy_install the package last I checked.

http://pyopengl.sourceforge.net/documentation/installation.html

My dictionary's definition of endless must be broken ;) :) ,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Unzip Files

2009-05-31 Thread Brock
Hi all,

I am new to python, so please don't attack me if this question is easy
or basic.  How can I go about extracting the contents of a zip file to
the same directory?  Can I extend this question to a zip file that
sits on the internet?

Point being I need to work with the files inside the zipped file, and
there are times when the file is already on my computer, and their
others where the datafile sits on the Internet.

Any help you can provide will be greatly appreciated.  In full
disclosure, I usually learn by example and not by trial and error, so
any nudges in the right direction will be greatly appreciated.

Many thanks,

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


Re: RFID and Python

2009-05-31 Thread Kevin MacPhail
On Sun, May 31, 2009 at 3:55 PM, Ronn Ross  wrote:

> I'm looking to play around with RFID and Python. Can anyone offer any
> suggestions on the cheap? I'm possibly looking for a starter kit.
>

The Phidgets  RFID starter kit sounds like it might
meet your needs.  There's at least one Python binding for the Phidgets
library that I'm aware of: http://www.lothar.com/Projects/Phidgets/

Cheers,

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


Re: Generating all combinations

2009-05-31 Thread member thudfoo
On 5/31/09, Scott David Daniels  wrote:
> Johannes Bauer wrote:
>
> > Hello group,
> >
> > I'm trying to write a function in Python which does the following: For a
> > number of arguments which are all lists, return a list (or generator)
> > which yields all tuples of combination. E.g:
> >
>
>  Look here:
>
> http://docs.python.org/library/itertools.html#itertools.product
>
>  (new in 2.6, but code works in lower versions).
>

How would one go about installing the python 2.6 itertools code in python 2.5?

>  --Scott David Daniels
>  [email protected]
>
>
>
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decoding keyboard input when using curses

2009-05-31 Thread Chris Jones
On Sun, May 31, 2009 at 02:30:54PM EDT, Arnaud Delobelle wrote:
> Chris Jones  writes:

> [...]

> > Try this:
> >
> > #include 
> > #include 
> > #include 
> > #include 
> > #include 
> 
> /* Here I need to add the following include to get wint_t on macOS X*/
> 
> #include 

Ah.. interesting. My posts were rather linux-centric, I must say.

Naturally, the library & header files setup on MacOS would likely
differ.

[..]

> > gcc -lncursesw uni10.c -o uni10   # different lib..
> >  ^
> 
> My machine doesn't know about libncursesw:
> 
> marigold:c arno$ ls /usr/lib/libncurses*
> /usr/lib/libncurses.5.4.dylib
> /usr/lib/libncurses.dylib
> /usr/lib/libncurses.5.dylib
> 
> So I've compiled it with libncurses as before and it works.

Nothing to complain about.. makes it even more seamless..!

> This is what I get:
> 
> If I run the program and type 'é', I get a code of 'e9'.
> 
> In python:
> 
> >>> print '\xe9'.decode('latin1')
> é
> 
> So it has been encoded using isolatin1.  I really don't understand why.
> I'll have to investigate this further.

That's why I tested both my efforts with a euro symbol that I entered
via the Compose key + E= .. which generates 0x20AC in a UTF-8 setup.

> If I change the line:
> 
>setlocale(LC_ALL, ""); /* make sure UTF8   */
> 
> to
> 
>setlocale(LC_ALL, "en_GB.UTF-8");   /* make sure UTF8   */
> 
> then the behaviour is the same as before (i.e. get_wch() gets called
> twice instantly).
> 
> I'll do some more investigating (when I can think of *what* to
> investigate) and I will tell you my findings.

This is really strange.

I am absolutely certain that I had gotten my initial version, with the
old getch() .. etc. routines to work, but since I continued
experimenting with the same source snippet, I no longer had available to
investigate where I erred.

I copy/pasted the snippet back from my earlier post.. and so far I
haven't been able to get it work again.. :-(

The logic behind my assuming that getch() et al. should work
transparently in a UTF-8 context is that:

1. the 3NCURSES man pages are rather detailed and I could not find UTF-8
   or "unicode" mentioned anywhere apart from some obscure configuration
   option that is likely turned on everywhere by default.

2. More importantly, having to switch to the "wide character" macros or
   functions instead of the "narrow" versions would have meant that just
   about every application that uses ncurses would have had to be
   heavily patched - I would have imagined that all the changes would be
   made in the library in a transparent fashion so that the maintainers
   of such apps would only have had to link against the new ncurses
   lib..??? 

I'll keep you posted if I find something useful.

CJ

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


Re: Unzip Files

2009-05-31 Thread Chris Rebert
On Sun, May 31, 2009 at 2:42 PM, Brock  wrote:
> Hi all,
>
> I am new to python, so please don't attack me if this question is easy
> or basic.  How can I go about extracting the contents of a zip file to
> the same directory?  Can I extend this question to a zip file that
> sits on the internet?
>
> Point being I need to work with the files inside the zipped file, and
> there are times when the file is already on my computer, and their
> others where the datafile sits on the Internet.
>
> Any help you can provide will be greatly appreciated.  In full
> disclosure, I usually learn by example and not by trial and error, so
> any nudges in the right direction will be greatly appreciated.

See the extractall() method of ZipFile objects --
http://docs.python.org/library/zipfile.html

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


Re: Unzip Files

2009-05-31 Thread Tim Chase

I am new to python, so please don't attack me if this question is easy
or basic.  How can I go about extracting the contents of a zip file to
the same directory?  Can I extend this question to a zip file that
sits on the internet?


While the ZipFile object can take a file-like object, it looks 
like it expects to at least be able to seek() on that 
file-object.  The object you get back from a urlopen() call 
doesn't offer a seek(), so you can't directly use this object.


As such, you'd have to (1) download the remote .zip locally or 
(2) create your own urlopener (a'la urllib) that has a seek() 
method and uses HTTP Content-Range[1] if the server supports it. 
 Method #1 is fairly easy (especially if the file fits entirely 
within memory) but assumes the file isn't gargantuan because 
you're slurping the entire file over the network.  Method #2 
requires much crazier hacking skills but could produce serious 
gains if your file was mammoth.



Point being I need to work with the files inside the zipped file, and
there are times when the file is already on my computer, and their
others where the datafile sits on the Internet.


I'd create a wrapper that checks if the passed "filename" is a 
URL or a filename.  If it's not a local file, download it to a 
local tempfile, and then proceed with that file the same as with 
the local file, only optionally deleting it when done.


Since the ZipFile can take any file-like that allows for seek(), 
memory permitting, you can even read the web-content into a 
cStringIO object without having to touch your filesystem.


-tkc

[1]
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16



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


Re: Metaclass mystery

2009-05-31 Thread LittleGrasshopper
On May 31, 2:03 pm, [email protected] (Aahz) wrote:
> In article 
> ,
>
> LittleGrasshopper   wrote:
> >> On May 31, 12:19=A0am, Arnaud Delobelle  wrote:
>
> >>> [1]http://www.python.org/download/releases/2.2.3/descrintro/
>
> >I'm about 2/3 of the way through this paper (although I don't claim to
> >understand all of it.) There is some heavy duty material in there,
> >enough to make me feel really stupid and frustrated at times. I'm
> >making connections as I go though, hopefully everything will sink in
> >eventually.
>
> >Is this stuff actually tough, or am I just a dummy?
>
> Definitely tough!  Metaclasses can cause dain bramage.
> --
> Aahz ([email protected])           <*>        http://www.pythoncraft.com/
>
> my-python-code-runs-5x-faster-this-month-thanks-to-dumping-$2K-
>     on-a-new-machine-ly y'rs  - tim

Good to know, I'll stick to it and persevere. Will check doctor
regularly for dain bramage though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Simple metaclass code failing

2009-05-31 Thread LittleGrasshopper
This is some simple code which I got from Guido's paper on the
unification of classes and types, which Arnaud suggested to improve my
knowledge of metaclasses:

class M1(type):
pass
class M2(M1):
pass
class M3(M2):
pass
class C1:
__metaclass__ = M1
class C2(C1):
__metaclass__ = M2
class C3(C1, C2):
__metaclass__ = M3

It is failing when processing C3:
Traceback (most recent call last):
  File "metaerror.py", line 18, in 
class C3(C1, C2):
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases C2, C1

Since M3 is a subclass of M1 and M2 (which are the metaclasses for the
bases of C3, I don't understand the error. Then again, the error seems
to reference the MRO.

I hope this is one of those posts that I can look back in a few months
from now and think "Man, was that a dumb thing to ask!" Until then, I
would appreciate your help in trying to figure out what's going on.

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


Re: Simple metaclass code failing

2009-05-31 Thread LittleGrasshopper
On May 31, 3:52 pm, LittleGrasshopper  wrote:
> This is some simple code which I got from Guido's paper on the
> unification of classes and types, which Arnaud suggested to improve my
> knowledge of metaclasses:
>
> class M1(type):
>     pass
> class M2(M1):
>     pass
> class M3(M2):
>     pass
> class C1:
>     __metaclass__ = M1
> class C2(C1):
>     __metaclass__ = M2
> class C3(C1, C2):
>     __metaclass__ = M3
>
> It is failing when processing C3:
> Traceback (most recent call last):
>   File "metaerror.py", line 18, in 
>     class C3(C1, C2):
> TypeError: Error when calling the metaclass bases
>     Cannot create a consistent method resolution
> order (MRO) for bases C2, C1
>
> Since M3 is a subclass of M1 and M2 (which are the metaclasses for the
> bases of C3, I don't understand the error. Then again, the error seems
> to reference the MRO.
>
> I hope this is one of those posts that I can look back in a few months
> from now and think "Man, was that a dumb thing to ask!" Until then, I
> would appreciate your help in trying to figure out what's going on.
>
> Lukas

I forgot to say, this is Python 2.5.2 (in case that makes any
difference.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple metaclass code failing

2009-05-31 Thread Carl Banks
On May 31, 3:52 pm, LittleGrasshopper  wrote:
> This is some simple code which I got from Guido's paper on the
> unification of classes and types, which Arnaud suggested to improve my
> knowledge of metaclasses:
>
> class M1(type):
>     pass
> class M2(M1):
>     pass
> class M3(M2):
>     pass
> class C1:
>     __metaclass__ = M1
> class C2(C1):
>     __metaclass__ = M2
> class C3(C1, C2):
>     __metaclass__ = M3
>
> It is failing when processing C3:
> Traceback (most recent call last):
>   File "metaerror.py", line 18, in 
>     class C3(C1, C2):
> TypeError: Error when calling the metaclass bases
>     Cannot create a consistent method resolution
> order (MRO) for bases C2, C1
>
> Since M3 is a subclass of M1 and M2 (which are the metaclasses for the
> bases of C3, I don't understand the error. Then again, the error seems
> to reference the MRO.
>
> I hope this is one of those posts that I can look back in a few months
> from now and think "Man, was that a dumb thing to ask!" Until then, I
> would appreciate your help in trying to figure out what's going on.


http://www.python.org/download/releases/2.3/mro/


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


Re: Simple metaclass code failing

2009-05-31 Thread LittleGrasshopper
On May 31, 3:59 pm, Carl Banks  wrote:
> On May 31, 3:52 pm, LittleGrasshopper  wrote:
>
>
>
> > This is some simple code which I got from Guido's paper on the
> > unification of classes and types, which Arnaud suggested to improve my
> > knowledge of metaclasses:
>
> > class M1(type):
> >     pass
> > class M2(M1):
> >     pass
> > class M3(M2):
> >     pass
> > class C1:
> >     __metaclass__ = M1
> > class C2(C1):
> >     __metaclass__ = M2
> > class C3(C1, C2):
> >     __metaclass__ = M3
>
> > It is failing when processing C3:
> > Traceback (most recent call last):
> >   File "metaerror.py", line 18, in 
> >     class C3(C1, C2):
> > TypeError: Error when calling the metaclass bases
> >     Cannot create a consistent method resolution
> > order (MRO) for bases C2, C1
>
> > Since M3 is a subclass of M1 and M2 (which are the metaclasses for the
> > bases of C3, I don't understand the error. Then again, the error seems
> > to reference the MRO.
>
> > I hope this is one of those posts that I can look back in a few months
> > from now and think "Man, was that a dumb thing to ask!" Until then, I
> > would appreciate your help in trying to figure out what's going on.
>
> http://www.python.org/download/releases/2.3/mro/
>
> Carl Banks

Thank you, I'll read on that paper too in order to figure out what is
going on. I guess the resulting MROs do not satisfy monotonicity, I
just have to find out how to derive the MRO. I had the notion that it
was constructed by listing the current class, followed by the MROs of
each base in order, and then retaining the rightmost instance of each
class in the MRO list, but I think that might be an
oversimplification, since in this case that would be:
(C1, object)
(C2, C1, object)
(C3, C2, C1, object)
And I don't see any issues. But I'll read the paper to figure out what
the problem is, thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I change the behavior of the 'python-docs' action in IDLE?

2009-05-31 Thread samwyse
On Apr 16, 2:02 pm, samwyse  wrote:
> In the Windows version of Python 2.5, pressing F1 brought up the
> python.chm file.  I've just installed 2.6, and the same action 
> openshttp://www.python.org/doc/current/.  I'd prefer the former behavior.
> I know how to change the key bindings in config-keys.def, but I think
> I want to change the action, not the key binding.  Thanks.

I just installed Python 3.0.1 via the Windows 32-bit installer.
Opening "Python Docs" takes me to http://docs.python.org/dev/3.0/,
which doesn't exist.  Renaming python301.chm to python30.chm or
python300.chm doesn't seem to help find that file.  HELP!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating all combinations

2009-05-31 Thread Scott David Daniels

member thudfoo wrote:

On 5/31/09, Scott David Daniels  wrote:

Johannes Bauer wrote:

I'm trying to write a function in Python which ...

 Look here:
  http://docs.python.org/library/itertools.html#itertools.product
(new in 2.6, but code works in lower versions).

How would one go about installing the python 2.6 itertools code in python 2.5?


Either copy the code from the documentation for itertools.product
(_very_ easy), or go to the source for 2.6 and get a copy of
.../Lib/itertools.py and save as some other name in site-packages,
and try using that (I'd use some name like itertools_26).

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: hash and __eq__

2009-05-31 Thread Steven D'Aprano
On Sun, 31 May 2009 12:08:33 +0100, Arnaud Delobelle wrote:

> Anyway, it's good to know that quicksort is O(n^2) in the worst case -
> and that this worst case can crop up very easily in some situations,
> especially if not too much care has been taken implementing it.

The naive quicksort algorithm, where you recursively split the list into 
two halves, performs badly if the list is already sorted (or nearly so). 
It's easy to fix that: randomise the list before you sort! You can do 
that with a single pass of the list. That has the advantage of ensuring 
that no specific input can cause degraded performance, so an attacker 
can't DOS your application by passing sorted lists to be sorted.

Another strategy is to randomly exchange the pivot element when sorting. 
This avoids having to do a separate pass over the list, while still 
ensuring that no particular input can cause degraded performance.

A third strategy is to use a hybrid insertion/quicksort function. This is 
probably a good idea regardless, because for small lists, the overhead of 
quicksort generally makes insertion sort faster anyway. (CPython's sort 
used to be similar: it was a hybrid insertion/samplesort until, by 
memory, version 2.2, when it was changed for Timsort.)



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


Re: (windows) How to get information as string from a GreenHills project?

2009-05-31 Thread Gabriel Genellina

En Sat, 30 May 2009 23:28:23 -0300, Jebel  escribió:


I use python to start a GreenHills project in command line. And the
GreenHills project create a string which is include the information
that needed to be analyzed. How Can I return this string from
GreenHills project to python?


I have no idea what a GreenHills project is. But if "create a string"
means that it outputs something on screen, try the subprocess module:
http://docs.python.org/library/subprocess.html (see the very first example)

--
Gabriel Genellina

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


Turning HTMLParser into an iterator

2009-05-31 Thread samwyse
I'm processing some potentially large datasets stored as HTML.  I've
subclassed HTMLParser so that handle_endtag() accumulates data into a
list, which I can then fetch when everything's done.  I'd prefer,
however, to have handle_endtag() somehow yield values while the input
data is still streaming in.  I'm sure someone's done something like
this before, but I can't figure it out.  Can anyone help?  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Q: finding distance between 2 time's

2009-05-31 Thread CTO
On May 30, 8:49 pm, John Machin  wrote:
>   > import time
>   You are in a maze of twisty little functions, all alike.

Quote of the week. Perhaps the year. I hope you don't mind
me using it in the future.

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


Re: (windows) How to get information as string from a GreenHills project?

2009-05-31 Thread Jebel
On Jun 1, 9:33 am, "Gabriel Genellina"  wrote:
> En Sat, 30 May 2009 23:28:23 -0300, Jebel  escribió:
>
> > I use python to start a GreenHills project in command line. And the
> > GreenHills project create a string which is include the information
> > that needed to be analyzed. How Can I return this string from
> > GreenHills project to python?
>
> I have no idea what a GreenHills project is. But if "create a string"
> means that it outputs something on screen, try the subprocess 
> module:http://docs.python.org/library/subprocess.html(see the very first 
> example)
>
> --
> Gabriel Genellina

Thank you Gabriel. I resolved this problem with os.popen().
Thank you very much.
By the way, a GreenHills project means a project built by
GreenHills,:)

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


Re: Simple metaclass code failing

2009-05-31 Thread LittleGrasshopper
On May 31, 4:11 pm, LittleGrasshopper  wrote:
> On May 31, 3:59 pm, Carl Banks  wrote:
>
>
>
> > On May 31, 3:52 pm, LittleGrasshopper  wrote:
>
> > > This is some simple code which I got from Guido's paper on the
> > > unification of classes and types, which Arnaud suggested to improve my
> > > knowledge of metaclasses:
>
> > > class M1(type):
> > >     pass
> > > class M2(M1):
> > >     pass
> > > class M3(M2):
> > >     pass
> > > class C1:
> > >     __metaclass__ = M1
> > > class C2(C1):
> > >     __metaclass__ = M2
> > > class C3(C1, C2):
> > >     __metaclass__ = M3
>
> > > It is failing when processing C3:
> > > Traceback (most recent call last):
> > >   File "metaerror.py", line 18, in 
> > >     class C3(C1, C2):
> > > TypeError: Error when calling the metaclass bases
> > >     Cannot create a consistent method resolution
> > > order (MRO) for bases C2, C1
>
> > > Since M3 is a subclass of M1 and M2 (which are the metaclasses for the
> > > bases of C3, I don't understand the error. Then again, the error seems
> > > to reference the MRO.
>
> > > I hope this is one of those posts that I can look back in a few months
> > > from now and think "Man, was that a dumb thing to ask!" Until then, I
> > > would appreciate your help in trying to figure out what's going on.
>
> >http://www.python.org/download/releases/2.3/mro/
>
> > Carl Banks
>
> Thank you, I'll read on that paper too in order to figure out what is
> going on. I guess the resulting MROs do not satisfy monotonicity, I
> just have to find out how to derive the MRO. I had the notion that it
> was constructed by listing the current class, followed by the MROs of
> each base in order, and then retaining the rightmost instance of each
> class in the MRO list, but I think that might be an
> oversimplification, since in this case that would be:
> (C1, object)
> (C2, C1, object)
> (C3, C2, C1, object)
> And I don't see any issues. But I'll read the paper to figure out what
> the problem is, thanks.

Thank you for pointing that paper. I read the paper and figured out
what was wrong (local precedence is not maintained.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to find the last decorator of a chain

2009-05-31 Thread samwyse
On May 30, 6:16 pm, Gabriel  wrote:

> I have something like this:
>
> @render(format="a")
> @render(format="b")
> @
> def view(format, data):
>   return data

> In my understanding this equivalent to:
>
> render('a',
>  render('b',
>   view(***)))

Not quite.  'render' is a function of one argument that returns a
decorator. So, the equivalent is more like this:
  view = render('a')(render('b')(view))
or more simply:
  fb = render('b')
  view = fb(view)
  fa = render('a')
  view = fa(view)

> Is there any way to know, in this case, that 'a' is the 'default' format?

Will this do?  (In case the formatting gets messed up, I've also
posted the code to http://python.pastebin.com/f7f229d9d)

##from functools import wraps

def render(c):
def decorator(f):
##@wraps(f)
def wrapper(*args, **kwds):
if getattr(wrapper, 'outermost', False):
print('outer wrapper', c)
else:
print('inner wrapper', c)
return f(*args, **kwds)
return wrapper
return decorator

def mark_as_top(f):
print('marking', f)
f.outermost = True
##@wraps(f)
return f

@mark_as_top
@render('a')
@render('b')
@render('c')
@render('d')
def f():
pass

f()

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


Re: hash and __eq__

2009-05-31 Thread Terry Reedy

Steven D'Aprano wrote:

On Sun, 31 May 2009 12:08:33 +0100, Arnaud Delobelle wrote:


Anyway, it's good to know that quicksort is O(n^2) in the worst case -
and that this worst case can crop up very easily in some situations,
especially if not too much care has been taken implementing it.


The naive quicksort algorithm, where you recursively split the list into 
two halves, performs badly if the list is already sorted (or nearly so). 
It's easy to fix that: randomise the list before you sort! You can do 
that with a single pass of the list. That has the advantage of ensuring 
that no specific input can cause degraded performance, so an attacker 
can't DOS your application by passing sorted lists to be sorted.


Another strategy is to randomly exchange the pivot element when sorting. 
This avoids having to do a separate pass over the list, while still 
ensuring that no particular input can cause degraded performance.


A third strategy is to use a hybrid insertion/quicksort function. This is 
probably a good idea regardless, because for small lists, the overhead of 
quicksort generally makes insertion sort faster anyway. (CPython's sort 
used to be similar: it was a hybrid insertion/samplesort until, by 
memory, version 2.2, when it was changed for Timsort.


Which is hybrid binary insertion sort and mergesort, with b.i.s used for 
sublists less than 64 items.



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


Re: [Tutor] Challenge supporting custom deepcopy with inheritance

2009-05-31 Thread Michael H . Goldwasser

Hi Kent,

Thanks for your thoughts. 

For the original example code, you are correct that we could make it
work by having B provide the one-arg constructor to match A's
constructor signature.  But I don't see this as a general solution.

Having B.__deepcopy__() make a call to A.__deepcopy__() assumes that A
supports __deepcopy__ either direclty or indirectly.  This is not
guaranteed as __deepcopy__ is not supported all the way back to the
object base class.  It could be that the author of A has guaranteed
that the syntax deepcopy(instanceA) is properly supported, but that
could be done by other means without an explicit __deepcopy__ (such as
relying on a true deep copy, or using getstate/setstate to affect both
pickling and deepcopy).

As another basic puzzle, consider a class definition for B where B has
a registry list that it doesn't want cloned for the new instance (but
it does want pickled when serialized).  This would seem to require
that B implement its own __deepcopy__.   We want to somehow rely on
the class definition for A to enact the cloning fo the state defined
by A.   But without knowing about how A supports the deepcopy
semantics, I don't see how to accomplish this goal.

class B(A):
def __init__(self):
self.__registry = []

def register(self, obj):
self.__registry.append(obj)

def __deepcopy__(self, memo={}):
dup =   # would like something like A's version of 
deepcopy(self,memo)
# as our starting point but we need an instance of 
class B
# and B.__deepcopy__ masks our ability to rely on the
# inherited semantics of deepcopy(self)
dup.__registry = []
memo[id(self)] = dup
return dup


On Sunday May 31, 2009, Kent Johnson wrote: 

>On Sun, May 31, 2009 at 5:35 PM, Michael H. Goldwasser  
> wrote:
>>
>> Yesterday, I posted a question to python-list involving custom
>> deepcopies in an inheritance hierarchy.  I haven't received any
>> responses, so I thought I'd cross-post to see if anyone on tutor
>> has any thoughts.
>>
>> To avoid splitting the thread, I'll simply reference the original post at
>> http://mail.python.org/pipermail/python-list/2009-May/714866.html
>> and ask for responses to be sent there.
>
>Sorry, splitting the thread for you...
>
>ISTM that in general B.__deepcopy__() should call A.__deepcopy__() to
>do the "A" part of the work. In your example, this won't work because
>A.__deepcopy__() assumes that subclasses have a one-argument
>constructor. So, I would say that B is not fulfilling the contract
>assumed by A.
>
>What if you give B a one-arg constructor by making the bTag argument
>optional? Then I think B.__deepcopy__() can call A.__deepcopy__(),
>then do the "B" part of the copy on the result.
>
>Kent


   +---
   | Michael Goldwasser
   | Associate Professor
   | Dept. Mathematics and Computer Science
   | Saint Louis University
   | 220 North Grand Blvd.
   | St. Louis, MO 63103-2007
   |
   | Office: Ritter Hall 6
   | Email:  [email protected]
   | URL:http://cs.slu.edu/~goldwasser
   | Phone:  (314) 977-7039
   | Fax:(314) 977-1452

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


Re: try except inside exec

2009-05-31 Thread alex23
Michele Petrazzo  wrote:
> I want to execute a python code inside a string and so I use the exec
> statement. The strange thing is that the try/except couple don't catch
> the exception and so it return to the main code.
> Is there a solution to convert or make this code work?
>
> My code:
>
> STR = """
> err = 0
> try:
>    def a_funct():
>      1/0
> except:
>    import traceback
>    err = traceback.format_exc()
> """
>
> env = {}
> exec STR in env
> env["a_funct"]()
> print env["err"]

Hello Michele,

>From your code, I'm not sure if you're aware that functions are
themselves objects within Python. You could avoid the use of exec
entirely by doing something like the following:

import traceback

class FuncTester(object):
  def __init__(self, function):
self.function = function

  def test(self, *args, **kwargs):
self.result, self.error = None, None
try:
  self.result = self.function(*args, **kwargs)
  success = True
except:
  self.error = traceback.format_exc()
  success = False
return success

>>> def f(x): return 'f does this: %s' % x
...
>>> ft = FuncTester(f) # note that we're referring to the function directly
>>> ft.test('foo')
True
>>> ft.result
'f does this: foo'
>>> ft.test()
False
>>> print ft.error
Traceback (most recent call last):
  File "tester.py", line 10, in test
self.result = self.function(*args, **kwargs)
TypeError: f() takes exactly 1 argument (0 given)

I think you'll find this approach to be a lot more flexible than using
exec.

Hope this helps,
alex23
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pygame error: file is not a windows bmp file

2009-05-31 Thread Aahz
In article ,
Djames Suhanko   wrote:
>
>"pygame error: file is not a windows bmp file"
>
> I couldn't found a solution for this problem.
>My python script run fine in local machine using cxfreeze, but don't
>work when copied to my live linux system.
>If I put bmp image, works fine, but png don't.
>Can you help me?

Convert with PIL?
http://www.pythonware.com/products/pil/
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

my-python-code-runs-5x-faster-this-month-thanks-to-dumping-$2K-
on-a-new-machine-ly y'rs  - tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling and transporting modules/libraries in python

2009-05-31 Thread alex23
On May 31, 2:27 am, Abe  wrote:
>     I use python at a home office and in a university computer lab,
> but I don't have the administrative rights to install libraries on the
> lab computers.  It would be really nice if there were a way I could
> put, say, all of numpy into a file "my_numpy.pyc" and treat it as a
> single (large) module.

You should be able to use virtualenv to provide this functionality:

  http://pypi.python.org/pypi/virtualenv

Create the environment you want on your home computer, then copy it
wholesale to your lab computer or even use it directly from a USB
device.

You might also want to look into one of the portable Python set ups.
This way you can have a fully portable environment that you control
completely:

  Portable Python: http://www.portablepython.com/
  Movable Python: http://www.voidspace.org.uk/python/movpy/

Hope this helps.

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


Re: automated web with python?

2009-05-31 Thread P. Kaminski
OK, thanks, I'll give it a try,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Turning HTMLParser into an iterator

2009-05-31 Thread Stefan Behnel
samwyse wrote:
> I'm processing some potentially large datasets stored as HTML.  I've
> subclassed HTMLParser so that handle_endtag() accumulates data into a
> list, which I can then fetch when everything's done.  I'd prefer,
> however, to have handle_endtag() somehow yield values while the input
> data is still streaming in.  I'm sure someone's done something like
> this before, but I can't figure it out.  Can anyone help?  Thanks.

If you can afford stepping away from HTMLParser, you could give lxml a try.
Its iterparse() function supports HTML parsing.

http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk

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


Is there any module for sea tides?

2009-05-31 Thread alejandro
I found some in C but could not find in Python 


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