socket.getsockopt() and SO_ORIGINAL_DST

2010-05-20 Thread chris
Hi guys,

On netfilter-based NAT systems there is theoretically a possibility to
retrieve the original address *after* NAT'ing a connection. In C, this
can be done as in squid, a transparent HTTP proxy:

  http://paste.pocoo.org/show/216495/


I'd like to do the same in Python. So I started with a small script:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 2626))
s.listen(1)
conn, addr = s.accept()
dst = conn.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST)



Since SO_ORIGINAL_DST is not defined in socket.py, the program fails:
  AttributeError: 'module' object has no attribute 'SO_ORIGINAL_DST'

So I thought I'd be smart and look up the constant myself. Indeed, I
found it to be defined in:

  /usr/include/linux/netfilter_ipv4.h:75:#define SO_ORIGINAL_DST 80

I replaced the getsockopt() call with

  dst = conn.getsockopt(socket.SOL_IP, 80)

and ran into a new problem:

Traceback (most recent call last):
  File "listen.py", line 14, in 
dst = conn.getsockopt(socket.SOL_IP, 80)
  File "", line 1, in getsockopt
socket.error: [Errno 22] Invalid argument


In C, everything works fine. But I really need this problem to be solved
in Python. Do you have any ideas?

Thanks for any support in advance and regards,
Chris

PS: I know there are ugly work-arounds to parse /proc/net/ip_conntrack
to do this job, but I will defenitely avoid that.

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


Help with PyQt4 tabwidget setup

2010-05-20 Thread dpalmboom
I am creating an application and I'm busy designing the main layout on the
main window. What I would like to do is the following:

Create a QTabWidget with a QVBoxLayout already inside it and also a
scrollbar inside it. When a user triggers a menu item,
a QDockWidget must be created and inserted into the QVBoxLayout, but it must
not stretch to the bottom of the QTabWidget.
The QDockWidget must keep a set size in the QVBoxLayout. When the user
triggers another menu item, the next QDockWidget must go
above or below the existing QDockWidgets in the QVBoxLayout.

I currently have the following code for the QTabWidget:

class PaneTabWidget(PyQt4.QtGui.QTabWidget):

def __init__(self, tabs, parent=None):

"""
A tabwidget to go inside a Pane.
""" 

super(PaneTabWidget, self).__init__(parent)

for tab in tabs:

if tab == "Properties":
self.propertiesBin()
elif tab == "Schedule":
self.scheduleBin()
elif tab == "Pricelist":
self.pricelistBin()

def setLayoutAndScrollBar(self, page):
pass

def addPanel(self, panel, type):
self.addTab(panel, type)

def propertiesBin(self):
self.page = PyQt4.QtGui.QWidget()
self.addTab(self.page, "Properties")
self.setLayoutAndScrollBar(self.page)

Right now, the dockwidget gets put into a new tab in the tab widget, but I
would like to put it into an existing 
QVBoxLayout. I currently have a blank QWidget as a "placeholder" page of the
tabwidget.

If anyone can help me with this, it would be greatly appreciated.

Thanks


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


Re: optional argument to a subclass of a class

2010-05-20 Thread Alex Hall
On 5/20/10, alex23  wrote:
> Patrick Maupin  wrote:
>> One thing you can do is in battleship, you can accept additional
>> keyword arguments:
>>
>> def __init__(self, name, ..., **kw):
>>
>> Then you could invoke the superclass's init:
>>
>> Craft.__init__(self, name, **kw)
>
> _All_ of which is covered in the tutorial. At what point do we expect
> people to actually put some effort into learning the language
> themselves? Is this why we're constantly spammed with "write my code
> for me" requests?
I am certainly NOT asking anyone to write my code for me. In fact, I
almost never copy and paste code, since writing it myself helps me to
both remember it and examine it to see what is going on and figure out
why it works. I am basically teaching myself Python; my experience is
in Java (basic), JS (somewhat advanced), and a smattering of other
languages. I have rarely dealt with classes before, and certainly not
sub-classing. I have googled all of this and have read the docs and
tutorials, but nothing made sense enough for me to figure out why I
would be getting my particular error. I have since updated each ship's
__init__ to accept all the arguments that Craft accepts so that I can
support all optional arguments, but I thought subclassing was supposed
to take care of this for me... Suppose not.
>
> If you're asking _basic_ "how do I" questions, and you don't even have
> the common sense to read through the support docs before doing so,
> then you really should be directing questions here:
> http://mail.python.org/mailman/listinfo/tutor
Again, I have read the docs. I often find them quite useful, but there
are times where a new concept, in a relatively new language, just will
not work and a doc is not going to say "at this point in your code,
you should to A instead of B, because..."
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional argument to a subclass of a class

2010-05-20 Thread Patrick Maupin
On May 20, 10:35 pm, Alex Hall  wrote:

> So how do I get at anything inside **kw? Is it a list?

It's a dictionary.  Use *args for a list.  (As with self, the name is
whatever you want to use, but some sort of consistency is nice.)

One of the cool things about Python is how easy it is to play at the
command prompt:

>>> def foo(x=3, y=7):
... print x,y
...
>>> def sam(**kw):
... print kw
... foo(**kw)
...

>>> sam(x=5)
{'x': 5}
5 7

>>> sam(y='hi there')
{'y': 'hi there'}
3 hi there

>>> sam(z=42)
{'z': 42}
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in sam
TypeError: foo() got an unexpected keyword argument 'z'
>>>


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


Re: optional argument to a subclass of a class

2010-05-20 Thread alex23
Patrick Maupin  wrote:
> One thing you can do is in battleship, you can accept additional
> keyword arguments:
>
>     def __init__(self, name, ..., **kw):
>
> Then you could invoke the superclass's init:
>
>     Craft.__init__(self, name, **kw)

_All_ of which is covered in the tutorial. At what point do we expect
people to actually put some effort into learning the language
themselves? Is this why we're constantly spammed with "write my code
for me" requests?

If you're asking _basic_ "how do I" questions, and you don't even have
the common sense to read through the support docs before doing so,
then you really should be directing questions here:
http://mail.python.org/mailman/listinfo/tutor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional argument to a subclass of a class

2010-05-20 Thread Alex Hall
On 5/20/10, Patrick Maupin  wrote:
> On May 20, 9:56 pm, Alex Hall  wrote:
>> Hi all,
>> I am now trying to allow my classes, all of which subclass a single
>> class (if that is the term), to provide optional arguments. Here is
>> some of my code:
>>
>> class Craft():
>>  def __init__(self,
>>  name,
>>  isAircraft=False,
>>  id=helpers.id(),
>>  hits=0,
>>  weapons=[]):
>>   self.name=name
>>   self.id=id
>>   self.hits=hits
>>   self.weapons=weapons
>>   self.isAircraft=isAircraft
>>  #end def
>> #end class
>>
>> #now a class for each type of craft in the game
>> #each will subclass the Craft class, but each also has its own settings
>>
>> class Battleship(Craft):
>>  def __init__(self,
>>  name,
>>  maxHits):
>>   Craft.__init__(self, name)
>>   self.maxHits=maxHits
>>   self.length=maxHits #in Battleship, each ship's length is the same
>> as how many times it can be hit
>>  #end def
>> #end class
>>
>> I want to be able to say something like
>> b=Battleship("battleship1", 4, weapons=["missile1","missile2"])
>> When I do that, though, I get a traceback on the above line saying
>> "type error: __init__() got an unexpected keyword argument 'weapons'".
>> What did I do wrong / what do I need to change so that any Craft
>> (Battleship, Carrier, and so on) can optionally provide a list of
>> weapons, or any other arguments to which I assign default values in my
>> Craft class? I hope this makes sense.
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg...@gmail.com;http://www.facebook.com/mehgcap
>
> You overrode the __init__method from the superclass.
I know, I thought I had to in order to make all of Craft's attribs
available to the Battleship. Is that not the case?
>
> One thing you can do is in battleship, you can accept additional
> keyword arguments:
>
> def __init__(self, name, ..., **kw):
>
> Then you could invoke the superclass's init:
>
> Craft.__init__(self, name, **kw)
So how do I get at anything inside **kw? Is it a list?
>
> Regards,
> Pat
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional argument to a subclass of a class

2010-05-20 Thread Patrick Maupin
On May 20, 9:56 pm, Alex Hall  wrote:
> Hi all,
> I am now trying to allow my classes, all of which subclass a single
> class (if that is the term), to provide optional arguments. Here is
> some of my code:
>
> class Craft():
>  def __init__(self,
>  name,
>  isAircraft=False,
>  id=helpers.id(),
>  hits=0,
>  weapons=[]):
>   self.name=name
>   self.id=id
>   self.hits=hits
>   self.weapons=weapons
>   self.isAircraft=isAircraft
>  #end def
> #end class
>
> #now a class for each type of craft in the game
> #each will subclass the Craft class, but each also has its own settings
>
> class Battleship(Craft):
>  def __init__(self,
>  name,
>  maxHits):
>   Craft.__init__(self, name)
>   self.maxHits=maxHits
>   self.length=maxHits #in Battleship, each ship's length is the same
> as how many times it can be hit
>  #end def
> #end class
>
> I want to be able to say something like
> b=Battleship("battleship1", 4, weapons=["missile1","missile2"])
> When I do that, though, I get a traceback on the above line saying
> "type error: __init__() got an unexpected keyword argument 'weapons'".
> What did I do wrong / what do I need to change so that any Craft
> (Battleship, Carrier, and so on) can optionally provide a list of
> weapons, or any other arguments to which I assign default values in my
> Craft class? I hope this makes sense.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com;http://www.facebook.com/mehgcap

You overrode the __init__method from the superclass.

One thing you can do is in battleship, you can accept additional
keyword arguments:

def __init__(self, name, ..., **kw):

Then you could invoke the superclass's init:

Craft.__init__(self, name, **kw)

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


optional argument to a subclass of a class

2010-05-20 Thread Alex Hall
Hi all,
I am now trying to allow my classes, all of which subclass a single
class (if that is the term), to provide optional arguments. Here is
some of my code:

class Craft():
 def __init__(self,
 name,
 isAircraft=False,
 id=helpers.id(),
 hits=0,
 weapons=[]):
  self.name=name
  self.id=id
  self.hits=hits
  self.weapons=weapons
  self.isAircraft=isAircraft
 #end def
#end class


#now a class for each type of craft in the game
#each will subclass the Craft class, but each also has its own settings

class Battleship(Craft):
 def __init__(self,
 name,
 maxHits):
  Craft.__init__(self, name)
  self.maxHits=maxHits
  self.length=maxHits #in Battleship, each ship's length is the same
as how many times it can be hit
 #end def
#end class


I want to be able to say something like
b=Battleship("battleship1", 4, weapons=["missile1","missile2"])
When I do that, though, I get a traceback on the above line saying
"type error: __init__() got an unexpected keyword argument 'weapons'".
What did I do wrong / what do I need to change so that any Craft
(Battleship, Carrier, and so on) can optionally provide a list of
weapons, or any other arguments to which I assign default values in my
Craft class? I hope this makes sense.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread D'Arcy J.M. Cain
On Thu, 20 May 2010 19:53:42 + (UTC)
Grant Edwards  wrote:
> Since Python is interactive, and you don't get charged for each time
> you run your deck through the reader, that's easy enough to check:

Whoa!  For a moment there I thought it was 1969.  :-)

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ugly modification of a class, can it be done better ?

2010-05-20 Thread Steven D'Aprano
Sorry for breaking threading, but Stef's original post has not come 
through to me.

> On Thu, May 20, 2010 at 8:13 PM, Stef Mientki 
> wrote:

>> So I want to change the behavior of the class dynamically. I've done it
>> by adding a global variable (Base_Grid_Double_Click) in the module,
>> initial set to None,
>> but can be changed by the main program to some callback function. (see
>> the code below)

How is this supposed to work? If you have *one* global, then *every* 
instance will see the same setting. To change it dynamically, you enter a 
nightmare world of having to save the global, modify it, then restore it, 
every single time. Trust me, I've been there, this is the *worst* way of 
programming. This is why object oriented inheritance was invented, to 
escape this nonsense!

The first thing is to make the callback specific to the class, not 
global. Why does your printing code need access to the callback that 
handles double-clicking on a grid? It doesn't! So don't give it that 
access (at least, not easy access). Put the callback in the class.

class MyClass:
callback = None
def method(self, *args):
if self.callback is None:
behaviour_with_no_callback()
else:
behaviour_with_callback()


Now if you want to apply a callback to some instances, and not others, it 
is totally simple:


red = MyClass()
blue = MyClass()
red.callback = my_callback_function

and you're done.


If you have lots of instances that use the same callback? Make a subclass.

class MyDottedClass(MyClass):
pass

red = MyClass()
blue = MyClass()
red_with_green_dots = MyDottedClass()
blue_with_green_dots = MyDottedClass()

MyDottedClass.callback = dotted_callback

And now all the dot instances will use the same callback without 
effecting the undotted instances. What to change them all to use a 
different behaviour?

MyDottedClass.callback = something_different

and now they all change, again without effecting the undotted instances.




>> Is this a valid construction ( sorry I'm not a programmer), or are
>> there better ways to accomplish similar dynamic behavior ?

Of course you're a programmer! You're writing programs, aren't you?




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


Re: starting repl programmatically

2010-05-20 Thread Steven D'Aprano
On Thu, 20 May 2010 17:11:17 -0700, Brendan Miller wrote:

> python -i myscript.py
> 
> almost does what I want. The only problem is if I exit with exit(0) it
> does *not* enter interactive mode. I have to run off the end of the
> script as near as I can tell. Is there another way to exit without
> breaking python -i?

Upgrade to Python 2.6 and it will work as expected.

[st...@sylar ~]$ python2.6 -i -c "import sys; sys.exit(0)"
Traceback (most recent call last):
  File "", line 1, in 
SystemExit: 0
>>>



If you're stuck with 2.5, you can wrap your script in a try...except and 
catch the exit:


[st...@sylar ~]$ python -i -c "import sys
> try:
> x = 2
> sys.exit(0)
> except SystemExit:
> pass
> "
>>> x
2


The only side-effect I can think of is that you may lose any non-zero 
result codes, but you probably do that after entering interactive mode 
anyway.

If you want to be fancy, you can inspect the state of the environment 
variable and Python options inside the except block, and re-raise if 
necessary. Untested:

except SystemExit:
if os.getenv('PYTHONINSPECT'):
pass
else:
raise


I can't find a way to check for a -i switch from inside Python 2.5. There 
is a sys.flags but it is only available in Python 2.6 or higher.



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


Re: starting repl programmatically

2010-05-20 Thread Patrick Maupin
On May 20, 6:57 pm, Brendan Miller  wrote:
> I have a python script that sets up some environmental stuff. I would
> then like to be able to change back to interactive mode and use that
> environment. What's the best way to do that?

>>> import cmd
>>> class MyCmd(cmd.Cmd):
...   def default(self, line):
... exec line in globals()
...
>>> MyCmd().cmdloop()
(Cmd) s = 'The answer is probably to use %s'
(Cmd) print s % 'the cmd module'
The answer is probably to use the cmd module
(Cmd)

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


Re: Ugly modification of a class, can it be done better ?

2010-05-20 Thread Jack Diederich
On Thu, May 20, 2010 at 8:13 PM, Stef Mientki  wrote:
> hello,
>
> This might be a strange question, but as a practical guy, I'm not searching
> for the best solution, but for a practical solution.
>
> I've a class which I've used very extensively.
> Now I want to extend that class with an action on a double click event, but
> that action is determined by the main program.
> Normally I would create an derived class and add that specific action.
> But I find it too much effort in this specific case, half of the instances
> need the extension, half of it dont.
> So I want to change the behavior of the class dynamically.
> I've done it by adding a global variable (Base_Grid_Double_Click) in the
> module,
> initial set to None,
> but can be changed by the main program to some callback function.
> (see the code below)
> Is this a valid construction ( sorry I'm not a programmer),
> or are there better ways to accomplish similar dynamic behavior ?
>

You can have two classes and then just change the class of the
instances that need it.

class A(object):
  def method1(self): pass

class B(A):
  def method2(self): pass

ob = A()
# click happens
ob.__class__ = B

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


Re: starting repl programmatically

2010-05-20 Thread Steven D'Aprano
On Thu, 20 May 2010 16:57:40 -0700, Brendan Miller wrote:

> I have a python script that sets up some environmental stuff. I would
> then like to be able to change back to interactive mode and use that
> environment. What's the best way to do that?

On most(?) Linux distros, `man python` is your friend. (Like all well-
behaviour apps, python should come with a man page.) `python --help` is 
useful too, and will be platform independent. Both tell me that you want 
to pass -i as an option to enter the interactive interpreter after 
running a module or command:

[st...@sylar ~]$ python -c "print 'hello world'; x = 2"
hello world
[st...@sylar ~]$ python -i -c "print 'hello world'; x = 2"
hello world
>>> x
2

You can also set an environment variable to force the same behaviour. See 
the help for details.


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


Ugly modification of a class, can it be done better ?

2010-05-20 Thread Stef Mientki
hello,

This might be a strange question, but as a practical guy, I'm not
searching for the best solution, but for a practical solution.

I've a class which I've used very extensively.
Now I want to extend that class with an action on a double click event,
but that action is determined by the main program.
Normally I would create an derived class and add that specific action.
But I find it too much effort in this specific case, half of the
instances need the extension, half of it dont.
So I want to change the behavior of the class dynamically.
I've done it by adding a global variable (Base_Grid_Double_Click) in the
module,
initial set to None,
but can be changed by the main program to some callback function.
(see the code below)
Is this a valid construction ( sorry I'm not a programmer),
or are there better ways to accomplish similar dynamic behavior ?

thanks,
Stef Mientki



#== module grid_library ==

Base_Grid_Double_Click = None

class Base_Grid ( wx.grid.Grid ) :
  def __init__ ( self, 

self.Bind ( gridlib.EVT_GRID_CELL_LEFT_DCLICK , self._On_Double_Click )
   

  def _On_Double_Click ( self, event ) :
if Base_Grid_Double_Click :
  Row = event.Row
  Col = event.Col
  Col_Label = self.GetColLabelValue ( Col )
  Row_Label = self.GetRowLabelValue ( Row )
  Base_Grid_Double_Click ( self.GetCellValue ( Row, Col ),
   Col_Label, Row_Label )
else :
  event.Skip ()

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


Re: starting repl programmatically

2010-05-20 Thread Brendan Miller
python -i myscript.py

almost does what I want. The only problem is if I exit with exit(0) it
does *not* enter interactive mode. I have to run off the end of the
script as near as I can tell. Is there another way to exit without
breaking python -i?

On Thu, May 20, 2010 at 4:57 PM, Brendan Miller  wrote:
> I have a python script that sets up some environmental stuff. I would
> then like to be able to change back to interactive mode and use that
> environment. What's the best way to do that?
>
-- 
http://mail.python.org/mailman/listinfo/python-list


starting repl programmatically

2010-05-20 Thread Brendan Miller
I have a python script that sets up some environmental stuff. I would
then like to be able to change back to interactive mode and use that
environment. What's the best way to do that?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Display file names in Tkinter Listbox

2010-05-20 Thread sit
On Fri, 21 May 2010 08:02:30 +1000, John McMonagle
 wrote:

>s...@home.com wrote:
>
>> I have made the modifications and it does print inside the listbox,
>> however they are all  printed on the same line. 
>> 
>
>Sorry, I didn't realize askopenfilenames returned the filenames as a
>whitespace separated string, on my system they are returned as a tuple
>of strings.
>
>
>> My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like
>> them to be printed sorted on a separate line. When I did a 
>> type(fileNames) it showed me that it was in unicode and printed
>> character per line, so I tried it this way
>> 
>> listFileNames = str(fileNames).split(' ')
>> for fileName in listFileNames:
>>  self.lbox.insert(0, fileName)
>>  
>> it works but does not print sorted.
>> 
>> it prints
>> 
>> name.2
>> name.1
>> name.0
>> name.3
>> 
>> 
>
>You obviously need to sort the list before you loop over the items and
>add them to your listbox.
>
>listFileNames = sorted(str(filenames).split()
>
>
>Regards,
>
>John

Thank you, it worked 
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Picking a license

2010-05-20 Thread Delaney, Timothy (Tim)
From: Ben Finney

> This thread is already off-topic and too long. I'm conflicted about my
role in that;
> I have endeavoured only to address falsehoods that IMO were not
otherwise being addressed.
>
> So I'll try to keep this brief.
>
> Ethan Furman  writes:
>
>> This doesn't make sense to me, but I'm willing to learn -- how do you

>> do this in practice? Are you really selling the software
>
> Perhaps in private email we can discuss what you mean by "really
selling the software";
> it's too off-topic here. By my understanding of that term, yes, I am
selling software.
>
>> or rather selling things like setup, support, new code (or time to 
>> code), etc?
>
>All of the above, depending on the project.

Considering that's one of the only two interesting things that have come
out of this
discussion, if you're willing to discuss that in public (in another
thread) I'd be very
interested in reading it.

BTW, the other interesting thing is the inadvertent license violations
where I tend to
think Pat has the right interpretation, but am not sure.

For the record, I tend to be in favour of permissive licenses both for
releasing my own
code and using others' (not least because I am employed by a company and
it makes my work
easier), but there are good reasons for using any license so long as you
understand the
consequences of your decision.

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


Re: Display file names in Tkinter Listbox

2010-05-20 Thread John McMonagle
s...@home.com wrote:

> I have made the modifications and it does print inside the listbox,
> however they are all  printed on the same line. 
> 

Sorry, I didn't realize askopenfilenames returned the filenames as a
whitespace separated string, on my system they are returned as a tuple
of strings.


> My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like
> them to be printed sorted on a separate line. When I did a 
> type(fileNames) it showed me that it was in unicode and printed
> character per line, so I tried it this way
> 
> listFileNames = str(fileNames).split(' ')
> for fileName in listFileNames:
>   self.lbox.insert(0, fileName)
>   
> it works but does not print sorted.
> 
> it prints
> 
> name.2
> name.1
> name.0
> name.3
> 
> 

You obviously need to sort the list before you loop over the items and
add them to your listbox.

listFileNames = sorted(str(filenames).split()


Regards,

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


Re: What's the matter with docs.python.org?

2010-05-20 Thread David Bolen
Christian Mertes  writes:

> On Mi, 2010-05-19 at 16:42 -0700, Aahz wrote:
>> Also, I think you need to pass the host HTTP header to access
>> docs.python.org
>
> Look, I don't really want to read Python docs via telnet. I basically
> wanted to point out that there is strange behaviour and someone might
> feel responsible and look into it.

I think the point is that if you are going to use telnet as a
diagnostic tool you need to more accurately represent the browser.  I
just tried and using the Host header renders a completely different
response than not (presumably because the server is using virtual
hosting).  With an appropriate "Host: docs.python.org" you get the
actual documentation home page, without it you get the "page has
moved" text you saw.

It may or may not have anything to do with the original problem, but
it probably does explain the response you got when you tried to use
telnet as a test tool.

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


Re: intervall of about 1 second for xmlrpc calls?

2010-05-20 Thread Adam Tauno Williams
On Thu, 2010-05-20 at 22:46 +0200, News123 wrote:
> Hi Adam,
> Adam Tauno Williams wrote:
> > On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote:
> >>> What's wrong?
> >> Obviously there's a problem with "localhost". When using the IP of my
> >> machine everything is working fast.
> I think you're right.
> localhost  with IPV6 was also a problem for me. At least it was for me
> on a windows 7 host.
> I 'solved' the problem by disabling IPV6, but this is a workaround, not
> a proper solution.
> > You box may first be trying to connect to ::1 (ipv6) and when that fails
> > it falls back to 127.0.0.1.  Make sure IPv6 is properly
> > configured/enabled and try the script again.
> Do you know why the default config of IPV6 could be wrong on a windows
> 7 host?

No.  This would seem to have something to do with the resolver.  If you
do a nslookup for localhost what does it say.

> Having no experience with IPV6:

Have lots, it's really nice.  Once you get most things cut over.

> How should it be configured?
> How to detect issues?

Does nslookup localhost return the correct result?  That might depend on
your DNS server - not your local host.

Also "ping ::1"?
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

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


Re: intervall of about 1 second for xmlrpc calls?

2010-05-20 Thread News123
Hi Adam,


Adam Tauno Williams wrote:
> On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote:
>>> What's wrong?
>> Obviously there's a problem with "localhost". When using the IP of my
>> machine everything is working fast.

I think you're right.

localhost  with IPV6 was also a problem for me. At least it was for me
on a windows 7 host.
I 'solved' the problem by disabling IPV6, but this is a workaround, not
a proper solution.

> 
> You box may first be trying to connect to ::1 (ipv6) and when that fails
> it falls back to 127.0.0.1.  Make sure IPv6 is properly
> configured/enabled and try the script again.

Do you know why the default config of IPV6 could be wrong on a windows
7 host?

Having no experience with IPV6:

How should it be configured?
How to detect issues?


thanks


N


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


download youtube free and fast

2010-05-20 Thread women
download youtube free and fast

http://echance.info/cj/youtube.htm
-- 
http://mail.python.org/mailman/listinfo/python-list


Bearing and speed of fertilization

2010-05-20 Thread women
Infertility treatment for free


Bearing and speed of fertilization
http://echance.info/cj/fb.htm
-- 
http://mail.python.org/mailman/listinfo/python-list


Infertility treatment for free

2010-05-20 Thread women
Infertility treatment for free


Bearing and speed of fertilization
http://echance.info/cj/fb.htm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread Grant Edwards
On 2010-05-20, superpollo  wrote:
> Grant Edwards ha scritto:
>> On 2010-05-20, superpollo  wrote:
>>> Steven D'Aprano ha scritto:
 On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:

> ... how many positive integers less than n have digits that sum up to m:

 Does the name "prttn" mean anything? I'm afraid I keep reading it as
 a mispelling of "print n".
>>>
>>> pArtItIOn
>> 
>> One might be tempted to suggest the name "partition".
>
> no kidding: i was afraid to use some reserved word...

Since Python is interactive, and you don't get charged for each time
you run your deck through the reader, that's easy enough to check:

   $ python
   Python 2.6.4 (r264:75706, Mar  1 2010, 10:33:43) 
   [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2
   Type "help", "copyright", "credits" or "license" for more information.
   
   >>> partition
   Traceback (most recent call last):
 File "", line 1, in 
   NameError: name 'partition' is not defined
   
   >>> sum
   
   
   >>> int
   
   
   >>> file
   


Lest my allusions to Fortran IV be lost upon the less grizzled, only
the first 6 characters were significant in Fortran IV identifiers, and
removing all of the vowels from a longer word was an idiomatic way to
create an identifier with a length <= 6.

IIRC, the number 6 was originally chosen because that's how many 6-bit
characters you could hold in a single 36-bit CPU register.  That way
when writing a compiler/link/assembly you could compare two
identifiers using a single "CMP" instruction.

I'm not sure why 36-bits was such a popular ALU width, but many
different vendors sold 36-bit machines back in the day.

-- 
Grant Edwards   grant.b.edwardsYow! Hand me a pair of
  at   leather pants and a CASIO
  gmail.comkeyboard -- I'm living
   for today!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 250

2010-05-20 Thread Emile van Sebille

On 5/20/2010 12:39 AM Martin P. Hellwig said...

On 05/20/10 07:51, cosmeticsafrolatino wrote:

hi

250 locahost.local Hello WimaxUser3645-219.wateen.net [110.36.45.219],
pleased to meet you


:)

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


Re: function that counts...

2010-05-20 Thread superpollo

Grant Edwards ha scritto:

On 2010-05-20, superpollo  wrote:

Steven D'Aprano ha scritto:

On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:


... how many positive integers less than n have digits that sum up to m:

In [197]: def prttn(m, n):
Does the name "prttn" mean anything? I'm afraid I keep reading it as a 
mispelling of "print n".

pArtItIOn


One might be tempted to suggest the name "partition".


no kidding: i was afraid to use some reserved word...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables for python applications

2010-05-20 Thread TomF



On 2010-05-19 07:34:37 -0700, Steven D'Aprano said:


# Untested.
def verbose_print(arg, level, verbosity=1):
if level <= verbosity:
print arg

def my_function(arg):
my_print(arg, level=2)
return arg.upper()

if __name__ == '__main__':
if '--verbose' in sys.argv:
my_print = functools.partial(verbose_print, verbosity=2)
elif '--quiet' in sys.argv:
my_print = functools.partial(verbose_print, verbosity=0)

my_function("hello world")


Note that although there is no verbosity global setting, every function
that calls my_print will do the right thing (unless I've got the test
backwards...), and if a function needs to override the implicit verbosity
setting, it can just call verbose_print directly.



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


Re: Strange MySQL Problem

2010-05-20 Thread Victor Subervi
On Thu, May 20, 2010 at 12:56 PM, MRAB  wrote:

>
> When performing SQL operations, don't insert the values using Python's
> string formatting, because that makes it vulnerable to SQL-injection
> attacks, ie don't do this:
>
>cursor.execute(sql_command % values)
>
> do this:
>
>cursor.execute(sql_command, values)


Oh, thank you!


> I think you need to 'commit' any changes to do to the database.
>

Caught by the commit again. Yes, thanks.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange MySQL Problem

2010-05-20 Thread Christian Heimes

MRAB wrote:

I think you need to 'commit' any changes to do to the database.


Yeah, you are right.
Also some RDBMS don't support DDL and DML statements inside one 
transaction. You may need to commit and begin after the create table DDL.


Christian

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


Re: Strange MySQL Problem

2010-05-20 Thread MRAB

Victor Subervi wrote:

Hi;
I have this code:

#!/usr/bin/python

import cgitb; cgitb.enable()
import cgi
import sys,os
sys.path.append(os.getcwd())
import MySQLdb
from login import login

def create_edit_passengers4():
  print "Content-Type: text/html"
  print
  print '''
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd";>

http://www.w3.org/1999/xhtml";>


'''
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  form = cgi.FieldStorage()
  cursor.execute('create table if not exists Passengers (id int(11) 
auto_increment primary key, flights_id int(11) not null, customer_id 
int(11) not null, foreign key (id) references Flights (flights_id), 
foreign key (id) references Customers (customer_id), name varchar(40), 
weight int) engine=InnoDB;')

  new_passengers = int(form.getfirst('new_passengers'))
  i = 0
  while i < new_passengers:
cursor.execute('insert into Passengers values (Null, %s, %s, "%s", 
%s);' % (form.getfirst('%d:flight' % i), form.getfirst('%d:customer' % 
i), form.getfirst('%d:name' % i, ''), form.getfirst('%d:weight' % i)))


When performing SQL operations, don't insert the values using Python's
string formatting, because that makes it vulnerable to SQL-injection
attacks, ie don't do this:

cursor.execute(sql_command % values)

do this:

cursor.execute(sql_command, values)


i += 1
  print "All passenger information has successfully been added."
  cursor.close()
  print "\n"

create_edit_passengers4()

Now, it throws no errors; however, it doesn't insert. If I print out the 
insert statement to screen and then manually insert it in MySQL it 
inserts. Huh??



I think you need to 'commit' any changes to do to the database.
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread Grant Edwards
On 2010-05-20, superpollo  wrote:
> Steven D'Aprano ha scritto:
>> On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:
>> 
>>> ... how many positive integers less than n have digits that sum up to m:
>>>
>>> In [197]: def prttn(m, n):
>> 
>> Does the name "prttn" mean anything? I'm afraid I keep reading it as a 
>> mispelling of "print n".
>
> pArtItIOn

One might be tempted to suggest the name "partition".

This isn't Fortran-IV. ;)

-- 
Grant Edwards   grant.b.edwardsYow! I've got a COUSIN
  at   who works in the GARMENT
  gmail.comDISTRICT ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread superpollo

Peter Pearson ha scritto:

On Wed, 19 May 2010 21:58:04 +0200, superpollo  wrote:

... how many positive integers less than n have digits that sum up to m:


If it's important for the function to execute quickly for large n,
you might get a useful speedup by testing only every ninth integer,
since any two integers whose digits add up to m differ by a multiple
of 9.  A simple application of this observation would be to test
range( m % 9, n, 9 ) rather than testing range( 1, n ).

I suspect that further applications of number theory would
provide additional, substantial speedups, but this wanders
away from the subject of Python.



great suggestion, thanks!

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


Python 2.6.1 + wxPython 2.8.9.1 compiled form source

2010-05-20 Thread Angel
Hi,

I have a Red Hat 4.6 machone and I compiled and installed python 2.6.1
from source.

Then, I compiled wxPython 2.8.9.1 form source too.

And then, when I try to run it:

# python
Python 2.6.1 (r261:67515, Mar  4 2009, 20:10:49)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
Aborted

Any hint? Anything I am missing? Anyhere to check? Read?

Thanks in advance.

This in my environment:

LD_LIBRARY_PATH=/opt/wxPython/2.8.9.1/lib:/opt/python/2.6.1/lib:/opt/
hpmpi/lib/linux_amd64:/opt/intel/cce/10.1.008/lib:/opt/intel/fce/
10.1.008/lib:/lib:/lib64:/usr/lib:/usr/lib64:/usr/X11R6/lib:/usr/X11R6/
lib64:/usr/local/lib:/usr/local/lib64
PATH=/opt/wxPython/2.8.9.1/bin:/opt/python/2.6.1/bin:/root/aaks/bin:/
opt/hpmpi/bin:/opt/intel/cce/10.1.008/bin:/opt/intel/fce/10.1.008/bin:/
usr/local/bin:/usr/local/X11/bin:/opt/torque/2.3.6/bin:/opt/torque/
2.3.6/sbin:/usr/java/jdk1.6.0_12/bin:/usr/local/sbin:/usr/local/bin:/
sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/etc:/usr/etc:/usr/local/
etc:.:/opt/maui/3.2.6p21/sbin:/opt/maui/3.2.6p21/bin:/root/bin:/opt/
pdsh/2.17/bin
PYTHONPATH=/opt/wxPython/2.8.9.1:/opt/python/2.6.1

And.. a verbose output:

# python -vv
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# trying /opt/wxPython/2.8.9.1/site.so
# trying /opt/wxPython/2.8.9.1/sitemodule.so
# trying /opt/wxPython/2.8.9.1/site.py
# trying /opt/wxPython/2.8.9.1/site.pyc
# trying /opt/python/2.6.1/site.so
# trying /opt/python/2.6.1/sitemodule.so
# trying /opt/python/2.6.1/site.py
# trying /opt/python/2.6.1/site.pyc
# trying /opt/python/2.6.1/lib/python2.6/site.so
# trying /opt/python/2.6.1/lib/python2.6/sitemodule.so
# trying /opt/python/2.6.1/lib/python2.6/site.py
# /opt/python/2.6.1/lib/python2.6/site.pyc matches /opt/python/2.6.1/
lib/python2.6/site.py
import site # precompiled from /opt/python/2.6.1/lib/python2.6/
site.pyc
# trying /opt/wxPython/2.8.9.1/os.so
# trying /opt/wxPython/2.8.9.1/osmodule.so
# trying /opt/wxPython/2.8.9.1/os.py
# trying /opt/wxPython/2.8.9.1/os.pyc
# trying /opt/python/2.6.1/os.so
# trying /opt/python/2.6.1/osmodule.so
# trying /opt/python/2.6.1/os.py
# trying /opt/python/2.6.1/os.pyc
# trying /opt/python/2.6.1/lib/python2.6/os.so
# trying /opt/python/2.6.1/lib/python2.6/osmodule.so
# trying /opt/python/2.6.1/lib/python2.6/os.py
# /opt/python/2.6.1/lib/python2.6/os.pyc matches /opt/python/2.6.1/lib/
python2.6/os.py
import os # precompiled from /opt/python/2.6.1/lib/python2.6/os.pyc
import errno # builtin
import posix # builtin
# trying /opt/wxPython/2.8.9.1/posixpath.so
# trying /opt/wxPython/2.8.9.1/posixpathmodule.so
# trying /opt/wxPython/2.8.9.1/posixpath.py
# trying /opt/wxPython/2.8.9.1/posixpath.pyc
# trying /opt/python/2.6.1/posixpath.so
# trying /opt/python/2.6.1/posixpathmodule.so
# trying /opt/python/2.6.1/posixpath.py
# trying /opt/python/2.6.1/posixpath.pyc
# trying /opt/python/2.6.1/lib/python2.6/posixpath.so
# trying /opt/python/2.6.1/lib/python2.6/posixpathmodule.so
# trying /opt/python/2.6.1/lib/python2.6/posixpath.py
# /opt/python/2.6.1/lib/python2.6/posixpath.pyc matches /opt/python/
2.6.1/lib/python2.6/posixpath.py
import posixpath # precompiled from /opt/python/2.6.1/lib/python2.6/
posixpath.pyc
# trying /opt/wxPython/2.8.9.1/stat.so
# trying /opt/wxPython/2.8.9.1/statmodule.so
# trying /opt/wxPython/2.8.9.1/stat.py
# trying /opt/wxPython/2.8.9.1/stat.pyc
# trying /opt/python/2.6.1/stat.so
# trying /opt/python/2.6.1/statmodule.so
# trying /opt/python/2.6.1/stat.py
# trying /opt/python/2.6.1/stat.pyc
# trying /opt/python/2.6.1/lib/python2.6/stat.so
# trying /opt/python/2.6.1/lib/python2.6/statmodule.so
# trying /opt/python/2.6.1/lib/python2.6/stat.py
# /opt/python/2.6.1/lib/python2.6/stat.pyc matches /opt/python/2.6.1/
lib/python2.6/stat.py
import stat # precompiled from /opt/python/2.6.1/lib/python2.6/
stat.pyc
# trying /opt/wxPython/2.8.9.1/genericpath.so
# trying /opt/wxPython/2.8.9.1/genericpathmodule.so
# trying /opt/wxPython/2.8.9.1/genericpath.py
# trying /opt/wxPython/2.8.9.1/genericpath.pyc
# trying /opt/python/2.6.1/genericpath.so
# trying /opt/python/2.6.1/genericpathmodule.so
# trying /opt/python/2.6.1/genericpath.py
# trying /opt/python/2.6.1/genericpath.pyc
# trying /opt/python/2.6.1/lib/python2.6/genericpath.so
# trying /opt/python/2.6.1/lib/python2.6/genericpathmodule.so
# trying /opt/python/2.6.1/lib/python2.6/genericpath.py
# /opt/python/2.6.1/lib/python2.6/genericpath.pyc matches /opt/python/
2.6.1/lib/python2.6/genericpath.py
import genericpath # precompiled from /opt/python/2.6.1/lib/python2.6/
genericpath.pyc
# trying /opt/wxPython/2.8.9.1/warnings.so
# trying /opt/wxPython/2.8.9.1/warningsmodule.so
# trying /opt/wxPython/2.8.9.1/warnings.py
# trying /opt/wxPython/2.8.9.1/warnings.pyc
# trying /opt/python/2.6.1/warnings.so
# trying /opt/python/2.6.1/warningsmodule.so
# trying /opt/python/2.6.1/warnings.py
# trying /opt/python/2.6.1/warn

Strange MySQL Problem

2010-05-20 Thread Victor Subervi
Hi;
I have this code:

#!/usr/bin/python

import cgitb; cgitb.enable()
import cgi
import sys,os
sys.path.append(os.getcwd())
import MySQLdb
from login import login

def create_edit_passengers4():
  print "Content-Type: text/html"
  print
  print '''
http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd";>
http://www.w3.org/1999/xhtml";>


'''
  user, passwd, db, host = login()
  database = MySQLdb.connect(host, user, passwd, db)
  cursor = database.cursor()
  form = cgi.FieldStorage()
  cursor.execute('create table if not exists Passengers (id int(11)
auto_increment primary key, flights_id int(11) not null, customer_id int(11)
not null, foreign key (id) references Flights (flights_id), foreign key (id)
references Customers (customer_id), name varchar(40), weight int)
engine=InnoDB;')
  new_passengers = int(form.getfirst('new_passengers'))
  i = 0
  while i < new_passengers:
cursor.execute('insert into Passengers values (Null, %s, %s, "%s", %s);'
% (form.getfirst('%d:flight' % i), form.getfirst('%d:customer' % i),
form.getfirst('%d:name' % i, ''), form.getfirst('%d:weight' % i)))
i += 1
  print "All passenger information has successfully been added."
  cursor.close()
  print "\n"

create_edit_passengers4()

Now, it throws no errors; however, it doesn't insert. If I print out the
insert statement to screen and then manually insert it in MySQL it inserts.
Huh??
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-20 Thread Peter Pearson
On Wed, 19 May 2010 21:58:04 +0200, superpollo  wrote:
> ... how many positive integers less than n have digits that sum up to m:

If it's important for the function to execute quickly for large n,
you might get a useful speedup by testing only every ninth integer,
since any two integers whose digits add up to m differ by a multiple
of 9.  A simple application of this observation would be to test
range( m % 9, n, 9 ) rather than testing range( 1, n ).

I suspect that further applications of number theory would
provide additional, substantial speedups, but this wanders
away from the subject of Python.

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


Re: Display file names in Tkinter Listbox

2010-05-20 Thread sit
On Thu, 20 May 2010 15:36:59 +1000, John McMonagle
 wrote:

>r...@home.com wrote:
>> Hello,
>> 
>> My first attenpt at a simple  python Tkinter application. I wanted to
>> see how to load file names into a listbox from a menu. This is what I
>> got until the part of displaying the file names in a listbox, which I
>> could not figfure out how to do?
>> 
>> Any help would be appreciated. Trying to do this as simple as possible
>> to understand.
>> 
>> The "print fileNames" does work but how to display it in listbox?
>> 
>> from Tkinter import *
>> from tkFileDialog   import askopenfilenames
>> 
>> class MyCode:
>>def __init__(self):
>>   root = Tk()
>>   
>>   menubar = Menu(root)
>>   filemenu = Menu(menubar)
>>   
>>   lbox = Listbox(root, width=50).pack()
>
>Your problem is the above line of code.
>
>Here you are assigning the return value of the pack (None if I recall).
>
>Later when you want to put things in the Listbox you don't have the
>widget reference anymore.
>
>It's probably a good idea to make the Listbox widget an attribute of
>your class so you can use it in class methods without having to pass it
>as an argument.
>
>So, change the above line of code to:
>
>self.lbox = Listbox(root, width=50)
>self.lbox.pack()
>
>>   
>>   menubar.add_cascade(label='File', menu=filemenu)
>>   filemenu.add_command(label='New Project')
>>   filemenu.add_command(label='Load Files...', command=self.OnLoad)
>>   
>> 
>>   filemenu.add_command(label='Exit', command=root.quit)
>>   
>>   root.config(menu=menubar)
>>   
>>   root.mainloop()
>>   
>>   
>>def OnLoad(self):
>>   fileNames = askopenfilenames(filetypes=[('Split Files', '*')])
>>   print fileNames
>> 
>
>Now that you've got a reference to your Listbox widget that is an
>attribute of your class, you should be able to insert the file names
>into the Listbox like so.
>
>self.lbox.insert(0, fileNames)
>
>Regards,
>
>John

Thank you John for your reply.

I have made the modifications and it does print inside the listbox,
however they are all  printed on the same line. 

My files are named Name.0 Name.1 Name.2 Name.3 etc so I would like
them to be printed sorted on a separate line. When I did a 
type(fileNames) it showed me that it was in unicode and printed
character per line, so I tried it this way

listFileNames = str(fileNames).split(' ')
for fileName in listFileNames:
self.lbox.insert(0, fileName)

it works but does not print sorted.

it prints

name.2
name.1
name.0
name.3


Thank you for all your help. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why struct.pack behave like this

2010-05-20 Thread Dave Angel

Xie&Tian wrote:

Hi

When I use struct to pack binary data, I found this interesting behaviour:

  

import struct
struct.pack('B', 1)


'\x01'
  

struct.pack('H', 200)


'\xc8\x00'
  

struct.pack('BH',1, 200)


'\x01\x00\xc8\x00'
  

struct.calcsize('BH')


4

Why does "struct.pack('BH',1, 200)" come out with an extra "\x00"?


  

To quote the help:

>>By default, C numbers are represented in the machine’s native format 
and byte order,
>>and properly aligned by skipping pad bytes if necessary (according to 
the rules used by the C compiler).


C's standard rules say that when a smaller type is followed by a larger 
one, padding is used so that the second field is aligned according to 
its size.  So a H type will be aligned to a 2byte boundary.  If you had 
two B's before it, no padding would be added.


In C, you can use a compiler switch or a pragma to override standard 
alignment.  Similarly, here you can use a prefix like "=" to override 
the native alignment rules.


DaveA


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


Re: function that counts...

2010-05-20 Thread superpollo

Richard Thomas ha scritto:

For this kind of problem you should avoid all that stringification. I
find it best to deal with sequences of digits of a fixed length and go
from there. For example:

def count1(m, n, cache={}):
"""Number of digit sequences of length `n` summing to `m`."""
if n < 0 or m < 0:
return 0
elif n == 0:
return int(m == 0)
elif (m, n) in cache:
return cache[m, n]
# This is an optimisation using the combinatoric choose function.
#elif m < 10:
#result = choose(n + m - 1, n - 1)
else:
result = 0
for digit in xrange(min(10, m + 1)):
result += count1(m - digit, n - 1)
cache[m, n] = result
return result

Notice the caching of results. With this we can compute the required
thing quite easily:

def count2(m, n):
"""Number of numbers less than `n` whose digits sum to `m`."""
result = 0
digits = map(int, str(n))
length = len(digits)
for idx, digit in enumerate(digits):
for seq_digit in xrange(digit):
seq_limit = m - seq_digit
seq_length = length - idx - 1
result += count1(seq_limit, seq_length)
m -= digit
return result

Essentially we move through the number left to right, choose digits
less than the digit in the number and count digit sequences to fill
the remainder. Then fix the actual digit and step forward.

An approach like this avoids the relatively slow stringification
process and makes decent use of caching and iteration (both easy and
efficient in Python).

In [1]: count2(25, 1)
Out[1]: 348

In [2]: timeit count2(25, 1)
10 loops, best of 3: 12.6 us per loop


wow.

impressive, thanks.

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


Re: function that counts...

2010-05-20 Thread superpollo

Steven D'Aprano ha scritto:

On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:


... how many positive integers less than n have digits that sum up to m:

In [197]: def prttn(m, n):


Does the name "prttn" mean anything? I'm afraid I keep reading it as a 
mispelling of "print n".


pArtItIOn




[...]

 s = str(i)
 sum = 0
 for j in range(len(s)):
 sum += int(s[j])


Rather than iterating over an index j = 0, 1, 2, ... and then fetching 
the jth character of the string, you can iterate over the characters 
directly. So the inner loop is better written:


for c in s:
sum += int(c)


d'oh! some day i will learn to speak pythonese!

thanks

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


Re: function that counts...

2010-05-20 Thread superpollo

Steven D'Aprano ha scritto:

On Wed, 19 May 2010 22:58:22 +0200, superpollo wrote:


In [266]: del(sum)



del is a statement, not a function, so the brackets are pointless. This 
is like writing:


x = (1)

instead of

x = 1

`del sum` is all you need.


sorry about that, thanks a lot!

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


Re: Import Module

2010-05-20 Thread Gary Herron

On 05/19/2010 09:40 AM, Harikrishnan R wrote:

Hi ,
 I have a file a.py contains

 from one.two import abc

 is there any way to find out  "one.two" the import Path of abc. ?
I don't want one.two.abc . Any function or attribute which directly
give one.two ?

-Regards

   


What's so hard about computing what you want from what your can get.

Since abc.__module__ gives gives you too much, trim it down -- perhaps 
even with os.path.splitext, although that's not what what splitext was 
meant for.


os.path.splitext(abc.__module__)[0]


Gary Herron

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


Re: Drawing glyphs based on their index (NOT their character code)

2010-05-20 Thread Christian Stapfer
"Christian Stapfer"  schrieb im Newsbeitrag 
news:b7256$4bf516e1$544ba447$20...@news.hispeed.ch...
Here's an interesting little problem: I am given a master.ttf font file 
and a subset file subset.ttf of that font, and I am asked to map indices 
of all the glyphs in subset.ttf to the corresponding indices in 
master.ttf. The subset font file is the result of a pipeline of 3 tools 
(pdflatex, Adobe Reader, and the Microsoft XPS Document Writer).




So my next best idea is to draw the various glyphs as, 16x16 B/W images, 
say, and use the 16*16 bits (that is, 16 ints or 8 longs) that result from 
this as a sufficiently precise description of the glyph to do the 
necessary comparisons.


PIL would be great for this, except for one "little" problem: I need to be 
able to draw glyphs based on their index, not based on their character 
code.


Any ideas to get around that limitation of PIL's drawing primitives?


To answer my own question: I might parse the cmap table of the ttf file, and 
then invert that mapping char->index. I think that's going to be the next 
approach that I will try.


Regards,
Christian


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


why struct.pack behave like this

2010-05-20 Thread
Hi

When I use struct to pack binary data, I found this interesting behaviour:

>>> import struct
>>> struct.pack('B', 1)
'\x01'
>>> struct.pack('H', 200)
'\xc8\x00'
>>> struct.pack('BH',1, 200)
'\x01\x00\xc8\x00'
>>> struct.calcsize('BH')
4

Why does "struct.pack('BH',1, 200)" come out with an extra "\x00"?


-- 
Luyun Xie
http://magefromhell.blogspot.com/
(http://blog.hellmage.info/)
-- 
http://mail.python.org/mailman/listinfo/python-list


Import Module

2010-05-20 Thread Harikrishnan R
Hi ,
I have a file a.py contains

from one.two import abc

is there any way to find out  "one.two" the import Path of abc. ?
I don't want one.two.abc . Any function or attribute which directly
give one.two ?

-Regards

-- 
Harikrishan R
http://harikrishnanr.wordpress.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: intervall of about 1 second for xmlrpc calls?

2010-05-20 Thread Adam Tauno Williams
On Thu, 2010-05-20 at 03:40 -0700, Thomas Lehmann wrote:
> > What's wrong?
> Obviously there's a problem with "localhost". When using the IP of my
> machine everything is working fast.

You box may first be trying to connect to ::1 (ipv6) and when that fails
it falls back to 127.0.0.1.  Make sure IPv6 is properly
configured/enabled and try the script again.
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

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


Error regarding numpy

2010-05-20 Thread sanam singh

hi,
when i import numpy i get following error

>>> import numpy
Traceback (most recent call last):
  File "/usr/lib/wingide-personal3.2/src/debug/tserver/_sandbox.py", line 1, in 

# Used internally for debug sandbox under external interpreter
  File "/usr/lib/python2.6/dist-packages/numpy/__init__.py", line 130, in 

import add_newdocs
  File "/usr/lib/python2.6/dist-packages/numpy/add_newdocs.py", line 9, in 

from lib import add_newdoc
  File "/usr/lib/python2.6/dist-packages/numpy/lib/__init__.py", line 152, in 

from type_check import *
  File "/usr/lib/python2.6/dist-packages/numpy/lib/type_check.py", line 8, in 

import numpy.core.numeric as _nx
  File "/usr/lib/python2.6/dist-packages/numpy/core/__init__.py", line 5, in 

import multiarray
ImportError: /usr/lib/python2.6/dist-packages/numpy/core/multiarray.so: 
undefined symbol: _PyUnicodeUCS4_IsWhitespace

please help me.
Cheers
  
_
Hotmail: Free, trusted and rich email service.
https://signup.live.com/signup.aspx?id=60969-- 
http://mail.python.org/mailman/listinfo/python-list


Drawing glyphs based on their index (NOT their character code)

2010-05-20 Thread Christian Stapfer
Here's an interesting little problem: I am given a master.ttf font file and 
a subset file subset.ttf of that font, and I am asked to map indices of all 
the glyphs in subset.ttf to the corresponding indices in master.ttf. The 
subset font file is the result of a pipeline of 3 tools (pdflatex, Adobe 
Reader, and the Microsoft XPS Document Writer).
 The resulting document format (XAML) holds indices into subset.ttf, and in 
order to display that document with reference to master.ttf, I need to do 
this mapping of indices: subset -> master.
(Carrying subset.ttf along with the XAML code is not an option, I think, 
because I need to be able to support copy and paste of small snippets from 
that document through a shared whiteboard.)


I have tried to parse the two font files to the point of having the x- and 
y-coordinate points of the outlines of glyphs handy. But, unfortunately, 
subset.ttf has been processed in a way that makes it very difficult to 
compare its glyph outlines with the outlines of glyphs in master.ttf.


So my next best idea is to draw the various glyphs as, 16x16 B/W images, 
say, and use the 16*16 bits (that is, 16 ints or 8 longs) that result from 
this as a sufficiently precise description of the glyph to do the necessary 
comparisons.


PIL would be great for this, except for one "little" problem: I need to be 
able to draw glyphs based on their index, not based on their character code.


Any ideas to get around that limitation of PIL's drawing primitives?

Thanks in advance,
Christian 


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


Re: Problem with an huge dictionary

2010-05-20 Thread Thomas Lehmann
>
> The question is:
> Is there a limit on the number of entries a dictionary can have i
> jython?
>
> I wrote a little app where my data is stored in a huge dictionary
> (11746 entries) generated with a python script.
> When I try to import the dictionary, jython complains with the
> following message:
>

1) You did not say what you have saved (content of your dictionary).
2) You did not say how you have saved.

>From the callstack - also I have never used jython - it looks like
that
there is a try to create a class. It looks like - I may be wrong -
that
you have saved user objects in your dictionary - have you?

If so you might fail on loading those objects - especially when your
program
does not have the code for it.

More details are required...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: intervall of about 1 second for xmlrpc calls?

2010-05-20 Thread Thomas Lehmann
> What's wrong?
>

Obviously there's a problem with "localhost". When using the IP of my
machine everything is working fast.
-- 
http://mail.python.org/mailman/listinfo/python-list


Transferring an exception from one thread to an other.

2010-05-20 Thread Antoon Pardon
I have a numver of tarfiles on a remote host that I need to process and
that I fetch via FTP. I wrote the following as a test to see how I would
best approach this. (I'm using python 2.5)

 ftptst1 
import tarfile as tar
from ftplib import FTP, error_perm as FTPError, error_temp as FTPProblem
from socket import error as SocketError

ftp = FTP(host, user, password)

def gettarfile(rfn):
  import tempfile
  tfl = tempfile.TemporaryFile()
  ftp.retrbinary("RETR %s" % (rfn,), tfl.write)
  tfl.seek(0)
  return tar.open(mode = "r:bz2", fileobj = tfl)
  
def process():
  for rfn in ("testfile.tbz", "nosuchfile"):
try:
  tf = gettarfile(rfn)
  for tarinfo in tf:
print tarinfo.name
  print 
except Exception:
  print "Something went wrong with '%s'" % rfn

process()
-

Executing this gives me this result:

testfile/
testfile/tstfl.0

Something went wrong with 'nosuchfile'


However the tarfile can be to big to store localy. That is why I rewrote
the above as follows:

 ftptst2 
import tarfile as tar
from ftplib import FTP, error_perm as FTPError, error_temp as FTPProblem
from socket import error as SocketError

ftp = FTP("nestor", "apardon", "0nZM,F!m")

def connect(lfl, rfn):
  ftp.retrbinary("RETR %s" % (rfn,), lfl.write)
  lfl.close()
  
def gettarfile(rfn):
  import os, threading
  rfd, wfd = os.pipe()
  wfl = os.fdopen(wfd, "w")
  rfl = os.fdopen(rfd, "r")
  xfer = threading.Thread(target = connect, args = (wfl, rfn))
  xfer.setDaemon(True)
  xfer.start()
  return tar.open(mode = "r|bz2", fileobj = rfl)
  
def process():
  for rfn in ("testfile.tbz", "nosuchfile"):
try:
  tf = gettarfile(rfn)
  for tarinfo in tf:
print tarinfo.name
  print 
except Exception:
  print "Something went wrong with '%s'" % rfn

process()
-

Executing this new test gives this result:

testfile/
testfile/tstfl.0

Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner
self.run()
  File "/usr/lib/python2.5/threading.py", line 446, in run
self.__target(*self.__args, **self.__kwargs)
  File "ftptst2", line 10, in connect
ftp.retrbinary("RETR %s" % (rfn,), lfl.write)
  File "/usr/lib/python2.5/ftplib.py", line 390, in retrbinary
conn = self.transfercmd(cmd, rest)
  File "/usr/lib/python2.5/ftplib.py", line 356, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
  File "/usr/lib/python2.5/ftplib.py", line 327, in ntransfercmd
resp = self.sendcmd(cmd)
  File "/usr/lib/python2.5/ftplib.py", line 241, in sendcmd
return self.getresp()
  File "/usr/lib/python2.5/ftplib.py", line 216, in getresp
raise error_perm, resp
error_perm: 550 nosuchfile: No such file or directory.


Now I totally understand what is happening. What is less clear is how
best to fix ftptst2, so that it behaves like ftptst1 in case of ftp
problems. I know about the PyThreadState_SetAsyncExc function; would
this be an acceptable solution here by catching the excption in the
xfer/connect thread and raising them in the main thread? Is there
an other possibility of combining ftplib and tarfile, that doesn't
need threads but also doesn't need to store the remote file locally?

Any other suggestion?

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


intervall of about 1 second for xmlrpc calls?

2010-05-20 Thread Thomas Lehmann
Hi,

I'm wondering about the behavior. Running this example - it looks like
- that each rpc call is triggered in a visible interval (about one
second).

What's wrong?

Thomas

APPENDIX:


import threading
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client

class MyServer(threading.Thread):
def __init__(self, host, port):
threading.Thread.__init__(self)
self.server = SimpleXMLRPCServer((host, port))
self.server.register_function(self.is_even, "is_even")
self.server.register_function(self.stop, "stop_server")

def run(self):
print("server: waiting for requests...")
self.server.serve_forever()
print("server: is down.")

def stop(self):
print("server: shutdown requested...")
self.stoptimer = threading.Timer(1, self.server.shutdown)
self.stoptimer.start()
return "done."

def is_even(self, n):
print("server: check %d to be even" % (n))
return n%2 == 0


# server as thread
server = MyServer("localhost", 1234)
server.start()

# client code
serverProxy = xmlrpc.client.ServerProxy("http://localhost:1234";)
for n in range(1,2+1):
print("%d is %s" % (n, ["odd", "even"][serverProxy.is_even(n)]))
serverProxy.stop_server()

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


Re: Reading data from a Microsoft Access 2003 database

2010-05-20 Thread Jimoid
I've now had a closer look at both pyODBC and mxODBC and it seems to
me that they both require the database to be running to be able to
query it. Is this correct? If so I think I will have to use mdb-* as
the database I want to query is not running.

Cheers,

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


250

2010-05-20 Thread Martin P. Hellwig

On 05/20/10 07:51, cosmeticsafrolatino wrote:

hi
250 locahost.local Hello WimaxUser3645-219.wateen.net [110.36.45.219], 
pleased to meet you

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


Re: Reading data from a Microsoft Access 2003 database

2010-05-20 Thread Jimoid
Thanks to all for your helpful suggestions.

So far I have installed and played around with mdbtools, and it
appears that I can use this from the shell to extract the information
I need, e.g. mdb-export for dumping an entire table or mdb-sql to run
a query. I am also interested by mxODBC and pyodbc as these seem to be
python only solutions, so could be useful for platform independent
python solutions (it may be that my programme will be used by some
Windows users, if it is successful).

To give it a bit of context, I am extracting data from the on-board
flight planning software from an aerial survey plane (the Access
database). I will extract the GPS data for each image taken so that I
can then georeference the images.

Cheers,

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