Solutions for finding the 1000th prime

2010-05-21 Thread Neal
I'm doing the MIT OpenCourseWare class that this assignment hails from
and I don't doubt that its a relatively common assignment. Upon
searching for it for some ideas of why my program wouldn't work one of
the top results is this a thread from this group full of derision and
sarcasm. Believe me I understand that the people here don't want to do
another person's homework but for someone who isn't going to be coding
for a living or is a hobbyist like I am, there could be some useful
information. Eventually I figured out what I was doing wrong, and I
was hoping to add some insight. At this point in the lectures about
all we've learned to deal with as far as commands are: while, if,
else, elif and some boolean operators.

I started defining three variables I would need:
 One to count how many primes I have
 Which number I'm currently checking to be a prime
 Current number I'm dividing by as my checker

The assignment states that its easiest to check all odd integers > 1
but not to forget that 2 is a prime, easiest probably just to start
your counter at 1, I didn't but it took an extra 3 lines just to get
my counter to 1, and then get to the next number I'm checking all
without being in a usable loop.

You start your loop with the stated condition, no need for it to run
any more past counting the 1000th prime.

You could have your program check to see if a number is divisible by
every number less than itself and if so moving on to your next number.
However you do know that any number isn't going to be divisible by
another number in that sequence until it reaches itself divided by 2.
If you keep in mind though that we are only dealing with odd numbers,
you know that they will not be divisible by two, so instead we can
move on to itself divided by 3.

Every iteration of the loop when it finds a prime, needs to increase
the count, move onto the next candidate you're checking, and redefine
the divisor you're starting to check next time around. If a number is
determined not to be a prime you need to move onto the next candidate
and redefine your divisor (which is where I was stuck for a long time
writing this program). If your not sure that the number is a prime or
not a prime you simply need to redefine the divisor and continue the
loop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional argument to a subclass of a class

2010-05-21 Thread Steven D'Aprano
On Thu, 20 May 2010 23:35:01 -0400, Alex Hall wrote:

>> 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?

No, the opposite in fact.

One of the basic features of objects (at least as implemented by Python, 
and many other languages) is inheritance. That is, a class inherits 
behaviour and state (methods and attributes) from its parent class (or 
classes).

So if you have a class A and a subclass B, B inherits behaviour from A:

>>> class A:
... def method(self):
... print("method in A")
...
>>> class B(A):
... pass
... 
>>> b = B()
>>> b.method()
method in A


But if you override method, then Python doesn't *automatically* call the 
parent's method. How can it know where to call it, and what to do with 
the result? Should it call it before the new method, or after, or 
somewhere in the middle? It's impossible to tell. 


>>> class C(A):
... def method(self):
... print("called from C")
...
>>> c = C()
>>> c.method()
called from C


If you want both behaviours, then you have to explicitly call the parent 
class, and pass the current instance as an argument:

>>> class D(A):
... def method(self):
... print("called from D")
... A.method(self)
...
>>> d = D()
>>> d.method()
called from D
method in A



Exactly the same rules apply to __init__, with the added complication 
that frequently you want to modify the function signature:


>>> class Sandwich:
... def __init__(self, filling, bread='white'):
... self.filling = filling
... self.bread = bread
... def __str__(self):
... return ("%s on two slices of %s bread" % 
... (self.filling, self.bread))
...
>>> s = Sandwich("cheese", "rye")
>>> print(s)
cheese on two slices of rye bread
>>>
>>> class BLT(Sandwich):
... def __init__(self):
... Sandwich.__init__(self, "bacon, lettuce and tomato", 
... "sour dough")
...
>>> b = BLT()
>>> print(b)
bacon, lettuce and tomato on two slices of sour dough bread



Hope this helps.


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


Re: optional argument to a subclass of a class

2010-05-21 Thread Peter Otten
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.

You have to repeat the arguments for the base class in the Battleship 
initializer. Battleship(...) will only invoke Battleship.__init__(...), not 
Craft.__init__(...) -- so you have to do that explicitly inside 
Battleship.__init__() while passing along all parameters it is supposed to 
process. As simplified example:

class Craft(object):
def __init__(self, name, id=None, weapons=None):
if id is None: 
id = helpers.id()
if weapons is None:
weapons = []
self.name = name
self.id = id
self.weapons = weapons

class Battleship(Craft):
def __init__(self, name, id=None, weapons=None, max_hits=None):
Craft.__init__(self, name, id, weapons)
self.max_hits = max_hits

Notice how using None to signal that a value was not provided simplifies 
things; without it you'd have to put a meanigful default for weapons into 
both the Craft and Battleship class. If you want a unique id for every Craft 
providing helpers.id() as a default is just wrong; default arguments are 
calculated once and you would end up with the same id for every Craft 
instance.

Peter

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


Re: socket.getsockopt() and SO_ORIGINAL_DST

2010-05-21 Thread chris
Hi guys,

I found a solution myself in O'Reilly's Security Power Tools. It works
seamlessly as follows:


from socket import *
SO_ORIGINAL_DST = 80
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('192.168.255.254', 80))
s.listen(1)
conn, addr = s.accept()

dst = conn.getsockopt(SOL_IP, SO_ORIGINAL_DST, 16)
srv_port, srv_ip = struct.unpack("!2xH4s8x", dst)
print "original %s:%d" % (inet_ntoa(srv_ip), srv_port)


Basically, my fault was not specifying the buffer length :(

Have fun with it, whoever needs it.

Regards,
Chris


chris wrote:
> 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


Re: Solutions for finding the 1000th prime

2010-05-21 Thread Peter Otten
Neal wrote:

> I'm doing the MIT OpenCourseWare class that this assignment hails from
> and I don't doubt that its a relatively common assignment. Upon
> searching for it for some ideas of why my program wouldn't work one of
> the top results is this a thread from this group full of derision and
> sarcasm. Believe me I understand that the people here don't want to do
> another person's homework but for someone who isn't going to be coding
> for a living or is a hobbyist like I am, there could be some useful
> information. Eventually I figured out what I was doing wrong, and I
> was hoping to add some insight. At this point in the lectures about
> all we've learned to deal with as far as commands are: while, if,
> else, elif and some boolean operators.

I'd like to bring your attention to my contribution to the above-mentioned 
thread.

http://mail.python.org/pipermail/python-list/2009-November/1226626.html

I posted it late in the thread's life because like you I disliked the 
direction the "discussion" was taking.

My answer is not so much about an efficient solution to the actual problem, 
but more about how to approach a programming problem that initially seems to 
be over your head.

As a long time reader I can confirm that if you show that you have made a 
minimum effort to solve even "homeworky" problems you usually get 
constructive hints on comp.lang.python. There is also a mailing list

http://mail.python.org/mailman/listinfo/tutor

for the absolute beginner.

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


Re: intervall of about 1 second for xmlrpc calls?

2010-05-21 Thread rav
I had similar problem with SimpleXMLRPCServer
Create the request handler class

class ExtendedXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
# originally this one was slowing down my server A LOT due to DNS
settings!!!
def log_request(self, *args):
pass

and put it in your SimpleXMLRPCServer constructor

(...)

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

(...)

I would also change all 'localhost' occurences in the code to ip
'127.0.0.1'.

Good luck!
Rafal
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI python 3 write RAW BINARY

2010-05-21 Thread sam
On May 7, 7:33 am, Dodo  wrote:
> Le 01/05/2010 12:52, Dodo a écrit :
>
>
>
>
>
> > Le 30/04/2010 17:52, Antoine Pitrou a écrit :
> >> Le Thu, 29 Apr 2010 23:37:32 +0200, Dodo a écrit :
> >>> I don't get a thing.
> >>> Now with the fix :
> >>> All browsers shows a different thing, but not the image!
> >>>http://ddclermont.homeip.net/misc/python/
>
> >>> If I save it to computer :
> >>> * Windows image viewer won't read it
> >>> * Irfanview can read it without problems
>
> >> Did you set the content-type and content-length in the HTTP headers?
> >> Can you post your code?
>
> > I didn't know about content-lenght
> > Here's the new code (I used a fixed image patch to make sure this is not
> > the source of the problem)
>
> > #!/usr/bin/python3
> > import cgi, sys, cgitb
> > cgitb.enable()
>
> > f = open("/home/dodo/54.jpg", "rb")
> > data = f.read()
> > l = len(data)
> > f.close()
>
> > print("Content-type:image/jpg\nContent-length:%d\n\n" % l)
>
> > sys.stdout.flush()
> > sys.stdout.buffer.write( data )
>
> > Dorian
>
> Anyone?

Yes for windows you need to call this before you write it out.  And
yes its totally retarded that you have to do this.  The whole point of
python is that I don't have to worry about the particular system its
running on.

 def __SetStdOutForWindowsToBinaryMode():
# Without this method a windows server will translate '\n'
into '\r\n'
# even for binary output.  This probably isn't needed on linux
servers
# so the exception will be caught harmlessly.
# At some point we may have to worry about switching this mode
*back* to original
# (see 
http://bytes.com/topic/python/answers/30987-cgi-proplem-displaying-image)
try:
import msvcrt,os
msvcrt.setmode( 1, os.O_BINARY ) # 1 = stdout; use 0 for
stdin
except ImportError:
pass


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


Re: client server console app with cmd library

2010-05-21 Thread kak...@gmail.com
On May 20, 1:54 am, "kak...@gmail.com"  wrote:
> Hi to all,
> i need some hints about a console application i' m trying.
> I want to make it act as a client and as a server at a same time.
> And since it is a console application i' m using cmd library.
> I want something that works like asterisk. while working with my app
> i want to listen for incoming requests, that they appear automatically
> at my console.
> Any design considerations?
> Do i have to use threads?
> Please i want your advice.
> Any examples somewhere?
>
> Thanks in advance!
> Antonis

Hi again. I wonder is my question stupid, or what i want can't be
done?
-- 
http://mail.python.org/mailman/listinfo/python-list


where are the program that are written in python?

2010-05-21 Thread Deep_Feelings
python is not a new programming language ,it has been there for the
last  15+ years or so ? right ?

however by having a look at this page http://wiki.python.org/moin/Applications
i could not see many programs written in python (i will be interested
more in COMMERCIAL programs written in python ). and to be honest ,i
tried some of the programs in that list and all the programs that i
tried either dead projects or so buggy !

1- where are the programs that is written in python ?
2- python is high productivity language : why there are no commercial
programs written in python ?

is python a valid practical programming language ?
why it is not used in commercial software ?

please don't mention programs where python was used as a glue ,those
programs are not actually written in python.

any help will be appreciated

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


Re: where are the program that are written in python?

2010-05-21 Thread Simon Brunning
On 21 May 2010 11:21:11 UTC+1, Deep_Feelings  wrote:
> 1- where are the programs that is written in python ?
> 2- python is high productivity language : why there are no commercial
> programs written in python ?

See http://www.python.org/about/success/

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


Re: where are the program that are written in python?

2010-05-21 Thread Martin P. Hellwig

On 05/21/10 11:21, Deep_Feelings wrote:

python is not a new programming language ,it has been there for the
last  15+ years or so ? right ?

Yeah about the same as Java


however by having a look at this page http://wiki.python.org/moin/Applications
i could not see many programs written in python (i will be interested
more in COMMERCIAL programs written in python ). and to be honest ,i
tried some of the programs in that list and all the programs that i
tried either dead projects or so buggy !
It's a wiki, if anybody is interested they could change the page, I 
actually have never looked at it.


1- where are the programs that is written in python ?
2- python is high productivity language : why there are no commercial
programs written in python ?

is python a valid practical programming language ?
why it is not used in commercial software ?
My experience is that Python is the FreeBSD of the programming 
languages. For example, the average user knows mac and windows, the 
average admin knows there is also something like linux, and the average 
linux admin knows there is also something like BSD.


please don't mention programs where python was used as a glue ,those
programs are not actually written in python.
Python is used in a lot in custom applications, while off the shelve 
software needs a lot of buzzwords to shift any market interest.
I have participated in a couple of 'pure' Python programs, used by 
Airbus, Randstad and a whole fleet of small firms. But yes, off the 
shelve software seems to be either written in Java or any .net equivalent.


any help will be appreciated

thank you


hth
--
mph

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


Re: where are the program that are written in python?

2010-05-21 Thread Jake b
did this not go to the list? Arg, reply does in other mailing list.

On Fri, May 21, 2010 at 5:48 AM, Jake b  wrote:

> I took it as game-domain only question:
> I don't know of any big game written in python. ( meaning python code,
> using c++ libs. ) Verses games that at their is in c++ , calling a scripting
> language under the hood.
> Even if a game is written at its base in python, it still uses python
> libraries which can use c++ under the hood.
>
> WoW had a huge amount of logic, in LUA combined with xml. Was cool seeing
> the crazy things implemented.
>
> There are a lot that use a c++ engine, with a scripting engine under the
> hood. python, lua, unrealscript, etc... Civ4 uses python for map generation.
> Not sure how much else?
> Wouldn't be surprised, alpha centauria even had text files you could mod
> the game with.
>
> Unreal games: U, UT, UT2k4, etc.. (since before UT original, use
> scripting(unreal script) to control basically everything.) There are
> classes, and methods that 'do the work' in c++ for speed.
>
> From development point, You're on a deadline, if your company all know the
> existing language/engine/api, there isn't much incentive to learn a new api,
> and convert existing code, and not having all the previous examples, and
> api's. [ That can even mean using game engine X, even if Y is in the same
> language, and is technically better. ]
>
>
> --
> Jake
>



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


Re: client server console app with cmd library

2010-05-21 Thread Jake b
Networking can be hard. I'd suggest checking out these libs.

pygame mastermind:
http://www.pygame.org/project-Mastermind+Networking+Lib-859-1773.html
podSixNet : http://mccormick.cx/projects/PodSixNet/
twisted: http://wiki.python.org/moin/Twisted-Examples
lots of references in the  answers to this StackOverflow post:
http://stackoverflow.com/questions/78704/good-python-network-programing-resource

Twisted is the hardest in that list to get into.
-- 
Jake
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] oStri: Cython optimized String object

2010-05-21 Thread Stefan Behnel

Mike 'Fuzzy' Partin, 21.05.2010 08:37:

Optimized String-like Object is kind of a misnomer in that, the object
provided is a subclass of the base str type, adding optimized (Cython
bindings to the standard (POSIX) libc regex and string functions)
match() and sub() methods.


Hi,

could you give an idea what the advantage of this package is? Why would one 
want to use it?


Also, while the main class is a subclass of str, it doesn't take advantage 
of that fact at all.


Stefan

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


Re: where are the program that are written in python?

2010-05-21 Thread Deep_Feelings
On May 21, 1:35 pm, Simon Brunning  wrote:
> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings  wrote:
>
> Seehttp://www.python.org/about/success/

thankx for reply.

from that list i have a feeling that python is acting only as "quick
and dirty work" nothing more !
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where are the program that are written in python?

2010-05-21 Thread News123
Deep_Feelings wrote:
> On May 21, 1:35 pm, Simon Brunning  wrote:
>> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings  wrote:
>>
>> Seehttp://www.python.org/about/success/
> 
> thankx for reply.
> 
> from that list i have a feeling that python is acting only as "quick
> and dirty work" nothing more !
Too bad, that still nobody feels insulted isn't it?
-- 
http://mail.python.org/mailman/listinfo/python-list


unique values of a Dictionary list (removing duplicate elements of a list)

2010-05-21 Thread Chad Kellerman
Python users,
  I am parsing an AIX trace file and creating a dictionary containing
keys (PIDS) and values (a list of TIDS).  With PIDS being unique process ids
and TIDS, being a list of thread ids.  My function populates the keys so
that they are unique, but my list contains duplicates.

 Can someone point me in the right direction so that my dictionary value
does not contain duplicate elements?


here is what I got.



pidtids  = {}

# --- function to add pid and tid to a dictionary
def addpidtids(pid,tid):
pidtids.setdefault(pid,[]).append(tid)

# --- function to parse a file
def grep(pattern, fileObj, include_line_nums=False):
r=[]
compgrep = re.compile(pattern)

for line_num, line in enumerate(fileObj):
if compgrep.search(line):
info = line.split()
p = info[7].lstrip("pid=")
t = info[8].lstrip("tid=")
addpidtids(p,t)


# process trace.int
tf = open(tracefile, 'r')
grep("cmd=java pid",tf)
tf.close()



Any help would be greatly appreciated.


Thanks,
Chad

-- 
A grasshopper walks into a bar and the bartender says "Hey, we have a drink
named after you." And the grasshopper says "Really, You have a drink named
Murray?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where are the program that are written in python?

2010-05-21 Thread Xavier Ho
On Fri, May 21, 2010 at 9:12 PM, Deep_Feelings  wrote:

> thankx for reply.
>
> from that list i have a feeling that python is acting only as "quick
> and dirty work" nothing more !
>

 You might have just offended a lot of people on the list here

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


Re: where are the program that are written in python?

2010-05-21 Thread Simon Brunning
On 21 May 2010 12:12:18 UTC+1, Deep_Feelings  wrote:
> from that list i have a feeling that python is acting only as "quick
> and dirty work" nothing more !

Really?

Well, in any case, I can tell you that I know of a number of large
commercial web sites built with Django. I just can't tell you what
they are. ;-)

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


Re: where are the program that are written in python?

2010-05-21 Thread Wolfgang Rohdewald
On Freitag 21 Mai 2010, Jake b wrote:
> > I don't know of any big game written in python. ( meaning
> > python code, using c++ libs

would you call 8702 python statements big? If so,
Kajongg would be a candidate.

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


Re: unique values of a Dictionary list (removing duplicate elements of a list)

2010-05-21 Thread Peter Otten
Chad Kellerman wrote:

> Python users,
>   I am parsing an AIX trace file and creating a dictionary containing
> keys (PIDS) and values (a list of TIDS).  With PIDS being unique process
> ids
> and TIDS, being a list of thread ids.  My function populates the keys so
> that they are unique, but my list contains duplicates.
> 
>  Can someone point me in the right direction so that my dictionary
>  value
> does not contain duplicate elements?
> 
> 
> here is what I got.
> 
> 
> 
> pidtids  = {}
> 
> # --- function to add pid and tid to a dictionary
> def addpidtids(pid,tid):
> pidtids.setdefault(pid,[]).append(tid)

Use a set instead of a list (and maybe a defaultdict):

from collections import defaultdict

pidtids = defaultdict(set)

def addpidtids(pid, tid):
pidtids[pid].add(tid)

Peter

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


Re: unique values of a Dictionary list (removing duplicate elements of a list)

2010-05-21 Thread Chad Kellerman
On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__pete...@web.de> wrote:

> Chad Kellerman wrote:
>
> > Python users,
> >   I am parsing an AIX trace file and creating a dictionary containing
> > keys (PIDS) and values (a list of TIDS).  With PIDS being unique process
> > ids
> > and TIDS, being a list of thread ids.  My function populates the keys so
> > that they are unique, but my list contains duplicates.
> >
> >  Can someone point me in the right direction so that my dictionary
> >  value
> > does not contain duplicate elements?
> >
> >
> > here is what I got.
> >
> > 
> >
> > pidtids  = {}
> >
> > # --- function to add pid and tid to a dictionary
> > def addpidtids(pid,tid):
> > pidtids.setdefault(pid,[]).append(tid)
>
> Use a set instead of a list (and maybe a defaultdict):
>
> from collections import defaultdict
>
> pidtids = defaultdict(set)
>
> def addpidtids(pid, tid):
>pidtids[pid].add(tid)
>
> Peter
>

Thanks.  I guess I should have posted this in my original question.

I'm on 2.4.3  looks like defautldict is new in 2.5.

I'll see if I can upgrade.

Thanks again.



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



-- 
A grasshopper walks into a bar and the bartender says "Hey, we have a drink
named after you." And the grasshopper says "Really, You have a drink named
Murray?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional argument to a subclass of a class

2010-05-21 Thread Alex Hall
On 5/21/10, Peter Otten <__pete...@web.de> wrote:
> 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.
>
> You have to repeat the arguments for the base class in the Battleship
> initializer. Battleship(...) will only invoke Battleship.__init__(...), not
> Craft.__init__(...) -- so you have to do that explicitly inside
> Battleship.__init__() while passing along all parameters it is supposed to
> process. As simplified example:
>
> class Craft(object):
> def __init__(self, name, id=None, weapons=None):
> if id is None:
> id = helpers.id()
> if weapons is None:
> weapons = []
> self.name = name
> self.id = id
> self.weapons = weapons
>
> class Battleship(Craft):
> def __init__(self, name, id=None, weapons=None, max_hits=None):
> Craft.__init__(self, name, id, weapons)
> self.max_hits = max_hits
>
> Notice how using None to signal that a value was not provided simplifies
> things; without it you'd have to put a meanigful default for weapons into
> both the Craft and Battleship class. If you want a unique id for every Craft
> providing helpers.id() as a default is just wrong; default arguments are
> calculated once and you would end up with the same id for every Craft
> instance.
Yes, I found that out the hard way :), but it made perfect sense as
soon as I realized that I was not getting unique IDs; the class()
statement is just a fancy function call in Python, as I understand it,
so of course it would be called only once, not each time I make a new
instance.
>
> Peter
>
> --
> 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: intervall of about 1 second for xmlrpc calls?

2010-05-21 Thread Adam Tauno Williams
On Fri, 2010-05-21 at 02:10 -0700, rav wrote:
> I had similar problem with SimpleXMLRPCServer
> Create the request handler class
> class ExtendedXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
> # originally this one was slowing down my server A LOT due to DNS
> settings!!!
> def log_request(self, *args):
> pass
> and put it in your SimpleXMLRPCServer constructor
> (...)
> class MyServer(threading.Thread):
> def __init__(self, host, port):
> threading.Thread.__init__(self)
> self.server = SimpleXMLRPCServer((host, port),
> ExtendedXMLRPCRequestHandler)
> self.server.register_function(self.is_even, "is_even")
> self.server.register_function(self.stop, "stop_server")
> (...)
> I would also change all 'localhost' occurences in the code to ip
> '127.0.0.1'.

Or the better solution is to fix your resolver.
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

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


Re: where are the program that are written in python?

2010-05-21 Thread Adam Tauno Williams
On Fri, 2010-05-21 at 11:37 +0100, Martin P. Hellwig wrote:
> On 05/21/10 11:21, Deep_Feelings wrote:
> > however by having a look at this page 
> > http://wiki.python.org/moin/Applications
> > i could not see many programs written in python (i will be interested
> > more in COMMERCIAL programs written in python ). and to be honest ,i
> > tried some of the programs in that list and all the programs that i
> > tried either dead projects or so buggy !

Most projects are dead projects; that is just the natural state of
things regardless of language.  Just browse Sourceforge for awhile.

> It's a wiki, if anybody is interested they could change the page, I 
> actually have never looked at it.

I've looked it over, there is some interesting stuff.  But why
contribute a story when you could be coding on your project!  A
perennial problem. :)

> > 1- where are the programs that is written in python ?
> > 2- python is high productivity language : why there are no commercial
> > programs written in python ?
> > is python a valid practical programming language ?
> > why it is not used in commercial software ?

I suppose it depends on your use of the term "used".  It is used a *lot*
in the SOA / Workflow world - in the form of Jython.  That provides a
very nice way to extend Java applications [it is still Python!  Python
is a language, not a runtime].

In general to 'core' of large applications are, IMO, easier to maintain
in the more rigid statically typed languages as the toolchain can do
more work for you.  Of course someone here will have a fit about that
statement.

> > please don't mention programs where python was used as a glue

Why not?

And what about Gwibber? Zeitgeist? BitTorrent? Zope/Plone?  Those are
all certainly "real" applications.  Zope is almost an industry unto
itself.

>  ,those programs are not actually written in python.

I think your distinction is not valid.  "glue" is a vital part of every
enterprise.  And the sophistication of some "glue" certainly surpasses
many "applications".

> Python is used in a lot in custom applications, while off the shelve 
> software needs a lot of buzzwords to shift any market interest.
> I have participated in a couple of 'pure' Python programs, used by 
> Airbus, Randstad and a whole fleet of small firms. But yes, off the 
> shelve software seems to be either written in Java or any .net equivalent.

 is an 
interesting read.  Certainly the 'packaging' mechanism is less end-user 
friendly than .NET.  I personally would not choose to create an end-user 
application in Python; but it has become my first choice for server-side 
development.

-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

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


Re: Reading data from a Microsoft Access 2003 database

2010-05-21 Thread Adam Tauno Williams
On Thu, 2010-05-20 at 22:58 -0700, Dennis Lee Bieber wrote:
> On Thu, 20 May 2010 02:45:10 -0700 (PDT), Jimoid
>  declaimed the following in
> gmane.comp.python.general:
> > 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.
> To my knowledge, all "ODBC" modules (in any language) rely upon a
> DBMS specific driver.

Correct (of course, so does DB-API if you are using a 'native' Python
connection).

>  Where the DB-API definition defines the common
> Python side of a database interface, ODBC defines a common OS-level
> interface to the DBMS, using a named driver (driver specified in the
> connection string or, for Windows, externally with the connection string
> specifying the connection definition) 

There is no distinction between how ODBC operates on Windows or LINUX.
Both use the same connection strings [provided the drivers have the same
names].

> to translate ODBC calls into actual DBMS calls.

Yes, just like a DB-API provider, except that the 'translation' happens
in the ODBC driver.
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

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


Re: unique values of a Dictionary list (removing duplicate elements of a list)

2010-05-21 Thread Chad Kellerman
On Fri, May 21, 2010 at 8:07 AM, Chad Kellerman  wrote:

>
>
> On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__pete...@web.de> wrote:
>
>> Chad Kellerman wrote:
>>
>> > Python users,
>> >   I am parsing an AIX trace file and creating a dictionary
>> containing
>> > keys (PIDS) and values (a list of TIDS).  With PIDS being unique process
>> > ids
>> > and TIDS, being a list of thread ids.  My function populates the keys so
>> > that they are unique, but my list contains duplicates.
>> >
>> >  Can someone point me in the right direction so that my dictionary
>> >  value
>> > does not contain duplicate elements?
>> >
>> >
>> > here is what I got.
>> >
>> > 
>> >
>> > pidtids  = {}
>> >
>> > # --- function to add pid and tid to a dictionary
>> > def addpidtids(pid,tid):
>> > pidtids.setdefault(pid,[]).append(tid)
>>
>> Use a set instead of a list (and maybe a defaultdict):
>>
>> from collections import defaultdict
>>
>> pidtids = defaultdict(set)
>>
>> def addpidtids(pid, tid):
>>pidtids[pid].add(tid)
>>
>> Peter
>>
>
> Thanks.  I guess I should have posted this in my original question.
>
> I'm on 2.4.3  looks like defautldict is new in 2.5.
>
> I'll see if I can upgrade.
>
> Thanks again.
>


 instead of upgrading.. (probably be faster to use techniques in available
2.4.3)

Couldn't I check to see if the pid exists (has_key I believe) and then check
if the tid is a value, in the the list for that key, prior to passing it to
the function?

Or would that be too 'expensive'?


>
>
>
>>
>> --
>>
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> A grasshopper walks into a bar and the bartender says "Hey, we have a drink
> named after you." And the grasshopper says "Really, You have a drink named
> Murray?"
>



-- 
A grasshopper walks into a bar and the bartender says "Hey, we have a drink
named after you." And the grasshopper says "Really, You have a drink named
Murray?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unique values of a Dictionary list (removing duplicate elements of a list)

2010-05-21 Thread Peter Otten
Chad Kellerman wrote:

> On Fri, May 21, 2010 at 8:07 AM, Chad Kellerman 
> wrote:
> 
>>
>>
>> On Fri, May 21, 2010 at 7:50 AM, Peter Otten <__pete...@web.de> wrote:
>>
>>> Chad Kellerman wrote:
>>>
>>> > Python users,
>>> >   I am parsing an AIX trace file and creating a dictionary
>>> containing
>>> > keys (PIDS) and values (a list of TIDS).  With PIDS being unique
>>> > process ids
>>> > and TIDS, being a list of thread ids.  My function populates the keys
>>> > so that they are unique, but my list contains duplicates.
>>> >
>>> >  Can someone point me in the right direction so that my dictionary
>>> >  value
>>> > does not contain duplicate elements?
>>> >
>>> >
>>> > here is what I got.
>>> >
>>> > 
>>> >
>>> > pidtids  = {}
>>> >
>>> > # --- function to add pid and tid to a dictionary
>>> > def addpidtids(pid,tid):
>>> > pidtids.setdefault(pid,[]).append(tid)
>>>
>>> Use a set instead of a list (and maybe a defaultdict):
>>>
>>> from collections import defaultdict
>>>
>>> pidtids = defaultdict(set)
>>>
>>> def addpidtids(pid, tid):
>>>pidtids[pid].add(tid)
>>>
>>> Peter
>>>
>>
>> Thanks.  I guess I should have posted this in my original question.
>>
>> I'm on 2.4.3  looks like defautldict is new in 2.5.
>>
>> I'll see if I can upgrade.
>>
>> Thanks again.
>>
> 
> 
>  instead of upgrading.. (probably be faster to use techniques in available
> 2.4.3)
> 
> Couldn't I check to see if the pid exists (has_key I believe) and then
> check if the tid is a value, in the the list for that key, prior to
> passing it to the function?
> 
> Or would that be too 'expensive'?

No.

pidtids = {}
def addpidtids(pid, tid):
if pid in pidtids:
pidtids[pid].add(tid)
else:
pidtids[pid] = set((tid,))

should be faster than

def addpidtids(pid, tid):
pidtids.setdefault(pid, set()).add(tid)

and both should work in python2.4.

Peter

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


Another "Go is Python-like" article.

2010-05-21 Thread Grant Edwards
In a recent Reg article, there's yet more yammering on about how Go is
somehow akin to Python -- referring to Go as a "Python-C++" crossbreed.

http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/

I still don't get it.

What about Go, exactly, do people see as Phython-like?

Go doesn't seem to have any of the salient features (either syntactic
or semantic) of Python other than garbage collection.

How is Go not just warmed-over Java?

-- 
Grant Edwards   grant.b.edwardsYow! RELATIVES!!
  at   
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another "Go is Python-like" article.

2010-05-21 Thread David Cournapeau
On Fri, May 21, 2010 at 11:20 PM, Grant Edwards  wrote:
> In a recent Reg article, there's yet more yammering on about how Go is
> somehow akin to Python -- referring to Go as a "Python-C++" crossbreed.
>
> http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/
>
> I still don't get it.
>
> What about Go, exactly, do people see as Phython-like?

I guess the type system without a strict hierarchy, as well as very
fast compilation enabling fast iteration. Granted, a lot of languages
have those features nowadays, and I doubt anyone would speaks about it
if it was not where it was coming from. The fact that google feels the
need to create a new system programming language is maybe the most
interesting fact of it ?

cheers,

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


Re: function that counts...

2010-05-21 Thread Albert van der Horst
In article ,
Grant Edwards   wrote:
>
>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.

16 bit mini computers were popular: the pdp11.
Now 3 FORTRAN char's fitted in one word (radix 40).
At least it helped to shoe horn identifier names into two words.

>
>--
>Grant Edwards   grant.b.edwardsYow! Hand me a pair of
>  at   leather pants and a CASIO
>  gmail.comkeyboard -- I'm living
>   for today!


--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


creating addon system

2010-05-21 Thread timo verbeek
What is the easiest way in python to create a addon system?
I found to easy ways:
* using a import system like this:
   for striper in stripers:
if striper["enabled"]:
exec("from strip import %s as _x"%striper["striper"])
string = _x.start(string)
* using exec
   for striper in stripers:
if striper["enabled"]:
use=open(stripper)
exec(use)

Do you now is the best way?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with an huge dictionary

2010-05-21 Thread keobox
On 20 Mag, 12:58, Thomas Lehmann  wrote:
> > 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).

- As you can see I received the error when I tried to import
jmoco_event_data.py module from the jython interpreter prompt.
- The "import" will cause the module compilation, jython will produce
a .class file instead of .pyc.
- jmoco_event_data.py contains 4 dictionaries:

typesValToName={
220:'EMS_EVENT_EMS_INTERNAL_BASE',
221:'EMS_EVENT_INTERNAL_TYPE_BASE',
222:'EMS_EVENT_INTERNAL_N_E_P_M_EVENT',
223:'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD',
224:'EMS_EVENT_NE_SPECIFIC_BASE',
... 11746 entries int key: string value
}

typesNameToVal={
'EMS_EVENT_EMS_INTERNAL_BASE':220,
'EMS_EVENT_INTERNAL_TYPE_BASE':221,
'EMS_EVENT_INTERNAL_N_E_P_M_EVENT':222,
'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD':223,
'EMS_EVENT_NE_SPECIFIC_BASE':224,
... total 11746 entries string key: int value
}

causesValToName={
0:'NOT_APPLICABLE_UNKNOWN',
1:'SOFTWARE_CAUSE_UNKNOWN',
2:'ABSENT_MODULE',
3:'FAULTY_MODULE',
... 483 entries int key: string value
}

causesNameToVal={
'NOT_APPLICABLE_UNKNOWN':0,
'SOFTWARE_CAUSE_UNKNOWN':1,
'ABSENT_MODULE':2,
'FAULTY_MODULE':3,
... 483 entries string key: int value
}

> 2) You did not say how you have saved.

The dictionaries are in the jmoco_event_data.py module.

> 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?

Nope, the dictionaries are only int to string mappings and string to
int mappings

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

The failure happens during module's import, so my question is: Is
jython able to handle such big dictionaries?

> More details are required...

jmoco_event_data.py has a size of roughly 700KB.
-- 
http://mail.python.org/mailman/listinfo/python-list


string.Template.safe_substitute() with % type formatting?

2010-05-21 Thread python
Python 2.6: Is there a programming technique or 3rd party
formatting module that supports string.Template.safe_substitute()
type string substituion with % type formatting rules for width,
decimals, justification, etc?

Or do I need to use a 3rd party template engine to get the best
of both worlds?

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


Re: help need to write a python spell checker

2010-05-21 Thread Albert van der Horst
In article ,
Terry Reedy   wrote:
>On 5/19/2010 3:17 AM, CM wrote:
>> I love how he just copied and pasted the assignment without any other
>> remarks.
>
>Yeah, that way he did not mess it up ;-).

OTOH it may be a copyright infringement. Or is posting an assignment to a
newsgroup "fair use"?

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: where are the program that are written in python?

2010-05-21 Thread Jason Scheirer
On May 21, 3:21 am, Deep_Feelings  wrote:
> python is not a new programming language ,it has been there for the
> last  15+ years or so ? right ?
>
> however by having a look at this pagehttp://wiki.python.org/moin/Applications
> i could not see many programs written in python (i will be interested
> more in COMMERCIAL programs written in python ). and to be honest ,i
> tried some of the programs in that list and all the programs that i
> tried either dead projects or so buggy !
>
> 1- where are the programs that is written in python ?
> 2- python is high productivity language : why there are no commercial
> programs written in python ?
>
> is python a valid practical programming language ?
> why it is not used in commercial software ?
>
> please don't mention programs where python was used as a glue ,those
> programs are not actually written in python.
>
> any help will be appreciated
>
> thank you

I write commercial software full-time in Python (well, mixed with C++)
at ESRI. I have been able to make a living developing in Python full
time at various places for the last 4 years. I can assure you that
there is plenty of commercial software out there that uses Python. The
reason you don't *see* it is because the development language for a
commercial product is a lot less important than the functionality of
the product, so "WRITTEN IN PYTHON" is likely not going to be a
bullet point on a marketing slide. And quite frankly, it should be a
trade secret for the companies enlightened enough to use it as their
language of choice because it is to productive that it provides a
competitive advantage.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange MySQL Problem

2010-05-21 Thread John Nagle

Christian Heimes wrote:

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


   Er, yes.  Generally, you don't try a create on every insert transaction.
Since your create has foreign keys, it will fail if the other tables don't
already exist. So you need to have a more organized way of setting up the
database.

   InnoDB is a proper transaction database.  You must commit after insert
or the inserts will be properly rolled back and undone after
database disconnect.

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


Another Strange MySQL Problem

2010-05-21 Thread Victor Subervi
Hi;
When I try to execute this code from my Python script, I get this error:

Traceback (most recent call last):
  File 
"/var/www/html/creative.vi/clients/sea-flight/reservations/create_edit_bags3.py",
line 38, in ?

create_edit_bags3()
  File 
"/var/www/html/creative.vi/clients/sea-flight/reservations/create_edit_bags3.py",
line 32, in create_edit_bags3

cursor.execute('insert into Baggage values (Null, %s, %s, %s,
%s)', (flight_id, customer_id, weight, ticket_no))
  File "/usr/lib64/python2.4/site-packages/MySQLdb/cursors.py", line
163, in execute

self.errorhandler(self, exc, value)
  File "/usr/lib64/python2.4/site-packages/MySQLdb/connections.py",
line 35, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1452, 'Cannot add or update a child row: a foreign
key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2`
FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))')

However, when I try from the MySQL prompt after duly printing it out from
the code, it works. Why?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional argument to a subclass of a class

2010-05-21 Thread Terry Reedy

On 5/20/2010 10:56 PM, Alex Hall wrote:

A couple of style comments for you to consider.


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


Not indenting lines after def makes the code harder to read for me, and, 
I expect, many others here who use indentation as a cue. If you want one 
param per line, give them extra indents if you want.



   self.name=name
   self.id=id
   self.hits=hits
   self.weapons=weapons
   self.isAircraft=isAircraft
  #end def
#end class


#end markers are fine for private code but are distracting noise to me, 
and, I expect, other experienced Python coders.


Terry Jan Reedy

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


Re: optional argument to a subclass of a class

2010-05-21 Thread Alex Hall
On 5/21/10, Terry Reedy  wrote:
> On 5/20/2010 10:56 PM, Alex Hall wrote:
>
> A couple of style comments for you to consider.
>
>> class Craft():
>>   def __init__(self,
>>   name,
>>   isAircraft=False,
>>   id=helpers.id(),
>>   hits=0,
>>   weapons=[]):
>
> Not indenting lines after def makes the code harder to read for me, and,
> I expect, many others here who use indentation as a cue. If you want one
> param per line, give them extra indents if you want.
Good point, I had not considered that; Python's relyance on
indentation made me think that indenting past the level of the class
would cause problems.
>
>>self.name=name
>>self.id=id
>>self.hits=hits
>>self.weapons=weapons
>>self.isAircraft=isAircraft
>>   #end def
>> #end class
>
> #end markers are fine for private code but are distracting noise to me,
> and, I expect, other experienced Python coders.
I will try to remember to remove them for posting, but I find them
immensely helpful; using a screen reader, and so not being able to
look at code and see the indentation, means that I have to have a way
to tell myself where things end, much like braces in other languages.
When I post here I will try to remove them, but for code I zip and put
on my website they have to stay since I rely on them and the zip is
just what I am working on at the time, plus there are a lot of those
comments to remove from an entire project.
>
> Terry Jan Reedy
>
> --
> 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-21 Thread Christian Heimes

Am 21.05.2010 04:56, schrieb 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=[]):


I hope you are aware that helpers.id() is called just once when the 
*class* is defined and that the list weapons is shared across all 
instances of the craft class. :)


Have you read about *args and **kwargs in the Python docs? I bet you 
find them useful for your problem.


Christian

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


Re: Solutions for finding the 1000th prime

2010-05-21 Thread Neal
You did provide a very constructive answer and I do apologize for
generalizing the group or all the posts. And while the original poster
did not seem to have made much of an effort, the tone of the initial
response of that thread turns off anyone else who may be willing to
make that effort.

I also want people who may have forgotten to understand how early this
problem shows up in an Introduction to Computer Science course. In
this class its the second assignment, right after the obligatory
'Hello World!' variant.

I'm sure that while finding solutions and new keywords is integral to
learning how to program in a language, defining the a function isn't a
tool that has been introduced quite yet, as simple as it may seem.

Thank you for the link to the mailing list as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where are the program that are written in python?

2010-05-21 Thread Terry Reedy

On 5/21/2010 7:12 AM, Deep_Feelings wrote:

On May 21, 1:35 pm, Simon Brunning  wrote:

On 21 May 2010 11:21:11 UTC+1, Deep_Feelings  wrote:

Seehttp://www.python.org/about/success/


thankx for reply.

from that list i have a feeling that python is acting only as "quick
and dirty work" nothing more !


Try 'quick and clean' and you would be more accurate.

But that would not be so trollish, would it?

tjr


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


Re: where are the program that are written in python?

2010-05-21 Thread Patrick Maupin
On May 21, 5:21 am, Deep_Feelings  wrote:

> i could not see many programs written in python

Well you could try PyPi, or even a search on googlecode.

> (i will be interested
> more in COMMERCIAL programs written in python ).

What do you mean by commercial, and why?

> and to be honest ,i
> tried some of the programs in that list and all the programs that i
> tried either dead projects or so buggy !

So, you want us to believe that you desperately want to pay someone
for working Python software, but are finding it hard to find some?

> 1- where are the programs that is written in python ?

All over the place.

> 2- python is high productivity language : why there are no commercial
> programs written in python ?

There are a lot of commercial programs written in Python.  But any
company which thinks it has a lock on some kind of super secret sauce
isn't going to use Python, because it's very easy to reverse engineer
even compiled Python programs.  Also, any company in a competitive
market where execution speed is extremely important might choose some
other language because, frankly, the fact that a development tool is
highly productive is not something that the end user directly cares
about.  (But the up-front choice of another language simply for speed,
rather than prototyping with Python and then recoding the slow bits,
would probably be a decision borne of ignorance.)

> is python a valid practical programming language ?

Absolutely.  I've been using it heavily for 11 years, for real work,
for which I get paid.

> why it is not used in commercial software ?

What makes you think that it's not?  Is this some kind of "big lie"
strategy?  To what end?

> any help will be appreciated

It's hard to help when you don't describe the problem.  Reading
between the lines, the most charitable and probable interpretation of
your problem I can come up with is that you think you're going to
create a multi-billion dollar computer program and you're desperately
trying to validate your preconceived notion that Python isn't the
language to write it in. Sorry, but I can't help with that.

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


Re: creating addon system

2010-05-21 Thread Krister Svanlund
On Fri, May 21, 2010 at 5:50 PM, timo verbeek  wrote:
> What is the easiest way in python to create a addon system?
> I found to easy ways:
> * using a import system like this:
>       for striper in stripers:
>        if striper["enabled"]:
>            exec("from strip import %s as _x"%striper["striper"])
>            string = _x.start(string)
> * using exec
>       for striper in stripers:
>        if striper["enabled"]:
>            use=open(stripper)
>            exec(use)
>
> Do you now is the best way?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Check this one out: http://docs.python.org/library/functions.html#__import__
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional argument to a subclass of a class

2010-05-21 Thread Alex Hall
On 5/21/10, Christian Heimes  wrote:
> Am 21.05.2010 04:56, schrieb 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=[]):
>
> I hope you are aware that helpers.id() is called just once when the
> *class* is defined and that the list weapons is shared across all
> instances of the craft class. :)
I know id is called once, but what do you mean weapons is shared?
>
> Have you read about *args and **kwargs in the Python docs? I bet you
> find them useful for your problem.
>
> Christian
>
> --
> 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: where are the program that are written in python?

2010-05-21 Thread geremy condra
On Fri, May 21, 2010 at 4:12 AM, Deep_Feelings  wrote:
> On May 21, 1:35 pm, Simon Brunning  wrote:
>> On 21 May 2010 11:21:11 UTC+1, Deep_Feelings  wrote:
>>
>> Seehttp://www.python.org/about/success/
>
> thankx for reply.
>
> from that list i have a feeling that python is acting only as "quick
> and dirty work" nothing more !

Yeah, there's not really a lot of industry support. If only we could
get a huge search engine like bing to use python extensively we'd
be in a lot better shape.

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


Re: Another Strange MySQL Problem

2010-05-21 Thread Tim Chase

On 05/21/2010 12:31 PM, Victor Subervi wrote:

 cursor.execute('insert into Baggage values (Null, %s, %s, %s,
%s)', (flight_id, customer_id, weight, ticket_no))


You're trying to insert stuff...


OperationalError: (1452, 'Cannot add or update a child row: a foreign
key constraint fails (`seaflight/Baggage`, CONSTRAINT `Baggage_ibfk_2`
FOREIGN KEY (`customer_id`) REFERENCES `Customers` (`id`))')


But the value you're giving for the customer_id doesn't exist in 
the Customers table (as mandated by the FK).  Or perhaps the 
column-order for Baggage isn't what you think it is.  I always 
specify it explicitly:


  INSERT INTO Baggage (
   something, flight_id, customer_id, weight, ticket_no
  ) VALUES (Null, %s, %s, %s, %s)

just in case the table column-order ever changes during a 
database update.


-tkc



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


Re: where are the program that are written in python?

2010-05-21 Thread Terry Reedy

On 5/21/2010 6:21 AM, Deep_Feelings wrote:

python is not a new programming language ,it has been there for the
last  15+ years or so ? right ?

however by having a look at this page http://wiki.python.org/moin/Applications
i could not see many programs written in python (i will be interested
more in COMMERCIAL programs written in python ). and to be honest ,i


There are two kinds of 'commercial' programs.
1. The vast majority are proprietary programs kept within a company for 
its own use. As long as these work as intended, they are mostly 
invisible to the outside world.

2. Programs sold to anyone who wants them.

Python trades programmer speed for execution speed. If a successful 
Python program is going to be run millions of times, it makes economic 
sense to convert time-hogging parts to (for instance) C.  In fact, this 
is a consideration in deciding what functions should be builtin and 
which stdlib modules are written or rewritten in C.


Programs being sold tend to be compared to competitors on speed with 
perhaps more weight than they rationally should. Speed is easier to 
measure than, for instance, lack of bugs.


Python programs can be and sometimes are distributed as .exe files. The 
users of such neither know nor care that some of the source is Python.



tried some of the programs in that list and all the programs that i
tried either dead projects or so buggy !

1- where are the programs that is written in python ?


Mostly kept private. For instance, GvR, Python's inventor, spent part of 
his first year at Google writing a neat-looking programmer console 
program in Python (Mondrian) designed to improve the productivity of 
Google programmers. As far as I know, Google has not released it.



please don't mention programs where python was used as a glue ,those
programs are not actually written in python.


A C program glues together micro-coded functions. Even a 'pure' CPython 
program glues together C-coded functions. Some are in builtins, some are 
imported from the stdlib, and some can be imported from 3rd party 
packages. The extensibility of CPython is part of its design.


Terry Jan Reedy

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


Re: optional argument to a subclass of a class

2010-05-21 Thread Chris Rebert
On Fri, May 21, 2010 at 11:38 AM, Alex Hall  wrote:
> On 5/21/10, Christian Heimes  wrote:
>> Am 21.05.2010 04:56, schrieb 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=[]):
>>
>> I hope you are aware that helpers.id() is called just once when the
>> *class* is defined and that the list weapons is shared across all
>> instances of the craft class. :)
> I know id is called once, but what do you mean weapons is shared?

Read the "Important warning" on
http://docs.python.org/tutorial/controlflow.html#default-argument-values
`weapons` will be the *exact same list object* for all Craft instances
the way you have it currently (i.e. it will not be copied and changes
to it will affect all Crafts).

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


Re: optional argument to a subclass of a class

2010-05-21 Thread Peter Otten
Alex Hall wrote:

> On 5/21/10, Christian Heimes  wrote:
>> Am 21.05.2010 04:56, schrieb 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=[]):
>>
>> I hope you are aware that helpers.id() is called just once when the
>> *class* is defined and that the list weapons is shared across all
>> instances of the craft class. :)
> I know id is called once, but what do you mean weapons is shared?

All Craft instances for which you don't provide a weapons argument 
explicitly will share the same list. If you later append a weapon to that 
list all these Craft instances will see this change and get the extra 
weapon:

a = Craft("first")
b = Craft("second")
a.weapons.append("surprise")
print b.weapons # ['surprise']

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


Re: where are the program that are written in python?

2010-05-21 Thread Tim Chase

On 05/21/2010 01:40 PM, geremy condra wrote:

See http://www.python.org/about/success/


thankx for reply.

from that list i have a feeling that python is acting only as "quick
and dirty work" nothing more !


Yeah, there's not really a lot of industry support. If only we could
get a huge search engine like bing to use python extensively we'd
be in a lot better shape.


Or if an organization known to hire a bunch of rocket-scientists 
were to use Python...that would make it a real language...


-tkc


http://www.python.org/about/success/usa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: optional argument to a subclass of a class

2010-05-21 Thread Chris Rebert
On Fri, May 21, 2010 at 11:49 AM, Chris Rebert  wrote:
> On Fri, May 21, 2010 at 11:38 AM, Alex Hall  wrote:
>> On 5/21/10, Christian Heimes  wrote:
>>> Am 21.05.2010 04:56, schrieb 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=[]):
>>>
>>> I hope you are aware that helpers.id() is called just once when the
>>> *class* is defined and that the list weapons is shared across all
>>> instances of the craft class. :)
>> I know id is called once, but what do you mean weapons is shared?
>
> Read the "Important warning" on
> http://docs.python.org/tutorial/controlflow.html#default-argument-values
> `weapons` will be the *exact same list object* for all Craft instances
> the way you have it currently (i.e. it will not be copied and changes
> to it will affect all Crafts).

Er, all Craft instances /where you didn't pass an explicit `weapons`
argument to the constructor/, that is.

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


Re: optional argument to a subclass of a class

2010-05-21 Thread Ethan Furman

Alex Hall wrote:

On 5/20/10, alex23  wrote:
I have since updated each ship's
__init__ to accept all the arguments that Craft accepts so that I can
support all optional arguments, 


Ick.  Now you'll have to change several things if you make one change to 
the Craft class.  Better to do it this way:


[borrowing Peter's example]

class Craft(object):
def __init__(self, name, id=None, weapons=None):
if id is None:
id = helpers.id()
if weapons is None:
weapons = []
self.name = name
self.id = id
self.weapons = weapons

class Battleship(Craft):
def __init__(self, name, max_hits=None, **kwds):
Craft.__init__(self, name, **kwds)
self.max_hits = max_hits



Notice the **kwds in Battleships's init, both in the parameter line, and 
in the call to Craft's init.  This way all keyword arguments that 
Battleship doesn't directly support will be passed through to Craft.


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


Re: creating addon system

2010-05-21 Thread Adam Tauno Williams
On Fri, 2010-05-21 at 08:50 -0700, timo verbeek wrote:
> What is the easiest way in python to create a addon system?
> I found to easy ways:
> * using a import system like this:
>for striper in stripers:
> if striper["enabled"]:
> exec("from strip import %s as _x"%striper["striper"])
> string = _x.start(string)

This is how I chose to do it.  Just walking a list of bundles and
discover the available classes [as plugins].



-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

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


Re: optional argument to a subclass of a class

2010-05-21 Thread Alex Hall
On 5/21/10, Ethan Furman  wrote:
> Alex Hall wrote:
>> On 5/20/10, alex23  wrote:
>> I have since updated each ship's
>> __init__ to accept all the arguments that Craft accepts so that I can
>> support all optional arguments,
>
> Ick.  Now you'll have to change several things if you make one change to
> the Craft class.  Better to do it this way:
>
> [borrowing Peter's example]
>
> class Craft(object):
Curious: I do not pass Craft this "object" keyword and I have no
problems. What is it for? Just a convention, something like self being
called self?
>  def __init__(self, name, id=None, weapons=None):
>  if id is None:
>  id = helpers.id()
>  if weapons is None:
>  weapons = []
>  self.name = name
>  self.id = id
>  self.weapons = weapons
>
> class Battleship(Craft):
>  def __init__(self, name, max_hits=None, **kwds):
>  Craft.__init__(self, name, **kwds)
>  self.max_hits = max_hits
>
>
>
> Notice the **kwds in Battleships's init, both in the parameter line, and
> in the call to Craft's init.  This way all keyword arguments that
> Battleship doesn't directly support will be passed through to Craft.

Thanks, the **kwords makes sense!! I implemented it much as you
described, and life is much easier; each ship or aircraft now has a
simple constructor, and I am still free to change any attrib I want
later or at creation time. A very powerful concept, and I now have
2-line constructors.

class Battleship(Craft):
 def __init__(self, name, **kwords):
  Craft.__init__(self, name, maxHits=4, **kwords) #call the
superclass's __init__

class Carrier(Craft):
 def __init__(self, name, **kwords):
  Craft.__init__(self, name, maxHits=5, **kwords) #call the
superclass's __init__


>
> ~Ethan~
> --
> 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-21 Thread Chris Rebert
On Fri, May 21, 2010 at 1:09 PM, Alex Hall  wrote:
> On 5/21/10, Ethan Furman  wrote:
>> Alex Hall wrote:
>>> On 5/20/10, alex23  wrote:
>>> I have since updated each ship's
>>> __init__ to accept all the arguments that Craft accepts so that I can
>>> support all optional arguments,
>>
>> Ick.  Now you'll have to change several things if you make one change to
>> the Craft class.  Better to do it this way:
>>
>> [borrowing Peter's example]
>>
>> class Craft(object):
> Curious: I do not pass Craft this "object" keyword and I have no
> problems. What is it for? Just a convention, something like self being
> called self?

It causes the class to be "new-style". See
http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes

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


First Tkinter script: requesting comments

2010-05-21 Thread Bart Kastermans

I wrote a first script using Tkinter.  As I am new to its
use, I am only just feeling my way around.  I would very
much like comments on the design of the script (and in fact
any other comments on my code would also be very welcome).

I have it posted (with syntax coloring) at:

http://kasterma.wordpress.com/2010/05/21/first-experiments-with-tkinter/

But will also include it here for convenience.

Thanks for any help,

Best,
Bart

***

#!/usr/bin/env python
#
# Getting a list of students and grades displayed so that grades can
# be updated, and we poll these changes (so that in the future we can
# act on it).
#
# Bart Kastermans, www.bartk.nl

"""
Design of the window

  +-+
  |  root   |
  |  +--+   |
  |  | title_frame  |   |
  |  |  +--+|   |
  |  |  | Label(title) ||   |
  |  |  |  ||   |
  |  |  +--+|   |
  |  +--+   |
  |  +--+   |
  |  | exam_grades_frames   |   |
  |  |  +-+ |   |
  |  |  | Frame(ex)   | |   |
  |  |  | ++  +-+ | |   |
  |  |  | | Entry(name)|  | Entry(grade)| | |   |
  |  |  | ||  | | | |   |
  |  |  | ++  +-+ | |   |
  |  |  +-+ |   |
  |  |  |   |
  |  +--+   |
  | |
  | +-+ |
  | | quit_button | |
  | | | |
  | +-+ |
  +-+

"""



from Tkinter import *

# global info for this specific example

# four students
no_stud = 4
exam_grades = [1,2,3,4]
names = ["Ben", "Jim", "James", "Mel"]
# upper bound for name length
max_name_len = max (map (len, names))

# set up root window
root = Tk()
root.geometry ("400x400")

exam_grades_string = map (lambda x: StringVar (root,str (x)), exam_grades)

names_string = map (lambda x: StringVar (root, x), names)

def setup ():
""" setup the window with the list of students.

This is test-code to figure out what the app finally should look
like.
"""

# title frame, with title Grade Correction in it
title_frame = Frame(root)
title_frame.pack (fill=X)

w = Label (title_frame, text = "Grade Correction", font = ("Helvetica", 25))
w.pack (side=LEFT)

# from to hold the list of grades
exam_grades_frame = Frame (root)
exam_grades_frame.pack (fill=BOTH)

exam_label = Label (exam_grades_frame, text="EXAMS")
exam_label.pack ()

# set up the list of grades
for i in range (0,no_stud):
# a frame per student
ex = Frame (exam_grades_frame)
ex.pack ()
# name on the left
name = Entry (ex, textvariable=names_string[i], width=max_name_len+2)
name.config (state=DISABLED)
name.pack (side=LEFT)
# grade next to it
grade = Entry (ex, textvariable=exam_grades_string [i], width=4)
grade.pack (side=LEFT)

# button to quit the application
qb = Button (root)
qb ['text'] = "quit"
qb ['command'] = root.quit
qb.pack ()


def to_int (st):
""" helper function to convert strings to integers.

Empty string represents 0.
"""
if len (st) == 0:
return 0
else:
return int (st)

def get_curr_grades ():
""" extract the grades from exam_grades_string.

exam_grades_string consists of StringVar that get updated when the
fields are updated in the GUI.
"""
grades = []
for i in range (0, no_stud):
grades.append (exam_grades_string [i].get())
return grades

# get the current grades
curr_grades = map (to_int, get_curr_grades ())

def poll_exams ():
""" function that keeps polling the current grades, looking for changes"""
global curr_grades
new_grades = map (to_int, get_curr_grades ())
if new_grades != curr_grades:
print new_grades
curr_grades = new_grades
root.after( 250, poll_exams)

# window setup
setup ()

gettext compatible, public domain collections of translations for strings commonly used in software applications?

2010-05-21 Thread python
It seems to me that there must be some public domain collection
of translated strings that could be searched for 1:1 or fuzzy
translations for strings commonly used in software applications?

Is there a technical and copyright friendly (LGPL licensed?) way
to query services like Google's Translator Toolkit, LaunchPad,
Mygengo, etc. to find translations for common strings?

I've tried to google this topic without success.

Example: public domain po (translation|translations)

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


Re: optional argument to a subclass of a class

2010-05-21 Thread Alex Hall
On 5/21/10, Chris Rebert  wrote:
> On Fri, May 21, 2010 at 1:09 PM, Alex Hall  wrote:
>> On 5/21/10, Ethan Furman  wrote:
>>> Alex Hall wrote:
 On 5/20/10, alex23  wrote:
 I have since updated each ship's
 __init__ to accept all the arguments that Craft accepts so that I can
 support all optional arguments,
>>>
>>> Ick.  Now you'll have to change several things if you make one change to
>>> the Craft class.  Better to do it this way:
>>>
>>> [borrowing Peter's example]
>>>
>>> class Craft(object):
>> Curious: I do not pass Craft this "object" keyword and I have no
>> problems. What is it for? Just a convention, something like self being
>> called self?
>
> It causes the class to be "new-style". See
> http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes
Oh, I see. Thanks.
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>


-- 
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


Traceback spoofing

2010-05-21 Thread Zac Burns
Why can't I inherit from traceback to 'spoof' tracebacks? I would like to
create a traceback that is save-able to re-raise exceptions later without
leaking all the locals. (I'm sure this idea has been discussed before but I
can't find it anymore.)

class Traceback(types.TracebackType): pass
TypeError: Error when calling the metaclass bases
 type 'traceback' is not an acceptable base type

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer
Zindagi Games
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-21 Thread Bryan
Peter Pearson wrote:
> 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,

Our standards for "quickly" and "large" seem kind of thin.

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

I was thinking combinatorics more than number theory. I didn't find a
neat formula, but I came up with a recursive memo-izing algorithm that
handles 100-digit n's. I tested this against the initial algorithm
plus Peter Pearson's optimization for numbers up to several thousand,
and it agrees... well, after I fixed stuff that is.

-Bryan Olson

# ---
_nds = {}
def ndsums(m, d):
""" How many d-digit ints' digits sum to m?
"""
assert m >= 0 and d >= 0
if m > d * 9:
return 0
if m == 0 or d == 1:
return 1
if (m, d) not in _nds:
_nds[(m, d)] = sum(ndsums(m - i, d - 1)
   for i in range(min(10, m + 1)))
return _nds[(m, d)]


def prttn(m, n):
assert m > 0 and n > 0
def inner(m, dls):
if not dls:
return 1 if m == 0 else 0
count = 0
msd, rest = dls[0], dls[1:]
for d in range(msd):
if m >= d:
count += ndsums(m - d, len(dls) - 1)
count += inner(m - msd, dls[1:])
return count
return inner(m, [int(c) for c in str(n - 1)])

pi100 =
3141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067

print(prttn(500, pi100))


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


Re: gettext compatible, public domain collections of translations for strings commonly used in software applications?

2010-05-21 Thread Steven D'Aprano
On Fri, 21 May 2010 18:01:58 -0400, python wrote:

> It seems to me that there must be some public domain collection of
> translated strings that could be searched for 1:1 or fuzzy translations
> for strings commonly used in software applications?

There must be? Is that a law of nature or something? "I want it, so it 
must exist, QED."


> Is there a technical and copyright friendly (LGPL licensed?) way to
> query services like Google's Translator Toolkit, LaunchPad, Mygengo,
> etc. to find translations for common strings?

You would need to check the licence terms and conditions for those 
services. It's not enough to have LGPL-licenced software to access 
Translator Toolkit, if Google put limits or prohibitions on access.

You will need to check the services in question to see if they publish an 
API for programmatically using their software. 


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


Re: links button gone from python.org

2010-05-21 Thread Aahz
In article <290f2f31-0893-469a-a12c-49eff9ffb...@y21g2000vba.googlegroups.com>,
eric_dex...@msn.com  wrote:
>
>I noticed that that the link to that section is gone.  The page
>seems to be there when I use the url that is stored on my computer.

What are you talking about?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Traceback spoofing

2010-05-21 Thread Terry Reedy

On 5/21/2010 7:22 PM, Zac Burns wrote:

Why can't I inherit from traceback to 'spoof' tracebacks?


Because a) they are, at least in part, an internal implementation detail 
of CPython, and b) even if you could, Python would use the builtin 
original with exceptions, and c) you can probably do anything sensible 
you want with them by wrapping them, as in, define a class with a 
traceback as the main instance attribute.


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


Re: where are the program that are written in python?

2010-05-21 Thread Aahz
In article ,
Patrick Maupin   wrote:
>
>There are a lot of commercial programs written in Python.  But any
>company which thinks it has a lock on some kind of super secret sauce
>isn't going to use Python, because it's very easy to reverse engineer
>even compiled Python programs.  

That's not always true.  Both my employer (Egnyte) and one of our main
competitors (Dropbox) use Python in our clients.  We don't care much
because using our servers is a requirement of the client.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Traceback spoofing

2010-05-21 Thread exarkun

On 01:42 am, tjre...@udel.edu wrote:

On 5/21/2010 7:22 PM, Zac Burns wrote:

Why can't I inherit from traceback to 'spoof' tracebacks?


Because a) they are, at least in part, an internal implementation 
detail of CPython,


But you can just say this about anything, since there is no Python 
specification.  So it's mostly meaningless.
and b) even if you could, Python would use the builtin original with 
exceptions,


Only if it were implemented that way.  One could certainly an 
implementation with different behavior.
and c) you can probably do anything sensible you want with them by 
wrapping them, as in, define a class with a traceback as the main 
instance attribute.


Except you can't re-raise them.

Something like this feature has been proposed before.  The only objects 
that I've ever heard raised are that it's harder to implement on CPython 
than anyone is willing to tackle.


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


Re: where are the program that are written in python?

2010-05-21 Thread Ben Finney
a...@pythoncraft.com (Aahz) writes:

> In article 
> ,
> Patrick Maupin   wrote:
> >
> >There are a lot of commercial programs written in Python.  But any
> >company which thinks it has a lock on some kind of super secret sauce
> >isn't going to use Python, because it's very easy to reverse engineer
> >even compiled Python programs.  
>
> That's not always true.  Both my employer (Egnyte) and one of our main
> competitors (Dropbox) use Python in our clients.  We don't care much
> because using our servers is a requirement of the client.

Doesn't that mean those companies don't fit the above description? That
is, neither of them “thinks it has a lock on some kind of super secret
sauce” in the programs. So they don't seem to be counter-examples.

-- 
 \“The right to search for truth implies also a duty; one must |
  `\  not conceal any part of what one has recognized to be true.” |
_o__) —Albert Einstein |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Traceback spoofing

2010-05-21 Thread Zac Burns
> Except you can't re-raise them.
>

Yes, I should have noted that in the original post:

>>> raise RuntimeError, 'X', wrapped_traceback
Traceback (most recent call last):
  File "", line 1, in 
TypeError: raise: arg 3 must be a traceback or None


Does someone know where the thread went about it being hard to implement?
I'm interested to see what makes it difficult.

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer
Zindagi Games
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where are the program that are written in python?

2010-05-21 Thread Lie Ryan
On 05/22/10 04:47, Terry Reedy wrote:
> On 5/21/2010 6:21 AM, Deep_Feelings wrote:
>> python is not a new programming language ,it has been there for the
>> last  15+ years or so ? right ?
>>
>> however by having a look at this page
>> http://wiki.python.org/moin/Applications
>> i could not see many programs written in python (i will be interested
>> more in COMMERCIAL programs written in python ). and to be honest ,i
> 
> There are two kinds of 'commercial' programs.
> 1. The vast majority are proprietary programs kept within a company for
> its own use. As long as these work as intended, they are mostly
> invisible to the outside world.
> 2. Programs sold to anyone who wants them.
> 
> Python trades programmer speed for execution speed. If a successful
> Python program is going to be run millions of times, it makes economic
> sense to convert time-hogging parts to (for instance) C.  In fact, this
> is a consideration in deciding what functions should be builtin and
> which stdlib modules are written or rewritten in C.
> 
> Programs being sold tend to be compared to competitors on speed with
> perhaps more weight than they rationally should. Speed is easier to
> measure than, for instance, lack of bugs.

doubting python's speed? Look at Mercurial vs. SVN; Mercurial is written
in Python while SVN in C. Mercurial beats SVN in speed by several orders
of magnitude.

One of Mercurial's design goal was to be faster than SVN, if the
programmers have naively believed that choice of language would matter
to program's speed, they'd choose to write Mercurial in assembly instead
(the same argument applies to Git, written in shell scripts).

Now, you may think this is an unfair comparison, since Mercurial is hype
and new, SVN is antiquated and old. But it shows that in real-life, the
language being inherently slow often dosn't matter. What matters more
are the choice of data structure and algorithm, I/O speed, network
latency, and development speed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another "Go is Python-like" article.

2010-05-21 Thread John Roth
On May 21, 8:20 am, Grant Edwards  wrote:
> In a recent Reg article, there's yet more yammering on about how Go is
> somehow akin to Python -- referring to Go as a "Python-C++" crossbreed.
>
> http://www.theregister.co.uk/2010/05/20/go_in_production_at_google/
>
> I still don't get it.
>
> What about Go, exactly, do people see as Phython-like?
>
> Go doesn't seem to have any of the salient features (either syntactic
> or semantic) of Python other than garbage collection.
>
> How is Go not just warmed-over Java?
>
> --
> Grant Edwards               grant.b.edwards        Yow! RELATIVES!!
>                                   at              
>                               gmail.com            

Actually, Go seems to be more C implemented the way the C developers
would have done it if they knew then what they know now. That's not a
joke - look at the names on the development team.

I haven't a clue how anyone can think it's similar to Python. Or Java,
for that matter.

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


Re: where are the program that are written in python?

2010-05-21 Thread Chris Rebert
On Fri, May 21, 2010 at 8:03 PM, Lie Ryan  wrote:
> On 05/22/10 04:47, Terry Reedy wrote:
>> On 5/21/2010 6:21 AM, Deep_Feelings wrote:
>>> python is not a new programming language ,it has been there for the
>>> last  15+ years or so ? right ?
>>>
>>> however by having a look at this page
>>> http://wiki.python.org/moin/Applications
>>> i could not see many programs written in python (i will be interested
>>> more in COMMERCIAL programs written in python ). and to be honest ,i
>>
>> There are two kinds of 'commercial' programs.
>> 1. The vast majority are proprietary programs kept within a company for
>> its own use. As long as these work as intended, they are mostly
>> invisible to the outside world.
>> 2. Programs sold to anyone who wants them.
>>
>> Python trades programmer speed for execution speed. If a successful
>> Python program is going to be run millions of times, it makes economic
>> sense to convert time-hogging parts to (for instance) C.  In fact, this
>> is a consideration in deciding what functions should be builtin and
>> which stdlib modules are written or rewritten in C.
>>
>> Programs being sold tend to be compared to competitors on speed with
>> perhaps more weight than they rationally should. Speed is easier to
>> measure than, for instance, lack of bugs.
>
> doubting python's speed? Look at Mercurial vs. SVN; Mercurial is written
> in Python while SVN in C. Mercurial beats SVN in speed by several orders
> of magnitude.

Erm, in fairness, I recall hearing that some speed-critical bits of hg
are written in C. It does lend credence to the "Python as glue
language" argument though; I doubt hg's extensibility and friendly
interface would have been as easy to implement it C (particularly the
slick instant-server feature).

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


How to show the current line number with pdb.set_trace()

2010-05-21 Thread Peng Yu
After starting pdb.set_trace(), python doens't show line number. Could
you let me know how to print the number by default so that I know
where the current line is?

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


Re: where are the program that are written in python?

2010-05-21 Thread Carl Banks
On May 21, 3:21 am, Deep_Feelings  wrote:
> please don't mention programs where python was used as a glue ,those
> programs are not actually written in python.

I hate to answer a troll, but I'll just mention that when people talk
about a "glue language", they're not talking about using some Python
code to connect two big systems together (although Python is good for
that).

What they are saying is that Python is a good language to serve as
high-level logic interfacing lots of different library codes--often
but not always written in faster languages--together in one program.
In that case, yes, the program is written in Python.

The word "glue" is probably not the best metaphor, since to most
people it means "something you use to connect two objects together".
A better metaphor would be like a "substrate language".

A lot of materials do use a form of glue as the substrate, but never
mind that.


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


Re: Problem with an huge dictionary

2010-05-21 Thread Peter Otten
keobox wrote:

> On 20 Mag, 12:58, Thomas Lehmann  wrote:
>> > 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).
> 
> - As you can see I received the error when I tried to import
> jmoco_event_data.py module from the jython interpreter prompt.
> - The "import" will cause the module compilation, jython will produce
> a .class file instead of .pyc.
> - jmoco_event_data.py contains 4 dictionaries:
> 
> typesValToName={
> 220:'EMS_EVENT_EMS_INTERNAL_BASE',
> 221:'EMS_EVENT_INTERNAL_TYPE_BASE',
> 222:'EMS_EVENT_INTERNAL_N_E_P_M_EVENT',
> 223:'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD',
> 224:'EMS_EVENT_NE_SPECIFIC_BASE',
> ... 11746 entries int key: string value
> }
> 
> typesNameToVal={
> 'EMS_EVENT_EMS_INTERNAL_BASE':220,
> 'EMS_EVENT_INTERNAL_TYPE_BASE':221,
> 'EMS_EVENT_INTERNAL_N_E_P_M_EVENT':222,
> 'EMS_EVENT_INTERNAL_N_E_ALARM_RCVD':223,
> 'EMS_EVENT_NE_SPECIFIC_BASE':224,
> ... total 11746 entries string key: int value
> }
> 
> causesValToName={
> 0:'NOT_APPLICABLE_UNKNOWN',
> 1:'SOFTWARE_CAUSE_UNKNOWN',
> 2:'ABSENT_MODULE',
> 3:'FAULTY_MODULE',
> ... 483 entries int key: string value
> }
> 
> causesNameToVal={
> 'NOT_APPLICABLE_UNKNOWN':0,
> 'SOFTWARE_CAUSE_UNKNOWN':1,
> 'ABSENT_MODULE':2,
> 'FAULTY_MODULE':3,
> ... 483 entries string key: int value
> }
> 
>> 2) You did not say how you have saved.
> 
> The dictionaries are in the jmoco_event_data.py module.
> 
>> 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?
> 
> Nope, the dictionaries are only int to string mappings and string to
> int mappings
> 
>> If so you might fail on loading those objects - especially when your
>> program
>> does not have the code for it.
> 
> The failure happens during module's import, so my question is: Is
> jython able to handle such big dictionaries?

The problem seems to be the size of the code, i. e. the dict literal rather 
than the size of the dictionary. With a slightly smaller dict I get

$ cat make_dict_source.py
from itertools import chain, count, islice

def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("n", type=int, default=100)
parser.add_argument("py")

args = parser.parse_args()

prefix = ["data = {\n"]
suffix = ["}\n"]
pairs = ("'enum_whatever_{0}': {0},\n".format(i) for i in count())
pairs = islice(pairs, args.n)
with open(args.py, "w") as outstream:
lines = chain(prefix, pairs, suffix)
outstream.writelines(lines)

if __name__ == "__main__":
main()
$ python make_dict_source.py 4000 tmp.py
$ jython tmp.py
Traceback (innermost last):
  (no code object) at line 0
java.lang.ClassFormatError: Invalid method Code length 71912 in class file 
org/python/pycode/_pyx0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:632)
at org.python.core.BytecodeLoader2.loadClassFromBytes(Unknown 
Source)
at org.python.core.BytecodeLoader.makeClass(Unknown Source)
at org.python.core.BytecodeLoader.makeCode(Unknown Source)
at org.python.core.Py.compile_flags(Unknown Source)
at org.python.core.Py.compile_flags(Unknown Source)
at org.python.core.__builtin__.execfile_flags(Unknown Source)
at org.python.util.PythonInterpreter.execfile(Unknown Source)
at org.python.util.jython.main(Unknown Source)

java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid method Code 
length 71912 in class file org/python/pycode/_pyx0
$ jython --version
Jython 2.2.1 on java1.6.0_0

Jython seems to generate a method that is bigger than the 64K allowed by 
Java. 

The simplest workaround is probably to let your module read the dict data 
from a separate file in e. g. csv format.

Peter


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


Re: where are the program that are written in python?

2010-05-21 Thread sturlamolden
On 21 Mai, 12:21, Deep_Feelings  wrote:

> 1- where are the programs that is written in python ?

You could search for them with Google and download your results
Bittorrent.

> is python a valid practical programming language ?

No, it is probably Turing incomplete.


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


Re: Another "Go is Python-like" article.

2010-05-21 Thread sturlamolden
On 21 Mai, 16:20, Grant Edwards  wrote:

> I still don't get it.
>
> What about Go, exactly, do people see as Phython-like?
>
> Go doesn't seem to have any of the salient features (either syntactic
> or semantic) of Python other than garbage collection.
>
> How is Go not just warmed-over Java?

Go is Algol 68. Reinventing the wheel is always fun.






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


Re: where are the program that are written in python?

2010-05-21 Thread Patrick Maupin
On May 21, 8:45 pm, a...@pythoncraft.com (Aahz) wrote:
> In article 
> ,
> Patrick Maupin   wrote:
> >There are a lot of commercial programs written in Python.  But any
> >company which thinks it has a lock on some kind of super secret sauce
> >isn't going to use Python, because it's very easy to reverse engineer
> >even compiled Python programs.  
>
> That's not always true.  Both my employer (Egnyte) and one of our main
> competitors (Dropbox) use Python in our clients.  We don't care much
> because using our servers is a requirement of the client.

Absolutely.  I wrote my post after the OP's second post, and from that
short, derisive tome, I inferred that the OP's definition of
"commercial" was quite narrow, so I was trying to respond on the basis
of what he would consider "commercial," which BTW, probably wouldn't
include a lot of programs that, e.g. Google uses to make money.

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


Re: where are the program that are written in python?

2010-05-21 Thread Patrick Maupin
On May 21, 9:12 pm, Ben Finney  wrote:
> a...@pythoncraft.com (Aahz) writes:
> > In article 
> > ,
> > Patrick Maupin   wrote:
>
> > >There are a lot of commercial programs written in Python.  But any
> > >company which thinks it has a lock on some kind of super secret sauce
> > >isn't going to use Python, because it's very easy to reverse engineer
> > >even compiled Python programs.  
>
> > That's not always true.  Both my employer (Egnyte) and one of our main
> > competitors (Dropbox) use Python in our clients.  We don't care much
> > because using our servers is a requirement of the client.
>
> Doesn't that mean those companies don't fit the above description? That
> is, neither of them “thinks it has a lock on some kind of super secret
> sauce” in the programs. So they don't seem to be counter-examples.

Just because someone has competition doesn't mean they don't think
they have secret sauce.  I think Aahz's main point was that in his sub-
industry, the secret sauce is guarded by not actually letting the
customer have access to executable code, other than through the
network.

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