Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-12 Thread Robert Bossy
Jeff Schwab wrote:
> Erik Max Francis wrote:
>   
>> Jeff Schwab wrote:
>>
>> 
>>> Erik Max Francis wrote:
>>>   
 Robert Bossy wrote:
 
> I'm pretty sure we can still hear educated people say that free fall 
> speed depends on the weight of the object without realizing it's a 
> double mistake.
>   
 Well, you have to qualify it better than this, because what you've 
 stated in actually correct ... in a viscous fluid.
 
>>> By definition, that's not free fall.
>>>   
>> In a technical physics context.  But he's talking about posing the 
>> question to generally educated people, not physicists (since physicists 
>> wouldn't make that error).  In popular parlance, "free fall" just means 
>> falling freely without restraint (hence "free fall rides," "free 
>> falling," etc.).  And in that context, in the Earth's atmosphere, you 
>> _will_ reach a terminal speed that is dependent on your mass (among 
>> other things).
>>
>> So you made precisely my point:  The average person would not follow 
>> that the question was being asked was about an abstract (for people 
>> stuck on the surface of the Earth) physics principle, but rather would 
>> understand the question to be in a context where the supposedly-wrong 
>> statement is _actually true_.
>> 
>
> So what's the "double mistake?"  My understanding was (1) the misuse 
> (ok, vernacular use) of the term "free fall," and (2) the association of 
> weight with free-fall velocity ("If I tie an elephant's tail to a 
> mouse's, and drop them both into free fall, will the mouse slow the 
> elephant down?")
>   
In my mind, the second mistake was the confusion between weight and mass.

Cheers
RB

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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-12 Thread Erik Max Francis
Robert Bossy wrote:

> In my mind, the second mistake was the confusion between weight and mass.

I see.  If so, then that sounds like another terminology gotcha.  The 
distinction between weight and mass is all but irrelevant for everyday 
activities, since the acceleration due to gravity is so nearly constant 
for all circumstances under which non-physicists operate in everyday life.

Not only in everyday life does the terminal speed of a falling object 
depend on its mass (m) -- among other things -- but that is also 
equivalent to that speed depending on its weight (m g_0).  Physicists 
even talk about a "standard gravity" or "acceleration due to gravity" 
being an accepted constant (g_0 = 9.806 65 m/s^2), and most SI 
guidelines, including NIST's, fully acknowledge the effective 
equivalence for everyday usage and make no requirement of using the 
"proper" units for mass (kg) vs. weight (N) for, say, buying things at 
the store, even though it's technically wrong (where "weight" is given 
in kilograms even though that's not a unit of weight, but rather of mass).

To put it another way, there are far better ways to teach physics than 
this, because these misunderstanding are not wrong in any meaningfully 
useful way.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   It isn't important to come out on top, what matters is to be the one
who comes out alive. -- Bertolt Brecht, 1898-1956
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python equivt of __FILE__ and __LINE__

2008-02-12 Thread alain
On Feb 11, 10:58 am, "Bill Davy" <[EMAIL PROTECTED]> wrote:
> Writing a quick and dirty assembler and want to give the user the location
> of an error.  The "assembly language" is Python.  If the user wants to
> generat some object code they write something  like:
>
> Label(LoopLable)
>     Load(R4)
>     Dec()
>     JNZ(LoopLabel)
>
> I can use Python to do all the expression evalutaion, conversion from Python
> FP to target FP, include files, macros (done as function definitions).  The
> functions like Load() generate the approproyte object code.
>
> So, for example, when a label is defined or referenced, I save the File,Line
> so if there is not exactly one defintion or no references, I can report the
> file location(s) to be considered.  In the example, I would want to report
> that LoopLable is not referenced, and LoopLabel is not defined.
>
> TIA,
>     Bill
>
> PSwww.SynectixLtd.comis not relevant

def __LINE__():
try:
raise Exception
except:
return sys.exc_info()[2].tb_frame.f_back.f_lineno
def __FILE__():
return inspect.currentframe().f_code.co_filename

Best regards

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


Re: Combinatorics

2008-02-12 Thread bearophileHUGS
Michael Robertson:
> I'm guessing sage has this, but shouldn't something like this be part of
> the standard library (perhaps in C)?

My answer is positive. As a reference point you can look at the
combinatorics module of Mathematica.

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


Re: idiom to ask if you are on 32 or 64 bit linux platform?

2008-02-12 Thread Christian Heimes
Jon wrote:
> Can someone tell me an idiom to choose the right one?

You can check the size of a void pointer with ctypes:

>>> import ctypes
>>> ctypes.sizeof(ctypes.c_void_p) * 8
32

Christian

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


Re: Possible to tack on random stuff to objects?

2008-02-12 Thread Bruno Desthuilliers
Cruxic a écrit :
> Is it possible to tack on arbitrary attributes to a python object?

Depends on the object's class. In the common case it's possible but 
there are a couple cases - mostly builtin immutable types - where it's not.

> For example:
> 
> s = 'nice 2 meet you'
> s.isFriendly = True
> 
> In the above example Python complains on the second line with:
> 
> AttributeError: 'str' object has no attribute 'isFriendly'
> 
> Is there another way?

 >>> class MyString(str): pass
...
 >>> s = MyString("hello")
 >>> s.is_friendly = True
 >>> s
'hello'
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom to ask if you are on 32 or 64 bit linux platform?

2008-02-12 Thread Jon
Christian Heimes wrote:
> You can check the size of a void pointer with ctypes:

>>> import ctypes
>>> ctypes.sizeof(ctypes.c_void_p) * 8

And Matt Nordhoff wrote:

>>> import platform
>>> platform.architecture()

Thanks guys! Exactly what I was after.

-Jon

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


Re: callback send data to webpage

2008-02-12 Thread Bruno Desthuilliers
Will a écrit :
> I have a small python script with a callback in it that receives data 
> from another app. Everytime the callback gets data, I'd like to send it 
> into a webpage w/o refreshing the entire webpage.
> 
> Anyone know of a tutorial that would help do that?
> 

The best thing to do would be to learn how HTTP works. Then have a look 
at Ajax and Comet:
http://en.wikipedia.org/wiki/Comet_%28programming%29
http://cometd.com/
http://www.irishdev.com/NewsArticle.aspx?id=2166
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combinatorics

2008-02-12 Thread pataphor
On Mon, 11 Feb 2008 23:52:31 -0800
Michael Robertson <[EMAIL PROTECTED]> wrote:

> Am I wishing on a star?
 
for i in xrange(10**10):
print i
OverflowError: long int too large to convert to int

The problem seems to be that although python supports arbitrary long
integers, all the internal loop counters still use limited size integers.

I'm not arguing that any program would conceivably finish the above
loop in a reasonable time, but I think it should be possible to use
itertools.islice to get a smaller slice of this iterator (somewhere in
the middle) and iterate on that. Maybe it could be done with something
like "from __future__ import use_long_integers".

P.

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


bluetooth file transfer in python

2008-02-12 Thread chartsoft
I am a teacher and need to set up a computer with a bluetooth dongle
to poll for mobile phones with bluetooth switched on in the area then
send them a jpg file.

I understand that python is capeable of this.

1.) is it worth learning python to do this or can someone out there do
it for me for a v small fee?

2.) If I am going to do it can anyone give me pointers in the best way
to do it so I do not spend hours wasting time.

Many thanks

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


Re: CSV Reader

2008-02-12 Thread Mike P
I did just try to post, but it doesn't look like it has appeared?

I've used your advice Andrew and tried to use the CSV module, but now
it doesn't seem to pick up the startswith command?
Is this because of the way the CSV module is reading the data in?
I've looked into the module description but i can't find anything that
i hould be using?

Can anyone offer an advice?

Cheers again

Mike

working_CSV =  "//filer/common/technical/Research/E2C/Template_CSV/
DFAExposureToConversionQueryTool.csv"

save_file = "//filer/common/technical/Research/E2C/Template_CSV/
CSV_Data2.csv"

start_line=False
import csv
reader = csv.reader(open(working_CSV, "rb"))
writer = csv.writer(open(save_file, "wb"))
for row in reader:
if not start_line and record.startswith("'Transaction ID'"):
start_line=True
if start_line:
print row
writer.writerows(rows)
#writer.close()

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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-12 Thread Erik Max Francis
Dennis Lee Bieber wrote:

> On Tue, 12 Feb 2008 00:18:38 -0800, Erik Max Francis <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
>> equivalence for everyday usage and make no requirement of using the 
>> "proper" units for mass (kg) vs. weight (N) for, say, buying things at 
> 
>   Ah, but in the US, the unwashed masses (as in "lots of people")
> don't even know that there is a difference between lb-force and lb-mass
> (okay, all they know of is a simple "lb" which is based upon force of
> gravity at point of measurement, while lb-mass is a sort of artificial
> unit... don't mention slugs )

Yes, exactly; you started with another word game and then in the process 
dismissed it with a half-joke at the end.  Pounds came first, and 
rationalized systems (lbm/lbf, slug/lb, and even ridiculous retrofits 
like kg/kgf, completely turning the apple cart upside down) came 
afterwards.  The point is, the difference between the two is _totally 
irrelevant_ to those "unwashed masses" (and in the contexts we've been 
talking about).  Even NIST (among other) SI guidelines acknowledge that 
because, well, it's blatantly obvious.

That actually feeds right back into my earlier port about physics 
subsuming terminology to its own ends.  Making the distinction between 
mass and weight is critical for understanding physics, but not for 
everyday behavior involving measuring things in pounds; after all, in 
extending the popular concept of a "pound," different physicists made a 
distinction between mass and weight differently (i.e., the rationalized 
systems above) such that there is no accepted standard.  Of _course_ 
physicists have to make a distinction between mass and weight, and to do 
so with Imperial or American systems of units requires deciding which 
one a "pound" is, and what to do with the other unit.  But that's a 
physicist making distinctions that do not exist in the more general 
language, just the same as a physicist meaning something different by 
"free fall" than a layman.

But (say) dinging some Joe Schmo because he doesn't know that a pound is 
really a unit of force (or mass) is really just playing pointless word 
games.  As I said earlier, there are better ways to teach physics.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   Don't ever get discouraged / There's always / A better day
-- TLC
-- 
http://mail.python.org/mailman/listinfo/python-list


Sybase module 0.39pre1 released

2008-02-12 Thread Sébastien Sablé
WHAT IS IT:

The Sybase module provides a Python interface to the Sybase relational
database system.  It supports all of the Python Database API, version
2.0 with extensions.

** This version is a pre-release not intended for production use **

The module is available here:

http://downloads.sourceforge.net/python-sybase/python-sybase-0.39pre1.tar.gz

The module home page is here:

http://python-sybase.sourceforge.net/

MAJOR CHANGES SINCE 0.38:

* Added type mapping as proposed in
  http://www.uniqsys.com/~carsten/typemap.html by Carsten Haese
* Handle engineer notation of numbers in numeric
* Added support for CS_DATE_TYPE
* Added support for python Decimal objects in databuf
* Possibility to use ct_cursor for some requests
* Refactoring - merged Fetchers, CTCursor and CmdCursor in Cursor
* Refactored _cancel_cmd
* Added a prepare method to Cursor
* Additional 'locale' argument to connect and Connection to set the
  locale of the connection thanks to patch by Harri Pasanen
* Better compliance with DBAPI: returns None in nextset when no more
  set
* Added conversion from string to int when assigning to a CS_INT_TYPE
  DataBuf

BUGS CORRECTED SINCE 0.38:

* Corrected documentation about CS_CONTEXT Objects thanks to bug
  report by Derek Harland (close tracker 1748109)
* Corrected bug in close() if connection killed from outside thanks to
  patch by Derek Harland (close tracker 1746220)
* Corrected bug if inherit from Sybase.Connection thanks to patch by
  Derek Harland (close tracker 1719789)
* Optimization in fetchall - using fetchmany instead of fetchone to
  avoid locking time penalty, thanks to patch by Derek Harland (close
  tracker 1746908)
* Corrections to compile with bcp-support against freetds thanks to
  patch by Klaus-Martin Hansche (close tracker 1724088)
* Corrected documentation to compile with FreeTDS and Threads thanks
  to Derek Harland (close tracker 1709043)
* Corrected bug in databuf_alloc: Sybase reports the wrong maxlength
  for numeric type - verified with Sybase 12.5 - thanks to patch
  provided by Phil Porter
* Better detection of Sybase libraries
* the C API to datetime only exists since python 2.4 - disable
  datetime with previous versions
* Corrected python long handling (using CS_NUMERIC instead of CS_LONG
  which is unspecified)
* Corrected various compilation warnings (some linked to python 2.5)

The full ChangeLog is here:

https://python-sybase.svn.sourceforge.net/svnroot/python-sybase/tags/r0_39pre1/ChangeLog

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


Re: Python equivt of __FILE__ and __LINE__

2008-02-12 Thread Jeff Schwab
Gabriel Genellina wrote:
> En Tue, 12 Feb 2008 14:41:20 -0200, Jeff Schwab <[EMAIL PROTECTED]> 
> escribi�:
> 
>>  def line():
>>  try:
>>  raise Exception
>>  except:
>>  return sys.exc_info()[2].tb_frame.f_back.f_lineno
>>  def file():
>>  return inspect.currentframe().f_code.co_filename
> 
> It's not a good idea to shadow the file type; I'd suggest current_file 
> and current_line.
> 
> file() should return inspect.currentframe().f_back.f_code.co_filename, 
> else you're using the filename for file() itself, not the caller's

Both excellent points.

> And why the assymetry? Using try/except might help Jython, but that 
> should be an implementation detail of inspect.currentframe() anyway. 
> line() should just return inspect.currentframe().f_back.f_lineno

I suspect that Alain was just showing two ways to accomplish the same 
end, since he was giving a purely didactic example.  I dumbly copied his 
code.

What about the following?  Should the underscores be omitted from the 
method names, for consistency with inspect?

 # srcinfo.py
 import inspect
 import sys

 def currentline():
 return inspect.currentframe().f_back.f_lineno

 def currentfile():
 return inspect.currentframe().f_back.f_code.co_filename

 # client.py
 import srcinfo
 import sys

 debug = '-d' in sys.argv
 # ...
 if debug:
 print('reached %s:%d' %
 (srcinfo.currentfile(), srcinfo.currentline()))
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: IDLE: Clearing Breakpoints and Find with Help

2008-02-12 Thread W. Watson
I'll add a couple more. I forgot to mention that it seems impossible to do a 
Ctrl-F for a "Find" within the Help text. Is there another way? Is it 
possible to set IDLE so that it goes to another folder other than the 
install folder when I start it? Why doe both close and exit do the same 
thing? I would have thought Close meant to just close the open py file.

W. Watson wrote:
> How does one clear all breakpoints or even list where they are? When 
> looking at the source code, is it possible to tell which line number is 
> used for a statement. When I bring up the Help--Python Docs, the link to 
> how-to is broken.
> 
> Release 2.4.4.
> 

-- 
  Wayne Watson (Nevada City, CA)

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


Re: dream hardware

2008-02-12 Thread Tim Chase
>>> What is dream hardware for the Python interpreter?
> 
> The only "dream hardware" I know of is the human brain.  I have a 
> slightly used one myself, and it's a  pretty mediocre Python interpreter.

the human brain may be a pretty mediocre Python interpreter, but
darn if I don't miss

  >>> import dwim

on other platforms...

-tkc



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


How to access object attributes given a string

2008-02-12 Thread Santiago Romero
 Hi...

 I'm trying to guess how to access attributes of an existing object
given the attribute name in a string. I mean:

class Object:
self.x = 12
self.y = 20
self.name = "blah"

def ChangeAttribute( object, attribute, value ):
  # Insert here the code for object.attribute = value
  X

 Allowing this kind of calls:

 ChangeAttribute( object, "x", 200 )
 ChangeAttribute( object, "name", "my name" )

 Thanks.

PS: I need it for a concrete case in a game scripting language I'm
writing, so that I can call functions like "CHANGE_PLAYER_VALUES( "x",
100 )".
-- 
http://mail.python.org/mailman/listinfo/python-list


Unicode char replace

2008-02-12 Thread DiMar
Hi all,

I have this unicode string:

string = u'Macworld » Jobs 1 - Twitter 0'

and I want to replace the '»' (aka \xbb) char to '»'.
I've tried 2 ways:

1.
>>> string2 = string.replace('\\xbb','»')
u'Macworld \xbb Jobs 1 - Twitter 0'

2.
>>> import cgi
>>> string2 = cgi.escape(string).encode("ascii", "xmlcharrefreplace")
>>> string2
'Macworld » Jobs 1 - Twitter 0'

None of them gives me 'Macworld » Jobs 1 - Twitter 0'

Any idea?

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


Re: How to access object attributes given a string

2008-02-12 Thread [EMAIL PROTECTED]
On 12 fév, 21:35, Dennis Kempin <[EMAIL PROTECTED]> wrote:
> Santiago Romero schrieb:
(snip - others already answered)
> > PS: I need it for a concrete case in a game scripting language I'm
> > writing, so that I can call functions like "CHANGE_PLAYER_VALUES( "x",
> > 100 )".
>
> You are using a scripting language.. why not use python directly?

I can only second this suggestion - FWIW, there are already quite a
couple popular (and less popular) games using Python as a scripting
language.

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


Re: How to access object attributes given a string

2008-02-12 Thread Dennis Kempin
Santiago Romero schrieb:
>  Hi...
> 
>  I'm trying to guess how to access attributes of an existing object
> given the attribute name in a string. I mean:
> 
> class Object:
> self.x = 12
> self.y = 20
> self.name = "blah"
> 
> def ChangeAttribute( object, attribute, value ):
>   # Insert here the code for object.attribute = value
>   X

have a look a getattr and setattr
setattr(object, "name", "value")
> 
>  Allowing this kind of calls:
> 
>  ChangeAttribute( object, "x", 200 )
>  ChangeAttribute( object, "name", "my name" )
> 
>  Thanks.
> 
> PS: I need it for a concrete case in a game scripting language I'm
> writing, so that I can call functions like "CHANGE_PLAYER_VALUES( "x",
> 100 )".
You are using a scripting language.. why not use python directly? You 
can pass commands from the game console via the exec statement, and have 
the complete power of python in your game scripts

greetings,
Dennis

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


Re: Recursive generator

2008-02-12 Thread Paul Rubin
Paul Hankin <[EMAIL PROTECTED]> writes:
> def genDescendants(self):
> return chain([self], *[child.genDescendants()
> for child in self.children])

That is scary.  It generates an in-memory list the size of the
whole subtree, at every level.  Total memory consumption is maybe
even quadratic, depending on the tree shape, but even if it's
only linear, it's way ugly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Won't Start w/o Socket Error--Win XP

2008-02-12 Thread Mike Driscoll
On Feb 12, 2:18 pm, "W. Watson" <[EMAIL PROTECTED]> wrote:
> After simply trying to write a program with help(MakeQTE), a module, and
> having it fail with socket errors, I decided to restart IDLE, thinking I
> knew the cause. I'm now getting msgs like: "IDLE's subprocess didn't make
> connection. ... firewall may be blocking the connection." I doubt the FW
> connection. There's a small X warning dialog that says "Socket Error:
> Connection refused." Is there a way to reset IDLE?
> --
>   Wayne Watson (Nevada City, CA)
>
> Web Page: 

I sometimes get this message when one of my programs fails to shutdown
properly. I program almost exclusively in Windows, so I open Task
Manager and kill all instance of Python.exe to fix this problem. I
have seen ZoneAlarm flag IDLE when I first installed Python, so if you
upgraded it recently, the firewall may be an issue.

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


Re: Is there a web visitor counter available in Python ...

2008-02-12 Thread Dotan Cohen
On 12/02/2008, W. Watson <[EMAIL PROTECTED]> wrote:
> PHP. Well, that's a new one on me. Google gave me some idea of what it's
>  about, and I found some code on how to do it. It requires yet another
>  "programming language", which means finding the editor, etc.

Any text editor will do PHP. I personally use Kate. It's free, does
code highlighting (and folding, though I don't use that) and it has
internal SSH bookmarks. I've got 10 or so servers bookmarked right
inside Kate.

Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to access object attributes given a string

2008-02-12 Thread Santiago Romero

 This is faster:

http://www.sromero.org/python/zx_parseexec.py
http://www.sromero.org/python/test.par

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


Re: How to access object attributes given a string

2008-02-12 Thread Santiago Romero

 And the rest of the code:


#
def ExecParser_Exec( exec_type, code, game, debug=0 ):
   """
   Execute the previously "compiled" code:
   """
   code_level = 0

   #player = game.player
   #world = game.world

   # Take only opcodes for EXEC or EXEC2, deppending on exec_type
   exec_code = filter( lambda x : x[0] == exec_type, code )

   i = -1
   while 1:

  i += 1
  cmd_level, cmd, params = exec_code[i][1:4]
  spaces = " "*((code_level+1)*3)

  # End of script (appended by the compiler)


  if code_level == cmd_level:
 if cmd.startswith("IF ") or cmd.startswith("ELIF "):
# Get boolean funtion and evaluate it
# IF true:
#remove all ELIF/ELSE blocks until next ENDIF at the
same code level
#increase codelevel
# IF false:
#remove all code until next ELIF/ELSE/ENDIF at the
same code level
booleanf = cmd.split(" ")[1]
if debug: print "Checking ", spaces, cmd, params,
" (returned",
if ExecParser_CheckBoolean(booleanf, params):
   if debug: print "TRUE)"
   # Ignore lines until we find an ENDIF at the same code
level:
   done = 0
   j = i

   # Ignore all lines until we found the same code level
(next ELIF/ELSE/ENDIF):
   while not done:
  j += 1
  next_cmd_level, next_cmd = exec_code[j][1:3]
  if next_cmd_level==cmd_level or
next_cmd.startswith("END"):
 done = 1

   nextcond_line = j
   # Next branch is an endif, do nothing:
   if exec_code[nextcond_line][2].startswith("ENDIF") or \
  exec_code[nextcond_line][2] == "END":
  pass
   # Next branch is ELIF or ELSE: delete all until ENDIF
+cmd_level found
   else:
  done = 0
  while not done:
 if exec_code[nextcond_line]
[2].startswith("ENDIF") or \
exec_code[nextcond_line][2] == "END":
done = 1
 else:
del exec_code[nextcond_line]

   #  - Endif -> stop here
   code_level += 1
   i -= 1
else:
   if debug: print "FALSE)"
   done = 0
   # Ignore all lines in the current
   while not done:
  i += 1
  next_cmd_level, next_cmd = exec_code[i][1:3]
  if (next_cmd.startswith("ELIF ") or
next_cmd.startswith("ELSE")):
 i -= 1
 done = 1
  elif next_cmd.startswith("ENDIF") and
(next_cmd_level == code_level):
 done = 1
continue

  if cmd.startswith("ELSE") and cmd_level != -1:
 if debug: print "Entering ", spaces, "ELSE"
 code_level += 1

  elif cmd.startswith("ENDIF") and cmd_level != -1:
 if code_level > 0: code_level -= 1

  else:
 if code_level == cmd_level:
if cmd == "END":
   if debug: print "Executing", spaces, cmd
   return 1
else:
   if debug: print "Executing", " "*((code_level+1)*3),
cmd, params
   ExecParser_ExecOpcode( cmd, params, game, debug )
   return 1



#
def ExecParser_PrintCode( code, formatted=0 ):
   """
   Print code compiled/parsed by ExecParser_Parse().

   Prints opcodes (formatted=0) or indented source code (formatted=1)
   from a previously compiled/parsed opcode list.
   """

   if not formatted:
  # Print opcodes:
  print "\n> Compiled opcodes: <"
  print "\nExecType  CodeLevel  Opcode"
  print
"--"
  for c in code:
 print "%-8s %-8s" % (c[0],c[1]),
 for f in c[2:]:
if f != []: print f,
 print

   else:
  # Display source code indented
  print "\n> Formatted code (parsing opcodes): <"
  print "\nMain:"
  for i in code:
 spaces = " " * 3*(1+i[1])
 func = i[2]
 params = [ str(x) for x in i[3] ]
 if func == "REM":
print "%s%s %s" % (spaces, func, i[3][0])
 else:
if params != []:
   print "%s%s(" % (spaces, func),
   for i,p in enumerate(params):
  if i == len(params)-1: print "%s )" % (p)
  else:  print "%s," % (p),
else   :
   print "%s%s" % (spaces, func)



 That's all. I can put the .py and test.par files online if anyone
wants to test it and point me to the right direction on "how to code
your own small scripting language written in python scriptin

Re: Unicode char replace

2008-02-12 Thread DiMar
On 12 Feb, 22:11, Michael Goerz <[EMAIL PROTECTED]>
wrote:

> How about this?
> string.replace(u'\xbb', u'»')

Thanks, it works!!!

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


Re: Unicode char replace

2008-02-12 Thread Michael Goerz
DiMar wrote, on 02/12/2008 09:54 PM:
> Hi all,
> 
> I have this unicode string:
> 
> string = u'Macworld » Jobs 1 - Twitter 0'
> 
> and I want to replace the '»' (aka \xbb) char to '»'.
> I've tried 2 ways:
> 
> 1.
 string2 = string.replace('\\xbb','»')
> u'Macworld \xbb Jobs 1 - Twitter 0'
How about this?
string.replace(u'\xbb', u'»')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython vs CPython: faster in 1.6 times?

2008-02-12 Thread Fuzzyman
On Feb 12, 7:49 pm, [EMAIL PROTECTED] wrote:
> Fuzzyman:
>
> > Another interesting little benchmark of CPython and IronPython. Can't
> > see the code, but it looks like an implementation of the 11 queens
> > problem and IronPython comes out a clear winner on this one. (Looks
> > like no benchmark for psyco.)
>
> If you want a more reliable set of benchmarks, take all the shootout
> benchmarks, and try them on IronPython on dotnet, on CPython and on
> Psyco.
>

Go for it!

> Bye,
> bearophile

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


Re: dream hardware

2008-02-12 Thread Martin P. Hellwig
Bjoern Schliessmann wrote:
> Jeff Schwab wrote:
> 
>> The only "dream hardware" I know of is the human brain.
> 
> Nah. Too few storage capacity, and too slow and error-prone at
> simple calculations. The few special but very advanced features are
> all hard-wired to custom hardware, it's a real nightmare
> interfacing with it.
> 
> Regards,
> 
> 
> Björn
> 
Yes and don't try to do a direct interface if you are not absolutely, 
certainly, 100% sure, that the understanding of the API is mutual.

If not, be prepare to handle exceptions. Some you can ignore in a 
try/except clause like SyntaxError, MemoryError, RuntimeError and 
ReferenceError.

Others should be more interpreted like a progress indication, for 
example: ArithmeticError which may be raised like a plain StandardError.

But if you are lucky and get things more or less running watch out for
LookupError, BaseException, EnvironmentError and NameError, does can 
ruin your day and may even be fatal.

Absolutely fatal are: ValueError and TypeError, nothing really you can 
do against, even if you can catch these errors the program will usually 
still halt on a SystemExit.

And if you think that is the worst can happen, he!
There is still: AttributeError, ImportError, IOError and OverflowError.

And it the end if all that didn't happen there is quite a chance either 
you or the other go for a NotImplementedError.

If that didn't happen you always get after random() time an EOFError, 
however the good thing is that the process continues due to os.fork() 
(not available on all platforms).

Don't count on return(0).

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


Re: ways to declare empty set variable

2008-02-12 Thread bearophileHUGS
Paul Rubin:
> In 3.0 you may be able to say {,} but there is a contingent that would
> just as soon get rid of all that special syntax, so you'd say list()
> instead of [], dict() instead of {}, etc.

For Python 3.0 I'd like {} for the empty set and {:} for the empty
dict, but that idea was refused time ago, probably for some mental
backward compatibility. Missing that, I think dict() and set() and
tuple() and list() look better than using {} for the empty dict and
{/} for the empty set and () for empty tuple (or {} for the empty dict
and set() for the empty set).
dict() is a bit more verbose than {}, but it doesn't matter much. With
those dict(), set(), tuple(), list() the only little wart left is the
unary tuple literal: x,  that I don't like much, maybe I'd like tuple
to be identified by a pair of delimiters, maybe like [|x|] or
something like that as in the Fortress language. I don't know...

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


Double underscore names

2008-02-12 Thread Steven D'Aprano
Double-underscore names and methods are special to Python. Developers are 
prohibited from creating their own (although the language doesn't enforce 
that prohibition). From PEP 0008, written by Guido himself:

  __double_leading_and_trailing_underscore__: "magic" objects or
  attributes that live in user-controlled namespaces.  E.g. __init__,
  __import__ or __file__.  Never invent such names; only use them
  as documented.

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



But then there are modules like doctest, which uses the special double-
underscore name __test__.

There are times where I would like to create my own protocol, like the 
early sequence protocol: if an object has a __getitem__ method, it can be 
used with for loops. Python calls obj.__getitem__(i) with i starting at 0 
and increasing by one each time until it gets an IndexError exception.

This sequence protocol has been made partly obsolete by the iterator 
protocol, but you see the point: in the spirit of duck typing, having the 
ability to create a protocol is a Very Good Thing, and double leading and 
trailing underscore names are the accepted Python style for such special 
methods.

But the style guide says not to do that.

So I find myself conflicted. I'm aware that the style guide also says, 
know when to break the rules, but the examples given don't seem to apply 
to this case. The prohibition against inventing new double-underscore 
names like __parrot__ seems much stronger than the other style guides.

So what do folks think? I believe the protocol idiom ("look for a method 
called __parrot__ and then do something with it") is too useful and 
powerful to be ignored, but then if __parrot__ is reserved by Python, 
what to do?



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


Re: Can anyone help, please?

2008-02-12 Thread Paul McGuire
On Feb 12, 4:10 pm, maehhheeyy <[EMAIL PROTECTED]> wrote:
> Hi, right now I'm using Python and Multicast. I have the code for
> Multicast receiver on Python but I keep getting this error;
>
> File "", line 1, in bind
> error: (10049, "Can't assign requested address")
>
> The error is coming from this line;
> sock.bind ((MCAST_ADDR, MCAST_PORT))
>
> This is the code that I am using:
>
 
>
> I'm using the UDP multicast. Is there anything that I did wrong in
> this code?
>
> Can anyone please help me solve this problem?

I cannot help you directly, but googling for this error number and
message and chasing a few Usenet posts led me to "Beej's Guide to
Network Programming Using Internet Sockets" (http://beej.us/guide/
bgnet/), which someone else having your problem reported to have been
helpful (and it looks like it was recently updated).

Good luck,
-- Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive generator

2008-02-12 Thread Paul Hankin
On Feb 12, 10:17 pm, Ben C <[EMAIL PROTECTED]> wrote:
> On 2008-02-12, Paul Rubin <> wrote:
>
> > Paul Hankin <[EMAIL PROTECTED]> writes:
> >> def genDescendants(self):
> >>     return chain([self], *[child.genDescendants()
> >>         for child in self.children])
>
> > That is scary.  It generates an in-memory list the size of the
> > whole subtree, at every level.  Total memory consumption is maybe
> > even quadratic, depending on the tree shape, but even if it's
> > only linear, it's way ugly.
>
> This would probably be better (in terms of memory if not beauty):
>
>     def genDescendants(self):
>         return chain([self], *(child.genDescendants()
>             for child in self.children))

No, it's the same I think. When I wrote the original function, I
forgot that a generator using yield isn't the same as the same
function that returns an equivalent generator, because one is lazy and
the other isn't. To get the lazy behaviour back, you'd have to
write

def genDescendants(self):
for g in chain([self], *(child.genDescendants()
for child in self.children)):
yield g

But that's really ugly, so it looks like the simple version which
doesn't use itertools is the best.

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


Re: ways to declare empty set variable

2008-02-12 Thread bearophileHUGS
Ben Finney:
> I often use these myself. They're slightly more explicit, which can
> help when I want the reader not to have to think too much, and they're
> not particularly verbose because the names are well-chosen and short.

I'd like "list" be called "array" ;-)


> Note that '()' is syntactically null. Parentheses don't declare a
> tuple literal, commas do.

() is the literal for the empty tuple:

>>> t = ()
>>> type(t)

>>> (1, 2)[0:0]
()


>Parentheses are for grouping within expressions, not specifying type.<

I know, but I prefer Fortress in that regard, where each container has
its specific delimiter(s). In Python ( ) denote:
- expression grouping
- they are very often used to denote tuples (despite being necessary
only for the empty one)
- generators (x for x in ...).
The Boo language shows that () aren't that necessary for the
generators.


> I thought you said above that you preferred 'set()' for an empty set?
> I'm not sure what it is you're saying now.

Your language isn't my first one, and for me sometimes it's not easy
to express complex things :-) I can try again. Here are syntax pairs
(for empty dict && empty set) sorted from the (IMHO) the best one to
the worst one:
{:}   &&  {}
dict()   &&   set()
{}   &&  set()
{}   &&  {/}


> I think the harm done by trying to change it would be more
> than the harm done by leaving it in.

I agree.

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


Re: ways to declare empty set variable

2008-02-12 Thread bearophileHUGS
Ben Finney:
> Generator literals do not require the
> parens at all. However, the syntax of where the generator literal
> *appears* can make it necessary to explicitly group the expression
> using parens.

Have you taken a look at Boo?
In Python this isn't possible:
s = char for char in string.digits
You need ( ) there, while in Boo they aren't necessary there.

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


Re: Getting a Foothold on the IDLE Debugger

2008-02-12 Thread Nir
On Feb 12, 7:15 am, "W. Watson" <[EMAIL PROTECTED]> wrote:
> I thought I try to step through some simplePythoncode I wrote with IDLE
> using Debug. I'm at the early stages of learningPython. I used the shell to
> Run, then clicked on Debug->Debugger. That brought up a window with Stack
> and Locals checked. The buttons Go, Step, etc. are greyed out. How do I
> proceed?

Proceed to the Winpdb Python debugger.
http://www.winpdb.org

(Runs on Linux as well)

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


Re: How to broad cast ping address.......

2008-02-12 Thread Gabriel Genellina
En Mon, 11 Feb 2008 23:26:14 -0200, Steve Holden <[EMAIL PROTECTED]>  
escribió:

> Gabriel Genellina wrote:
>> En Mon, 11 Feb 2008 13:31:56 -0200, Manikandan R <[EMAIL PROTECTED]>
>> escribió:
>>
>>> I am working in Python scripting. I an need to find out all the
>>> device
>>> connected in the network. Just I planned to broad cast the ping address
>>
>> The simplest approach is to enumerate and ping each and every address in
>> your subnet and wait for the response, but consider that some hosts may
>> have been configured to not answer (and assuming you don't have a /8
>> network...)
>> There is an ICMP library in the Python cookbook
>>
> Don't I remember Microsoft withdrawing access to the raw packet driver
> on Windows XP, or was thing something they decided to ruin in Vaster?

Uh, yes, raw sockets are crippled on XP SP2. There is always  
subprocess.call("ping ...") - not very nice, of course

-- 
Gabriel Genellina

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


Re: ways to declare empty set variable

2008-02-12 Thread Ben Finney
[EMAIL PROTECTED] writes:

> In Python ( ) denote:
> - expression grouping
> - they are very often used to denote tuples (despite being necessary
> only for the empty one)
> - generators (x for x in ...).
> The Boo language shows that () aren't that necessary for the
> generators.

Now, that one I *am* sure of. Generator literals do not require the
parens at all. However, the syntax of where the generator literal
*appears* can make it necessary to explicitly group the expression
using parens.

>>> import string
>>> list(char for char in string.digits)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> char for char in string.digits
  File "", line 1
char for char in string.digits
   ^
SyntaxError: invalid syntax

So, it's not that parens are "used for generator literals". It's that
parens can be used to make grouping explicit where the syntax would
otherwise be ambiguous.

-- 
 \ "If you're a horse, and someone gets on you, and falls off, and |
  `\  then gets right back on you, I think you should buck him off |
_o__) right away."  -- Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-12 Thread Steve Holden
Ben Finney wrote:
[...]
> 
> Note that '()' is syntactically null. Parentheses don't declare a
> tuple literal, commas do. Parentheses are for grouping within
> expressions, not specifying type.
> 
Tell that to the interpreter:

 >>> type(())

 >>> tuple() is ()
True
 >>>

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: dream hardware

2008-02-12 Thread Ben Finney
Jeff Schwab <[EMAIL PROTECTED]> writes:

> *Oven-roasted* garlic?  OK, that's just weird.

Why, where do you roast your garlic?

-- 
 \"Crime is contagious ... if the government becomes a |
  `\lawbreaker, it breeds contempt for the law."  -- Justice Louis |
_o__) Brandeis |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-12 Thread Ben Finney
[EMAIL PROTECTED] writes:

> Ben Finney:
> > Generator literals do not require the parens at all. However, the
> > syntax of where the generator literal *appears* can make it
> > necessary to explicitly group the expression using parens.
> 
> Have you taken a look at Boo?
> In Python this isn't possible:
> s = char for char in string.digits
> You need ( ) there, while in Boo they aren't necessary there.

We seem to be saying the same thing in different ways.

-- 
 \   "Everyone is entitled to their own opinions, but they are not |
  `\ entitled to their own facts."  -- US Senator Pat Moynihan |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Unbuffered mode

2008-02-12 Thread Hamish Allan
Hi,

The man page for python says:

"-u Force stdin, stdout and stderr to be totally unbuffered."

However, when I try:

$ ssh localhost python -u
print 'hello, world'
[^D]
hello, world
$

Nothing happens until I send that EOF. I'm pretty sure it's not SSH
that's buffering because when I try:

$ ssh localhost bash
echo 'hello, world'
hello, world
[^D]
$

The 'hello, world' comes back immediately (I don't need to send the EOF).

I've also tried:

$ ssh localhost python -u
import sys
sys.stdout.write('hello, world\n')
sys.stdout.flush()
[^D]
hello, world
$

Again, nothing happens until I send the EOF. How can I get Python to
run over SSH unbuffered?

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


Re: Difficulty with "inconsistent use of tabs and spaces in indentation" in file called

2008-02-12 Thread ibloom
On Feb 11, 9:10 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Mon, 11 Feb 2008 21:57:00 -0200, ibloom <[EMAIL PROTECTED]> escribió:
>
> > My main problem is, I don't know where to find the file:
> >   File "", line 628
>
> > As in I don't know what code it is refering to by  ??
> > It isn't code that I wrote, its something from python or pyObjC
>
> Mmm, didn't you get my previous post? The call is inside the py2app  
> package. Quoting myself:
>
> >> : inconsistent use of tabs and spaces in indentation
> >> Traceback (most recent call last):
> >>   File "/Library/Frameworks/Python.framework/Versions/2.4/lib/
> >> python2.4/site-packages/py2app/py2app/util.py", line 13, in
> >> find_version
> >>     ast = compiler.parseFile(fn)
>
> > Put a print statement just above that line, to see which file triggers  
> > the
> > error.
>
> In case it wasn't clear, modify the file  
> /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packag 
> es/py2app/py2app/util.py,  
> around line 13, in the find_version function, adding this print statement:
>
>      print 'about to compile', fn
>      ast = compiler.parseFile(fn)
>
> The last line printed (in case there are many) should be the offending  
> filename.
>
> Of course you don't have to keep the modified library, this is just to  
> detect which file triggers the error. You should report this to the py2app  
> developers as well.
>
> --
> Gabriel Genellina

Gabriel, your the master.
Of course I didn't understand that py2app was trying to compile my own
python source code and when I switched to Xcode as my new editor, I
started mixing in tabs. So  was in fact my code. All I had to
do was change my preferences in Xcode, to generate spaces instead of
tabs, remove all of the offending tabs and voila. You've ended days of
frustrations. Thank you.

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


Re: dream hardware

2008-02-12 Thread castironpi
On Feb 12, 7:31 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Steven D'Aprano wrote:
> > On Tue, 12 Feb 2008 10:05:59 -0800, castironpi wrote:
>
> >> What is dream hardware for the Python interpreter?
>
> > I'm not sure that the Python interpreter actually does dream, but if it's
> > anything like me, it's probably a giant computer the size of a bus, made
> > out of broccoli and oven-roasted garlic, that suddenly turns into
> > Sylvester Stallone in a tutu just before my program returns its result.
>
> *Oven-roasted* garlic?  OK, that's just weird.

Is it anything special over multi-use cores/cpus/systa?

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


Re: Double underscore names

2008-02-12 Thread Steven Bethard
Steven D'Aprano wrote:
> Double-underscore names and methods are special to Python. Developers are 
> prohibited from creating their own (although the language doesn't enforce 
> that prohibition). From PEP 0008, written by Guido himself:
> 
>   __double_leading_and_trailing_underscore__: "magic" objects or
>   attributes that live in user-controlled namespaces.  E.g. __init__,
>   __import__ or __file__.  Never invent such names; only use them
>   as documented.
> 
> http://www.python.org/dev/peps/pep-0008/
> 
> But then there are modules like doctest, which uses the special double-
> underscore name __test__.
> 
> There are times where I would like to create my own protocol, like the 
> early sequence protocol: if an object has a __getitem__ method, it can be 
> used with for loops. Python calls obj.__getitem__(i) with i starting at 0 
> and increasing by one each time until it gets an IndexError exception.
> 
> This sequence protocol has been made partly obsolete by the iterator 
> protocol, but you see the point: in the spirit of duck typing, having the 
> ability to create a protocol is a Very Good Thing, and double leading and 
> trailing underscore names are the accepted Python style for such special 
> methods.
> 
> But the style guide says not to do that.
> 
> So I find myself conflicted. I'm aware that the style guide also says, 
> know when to break the rules, but the examples given don't seem to apply 
> to this case. The prohibition against inventing new double-underscore 
> names like __parrot__ seems much stronger than the other style guides.
> 
> So what do folks think? I believe the protocol idiom ("look for a method 
> called __parrot__ and then do something with it") is too useful and 
> powerful to be ignored, but then if __parrot__ is reserved by Python, 
> what to do?

I've come to believe that in most cases when you want to establish a new 
protocol, you'd be better off defining a generic function and 
overloading it rather than using the __magic__ attribute approach. See, 
for example, the simplegeneric module:

 http://pypi.python.org/pypi/simplegeneric/

Generic functions have the advantage that when one of your users 
discovers someone else's class that is missing support for your 
protocol, then can add it to that class without having to edit the code 
of the class (e.g. so that they can add a __magic__ attribute). Instead, 
they can just register an appropriate overload for that class.

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


Re: mmap and shared memory

2008-02-12 Thread Jeff Schwab
greg wrote:
> Carl Banks wrote:
>> In C you can use the mmap call to request a specific physical location
>> in memory (whence I presume two different processes can mmap anonymous
>> memory block in the same location)
> 
> Um, no, it lets you specify the *virtual* address in the process's
> address space at which the object you specify is to be mapped.
> 
> As far as I know, the only way two unrelated processes can share
> memory via mmap is by mapping a file. An anonymous block is known
> only to the process that creates it -- being anonymous, there's
> no way for another process to refer to it.

On POSIX systems, you can create a shared memory object without a file 
using shm_open.  The function returns a file descriptor.

> However, if one process is forked from the other, the parent
> can mmap an anonymous block and the child will inherit that
> mapping.
> 
> (I suppose if both processes had sufficient privileges they
> could map physical memory out of /dev/mem, but that would be
> *really* dangerous!)
> 
> -- 
> Greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Combinatorics

2008-02-12 Thread Raymond Hettinger
On Feb 11, 11:52 pm, Michael Robertson <[EMAIL PROTECTED]>
wrote:
> Where is the python equivalent of:
>
> http://search.cpan.org/~fxn/Algorithm-Combinatorics-0.16/Combinatoric...
>
> combinations (with and without repetition)
> variations (with and without repetition)
> permutations
> partitions
> derangements
> etc
>
> I'm guessing sage has this, but shouldn't something like this be part of
> the standard library (perhaps in C)?  I'd understand if derangements and
> partitions were excluded, but the standard combinatorics (replacement
> on/off, repetition on/off) would be quite nice.  It would also be
> helpful to have a general cartesian product function which combined
> elements from an arbitrary number of lists.
>
> It seems that questions for these algorithms occur too frequently.
>
> Am I wishing on a star?

FWIW, I'm adding cartesian product to the itertools module in Py2.6.


Raymond

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


Re: Difficulty with "inconsistent use of tabs and spaces in indentation" in file called

2008-02-12 Thread greg
ibloom wrote:
> Of course I didn't understand that py2app was trying to compile my own
> python source code and when I switched to Xcode as my new editor, I
> started mixing in tabs. So  was in fact my code.

Seems like py2app could be a bit friendlier about reporting
syntax errors in the code it's trying to compile!

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


Re: mmap and shared memory

2008-02-12 Thread greg
Carl Banks wrote:
> In C you can use the mmap call to request a specific physical location
> in memory (whence I presume two different processes can mmap anonymous
> memory block in the same location)

Um, no, it lets you specify the *virtual* address in the process's
address space at which the object you specify is to be mapped.

As far as I know, the only way two unrelated processes can share
memory via mmap is by mapping a file. An anonymous block is known
only to the process that creates it -- being anonymous, there's
no way for another process to refer to it.

However, if one process is forked from the other, the parent
can mmap an anonymous block and the child will inherit that
mapping.

(I suppose if both processes had sufficient privileges they
could map physical memory out of /dev/mem, but that would be
*really* dangerous!)

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


RE: Is there a way to use .NET DLL from Python

2008-02-12 Thread Dino Viehland
>>
>> Oh, I know what you mean.
>> But that was exactly the reason for having a .DLLs folder, isn't it?
>> When you place an assembly into this folder, you avoid having to write
>> this boilerplate code, and simply import the assembly as you would
>> with a normal python module. At least, that´s how it worked in
>> previous versions...
>No. You have always had to add references to assemblies before being
>able to use the namespaces they contain. You even have to do this with
>C# in Visual Studio.

This *should* work in both IronPython 1.x and IronPyton 2.0 - the catch though 
is that it's implemented in the default site.py we ship with.  So if you do the 
usual thing and use CPython's Lib directory you'll lose this feature w/o 
copying it over.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: call 'the following function' using decorators

2008-02-12 Thread castironpi
On Feb 12, 12:10 pm, [EMAIL PROTECTED] wrote:
> On Feb 12, 12:05 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
>
>
>
>
>
> > En Tue, 12 Feb 2008 15:20:32 -0200, <[EMAIL PROTECTED]> escribi�:
>
> > > I assert it's easier to write:
>
> > > start_new_thread( this_func )
> > > def thrA():
> > >     normal_suite()
>
> > > than
>
> > > def thrA():
> > >     normal_suite()
> > > start_new_thread( thrA )
>
> > > If you don't, stop reading.  If you do, accomplish it like this:
>
> > > @decwrap( start_new_thread, Link, ( 2, 3 ) )
> > > def anonfunc( a, b ):
> > >    print( a, b )
>
> > And I have to *guess* that start_new_thread is called?
> > A @threaded decorator might be useful, but the above isn't clear at all.
>
> > `import this` inside the interpreter.
>
> > --
> > Gabriel Genellina- Hide quoted text -
>
> > - Show quoted text -
>
> No new guessing.  It's called in
>
>                 ret= func( *ar2, **kwar2 )
>
> You might suggest a better name, though, than decwrap.  Something like
> @call_here
> with_specified_function.  What?  This probably goes under "Complex is
> better than complicated."
>
> It's not a typical decorator, but the f= g( f ) semantics come handily.- Hide 
> quoted text -
>
> - Show quoted text -

And Link could do well to call itself Blank/FuncBlank/NextFunc/
something clever
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Possible to tack on random stuff to objects?

2008-02-12 Thread Cruxic
That does the trick.  Thanks, Bruno.

On Feb 12, 1:23 am, Bruno Desthuilliers  wrote:
> Cruxic a écrit :
>
> > Is it possible to tack on arbitrary attributes to a python object?
>
> Depends on the object's class. In the common case it's possible but
> there are a couple cases - mostly builtin immutable types - where it's not.
>
> > For example:
>
> > s = 'nice 2 meet you'
> > s.isFriendly = True
>
> > In the above example Python complains on the second line with:
>
> > AttributeError: 'str' object has no attribute 'isFriendly'
>
> > Is there another way?
>
>  >>> class MyString(str): pass
> ...
>  >>> s = MyString("hello")
>  >>> s.is_friendly = True
>  >>> s
> 'hello'
>  >>>

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


Re: ways to declare empty set variable

2008-02-12 Thread Ben Finney
George Sakkis <[EMAIL PROTECTED]> writes:

> On Feb 12, 7:02 pm, Ben Finney <[EMAIL PROTECTED]>
> wrote:
> > That makes it even more a violation of
> > principle-of-least-astonishment that the '(foo)' form doesn't give
> > a one-element tuple literal.
> 
> The reason being, of course, that in this case '(1+2) * 3' would
> give a result several orders of magnitude more astonishing,

Yes, of course.

> so it's well worth the slight inconvenience of one-element tuples.

I didn't make it clear, but my expected solution to this is that '()'
should not create an empty tuple (as I was clearly assuming earlier in
this thread). An empty set can still be created with 'set()'.

That way, it becomes clearer that it's the comma separator, not the
parens, that create a tuple literal. With '()' creating an empty tuple
literal, and '(foo, bar)' creating a two-element tuple literal, it
remains that much harder to remember that '(foo)' does *not* create a
tuple.

-- 
 \   “Imagine a world without hypothetical situations.” —anonymous |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: ways to declare empty set variable

2008-02-12 Thread George Sakkis
On Feb 12, 7:02 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> Steve Holden <[EMAIL PROTECTED]> writes:
> > Ben Finney wrote:
> > [...]
>
> > > Note that '()' is syntactically null. Parentheses don't declare a
> > > tuple literal, commas do. Parentheses are for grouping within
> > > expressions, not specifying type.
>
> > Tell that to the interpreter:
>
> > >>> type(())
> > 
> > >>> tuple() is ()
> > True
>
> Well, knock me down with a kipper.
>
> That makes it even more a violation of principle-of-least-astonishment
> that the '(foo)' form doesn't give a one-element tuple literal.

The reason being, of course, that in this case '(1+2) * 3' would give
a result several orders of magnitude more astonishing, so it's well
worth the slight inconvenience of one-element tuples.

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


Re: *Oven-roasted* garlic?

2008-02-12 Thread Asun Friere
On Feb 13, 12:31 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> *Oven-roasted* garlic?  OK, that's just weird.

Not weird -- delicious!  Try doing it like this:  Take a whole knob
unpeeled dribble on some olive oil and black pepper and bake in a
medium oven for 10-15 mins.  Pull apart into individual cloves which
are pressed to squirt the now soft (and much less pungent) garlic
out.  Eat it on croutons, toast, the chicken you've just roasted at
the same time or whatever.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dream hardware

2008-02-12 Thread castironpi
On Feb 12, 4:51 pm, "Martin P. Hellwig" <[EMAIL PROTECTED]> wrote:
> Bjoern Schliessmann wrote:
> > Jeff Schwab wrote:
>
> >> The only "dream hardware" I know of is the human brain.
>
> > Nah. Too few storage capacity, and too slow and error-prone at
> > simple calculations. The few special but very advanced features are
> > all hard-wired to custom hardware, it's a real nightmare
> > interfacing with it.
>
> > Regards,
>
> > Björn
>
> Yes and don't try to do a direct interface if you are not absolutely,
> certainly, 100% sure, that the understanding of the API is mutual.
>
> If not, be prepare to handle exceptions. Some you can ignore in a
> try/except clause like SyntaxError, MemoryError, RuntimeError and
> ReferenceError.
>
> Others should be more interpreted like a progress indication, for
> example: ArithmeticError which may be raised like a plain StandardError.
>
> But if you are lucky and get things more or less running watch out for
> LookupError, BaseException, EnvironmentError and NameError, does can
> ruin your day and may even be fatal.
>
> Absolutely fatal are: ValueError and TypeError, nothing really you can
> do against, even if you can catch these errors the program will usually
> still halt on a SystemExit.
>
> And if you think that is the worst can happen, he!
> There is still: AttributeError, ImportError, IOError and OverflowError.
>
> And it the end if all that didn't happen there is quite a chance either
> you or the other go for a NotImplementedError.
>
> If that didn't happen you always get after random() time an EOFError,
> however the good thing is that the process continues due to os.fork()
> (not available on all platforms).
>
> Don't count on return(0).
>
> --
> mph

Fortunately, import curses comes linked in the assembly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Getting Wireless Signal Strength / Windows XP

2008-02-12 Thread williambattersea
Hello,

I'm looking for a way to get wireless signal strength on Windows XP
with Python. I see there's a library for Linux, but I can't find
anything for windows. However, I see that using WMI I can access it in
theory at least, using a query like "select
Ndis80211ReceivedSignalStrength from
MSNdis_80211_ReceivedSignalStrength where active=true"

(I got this from: http://www.dotnet247.com/247reference/msgs/36/181397.aspx)

I just began playing with the WMI library, but I can't get a hold of
the signal strength.

As far as I can tell, I should be able to get a handle on it with:

import wmi
c = wmi.WMI()

wql = "select Ndis80211ReceivedSignalStrength from
MSNdis_80211_ReceivedSignalStrength where active=true"

o = c.query(wql)

But I get an error.
Traceback (most recent call last):
  File "", line 1, in 
c.query("select Ndis80211ReceivedSignalStrength from
MSNdis_80211_ReceivedSignalStrength where active=true")
  File "C:\Python25\Lib\site-packages\wmi.py", line 889, in query
return [ _wmi_object (obj, instance_of, fields) for obj in
self._raw_query(wql) ]
  File "C:\Python25\lib\site-packages\win32com\client\util.py", line
83, in next
return _get_good_object_(self._iter_.next())
com_error: (-2147217392, 'OLE error 0x80041010', None, None)

Is this not available to me? Any ideas? Am I going about this in the
wrong way?

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


Re: bluetooth file transfer in python

2008-02-12 Thread Paul Boddie
On 12 Feb, 10:50, chartsoft <[EMAIL PROTECTED]> wrote:
> I am a teacher and need to set up a computer with a bluetooth dongle
> to poll for mobile phones with bluetooth switched on in the area then
> send them a jpg file.

I guess you'd use OBEX to send the file, specifically using the "push"
mode of OBEX. Various tools such as hcitool and sdptool (found on GNU/
Linux distributions) and their counterparts exposed by Python
libraries such as PyBluez [1] would be appropriate for scanning for
devices.

> I understand that python is capeable of this.
>
> 1.) is it worth learning python to do this or can someone out there do
> it for me for a v small fee?
>
> 2.) If I am going to do it can anyone give me pointers in the best way
> to do it so I do not spend hours wasting time.

I've previously done OBEX-related things, mostly fetching things from
mobile phones, using the obexftp program [2] which is part of the
OpenOBEX project [3]. Naturally, you can call the obexftp program from
Python and interpret the responses and exit codes using functions in
the os, popen2 and subprocess modules. I believe that obexftp also
supports "push" mode, but you could probably find something else
related to OpenOBEX if it does not.

Since Bluetooth communications are supported using sockets in GNU/
Linux distributions and in Python (provided that the Bluetooth support
is detected and configured), you could communicate with phones using
plain network programming, but this would probably require you to
implement the OBEX protocols yourself - not a straightforward task for
a number of reasons, including one I mention below. Thus, it's
probably easier to go with obexftp at least initially.

There are a number of awkward things with obexftp and OpenOBEX,
however. Some phones do not follow the "standards" and the maintainer
of OpenOBEX wouldn't or just didn't include support for various
deviating Sony Ericsson phones, for example, thus requiring me to
patch the library myself. Although there may be a Python wrapper for
OpenOBEX, it's easier to just call obexftp as mentioned above, but
this means that you're limited to what that program can do.

Finally, and most significantly, OBEX isn't a totally free standard:
if you didn't already get the standards documents while they were
freely available, you now have to sign up with the quaintly named
Infrared Data Association [4] - a "pay to play" organisation with
restrictive redistribution terms on their specifications. Although I'd
recommend that anyone doing brand new stuff with mobile devices just
uses real standards instead of OBEX, I doubt that you have the choice.

Anyway, I hope that this helps you understand the subject area a bit
more.

Paul

P.S. It does also occur to me that desktop environments like KDE have
Bluetooth controls which could be automated in some way in order to
send files, but I haven't investigated this at all.

[1] http://org.csail.mit.edu/pybluez/
[2] http://triq.net/obexftp.html
[3] http://dev.zuckschwerdt.org/openobex/
[4] http://www.irda.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


PyCon: deadline for hotel reservations and early-bird registration coming soon!

2008-02-12 Thread David Goodger

If you haven't registered for PyCon yet, now is the time!  The
early-bird registration deadline is February 20, one week away.  After
that, the price for registration will be going up.

http://us.pycon.org/2008/registration/

The deadline for hotel reservations at the conference rate is also
February 20.  Act now, because the regular rate is considerably
higher!

http://us.pycon.org/2008/registration/hotel/

A reminder to tutorial and talk speakers: you are responsible for your
own registration and hotel reservations.  So don't delay!

PyCon 2008: March 14-16, 2008 (& tutorials March 13, & sprints March 17-20)

David Goodger
PyCon 2008 Chair



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: ways to declare empty set variable

2008-02-12 Thread Ben Finney
Steve Holden <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> [...]
> >
> > Note that '()' is syntactically null. Parentheses don't declare a
> > tuple literal, commas do. Parentheses are for grouping within
> > expressions, not specifying type.
> >
> Tell that to the interpreter:
> 
> >>> type(())
> 
> >>> tuple() is ()
> True
> >>>

Well, knock me down with a kipper.

That makes it even more a violation of principle-of-least-astonishment
that the '(foo)' form doesn't give a one-element tuple literal.

-- 
 \   "If consumers even know there's a DRM, what it is, and how it |
  `\ works, we've already failed." —Peter Lee, Disney corporation, |
_o__) 2005 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Double underscore names

2008-02-12 Thread Christian Heimes
Steven D'Aprano wrote:
> So what do folks think? I believe the protocol idiom ("look for a method 
> called __parrot__ and then do something with it") is too useful and 
> powerful to be ignored, but then if __parrot__ is reserved by Python, 
> what to do?

The Python core claims all rights for __magic__ methods with a leading
and trailing double underscore. Of course Python won't stop you from
introducing your own magic names but you are on your own.

Future versions of Python may introduce a magic hook with the same name.
Be warned and don't complain ;)

Christian

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


Re: dream hardware

2008-02-12 Thread Warren Myers
/me no longer wishes to know about your dreams.

WMM

On Feb 12, 2008 4:56 PM, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Tue, 12 Feb 2008 10:05:59 -0800, castironpi wrote:
>
> > What is dream hardware for the Python interpreter?
>
> I'm not sure that the Python interpreter actually does dream, but if it's
> anything like me, it's probably a giant computer the size of a bus, made
> out of broccoli and oven-roasted garlic, that suddenly turns into
> Sylvester Stallone in a tutu just before my program returns its result.
>
>
> --
> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://warrenmyers.com
"God may not play dice with the universe, but something strange is
going on with the prime numbers." --Paul Erdős
"It's not possible. We are the type of people who have everything in
our favor going against us." --Ben Jarhvi, Short Circuit 2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a Foothold on the IDLE Debugger

2008-02-12 Thread Gabriel Genellina
En Tue, 12 Feb 2008 04:23:17 -0200, W. Watson <[EMAIL PROTECTED]>  
escribió:

> BTW, what's with the close and exit options on the File menu? They both  
> dump
> me out of IDLE. Odd.

Try File|New

> Any idea of whether I can "glue" the File-?Open to a
> particular folder?

Mmm, no. But it remembers the last used directory.

> Any other similar programs with a better user interface for beginners?

Try PyScripter (Windows only, I think). People say that SPE (Stani's  
Python Editor, multiplatform) is good too.

-- 
Gabriel Genellina

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


Re: dream hardware

2008-02-12 Thread castironpi
On Feb 12, 3:42 pm, Bjoern Schliessmann  wrote:
> Jeff Schwab wrote:
> > The only "dream hardware" I know of is the human brain.
>
> Nah. Too few storage capacity, and too slow and error-prone at
> simple calculations. The few special but very advanced features are
> all hard-wired to custom hardware, it's a real nightmare
> interfacing with it.
>
> Regards,
>
> Björn
>
> --
> BOFH excuse #373:
>
> Suspicious pointer corrupted virtual machine

Hold only one- recognition.
-- 
http://mail.python.org/mailman/listinfo/python-list


MatPy question

2008-02-12 Thread Xin Ye
I am using Python 2.5.  I wonder how to use MatPy in this version of Python.
 
Xin

No virus found in this outgoing message.
Checked by AVG Free Edition. 
Version: 7.5.516 / Virus Database: 269.20.2/1272 - Release Date: 2/11/2008 5:28 
PM
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-12 Thread greg
Erik Max Francis wrote:
> My point was, and still is, that if this question without further 
> context is posed to a generally educated laymen, the supposedly wrong 
> answer that was given is actually _correct_.

Except that they probably don't understand exactly how and
why it's correct. E.g. they will likely expect a 2kg hammer
to fall to the floor twice as fast as a 1kg hammer, which
isn't anywhere near to being true.

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


Re: dream hardware

2008-02-12 Thread castironpi
On Feb 12, 2:15 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Feb 12, 1:05 pm, [EMAIL PROTECTED] wrote:
>
> > What is dream hardware for the Python interpreter?
>
> A 10 GHz single core.
>
> (Dual core if doing lots of I/O.)
>
> Carl Banks

Handle a dual 6GHz core.  Code sometimes happens in order.  Other
times not, and then you can dual-pipeline / dual-bus.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-12 Thread Paul Rubin
"Sun" <[EMAIL PROTECTED]> writes:
> I was wondering why can't I use a format as "var = {} " to "var=list()" in 
> set variable, and decided not to  bother with it.

In 3.0 you may be able to say {,} but there is a contingent that would
just as soon get rid of all that special syntax, so you'd say list()
instead of [], dict() instead of {}, etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-12 Thread Gabriel Genellina
En Tue, 12 Feb 2008 12:04:43 -0200, Sun <[EMAIL PROTECTED]> escribió:
> "Chris" <[EMAIL PROTECTED]> wrote

> test = set()
> test
>> set([])
>
> yeah, that 's what I am looking for, thanks all for such prompt answers!
>
> I was wondering why can't I use a format as "var = {} " to "var=list()"  
> in
> set variable, and decided not to  bother with it.

Python 3.0 has set literals {1,2,3} (perhaps they become frozensets  
instead). But {} still is, and will be, an empty dict.
In reply to the n-th proposal to define a literal for empty sets, Guido  
van Rossum said, in python-ideas:

"All possible proposals have already been discussed at length. Really,  
writing set() isn't so bad. Get used to it."

http://mail.python.org/pipermail/python-ideas/2008-January/001316.html

-- 
Gabriel Genellina

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


Re: Unicode char replace

2008-02-12 Thread DiMar
> May I ask why?

Of course! I have to find that string into a list of strings. This
list includes one, using »
Thanks! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE Won't Start w/o Socket Error--Win XP

2008-02-12 Thread W. Watson
Thanks. That did the trick.

Mike Driscoll wrote:
> On Feb 12, 2:18 pm, "W. Watson" <[EMAIL PROTECTED]> wrote:
>> After simply trying to write a program with help(MakeQTE), a module, and
>> having it fail with socket errors, I decided to restart IDLE, thinking I
...
> 
> I sometimes get this message when one of my programs fails to shutdown
> properly. I program almost exclusively in Windows, so I open Task
> Manager and kill all instance of Python.exe to fix this problem. I
> have seen ZoneAlarm flag IDLE when I first installed Python, so if you
> upgraded it recently, the firewall may be an issue.
> 
> Mike

-- 
  Wayne Watson (Nevada City, CA)

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


Re: IDLE Won't Start w/o Socket Error--Win XP

2008-02-12 Thread Gabriel Genellina
En Tue, 12 Feb 2008 18:18:20 -0200, W. Watson <[EMAIL PROTECTED]>  
escribió:

> After simply trying to write a program with help(MakeQTE), a module, and
> having it fail with socket errors, I decided to restart IDLE, thinking I
> knew the cause. I'm now getting msgs like: "IDLE's subprocess didn't make
> connection. ... firewall may be blocking the connection." I doubt the FW
> connection. There's a small X warning dialog that says "Socket Error:
> Connection refused." Is there a way to reset IDLE?

 From the IDLE About box:

IDLE executes Python code in a separate process, which is restarted for  
each
Run (F5) initiated from an editor window.  The environment can also be
restarted from the Shell window without restarting IDLE.

(Personal firewall software may warn about the connection IDLE makes to its
subprocess using this computer's internal loopback interface.  This  
connection
is not visible on any external interface and no data is sent to or received
 from the Internet.)

 From the help:

Running without a subprocess:

If IDLE is started with the -n command line switch it will run in a
single process and will not create the subprocess which runs the RPC
Python execution server.  This can be useful if Python cannot create
the subprocess or the RPC socket interface on your platform.  However,
in this mode user code is not isolated from IDLE itself.  Also, the
environment is not restarted when Run/Run Module (F5) is selected.  If
your code has been modified, you must reload() the affected modules and
re-import any specific items (e.g. from foo import baz) if the changes
are to take effect.  For these reasons, it is preferable to run IDLE
with the default subprocess if at all possible.

-- 
Gabriel Genellina

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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-12 Thread Dotan Cohen
On 12/02/2008, Erik Max Francis <[EMAIL PROTECTED]> wrote:
> Dennis Lee Bieber wrote:
>
>  > On Tue, 12 Feb 2008 00:18:38 -0800, Erik Max Francis <[EMAIL PROTECTED]>
>  > declaimed the following in comp.lang.python:
>  >
>  >> equivalence for everyday usage and make no requirement of using the
>  >> "proper" units for mass (kg) vs. weight (N) for, say, buying things at
>  >
>  >   Ah, but in the US, the unwashed masses (as in "lots of people")
>  > don't even know that there is a difference between lb-force and lb-mass
>  > (okay, all they know of is a simple "lb" which is based upon force of
>  > gravity at point of measurement, while lb-mass is a sort of artificial
>  > unit... don't mention slugs )
>
>
> Yes, exactly; you started with another word game and then in the process
>  dismissed it with a half-joke at the end.  Pounds came first, and
>  rationalized systems (lbm/lbf, slug/lb, and even ridiculous retrofits
>  like kg/kgf, completely turning the apple cart upside down) came
>  afterwards.  The point is, the difference between the two is _totally
>  irrelevant_ to those "unwashed masses" (and in the contexts we've been
>  talking about).  Even NIST (among other) SI guidelines acknowledge that
>  because, well, it's blatantly obvious.
>
>  That actually feeds right back into my earlier port about physics
>  subsuming terminology to its own ends.  Making the distinction between
>  mass and weight is critical for understanding physics, but not for
>  everyday behavior involving measuring things in pounds; after all, in
>  extending the popular concept of a "pound," different physicists made a
>  distinction between mass and weight differently (i.e., the rationalized
>  systems above) such that there is no accepted standard.  Of _course_
>  physicists have to make a distinction between mass and weight, and to do
>  so with Imperial or American systems of units requires deciding which
>  one a "pound" is, and what to do with the other unit.  But that's a
>  physicist making distinctions that do not exist in the more general
>  language, just the same as a physicist meaning something different by
>  "free fall" than a layman.
>
>  But (say) dinging some Joe Schmo because he doesn't know that a pound is
>  really a unit of force (or mass) is really just playing pointless word
>  games.  As I said earlier, there are better ways to teach physics.

I recently had to tell my mother how to convert kilograms to pounds. I
told her that near the Earth's surface, she should multiply by 2.2.
Knowing me, she didn't even bother to ask about the "near the Earth's
surface" part. We've already established that that's where she and all
her friends live in other conversations.

Note that Google will give a calculator result for "1 kilogram in
pounds", but not for "1 kilogram in inches". I wonder why not? After
all, both are conversions of incompatible measurements, ie, they
measure different things.


Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to access object attributes given a string

2008-02-12 Thread Santiago Romero

 And the big functions:

 I imagine that the following is HORRIBLE in the pythonic-vision and
surely can be rewriten with a single map+reduce+filter + 200 lambdas
functions X-D, but I come from C and any advice on how to implement my
"simple scripting language" without using lex or yacc is welcome :)



#
def ExecParser_Parse( key, value, line, file ):
   """
   Parses an exec or exec2 line, generating a list of "opcodes".

   This function takes an exec= line from a OBJ file and parses it
   generating a list of "executable opcodes" in a format executable
   by ExecParser_Exec().

   The rules for this "small" language are:
   - Spaces and tabs are stripped.
   - Comments (starting by REM) are ignored.
   - A simple set of commands is available. Those commands modify
 some game variables or objects. As an example: PLAYSOUND(snd),
 plays the sound identified by the sound_tag "snd".
   - Commands must be separated by ";" characters.
   - Commands can receive parameters enclosed between ( and ) of
 types INT or STR.
   - Programmer can use "self" to refer to the current object in
 functions that accept an object or enemy text id.
   - Simple control flow is present with IF, ELIF, ELSE and ENDIF
 statements.
   - IF and ELIF statemens are followed by a BOOLEAN command, which
 will return 0 or 1.

   Example ('\' character wraps lines in the OBJ file):

  KILLOBJECT(coin);\
  REM Wait 5 seconds;\
  IF FLAG(5);\
 SLEEP(5);\
 PLAYERSAY(test,5);\
 SETMAP(10,10,top,5);\
 IF FLAG(6);\
NOP();\
SLEEP(7);\
 ELIF FLAG(7);\
NOP();\
SLEEP(9);\
 ELSE;\
SLEEP(999);\
 ENDIF;\
 IF FLAG_VALUE(7,1);\
CHANGESCREEN(start,10,100);\
PLAYERFACING(0);\
 ENDIF;\
  ENDIF;\
  SLEEP(12);\
  SLEEP(11);

   This function will parse the exec line and produce as output
opcodes in
   this format:

   [ type_of_exec, if_level, opcode, parameters ]

   type_of_exec = 1 for exec= lines, and 2 for exec2= lines.
   if_level is the current code "level" or scope. IF statements
increase
if_level and ENDIF statements decrease it.
   opcode and parameters are the function_name and the params for this
command.

   Example:

 ExecType  CodeLevel  Opcode and params
  --
  10KILLOBJECT ['coin']
  00REM ['Wait 5 seconds']
  10IF FLAG [5]
  11SLEEP [5]
  11PLAYERSAY ['test', 5]
  11SETMAP [10, 10, 'top', 5]
  11IF FLAG [6]
  12NOP
  12SLEEP [7]
  11ENDIF
  10ENDIF
  10END


   The function makes some small checkings, like:
count(IF)==count(ENDIFs),
   check number of arguments, argument type checking, validate command
   functions, and some others, but it does not cover all possible
syntax
   errors or typing mistakes.
   """

   reserved_words = {
   "SETMAP" : ( 4, "int", "int", "str", "int" ),
   "KILLOBJECT" : ( 1, "str" ),
   "ENABLEOBJECT" : ( 1, "str" ),
   "DISABLEOBJECT" : ( 1, "str" ),
   "PLAYSOUND" : ( 1, "str" ),
   "PLAYMUSIC" : ( 1, "str" ),
   "SLEEPCYCLES" : ( 1, "int" ),
   "SLEEP" : ( 1, "int" ),
   "SHOWTEXT" : ( 1, "str" ),
   "SHOWTEXTTIMED" : ( 2, "str", "int" ),
   "SHOWSCREEN" : ( 2, "str", "int" ),
   "CHANGESCREEN" : ( 3, "str", "int", "int" ),
   "ADDINVENTORY" : ( 1, "str" ),
   "REMOVEINVENTORY" : ( 1, "str" ),
   "OBJECTFACING" : ( 2, "str", "int" ),
   "PLAYERFACING" : ( 1, "int" ),
   "PLAYERSAY" : ( 2, "str", "int" ),
   "OBJECTSAY" : ( 3, "str", "str", "int" ),
   "SETFLAG" : (2, "int", "int" ),
   "INCFLAG" : (1, "int" ),
   "DECFLAG" : (1, "int" ),
   "DELEXEC" : (1, "int" ),
   "REM" : ( 0, ),
   "NOP" : ( 0, ),
   "END" : ( 0, ),
   "TRUE" : ( 0, ),
   "FALSE" : ( 0, ),
   "IF" : ( 0, ),
   "ELIF" : ( 0, ),
   "ELSE" : ( 0, ),
   "ENDIF" : ( 0, ),
   "FLAG" : ( 1, "int" ),
   "NOT_FLAG" : ( 1, "int" ),
   "FLAG_VALUE" : ( 2, "int", "int" ),
   "PLAYER_HAS" : ( 1, "str" ),
   "PLAYER_HAS_NOT" : ( 1, "str" ),
   "SCREEN_IS" : ( 1, "str" ),
   "SCREEN_IS_NOT" : ( 1, "str" )
   }


   #input is something like: "exec=COMMAND;COMMAND;COMMAND..."

   if key.upper() == "EXEC":  exec_type = 1
   code = []  # Resulting code

   if ";" in value:  commands = value.split(";")
   else: commands = list( value )

   # Filter empty lines
   commands = filter( lambda x: len(x) > 1, commands )

   code_level = level_inc = 0 # Current scope level
   found_if = found_elif = 0

   # Parse all commands in the input script
   for cmd_counter, cmd in enumerate(commands):

  if cmd == '': continue
  

Re: Unicode char replace

2008-02-12 Thread Martin v. Löwis
> string = u'Macworld » Jobs 1 - Twitter 0'
> 
> 
> None of them gives me 'Macworld » Jobs 1 - Twitter 0'
> 
> Any idea?

So I assume you *want* it to produce ». May I ask why?
I really recommend that you use » instead.

In any case, you need to define your own error handler, such as
the one in

http://herlock.com/ob/pythoncb/0596007973/chp-1-sect-23.html

HTH,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to access object attributes given a string

2008-02-12 Thread Santiago Romero

 Before I reinvent the wheel, I'm going to post the code.

 Feel free to give any advice, and think that I'm new to python, it's
only 1 month since I began programming in python "seriously" (up to
that moment, I wrote just a few log-text parsing system administration
scripts to speed up some old bash scripts).

 First of all, my currently test file:

KILLOBJECT(coin);\
REM Wait 5 seconds;\
IF FLAG(5);\
   SLEEP(5);\
   PLAYERSAY(test,5);\
   SETMAP(10,10,top,5);\
   IF FLAG(6);\
  NOP();\
  SLEEP(7);\
   ELIF FLAG(7);\
  NOP();\
  SLEEP(9);\
   ELSE;\
  SLEEP(999);\
   ENDIF;\
   IF FLAG_VALUE(7,1);\
  CHANGESCREEN(start,10,100);\
  PLAYERFACING(0);\
   ELSE;\
  PLAYERFACING(1);\
   ENDIF;\
ENDIF;\
SLEEP(12);\
SLEEP(11)

 And the parse code:


if __name__ == "__main__":
   """
   To test: create an example file test.par with language commands.
   """

   numline = 0
   try:
  fp = open("test.par")
   except:
  print "Error, cant open test.par"
  import sys
  sys.exit(0)

   while 1:
  # Read line, ignore comments and stop with EOF
  numline += 1
  line = fp.readline()
  if line == '': break

  line = line.strip()
  startline = numline
  # Join lines splitted with \ in the text file
  while line.endswith("\\"):
 next_line = fp.readline()
 if next_line == '': break
 if next_line.strip() == '': continue
 numline += 1
 next_line = next_line.strip()
 line = line[:-1] + next_line

  code = ExecParser_Parse( "exec", line, startline, "test.par" )

   for i in 0, 1:
  ExecParser_PrintCode( code, i )
  print
   ExecParser_Exec( 1, code, 0, debug=1 )


 And this is the output:

> Compiled opcodes: <

ExecType  CodeLevel  Opcode
--
10KILLOBJECT ['coin']
00REM ['Wait 5 seconds']
10IF FLAG [5]
11SLEEP [5]
11PLAYERSAY ['test', 5]
11SETMAP [10, 10, 'top', 5]
11IF FLAG [6]
12NOP
12SLEEP [7]
11ELIF FLAG [7]
12NOP
12SLEEP [9]
11ELSE
12SLEEP [999]
11ENDIF
11IF FLAG_VALUE [7, 1]
12CHANGESCREEN ['start', 10, 100]
12PLAYERFACING [0]
11ELSE
12PLAYERFACING [1]
11ENDIF
10ENDIF
10SLEEP [12]
10SLEEP [11]
10END


> Formatted code (parsing opcodes): <

Main:
   KILLOBJECT( coin )
   REM Wait 5 seconds
   IF FLAG( 5 )
  SLEEP( 5 )
  PLAYERSAY( test, 5 )
  SETMAP( 10, 10, top, 5 )
  IF FLAG( 6 )
 NOP
 SLEEP( 7 )
  ELIF FLAG( 7 )
 NOP
 SLEEP( 9 )
  ELSE
 SLEEP( 999 )
  ENDIF
  IF FLAG_VALUE( 7, 1 )
 CHANGESCREEN( start, 10, 100 )
 PLAYERFACING( 0 )
  ELSE
 PLAYERFACING( 1 )
  ENDIF
   ENDIF
   SLEEP( 12 )
   SLEEP( 11 )
   END

Executing KILLOBJECT ['coin']
Checking  IF FLAG [5]  (returned TRUE)
ExecutingSLEEP [5]
ExecutingPLAYERSAY ['test', 5]
ExecutingSETMAP [10, 10, 'top', 5]
Checking IF FLAG [6]  (returned FALSE)
Checking ELIF FLAG [7]  (returned FALSE)
Entering ELSE
Executing   SLEEP [999]
Checking IF FLAG_VALUE [7, 1]  (returned FALSE)
Entering ELSE
Executing   PLAYERFACING [1]
Executing SLEEP [12]
Executing SLEEP [11]
Executing END
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to access object attributes given a string

2008-02-12 Thread Gary Herron
Santiago Romero wrote:
>  Hi...
>
>  I'm trying to guess how to access attributes of an existing object
> given the attribute name in a string. I mean:
>
> class Object:
> self.x = 12
> self.y = 20
> self.name = "blah"
>
> def ChangeAttribute( object, attribute, value ):
>   # Insert here the code for object.attribute = value
>   X
>
>  Allowing this kind of calls:
>
>  ChangeAttribute( object, "x", 200 )
>  ChangeAttribute( object, "name", "my name" )
>
>  Thanks.
>
> PS: I need it for a concrete case in a game scripting language I'm
> writing, so that I can call functions like "CHANGE_PLAYER_VALUES( "x",
> 100 )".
>   
You want getattr and setattr:
setattr(ob, 'blah', 123)
and
getattr(ob, 'blah')

Gary Herron

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


Re: Is there a web visitor counter available in Python ...

2008-02-12 Thread subeen
Well, you don't need to worry about code, you can just copy paste the
code of the hit counters available for free.

In my blog, http://love-python.blogspot.com/ I am using two type of
hit counters (both are free). You can try them. They generate code
that you just paste in the source code of your website.


Regards,
Subeen.



On Feb 12, 11:37 am, "W. Watson" <[EMAIL PROTECTED]> wrote:
> PHP. Well, that's a new one on me. Google gave me some idea of what it's
> about, and I found some code on how to do it. It requires yet another
> "programming language", which means finding the editor, etc.
>
>
>
> Jon "Fluffy" Saul wrote:
> > On Feb 11, 2008 9:21 PM, W. Watson <[EMAIL PROTECTED]> wrote:
> >> ... that is free for use without advertising that I can use on my web 
> >> pages?
> >> I have no idea is suitable for this. My knowledge of Python is somewhat
> >> minimal at this point. Maybe Java is better choice.
>
> >> --
> >>   Wayne Watson (Nevada City, CA)
>
> >> Web Page: 
> >> --
> >>http://mail.python.org/mailman/listinfo/python-list
>
> > PHP would be the best choice.
> > Simple and advanced PHP hit counters can be found with a search of Google.
> > "PHP hit counter", etc.
>
> --
>   Wayne Watson (Nevada City, CA)
>
> Web Page: 

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


Re: How to access object attributes given a string

2008-02-12 Thread Chris
On Feb 12, 10:25 pm, Santiago  Romero <[EMAIL PROTECTED]> wrote:
>  Hi...
>
>  I'm trying to guess how to access attributes of an existing object
> given the attribute name in a string. I mean:
>
> class Object:
> self.x = 12
> self.y = 20
> self.name = "blah"
>
> def ChangeAttribute( object, attribute, value ):
>   # Insert here the code for object.attribute = value
>   X
>
>  Allowing this kind of calls:
>
>  ChangeAttribute( object, "x", 200 )
>  ChangeAttribute( object, "name", "my name" )
>
>  Thanks.
>
> PS: I need it for a concrete case in a game scripting language I'm
> writing, so that I can call functions like "CHANGE_PLAYER_VALUES( "x",
> 100 )".

   help(setattr)

Help on built-in function setattr in module __builtin__:

setattr(...)
setattr(object, name, value)

Set a named attribute on an object; setattr(x, 'y', v) is
equivalent to
``x.y = v''.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dream hardware

2008-02-12 Thread Carl Banks
On Feb 12, 1:05 pm, [EMAIL PROTECTED] wrote:
> What is dream hardware for the Python interpreter?

A 10 GHz single core.

(Dual core if doing lots of I/O.)


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


Re: Combinatorics

2008-02-12 Thread [EMAIL PROTECTED]
On Feb 12, 1:52 am, Michael Robertson <[EMAIL PROTECTED]> wrote:
> Where is the python equivalent of:
>
> http://search.cpan.org/~fxn/Algorithm-Combinatorics-0.16/Combinatoric...
>
> combinations (with and without repetition)
> variations (with and without repetition)
> permutations
> partitions
> derangements
> etc
>
> I'm guessing sage has this, but shouldn't something like this be part of
> the standard library (perhaps in C)?  I'd understand if derangements and
> partitions were excluded, but the standard combinatorics (replacement
> on/off, repetition on/off) would be quite nice.  It would also be
> helpful to have a general cartesian product function which combined
> elements from an arbitrary number of lists.
>
> It seems that questions for these algorithms occur too frequently.
>
> Am I wishing on a star?

Did you know that you can do a Cartesian Product
(permutations with replacement) using SQL?

And that things like Combinations with Replacement,
Permutaions withour Replacement and Combinations
without Replacement are simple Cartesian Product
subsets which can be seleceted via a WHERE clause?

For example:

# unjoined tables create a Cartesian Product

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
create table letter(n);
""")

letters = [('a'),('b'),('c'),('d'),('e'),('f'),('g'),('h')]

cur.executemany("""
INSERT INTO letter(n)
VALUES  (?);"""
, letters)

# note: no JOIN clause
cur.execute("""
SELECT letter.*,
   letter1.*
FROM   letter, letter AS letter1
ORDER BY   letter.n;
""")

cartesian_product = cur.fetchall()

for i in cartesian_product:
   print i[0]+i[1],

##aa ab ac ad ae af ag ah
##ba bb bc bd be bf bg bh
##ca cb cc cd ce cf cg ch
##da db dc dd de df dg dh
##ea eb ec ed ee ef eg eh
##fa fb fc fd fe ff fg fh
##ga gb gc gd ge gf gg gh
##ha hb hc hd he hf hg hh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic method parameter access?

2008-02-12 Thread Chris
On Feb 12, 9:38 pm, Dennis Kempin <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I have a set of some objects. With these objects I want to call a Python
> method. But the writer of the method shall have the option to select
> from these objects as method parameter.
>
> At the moment i use the following way to call a method with the a or b
> or both parameter.
>
> try:
>  method(a=value)
> except TypeError:
>  try:
>  method(b=value)
>  except TypeError:
> method(a=value, b=value)
>
> This is getting really complex the more optional parameters I want to
> provide.
> Is there any other way to access the method parameter?
>
> Thanks in advance,
> Dennis

Instead of having set variable names, why not pass a dictionary ?

def method(**kwargs):
print kwargs

method(a='test1')
{'a': 'test1'}

method(a='test1', b='test2')
{'a': 'test1', 'b': 'test2'}

You can unpack the args once you are in your method to determine what
you need to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython vs CPython: faster in 1.6 times?

2008-02-12 Thread bearophileHUGS
Fuzzyman:
> Another interesting little benchmark of CPython and IronPython. Can't
> see the code, but it looks like an implementation of the 11 queens
> problem and IronPython comes out a clear winner on this one. (Looks
> like no benchmark for psyco.)

If you want a more reliable set of benchmarks, take all the shootout
benchmarks, and try them on IronPython on dotnet, on CPython and on
Psyco.

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


Re: dream hardware

2008-02-12 Thread castironpi
On Feb 12, 1:03 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> >>> What is dream hardware for the Python interpreter?
>
> > The only "dream hardware" I know of is the human brain.  I have a
> > slightly used one myself, and it's a  pretty mediocre Python interpreter.
>
> the human brain may be a pretty mediocre Python interpreter, but
> darn if I don't miss
>
>   >>> import dwim
>
> on other platforms...
>
> -tkc

You ever go to bars?  import dwis.  sigh()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IronPython vs CPython: faster in 1.6 times?

2008-02-12 Thread Fuzzyman
On Feb 5, 5:31 pm, dmitrey <[EMAIL PROTECTED]> wrote:
> Hi all,
> the urlhttp://torquedev.blogspot.com/2008/02/changes-in-air.html
> (blog of a game developers)
> saysIronPythonis faster than CPython in 1.6 times.
> Is it really true?
> If yes, what areIronPythondrawbacks vs CPython?
> And is it possible to useIronPythonin Linux?
>
> D.

Another interesting little benchmark of CPython and IronPython. Can't
see the code, but it looks like an implementation of the 11 queens
problem and IronPython comes out a clear winner on this one. (Looks
like no benchmark for psyco.)

http://www.sokoide.com/index.php?itemid=1427

Michael
http://www.manning.com/foord
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C function in a Python context

2008-02-12 Thread castironpi
On Feb 9, 3:04 pm, [EMAIL PROTECTED] wrote:
> On Feb 9, 1:48 pm, [EMAIL PROTECTED] wrote:
>
>
>
>
>
> > To write quick C things that Python won't do up to speed.  So it's got
> > a redundancy.
>
> > import ext
> > extA= ext.Ext()
> > extA[ 'enumfactors' ]= r"""
> >     int enumfactors( int a, const char* sep ) {
> >         int ret= 0, i;
> >         for( i= 1; i<= a; i++ ) {
> >             if( a% i== 0 ) {
> >                 ret+= 1;
> >                 if( i> 1 ) {
> >                     printf( "%s", sep );
> >                 }
> >                 printf( "%i", i );
> >             }
> >         }
> >         printf( "\n" );
> >         return ret;
> >     }
> >     """, ("i","i","s")
>
> > factorsn= extA.enumfactors( 209677683, ', ' )
> > print( "%i factors total."% factorsn )
>
> > import sys
> > sys.exit()
>
> > 1, 3, 23, 69, 131, 393, 3013, 9039, 23197, 69591, 533531, 1600593,
> > 3038807, 9116
> > 421, 69892561, 209677683
> > 16 factors total.
>
> '''Prototype implementation, slightly rigid.  If anyone knows how to
> compile and link without intermediate object file, and from a string,
> memory, or stdin, let me know.  Change first four lines.  If you are
> not using gcc, look at regenpyd().'''
>
> compilercommand=    'c:/programs/mingw/bin/gcc'
> pythondll=          'python30'
> pythonpathinclude=  'c:/programs/python/include'
> pythonpathlibs=     'c:/programs/python/libs'
>
> class Ext:
>     strctypes= { 'i': 'int', 's': 'const char*' }
>     class ExtElem:
>         def __init__( self, name, code, types ):
>             self.name, self.code= name, code
>             self.types= types
>     def __init__( self ):
>         self.__dict__[ 'exts' ]= []
>     def regenc( self ):
>         extcode= open( 'extcode.c', 'w' )
>         wr= extcode.write
>         wr( '#include <%s'% pythonpathinclude )
>         wr( '/Python.h>\n\n' )
>         for ext in self.exts:
>             wr( ext.code )
>             wr( '\n' )
>         for ext in self.exts:
>             wr( 'static PyObject *\n' )
>             wr( 'extcode_%s'% ext.name )
>             wr( '(PyObject *self, ' )
>             wr( 'PyObject *args) {\n' )
>             wr( '\t%s result;\n'%
>                 Ext.strctypes[ext.types[0]] )
>             for i, type in enumerate( ext.types[1:] ):
>                 wr( '\t%s arg%i;\n'%
>                     ( Ext.strctypes[type], i ) )
>             wr( '\tPyArg_ParseTuple(args, "' )
>             wr( ''.join( ext.types[1:] ) )
>             wr( '"' )
>             for i, type in enumerate( ext.types[1:] ):
>                 wr( ', &arg%i'% i )
>             wr( ' );\n' )
>             wr( '\tresult= %s( '% ext.name )
>             wr( ', '.join( [ 'arg%i'% i for i
>                 in range( len( ext.types[1:] ) ) ] ) )
>             wr( ' );\n' )
>             wr( '\treturn Py_BuildValue' )
>             wr( '( "%s", result );\n'% ext.types[0] )
>             wr( '}\n\n' )
>         wr( 'static PyMethodDef ExtcodeMethods[] = {\n' )
>         for ext in self.exts:
>             wr( '\t{ "%s", extcode_%s, '%
>                             ( ext.name, ext.name ) )
>             wr( 'METH_VARARGS, "" },\n' )
>         wr( '\t{NULL, NULL, 0, NULL}\n' )
>         wr( '};\n\n' )
>         wr( 'PyMODINIT_FUNC\n' )
>         wr( 'initextcode(void) {\n' )
>         wr( '\t(void) Py_InitModule' )
>         wr( '("extcode", ExtcodeMethods);\n' )
>         wr( '}\n\n' )
>         extcode.close()
>     def regenpyd( self ):
>         import os, os.path
>         if os.path.exists( 'extcode.pyd' ):
>             os.remove( 'extcode.pyd' )
>         import subprocess
>         retcompile= subprocess.call(
>             '%s extcode.c -c -I%s'%
>             ( compilercommand, pythonpathinclude ) )
>         assert not retcompile, 'Compiler error'
>         retlink= subprocess.call(
>             '%s -shared extcode.o -o extcode.pyd -L%s -l%s'
>             % ( compilercommand, pythonpathlibs,
>             pythondll ) )
>         assert not retlink, 'Linker error'
>         os.remove( 'extcode.o' )
>         os.remove( 'extcode.c' )
>     def __setitem__( self, key, value ):
>         code, types= value
>         self.exts.append( Ext.ExtElem( key, code, types ) )
>         self.regenc()
>         self.regenpyd()
>         import extcode
>         setattr( self, key, getattr( extcode, key ) )- Hide quoted text -
>
> - Show quoted text -

This is- and returns a list, of the enumerated factors.  Is it
starting to get bulky.


import ext
extA= ext.Ext()
extA[ 'enumfactors' ]= r"""
#include 
#include 
using namespace std;
PyObject* enumfactors( int a, const char* sep ) {
string fmt= "[";
vector< long > resv;
for( int i= 1; i<= a; i++ ) {
if( a% i== 0 ) {
resv.push_back( i );
fmt.append( "i" );
if( i> 1 ) {
printf( "%s", sep );
}
printf( "%i", i );
}
}

Re: dream hardware

2008-02-12 Thread castironpi
On Feb 12, 12:31 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> > On Feb 12, 2008 1:05 PM,  <[EMAIL PROTECTED]> wrote:
> >> What is dream hardware for the Python interpreter?
> Warren Myers wrote:
>
>  > A Cray?
>  >
>  > What are you trying to do? "dream" hardware is a very wide question.
>
> The only "dream hardware" I know of is the human brain.  I have a
> slightly used one myself, and it's a  pretty mediocre Python interpreter.

Someone mentioned language-specific chips earlier.  Or, if you could
dedicate processes on certain chips or cores.  Paralell, serial, cache
size, pick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python equivt of __FILE__ and __LINE__

2008-02-12 Thread Jeff Schwab
Gabriel Genellina wrote:
> En Tue, 12 Feb 2008 16:20:12 -0200, Jeff Schwab <[EMAIL PROTECTED]> 
> escribió:
> 
>> What about the following?  Should the underscores be omitted from the
>> method names, for consistency with inspect?
> 
> I prefer the names_with_underscore, the "current" style recommended by 
> PEP8 http://www.python.org/dev/peps/pep-0008/ but hurry up before it 
> changes!

Right on.  Won't I feel silly if the inspect.currentmethods() ever get 
renamed,for consistency with the PEP?

It still would be nice to have syntax as clean as __FILE__ and __LINE__. 
  Has anybody already written a module of syntactic sugar around 
inspect?  These things are mega-useful while debugging, especially for 
those of us who prefer in-language libraries to separate debuggers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python equivt of __FILE__ and __LINE__

2008-02-12 Thread Gabriel Genellina
En Tue, 12 Feb 2008 16:20:12 -0200, Jeff Schwab <[EMAIL PROTECTED]>  
escribió:

> What about the following?  Should the underscores be omitted from the
> method names, for consistency with inspect?

I prefer the names_with_underscore, the "current" style recommended by  
PEP8 http://www.python.org/dev/peps/pep-0008/ but hurry up before it  
changes!

-- 
Gabriel Genellina

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


Re: dream hardware

2008-02-12 Thread Jeff Schwab

> On Feb 12, 2008 1:05 PM,  <[EMAIL PROTECTED]> wrote:
>> What is dream hardware for the Python interpreter?

Warren Myers wrote:
 > A Cray?
 >
 > What are you trying to do? "dream" hardware is a very wide question.

The only "dream hardware" I know of is the human brain.  I have a 
slightly used one myself, and it's a  pretty mediocre Python interpreter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classobj() question

2008-02-12 Thread Roland Hedberg
Peter Otten wrote:
> Roland Hedberg wrote:
> 
>> I'm in the position that I have a bunch of classes defined before hand
>> and then in some special circumstances I need to dynamically create a
>> class that has a number of the static classes as parents.
>>
>> So I thought I could use classobj() from the new module, it seem exactly
>> what I wanted.
>>
>> But, it doesn't perform as I expected.
>>
>> I've made an extremely simple program to try to show what I mean and
>> what I expected. It's attached to this mail.
>>
>> So, how should I have done it ?
> 
> (1) You are working with newstyle classes -- use type() instead of
> new.classobj().
> (2) Your inheritance tree has diamonds in it -- call baseclass initializers
> using super() in *all* classes, e. g:
> 
> class A(object):
> def __init__(self):
> super(A, self).__init__()
> # your code
> 
> Python will then take care that every initializer in the inheritance tree is
> called once.

Thanks Peter, your hints was exactly what I needed. Now it works !

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


Re: ways to declare empty set variable

2008-02-12 Thread George Sakkis
On Feb 12, 9:30 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> George Sakkis <[EMAIL PROTECTED]> writes:
> > On Feb 12, 7:02 pm, Ben Finney <[EMAIL PROTECTED]>
> > wrote:
> > > That makes it even more a violation of
> > > principle-of-least-astonishment that the '(foo)' form doesn't give
> > > a one-element tuple literal.
>
> > The reason being, of course, that in this case '(1+2) * 3' would
> > give a result several orders of magnitude more astonishing,
>
> Yes, of course.
>
> > so it's well worth the slight inconvenience of one-element tuples.
>
> I didn't make it clear, but my expected solution to this is that '()'
> should not create an empty tuple (as I was clearly assuming earlier in
> this thread). An empty set can still be created with 'set()'.
>
> That way, it becomes clearer that it's the comma separator, not the
> parens, that create a tuple literal. With '()' creating an empty tuple
> literal, and '(foo, bar)' creating a two-element tuple literal, it
> remains that much harder to remember that '(foo)' does *not* create a
> tuple.

*shrug* I've never been bitten by this. From a purist POV I see your
point but I guess it's one of the things you learn when you first pick
up Python and never have to think again.

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


Re: dream hardware

2008-02-12 Thread Warren Myers
A Cray?

What are you trying to do? "dream" hardware is a very wide question.

WMM

On Feb 12, 2008 1:05 PM,  <[EMAIL PROTECTED]> wrote:
> What is dream hardware for the Python interpreter?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://warrenmyers.com
"God may not play dice with the universe, but something strange is
going on with the prime numbers." --Paul Erdős
"It's not possible. We are the type of people who have everything in
our favor going against us." --Ben Jarhvi, Short Circuit 2
-- 
http://mail.python.org/mailman/listinfo/python-list


infinite loop when starting pdb

2008-02-12 Thread AndrewStone
I am starting pdb.pm() in an embedded, multithreaded python PyCrust
shell (wx toolkit) --  but other than that it's COMPLETELY
vanilla :-)) and pdb is getting stuck in an infinite loop, sucking
down all CPU.  I never get the pdb prompt.  Anyone have any experience
with this?  I'm pretty new at threading under embedded Python, so
don't ignore the obvious.  Everything except pdb is working which
seems to be to be very strange.

Here are a few stack traces:

Thread 2 (Thread -1305482352 (LWP 11969)):
#0  0xb7fca402 in __kernel_vsyscall ()
#1  0xb7b77882 in [EMAIL PROTECTED] () from /lib/tls/i686/nosegneg/
libpthread.so.0
#2  0xb7c6870d in PyThread_release_lock () from /usr/lib/
libpython2.5.so.1.0
#3  0xb7c3657b in PyEval_SaveThread () from /usr/lib/libpython2.5.so.
1.0
#4  0xb44252e7 in wxPyBeginAllowThreads () from /usr/lib/python2.5/
site-packages/wx-2.8-gtk2-unicode/wx/_core_.so
#5  0xb442df11 in ?? () from /usr/lib/python2.5/site-packages/wx-2.8-
gtk2-unicode/wx/_core_.so
#6  0xb7bef437 in PyCFunction_Call () from /usr/lib/libpython2.5.so.
1.0
#7  0xb7bb8987 in PyObject_Call () from /usr/lib/libpython2.5.so.1.0
#8  0xb7c3af4b in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#9  0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#10 0xb7c3c663 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#11 0xb7c3cd30 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#12 0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#13 0xb7c3c663 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#14 0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#15 0xb7c3c663 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#16 0xb7c3cd30 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#17 0xb7c3cd30 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#18 0xb7c3cd30 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#19 0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#20 0xb7c3e273 in PyEval_EvalCode () from /usr/lib/libpython2.5.so.1.0
#21 0xb7c3c749 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#22 0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#23 0xb7c3c663 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#24 0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#25 0xb7bdb6ba in ?? () from /usr/lib/libpython2.5.so.1.0
#26 0xb4698800 in ?? ()
#27 0xb4673a44 in ?? ()
#28 0x in ?? ()

and another:

(gdb) bt
#0  0xb7fca402 in __kernel_vsyscall ()
#1  0xb7b77882 in [EMAIL PROTECTED] () from /lib/tls/i686/nosegneg/
libpthread.so.0
#2  0xb7c6870d in PyThread_release_lock () from /usr/lib/
libpython2.5.so.1.0
#3  0xb7c374fc in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#4  0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#5  0xb7c3c663 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#6  0xb7c3cd30 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#7  0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#8  0xb7c3c663 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#9  0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#10 0xb7c3c663 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#11 0xb7c3cd30 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#12 0xb7c3cd30 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#13 0xb7c3cd30 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#14 0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#15 0xb7c3e273 in PyEval_EvalCode () from /usr/lib/libpython2.5.so.1.0
#16 0xb7c3c749 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#17 0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#18 0xb7c3c663 in PyEval_EvalFrameEx () from /usr/lib/libpython2.5.so.
1.0
#19 0xb7c3e1f4 in PyEval_EvalCodeEx () from /usr/lib/libpython2.5.so.
1.0
#20 0xb7bdb6ba in ?? () from /usr/lib/libpython2.5.so.1.0
#21 0xb4698800 in ?? ()
#22 0xb4673a44 in ?? ()
#23 0x in ?? ()
(gdb)


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


dream hardware

2008-02-12 Thread castironpi
What is dream hardware for the Python interpreter?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: call 'the following function' using decorators

2008-02-12 Thread Gabriel Genellina
En Tue, 12 Feb 2008 15:20:32 -0200, <[EMAIL PROTECTED]> escribi�:

> I assert it's easier to write:
>
> start_new_thread( this_func )
> def thrA():
> normal_suite()
>
> than
>
> def thrA():
> normal_suite()
> start_new_thread( thrA )
>
> If you don't, stop reading.  If you do, accomplish it like this:
>
> @decwrap( start_new_thread, Link, ( 2, 3 ) )
> def anonfunc( a, b ):
>   print( a, b )

And I have to *guess* that start_new_thread is called?
A @threaded decorator might be useful, but the above isn't clear at all.

`import this` inside the interpreter.

-- 
Gabriel Genellina

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

Re: Python equivt of __FILE__ and __LINE__

2008-02-12 Thread Steve Holden
Bill Davy wrote:
[...]
 > What a lovely langauge.
> 
+1 QOTW
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Recursive generator

2008-02-12 Thread Ben C
On 2008-02-12, Paul Rubin <> wrote:
> Paul Hankin <[EMAIL PROTECTED]> writes:
>> def genDescendants(self):
>> return chain([self], *[child.genDescendants()
>> for child in self.children])
>
> That is scary.  It generates an in-memory list the size of the
> whole subtree, at every level.  Total memory consumption is maybe
> even quadratic, depending on the tree shape, but even if it's
> only linear, it's way ugly.

This would probably be better (in terms of memory if not beauty):

def genDescendants(self):
return chain([self], *(child.genDescendants()
for child in self.children))
-- 
http://mail.python.org/mailman/listinfo/python-list


Can anyone help, please?

2008-02-12 Thread maehhheeyy
Hi, right now I'm using Python and Multicast. I have the code for
Multicast receiver on Python but I keep getting this error;

File "", line 1, in bind
error: (10049, "Can't assign requested address")


The error is coming from this line;
sock.bind ((MCAST_ADDR, MCAST_PORT))

This is the code that I am using:

import socket
import time

ANY = "0.0.0.0"
SENDERPORT = 1501
MCAST_ADDR = "224.168.2.9"
MCAST_PORT = 1600

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
status = sock.setsockopt(socket.IPPROTO_IP,
 socket.IP_ADD_MEMBERSHIP,
 socket.inet_aton(MCAST_ADDR) +
socket.inet_aton(ANY));

sock.setblocking(0)
ts = time.time()
while 1:
   try:
  data, addr = sock.recvfrom(1024)
   except socket.error, e:
  pass
   else:
  print "We got data!"
  print "FROM: ", addr
  print "DATA: ", data

I'm using the UDP multicast. Is there anything that I did wrong in
this code?

Can anyone please help me solve this problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python equivt of __FILE__ and __LINE__

2008-02-12 Thread Gabriel Genellina
En Tue, 12 Feb 2008 14:41:20 -0200, Jeff Schwab <[EMAIL PROTECTED]>  
escribi�:

>  def line():
>  try:
>  raise Exception
>  except:
>  return sys.exc_info()[2].tb_frame.f_back.f_lineno
>  def file():
>  return inspect.currentframe().f_code.co_filename

It's not a good idea to shadow the file type; I'd suggest current_file and  
current_line.

file() should return inspect.currentframe().f_back.f_code.co_filename,  
else you're using the filename for file() itself, not the caller's

And why the assymetry? Using try/except might help Jython, but that should  
be an implementation detail of inspect.currentframe() anyway. line()  
should just return inspect.currentframe().f_back.f_lineno

-- 
Gabriel Genellina

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

  1   2   >