Re: Is there a way to find IP address?

2006-09-15 Thread Tim Roberts
"Lad" <[EMAIL PROTECTED]> wrote:
>
>Normaly I can log user's IP address using os.environ["REMOTE_ADDR"] .
>If a user  is behind a proxy, I will log  proxy's IP address only.
>Is there a way how to find a real IP user's address?

Not reliably, but why would you want to?  That IP address is not reachable
from your server anyway.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pre-defining an action to take when an expected error occurs

2006-09-15 Thread John Machin
Tempo wrote:
> Thanks for all of the help. It all has been very useful to an new
> python programmer. I agree that I should fix the error/bug instead of
> handeling it with a try/etc. However, I do not know why
> "range(sh.nrows)" never gets the right amount of rows right. For
> example, if the Excel sheet has 10 rows with data in them, the
> statement "range(sh.nrows)" should build the list of numbers [0,
> 1,...9]. It should, but it doesn't do that. What it does is buld a list
> from [0, 1...20] or more or a little less, but the point is that it
> always grabs empy rows after the last row containing data. Why is that?
> I have no idea why, but I do know that that is what is producing the
> error I am getting. Thanks again for the responses that I have received
> already, and again thanks for any further help. Thanks you.

So the xlrd package's Book.Sheet.nrows allegedly "never gets the right
amount of rows right"? Never?? Before making such rash statements in a
public forum [1], you might like to check exactly what you have in your
file. Here's how:

(1) Using OpenOffice.org Calc or Gnumeric (or Excel if you must), open
yourfile.xls and save it as yourfile.csv. Inspect yourfile.csv

(2) Use the runxlrd script that's supplied with xlrd:

runxlrd.py show yourfile.xls >yourfile_show.txt

Inspect yourfile_show.txt. You'll see things like:
cell A23: type=1, data: u'ascii'
cell B23: type=0, data: ''
cell C23: type=1, data: u'123456'
cell D23: type=0, data: ''
cell E23: type=4, data: 0
The cell-type numbers are in the docs, but briefly: 0 is empty cell, 1
is text, 2 is number, 3 is date, 4 is boolean, 5 is error. If you find
only type=0 in the last row, then indeed you have found a bug and
should report it to the package author (together with a file that
exhibits the problem).

You are likely to find that there are cells containing zero-length
strings, or strings that contain spaces. They *do* contain data, as
opposed to empty cells.

[1] There's a possibility that the package's author reads this
newsgroup, and I've heard tell that he's a cranky old so-and-so; you
wouldn't want him to take umbrage, would you?

HTH,
John

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


Re: Help me use my Dual Core CPU!

2006-09-15 Thread Simon Wittber
Wolfgang Keller wrote:
> > Are there any other concurrency options I've not discovered yet?
>
> PyMPI?
>
> Ironpython?
>

I'm looking at IronPython right now. I'm attempting to get it to run
pybench, but first, I think I have to work out how to enable
tracebacks...

When the dual core notebook finally arrives, I'm going to test out this
code:

http://entitycrisis.blogspot.com/2006/09/if-i-had-concurrent-python-what-would-i.html

(a multithreaded map function) on some nice large pixel buffers, and
compare performance to CPython. I think the results will be very
interesting!

-Sw.

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


Re: Is there a way to find IP address?

2006-09-15 Thread Winfried Tilanus
On 09/15/2006 Lad wrote:
> How can be HTTP_X_FORWARDED_FOR easily  spoofed? I thought that  IP
> address is not possible change.

Because it is a header that is added by the proxy. This header has (or
should have) no role in the proces of relaying the request by the proxy.
It is just politely added by the proxy to make it possible to identify
for who the request is forwarded. So the proxy might add anything it
likes, or nothing at all if it is an anonymizing proxy.

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


Check if variable is an instance of a File object

2006-09-15 Thread sc_wizard29
Hi everyone,

Maybe these questions will sound strange to you, but I sometime have a
hard time switching from Java to Python ;-)

Let's say I have a function like this :

def show_lines(file):
for next_line in file:
...

What can I do to be sure that the input argument is indeed a 'File'
object ?

#1 : should I start by checking that 'file' is indeed an instance of a
File object ? (and how do I do this ?)
#2 : should I do nothing ? (but I don't like the idea of risking to
have a runtime exception raised somewhere)

Thanks for helping...

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


UDP packets to PC behind NAT

2006-09-15 Thread Janto Dreijer
This is probably more of a networking question than a Python one, but
it would be nice to know if someone has done this with Python's socket
module. And besides one usually gets more information from c.l.py than
anywhere else :)

I have a server with a static "public" IP and a client behind a NAT. I
would like to send UDP packets from the server to the client. So what I
need to do is open up a "hole" in the NAT and let the server know the
target IP and port of the client where it can send its packets.

Now I have read somewhere that you can have TCP and UDP running on the
same port. Not sure if this is true. Would it be a reasonable solution
to initiate a TCP connection from the client to the server and somehow
(?) let the server figure out how the client is connecting? And then
send UDP to client over the same (IP, port)?

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


Re: Looking for the Perfect Editor

2006-09-15 Thread Ramon Diaz-Uriarte
On 9/15/06, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:
> Ramon Diaz-Uriarte wrote:
> >> c) can run programs right from within
> >
> > But of course. And, contrary to some others (e.g., JEdit, which I
> > think forces you to use Jython, so you are stuck with Python 2.1 for
> > now) you use the current python interpreter you have installed.
>
> Wrong. But so terribly wrong ;). Jython is not at all needed to use
> python with jEdit. I think the only reason to actually use Jython in

OK, so I stand corrected. However:

- I did not want to imply that you need Jython for editing Python with
JEdit. JEdit can eidt Python files without Jython, of course.

- I was referring to executing arbitrary sections of a Python file in
a Python interpreter in an "integrated way". When I tried JEdit, I
think that Jython was the way to go. (And I think this was also the
case for a while, at least to judge from D. Metrz's review
http://www-128.ibm.com/developerworks/library/l-cpyide/


> The console plugin (probably THE most useful of the pack) gives you a
> system shell and means to start compilers/interpreters based on your

But isn't this a "generic console": you go to the console, and then
type "python2.3" or "python2.4" or whatever? How do you send arbitrary
selections of Python code from the file you are editing to this shell?
Is there a way to mark a section of code and have it evaluated by the
python interpreter? Or a function definition?


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


Re: Check if variable is an instance of a File object

2006-09-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, sc_wizard29
wrote:

> Maybe these questions will sound strange to you, but I sometime have a
> hard time switching from Java to Python ;-)
> 
> Let's say I have a function like this :
> 
> def show_lines(file):
>   for next_line in file:
>   ...
> 
> What can I do to be sure that the input argument is indeed a 'File'
> object ?

Why do you want to be sure?  I would even rename the argument:

def show_lines(lines):
for line in lines:
...

This works with *every* iterable that contains "lines".  No need to
"cripple" it with a type checking.

> #2 : should I do nothing ? (but I don't like the idea of risking to
> have a runtime exception raised somewhere)

Then don't use Python.  Except `SyntaxError` almost every
exception is a runtime one.

And what do you do if you check for `file` and it isn't such an instance? 
Raise an exception?  A no, that's something you don't like.  So what else?  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check if variable is an instance of a File object

2006-09-15 Thread Calvin Spealman
On 15 Sep 2006 00:18:14 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Hi everyone,
>
> Maybe these questions will sound strange to you, but I sometime have a
> hard time switching from Java to Python ;-)
>
> Let's say I have a function like this :
>
> def show_lines(file):
> for next_line in file:
> ...
>
> What can I do to be sure that the input argument is indeed a 'File'
> object ?
>
> #1 : should I start by checking that 'file' is indeed an instance of a
> File object ? (and how do I do this ?)
> #2 : should I do nothing ? (but I don't like the idea of risking to
> have a runtime exception raised somewhere)
>
> Thanks for helping...
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Do nothing!

The caller might pass you a file-like object, and you can never be
exactly sure. Duck typing rules in this case. If what they pass acts
like a file, then it must be a file (for as much as the function needs
to care, anyway). Don't want to risk an exception at runtime? Well,
isn't that what you would do if you explicitly checked for a file
object and had something else, anyway? Just assume its a file and if
there is an error it should propogate because one of the callers
messed up and should know that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for the Perfect Editor

2006-09-15 Thread Ramon Diaz-Uriarte
On 9/15/06, David J. Braden <[EMAIL PROTECTED]> wrote:
> Wildemar Wildenburger wrote:

(...)
> > jEdit is extensible though java, and with the jython plugin also through
> > python.
>
> Thanks. That helps me get a sense of the landscape.

As an emacs user, this is a clear plus for JEdit (and for vim, for that matter).

>
> Very much so, and many thanks. My only languages are C and VBA, and the
> environments of R and Mathematica (hey, I'm ancient).

If the "R" you refer is the statistical environment, "GNU S", then you
probably want to check Emacs (with ESS): you get an integrated
environment where you can edit code, submit code pieces (lines,
regions, buffers, functions, etc) to a running R process (which looks
like another Emacs buffer),  opening R help in another buffer (with
the possibility of executing the example in the R process), clean up a
transcript of an R session to keep only the code, etc, etc, etc.
Moeover, you get a "smart" edition of Sweave (noweb literate
programming), where emacs knows when you are in a LaTeX part and when
you are in an R code chunck.

Alternatively, in the Windoze world, you might want to check Tinn-R,
which, regarding R, provides some similar functionality, and I think
it is also very nice for Python, LaTeX, etc.

HTH,

R.

-- 
Ramon Diaz-Uriarte
Bioinformatics Unit
Spanish National Cancer Centre (CNIO)
http://ligarto.org/rdiaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check if variable is an instance of a File object

2006-09-15 Thread sc_wizard29

Marc 'BlackJack' Rintsch a ecrit :

> And what do you do if you check for `file` and it isn't such an instance?
> Raise an exception?  A no, that's something you don't like.  So what else?  
> ;-)

Well, I prefer the idea of raising my *own* exception to the idea of
having an unknown behavior occur (for ex : what if the argument is NOT
a File, but is "itereable" ?)

But anyway, I guess the most "pythonic" way is to do nothing ;-)


One more question : how to test if 'file' is a File object ?

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


Re: Outbound port on sockets

2006-09-15 Thread Diez B. Roggisch
Bryan Olson schrieb:
> Diez B. Roggisch wrote:
>> bmearns schrieb:
>>> Is it possible to specify which port to use as the outbound port on a
>>> connection? 
> [...]
>>> Specifically, I'm trying to write an FTP host, and I'm trying to
>>> implement the PORT command. 
>>
>> AFAIK you neither can't do that nor need it.
> 
> It's not the issue here, but to specify the outgoing port
> call bind(('', portnum)) before connect().

I wasn't aware of that. Cool.

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


Re: Check if variable is an instance of a File object

2006-09-15 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> 
> Marc 'BlackJack' Rintsch a ecrit :
> 
>> And what do you do if you check for `file` and it isn't such an instance?
>> Raise an exception?  A no, that's something you don't like.  So what
>> else?  ;-)
> 
> Well, I prefer the idea of raising my *own* exception to the idea of
> having an unknown behavior occur (for ex : what if the argument is NOT
> a File, but is "itereable" ?)
> 
> But anyway, I guess the most "pythonic" way is to do nothing ;-)

Indeed, don't waste time to make your code less general. Why would you want
to prevent your show_lines() function from processing a list of strings or
a StringIO?
 
> One more question : how to test if 'file' is a File object ?

The file type is actually spelt lowercase, so 'file' is not a good idea as a
variable name.

>>> f = file("tmp.txt")
>>> isinstance(f, file) # isinstance(f, open) looks odd
True

isinstance() returns True for subclasses, if you don't want that either:

>>> type(f) is file
True

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


add without carry

2006-09-15 Thread Hugh
I would like to perform an addition without carrying of two integers...
I've got no idea how to do this in python, although I've been using it
for web/cgi/db work for a few years now.

Any help would be great.

Hugh

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


Re: Check if variable is an instance of a File object

2006-09-15 Thread sc_wizard29
Thanks for your help peter !

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


Re: UDP packets to PC behind NAT

2006-09-15 Thread Christophe
Janto Dreijer a écrit :
> This is probably more of a networking question than a Python one, but
> it would be nice to know if someone has done this with Python's socket
> module. And besides one usually gets more information from c.l.py than
> anywhere else :)
> 
> I have a server with a static "public" IP and a client behind a NAT. I
> would like to send UDP packets from the server to the client. So what I
> need to do is open up a "hole" in the NAT and let the server know the
> target IP and port of the client where it can send its packets.
> 
> Now I have read somewhere that you can have TCP and UDP running on the
> same port. Not sure if this is true. Would it be a reasonable solution
> to initiate a TCP connection from the client to the server and somehow
> (?) let the server figure out how the client is connecting? And then
> send UDP to client over the same (IP, port)?

Initiate an UDP connection from the client to the server and have the 
server send back the UDP packets to the address you get in the 
"recvfrom" result.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XPN 0.6.5 released

2006-09-15 Thread Nemesis
Marc 'BlackJack' Rintsch wrote:
> > XPN is monothreaded, so when it is downloading the headers (it is a
> > monolotic job) the progress bar can't be updated.
> Why?  I guess there's a loop involved.  Can't you update the GUI after
> each message?

If you use the "Donwload New Headers" function XPN will download the
header for the subscribed groups, for each group it has to send the
NNTP command XOVER to retrieve the new headers. For each group I update
the interface when the XOVER command ends, so the interface gets
updated betweenfor every group but if there are a lot of new headers
the XOVER command can take a lot of time ... and during this time I
can't update the interface.
This is the pseudo-code

for group in subscribed:
nntplib.xover(group)
statusbar.push("Downloaded ...")
gtk.update_interface()

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


Re: RELEASED Python 2.5 (release candidate 2)

2006-09-15 Thread Ant

Georg Brandl wrote:
> Georg Brandl wrote:
...
> > Please open a bug in the tracker at http://www.sf.net/projects/python.
> 
> Wait, don't bother - just fixed it myself.

Nice one, cheers!

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


Re: add without carry

2006-09-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Hugh wrote:

> I would like to perform an addition without carrying of two integers...
> I've got no idea how to do this in python, although I've been using it
> for web/cgi/db work for a few years now.

Your description is a bit vague.  What is `without carrying`?  Do you want
to limit the result to a given bit length with a "wrap around" behavior if
the number gets too large to fit into those bits?  Then this should do the
trick:

  a = (b + c) & (2**bits - 1)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: add without carry

2006-09-15 Thread John Machin

Hugh wrote:
> I would like to perform an addition without carrying of two integers...
> I've got no idea how to do this in python, although I've been using it
> for web/cgi/db work for a few years now.
>

In multiword addition in assembly language, one uses a normal ADD
instruction on the lowest-order pair of words, and an ADC (or ADDC or
whatever) i.e add *with* carry which adds in the carry bit from the
previous operation for each subsequent pair of words. IOW, addition
*without* carrying is normal, and I don't recall hearing the expression
before ..

Do you possibly mean: add two 32-bit integers such the result fits in
32 bits i.e. discard the generated carry bit, keep the low-order
32-bits?

If so, that's simply (a + b) & 0x (in Python as well as a few
other languages).

If you meant a different number of bits, well the answer for 8 bits
would be (a + b) & 0xFF.

Otherwise, you need to provide some examples of two integers and what
"addition without carrying" produces.

HTH,
John

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


blt error using py2exe

2006-09-15 Thread Agathe Sørflaten
Title: Message





Hello!
I have problem of using a exe file (it did well to make the exe 
file with py2exe) with the blt to make gui programs with graphics with 
windows. It seems to work well on my computer, but when running the 
.exe file on another computer I got the message:
Exception in Tkinter callback
Traceback (most recent call last):
File "Tkinter.pyc", line 1345, in __call__
File "SIT_graphics_testing.py", line 910, in 
next2
File "P:\Forsk\_diverse administrasjon FORSK\SIT New 
Version by AS\dist2\PmwBlt.py", line 99, in __init__
TclError: invalid command name 
"::blt::vector"
Exception _tkinter.TclError: 'invalid command name 
"::blt::vector"' in 
 
The folder is 
dist2/tcl/tcl8.4 and tk8.4 and where blt2.4 is under tcl8.4. I use version 
python 2.4 and py2exe 0.6.5 
So is the problem that the path for tcl/tk is not 
included in the path variable on other computers that mine? Do I need to install 
the python, pmw, blt, tcl/tk on the other computer as well?
I have copied pmw.py (made by using bundlepmw.py) and 
pmwblt.py and pmwcolor.py into the dist2 folder in the process of making an 
exe-file. 
I really hope that 
someone can help me! 
Agathe 
Sorflaten
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: add without carry

2006-09-15 Thread Hugh
Sorry, here's an example...

5+7=12

added without carrying, 5+7=2

i.e the result is always less than 10

I've been thinking some more about this and my brain is starting to
work something out... I just wondered if there was a function in python
math to do this automatically...

Hugh

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


Re: add without carry

2006-09-15 Thread MonkeeSage
Hugh wrote:
> Sorry, here's an example...
>
> 5+7=12
>
> added without carrying, 5+7=2
>
> i.e the result is always less than 10

def add(a, b, c=10):
  an = a + b
  if an >= c:
an -= c
  return an

add(5, 7) # = 2

?

Regards,
Jordan

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


Re: add without carry

2006-09-15 Thread Bryan Olson
Hugh wrote:
> Sorry, here's an example...
> 
> 5+7=12
> 
> added without carrying, 5+7=2
> 
> i.e the result is always less than 10

Are you looking for bitwise exclusive or? In Python it's
the '^' operator. For example:

 print 5 ^ 7


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


Re: add without carry

2006-09-15 Thread Hugh
Thankyou everyone this gives me something to work with.

Hugh

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


Re: add without carry

2006-09-15 Thread Peter Otten
Hugh wrote:

> Sorry, here's an example...
> 
> 5+7=12
> 
> added without carrying, 5+7=2
> 
> i.e the result is always less than 10
> 
> I've been thinking some more about this and my brain is starting to
> work something out... I just wondered if there was a function in python
> math to do this automatically...

>>> (5 + 7) % 10
2

In this context '%' is called 'modulo operator'. What John and Marc
suggested is basically the same operation for the special case of binary
numbers, i. e.

a % b == a & (b-1)

if a >= 0 and b == 2**N.

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


Re: add without carry

2006-09-15 Thread Hugh
Peter,

That was what I was thinking along the lines of, It's been two years
since I finished my CS degree and working in mechanical engineering
means I've nearly forgotten it all! :(

Thanks, I'll write a function in my app to handle this...

Hugh

> >>> (5 + 7) % 10
> 2
>
> In this context '%' is called 'modulo operator'. What John and Marc
> suggested is basically the same operation for the special case of binary
> numbers, i. e.
> 
> a % b == a & (b-1)
> 
> if a >= 0 and b == 2**N.
> 
> Peter

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


Re: [ANN] XPN 0.6.5 released

2006-09-15 Thread Franz Steinhaeusler
On Thu, 14 Sep 2006 19:36:01 GMT, Nemesis <[EMAIL PROTECTED]>
wrote:

>Mentre io pensavo ad una intro simpatica "Franz Steinhaeusler"
>scriveva:
>
>>>XPN (X Python Newsreader) is a multi-platform newsreader with Unicode
>[...]

Hello Nemesis,

>> Hello Nemesis,
>> that is a great program, thank you.
>
>Thanks.

you're welcome.

>
>> I will try to use it and also attempt to 
>> customize it, so that it works like forte agent.
>> Even better would it be to have it in wxPython
>
>I disagree :-D

He he :)

>
>> Some little points:
>>
>> There is no progress bar or other info, if I subscribe one list.
>> There is a little in the lower left corner, but if a lot of headers
>> and bodies are received, the program seems to hang.
>> I actually killed it, because I thought that hanging.
>
>XPN is monothreaded, so when it is downloading the headers (it is a
>monolotic job) the progress bar can't be updated.
>
>> It would be nice, if I click on the groups pane another group, 
>> the messages appear immediatly, without needing to double click the
>> group.
>
>You can configure this behaviour, in the Configure Window go to
>"Misc"->"Miscellaneous" and you'll find two check buttons
>One Click Enter Group
>One Click Enter Article

Thanks, this is quite useful.

>
>> When composing messages, the tab size is 8. It would be nice to 
>> have the possibility to adjust this size.
>
>Hmm, it is a GTK default I don't know if I can change it, I'll check it.

Not so important.

A few other notes (or should I post into the feature requests on
sourceforge?)

little point: I find it superfluos on the header pane, to always have
the term "Re:" before (it would probaly easier to read without this
text).

an option possibly (as in agent): if you click on the tree the "+" sign,
it would be more convenient (for me) to open *all* subbranches, this
means show all responses headers for this thread.

if you change the groups, it would be nice to remember the position of
the last readed thread in the header pane, which means changing forth
and back to a certain group (as option for example).

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


Re: add without carry

2006-09-15 Thread Bruno Desthuilliers
Hugh wrote:
> Sorry, here's an example...
> 
> 5+7=12
> 
> added without carrying, 5+7=2
> 
> i.e the result is always less than 10

> I've been thinking some more about this and my brain is starting to
> work something out... 

No need to think too long to come up with the most possibly Q&D solution:

res = int(str(5 + 7)[-1])

Like it ?-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: add without carry

2006-09-15 Thread Bruno Desthuilliers
Bryan Olson wrote:
> Hugh wrote:
>> Sorry, here's an example...
>>
>> 5+7=12
>>
>> added without carrying, 5+7=2
>>
>> i.e the result is always less than 10
> 
> Are you looking for bitwise exclusive or? In Python it's
> the '^' operator. For example:
> 
> print 5 ^ 7
> 
> 
>>> 10 ^ 21
31

Not really "less than 10"...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a varargs tuple to a list - a definite pitfall for new comers to Python

2006-09-15 Thread metaperl

Georg Brandl wrote:
> [EMAIL PROTECTED] wrote:
> > The following program does not work if you uncomment #lis =
> > ["xmms2"] + list(args)
> >
> > Evidently Python is opting for the nullary constructor list() as
> > opposed to the other one which takes a sequence. But no newcomer would
> > know this. And the Python docs dont give a good example of dealing with
> > taking a sequence of args and converting it to a list.
>
> Evidently you overlooked having defined a list() in global scope
> yourself which takes no arguments.

MASSIVELY overlooked it. Gosh. How embarrassing.

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


Re: add without carry

2006-09-15 Thread Christophe
Bruno Desthuilliers a écrit :
> Bryan Olson wrote:
>> Hugh wrote:
>>> Sorry, here's an example...
>>>
>>> 5+7=12
>>>
>>> added without carrying, 5+7=2
>>>
>>> i.e the result is always less than 10
>> Are you looking for bitwise exclusive or? In Python it's
>> the '^' operator. For example:
>>
>> print 5 ^ 7
>>
>>
 10 ^ 21
> 31
> 
> Not really "less than 10"...

But you must use numbers smaller than 10 as input! Still :

 >>> 8 ^ 2
10

:D

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


Re: Converting a varargs tuple to a list - a definite pitfall for new comers to Python

2006-09-15 Thread metaperl

John Machin wrote:
> [EMAIL PROTECTED] wrote:
> > The following program does not work if you uncomment #lis =
> > ["xmms2"] + list(args)
> >
> > Evidently Python is opting for the nullary constructor list() as
> > opposed to the other one which takes a sequence. But no newcomer would know 
> > this.
>
> Are you using "the nullary constructor list()" to mean "the 0-argument
> function list() that appears later in the script", and "the other one
> which takes a sequence" to mean the builtin function list()"???

No,  I'm talking about listing 2 here:
http://www-128.ibm.com/developerworks/library/os-python4/index.html

which states:
"If you look closely at the description for the list class in Listing
2, you'll see that two different constructors are provided. One takes
no arguments, and the other takes a sequence class."

and I figured that since the lower bound on arguments to *args could
zero, that Python was
default to the nullary constructor even before the function got its
args.

paranoia will do these things to you.


>
> >  And the Python docs dont give a good example of dealing with
> > taking a sequence of args and converting it to a list.
>
> You have produced 2 perfectly good examples yourself. What's your
> point?

I just mean that this:
http://docs.python.org/tut/node6.html#SECTION00673

does not use list() at all.



> Here's a tip: when you get into a pickle like that, try running
> pychecker and/or pylint over your code. Here's what pychecker has to
> say:
>
> metaperllist.py:4: Invalid arguments to (list), got 1, expected 0
> metaperllist.py:10: (list) shadows builtin


Great suggestion. I had not heard of those. Thanks.

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


Python for science (was: Re: Looking for the Perfect Editor)

2006-09-15 Thread Wildemar Wildenburger
David J. Braden wrote:
> I've come to sense, in the last (many) threads and topics brought up 
> that I have read in the last 3 weeks, that this NG attracts folks who 
> are very much into the web-app interface potential and usefulness of 
> Python, as you yourself seem to be (see following), and others, such as 
> I, who appreciate its power for technical apps, such as hard-core stats, 
> optimization, and integration with even more sophisticated off-the-shelf 
> apps, as well as home-brewed stuff, hopefully even original algorithms. 
>   I have seen, several times in this NG, references to "scientific 
> stuff". I take it to mean apps meant for, or used by, folks in 
> engineering, physics, applied mathematics, exploratory theoretical stats 
> and practical applied stats (at a very high level) --- these users have 
> PhDs in areas dealing with "scientific stuff". What's *your* view take 
> on this?
> 
I use python purely for personal coding, so I cannot give you much 
advice on scientific use of python. I understand however that it is very 
much used for what you describe. I still don't know what you're asking 
exactly, so I hope that's what you wanted to hear.


>> You might want to look at python packages such as scipy (?) or numpy 
>> (for numerical calculations) or whatever those are called.
> 
> "Whatever those ..." ?!? Maybe this clarifies my response.
Scipy: http://www.scipy.org/
Numpy: http://numpy.scipy.org/ (maybe that explains my confusion ;))
Scientific Python: http://sourcesup.cru.fr/projects/scientific-py/

Better?

> Thanks. I hope to very soon. Potential interactions with other APIs are 
> keeping me up nights. I could use your help on one of these in the near 
> future.
By 'you' you certainly mean the newsgroup, right? 'Cause I know nothing 
of that.

>>> I am not interested in Web/html apps.
>> Too bad, that's the future ;).
> 
> For whom?!? When? Been to a so-called 3rd-world country for an extended 
> period yet? Think Angola, Chad, ...
I. Was. Kidding.
Sort of ... :)
Seriously: Many people use it for the web, because python is just so 
darn good at it. An there is a trend towards web-based apps. There's n 
denying that.
Are you telling me that in, say, Angola they only use python for their 
hardcore scientific calculations? I don't quite get that argument. 
Though I understand your angle.

I'm out
wildemar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for the Perfect Editor

2006-09-15 Thread Wildemar Wildenburger
Ramon Diaz-Uriarte wrote:
> - I was referring to executing arbitrary sections of a Python file in
> a Python interpreter in an "integrated way". When I tried JEdit, I
> think that Jython was the way to go. (And I think this was also the
> case for a while, at least to judge from D. Metrz's review
> http://www-128.ibm.com/developerworks/library/l-cpyide/
> 
> 
>> The console plugin (probably THE most useful of the pack) gives you a
>> system shell and means to start compilers/interpreters based on your
> 
> But isn't this a "generic console": you go to the console, and then
> type "python2.3" or "python2.4" or whatever? How do you send arbitrary
> selections of Python code from the file you are editing to this shell?
> Is there a way to mark a section of code and have it evaluated by the
> python interpreter? Or a function definition?

Ahh, I see. Well, you're right, that is not that easily possible. But 
you know what? I've never missed such functionality; the "if __name__ 
..." trick always sufficed for me. Buts thats taste of course, lets not 
debate that.
So OK, jEdit is not that 'integrated' after all. Oh well ...

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


Re: add without carry

2006-09-15 Thread Bryan Olson
Bruno Desthuilliers wrote:
> Bryan Olson wrote:
>> Hugh wrote:
>>> Sorry, here's an example...
>>>
>>> 5+7=12
>>>
>>> added without carrying, 5+7=2
>>>
>>> i.e the result is always less than 10
>> Are you looking for bitwise exclusive or? In Python it's
>> the '^' operator. For example:
>>
>> print 5 ^ 7
>>
>>
 10 ^ 21
> 31
> 
> Not really "less than 10"...

I had little idea what he meant by that. My guess was that
no bit clear in an operand could be set in the result.
XOR is also known as mod-2 addition. It's what you get
if you add each bit independently, dropping carries, so
I thought it might be what he was looking for.
Unfortunately the bitwise mod-2 addition of 5 and 7 gives
the same result as mod-10 addition. Oh well.


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


Re: matplotlib

2006-09-15 Thread skip

diffuser> This site and webpage in particular doesn't open. I tried that
diffuser> too before posting my question.

Well, it is SourceForge.  They are known for flakiness.  Just keep trying.
If you never fail to open the tutorial, drop me a note and I'll send you a
copy.

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


Experienced UK based developer required

2006-09-15 Thread Dean Houghton
A software house based in Bristol, UK require an experienced developer to 
maintain and progress our Enterprise Management software suite.  The suite 
is a group of applications used to monitor, manage and alert on all aspects 
of the enterprise infrastructure from the network to application level.  The 
majority of the suite is developed using Python.



For more information please see http://www.rms.co.uk/careers.htm ,call Phil 
Golder / Dean Houghton on +44 (0) 1454 281265 or email [EMAIL PROTECTED]


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


Re: add without carry

2006-09-15 Thread Jon Ribbens
In article <[EMAIL PROTECTED]>, Bruno Desthuilliers wrote:
> Hugh wrote:
>> Sorry, here's an example...
>> 
>> 5+7=12
>> 
>> added without carrying, 5+7=2
>> 
>> i.e the result is always less than 10
> 
>> I've been thinking some more about this and my brain is starting to
>> work something out... 
> 
> No need to think too long to come up with the most possibly Q&D solution:
> 
> res = int(str(5 + 7)[-1])

Am I missing something subtle in the question or is there some reason
that nobody has posted the correct solution:

  (a + b) % 10

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


Re: add without carry

2006-09-15 Thread Bruno Desthuilliers
Christophe wrote:
> Bruno Desthuilliers a écrit :
>> Bryan Olson wrote:
>>> Hugh wrote:
 Sorry, here's an example...

 5+7=12

 added without carrying, 5+7=2

 i.e the result is always less than 10
>>> Are you looking for bitwise exclusive or? In Python it's
>>> the '^' operator. For example:
>>>
>>> print 5 ^ 7
>>>
>>>
> 10 ^ 21
>> 31
>>
>> Not really "less than 10"...
> 
> But you must use numbers smaller than 10 as input! Still :
> 
 8 ^ 2
> 10
> :D

Still fails:
>>> 8 ^ 7
15

Sorry !-p



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check if variable is an instance of a File object

2006-09-15 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Hi everyone,
> 
> Maybe these questions will sound strange to you, but I sometime have a
> hard time switching from Java to Python ;-)
> 
> Let's say I have a function like this :
> 
> def show_lines(file):
>   for next_line in file:
>   ...

OT :  this will shadow the builtin file type. Avoid shadowing builtin
types if you value your mental sanity !-)

> What can I do to be sure that the input argument is indeed a 'File'
> object ?

Why do you think you need "to be sure that the input argument is indeed
a 'File' object" ? As long as the object passed in is able to answer to
the messages you'll send to it, everything's fine, isn't it ? And if it
fails, well, you'll find out pretty soon...

> #1 : should I start by checking that 'file' is indeed an instance of a
> File object ? 

Unless you have a *very* compelling reason to do so (and I can't imagine
 one here), definitively, no. FWIW, it's pretty common in Python to pass
file-like objects (StringIo comes to mind... but there are lots of other
cases) to functions expecting a file object. And remember that Python
doesn't relies on inheritence for typing. Also, for what you showed of
your code, any iterable seems ok !-)

> (and how do I do this ?)

isinstance(obj, *classes)

OT : note that in your case, since the arg name 'file' shadows the
builtin type, you'll have hard time using it !-)

> #2 : should I do nothing ? 

Yes. Well, IMHO.

> (but I don't like the idea of risking to
> have a runtime exception raised somewhere)

Err... What exactly do you intend to do if the object passed in is not a
file ? Raise a TypeError ? If so, when do you think it will fires ? Yes
my friend- at runtime !-)

As you noticed, switching from Java to Python requires some mental
adjustements... Not fearing runtime exceptions is one of them. Thinking
in terms of implied interface is another one. In your above code, you
really don't care if the objects is a file or not - you just care if the
object support the subset of the file interface you intend to use. And
this, you'll only know at runtime.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check if variable is an instance of a File object

2006-09-15 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Marc 'BlackJack' Rintsch a ecrit :
> 
>> And what do you do if you check for `file` and it isn't such an instance?
>> Raise an exception?  A no, that's something you don't like.  So what else?  
>> ;-)
> 
> Well, I prefer the idea of raising my *own* exception to the idea of
> having an unknown behavior occur

The behavior in case of an uncaught exception is pretty well defined :
your app crashes with an error message and a traceback. Note that
nothing prevents you to try and catch most execptions at the top-level
and do whatever seems appropriate here (log the error, try to see if the
app just display the error and continue with another task or if it's
time to suicide, etc)...

> (for ex : what if the argument is NOT
> a File, but is "itereable" ?)

hard to tell without knowing the rest of the code, but if it's something
like this :

def show_lines(fileobj):
  for line in fileobj:
print line

it will just work...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Check if variable is an instance of a File object

2006-09-15 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
> Hi everyone,
>
> Maybe these questions will sound strange to you, but I sometime have a
> hard time switching from Java to Python ;-)
>
> Let's say I have a function like this :
>
> def show_lines(file):
>   for next_line in file:
>   ...
>
> What can I do to be sure that the input argument is indeed a 'File'
> object ?
>
> #1 : should I start by checking that 'file' is indeed an instance of a
> File object ? (and how do I do this ?)
> #2 : should I do nothing ? (but I don't like the idea of risking to
> have a runtime exception raised somewhere)
>

It depends how you want to do your exception handling. Assuming you
have passed in an object that isn't a file, how do you want to handle
it ?

Here is an example :

class ProgrammerError(Exception): pass

def function(myFile):
if not isinstance(myFile, file):
raise ProgrammerError
for line in myFile:
print myFile

try:
function('something')
except ProgrammerError:
print 'I did something wrong'

Writing tests that check your code doesn't do this would be a better
approach. This is 'strong testing' as opposed to 'strong typing'.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Thanks for helping...

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


Re: Tkinter on Python 2.4 on Mac OS X?

2006-09-15 Thread Bill Williams
In article <[EMAIL PROTECTED]>,
 "Ben Kovitz" <[EMAIL PROTECTED]> wrote:

> Maybe this is a better question for me to ask:  *How* did you get
> Python 2.4 running with Tkinter on OS X?
> 
> Ben Kovitz

Hi Ben

I am by no means a Python expert, but finding my way slowly. There is a 
lot of documentation, but it seems hard to find the critical nuggets 
among the mass. (Rather like playing Colossal Cave long ago!)

I didn't do anything special to get Python 2.4 and Tkinter running on OS 
10.3.9. Just downloaded and installed MacPython OSX 2.4.1 dmg (Mar 31, 
2005) and TclTk Aqua 8.4.10 dmg (June 6 2005). The IDE About box says 
IDE 1.0.2, Python 2.4.1 #2 Mar 31 2005 build 1666, and it all just 
works, including saving a script as an applet.

The point about applets is that one nugget of information points out 
that the graphics environments like Tkinter conflict with the IDE 
graphics environment, so you can't run them under the IDE, and saving as 
applets was the easiest way to get stuff to run standalone.

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


Re: XPN 0.6.5 released

2006-09-15 Thread Nemesis
Franz Steinhaeusler wrote:
> A few other notes (or should I post into the feature requests on
> sourceforge?)

To be honest I do not check sourceforge forums very often. If you want
you can also send me an email (the email is written in the readme
file).

> little point: I find it superfluos on the header pane, to always have
> the term "Re:" before (it would probaly easier to read without this
> text).

Maybe that's true ... but I tend not to modify the informations I show,
I like not to elaborate to much the articles.

> an option possibly (as in agent): if you click on the tree the "+" sign,
> it would be more convenient (for me) to open *all* subbranches, this
> means show all responses headers for this thread.

I should change the behaviour of the expander and that's not a correct
way of acting.
You can expand the whole thread with the command "Expand Selected
Subthread" in the "Subscribed Groups" menu (or on the Toolbar). If you
want you can associate a shortcut to this function ... there is also a
standard GTK shortcut for this function SHIFT+CTRL+NUMPAD_PLUS
where NUMPAD_PLUS is the plus key on the numpad.

> if you change the groups, it would be nice to remember the position of
> the last readed thread in the header pane, which means changing forth
> and back to a certain group (as option for example).

that's an optimization I've thinking about for a while ... but at the
moment I don't know how to implement it.

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


high level, fast XML package for Python?

2006-09-15 Thread Gleb Rybkin
I searched online, but couldn't really find a standard package for
working with Python and XML -- everybody seems to suggest different
ones.

Is there a standard xml package for Python? Preferably high-level, fast
and that can parse in-file, not in-memory since I  have to deal with
potentially MBs of data. 

Thanks.

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


Re: high level, fast XML package for Python?

2006-09-15 Thread Diez B. Roggisch
Gleb Rybkin wrote:

> I searched online, but couldn't really find a standard package for
> working with Python and XML -- everybody seems to suggest different
> ones.
> 
> Is there a standard xml package for Python? Preferably high-level, fast
> and that can parse in-file, not in-memory since I  have to deal with
> potentially MBs of data.

cElementTree and lxml (which is API-compatible to the former). cElementTree
has an incremental parser, which allows for lager-than-memory-files to be
processed.

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


Re: Looking for the Perfect Editor

2006-09-15 Thread Ramon Diaz-Uriarte
On 9/15/06, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:
> Ramon Diaz-Uriarte wrote:
> > - I was referring to executing arbitrary sections of a Python file in
> > a Python interpreter in an "integrated way". When I tried JEdit, I
> > think that Jython was the way to go. (And I think this was also the
> > case for a while, at least to judge from D. Metrz's review
> > http://www-128.ibm.com/developerworks/library/l-cpyide/
> >
> >
> >> The console plugin (probably THE most useful of the pack) gives you a
> >> system shell and means to start compilers/interpreters based on your
> >
> > But isn't this a "generic console": you go to the console, and then
> > type "python2.3" or "python2.4" or whatever? How do you send arbitrary
> > selections of Python code from the file you are editing to this shell?
> > Is there a way to mark a section of code and have it evaluated by the
> > python interpreter? Or a function definition?
>
> Ahh, I see. Well, you're right, that is not that easily possible. But
> you know what? I've never missed such functionality; the "if __name__
> ..." trick always sufficed for me. Buts thats taste of course, lets not
> debate that.

Thanks for the clarification. (And no, I won't debate that: the choice
of editor is (and should be) very much a matter of personal taste, and
JEdit is certainly a very fine and interesting editor).


Best,

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


Searching for patterns on the screen

2006-09-15 Thread Jerry Hill
Hello all,

I have a piece of code I could use some help optimizing.  What I'm
attempting to do is periodically grab a screenshot, and search for 2D
patterns of black pixels in it.  I don't care about any color other
than black.  Here's some simple code that simulates my worst-case
scenario, scanning the whole screen for a sequence that does not
exist:

import ImageGrab  # From the PIL library

def removeColor(rgb):
r, g, b = rgb
return (r == 0 and g == 0 and b == 0)

BMP = ImageGrab.grab.getdata()
x = map(removeColor, BMP)

The idea is to search for sequences of black pixels on a background
that can change colors.  To that end, I transform the screengrab into
a sequence of either black or nonblack pixels as I search them. Note
that in my actual code, I use imap so I only transform pixels as I
search them, and I'm using the KnuthMorrisPratt algorithm from
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117214 to do
the actual searching.

>From some testing using the timeit module:
map(None, BMP) takes about 0.6 seconds on a 1600x1200 screengrab.
map(removeColor, BMP) takes about 1.5 seconds.

I'd love to speed things up, if possible.  It seems like what I'm
doing would probably be a fairly well defined problem, but I don't
know enough about the field to even know where to start my research,
so even a list of keywords that would point me to discussion of
similar topics would be welcome.

This is being done in Python 2.5c2 using PIL 1.1.5

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


Re: Threads and Progress Bar

2006-09-15 Thread Thomas Guettler
On Fri, 01 Sep 2006 21:43:46 +0530
Ritesh Raj Sarraf <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I have a small application, written in Python, that uses threads.
> The application uses function foo() to download files from the web. As it 
> reads
> data from the web server, it runs a progress bar by calling an install of a
> progress bar class.
> 
> When using threads, I get the problem that the progress bar gets over-written 
> by
> the download progress of files from other threads.
> 
> I believe my change has to go into the progress bar class to make it thread
> aware.

You need some kind of lock. Look at the module threading. There
is a class called "Lock".

PS: If you use pygtk: I switched from using threads to idle_add and (*). This 
is much easier
and you don't need any locking. 

# (*)
while gtk.events_pending():
   gtk.main_iteration()

-- 
Thomas Güttler, http://www.tbz-pariv.de/ 
Bernsdorfer Str. 210-212, 09126 Chemnitz, Tel.: 0371/5347-917
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are Python's reserved words reserved in places they dont need to be?

2006-09-15 Thread NickC
Fredrik Lundh wrote:
> Antoon Pardon wrote:
>
> > One place where I would use such a feature is in a unittest
> > package.  I think being able to write self.assert or self.raise
> > looks better than having to append an underscore.
>
> patch here:
>
> http://mail.python.org/pipermail/python-list/2001-June/047996.html
>
> 

Heh. Imagine how much more fun the introduction of conditional
expressions and the yield statement -> yield expression transition in
Python 2.5 would have been if Python 2.4 had used this behaviour :)

Cheers,
Nick.

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


Re: add without carry

2006-09-15 Thread Jason
Jon Ribbens wrote:
> In article <[EMAIL PROTECTED]>, Bruno Desthuilliers wrote:
> >
> > No need to think too long to come up with the most possibly Q&D solution:
> >
> > res = int(str(5 + 7)[-1])
>
> Am I missing something subtle in the question or is there some reason
> that nobody has posted the correct solution:
>
>   (a + b) % 10
>
> ?

You're not missing anything.  That's the obvious solution.  We're just
celebrating our non-Dutchness at the moment.

>>> def bound(value, maxBound):
... while value > maxBound:
... value -= maxBound
... return value
...
>>> bound(5 + 6, 10)
1
>>> bound(8 + 7, 10)
5

See?  I'm definitely not Dutch.

--Jason

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 14)

2006-09-15 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Jack Diederich <[EMAIL PROTECTED]> wrote:
.
.
.
>More than you ever wanted to know about the types of regular expression
>engines and their history.
> 
>http://groups.google.com/group/comp.lang.python/browse_thread/thread/cd20b4cabc6fe26/
.
.
.
http://groups.google.com/group/comp.lang.python/browse_thread/thread/cd20b4cabc6fe264/
 

My profound apologies for sending out the wrong link.  Folks should have
a proper opportunity to read this topic, as I think it interests many.
-- 
http://mail.python.org/mailman/listinfo/python-list


PostgreSQL, psycopg2 and OID-less tables

2006-09-15 Thread Dale Strickland-Clark
Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
a newly inserted record?

I've tried three Python client libraries, including psycopg2, and where they
support cursor attribute 'lastrowid' (Python DB API 2.0), it is always
zero. 

Anyone figured this out?

Thanks.
-- 
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk

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


Re: high level, fast XML package for Python?

2006-09-15 Thread Steven Bethard
Diez B. Roggisch wrote:
> Gleb Rybkin wrote:
> 
>> I searched online, but couldn't really find a standard package for
>> working with Python and XML -- everybody seems to suggest different
>> ones.
>>
>> Is there a standard xml package for Python? Preferably high-level, fast
>> and that can parse in-file, not in-memory since I  have to deal with
>> potentially MBs of data.
> 
> cElementTree and lxml (which is API-compatible to the former). cElementTree
> has an incremental parser, which allows for lager-than-memory-files to be
> processed.

In Python 2.5, cElementTree and ElementTree will be available in the 
standard library as xml.etree.cElementTree and xml.etree.ElementTree. 
So learning them now is a great idea.

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


Re: UDP packets to PC behind NAT

2006-09-15 Thread Janto Dreijer
Awesome! I haven't tested it on the actual server but I think it works.
Thanks!
I prefer a TCP connection solution and will post one if it works.

server.py

from socket import *
print "listening"
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(("localhost", 1234)) # visibility to outside world
payload, addr = UDPSock.recvfrom(1024)
print "message from %s: %s" % (`addr`, payload)
UDPSock = socket(AF_INET, SOCK_DGRAM) # open UDP socket
result = UDPSock.sendto("your public address is %s" % `addr`, addr)

client.py
=
from socket import *
UDPSock = socket(AF_INET, SOCK_DGRAM) # open UDP socket
result = UDPSock.sendto("what's my public address?", ("localhost",
1234))
payload, addr = UDPSock.recvfrom(1024)
print payload

results:

listening
message from ('127.0.0.1', 32787): what's my public address?

your public address is ('127.0.0.1', 32787)

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


Re: UDP packets to PC behind NAT

2006-09-15 Thread Grant Edwards
On 2006-09-15, Christophe <[EMAIL PROTECTED]> wrote:

> Initiate an UDP connection from the client to the server and
> have the server send back the UDP packets to the address you
> get in the "recvfrom" result.

There's no such thing as a "UDP connection", so I don't
understand what you're suggesting.

-- 
Grant Edwards   grante Yow!  By MEER biz doo
  at   SCHOIN...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UDP packets to PC behind NAT

2006-09-15 Thread Grant Edwards
On 2006-09-15, Janto Dreijer <[EMAIL PROTECTED]> wrote:

> I have a server with a static "public" IP and a client behind a NAT. I
> would like to send UDP packets from the server to the client. So what I
> need to do is open up a "hole" in the NAT and let the server know the
> target IP and port of the client where it can send its packets.
>
> Now I have read somewhere that you can have TCP and UDP running on the
> same port.

True.

> Not sure if this is true.

It is.

> Would it be a reasonable solution to initiate a TCP connection
> from the client to the server and somehow (?) let the server
> figure out how the client is connecting? And then send UDP to
> client over the same (IP, port)?

I doubt that will work unless the firewall has been
specifically designed to recognize that pattern of activity and
allow the incoming UDP packets.  I don't think most firewall
have default rules that allow UDP packets to tunnel back along
a TCP connection.

-- 
Grant Edwards   grante Yow!  Clear the
  at   laundromat!! This
   visi.comwhirl-o-matic just had a
   nuclear meltdown!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Outbound port on sockets

2006-09-15 Thread Grant Edwards
On 2006-09-15, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:

 Is it possible to specify which port to use as the outbound port on a
 connection? 
>> [...]
 Specifically, I'm trying to write an FTP host, and I'm trying to
 implement the PORT command. 
>>>
>>> AFAIK you neither can't do that nor need it.
>> 
>> It's not the issue here, but to specify the outgoing port
>> call bind(('', portnum)) before connect().
>
> I wasn't aware of that. Cool.

It's an interesting thing to know, but I've been doing TCP
stuff for many years and never run across a situation where
it's something I needed to do.  If somebody in this thread
actually does need to do it, I'd be curious bout why...

-- 
Grant Edwards   grante Yow!  .. this must be what
  at   it's like to be a COLLEGE
   visi.comGRADUATE!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Question about pipes/os.popen

2006-09-15 Thread Kevin Walzer
I'm trying to structure a Python script that streams output over a pipe.

Here is my code:

import os

cmd = os.popen('echo foo | sudo -S /usr/sbin/tcpdump -en1')
cmd.read()

This returns output of "". I'm expecting the standard output of "tcpdump
-en1". How does one read unbuffered output over a pipe before the pipe
is closed in Python? Because I want the output to be updated in real
time, writing to a temporary file and then reading that data isn't
feasible.

I'm not sure what I'm doing wrong here.

-- 
Kevin Walzer
Poetic Code
http://www.kevin-walzer.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urlopen() error

2006-09-15 Thread John Machin

Paul McNett wrote:
> Tempo wrote:
> > Hello. I am getting an error and it has gotten me stuck. I think the
> > best thing I can do is post my code and the error message and thank
> > everybody in advanced for any help that you give this issue. Thank you.
> >
> > #
> > Here's the code:
> > #
> >
> > import urllib2
> > import re
> > import xlrd
> > from BeautifulSoup import BeautifulSoup
> >
> > book = xlrd.open_workbook("ige_virtualMoney.xls")
> > sh = book.sheet_by_index(0)
> > rx = 1
> > for rx in range(sh.nrows):

The above 2 lines should probably be:
   for rx.range(1, sh.nrows):
otherwise the likelihood is that a column heading will be treated as
data.
Now read on ;-)

> > u = sh.cell_value(rx, 0)
> > page = urllib2.urlopen(u)
> > soup = BeautifulSoup(page)
> > p = soup.findAll('span', "sale")
> > p = str(p)
> > p2 = re.findall('\$\d+\.\d\d', p)
> > for price in p2:
> > print price
> >
> > ##
> > Here are the error messages:
> > ##
> >
> > Traceback (most recent call last):
> >   File "E:\Python24\scraper.py", line 16, in -toplevel-
> > page = urllib2.urlopen(u)
> >   File "E:\Python24\lib\urllib2.py", line 130, in urlopen
> > return _opener.open(url, data)
> >   File "E:\Python24\lib\urllib2.py", line 350, in open
> > protocol = req.get_type()
> >   File "E:\Python24\lib\urllib2.py", line 233, in get_type
> > raise ValueError, "unknown url type: %s" % self.__original
> > ValueError: unknown url type: List
>
> You were expecting u to be a url string like "http://google.com";, but it
> looks like it is actually a list. I'm not familiar with package xlrd but
> cell_value() must be returning a list and not a cell value. Presumably,
> the list contains the cell value probably in element 0. Put in a print
> statement before your call to urlopen() like:
>
> print u

Sage advice. print repr(u) is in general even better advice.

>
> You'll likely discover your error.
>

Just for the record:

1. The xlrd package's Book.Sheet.cell_value() does *not* return lists.
As its docs say, it returns scalars, of the following types: unicode,
int, float, strg

2. The error is nothing to do with Python lists, it's all about
malformed URLs. "unknown url type" means it's not one of http, ftp,
file, data, gopher, ...

|>>> x = urllib2.urlopen('List')
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\lib\urllib2.py", line 130, in urlopen
return _opener.open(url, data)
  File "C:\Python24\lib\urllib2.py", line 350, in open
protocol = req.get_type()
  File "C:\Python24\lib\urllib2.py", line 233, in get_type
raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: List

|>>> x = urllib2.urlopen('GOTCHA')
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\lib\urllib2.py", line 130, in urlopen
return _opener.open(url, data)
  File "C:\Python24\lib\urllib2.py", line 350, in open
protocol = req.get_type()
  File "C:\Python24\lib\urllib2.py", line 233, in get_type
raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: GOTCHA
|>>>

HTH,
John

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


Re: UDP packets to PC behind NAT

2006-09-15 Thread Janto Dreijer
Oops. That second UDPSock = socket(...) in the server.py shouldn't be
there.

Janto Dreijer wrote:
> Awesome! I haven't tested it on the actual server but I think it works.
> Thanks!
> I prefer a TCP connection solution and will post one if it works.
>
> server.py
> 
> from socket import *
> print "listening"
> UDPSock = socket(AF_INET, SOCK_DGRAM)
> UDPSock.bind(("localhost", 1234)) # visibility to outside world
> payload, addr = UDPSock.recvfrom(1024)
> print "message from %s: %s" % (`addr`, payload)
> UDPSock = socket(AF_INET, SOCK_DGRAM) # open UDP socket
> result = UDPSock.sendto("your public address is %s" % `addr`, addr)
>
> client.py
> =
> from socket import *
> UDPSock = socket(AF_INET, SOCK_DGRAM) # open UDP socket
> result = UDPSock.sendto("what's my public address?", ("localhost",
> 1234))
> payload, addr = UDPSock.recvfrom(1024)
> print payload
>
> results:
> 
> listening
> message from ('127.0.0.1', 32787): what's my public address?
> 
> your public address is ('127.0.0.1', 32787)

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


Re: add without carry

2006-09-15 Thread John Machin

Jason wrote:
> Jon Ribbens wrote:
> > In article <[EMAIL PROTECTED]>, Bruno Desthuilliers wrote:
> > >
> > > No need to think too long to come up with the most possibly Q&D solution:
> > >
> > > res = int(str(5 + 7)[-1])
> >
> > Am I missing something subtle in the question or is there some reason
> > that nobody has posted the correct solution:
> >
> >   (a + b) % 10
> >
> > ?
>
> You're not missing anything.  That's the obvious solution.  We're just
> celebrating our non-Dutchness at the moment.
>
> >>> def bound(value, maxBound):
> ... while value > maxBound:

Does non-Dutchness require or permit bugs like > instead of >= or are
you merely having a braino?

> ... value -= maxBound
> ... return value
> ...
> >>> bound(5 + 6, 10)
> 1
> >>> bound(8 + 7, 10)
> 5
> 
> See?  I'm definitely not Dutch.
> 
> --Jason

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


Re: UDP packets to PC behind NAT

2006-09-15 Thread Janto Dreijer
Grant Edwards wrote:
> On 2006-09-15, Christophe <[EMAIL PROTECTED]> wrote:
>
> > Initiate an UDP connection from the client to the server and
> > have the server send back the UDP packets to the address you
> > get in the "recvfrom" result.
>
> There's no such thing as a "UDP connection", so I don't
> understand what you're suggesting.

I think he means "connection" as in "associated ip/port". Which
actually does work, as I've posted.

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


Re: Searching for patterns on the screen

2006-09-15 Thread Paul McGuire
"Jerry Hill" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello all,
>
> I have a piece of code I could use some help optimizing.  What I'm
> attempting to do is periodically grab a screenshot, and search for 2D
> patterns of black pixels in it.  I don't care about any color other
> than black.  Here's some simple code that simulates my worst-case
> scenario, scanning the whole screen for a sequence that does not
> exist:
>
> import ImageGrab  # From the PIL library
>
> def removeColor(rgb):
>r, g, b = rgb
>return (r == 0 and g == 0 and b == 0)
>
> BMP = ImageGrab.grab.getdata()
> x = map(removeColor, BMP)
>
> The idea is to search for sequences of black pixels on a background
> that can change colors.

I had to do a similar thing using pywinauto to interact with a IE browser 
running an embedded Flash application.  To speed things up, I included psyco 
to compile my functions.

As far as working just in Python, you could remove the tuple unpacking 
inside removeColor, and shorten it to just:

def removeColor(rgb):
return rgb==(0,0,0)

or even better:

BLACK = (0,0,0)
def removeColor(rgb):
return rgb==BLACK

By defining BLACK once and just referring to it by name, you also avoid 
dynamically constructing the (0,0,0) tuple in every call.

But you might also look at the PIL docs and see if there is a way to do this 
color manipulation using the PIL API - the advantage here is that then you 
would be invoking a C-compiled API routine, which will run way faster than 
any optimized Python method.

-- Paul



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


Re: UDP packets to PC behind NAT

2006-09-15 Thread Janto Dreijer
Grant Edwards wrote:
> On 2006-09-15, Janto Dreijer <[EMAIL PROTECTED]> wrote:
...
> > Would it be a reasonable solution to initiate a TCP connection
> > from the client to the server and somehow (?) let the server
> > figure out how the client is connecting? And then send UDP to
> > client over the same (IP, port)?
>
> I doubt that will work unless the firewall has been
> specifically designed to recognize that pattern of activity and
> allow the incoming UDP packets.  I don't think most firewall
> have default rules that allow UDP packets to tunnel back along
> a TCP connection.

Thanks for the info!

I think you may be right. I had to configure the local firewall to
allow all connections from the server. Which kinda defeats the purpose.
If you have control over the NAT why not just assign a dedicated port?

There might still be value in this approach, however. Even though I
have control over the NAT I have multiple clients that might need to
create these connections. I would need to map ports to be able to
handle simultaneous connections.

It's Friday afternoon over here, so I may be wrong...

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


Finding dynamic libraries

2006-09-15 Thread Bill Spotz
Hi,

Is there a way to tell an executing python script where to look for  
dynamically-loaded libraries?

My situation is that that I am developing python wrappers for a large  
software project.  I create python wrappers with swig, and those  
extension modules link against dynamic libraries from the project.  I  
have many test scripts that I would like to be able to run *prior* to  
installing these libraries into a standard location.

I have tried altering the LD_LIBRARY_PATH and DYLD_LIBRARY_PATH  
environment variables, both by direct assignment of os.environ and by  
calling os.putenv(), but neither results in python being able to find  
my dynamic libraries.

Thanks in advance

** Bill Spotz  **
** Sandia National Laboratories  Voice: (505)845-0170  **
** P.O. Box 5800 Fax:   (505)284-5451  **
** Albuquerque, NM 87185-0370Email: [EMAIL PROTECTED] **



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


Re: Searching for patterns on the screen

2006-09-15 Thread John Machin

Paul McGuire wrote:
> "Jerry Hill" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Hello all,
> >
> > I have a piece of code I could use some help optimizing.  What I'm
> > attempting to do is periodically grab a screenshot, and search for 2D
> > patterns of black pixels in it.  I don't care about any color other
> > than black.  Here's some simple code that simulates my worst-case
> > scenario, scanning the whole screen for a sequence that does not
> > exist:
> >
> > import ImageGrab  # From the PIL library
> >
> > def removeColor(rgb):
> >r, g, b = rgb
> >return (r == 0 and g == 0 and b == 0)
> >
> > BMP = ImageGrab.grab.getdata()
> > x = map(removeColor, BMP)
> >
> > The idea is to search for sequences of black pixels on a background
> > that can change colors.
>
> I had to do a similar thing using pywinauto to interact with a IE browser
> running an embedded Flash application.  To speed things up, I included psyco
> to compile my functions.
>
> As far as working just in Python, you could remove the tuple unpacking
> inside removeColor, and shorten it to just:
>
> def removeColor(rgb):
> return rgb==(0,0,0)
>
> or even better:
>
> BLACK = (0,0,0)
> def removeColor(rgb):
> return rgb==BLACK
>
> By defining BLACK once and just referring to it by name, you also avoid
> dynamically constructing the (0,0,0) tuple in every call.

Bzt. It's not dynamically constructed. Its a constant (in 2.4 at
least)

| >>> BLACK=(0,0,0)
| >>> def func1(rgb):
| ...return rgb==BLACK
| ...
| >>> def func2(rgb):
| ...return rgb==(0,0,0)
| ...
| >>> import dis
| >>> dis.dis(func1)
|   2   0 LOAD_FAST0 (rgb)
|   3 LOAD_GLOBAL  1 (BLACK)
|   6 COMPARE_OP   2 (==)
|   9 RETURN_VALUE
| >>> dis.dis(func2)
|   2   0 LOAD_FAST0 (rgb)
|   3 LOAD_CONST   2 ((0, 0, 0))
|   6 COMPARE_OP   2 (==)
|   9 RETURN_VALUE
| >>>


C:\junk>python -mtimeit -s"BLACK=(0,0,0);rgb=(1,1,1)" "rgb==BLACK"
100 loops, best of 3: 0.129 usec per loop

C:\junk>python -mtimeit -s"rgb=(1,1,1)" "rgb==(0,0,0)"
100 loops, best of 3: 0.127 usec per loop

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


xmlrpc with Basic Auth

2006-09-15 Thread Milos Prudek
I need to use XML-RPC call with Basic Authorization in HTTP headers. I found 
xmlrpclibBasicAuth.py, and it can be used as follows:

from xmlrpclibBasicAuth import Server
s=Server("http://www.example.com/rpc.php","user","pwd";)
print s.system.listMethods()

Is this possible in plain xmlrpclib, without xmlrpclibBasicAuth.py? 

I found the Transport class in xmlrpclib, and it has a method "get_host_info", 
which parses "user:pwd" out of "user:[EMAIL PROTECTED]". But when I tried to 
instantiate Server, it threw error "unsupported XML-RPC protocol". Here is a 
snippet:

from xmlrpclib import Server
s=Server("user:[EMAIL PROTECTED]://www.example.com/rpc.php")
...
File "/usr/local/lib/python2.3/xmlrpclib.py", line 1293, in __init__
raise IOError, "unsupported XML-RPC protocol"
IOError: unsupported XML-RPC protocol

I know that I am using it incorrectly. Does the basic authentication support 
in xmlrpclib mean something else than I take it for?

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


xmlrpc, extract data from http headers

2006-09-15 Thread Milos Prudek
I perform a XML-RPC call by calling xmlrpclibBasicAuth which in turn calls 
xmlrpclib. This call of course sends a HTTP request with correct HTTP 
headers. The response is correctly parsed by xmlrpclib, and I get my desired 
values. 

However, I also need to get the raw HTTP headers from the HTTP response. There 
is a cookie in the HTTP response and I need to read that cookie.

How could I do that?

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


Re: high level, fast XML package for Python?

2006-09-15 Thread Gleb Rybkin
Okay, thanks!

Steven Bethard wrote:
> Diez B. Roggisch wrote:
> > Gleb Rybkin wrote:
> >
> >> I searched online, but couldn't really find a standard package for
> >> working with Python and XML -- everybody seems to suggest different
> >> ones.
> >>
> >> Is there a standard xml package for Python? Preferably high-level, fast
> >> and that can parse in-file, not in-memory since I  have to deal with
> >> potentially MBs of data.
> >
> > cElementTree and lxml (which is API-compatible to the former). cElementTree
> > has an incremental parser, which allows for lager-than-memory-files to be
> > processed.
>
> In Python 2.5, cElementTree and ElementTree will be available in the
> standard library as xml.etree.cElementTree and xml.etree.ElementTree.
> So learning them now is a great idea.
> 
> STeVe

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


Re: Finding dynamic libraries

2006-09-15 Thread Robert Kern
Bill Spotz wrote:
> Hi,
> 
> Is there a way to tell an executing python script where to look for  
> dynamically-loaded libraries?
> 
> My situation is that that I am developing python wrappers for a large  
> software project.  I create python wrappers with swig, and those  
> extension modules link against dynamic libraries from the project.  I  
> have many test scripts that I would like to be able to run *prior* to  
> installing these libraries into a standard location.
> 
> I have tried altering the LD_LIBRARY_PATH and DYLD_LIBRARY_PATH  
> environment variables, both by direct assignment of os.environ and by  
> calling os.putenv(), but neither results in python being able to find  
> my dynamic libraries.

Those environment variables need to be set before the python executable starts.

-- 
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: UDP packets to PC behind NAT

2006-09-15 Thread Jean-Paul Calderone
On 15 Sep 2006 00:32:49 -0700, Janto Dreijer <[EMAIL PROTECTED]> wrote:
>This is probably more of a networking question than a Python one, but
>it would be nice to know if someone has done this with Python's socket
>module. And besides one usually gets more information from c.l.py than
>anywhere else :)
>
>I have a server with a static "public" IP and a client behind a NAT. I
>would like to send UDP packets from the server to the client. So what I
>need to do is open up a "hole" in the NAT and let the server know the
>target IP and port of the client where it can send its packets.
>
>Now I have read somewhere that you can have TCP and UDP running on the
>same port. Not sure if this is true. Would it be a reasonable solution
>to initiate a TCP connection from the client to the server and somehow
>(?) let the server figure out how the client is connecting? And then
>send UDP to client over the same (IP, port)?

You may be interested in Divmod Vertex 
() for its NAT traversal techniques, 
if not for its actual code.

The solution you describe above won't work on any widespread configuration
I am aware of.  In general, most individual solutions are only effective on
a portion of existing configurations.  A robust solution must employ multiple
techniques.

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


fail to indent in inner loop

2006-09-15 Thread perltcl
hi

I've started learning python. I was typing from a tutorial,
and I fail to indent on an inner loop.
I got an error and all my previous typed lines are gone.
is there a way to prevent this.
i don't mind editing the last line, but to lose all the previous lines
are too much.
(since it has history function like bash.)

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


Re: Outbound port on sockets

2006-09-15 Thread Sergei Organov
Grant Edwards <[EMAIL PROTECTED]> writes:

> On 2006-09-15, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>
> Is it possible to specify which port to use as the outbound port on a
> connection? 
>>> [...]
> Specifically, I'm trying to write an FTP host, and I'm trying to
> implement the PORT command. 

 AFAIK you neither can't do that nor need it.
>>> 
>>> It's not the issue here, but to specify the outgoing port
>>> call bind(('', portnum)) before connect().
>>
>> I wasn't aware of that. Cool.
>
> It's an interesting thing to know, but I've been doing TCP
> stuff for many years and never run across a situation where
> it's something I needed to do.  If somebody in this thread
> actually does need to do it, I'd be curious bout why...

Well, one of ftpd implementations I have here (C code from RTEMS) does
this:

  /* anchor socket to avoid multi-homing problems */
  data_source = info->ctrl_addr;
  data_source.sin_port = htons(20); /* ftp-data port */
  if(bind(s, (struct sockaddr *)&data_source, sizeof(data_source)) < 0)
ERROR;
  ...
  if(connect(s,
  (struct sockaddr *)&info->def_addr,
  sizeof(struct sockaddr_in)) < 0
  )
ERROR;

I've no idea what "multi-homing problems" are, but maybe it gives you
some hint?

-- Sergei.

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


Re: fail to indent in inner loop

2006-09-15 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> I've started learning python. I was typing from a tutorial,
> and I fail to indent on an inner loop.
> I got an error and all my previous typed lines are gone.
> is there a way to prevent this.
> i don't mind editing the last line, but to lose all the previous lines
> are too much.
> (since it has history function like bash.)

Use an IDE or editor that allows you to execute the code in the current
buffer. Thus you have the full editing capabilities combined with
interactive probing.

Python also has an option -i that when used together with a input file
makes it drop to the prompt - thus you can setup some things, and then
simply play around.

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


Re: Searching for patterns on the screen

2006-09-15 Thread Jerry Hill
On 15 Sep 2006 08:16:41 -0700, John Machin <[EMAIL PROTECTED]> wrote:
> C:\junk>python -mtimeit -s"BLACK=(0,0,0);rgb=(1,1,1)" "rgb==BLACK"
> 100 loops, best of 3: 0.129 usec per loop
>
> C:\junk>python -mtimeit -s"rgb=(1,1,1)" "rgb==(0,0,0)"
> 100 loops, best of 3: 0.127 usec per loop

Surprisingly (to me), hand splitting the tuple and doing short circuit
comparisons is slightly faster than either of those:

C:\Python25>python -mtimeit -s"BLACK=(0,0,0);rgb=(1,1,1)" "rgb==BLACK"
1000 loops, best of 3: 0.18 usec per loop

C:\Python25>python -mtimeit -s"rgb = (1,1,1)" "rgb == (0,0,0)"
1000 loops, best of 3: 0.169 usec per loop

C:\Python25>python -mtimeit -s"rgb = (1,1,1)" "rgb[0] == 0 and rgb[1]
== 0 and rgb[2] == 0"
1000 loops, best of 3: 0.158 usec per loop

It probably has to do with not needing to find the len of the tuple
each time you compare.

I agree with Paul's earlier statement that there's probably a better
way to do this through PIL.  I've read through the PIL docs, but I'm
afraid I'm running into problems caused by my own ignorance. It seems
like I should be able to do something with Image.eval(), the point()
method or one of the PIL filters, but I don't understand them well
enough.  I'll take a look through the source, and if that doesn't help
I'll take this to the PIL list to get some further feedback on how
those work.

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


Re: Searching for patterns on the screen

2006-09-15 Thread Claudio Grondi
Jerry Hill wrote:
> Hello all,
> 
> I have a piece of code I could use some help optimizing.  What I'm
> attempting to do is periodically grab a screenshot, and search for 2D
> patterns of black pixels in it.  I don't care about any color other
> than black.  Here's some simple code that simulates my worst-case
> scenario, scanning the whole screen for a sequence that does not
> exist:
> 
> import ImageGrab  # From the PIL library
> 
> def removeColor(rgb):
>r, g, b = rgb
>return (r == 0 and g == 0 and b == 0)
> 
> BMP = ImageGrab.grab.getdata()
> x = map(removeColor, BMP)
> 
> The idea is to search for sequences of black pixels on a background
> that can change colors.  To that end, I transform the screengrab into
> a sequence of either black or nonblack pixels as I search them. Note
> that in my actual code, I use imap so I only transform pixels as I
> search them, and I'm using the KnuthMorrisPratt algorithm from
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117214 to do
> the actual searching.
> 
>> From some testing using the timeit module:
> 
> map(None, BMP) takes about 0.6 seconds on a 1600x1200 screengrab.
> map(removeColor, BMP) takes about 1.5 seconds.
> 
> I'd love to speed things up, if possible.  It seems like what I'm
> doing would probably be a fairly well defined problem, but I don't
> know enough about the field to even know where to start my research,
> so even a list of keywords that would point me to discussion of
> similar topics would be welcome.
> 
> This is being done in Python 2.5c2 using PIL 1.1.5
> 
Use PIL for grabbing the screenshot and numarray for processing the 
image. See
http://groups.google.com.vc/group/comp.lang.python/browse_thread/thread/6207e7526fb6fdc6/a05646969d59102e
for some further helpful hints towards speeding things up.

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


Re: PostgreSQL, psycopg2 and OID-less tables

2006-09-15 Thread Tim N. van der Leeuw

Dale Strickland-Clark wrote:
> Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
> a newly inserted record?
>
> I've tried three Python client libraries, including psycopg2, and where they
> support cursor attribute 'lastrowid' (Python DB API 2.0), it is always
> zero.
>
> Anyone figured this out?
>

Hi,

It's of course strictly a PostgreSQL question, but have you tried

select lastval();

?

According to my reading of the postgress manuals, that should do the
trick.

Cheers,

--Tim


> Thanks.
> -- 
> Dale Strickland-Clark
> Riverhall Systems - www.riverhall.co.uk

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


Re: Searching for patterns on the screen

2006-09-15 Thread Filip Wasilewski
Jerry Hill wrote:
> Hello all,
>
> I have a piece of code I could use some help optimizing.  What I'm
> attempting to do is periodically grab a screenshot, and search for 2D
> patterns of black pixels in it.  I don't care about any color other
> than black.  Here's some simple code that simulates my worst-case
> scenario, scanning the whole screen for a sequence that does not
> exist:
>
> import ImageGrab  # From the PIL library
>
> def removeColor(rgb):
> r, g, b = rgb
> return (r == 0 and g == 0 and b == 0)
>
> BMP = ImageGrab.grab.getdata()
> x = map(removeColor, BMP)
>
> The idea is to search for sequences of black pixels on a background
> that can change colors.  To that end, I transform the screengrab into
> a sequence of either black or nonblack pixels as I search them. Note
> that in my actual code, I use imap so I only transform pixels as I
> search them, and I'm using the KnuthMorrisPratt algorithm from
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117214 to do
> the actual searching.
>
> >From some testing using the timeit module:
> map(None, BMP) takes about 0.6 seconds on a 1600x1200 screengrab.
> map(removeColor, BMP) takes about 1.5 seconds.
>
> I'd love to speed things up, if possible.  It seems like what I'm
> doing would probably be a fairly well defined problem, but I don't
> know enough about the field to even know where to start my research,
> so even a list of keywords that would point me to discussion of
> similar topics would be welcome.
>
> This is being done in Python 2.5c2 using PIL 1.1.5
>
> --
> Jerry

Calling Python function for every pixel results in significant
overhead. Instead of that you can use numpy to do the preprocesing.

im = ImageGrab.grab()
a = numpy.fromstring(im.tostring(), dtype=[('r','|u1'), ('g','|u1'),
('b','|u1')])
a.shape = im.size[::-1]
black = (a['r'] == 0) & (a['g'] == 0) & (a['b'] == 0)

s = black.tostring() # sequence of '\x00' and '\x01'

You can also take a look at scipy ndimage
(http://www.scipy.org/doc/api_docs/scipy.ndimage.html) if in need of
more specific routines.

cheers,
fw

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


Re: Outbound port on sockets

2006-09-15 Thread Grant Edwards
On 2006-09-15, Sergei Organov <[EMAIL PROTECTED]> wrote:

 It's not the issue here, but to specify the outgoing port
 call bind(('', portnum)) before connect().

>> It's an interesting thing to know, but I've been doing TCP
>> stuff for many years and never run across a situation where
>> it's something I needed to do.  If somebody in this thread
>> actually does need to do it, I'd be curious bout why...
>
> Well, one of ftpd implementations I have here (C code from RTEMS) does
> this:
>
>   /* anchor socket to avoid multi-homing problems */
>   data_source = info->ctrl_addr;
>   data_source.sin_port = htons(20); /* ftp-data port */
>   if(bind(s, (struct sockaddr *)&data_source, sizeof(data_source)) < 0)
> ERROR;
>   ...
>   if(connect(s,
>   (struct sockaddr *)&info->def_addr,
>   sizeof(struct sockaddr_in)) < 0
>   )
> ERROR;
>
> I've no idea what "multi-homing problems" are, but maybe it gives you
> some hint?

I don't know what "multi-homing problems are either".
Apparently there must be some ftp clients that require the
source port for the data connection to be port 20.

The RFC is pretty vague. It does say the server and clinet but
must "support the use of the default data port [port 20]" or
something like that. But, it's not all all clear to me what
that is supposed to mean.  My reading is that they must support
the default port as the destination port for a data connection
untill it's been changed by receipt of a PORT command.

But, like I said, is very vague, and I suppose some client
implementor could have read it as the server must use the
default data port as the source port for a data connection.

-- 
Grant Edwards   grante Yow!  Ha ha  Ha ha Ha ha
  at   Ha Ha Ha Ha -- When will I
   visi.comEVER stop HAVING FUN?!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: high level, fast XML package for Python?

2006-09-15 Thread Tim N. van der Leeuw
Hi Gleb,

Gleb Rybkin wrote:
> I searched online, but couldn't really find a standard package for
> working with Python and XML -- everybody seems to suggest different
> ones.
>
> Is there a standard xml package for Python? Preferably high-level, fast
> and that can parse in-file, not in-memory since I  have to deal with
> potentially MBs of data.
>
> Thanks.

Another option is Amara; also quite high-level and also allows for
incremental parsing. I would say Amara is somewhat higher level than
ElementTree since it allows you to access your XML nodes as Python
objects (with some extra attributes and some minor warts), as well as
giving you XPath expressions on the object tree.

URL:

http://uche.ogbuji.net/tech/4suite/amara/

Best version currently available is version 1.1.7

It does work together with py2exe on windows if the need ever arises
for you but you have to fiddle a bit with it (ask for details on this
list if you ever need to do that)

 Cheers,

--Tim

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


Coding Nested Loops

2006-09-15 Thread Rich Shepard
   I want to code what would be nested "for" loops in C, but I don't know the
most elegant way of doing the same thing in python. So I need to learn how
from you folks. Here's what I need to do: build a database table of 180
rows. Each row contains 31 columns: the first is an automatically
incremented integer as the primary key; the next two fields can each contain
one of three strings held in dictionaries, the last 28 fields are random
floats from a third dictionary.

   Of the 180 total rows, each of the three values in the first dictionary
will be the second field in 60 rows. Within each set of 60 rows, there will
be 13 rows containing the first value from the second dictionary, 14 rows
containing the second value from the second dictionary, and 33 rows from
the third value in that dictionary. Again, the final 28 fields in each row
are random values from the third dictionary.

   I suspect that iterators might be the way to accomplish this, but I really
don't know. However, I would like to learn so that I can solve similar
problems by myself.

TIA,

Rich

-- 
Richard B. Shepard, Ph.D.   |The Environmental Permitting
Applied Ecosystem Services, Inc.(TM)|Accelerator
 Voice: 503-667-4517  Fax: 503-667-8863
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I converted a null (0) terminated string to a Python string?

2006-09-15 Thread Michael
Robert,

Thanks to you and everyone else for the help. The "s.split('\x00',
1)[0] " solved the problem.

Thanks again,
MDM

Robert Kern wrote:
> Michael wrote:
> > I guess, I still don't see how this will work. I'm receiving a C
> > zero-terminated string in my Python program as a 1K byte block (UDP
> > datagram). If the string sent was "abc", then what I receive in Python
> > is <0> How is Python
> > going to know where in this 1K byte block the end of the string is? It
> > seems that what I need to do is tell Python that the string ends at
> > zero-relative index 3. What am I missing here?
>
> Nothing. This is what I would do:
>
>
> In [34]: s
> Out[34]: 'abc\x00garbage'
>
> In [35]: s.split('\x00', 1)[0]
> Out[35]: 'abc'
>
> In [36]: s.split?
> Type:   builtin_function_or_method
> Base Class: 
> String Form:
> Namespace:  Interactive
> Docstring:
>  S.split([sep [,maxsplit]]) -> list of strings
>
>  Return a list of the words in the string S, using sep as the
>  delimiter string.  If maxsplit is given, at most maxsplit
>  splits are done. If sep is not specified or is None, any
>  whitespace string is a separator.
>
>
> Using the maxsplit argument saves split from having to do unnecessary work
> splitting the garbage portion if there are nulls there, too.
>
> --
> 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


IDLE Problem in Windows XP

2006-09-15 Thread ELATTAOUI Xavier



Hi,
 
I have encountered 
the same problem so you can try the following :
 
- Be sure your 
%PYTHONPATH% is set
- open a DOS console 
and type : "python C:\Python23\Lib\idlelib\idle.py"
-> this will 
launch the IDLE
- then choose 
"configure IDLE" in Options menu
- in the menu 
"Highlighting" on right part, choose "IDLE Classic" and 
apply
- close all and try 
to launch now the IDLE
 
This is what I have 
done and now it works (don't ask me why !!).
 
Hope this 
help,
Xavier
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Limitate speed of a socket-based data transferring

2006-09-15 Thread Grant Edwards
On 2006-09-15, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 14 Sep 2006 04:54:48 -0700, "billie" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
>> Hi all. I'm writing a TCP-based application that I will use to trasfer
>> binary files through the network. This piece of code represents how do
>> I get a file from a remote peer and save it on my local hard drive:
>> 
>   
>> 
>> I would like to know how could be possible to limit the file transfer
>> speed (for example: don't write more than 50 Kb/sec).
>> Some ideas?
>> 
>   I'm not sure you /can/ limit the /receive/ speed.

Sure you can.  Just read data from the socket at the max speed
you want to receive.  The receive buffer for that socket will
fill up and the TCP window will start close up and throttle the
sender.

> The sender will send at whatever rate they are capable of, so
> packets may just become backlogged on your receiving socket

When that happens, the sending end of the socket will throttle
down to match the rate at which data is being read from the
socket.

> waiting for you to read them if you add some sort of delay to
> your reading loop.

-- 
Grant Edwards   grante Yow!  .. the HIGHWAY is
  at   made out of LIME JELLO and
   visi.commy HONDA is a barbequed
   OYSTER! Yum!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to build extensions on Windows?

2006-09-15 Thread michael . hatmaker

[EMAIL PROTECTED] wrote:
> Kevin D. Smith wrote:
> > I've written a simple Python extension for UNIX, but I need to get it
> > working on Windows now.  I'm having some difficulties figuring out how
> > to do this.  I've seen web pages that say that MS Visual Studio is
> > required, and other that say that's not true, that MinGW will work.
> > Then there is Mike Fletcher's web page
> > (http://www.vrplumber.com/programming/mstoolkit/) that describes in
> > detail how to build extensions, but most of the links to external
> > software are no longer valid.  I think it's safe to say that I am
> > completely lost, as there appears to be no authoritative, up-to-date
> > description on how to make this work.
> >
> > --
> > Kevin D. Smith
>
> Borland released a free version of their C++ compiler and IDE on 9/4,
> coinciding with my need to move my GeoTrans extension from Linux to
> Windows.  I didn't need the IDE for the project, since my
> GeoTransMethodsSetup.py script from Linux worked fine, running it with
> the command line argument "--compiler=bcpp".  Add paths to the include
> directories and library directories.
>
> The biggest headache was a bunch of nonsense linker error messages,
> which turned out to be because I had made the mistake of installing the
> compiler under "Program Files", and setup does not behave well with
> spaces in the path name.  As a quick work-around, I used the DOS 8.3
> filename.  Next time I will install Borland in a path with no spaces in
> the name.  So, I was able to use a state-of-the-art compiler, rather
> than work with an obsolete version of some compiler relic.
>
> from distutils.core import setup, Extension
> GeoTransMethods = Extension('GeoTransMethods',
>   include_dirs = ['C:\python24\include'],
>   library_dirs = [
>   r"C:\PROGRA~1\Borland\BDS\4.0\lib",
>   r"C:\PROGRA~1\Borland\BDS\4.0\lib\release",
>   r"C:\PROGRA~1\Borland\BDS\4.0\lib\obj",
>   r"C:\PROGRA~1\Borland\BDS\4.0\lib\PSDK",
>   r"C:\PROGRA~1\Borland\BDS\4.0\lib\Indy9"],
>   sources = ["GeoTransMethods.c", "mgrs.c", 
> "utm.c", "ups.c",
> "tranmerc.c", "polarst.c"])
>
> setup(name="GeoTransMethods", version="1.0",
>   ext_modules=[GeoTransMethods])

I neglected to mention another detail.  There are a number of postings
around regarding earlier Borland compilers.  There is a brief overview
at http://docs.python.org/inst/tweak-flags.html
It mentions the necessity of converting the object file format (COFF)
of python libraries built with Visual C++ to Borland's OMF object file
format.  You need to download coff2omf and run it to make
Borland-linkable copies of python24.lib and any other VC++ built libs,
such as zlib:

coff2omf python24.lib python24_bcpp.lib

Distutils run with the bccp compiler option will look for _bccp
versions and use them before attempting to use the VC++ versions.

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


Re: PostgreSQL, psycopg2 and OID-less tables

2006-09-15 Thread GHUM
Dale,

> Now that OIDs have been deprecated in PostgreSQL, how do you find the key of
> a newly inserted record?

using OIDs as primary key was no good idea for some PostgreSQL versions
allready ... i.e. they really make dump & restore much more
challenging.

So usually us have something along:

CREATE TABLE feuser
(
  id_user serial NOT NULL,
  name text,
  CONSTRAINT feuser_pkey PRIMARY KEY (id_user),
  CONSTRAINT feuser_name_key UNIQUE (name)
)
WITHOUT OIDS;

which automatically creates a sequence for you and rewrites the serial
"id_user" with a default of

nextval('feuser_id_user_seq'::regclass)

So, to get the key of a record inserted, basically there are two
methods. (from now on "cs" is a DB-API 2.0 compliant cursor object,
i.e. from psycopg2

cn=psycopg2.connect()
cs=cn.cursor()

a) get id first, then insert
cs.execute("select nextval('feuser_id_user_seq'::regclass)")
newid=cs.fetchone()[0]

cs.execute("insert into feuser (id_user, name) values (%(id_user)s,
%(name)s)",
 dict(id_user=newid, name="Karl Napf")

cs.commit()
-> now newid contains your new id.

b) create a serverside function on PostgreSQL:
CREATE OR REPLACE FUNCTION insfeuser (text)
  RETURNS integer AS
$BODY$
DECLARE
result int4;
BEGIN

   select nextval('feuser_id_user_seq'::regclass) into result;
   insert into feuser (id_user, name) values (result, $1);

 RETURN result;
END;

$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

within python:
cs.execute("select insfeuser(%(name)s)",  dict(name="Karl Napf"))
newid=cs.fetchone()[0]

Hope that helps,

Harald

--
GHUM Harald Massa
persuadere et programmare
Harald Armin Massa
Reinsburgstraße 202b
70197 Stuttgart
0173/9409607

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


Re: Pre-defining an action to take when an expected error occurs

2006-09-15 Thread Tempo
John Machin  thanks for all of your help, and I take responsibility for
the way I worded my sentences in my last reply to this topic. So in an
effort to say sorry, I want to make it clear to everybody that it seems
as though errors in my code and use of external programs (Excel in
particular) are making "range(sh.nrows)" have faulty results. I am
trying to pinpoint the spot in my code or use of Excel, before
"range(sh.nrows) is executed, that is bugged. John Machin, I am
thrilled that the package xlrd exists at all because it simplifies a
daunting task for a beginner programer--me. Its uses are not bound to
beginners either. So thanks for the package and your help to this point.

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


Re: Coding Nested Loops

2006-09-15 Thread Peter Otten
Rich Shepard wrote:

>I want to code what would be nested "for" loops in C, but I don't know
>the
> most elegant way of doing the same thing in python. So I need to learn how
> from you folks. Here's what I need to do: build a database table of 180
> rows. Each row contains 31 columns: the first is an automatically
> incremented integer as the primary key; the next two fields can each
> contain one of three strings held in dictionaries, the last 28 fields are
> random floats from a third dictionary.
> 
>Of the 180 total rows, each of the three values in the first dictionary
> will be the second field in 60 rows. Within each set of 60 rows, there
> will be 13 rows containing the first value from the second dictionary, 14
> rows containing the second value from the second dictionary, and 33 rows
> from the third value in that dictionary. Again, the final 28 fields in
> each row are random values from the third dictionary.
> 
>I suspect that iterators might be the way to accomplish this, but I
>really
> don't know. However, I would like to learn so that I can solve similar
> problems by myself.

It's not clear to me why you would use dictionaries, especially as they are
unordered; I used lists instead:

from itertools import count, izip, cycle, chain, repeat, starmap, imap
from random import choice

first =  ["X", "Y", "Z"]
second = ["A", "B", "C"]
second_count = [13, 14, 33]
third = [1.1, 2.2, 3.3, 4.4]

random_floats = imap(choice, repeat(third))
columns = [
count(),
chain(*[repeat(i, 60) for i in first]),
cycle(chain(*starmap(repeat, izip(second, second_count
]
columns.extend(repeat(random_floats, 28))

for row in izip(*columns):
print row

Now that is a nice occasion to get acquainted with the itertools module...

Peter

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


Re: Coding Nested Loops

2006-09-15 Thread Rich Shepard
On Fri, 15 Sep 2006, Peter Otten wrote:

> It's not clear to me why you would use dictionaries, especially as they
> are unordered; I used lists instead:

Peter,

   Because the data comes via a serial port as sequences of two bytes from an
OMR reader, and the byte pairs need to be converted into values meaningful
to the application.

Rich

-- 
Richard B. Shepard, Ph.D.   |The Environmental Permitting
Applied Ecosystem Services, Inc.(TM)|Accelerator
 Voice: 503-667-4517  Fax: 503-667-8863
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding Nested Loops

2006-09-15 Thread Bjoern Schliessmann
Rich Shepard wrote:
> On Fri, 15 Sep 2006, Peter Otten wrote:
 
>> It's not clear to me why you would use dictionaries, especially
>> as they are unordered; I used lists instead:

>Because the data comes via a serial port as sequences of two
>bytes from an
> OMR reader, and the byte pairs need to be converted into values
> meaningful to the application.

That doesn't answer the question. A list of 2-tuples would do the
same (and was ordered and could be indexed).

Regards,


Björn

-- 
BOFH excuse #408:

Computers under water due to SYN flooding.

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


Re: Exposing Excel as a Webservice

2006-09-15 Thread utabintarbo
Disclaimer: I am not an expert in python, or even programming, for that
matter

In any case, option #2 sounds like the most theoretically sound. It
sounds like you are using Excel as a database, and your worker thread
as a transaction queue.

Something to consider: do you really need to modify directly a
spreadsheet? Can you not use another format to feed a template
spreadsheet (ie. xml or csv), and then modify that file as a text file
without the overhead of Excel?

Just a thought

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


Re: Limitate speed of a socket-based data transferring

2006-09-15 Thread Steve Holden
Grant Edwards wrote:
> On 2006-09-15, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> 
>>On 14 Sep 2006 04:54:48 -0700, "billie" <[EMAIL PROTECTED]> declaimed the
>>following in comp.lang.python:
>>
>>
>>>Hi all. I'm writing a TCP-based application that I will use to trasfer
>>>binary files through the network. This piece of code represents how do
>>>I get a file from a remote peer and save it on my local hard drive:
>>>
>>
>>  
>>
>>>I would like to know how could be possible to limit the file transfer
>>>speed (for example: don't write more than 50 Kb/sec).
>>>Some ideas?
>>>
>>
>>  I'm not sure you /can/ limit the /receive/ speed.
> 
> 
> Sure you can.  Just read data from the socket at the max speed
> you want to receive.  The receive buffer for that socket will
> fill up and the TCP window will start close up and throttle the
> sender.
> 
> 
>>The sender will send at whatever rate they are capable of, so
>>packets may just become backlogged on your receiving socket
> 
> 
> When that happens, the sending end of the socket will throttle
> down to match the rate at which data is being read from the
> socket.
> 
> 
>>waiting for you to read them if you add some sort of delay to
>>your reading loop.
> 
> 
Of course this depends crucially on the window size. Since the addition 
of the window scaling TCP option it's been possible to specify very 
large windows, which are useful over high-bandwidth high-delay links.

The remote (send) throttling will only start to cut in when the window 
is full (since the whole point of the sliding window mechanism is to 
allow continuous transmission in the face of acknowledgment delay).

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


how do you convert and array of doubles into floats?

2006-09-15 Thread SpreadTooThin
I have some code...

import array

a = array.array('d')
f = open('file.raw')
a.fromfile(f, 10)

now I need to convert them into floats (32 bit...) what do i do?

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


REQ: Java/J2EE Developer 10 Months

2006-09-15 Thread shrikant
Hi Partners,

Please check the following project details. If you are comfortable with
the requirement. Please send me your resume with the following details
asap.

Name of the Consultant
  - Phone Number
  - Email
  - Rate / Salary
  - Availability
  - Location

Location: Dallas, TX.

Duration: 10 Months

Rate: DOE


Skill:


*Java, 2 year UNIX - HP / Solaris, 2 yrs OOA+D, Corba, Perl, XML, UML.
*Java dev experience, Swing, JPS, 2 years of OOA+D.



*We need 5 server side Java developers, and 5 front end Java devs


--
Regards

Shrikant,
COOLSOFT LLC,
E-Mail: [EMAIL PROTECTED]
www.coolsoft.com
502-212-9464

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


Re: Outbound port on sockets

2006-09-15 Thread Steve Holden
Grant Edwards wrote:
> On 2006-09-15, Sergei Organov <[EMAIL PROTECTED]> wrote:
> 
> 
>It's not the issue here, but to specify the outgoing port
>call bind(('', portnum)) before connect().
> 
> 
>>>It's an interesting thing to know, but I've been doing TCP
>>>stuff for many years and never run across a situation where
>>>it's something I needed to do.  If somebody in this thread
>>>actually does need to do it, I'd be curious bout why...
>>
>>Well, one of ftpd implementations I have here (C code from RTEMS) does
>>this:
>>
>>  /* anchor socket to avoid multi-homing problems */
>>  data_source = info->ctrl_addr;
>>  data_source.sin_port = htons(20); /* ftp-data port */
>>  if(bind(s, (struct sockaddr *)&data_source, sizeof(data_source)) < 0)
>>ERROR;
>>  ...
>>  if(connect(s,
>>  (struct sockaddr *)&info->def_addr,
>>  sizeof(struct sockaddr_in)) < 0
>>  )
>>ERROR;
>>
>>I've no idea what "multi-homing problems" are, but maybe it gives you
>>some hint?
> 
> 
> I don't know what "multi-homing problems are either".
> Apparently there must be some ftp clients that require the
> source port for the data connection to be port 20.
> 
> The RFC is pretty vague. It does say the server and clinet but
> must "support the use of the default data port [port 20]" or
> something like that. But, it's not all all clear to me what
> that is supposed to mean.  My reading is that they must support
> the default port as the destination port for a data connection
> untill it's been changed by receipt of a PORT command.
> 
> But, like I said, is very vague, and I suppose some client
> implementor could have read it as the server must use the
> default data port as the source port for a data connection.

Standard (port-mode) FTP has the client send a PORT command to the 
server when data transfer is required. The server then makes a 
connection to the indicated port from its own port 20. If you look in 
/etc/services you'll likely see that port 21 is identified as "ftp" or 
"ftp-control" and 20 as "ftp-data".

Passive mode was introduced so that the server is not required to make a 
connection inbound to the client, as more and more firewalls were 
interposed at the perimeter of networks, blocking the inbound requests 
to clients from servers.

I suspect that the reason for the comment is simply that the connection 
out from the server is being bound to the same interface (*IP address*) 
that the inbound request arrived on. That way it's less likely that the 
data stream will be routed differently from the control (port 21) stream.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Pre-defining an action to take when an expected error occurs

2006-09-15 Thread Steve Holden
John Machin wrote:
[...]
> 
> [1] There's a possibility that the package's author reads this
> newsgroup, and I've heard tell that he's a cranky old so-and-so; you
> wouldn't want him to take umbrage, would you?
> 
Cranks doesn't even *begin* to describe it ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: how do you convert and array of doubles into floats?

2006-09-15 Thread Diez B. Roggisch
SpreadTooThin schrieb:
> I have some code...
> 
> import array
> 
> a = array.array('d')
> f = open('file.raw')
> a.fromfile(f, 10)
> 
> now I need to convert them into floats (32 bit...) what do i do?

I guess module struct is your friend.

Something like this:

struct.pack("f" * len(a), *a)



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


Re: how do you convert and array of doubles into floats?

2006-09-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, SpreadTooThin
wrote:

> I have some code...
> 
> import array
> 
> a = array.array('d')
> f = open('file.raw')
> a.fromfile(f, 10)
> 
> now I need to convert them into floats (32 bit...) what do i do?

What about:

b = array.array('f', a)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >