[OT] Re: Why does python not have a mechanism for data hiding?

2008-06-12 Thread Bruno Desthuilliers

Dennis Lee Bieber a écrit :

On Wed, 11 Jun 2008 10:10:14 +0200, Bruno Desthuilliers
<[EMAIL PROTECTED]> declaimed the following in
comp.lang.python:


are some *very* talented and *experimented* programmers here.


Pardon, but I think you mean "experienced".


Indeed. Tim Golden already corrected me (in private) about my mistake. 
Please pardon my french :-/



Of course, GvR may qualify as "experimented" if one considers
designing a language from scratch to be an experiment 


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


Re: My fight with classes :)

2008-06-12 Thread TheSaint
On 04:51, giovedì 12 giugno 2008 Terry Reedy wrote:

First of all a big thank you, all.

> def makeappender():
> data = ['','']
> def appender(val):
> 
> return appender

I'll give it a try. I just doubting if the data will be shared outside the
function.
Actually, my practice goes to send all variables to the functions and
expecting a returned value. Usually I'm not relying on that module's
variables are read inside a function. Probably I got wrong learning or
experiences.

> For multiple functions, use classes.

That's what I'm leaning to :)
Then I re-elaborated the class according your points and now it's what I
wanted to be. :)
(last time I forgot to past the first line)
Here it comes:

class StrJoin:
""" Join a pair of strings according to the leading first letter A or D,
it returns a list of 2 elements"""

def __init__(self):
self.valueA= ''
self.valueD= ''

def append(self, value):
if not isinstance(value, str):
raise TypeError, 'Wrong type concatenation'
if value.lower().startswith('a'):
self.valueA += value
if value.lower().startswith('d'):
self.valueD += value
return [self.valueA ,self.valueD]

def __getitem__(self,idx):
if idx > 1 : return self
if idx == 0 : return self.valueA
if idx == 1 : return self.valueD

__call__= append

def __repr__(self):
return '['+ self.valueA+ ','+ self.valueD+ ']'

And the shell >>:

>>> from utilities import StrJoin as zx
>>> k =  zx()
>>> k
[,]
>>> k('add')
['add', '']
>>> k[2]
[add,]
>>> k[1]
''
>>> k[0]
'add'
>>> k('dad')
['add', 'dad']
>>> k('sad')
['add', 'dad']
>>> k('Alfa')
['addAlfa', 'dad']
>>> k('Dude')
['addAlfa', 'dadDude']
>>> k('Omega')
['addAlfa', 'dadDude']
>>> k('Dome')
['addAlfa', 'dadDudeDome']
>>> k.append[k]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'instancemethod' object is unsubscriptable
>>> k(89)
Traceback (most recent call last):
  File "", line 1, in 
  File "utilities.py", line 33, in append
raise TypeError, 'Wrong type concatenation'
TypeError: Wrong type concatenation
>>>

Mostly I'll use the call option. I also like to pass it into a function in
order to modularize the loop where it gets started.

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: How to set directory in save as combo box

2008-06-12 Thread Tim Golden

gopal mishra wrote:

In 'save as' dialog of window application, I am trying to set the path in
'save in' combo box using python win32 programming.



How we can set the directory in the 'save in' combo box.


There are several ways to display a "Save As" dialog. Can you
post [a minimal version of] the code you're using so we can see 
what you're doing, please?


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


Re: Converting a simple python script to a simple windows executable

2008-06-12 Thread William McBrine
On Wed, 11 Jun 2008 12:25:29 -0700, geoffbache wrote:

> (1) py2exe. This is really for when python isn't installed on the remote
> user's machine, so it requires you to distribute a large amount of DLLs
> etc which are part of the python installation. A bit silly when I know
> that the remote user has python anyway.

If you know the target user has Python installed, why don't you just 
distribute the .pyw file? (Use ".pyw" instead of ".py" to avoid the extra 
console window.)

-- 
09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on
--
http://mail.python.org/mailman/listinfo/python-list


Please recommend a blog program written using python-cgi

2008-06-12 Thread Royt
Hi, I'm a newbie to Python, but I think it won't be too hard to learn.
A few days ago I registered Google App Engine, it only support Python
2.5. I want to set my blog on it soon. But it's not easy for me to
finish it in a short time since I'm not very familiar with Python, so
I want find some codes available, throught reading the code, I can
learn something from it. I know there are many frameworks for web
development, but I just want the code using traditional CGI method,
it's easy to use and it doesn't require any additional knowledge about
framework. I need a simple example (support basic function of a
weblog, easy to revise) but not a complicated huge monster (I don't
think such a thing now exists).

I find some online course, i.e. 
http://www.upriss.org.uk/python/PythonCourse.html
& http://www.python.org/doc/essays/ppt/sd99east/index.htm  but I
didn't find the code needed, could anyone recommend it to me? thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ClassName.attribute vs self.__class__.attribute

2008-06-12 Thread Duncan Booth
Mike Orr <[EMAIL PROTECTED]> wrote:

> That's a misunderstanding of classes vs instances.  If you have an
> instance of MyClass(Superclass), there is one instance but several
> classes.  The instance is of MyClass; there is no instance of
> Superclass.  'self' has a .__class__ attribute because it's an
> instance, but MyClass and Superclass do not because they're already
> classes.

Classes are also instances, usually they are instances of the type 'type' 
(and even 'type' is an instance of itself):

>>> class SuperClass(object): pass

>>> SuperClass.__class__

>>> type(SuperClass)

>>> type.__class__


Old style classes don't have a class attribute, but you shouldn't be using 
old style classes anyway and so long as you use 
   type(x)
to access its class rather than accessing the __class__ attribute directly 
that doesn't particularly matter.


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: ClassName.attribute vs self.__class__.attribute

2008-06-12 Thread Hrvoje Niksic
Mike Orr <[EMAIL PROTECTED]> writes:

> There's a very good reason to use self.__class__: it makes it
> possible to subclass your class.

This really depends on the usage.  In the OP's use case, he wanted the
subclasses to share the same lock object defined in the superclass
(because of synchronization), so it would have been wrong to use
self.__class__ *because* of subclassing.

Also note that for new-style classes, self.__class__ can be spelled as
type(self), since there is no distinction between classes and types.

> It's a little annoying that if you want to print a class's name in
> some unknown object, you have to use obj.__class__.__name__ if it's
> an instance, and obj.__name__ if it's a class.  I sometimes wish
> classes had a .__class__ attribute that's the class itself, but I
> can see how that would cause its own confusion (and recursion).

They do, the metaclass.  :-)
--
http://mail.python.org/mailman/listinfo/python-list


suppress opening command window after using os.system command

2008-06-12 Thread boriq
Hi,

I'm using in my script command os.system('command') on Windows XP.
Each time the os.system command is used, python opens an empty ms-dos
command window (the black one) and then closes it. So when in one
script the os.system command 50 times is used, I see 50 black windows.

Is there a way of how to suppress this unnecessary command windows to
be opened?

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


Re: Please recommend a blog program written using python-cgi

2008-06-12 Thread Diez B. Roggisch
Royt wrote:

> Hi, I'm a newbie to Python, but I think it won't be too hard to learn.
> A few days ago I registered Google App Engine, it only support Python
> 2.5. I want to set my blog on it soon. But it's not easy for me to
> finish it in a short time since I'm not very familiar with Python, so
> I want find some codes available, throught reading the code, I can
> learn something from it. I know there are many frameworks for web
> development, but I just want the code using traditional CGI method,
> it's easy to use and it doesn't require any additional knowledge about
> framework. I need a simple example (support basic function of a
> weblog, easy to revise) but not a complicated huge monster (I don't
> think such a thing now exists).

I guess you are out of luck. Usually people use frameworks because it *does*
make work easier. AFAIK google engine supports Django. So try & aquaint you
with that - and I bet there are Django-based blogs out there.

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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-12 Thread Bruno Desthuilliers

Mike Orr a écrit :
(snip)

 'self' has a .__class__ attribute because it's an
instance, but MyClass and Superclass do not because they're already
classes.


Not true for new-style classes:

>>> class Toto(object): pass
...
>>> Toto.__class__



(snip)


I sometimes wish classes
had a .__class__ attribute that's the class itself, 


newstyle classes do have a class attribute, that refers to the metaclass.


but I can see how
that would cause its own confusion (and recursion).


FWIW, metaclasses do have a class attribute that refers to itself !-)

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


Re: matplotlib question

2008-06-12 Thread Tom Wright
asdf wrote:
> basically I need to plot a graph of data vs time. However when i use
> matplotlib the hr:min tick marks come out very close together and
> appear jumbled.

You need to look up the matplotlib.dates package - it's covered briefly in
the tutorial at http://matplotlib.sourceforge.net/tutorial.html

At a guess, you want something along the lines of this...

from matplotlib.dates import YearLocator, MonthLocator, WeekdayLocator, \
DayLocator, HourLocator, MinuteLocator, SecondLocator, \
DateFormatter

subplot.xaxis.set_major_locator(HourLocator(range(0,24,6)))
subplot.xaxis.set_major_formatter(DateFormatter("%a %H:%M"))
subplot.xaxis.set_minor_locator(HourLocator(range(0,24,1)))

...but you'll probably need to look up the documentation to get the details
to suit what you need.

Hope that helps!


-- 
I'm at CAMbridge, not SPAMbridge
--
http://mail.python.org/mailman/listinfo/python-list


Re: h2py.py bug?

2008-06-12 Thread Gabriel Genellina
En Wed, 11 Jun 2008 04:21:03 -0300, Gabriel Rossetti  
<[EMAIL PROTECTED]> escribió:



Gabriel Genellina wrote:
En Tue, 10 Jun 2008 09:44:13 -0300, Gabriel Rossetti  
<[EMAIL PROTECTED]> escribió:


I wanted to use the h2py.py script (Tools/scripts/h2py.py) and it  
didn't like char litterals :


Skipping: PC_ERROR = ord()

where my *.h file contained :

#define PC_ERROR '0'

I searched the web and found a post with the same error :

http://mail.python.org/pipermail/python-list/2005-September/340608.html

but it got no replies, I tried the fix and it works. I have the  
following questions:


1) Why did it not get any attention, is something wrong with it?
2) If nothing is wrong, did the fix not get applied because a bug  
report wasn't filed?


Very probably - bug reports outside the tracker are likely to go  
unnoticed or forgotten.



Ok, I'll file one then.
3) Isn't turning a char literal into the ordinal value not contrary to  
what a C programmer had in mind when he/she defined it? I mean if you  
define a char literal then in python you would have used a string  
value :


#define PC_ERROR '0'

would become :

PC_ERROR = '0'

in python, and if you intended to use the char type for an 8 bit  
numerical value you would have done :


#define PC_ERROR 0x30

where 0x30 is the '0' ascii hex value, so shouldn'it the line in the  
diff (see the post) be :


body = p_char.sub("'\\1'", body)

instead of :

body = p_char.sub("ord('\\1')", body)


It's not so clear what's the intended usage - chars are also integers  
in C. (I prefer the current behavior, but certainly it may be wrong in  
several places).


Yes, true, but if you intend to use it as an integer, wouldn't you use a  
numeric value instead of a character literal?


Not always. Using characters as ordinal numbers is very common in that  
language. A small example:


#define FIRST 'A'
#define LAST  'Z'
#define index(letter) ((letter)-FIRST)

int accum[LAST-FIRST+1];
...
char x = some_word[0];
accum[index(x)]++;

accum is an array of 26 integers, element 0 corresponding to letter 'A'.  
If one has to reproduce the exact same structure, in Python it would be:


FIRST = ord('A')
LAST = ord('Z')
def index(letter):
  return ord(letter)-FIRST

accum = [0 for i in range(LAST-FIRST+1)]
x = some_word[0]
accum[index(x)] += 1

Of course, in other cases, character constants are intended to be used as  
character data, so ord(...) is not the appropiate thing to do when  
converting to Python. But I don't think my example above is very contrived  
or uncommon - chars *are* integers from the C point of view, and some  
people isn't worried too much about the distinction, specially those who  
use C as their main or only language.


--
Gabriel Genellina

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


ATT WIRELESS

2008-06-12 Thread AISHWARYA
__
http://attwireless1.blogspot.com
http://onenesstemple.blogspot.com
http://maintanancemanagementsoftwareservises.blogspot.com
http://consolidation2.blogspot.com
http://debtmanagementcompany.blogspot.com/
http://personalloanscash.blogspot.com/
http://attwireless1.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: My fight with classes :)

2008-06-12 Thread Bruno Desthuilliers

TheSaint a écrit :

On 04:51, giovedì 12 giugno 2008 Terry Reedy wrote:

First of all a big thank you, all.


def makeappender():
  data = ['','']
  def appender(val):

  return appender


I'll give it a try. I just doubting if the data will be shared outside the
function.


Each time makeappender is called, it returns a new appender function 
object with it's own 'data' object. So 'data' won't be shared between 
different instances of the appender function.



Actually, my practice goes to send all variables to the functions and
expecting a returned value.


Mostly a sane, sound and sensible approach IMHO - but doesn't work that 
well when the function needs to maintain own state between calls.



Usually I'm not relying on that module's
variables are read inside a function. Probably I got wrong learning or
experiences.


As long as you only *read* module's globals from within a function, 
that's mostly ok. When you start *writing* them it may be time to 
reconsider the design (not that it's necessarily bad, but it's a 
possible signal that something is wrong).



For multiple functions, use classes.


Well... Closures are poor men's objects, or so they say (or is that the 
other way round ?-).


def make_person(name, age):
  state = dict(name=name, age=age)
  def set_name(new_name=None):
state['name'] = new_name
  def get_name():
return state['name']
  def grow():
state['age'] += 1
  def get_age()
return state['age']
  return set_name, get_name, grow, get_age

(toto_set_name,
 toto_get_name,
 toto_grow,
 toto_get_age) = make_person('toto', 42)

A bit cumbersome, indeed !-)


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

Re: suppress opening command window after using os.system command

2008-06-12 Thread Gabriel Genellina
En Thu, 12 Jun 2008 05:28:13 -0300, boriq <[EMAIL PROTECTED]>  
escribió:



I'm using in my script command os.system('command') on Windows XP.
Each time the os.system command is used, python opens an empty ms-dos
command window (the black one) and then closes it. So when in one
script the os.system command 50 times is used, I see 50 black windows.

Is there a way of how to suppress this unnecessary command windows to
be opened?


Use the subprocess module instead of os.system

--
Gabriel Genellina

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


Re: suppress opening command window after using os.system command

2008-06-12 Thread boriq
On 12 Jun., 11:51, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Thu, 12 Jun 2008 05:28:13 -0300, boriq <[EMAIL PROTECTED]>  
> escribió:
>
> > I'm using in my script command os.system('command') on Windows XP.
> > Each time the os.system command is used, python opens an empty ms-dos
> > command window (the black one) and then closes it. So when in one
> > script the os.system command 50 times is used, I see 50 black windows.
>
> > Is there a way of how to suppress this unnecessary command windows to
> > be opened?
>
> Use the subprocess module instead of os.system
>
> --
> Gabriel Genellina

I'm on version 2.2.1 because of a program we use and it uses this
version.

and the subprocess module was implemented in version 2.4

Any possibility to do it with the old stuff in ver 2.2.1?

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


Re: suppress opening command window after using os.system command

2008-06-12 Thread Gabriel Genellina
En Thu, 12 Jun 2008 07:08:00 -0300, boriq <[EMAIL PROTECTED]>  
escribió:



On 12 Jun., 11:51, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

En Thu, 12 Jun 2008 05:28:13 -0300, boriq <[EMAIL PROTECTED]>  
escribió:

> I'm using in my script command os.system('command') on Windows XP.
> Each time the os.system command is used, python opens an empty ms-dos
> command window (the black one) and then closes it. So when in one
> script the os.system command 50 times is used, I see 50 black windows.

> Is there a way of how to suppress this unnecessary command windows to
> be opened?

Use the subprocess module instead of os.system



I'm on version 2.2.1 because of a program we use and it uses this
version.

and the subprocess module was implemented in version 2.4

Any possibility to do it with the old stuff in ver 2.2.1?


Sure, depending on your needs, use any of the os.popen variants or any of  
the os.spawn variants.


--
Gabriel Genellina

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


Re: suppress opening command window after using os.system command

2008-06-12 Thread Tim Golden

Gabriel Genellina wrote:
En Thu, 12 Jun 2008 07:08:00 -0300, boriq <[EMAIL PROTECTED]> 
escribió:



On 12 Jun., 11:51, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
En Thu, 12 Jun 2008 05:28:13 -0300, boriq <[EMAIL PROTECTED]>  
escribió:


> I'm using in my script command os.system('command') on Windows XP.
> Each time the os.system command is used, python opens an empty ms-dos
> command window (the black one) and then closes it. So when in one
> script the os.system command 50 times is used, I see 50 black windows.

> Is there a way of how to suppress this unnecessary command windows to
> be opened?

Use the subprocess module instead of os.system



I'm on version 2.2.1 because of a program we use and it uses this
version.

and the subprocess module was implemented in version 2.4

Any possibility to do it with the old stuff in ver 2.2.1?


Sure, depending on your needs, use any of the os.popen variants or any 
of the os.spawn variants.


Or you can download the external module which became the subprocess
module in the stdlib:

http://www.lysator.liu.se/~astrand/popen5/

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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-12 Thread Duncan Booth
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:

> 
> FWIW, metaclasses do have a class attribute that refers to itself !-)
> 
One metaclass (i.e. type) has a class attribute that refers to itself.

Other metaclasses have a class attribute that refers to the metaclass's 
metaclass. I can't think of any situation where a metaclass would be its 
own metaclass except for 'type' itself, but then I think I've got a 
headache trying to think about this so maybe I'm wrong.

In fact, thinking about it a bit more, I think that if you did have another 
metaclass which is its own metaclass then the class cannot subclass 
'object'.

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


re quiz

2008-06-12 Thread David C. Ullrich
True or False? (no fair looking it up)

(*) If repl is a string then re.sub(pattern, repl, s) 
returns s with non-overlapping occurences of pattern 
replaced by repl.

I assumed it was true - spent a few hours trying to
figure out what was going on with a certain re.sub,
then noticed that (*) is false:

(**) "If repl is a string, any backslash escapes in it are 
processed. That is, "\n" is converted to a single newline 
character, "\r" is converted to a linefeed, and so forth."

So I changed my r"\remark{Hint}" to r"\\remark{Hint}"
and things were fine.

A pointless question and then a practical one.

Pointless question: There must be a good reason for (**).
What would it be? Seems needlessly confusing to me (of
course a lot of things seem confusing to me...)

Maybe it's going to be confusing no matter what they do.
But "\\n" looks like it doesn't contain a newline, but it
gets converted to something that does.

(Another fascinating question is how they could phrase
the docs here so as to confuse nobody. Because "\n"
_is_ a newline, or so it's going to look to many people;
I'd spell it out:: "a string containing '\' followed by 'n' ".)

Practical question: What's a _complete_ list of the
escapes included in the "and so forth" in (**)?

(Or is there a function somewhere that will convert
r"\remark{Hint}" to r"\\remark{Hint}" for me, and
do the same for precisely the escpapes referred to
in the "and so forth"?)


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


get keys with the same values

2008-06-12 Thread Nader
Hello,

I have a dictionary and will get all keys which have the same values.

d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}

I will something as :

d.keys(where their values are the same)

With this statement I can get two lists for this example:
l1= ['a','e']
l2=['b','d']

Would somebody tell me how I can do it?

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


regex for balanced parentheses?

2008-06-12 Thread David C. Ullrich
There's no regex that detects balanced parentheses,
or is there?

That is, search('and so ((x+y)+z) = (x+(y+z))')
should return '((x+y)+z)'.

Not just a theoretical question, I'm cleaning up
a large body of TeX code and a regex that did that
would be very convenient. (Yes, I know it's not
hard to detect balanced parentheses by hand...)

I don't know that stuff, but I seen to recall reading
that there's a theoretical notion of "regular expression"
in CS, and a regular expression in that sense cannot
do this. But in the same place I read that the actual
regexes in programming languages include things which
are not regular expressions in that theoretical sense.


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


using re module to find " but not " alone ... is this a BUG in re?

2008-06-12 Thread anton
Hi,

I want to replace all occourences of " by \" in a string.

But I want to leave all occourences of \" as they are.

The following should happen:

  this I want " while I dont want this \" 

should be transformed to:

  this I want \" while I dont want this \" 

and NOT:

  this I want \" while I dont want this \\" 

I tried even the (?<=...) construction but here I get an unbalanced paranthesis
error.

It seems tha re is not able to do the job due to parsing/compiling problems 
for this sort of strings.


Have you any idea??

  Anton


Example: 

import re

re.findall("[^\\]\"","this I want \" while I dont want this \\\" ")

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\re.py", line 175, in findall
return _compile(pattern, flags).findall(string)
  File "C:\Python25\lib\re.py", line 241, in _compile
raise error, v # invalid expression
error: unexpected end of regular expression

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


Re: Dynamic HTML from Python Script

2008-06-12 Thread Dave Parker
On Jun 11, 10:43 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> Those are not /server side/ refreshes...

Correct.  But we weren't discussing server side refreshes.  We were
discussing how to make the "browser refresh automatically in the
server side":

On Jun 11, 7:59 am, Lie <[EMAIL PROTECTED]> wrote:
> Surely you don't think you can do that without Javascript don't you?
> You can't make the browser refresh automatically in the server side,
> it has to be done in the client side scripting or like Opera browser
> that have an option to make it refresh a page every few seconds.

The example I posted showed a simple way to "make the browser refresh
automatically in the server side" by using an HTTP Refresh header
instead of using any Javascript or client side scripting or setting a
browser option to refresh the page every few seconds.


On Jun 11, 10:43 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Wed, 11 Jun 2008 07:36:59 -0700 (PDT), Dave Parker
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
>
> > Yes you can.  I don't know how to do it in Python, but here's an
> > example in Flaming Thunder of a small, fast, light compiled server
> > side CGI that delivers dynamic content every 10 seconds.
>
> >   # Write out the HTTP headers, followed by a blank line.
> >   # Make sure to write CRLF and not just LF, as per HTTP
> >   # specs.  Also, turn off caching using the no-cache and
> >   # expires options, so that caching doesn't conflict with
> >   # refreshes.
>
> >   Set CRLF to CarriageReturn+LineFeed.
> >   Write "Refresh: 10; url=http://www.flamingthunder.com/cgi/
> > refresh.cgi",CRLF.
>
>         Those are not /server side/ refreshes... The first thing being
> written is a command to the browser that tells the browser to reload the
> specified page after a delay period.
>
>         IOWs it is the browser doing the refresh -- which means it starts a
> whole new connection, receiving a page from the CGI script... Said page
> again having a browser command to do a delayed refresh.
>
>         Server side would mean that the server somehow continuously sends
> updates WITHOUT BEING ASKED.
> --
>         Wulfraed        Dennis Lee Bieber               KD6MOG
>         [EMAIL PROTECTED]             [EMAIL PROTECTED]
>                 HTTP://wlfraed.home.netcom.com/
>         (Bestiaria Support Staff:               [EMAIL PROTECTED])
>                 HTTP://www.bestiaria.com/

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


Plotting Graphs using Gnuplot

2008-06-12 Thread arslanburney
Hello. Was trying to create a simple plotting function. Wasnt working
however. If i write the same code without putting it inside a function
it works. :S. Could some1 tell me the problem? Heres the code:


# File name Plotting2

import Gnuplot

def plot(original, expected, actual):


if type (original) != type([]):
return False

else:

gp = Gnuplot.Gnuplot()
gp('set data style lines')


# Make the plot items
plot1 = Gnuplot.PlotItems.Data(original, title="Original")
plot2 = Gnuplot.PlotItems.Data(expected, title="Expected")
plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal")


return gp.plot(plot1, plot2, plot3)




import Plotting2   #The name of my file...

Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] )
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding a sense of word in a text

2008-06-12 Thread Piotrek Byzia
On 11 Cze, 19:10, Sengly <[EMAIL PROTECTED]> wrote:
> Dear all,
>
> This might be off group but I am looking for a python library that can
> help me to find a sense of a word in a text and eventually a list of
> synonyms of that term. I searched the web and found one but it is
> written in perl (http://www.d.umn.edu/~tpederse/senserelate.html) :(
>
> I appreciate any pointers.

Search for terms like text mining and NLP.

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


Re: Converting a simple python script to a simple windows executable

2008-06-12 Thread Gerry
On Jun 12, 4:04 am, William McBrine <[EMAIL PROTECTED]> wrote:
> On Wed, 11 Jun 2008 12:25:29 -0700, geoffbache wrote:
> > (1) py2exe. This is really for when python isn't installed on the remote
> > user's machine, so it requires you to distribute a large amount of DLLs
> > etc which are part of the python installation. A bit silly when I know
> > that the remote user has python anyway.
>
> If you know the target user has Python installed, why don't you just
> distribute the .pyw file? (Use ".pyw" instead of ".py" to avoid the extra
> console window.)
>
> --
> 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on

I really like cx_freeze:

http://python.net/crew/atuining/cx_Freeze/
--
http://mail.python.org/mailman/listinfo/python-list


Re: get keys with the same values

2008-06-12 Thread bearophileHUGS
Nader:
> d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> I will something as :
> d.keys(where their values are the same)

That's magic.


> With this statement I can get two lists for this example:
> l1= ['a','e']
> l2=['b','d']
> Would somebody tell me how I can do it?

You can create a new dict where the keys are the values of the input
dict and the values are a list of the keys of the original dict. So
scanning the keys, values of the input dict, you can fill the second
dict. Then you can scan the second dict, and create a list that
contains only value lists longer than one.

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


Re: get keys with the same values

2008-06-12 Thread David C. Ullrich
On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <[EMAIL PROTECTED]>
wrote:

>Hello,
>
>I have a dictionary and will get all keys which have the same values.
>
>d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}

That's not a dictionary, it's a syntax error. If you actually
have a dictionary you could say

d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}

dd = {}

for key, value in d.items():
  try:
dd[value].append(key)
  except KeyError:
dd[value] = [key]

Possibly dd is now what you really want; if you really
want what you said you want you could use

[l for l in dd.values() if len(l) > 1]

>I will something as :
>
>d.keys(where their values are the same)
>
>With this statement I can get two lists for this example:
>l1= ['a','e']
>l2=['b','d']
>
>Would somebody tell me how I can do it?
>
>Regards,
>Nader

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


Re: using re module to find " but not " alone ... is this a BUG in re?

2008-06-12 Thread John Machin
On Jun 12, 7:11 pm, anton <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I want to replace all occourences of " by \" in a string.
>
> But I want to leave all occourences of \" as they are.
>
> The following should happen:
>
>   this I want " while I dont want this \"
>
> should be transformed to:
>
>   this I want \" while I dont want this \"
>
> and NOT:
>
>   this I want \" while I dont want this \\"
>
> I tried even the (?<=...) construction but here I get an unbalanced 
> paranthesis
> error.

Sounds like a deficit of backslashes causing re to regard \) as plain
text and not the magic closing parenthesis in (?<=...) -- and don't
you want (?
> It seems tha re is not able to do the job due to parsing/compiling problems
> for this sort of strings.

Nothing is ever as it seems.

>
> Have you any idea??

For a start, *ALWAYS* use a raw string for an re pattern -- halves the
backslash pollution!


>
>
> re.findall("[^\\]\"","this I want \" while I dont want this \\\" ")

and if you have " in the pattern, use '...' to enclose the pattern so
that you don't have to use \"

>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\lib\re.py", line 175, in findall
> return _compile(pattern, flags).findall(string)
>   File "C:\Python25\lib\re.py", line 241, in _compile
> raise error, v # invalid expression
> error: unexpected end of regular expression

As expected.

What you want is:

>> import re
>> text = r'frob this " avoid this \", OK?'
>>> text
'frob this " avoid this \\", OK?'
>> re.sub(r'(?>

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


Re: get keys with the same values

2008-06-12 Thread Nader
On Jun 12, 1:35 pm, [EMAIL PROTECTED] wrote:
> Nader:
>
> > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> > I will something as :
> > d.keys(where their values are the same)
>
> That's magic.
>
> > With this statement I can get two lists for this example:
> > l1= ['a','e']
> > l2=['b','d']
> > Would somebody tell me how I can do it?
>
> You can create a new dict where the keys are the values of the input
> dict and the values are a list of the keys of the original dict. So
> scanning the keys, values of the input dict, you can fill the second
> dict. Then you can scan the second dict, and create a list that
> contains only value lists longer than one.
>
> Bye,
> bearophile

Is it niet possible with one or two statement, maybe with list
comprehension. For exmple:

l = [(k,v) for k in d.keys() for v in d.values() | en here we need
some extra logic (v = 1)]

I don;t konw how we can define a logic statement in a list
comprehension.
It will be very compact, if it would possible.

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


Re: Simple and safe evaluator

2008-06-12 Thread Hans Nowak

bvdp wrote:


Is there a simple/safe expression evaluator I can use in a python 
program. I just want to pass along a string in the form "1 + 44 / 3" or 
perhaps "1 + (-4.3*5)" and get a numeric result.


I can do this with eval() but I really don't want to subject my users to 
the problems with that method.


In this use I don't need python to worry about complex numbers, 
variables or anything else. Just do the math on a set of values. Would 
eval() with some restricted list of permitted operators do the trick?


This solution may be overly simply (especially compared to the AST-based 
solution suggested earlier), but... if all you need is numbers and operators, 
*maybe* you can get away with stripping all letters from the input string (and 
possibly the underscore), and then evaluating it:



import re
import traceback

re_letters = re.compile("[a-zA-Z_]+")

def safe_eval(s):
s = re_letters.sub("", s)
return eval(s)

# try it out...

>>> safe_eval("2+2")
4

>>> safe_eval("4 * (8 / 3.1) ** 7.2")
3685.5618352828474

>>> safe_eval("(2).__class__.__base__.__subclasses__()")
Traceback (most recent call last):
  File "", line 1, in 
  File "safe_eval.py", line 12, in safe_eval
return eval(s)
  File "", line 1
(2)...()
^
SyntaxError: invalid syntax

...It's primitive, but it might work for your purposes.

--
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: get keys with the same values

2008-06-12 Thread Nader
On Jun 12, 1:41 pm, David C. Ullrich <[EMAIL PROTECTED]> wrote:
> On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <[EMAIL PROTECTED]>
> wrote:
>
> >Hello,
>
> >I have a dictionary and will get all keys which have the same values.
>
> >d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
>
> That's not a dictionary, it's a syntax error. If you actually
> have a dictionary you could say
>
> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
>
> dd = {}
>
> for key, value in d.items():
>   try:
> dd[value].append(key)
>   except KeyError:
> dd[value] = [key]
>
> Possibly dd is now what you really want; if you really
> want what you said you want you could use
>
> [l for l in dd.values() if len(l) > 1]
>
> >I will something as :
>
> >d.keys(where their values are the same)
>
> >With this statement I can get two lists for this example:
> >l1= ['a','e']
> >l2=['b','d']
>
> >Would somebody tell me how I can do it?
>
> >Regards,
> >Nader
>
> David C. Ullrich

Thank for your type about the syntax error. This an example example,
the keys of my dictionary are tuples:
d = {(37.75, 42.22): 1 , (37.51, 40.02): 3 (45.55, 24.27): 4 (47.08,
30.99) : 1}

But what I will is to get all keys which has the same valus. And not
the keys that have value more than 1!

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


Re: Strange bug doesn't occur in Pydb

2008-06-12 Thread kj
In <[EMAIL PROTECTED]> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:

>kj schrieb:
>> I'm running into a strange seg fault with the module cjson.  The
>> strange part is that it does not occur when I run the code under
>> Emacs' Pydb.
>> 
>> Here's an example: 
>> 
>> 
>> import sys, cjson
>> 
>> d1 = {'a': 1, 'b': 2, 'c': 3}
>> print sys.version
>> j1 = cjson.encode(d1)
>> print j1   # should print the string '{"a": 1, "c": 3, "b": 2}'
>> 
>> The code above runs fine under Pydb, but segfaults at the call to
>> cjson.encode when I run it from the command line in a standard
>> Linux shell interaction.  In the printed version strings are
>> identical.
>> 
>> I figure this must be a bug in cjson.  I'd love to find a workaround
>> for it, and hope that this strange difference between Pydb and the
>> shell command line may be a clue to that.
>> 
>> Any thoughts?

>Are you sure you actually run the same interpreter in emacs as you do on 
>the commandline?

No, I'm not.  All I know is that both Emacs and the commandline
are running on the same machine, and that the version string that
the program prints is the same in both conditions.  How can I verify
that that the same interpreter is running in both cases?

Kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
--
http://mail.python.org/mailman/listinfo/python-list


Re: get keys with the same values

2008-06-12 Thread Chris
On Jun 12, 1:48 pm, Nader <[EMAIL PROTECTED]> wrote:
> On Jun 12, 1:35 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > Nader:
>
> > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> > > I will something as :
> > > d.keys(where their values are the same)
>
> > That's magic.
>
> > > With this statement I can get two lists for this example:
> > > l1= ['a','e']
> > > l2=['b','d']
> > > Would somebody tell me how I can do it?
>
> > You can create a new dict where the keys are the values of the input
> > dict and the values are a list of the keys of the original dict. So
> > scanning the keys, values of the input dict, you can fill the second
> > dict. Then you can scan the second dict, and create a list that
> > contains only value lists longer than one.
>
> > Bye,
> > bearophile
>
> Is it niet possible with one or two statement, maybe with list
> comprehension. For exmple:
>
> l = [(k,v) for k in d.keys() for v in d.values() | en here we need
> some extra logic (v = 1)]
>
> I don;t konw how we can define a logic statement in a list
> comprehension.
> It will be very compact, if it would possible.
>
> Nader

If you are going to use this reverse look-up alot you'd be better off
building another dictionary with the original values being keys and
the original keys being values, if it is used infrequently enough you
can search for it with result_list = [k for k,v in dictionary.items()
if v == search_value]
--
http://mail.python.org/mailman/listinfo/python-list


Re: re quiz

2008-06-12 Thread John Machin
On Jun 12, 8:57 pm, David C. Ullrich <[EMAIL PROTECTED]> wrote:
> True or False? (no fair looking it up)
>
> (*) If repl is a string then re.sub(pattern, repl, s)
> returns s with non-overlapping occurences of pattern
> replaced by repl.
>
> I assumed it was true - spent a few hours trying to
> figure out what was going on with a certain re.sub,
> then noticed that (*) is false:
>

Well, the docs do say "Return the string obtained by replacing the
leftmost non-overlapping occurrences of pattern in string by the
replacement repl." -- care to tell us what "a certain re.sub" is, and
false in what way?
--
http://mail.python.org/mailman/listinfo/python-list


Re: re quiz

2008-06-12 Thread Peter Otten
David C. Ullrich wrote:

> (Or is there a function somewhere that will convert
> r"\remark{Hint}" to r"\\remark{Hint}" for me, and
> do the same for precisely the escpapes referred to
> in the "and so forth"?)

I think you just have to escape the backslash:

re.sub(pattern, replacement_string.replace("\\", ""), s)

Anyway here's the list of troublemakers:

>>> def means_trouble(c):
... try:
... return re.sub("x", "\\" + c, "x") != "\\" + c
... except:
... return True
...
>>> [c for c in map(chr, range(256)) if means_trouble(c)]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\\', 'a', 'b', 'f', 'g', 
'n', 'r', 't', 'v']


Peter 

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


Re: get keys with the same values

2008-06-12 Thread Nader
On Jun 12, 2:05 pm, Chris <[EMAIL PROTECTED]> wrote:
> On Jun 12, 1:48 pm, Nader <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jun 12, 1:35 pm, [EMAIL PROTECTED] wrote:
>
> > > Nader:
>
> > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> > > > I will something as :
> > > > d.keys(where their values are the same)
>
> > > That's magic.
>
> > > > With this statement I can get two lists for this example:
> > > > l1= ['a','e']
> > > > l2=['b','d']
> > > > Would somebody tell me how I can do it?
>
> > > You can create a new dict where the keys are the values of the input
> > > dict and the values are a list of the keys of the original dict. So
> > > scanning the keys, values of the input dict, you can fill the second
> > > dict. Then you can scan the second dict, and create a list that
> > > contains only value lists longer than one.
>
> > > Bye,
> > > bearophile
>
> > Is it niet possible with one or two statement, maybe with list
> > comprehension. For exmple:
>
> > l = [(k,v) for k in d.keys() for v in d.values() | en here we need
> > some extra logic (v = 1)]
>
> > I don;t konw how we can define a logic statement in a list
> > comprehension.
> > It will be very compact, if it would possible.
>
> > Nader
>
> If you are going to use this reverse look-up alot you'd be better off
> building another dictionary with the original values being keys and
> the original keys being values, if it is used infrequently enough you
> can search for it with result_list = [k for k,v in dictionary.items()
> if v == search_value]

Thank you! It is the anwser which I was looking for. [(k,v) for k,v
in  d.items() if v is pattern].
But I don't understand what tou mean of "reverse look-up a lot"! I
have to read some informations inclusive (latitudes and longitudes)
form a file and after some processing to save part of this information
to other file.
Why do I make a new dictionary?

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


Re: get keys with the same values

2008-06-12 Thread Duncan Booth
Nader <[EMAIL PROTECTED]> wrote:

> I have a dictionary and will get all keys which have the same values.
> 
> d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> 
> I will something as :
> 
> d.keys(where their values are the same)
> 
> With this statement I can get two lists for this example:
> l1= ['a','e']
> l2=['b','d']
> 
> Would somebody tell me how I can do it?

Here's one way:

>>> import itertools, functools, operator
>>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
>>> get = functools.partial(operator.getitem, d)
>>> for (k,v) in itertools.groupby(sorted(d, key=get), key=get):
print k, list(v)


1 ['a', 'e']
2 ['c']
3 ['b', 'd']
4 ['f']

or if you want a dictionary:

>>> dict((k,list(v)) for (k,v) in
itertools.groupby(sorted(d, key=get), key=get))
{1: ['a', 'e'], 2: ['c'], 3: ['b', 'd'], 4: ['f']}

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Strange bug doesn't occur in Pydb

2008-06-12 Thread Diez B. Roggisch
kj wrote:

> In <[EMAIL PROTECTED]> "Diez B. Roggisch"
> <[EMAIL PROTECTED]> writes:
> 
>>kj schrieb:
>>> I'm running into a strange seg fault with the module cjson.  The
>>> strange part is that it does not occur when I run the code under
>>> Emacs' Pydb.
>>> 
>>> Here's an example:
>>> 
>>> 
>>> import sys, cjson
>>> 
>>> d1 = {'a': 1, 'b': 2, 'c': 3}
>>> print sys.version
>>> j1 = cjson.encode(d1)
>>> print j1   # should print the string '{"a": 1, "c": 3, "b": 2}'
>>> 
>>> The code above runs fine under Pydb, but segfaults at the call to
>>> cjson.encode when I run it from the command line in a standard
>>> Linux shell interaction.  In the printed version strings are
>>> identical.
>>> 
>>> I figure this must be a bug in cjson.  I'd love to find a workaround
>>> for it, and hope that this strange difference between Pydb and the
>>> shell command line may be a clue to that.
>>> 
>>> Any thoughts?
> 
>>Are you sure you actually run the same interpreter in emacs as you do on
>>the commandline?
> 
> No, I'm not.  All I know is that both Emacs and the commandline
> are running on the same machine, and that the version string that
> the program prints is the same in both conditions.  How can I verify
> that that the same interpreter is running in both cases?

By e.g. 

import sys
print sys.prefix

Additionally, you should compare what

sys.path

contains and if it's the same - otherwise it might be that cjson is picked
up from somewhere else.

If all that's the case, I'd invoke python through gdb and see where the
segfault happens.

BTW: I've been using (and even patching) cjson - without any troubles
whatsoever.

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


Re: Why does python not have a mechanism for data hiding?

2008-06-12 Thread Luis Zarrabeitia

Quoting Dennis Lee Bieber <[EMAIL PROTECTED]>:

> On Wed, 11 Jun 2008 21:54:33 -0700 (PDT), Michele Simionato
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
> > 
> > It looks like in French (as in Italian) *experimented* has the
> > meaning of "tried and tested on the field" when applied to a
> > person.
> >
>   
> 
>   Fascinating

Spanish also. I translate "experimentado" to "experienced", perhaps because I
had seen it before, but I never imagined that "experimented" would be wrong.

Fascinating x2

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

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


Re: re quiz

2008-06-12 Thread Duncan Booth
David C. Ullrich <[EMAIL PROTECTED]> wrote:

> Practical question: What's a _complete_ list of the
> escapes included in the "and so forth" in (**)?
> 
> (Or is there a function somewhere that will convert
> r"\remark{Hint}" to r"\\remark{Hint}" for me, and
> do the same for precisely the escpapes referred to
> in the "and so forth"?)
> 

As the documentation says:

Character escapes
Numbered Groups: \0 \1 \2 \3 ...
Named groups: \g
Numbered groups with explicit termination of the number: \g<0> \g<1> ...

But it doesn't matter what the complete list is. All of the escapes start 
with \ so doubling all the \\ will prevent any of them being interpreted as 
special so if you aren't wanting to substitute any groups into the string 
just try repl.replace('\\', r'\\')


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: using re module to find " but not " alone ... is this a BUG in re?

2008-06-12 Thread Duncan Booth
John Machin <[EMAIL PROTECTED]> wrote:

> What you want is:
> 
>>> import re
>>> text = r'frob this " avoid this \", OK?'
 text
> 'frob this " avoid this \\", OK?'
>>> re.sub(r'(? frob this \\" avoid this \\", OK?'
>>>
> 

Or you can do it without using regular expressions at all. Just replace 
them all and then fix up the result:

>>> text = r'frob this " avoid this \", OK?'
>>> text.replace('"', r'\"').replace(r'\\"', r'\"')
'frob this \\" avoid this \\", OK?'


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Alternative to Decimal type

2008-06-12 Thread Frank Millman
On Jun 11, 11:48 am, Frank Millman <[EMAIL PROTECTED]> wrote:
> Thanks to all for the various replies. They have all helped me to
> refine my ideas on the subject. These are my latest thoughts.
>
[snip]
>
> My main concern is that my approach may be naive, and that I will run
> into situations that I have not catered for, resulting in errors. If
> this is the case, I will drop this like a hot potato and stick to the
> Decimal type. Can anyone point out any pitfalls I might be unaware of?
>
> I will be happy to show the code for the new Number class if anyone is
> interested.
>

Thanks again for all the really useful replies.

I will have a look at gmpy, and I will study FixedPoint.py closely.

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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-12 Thread Hrvoje Niksic
Duncan Booth <[EMAIL PROTECTED]> writes:

> In fact, thinking about it a bit more, I think that if you did have
> another metaclass which is its own metaclass then the class cannot
> subclass 'object'.

You could if the metaclass of your metaclass inherited from 'type'.
Then your types could still be binary-compatible with Python types,
and your objects with 'object'.  It's difficult to envision what you'd
gain with a custom meta-meta-class, but it seems possible:

>>> class MetaMeta(type): pass
...
>>> class Meta(type):
...   __metaclass__ = MetaMeta
...
>>> class Foo(object):
...   __metaclass__ = Meta
...
>>> f = Foo()
>>> f
<__main__.Foo object at 0xb7d27bec>
>>> type(f)

>>> type(type(f))

>>> type(type(type(f)))

>>> isinstance(f, object)
True
--
http://mail.python.org/mailman/listinfo/python-list


Re: using re module to find " but not " alone ... is this a BUG in re?

2008-06-12 Thread Peter Otten
anton wrote:

> I want to replace all occourences of " by \" in a string.
> 
> But I want to leave all occourences of \" as they are.
> 
> The following should happen:
> 
>   this I want " while I dont want this \"
> 
> should be transformed to:
> 
>   this I want \" while I dont want this \"
> 
> and NOT:
> 
>   this I want \" while I dont want this \\"
> 
> I tried even the (?<=...) construction but here I get an unbalanced
> paranthesis error.
> 
> It seems tha re is not able to do the job due to parsing/compiling
> problems for this sort of strings.
> 
> 
> Have you any idea??

The problem is underspecified. Should r'\\"' become r'\\\"' or remain
unchanged? If the backslash is supposed to escape the following letter
including another backslash -- that can't be done with regular expressions
alone:

# John's proposal:
>>> print re.sub(r'(?>> parts = re.compile("(.)").split('no " one \\", two "')
>>> parts[::2] = [p.replace('"', '\\"') for p in parts[::2]]
>>> print "".join(parts)
no \" one \", two \\\"

Peter

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


Re: get keys with the same values

2008-06-12 Thread Chris
On Jun 12, 2:15 pm, Nader <[EMAIL PROTECTED]> wrote:
> On Jun 12, 2:05 pm, Chris <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jun 12, 1:48 pm, Nader <[EMAIL PROTECTED]> wrote:
>
> > > On Jun 12, 1:35 pm, [EMAIL PROTECTED] wrote:
>
> > > > Nader:
>
> > > > > d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> > > > > I will something as :
> > > > > d.keys(where their values are the same)
>
> > > > That's magic.
>
> > > > > With this statement I can get two lists for this example:
> > > > > l1= ['a','e']
> > > > > l2=['b','d']
> > > > > Would somebody tell me how I can do it?
>
> > > > You can create a new dict where the keys are the values of the input
> > > > dict and the values are a list of the keys of the original dict. So
> > > > scanning the keys, values of the input dict, you can fill the second
> > > > dict. Then you can scan the second dict, and create a list that
> > > > contains only value lists longer than one.
>
> > > > Bye,
> > > > bearophile
>
> > > Is it niet possible with one or two statement, maybe with list
> > > comprehension. For exmple:
>
> > > l = [(k,v) for k in d.keys() for v in d.values() | en here we need
> > > some extra logic (v = 1)]
>
> > > I don;t konw how we can define a logic statement in a list
> > > comprehension.
> > > It will be very compact, if it would possible.
>
> > > Nader
>
> > If you are going to use this reverse look-up alot you'd be better off
> > building another dictionary with the original values being keys and
> > the original keys being values, if it is used infrequently enough you
> > can search for it with result_list = [k for k,v in dictionary.items()
> > if v == search_value]
>
> Thank you! It is the anwser which I was looking for. [(k,v) for k,v
> in  d.items() if v is pattern].
> But I don't understand what tou mean of "reverse look-up a lot"! I
> have to read some informations inclusive (latitudes and longitudes)
> form a file and after some processing to save part of this information
> to other file.
> Why do I make a new dictionary?
>
> Nader

If you are just going to perform the lookup once or twice then it's
fine to traverse (step through) your original dictionary.  If you are
going to look up data often though it might be a better idea to build
another dictionary with the reverse of your original dictionary as it
will yield faster results.

For example, your original dictionary of values is built and then you
perform a handful of operations and move on, then use the list
comprehension to get your data and move on.  If, on the other hand,
you build your dictionary and then maybe iterate over a file and need
to look-up the information for every line in the file it would be
better suited to build a new dictionary that transposed the key and
value pairs for less resource intensive and faster operation. eg:

reverse_dict = {}
for k,v in original_dict:
if v in reverse_dict:
reverse_dict[v].append(k)
else:
reverse_dict[v] = [k]

Then once that is built and you want to find which keys in the
original dictionary have the value of "1" you can just do
"list_of_keys = reverse_dict[1]".

Essentially if you are going to do alot of searching for values that
match values found in a dictionary you would be better off to create
the new data structure.

Hope that helps.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Plotting Graphs using Gnuplot

2008-06-12 Thread Fuzzyman
On Jun 12, 12:30 pm, [EMAIL PROTECTED] wrote:
> Hello. Was trying to create a simple plotting function. Wasnt working
> however. If i write the same code without putting it inside a function
> it works. :S. Could some1 tell me the problem? Heres the code:
>
> # File name Plotting2
>
> import Gnuplot
>
> def plot(original, expected, actual):
>
> if type (original) != type([]):
> return False
>
> else:
>
> gp = Gnuplot.Gnuplot()
> gp('set data style lines')
>
> # Make the plot items
> plot1 = Gnuplot.PlotItems.Data(original, title="Original")
> plot2 = Gnuplot.PlotItems.Data(expected, title="Expected")
> plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal")
>
> return gp.plot(plot1, plot2, plot3)
>
> 
>
> import Plotting2   #The name of my file...
>
> Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] )

I've no idea about the answer to your question (I don't know how the
Gnuplot module works and I can't *see* anything obviously wrong with
your code), but this line:

   if type (original) != type([])

is better written:

   if not isinstance(original, list):

Michael Foord
http://www.ironpythoninaction.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: regex for balanced parentheses?

2008-06-12 Thread Paul McGuire
On Jun 12, 6:06 am, David C. Ullrich <[EMAIL PROTECTED]> wrote:
> There's no regex that detects balanced parentheses,
> or is there?
>
> That is, search('and so ((x+y)+z) = (x+(y+z))')
> should return '((x+y)+z)'.
>
> Not just a theoretical question, I'm cleaning up
> a large body of TeX code and a regex that did that
> would be very convenient. (Yes, I know it's not
> hard to detect balanced parentheses by hand...)
>
> I don't know that stuff, but I seen to recall reading
> that there's a theoretical notion of "regular expression"
> in CS, and a regular expression in that sense cannot
> do this. But in the same place I read that the actual
> regexes in programming languages include things which
> are not regular expressions in that theoretical sense.
>
> David C. Ullrich

Pyparsing includes several helper methods for building common
expression patterns, such as delimitedList, oneOf, operatorPrecedence,
countedArray - and a fairly recent addition, nestedExpr.  nestedExpr
creates an expression for matching nested text within opening and
closing delimiters, such as ()'s, []'s, {}'s, etc.  The default
delimiters are ()'s.  You can also specify a content expression, so
that pyparsing will look for and construct meaningful results.  The
default is to return any text nested within the delimiters, broken up
by whitespace.

Here is your sample string parsed using the default nestedExpr:
>>> from pyparsing import nestedExpr
>>> for e in nestedExpr().searchString('and so ((x+y)+z) = (x+(y+z))'):
... print e[0]
...
[['x+y'], '+z']
['x+', ['y+z']]

Pyparsing found 2 matches in your input string.  Note that the parens
are gone from the results - nestedExpr returns a nested list
structure, with nesting corresponding to the ()'s found in the
original string.

Pyparsing supports parse-time callbacks, called 'parse actions', and
it comes with several commonly used methods, such as removeQuotes,
upcaseTokens, and keepOriginalText.  The purpose of keepOriginalText
is to revert any structuring or parsing an expression or other parse
actions might do, and just return the originally matched text.

Here is how keepOriginalText gives you back just the nested
parenthetical expressions, without any additional processing or
grouping:
>>> from pyparsing import keepOriginalText
>>> matchedParens = nestedExpr().setParseAction(keepOriginalText)
>>> for e in matchedParens.searchString('and so ((x+y)+z) = (x+(y+z))'):
... print e[0]
...
((x+y)+z)
(x+(y+z))

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


Re: get keys with the same values

2008-06-12 Thread Paul McGuire
On Jun 12, 6:41 am, David C. Ullrich <[EMAIL PROTECTED]> wrote:
> On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <[EMAIL PROTECTED]>
> wrote:
>
> >Hello,
>
> >I have a dictionary and will get all keys which have the same values.
>

>
> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
>
> dd = {}
>
> for key, value in d.items():
>   try:
>     dd[value].append(key)
>   except KeyError:
>     dd[value] = [key]
>


Instead of all that try/except noise, just use the new defaultdict:

>>> from collections import defaultdict
>>>
>>> d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
>>>
>>> dd = defaultdict(list)
>>> for key, value in d.items():
... dd[value].append(key)
...
>>> for k,v in dd.items():
... print k,':',v
...
1 : ['a', 'e']
2 : ['c']
3 : ['b', 'd']
4 : ['f']

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


Summing a 2D list

2008-06-12 Thread Mark
Hi all,

I have a scenario where I have a list like this:

UserScore
1 0
1 1
1 5
2 3
2 1
3 2
4 3
4 3
4 2

And I need to add up the score for each user to get something like
this:

UserScore
1 6
2 4
3 2
4 8

Is this possible? If so, how can I do it? I've tried looping through
the arrays and not had much luck so far.

Any help much appreciated,

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


Re: Summing a 2D list

2008-06-12 Thread Diez B. Roggisch
Mark wrote:

> Hi all,
> 
> I have a scenario where I have a list like this:
> 
> UserScore
> 1 0
> 1 1
> 1 5
> 2 3
> 2 1
> 3 2
> 4 3
> 4 3
> 4 2
> 
> And I need to add up the score for each user to get something like
> this:
> 
> UserScore
> 1 6
> 2 4
> 3 2
> 4 8
> 
> Is this possible? If so, how can I do it? I've tried looping through
> the arrays and not had much luck so far.
> 
> Any help much appreciated,

Show us your efforts in code so far. Especially what the actual data looks
like. Then we can suggest a solution.

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


Re: Plotting Graphs using Gnuplot

2008-06-12 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Hello. Was trying to create a simple plotting function. Wasnt working
> however. If i write the same code without putting it inside a function
> it works. :S. Could some1 tell me the problem? 

Judging from the demo you have to keep a Gnuplot.Gnuplot instance alive. If
you don't, the display window is immediately garbage-collected.

> Heres the code: 
> 
> 
> # File name Plotting2
> 
> import Gnuplot
> 
> def plot(original, expected, actual):
> 
> 
> if type (original) != type([]):
> return False
> 
> else:
> 
> gp = Gnuplot.Gnuplot()
> gp('set data style lines')
> 
> 
> # Make the plot items
> plot1 = Gnuplot.PlotItems.Data(original, title="Original")
> plot2 = Gnuplot.PlotItems.Data(expected, title="Expected")
> plot3 = Gnuplot.PlotItems.Data(actual, title="Acutal")
> 
> 
  gp.plot(plot1, plot2, plot3)
  return gp
> 
> 
> 
> 
> import Plotting2   #The name of my file...
> 
  gp = Plotting2.plot( [(2,3), (3,4)], [(4,5), (5,6)], [(1,3), (4,8)] )
  raw_input()

By the way, I recommend that you raise an Exception instead of returning a
special value when plot() cannot deal with the arguments passed to it.

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


Re: Summing a 2D list

2008-06-12 Thread Benjamin Kaplan
On Thu, Jun 12, 2008 at 9:48 AM, Mark <[EMAIL PROTECTED]> wrote:

> Hi all,
>
> I have a scenario where I have a list like this:
>
> UserScore
> 1 0
> 1 1
> 1 5
> 2 3
> 2 1
> 3 2
> 4 3
> 4 3
> 4 2
>
> And I need to add up the score for each user to get something like
> this:
>
> UserScore
> 1 6
> 2 4
> 3 2
> 4 8
>
> Is this possible? If so, how can I do it? I've tried looping through
> the arrays and not had much luck so far.
>
> Any help much appreciated,
>

If your data is set up as a list of tuples or lists, you can try using a
dictionary for the final count, since each user will have only one final
entry. Then, you can check to see if the user already has an entry in the
dict so you know if you should create a new entry or just add to the old
one.

firstList = [your pairs of data]
totals = {}
for i, j in firstList :
   if i in totals :
  totals[i] += j
   else :
  totals[i] = j


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

Re: re quiz

2008-06-12 Thread David C. Ullrich
On Thu, 12 Jun 2008 05:12:55 -0700 (PDT), John Machin
<[EMAIL PROTECTED]> wrote:

>On Jun 12, 8:57 pm, David C. Ullrich <[EMAIL PROTECTED]> wrote:
>> True or False? (no fair looking it up)
>>
>> (*) If repl is a string then re.sub(pattern, repl, s)
>> returns s with non-overlapping occurences of pattern
>> replaced by repl.
>>
>> I assumed it was true - spent a few hours trying to
>> figure out what was going on with a certain re.sub,
>> then noticed that (*) is false:
>>
>
>Well, the docs do say "Return the string obtained by replacing the
>leftmost non-overlapping occurrences of pattern in string by the
>replacement repl."

That's the _first sentence_, yes. I _quoted_ another sentence
(from an old version, istr it phrased slightly differently in
recent versions) in my post.

> -- care to tell us what "a certain re.sub" is, and
>false in what way?

Read the OP.
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list


Re: Alternative to Decimal type

2008-06-12 Thread Grant Edwards
On 2008-06-12, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

> If you were to follow the footsteps of COBOL, you'd be using
> BCD internally, with a special code to represent the decimal
> point (and maybe, to save space, the sign too)
>
> Old mainframes had instructions to work with packed BCD as a
> register format (the Xerox Sigma series used four 32-bit
> registers to represent a 31 digit packed BCD number). Okay, I
> think even the Pentium's still have a BCD operation set,

IIRC, most general purpose microprocessors I've used had
special instructions to make packed BCD operations easier, and
back in the day (when Pascal was much more popular than C)
compilers for microprocessors usually offered a BCD floating
point data type.

-- 
Grant Edwards   grante Yow! The SAME WAVE keeps
  at   coming in and COLLAPSING
   visi.comlike a rayon MUU-MUU ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Summing a 2D list

2008-06-12 Thread Chris
On Jun 12, 3:48 pm, Mark <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I have a scenario where I have a list like this:
>
> User            Score
> 1                 0
> 1                 1
> 1                 5
> 2                 3
> 2                 1
> 3                 2
> 4                 3
> 4                 3
> 4                 2
>
> And I need to add up the score for each user to get something like
> this:
>
> User            Score
> 1                 6
> 2                 4
> 3                 2
> 4                 8
>
> Is this possible? If so, how can I do it? I've tried looping through
> the arrays and not had much luck so far.
>
> Any help much appreciated,
>
> Mark

user_score = {}
for record in list:
user, score = record.split()
if user in user_score: user_score[user] += score
else: user_score[user] = score

print '\n'.join(['%s\t%s' % (user, score) for user,score in
sorted(user_score.items())])

You don't mention what data structure you are keeping your records in
but hopefully this helps you in the right direction.
--
http://mail.python.org/mailman/listinfo/python-list


Re: re quiz

2008-06-12 Thread David C. Ullrich
On Thu, 12 Jun 2008 14:12:31 +0200, Peter Otten <[EMAIL PROTECTED]>
wrote:

>David C. Ullrich wrote:
>
>> (Or is there a function somewhere that will convert
>> r"\remark{Hint}" to r"\\remark{Hint}" for me, and
>> do the same for precisely the escpapes referred to
>> in the "and so forth"?)
>
>I think you just have to escape the backslash:
>
>re.sub(pattern, replacement_string.replace("\\", ""), s)
>
>Anyway here's the list of troublemakers:

Heh - I shoulda thought of that, determining which
ones cause trouble by checking to see which ones
cause trouble. Thanks.

 def means_trouble(c):
>... try:
>... return re.sub("x", "\\" + c, "x") != "\\" + c
>... except:
>... return True
>...
 [c for c in map(chr, range(256)) if means_trouble(c)]
>['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\\', 'a', 'b', 'f', 'g', 
>'n', 'r', 't', 'v']
>
>
>Peter 

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


Re: Simple and safe evaluator

2008-06-12 Thread Grant Edwards
On 2008-06-12, Hans Nowak <[EMAIL PROTECTED]> wrote:
> bvdp wrote:
>> 
>> Is there a simple/safe expression evaluator I can use in a python 
>> program. I just want to pass along a string in the form "1 + 44 / 3" or 
>> perhaps "1 + (-4.3*5)" and get a numeric result.
>> 
>> I can do this with eval() but I really don't want to subject my users to 
>> the problems with that method.
>> 
>> In this use I don't need python to worry about complex
>> numbers, variables or anything else. Just do the math on a set
>> of values. Would eval() with some restricted list of permitted
>> operators do the trick?
>
> This solution may be overly simply (especially compared to the
> AST-based solution suggested earlier), but... if all you need
> is numbers and operators, *maybe* you can get away with
> stripping all letters from the input string (and possibly the
> underscore), and then evaluating it:

It won't work for numbers expressed in scientific notation
(e.g. 1.23e-3).

-- 
Grant Edwards   grante Yow! All right, you
  at   degenerates!  I want
   visi.comthis place evacuated in
   20 seconds!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Summing a 2D list

2008-06-12 Thread Mark
On Jun 12, 3:02 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Mark wrote:
> > Hi all,
>
> > I have a scenario where I have a list like this:
>
> > User            Score
> > 1                 0
> > 1                 1
> > 1                 5
> > 2                 3
> > 2                 1
> > 3                 2
> > 4                 3
> > 4                 3
> > 4                 2
>
> > And I need to add up the score for each user to get something like
> > this:
>
> > User            Score
> > 1                 6
> > 2                 4
> > 3                 2
> > 4                 8
>
> > Is this possible? If so, how can I do it? I've tried looping through
> > the arrays and not had much luck so far.
>
> > Any help much appreciated,
>
> Show us your efforts in code so far. Especially what the actual data looks
> like. Then we can suggest a solution.
>
> Diez

Hi Diez, thanks for the quick reply.

To be honest I'm relatively new to Python, so I don't know too much
about how all the loop constructs work and how they differ to other
languages. I'm building an app in Django and this data is coming out
of a database and it looks like what I put up there!

This was my (failed) attempt:

predictions = Prediction.objects.all()
scores = []
for prediction in predictions:
i = [prediction.predictor.id, 0]
if prediction.predictionscore:
i[1] += int(prediction.predictionscore)
scores.append(i)

I did have another loop in there (I'm fairly sure I need one) but that
didn't work either. I don't imagine that snippet is very helpful,
sorry!

Any tips would be gratefully recieved!

Thanks,

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


Making wxPython a standard module?

2008-06-12 Thread John Salerno
Just out of curiosity, what are the chances of this happening (sort of like 
what happened with sqlite)? I read somewhere that Guido said the only reason 
Tkinter is still the standard GUI module instead of wxPython is because "it 
was there first." Perhaps a joke, but it got me thinking that there could be 
a chance of this happening.

I'm sure most Python work doesn't involve GUIs, so it's not a priority, but 
to have wxPython be a standard module would be great, and it might even 
encourage people to play around with GUI work more than normal (I don't 
think that's a bad thing!).   :) 


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


Re: Finding a sense of word in a text

2008-06-12 Thread Vlastimil Brom
2008/6/11, Sengly <[EMAIL PROTECTED]>:
>
> Dear all,
>
> This might be off group but I am looking for a python library that can
> help me to find a sense of a word in a text and eventually a list of
> synonyms of that term. I searched the web and found one but it is
> written in perl (http://www.d.umn.edu/~tpederse/senserelate.html) :(
>
> I appreciate any pointers.
>
> Thank you before hand.
>
> Kind regards,
>
> Sengly
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
You may try e.g. NLTK

http://nltk.sourceforge.net/

probably WordNet mentioned in the documentation in the 3rd chapter:

3.6 WordNet: An English Lexical Database  http://nltk.org/doc/en/words.html

 Greetings,

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

Re: re quiz

2008-06-12 Thread David C. Ullrich
On 12 Jun 2008 12:32:13 GMT, Duncan Booth
<[EMAIL PROTECTED]> wrote:

>David C. Ullrich <[EMAIL PROTECTED]> wrote:
>
>> Practical question: What's a _complete_ list of the
>> escapes included in the "and so forth" in (**)?
>> 
>> (Or is there a function somewhere that will convert
>> r"\remark{Hint}" to r"\\remark{Hint}" for me, and
>> do the same for precisely the escpapes referred to
>> in the "and so forth"?)
>> 
>
>As the documentation says:
>
>Character escapes
>Numbered Groups: \0 \1 \2 \3 ...
>Named groups: \g
>Numbered groups with explicit termination of the number: \g<0> \g<1> ...

Right - I was wondering about a complete list of character
escapes.

>But it doesn't matter what the complete list is. All of the escapes start 
>with \ so doubling all the \\ will prevent any of them being interpreted as 
>special so if you aren't wanting to substitute any groups into the string 
>just try repl.replace('\\', r'\\')

Good point.

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


Re: Summing a 2D list

2008-06-12 Thread Aidan

Mark wrote:

Hi all,

I have a scenario where I have a list like this:

UserScore
1 0
1 1
1 5
2 3
2 1
3 2
4 3
4 3
4 2

And I need to add up the score for each user to get something like
this:

UserScore
1 6
2 4
3 2
4 8

Is this possible? If so, how can I do it? I've tried looping through
the arrays and not had much luck so far.

Any help much appreciated,

Mark



does this work for you?


users = [1,1,1,2,2,3,4,4,4]
score = [0,1,5,3,1,2,3,3,2]

d = dict()

for u,s in zip(users,score):
  if d.has_key(u):
d[u] += s
  else:
d[u] = s

for key in d.keys():
  print 'user: %d\nscore: %d\n' % (key,d[key])
--
http://mail.python.org/mailman/listinfo/python-list


Comments on my first script?

2008-06-12 Thread Phillip B Oldham
I'm keen on learning python, with a heavy lean on doing things the
"pythonic" way, so threw the following script together in a few hours
as a first-attempt in programming python.

I'd like the community's thoughts/comments on what I've done;
improvements I can make, "don'ts" I should be avoiding, etc. I'm not
so much bothered about the resulting data - for the moment it meets my
needs. But any comment is welcome!

#!/usr/bin/env python
## Open a file containing a list of domains (1 per line),
## request and parse it's whois record and push to a csv
## file.

import subprocess
import re

src = open('./domains.txt')

dest = open('./whois.csv', 'w');

sep = "|"
headers = ["Domain","Registrant","Registrant's
Address","Registrar","Registrant Type","Date Registered","Renewal
Date","Last Updated","Name Servers"]

dest.write(sep.join(headers)+"\n")

def trim( txt ):
x = []
for line in txt.split("\n"):
if line.strip() == "":
continue
if line.strip().startswith('WHOIS'):
continue
if line.strip().startswith('>>>'):
continue
if line.strip().startswith('%'):
continue
if line.startswith("--"):
return ''.join(x)
x.append(" "+line)
return "\n".join(x)

def clean( txt ):
x = []
isok = re.compile("^\s?([^:]+): ").match
for line in txt.split("\n"):
match = isok(line)
if not match:
continue
x.append(line)
return "\n".join(x);

def clean_co_uk( rec ):
rec = rec.replace('Company number:', 'Company number -')
rec = rec.replace("\n\n", "\n")
rec = rec.replace("\n", "")
rec = rec.replace(": ", ":\n")
rec = re.sub("([^(][a-zA-Z']+\s?[a-zA-Z]*:\n)", "\n\g<0>", rec)
rec = rec.replace(":\n", ": ")
rec = re.sub("^[ ]+\n", "", rec)
return rec

def clean_net( rec ):
rec = rec.replace("\n\n", "\n")
rec = rec.replace("\n", "")
rec = rec.replace(": ", ":\n")
rec = re.sub("([a-zA-Z']+\s?[a-zA-Z]*:\n)", "\n\g<0>", rec)
rec = rec.replace(":\n", ": ")
return rec

def clean_info( rec ):
x = []
for line in rec.split("\n"):
x.append(re.sub("^([^:]+):", "\g<0> ", line))
return "\n".join(x)

def record(domain, record):
details = ['','','','','','','','','']
for k, v in record.items():
try:
details[0] = domain.lower()
result = {
"registrant": lambda: 1,
"registrant name": lambda: 1,
"registrant type": lambda: 4,
"registrant's address": lambda: 2,
"registrant address1": lambda: 2,
"registrar": lambda: 3,
"sponsoring registrar": lambda: 3,
"registered on": lambda: 5,
"registered": lambda: 5,
"domain registeration date": lambda: 5,
"renewal date": lambda: 6,
"last updated": lambda: 7,
"domain last updated date": lambda: 7,
"name servers": lambda: 8,
"name server": lambda: 8,
"nameservers": lambda: 8,
"updated date": lambda: 7,
"creation date": lambda: 5,
"expiration date": lambda: 6,
"domain expiration date": lambda: 6,
"administrative contact": lambda: 2
}[k.lower()]()
if v != '':
details[result] = v
except:
continue

dest.write(sep.join(details)+"\n")

## Loop through domains
for domain in src:

domain = domain.strip()

if domain == '':
continue

rec = subprocess.Popen(["whois",domain],
stdout=subprocess.PIPE).communicate()[0]

if rec.startswith("No whois server") == True:
continue

if rec.startswith("This TLD has no whois server") == True:
continue

rec = trim(rec)

if domain.endswith(".net"):
rec = clean_net(rec)

if domain.endswith(".com"):
rec = clean_net(rec)

if domain.endswith(".tv"):
rec = clean_net(rec)

if domain.endswith(".co.uk"):
rec = clean_co_uk(rec)

if domain.endswith(".info"):
   

Re: Summing a 2D list

2008-06-12 Thread John Salerno
"Mark" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On Jun 12, 3:02 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Mark wrote:

---
This was my (failed) attempt:

predictions = Prediction.objects.all()
scores = []
for prediction in predictions:
i = [prediction.predictor.id, 0]
if prediction.predictionscore:
i[1] += int(prediction.predictionscore)
scores.append(i)
---

Your question sounds like a fun little project, but can you post what the 
actual list of users/scores looks like? Is it a list of tuples like this:

[(1, 0), (1, 1) ... ]

Or something else?


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


Re: regex for balanced parentheses?

2008-06-12 Thread David C. Ullrich
On Thu, 12 Jun 2008 06:38:16 -0700 (PDT), Paul McGuire
<[EMAIL PROTECTED]> wrote:

>On Jun 12, 6:06 am, David C. Ullrich <[EMAIL PROTECTED]> wrote:
>> There's no regex that detects balanced parentheses,
>> or is there?
>>
>> [...]
>
>Pyparsing includes several helper methods for building common
>expression patterns, such as delimitedList, oneOf, operatorPrecedence,
>countedArray - and a fairly recent addition, nestedExpr.  nestedExpr
>creates an expression for matching nested text within opening and
>closing delimiters, such as ()'s, []'s, {}'s, etc. 

Keen. Howdya know I wanted that? Thanks.

TeX is one of the amazing things about free software. Knuth
is great in many ways. He totally blew it in one detail,
unfortunately one that comes up a lot: '$' is an opening
delimiter, for which the corresponding closing delimiter
is also '$'. Then better yet, '$$' is another double-duty
delimiter... what I've done with that is first split
on '$$', taking the odd-numbered bits to be the parts
enclosed in $$..$$, and then taking the remining
parts and splitting on $. Not hard but it gives me a
creepy feeling.

Hence the question: Can pyparsing tell the difference
between '$' and '$'? (heh-heh).

> The default
>delimiters are ()'s.  You can also specify a content expression, so
>that pyparsing will look for and construct meaningful results.  The
>default is to return any text nested within the delimiters, broken up
>by whitespace.
>
>Here is your sample string parsed using the default nestedExpr:
 from pyparsing import nestedExpr
 for e in nestedExpr().searchString('and so ((x+y)+z) = (x+(y+z))'):
>... print e[0]
>...
>[['x+y'], '+z']
>['x+', ['y+z']]
>
>Pyparsing found 2 matches in your input string.  Note that the parens
>are gone from the results - nestedExpr returns a nested list
>structure, with nesting corresponding to the ()'s found in the
>original string.
>
>Pyparsing supports parse-time callbacks, called 'parse actions', and
>it comes with several commonly used methods, such as removeQuotes,
>upcaseTokens, and keepOriginalText.  The purpose of keepOriginalText
>is to revert any structuring or parsing an expression or other parse
>actions might do, and just return the originally matched text.
>
>Here is how keepOriginalText gives you back just the nested
>parenthetical expressions, without any additional processing or
>grouping:
 from pyparsing import keepOriginalText
 matchedParens = nestedExpr().setParseAction(keepOriginalText)
 for e in matchedParens.searchString('and so ((x+y)+z) = (x+(y+z))'):
>... print e[0]
>...
>((x+y)+z)
>(x+(y+z))
>
>-- Paul

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


Re: Summing a 2D list

2008-06-12 Thread Diez B. Roggisch
> To be honest I'm relatively new to Python, so I don't know too much
> about how all the loop constructs work and how they differ to other
> languages. I'm building an app in Django and this data is coming out
> of a database and it looks like what I put up there!
> 
> This was my (failed) attempt:
> 
> predictions = Prediction.objects.all()
> scores = []
> for prediction in predictions:
> i = [prediction.predictor.id, 0]
> if prediction.predictionscore:
> i[1] += int(prediction.predictionscore)
> scores.append(i)
> 
> I did have another loop in there (I'm fairly sure I need one) but that
> didn't work either. I don't imagine that snippet is very helpful,
> sorry!

It is helpful because it tells us what your actual data looks like. 

What you need is to get a list of (predictor, score)-pairs. These you should
be able to get like this:

l = [(p.predictor.id, p.predictionscore) for p in predictions]

Now you need to sort this list - because in the next step, we will aggregate
the values for each predictor.

result = []
current_predictor = None
total_sum = 0
for predictor, score in l:
if predictor != current_predictor:
   # only if we really have a current_predictor, 
   # the non-existent first one doesn't count
   if current_predictor is not None:
   result.append((predictor, total_sum))
   total_sum = 0
   current_predictor = predictor
total_sum += score

That should be roughly it.

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


Re: Summing a 2D list

2008-06-12 Thread Mark
John, it's a QuerySet coming from a database in Django. I don't know
enough about the structure of this object to go into detail I'm
afraid.

Aidan, I got an error trying your suggestion: 'zip argument #2 must
support iteration', I don't know what this means!

Thanks to all who have answered! Sorry I'm not being very specific!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Summing a 2D list

2008-06-12 Thread Aidan

Mark wrote:

John, it's a QuerySet coming from a database in Django. I don't know
enough about the structure of this object to go into detail I'm
afraid.

Aidan, I got an error trying your suggestion: 'zip argument #2 must
support iteration', I don't know what this means!


well, if we can create 2 iterable sequences one which contains the user 
the other the scores, it should work


the error means that the second argument to the zip function was not an 
iterable, such as a list tuple or string


can you show me the lines you're using to retrieve the data sets from 
the database? then i might be able to tell you how to build the 2 lists 
you need.



Thanks to all who have answered! Sorry I'm not being very specific!

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


Re: Making wxPython a standard module?

2008-06-12 Thread Diez B. Roggisch
> Just out of curiosity, what are the chances of this happening (sort of
> like what happened with sqlite)? I read somewhere that Guido said the only
> reason Tkinter is still the standard GUI module instead of wxPython is
> because "it was there first." Perhaps a joke, but it got me thinking that
> there could be a chance of this happening.

This has been discussed before. While tkInter might not be the greatest
toolkit out there it has two extreme advantages:

   - it is comparably small regarding the footprint. Few external
dependencies, small libraries, small python-wrapping.

   - it is available on a wide range of platforms.

   - it is very stable, not only wrt bugs but also regarding features. There
is no external pressure to update it frequently.

   - it is easily maintainable.

None of these apply to wx. It is huge, needs for example the whole GTK-libs
under linux. It is under active development, with rather frequent releases,
which means it is better to not tie it to a certain version because that
happens to be the version available when the current interpreter was
released.

For example, think of python2.4 - it has been released 4(!) years ago. It is
in wide usage. Around that time wx was at version 2.5. Now it is 2.8. So
either you upgrade wx in the subsequent released pyhton 2.4 versions - or
you are stuck with 3 minor revisions in the past, which I can only assume
are a major drawback.

And on a personal note: I find it *buttugly*. But that has nothing to do
with the reasons given above - nor do I have any weight in the decision to
include it or not... :)

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


Re: Making wxPython a standard module?

2008-06-12 Thread Paul Boddie
On 12 Jun, 16:18, "John Salerno" <[EMAIL PROTECTED]> wrote:
> Just out of curiosity, what are the chances of this happening (sort of like
> what happened with sqlite)?

Plenty of prior discussion here:

http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=wxPython+standard+library

I doubt that the situation has changed in any significant way.

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


Re: Summing a 2D list

2008-06-12 Thread Aidan

Aidan wrote:

Mark wrote:

John, it's a QuerySet coming from a database in Django. I don't know
enough about the structure of this object to go into detail I'm
afraid.

Aidan, I got an error trying your suggestion: 'zip argument #2 must
support iteration', I don't know what this means!


well, if we can create 2 iterable sequences one which contains the user 
the other the scores, it should work


the error means that the second argument to the zip function was not an 
iterable, such as a list tuple or string


can you show me the lines you're using to retrieve the data sets from 
the database? then i might be able to tell you how to build the 2 lists 
you need.




wait you already did...

predictions = Prediction.objects.all()
pairs = [(p.predictor.id,p.predictionscore) for p in predictions]

those 2 lines will will build a list of user/score pairs.  you can then 
replace the call to zip with pairs


any luck?

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


Making wxPython a standard module?

2008-06-12 Thread Andrea Gavana
Hi Diez & All,

> And on a personal note: I find it *buttugly*.

Do you mind explaining "why" you find it *buttugly*? I am asking just
out of curiosity, obviously. I am so biased towards wxPython that I
won't make any comment on this thread in particular, but I am curious
to know why some people find it "ugly" or "bad" or whatever. It has
its own bugs and missing features, of course, but it is one of the
major GUI player in the arena, together with PyQt and PyGTK.

Andrea.

"Imagination Is The Only Weapon In The War Against Reality."
http://xoomer.alice.it/infinity77/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Strange cjson bug doesn't occur in Pydb

2008-06-12 Thread kj

[Note: I changed the subject line to make it more informative.]

In <[EMAIL PROTECTED]> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:

>kj wrote:

>> In <[EMAIL PROTECTED]> "Diez B. Roggisch"
>> <[EMAIL PROTECTED]> writes:
>> 
>>>kj schrieb:
 I'm running into a strange seg fault with the module cjson.  The
 strange part is that it does not occur when I run the code under
 Emacs' Pydb.
 
 Here's an example:
 
 
 import sys, cjson
 
 d1 = {'a': 1, 'b': 2, 'c': 3}
 print sys.version
 j1 = cjson.encode(d1)
 print j1   # should print the string '{"a": 1, "c": 3, "b": 2}'
 
 The code above runs fine under Pydb, but segfaults at the call to
 cjson.encode when I run it from the command line in a standard
 Linux shell interaction.  In the printed version strings are
 identical.
 
 I figure this must be a bug in cjson.  I'd love to find a workaround
 for it, and hope that this strange difference between Pydb and the
 shell command line may be a clue to that.
 
 Any thoughts?
>> 
>>>Are you sure you actually run the same interpreter in emacs as you do on
>>>the commandline?
>> 
>> No, I'm not.  All I know is that both Emacs and the commandline
>> are running on the same machine, and that the version string that
>> the program prints is the same in both conditions.  How can I verify
>> that that the same interpreter is running in both cases?

>By e.g. 

>import sys
>print sys.prefix

>Additionally, you should compare what

>sys.path

>contains and if it's the same - otherwise it might be that cjson is picked
>up from somewhere else.

>If all that's the case, I'd invoke python through gdb and see where the
>segfault happens.


Thanks for that suggestion.  I did so, and this is gdb's output at
the time failure:

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 47622454277872 (LWP 14555)]
encode_object (object=0x777390) at cjson.c:946
946 temp = PyList_GET_ITEM(pieces, 0);

In my experience, however, the root cause of a segfault is often
quite far away in the code from where it is triggered...

Anyway, thanks for your help.

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
--
http://mail.python.org/mailman/listinfo/python-list


Plotting Graph Functions using Gnuplot

2008-06-12 Thread arslanburney
Hello. Needed some help again. Im trying to calculate the best fit
line here. Given a set of points in a list. However, wirte in the end
where i plot the line it tells me tht the variable is not defined.
Either try correcting this or tell me a subsitute that i could use.
Thnks. Heres the code:


#File name Bestfit.py

import Gnuplot

def bestfit(uinput):

if not isinstance(uinput, list):
return False

else:


sigmax = sigmay = sigmaxy = sigmaxwhl = sigmaxsq = 0

for i in range(len(uinput)):

n = len(uinput)

sigmax = uinput[i][0] + sigmax
sigmay = uinput[i][1] + sigmay
sigmaxy = uinput[i][0] * uinput [i][1] + sigmaxy
sigmaxwhl = sigmax * sigmax
sigmaxsq = uinput[i][0] * uinput[i][0] + sigmaxsq
sigmaxsigmay = sigmax * sigmay

num = sigmaxsigmay - (n * sigmaxy)
den = sigmaxwhl - (n* sigmaxsq)

num2 = (sigmax * sigmaxy) - (sigmay * sigmaxsq)


gradient = num / den

intercept = num2 / den

m = gradient
c = intercept


y = m*x + c
plot (y)


---

import Bestfit

Bestfit.bestfit([(2,3), (3,8), (5,7), (4,9)])
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making wxPython a standard module?

2008-06-12 Thread Mike Driscoll
On Jun 12, 9:55 am, "Andrea Gavana" <[EMAIL PROTECTED]> wrote:
> Hi Diez & All,
>
> > And on a personal note: I find it *buttugly*.
>
> Do you mind explaining "why" you find it *buttugly*? I am asking just
> out of curiosity, obviously. I am so biased towards wxPython that I
> won't make any comment on this thread in particular, but I am curious
> to know why some people find it "ugly" or "bad" or whatever. It has
> its own bugs and missing features, of course, but it is one of the
> major GUI player in the arena, together with PyQt and PyGTK.
>
> Andrea.
>
> "Imagination Is The Only Weapon In The War Against 
> Reality."http://xoomer.alice.it/infinity77/


I'm curious too. I like wxPython because the widgets actually "look"
the way they should in a cross-platform way (for the most part)
because they use the actual widgets sets of the OS. Tkinter draws
everything and can look kind of weird on Windows, although I have seen
some very nice looking programs that use it.

Of course, wx doesn't really do "skinning", so in that respect it may
be hampered more than some of the other toolkits that Andrea
mentioned. I really don't know.

---
Mike Driscoll

Blog:   http://blog.pythonlibrary.org
Python Extension Building Network: http://www.pythonlibrary.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: can't assign to literal

2008-06-12 Thread Ethan Furman

TheSaint wrote:

On 01:37, giovedì 12 giugno 2008 Ethan Furman wrote:



Do you mean indenting, or wrapping?


I mean fill the line by increasing spaces between words in order to get a
paragraph aligned both side, left and right on the page.
So if the width is 78 chars it wouldn't have jig saw end to the right side,
unless applying some word hyphenation.
This feature would be nice for writing here and some plain documentation
plain text. Beside that it might doing for Python scripts as well.



I don't think justification is built in.  It does offer it's own script 
language, though, so you could write your own function to do that, and 
then only apply it to the doc strings, etc.

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


Re: Summing a 2D list

2008-06-12 Thread Gerhard Häring

Mark wrote:

John, it's a QuerySet coming from a database in Django. I don't know
enough about the structure of this object to go into detail I'm
afraid. [...]


Then let the database do the summing up. That's what it's there for :-)

select user, sum(score) from score_table
group by user

or something very similar, depending on the actual database schema. I 
don't know how to do this with Django's ORM, but is the way to do it in 
plain SQL.


-- Gerhard

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


Counting things fast - was Re: Summing a 2D list

2008-06-12 Thread Gerhard Häring

Aidan wrote:

does this work for you?

users = [1,1,1,2,2,3,4,4,4]
score = [0,1,5,3,1,2,3,3,2]

d = dict()

for u,s in zip(users,score):
  if d.has_key(u):
d[u] += s
  else:
d[u] = s

for key in d.keys():
  print 'user: %d\nscore: %d\n' % (key,d[key])


I've recently had the very same problem and needed to optimize for the 
best solution. I've tried quite a few, including:


1) using a dictionary with a default value

d = collections.defaultdict(lambda: 0)
d[key] += value

2) Trying out if avoiding object allocation is worth the effort. Using 
Cython:


cdef class Counter:
cdef int _counter
def __init__(self):
self._counter = 0

def inc(self):
self._counter += 1

def __int__(self):
return self._counter

def __iadd__(self, operand):
self._counter += 1
return self

And no, this was *not* faster than the final solution. This counter 
class, which is basically a mutable int, is exactly as fast as just 
using this one (final solution) - tada!


counter = {}
try:
counter[key] += 1
except KeyError:
counter[key] = 1

Using psyco makes this a bit faster still. psyco can't optimize 
defaultdict or my custom Counter class, though.


-- Gerhard

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


Re: Comments on my first script?

2008-06-12 Thread John Salerno
"Phillip B Oldham" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I'd like the community's thoughts/comments on what I've done;
> improvements I can make, "don'ts" I should be avoiding, etc. I'm not
> so much bothered about the resulting data - for the moment it meets my
> needs. But any comment is welcome!

I'm not expert, but here are a few thoughts. I hope they help.

> #!/usr/bin/env python
> ## Open a file containing a list of domains (1 per line),
> ## request and parse it's whois record and push to a csv
> ## file.

You might want to look into doc strings as a method of providing longer 
documentation like this about what your program does.

> dest = open('./whois.csv', 'w');

Semicolon :)

> def trim( txt ):
> x = []
> for line in txt.split("\n"):
> if line.strip() == "":
> continue
> if line.strip().startswith('WHOIS'):
> continue
> if line.strip().startswith('>>>'):
> continue
> if line.strip().startswith('%'):
> continue
> if line.startswith("--"):
> return ''.join(x)

Is all this properly indented? One thing you can do is put each of these on 
one line, since they are fairly simple:

if line.strip().startswith('WHOIS'): continue

although I still like proper indentation. But you have a lot of them so it 
might save a good amount of space to do it this way.

Also, just my personal preference, I like to be consistent with the type of 
quotes I use for strings. Here, you mix both single and double quotes on 
different lines.

> return "\n".join(x);

Semicolon  :) :)

> details = ['','','','','','','','','']

I don't have Python available to me right now, but I think you can do this 
instead:

details = [''] * 9

> except:
> continue

Non-specific except clauses usually aren't preferred since they catch 
everything, even something you might not want to catch.

> if domain == '':
> continue

You can say:

if not domain

instead of that equivalence test. But what does this if statement do?

> if rec.startswith("No whois server") == True:
> continue
>
> if rec.startswith("This TLD has no whois server") == True:
> continue

Like above, you don't need "== True" here.

> if domain.endswith(".net"):
> rec = clean_net(rec)
>
> if domain.endswith(".com"):
> rec = clean_net(rec)
>
> if domain.endswith(".tv"):
> rec = clean_net(rec)
>
> if domain.endswith(".co.uk"):
> rec = clean_co_uk(rec)
>
> if domain.endswith(".info"):
> rec = clean_info(rec)

Hmm, my first thought is to do something like this with all these if tests:

for extension in []:
rec = clean_net(extension)

But for that to work, you may need to generalize the clean_net function so 
it works for all of them, instead of having to call different functions 
depending on the extension.

Anyway, I hope some of that helps! 


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


Re: time.clock() or Windows bug?

2008-06-12 Thread mgenti
Don't forget that timeit module uses time.clock on windows as well:
if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time
http://svn.python.org/view/python/trunk/Lib/timeit.py

--Mark

On Jun 9, 5:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> Theo v. Werkhoven <[EMAIL PROTECTED]> wrote:
>
>
>
> >  The carbonbased lifeform Nick Craig-Wood inspired comp.lang.python with:
> > > Theo v. Werkhoven <[EMAIL PROTECTED]> wrote:
> > >>  Output:
> > >>  Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm
> > > [snip]
> > >>  Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm
> > >>  Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm
> > >>  Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm
> > >>  Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm
> > >>  Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm
> > >>  Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm
> > >>  Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm
> > >>  Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm
> > > [snip]
> > >>  But look at the timestamps of samples 21, 22 and 43.
> > >>  What is causing this?
> > >>  I've replaced the time.clock() with time.time(), and that seems to
> > >>  solve the problem, but I would like to know if it's something I
> > >>  misunderstand or if it's a problem with the platform (Windows Server
> > >>  2003) or the time.clock() function.
>
> > > time.clock() uses QueryPerformanceCounter under windows.  There are
> > > some known problems with that (eg with Dual core AMD processors).
>
> > > Seehttp://msdn.microsoft.com/en-us/library/ms644904.aspx
>
> > > And in particular
>
> > >     On a multiprocessor computer, it should not matter which processor
> > >     is called. However, you can get different results on different
> > >     processors due to bugs in the basic input/output system (BIOS) or
> > >     the hardware abstraction layer (HAL). To specify processor
> > >     affinity for a thread, use the SetThreadAffinityMask function.
>
> >  Alright, that explains that then.
>
> > > I would have said time.time is what you want to use anyway though
> > > because under unix time.clock() returns the elapsed CPU time which is
> > > not what you want at all!
>
> >  You're right, using fuctions that do not work cross platform isn't
> >  smart.
>
> Actually there is one good reason for using time.clock() under Windows
> - because it is much higher precision than time.time().  Under Windows
> time.time() is only accurate at best 1ms, and in fact it is a lot
> worse than that.
>
> Under Win95/98 it has a 55ms granularity and under Vista time().time()
> changes in 15ms or 16ms steps.
>
> Under unix, time.clock() is pretty much useless because it measures
> CPU time (with a variable precision, maybe 10ms, maybe 1ms), and
> time.time() has a precision of about 1us (exact precision depending on
> lots of things!).
>
> """
> Test timing granularity
>
> Under Vista this produces
>
> C:\>time_test.py
>   15000us -  40 times
>   16000us -  60 times
>
> Under linux 2.6 this produces
>
> $ python time_test.py
>       1us - 100 times
>
> """
>
> from time import time
>
> granularities = {}
>
> for i in range(100):
>     x = time()
>     j = 0
>     while 1:
>         y = time()
>         if x != y:
>             dt = int(100*(y - x)+0.5)
>             granularities[dt] = granularities.get(dt, 0) + 1
>             break
>         j += 1
>
> dts = granularities.keys()
> dts.sort()
> for dt in dts:
>     print "%7dus - %3d times" % (dt, granularities[dt])
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick

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


Re: re quiz

2008-06-12 Thread Johannes Bauer

David C. Ullrich schrieb:


-- care to tell us what "a certain re.sub" is, and
false in what way?


Read the OP.


Well, aren't you funny. Maybe you should have referenced the other 
thread so one can find the OP?


Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
  in de.sci.electronics <[EMAIL PROTECTED]>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making wxPython a standard module?

2008-06-12 Thread John Salerno
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> This has been discussed before. While tkInter might not be the greatest
> toolkit out there it has two extreme advantages:
>
>   - it is comparably small regarding the footprint. Few external
> dependencies, small libraries, small python-wrapping.
>
>   - it is available on a wide range of platforms.
>
>   - it is very stable, not only wrt bugs but also regarding features. 
> There
> is no external pressure to update it frequently.
>
>   - it is easily maintainable.

Ok, that was more than two advantages! :) But those are good points. I was 
wondering about the size of wx too. Probably huge compared to Tkinter.

> And on a personal note: I find it *buttugly*. But that has nothing to do
> with the reasons given above - nor do I have any weight in the decision to
> include it or not... :)

You find what ugly? The look of wxPython apps, or the code itself? To me it 
seems very nice, but what do I know! I also have started using XRC (putting 
the GUI in an xml file instead of in the program), so I see less of the code 
clutter my program. 


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


Re: Comments on my first script?

2008-06-12 Thread John Salerno
"John Salerno" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> if domain.endswith(".net"):
>> rec = clean_net(rec)
>>
>> if domain.endswith(".com"):
>> rec = clean_net(rec)
>>
>> if domain.endswith(".tv"):
>> rec = clean_net(rec)
>>
>> if domain.endswith(".co.uk"):
>> rec = clean_co_uk(rec)
>>
>> if domain.endswith(".info"):
>> rec = clean_info(rec)
>
> Hmm, my first thought is to do something like this with all these if 
> tests:
>
> for extension in []:
>rec = clean_net(extension)

Whoops, you'd still need an if test in there I suppose!

for extension in []:
if domain.endswith(extension):
rec = clean_net(extension)

Not sure if this is ideal. 


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


Re: regex for balanced parentheses?

2008-06-12 Thread Paul McGuire
Parsing TeX is definitely not for the faint-of-heart!  You might try
something like QuotedString('$', escQuote='$$') in pyparsing.  (I've
not poked at TeX or its ilk since the mid-80's so my TeXpertise is
long rusted away.)

I know of two projects that have taken on the problem using pyparsing
- one is the mathtext module in John Hunter's matplotlib, and Tim
Arnold posted some questions on the subject a while back - try
googling for "pyparsing tex" for further leads.

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


Re: Making wxPython a standard module?

2008-06-12 Thread Ed Leafe

On Jun 12, 2008, at 10:55 AM, Andrea Gavana wrote:


And on a personal note: I find it *buttugly*.


Do you mind explaining "why" you find it *buttugly*? I am asking just
out of curiosity, obviously. I am so biased towards wxPython that I
won't make any comment on this thread in particular, but I am curious
to know why some people find it "ugly" or "bad" or whatever. It has
its own bugs and missing features, of course, but it is one of the
major GUI player in the arena, together with PyQt and PyGTK.


Perhaps he meant the code, and not the results?

-- Ed Leafe



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


Re: Comments on my first script?

2008-06-12 Thread Chris
On Jun 12, 4:27 pm, Phillip B Oldham <[EMAIL PROTECTED]> wrote:
> I'm keen on learning python, with a heavy lean on doing things the
> "pythonic" way, so threw the following script together in a few hours
> as a first-attempt in programming python.
>
> I'd like the community's thoughts/comments on what I've done;
> improvements I can make, "don'ts" I should be avoiding, etc. I'm not
> so much bothered about the resulting data - for the moment it meets my
> needs. But any comment is welcome!
>
> #!/usr/bin/env python
> ## Open a file containing a list of domains (1 per line),
> ## request and parse it's whois record and push to a csv
> ## file.
>
> import subprocess
> import re
>
> src = open('./domains.txt')
>
> dest = open('./whois.csv', 'w');
>
> sep = "|"
> headers = ["Domain","Registrant","Registrant's
> Address","Registrar","Registrant Type","Date Registered","Renewal
> Date","Last Updated","Name Servers"]
>
> dest.write(sep.join(headers)+"\n")
>
> def trim( txt ):
>         x = []
>         for line in txt.split("\n"):
>                 if line.strip() == "":
>                         continue
>                 if line.strip().startswith('WHOIS'):
>                         continue
>                 if line.strip().startswith('>>>'):
>                         continue
>                 if line.strip().startswith('%'):
>                         continue
>                 if line.startswith("--"):
>                         return ''.join(x)
>                 x.append(" "+line)
>         return "\n".join(x)
>
> def clean( txt ):
>         x = []
>         isok = re.compile("^\s?([^:]+): ").match
>         for line in txt.split("\n"):
>                 match = isok(line)
>                 if not match:
>                         continue
>                 x.append(line)
>         return "\n".join(x);
>
> def clean_co_uk( rec ):
>         rec = rec.replace('Company number:', 'Company number -')
>         rec = rec.replace("\n\n", "\n")
>         rec = rec.replace("\n", "")
>         rec = rec.replace(": ", ":\n")
>         rec = re.sub("([^(][a-zA-Z']+\s?[a-zA-Z]*:\n)", "\n\g<0>", rec)
>         rec = rec.replace(":\n", ": ")
>         rec = re.sub("^[ ]+\n", "", rec)
>         return rec
>
> def clean_net( rec ):
>         rec = rec.replace("\n\n", "\n")
>         rec = rec.replace("\n", "")
>         rec = rec.replace(": ", ":\n")
>         rec = re.sub("([a-zA-Z']+\s?[a-zA-Z]*:\n)", "\n\g<0>", rec)
>         rec = rec.replace(":\n", ": ")
>         return rec
>
> def clean_info( rec ):
>         x = []
>         for line in rec.split("\n"):
>                 x.append(re.sub("^([^:]+):", "\g<0> ", line))
>         return "\n".join(x)
>
> def record(domain, record):
>         details = ['','','','','','','','','']
>         for k, v in record.items():
>                 try:
>                         details[0] = domain.lower()
>                         result = {
>                                 "registrant": lambda: 1,
>                                 "registrant name": lambda: 1,
>                                 "registrant type": lambda: 4,
>                                 "registrant's address": lambda: 2,
>                                 "registrant address1": lambda: 2,
>                                 "registrar": lambda: 3,
>                                 "sponsoring registrar": lambda: 3,
>                                 "registered on": lambda: 5,
>                                 "registered": lambda: 5,
>                                 "domain registeration date": lambda: 5,
>                                 "renewal date": lambda: 6,
>                                 "last updated": lambda: 7,
>                                 "domain last updated date": lambda: 7,
>                                 "name servers": lambda: 8,
>                                 "name server": lambda: 8,
>                                 "nameservers": lambda: 8,
>                                 "updated date": lambda: 7,
>                                 "creation date": lambda: 5,
>                                 "expiration date": lambda: 6,
>                                 "domain expiration date": lambda: 6,
>                                 "administrative contact": lambda: 2
>                         }[k.lower()]()
>                         if v != '':
>                                 details[result] = v
>                 except:
>                         continue
>
>         dest.write(sep.join(details)+"\n")
>
> ## Loop through domains
> for domain in src:
>
>         domain = domain.strip()
>
>         if domain == '':
>                 continue
>
>         rec = subprocess.Popen(["whois",domain],
> stdout=subprocess.PIPE).communicate()[0]
>
>         if rec.startswith("No whois server") == True:
>                 continue
>
>         if rec.startswith("This TLD has no whois server") == True:
>                 continue
>
>         rec = trim(rec)
>
>         if domain.endswith(".net"):
>  

Re: Summing a 2D list

2008-06-12 Thread Mark
On Jun 12, 3:45 pm, Aidan <[EMAIL PROTECTED]> wrote:
> Aidan wrote:
> > Mark wrote:
> >> John, it's a QuerySet coming from a database in Django. I don't know
> >> enough about the structure of this object to go into detail I'm
> >> afraid.
>
> >> Aidan, I got an error trying your suggestion: 'zip argument #2 must
> >> support iteration', I don't know what this means!
>
> > well, if we can create 2 iterable sequences one which contains the user
> > the other the scores, it should work
>
> > the error means that the second argument to the zip function was not an
> > iterable, such as a list tuple or string
>
> > can you show me the lines you're using to retrieve the data sets from
> > the database? then i might be able to tell you how to build the 2 lists
> > you need.
>
> wait you already did...
>
> predictions = Prediction.objects.all()
> pairs = [(p.predictor.id,p.predictionscore) for p in predictions]
>
> those 2 lines will will build a list of user/score pairs.  you can then
> replace the call to zip with pairs
>
> any luck?

Thanks Aidan, this works great!

Thanks also to everyone else, I'm sure your suggestions would have
worked too if I'd been competent enough to do them properly!
--
http://mail.python.org/mailman/listinfo/python-list


FPC: Exception : Unknown Run-Time error : 210

2008-06-12 Thread Sa�a Bistrovi�
Sa¹a Bistroviæ
Antuna Mihanviæa 13
4 Èakovec
Croatia
[EMAIL PROTECTED]

FPC: Exception : Unknown Run-Time error : 210

Hi, I'm Sa¹a from Croatia.

And I have :

Windows XP PRO SP3.
Pentium II MMX 400MHz.
256 MB of RAM.

I tried to compile fp.pas.

But I get this error message :

'Running "c:\fpc\fpcbuild-2.2.0\fpcsrc\ide\fp.exe "'
'Starting value of ConsoleMode is $001F'
'Compiler Verison  f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . 
e x e ' + same unknown exe characters as for GBD Verison
'GBD Verison  f p c b u i l d - 2 . 2 . 0 \ f p c s r c \ i d e \ f p . e x 
e ' + same unknown exe characters as for Compiler Verison
'Cygwin "C:\FPC\222A5D~1.0\BIN\I386-W~1\cygwin1.dll" version 1005.18.0.0'
'An unhandled exception occurred at $004A74E6'
'Exception : Unknown Run-Time error : 210'
'  $004A74E6 TSWITCHES__ADDBOOLEANITEM,  line 602 of 
c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas'
'  $004A92F4 INITSWITCHES,  line 1150 of 
c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/FPSwitch.pas'
'  $004020DF main,  line 382 of c:/fpc/fpcbuild-2.2.0/fpcsrc/ide/fp.pas' 


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

Re: Making wxPython a standard module?

2008-06-12 Thread Andrea Gavana
Hi Ed & All,

On Thu, Jun 12, 2008 at 4:11 PM, Ed Leafe wrote:
> On Jun 12, 2008, at 10:55 AM, Andrea Gavana wrote:
>
>>> And on a personal note: I find it *buttugly*.
>>
>> Do you mind explaining "why" you find it *buttugly*? I am asking just
>> out of curiosity, obviously. I am so biased towards wxPython that I
>> won't make any comment on this thread in particular, but I am curious
>> to know why some people find it "ugly" or "bad" or whatever. It has
>> its own bugs and missing features, of course, but it is one of the
>> major GUI player in the arena, together with PyQt and PyGTK.
>
>Perhaps he meant the code, and not the results?

Maybe. But I remember a nice quote made in the past by Roger Binns (4
years ago):

"""
The other thing I failed to mention is that the wxPython API isn't very
Pythonic.  (This doesn't matter to people like me who are used to GUI
programming - the wxPython API is very much in the normal style for GUI
APIs.)
"""

Whether the wxPython style is "Pythonic" or not (whatever "Pythonic"
means), this is a one-degree-above-insignificant issue for me. What I
care is the eye pleasing look of my apps and how easy it is to code
with a GUI framework. wxPython gives me both, the rest is just
academic discussion.
But I don't want to start another GUI war, let's save the bandwidth...
there are plenty of GUI frameworks around, every newbie in the GUI
world should try them and stick with the one he/she feels more
confortable with.

Andrea.

"Imagination Is The Only Weapon In The War Against Reality."
http://xoomer.alice.it/infinity77/
--
http://mail.python.org/mailman/listinfo/python-list


Re: regex for balanced parentheses?

2008-06-12 Thread Tim Arnold
"Paul McGuire" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Parsing TeX is definitely not for the faint-of-heart!  You might try
> something like QuotedString('$', escQuote='$$') in pyparsing.  (I've
> not poked at TeX or its ilk since the mid-80's so my TeXpertise is
> long rusted away.)
>
> I know of two projects that have taken on the problem using pyparsing
> - one is the mathtext module in John Hunter's matplotlib, and Tim
> Arnold posted some questions on the subject a while back - try
> googling for "pyparsing tex" for further leads.
>
> -- Paul

Definitely agree that TeX can get pretty complicated. My method (writing a 
converter from one TeX tag system to another)  was to pre-parse using string 
match/replace for really simple stuff, regular expressions for the more 
complex and pyparsing for the really tough stuff.

One thing that was surprisingly hard for me to figure out was filtering out 
comments. I finally just looped through the file line by line, looking for a 
'%' that wasn't in a verbatim environment and wasn't escaped, etc.
Funny how sometimes the simplest thing can be difficult to handle.

Definitely pyparsing made the job possible; I can't imagine that job without 
it.

--Tim Arnold



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


Re: Making wxPython a standard module?

2008-06-12 Thread bearophileHUGS
Andrea Gavana:
> Maybe. But I remember a nice quote made in the past by Roger Binns (4
> years ago):
> """
> The other thing I failed to mention is that the wxPython API isn't very
> Pythonic.  (This doesn't matter to people like me who are used to GUI
> programming - the wxPython API is very much in the normal style for GUI
> APIs.)
> """

There was a WX wrapper project named WAX (http://zephyrfalcon.org/
waxapi/wx._core.Image.html ) that was trying to create a more pythonic
API for WX that I have appreciated. But most people was not
interested, so once the original developer has lost interest, no one
else has improved the code, so the project has died...

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


Re: Simple and safe evaluator

2008-06-12 Thread Matimus
On Jun 11, 9:16 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Jun 11, 8:15 pm, bvdp <[EMAIL PROTECTED]> wrote:
>
>
>
> > Matimus wrote:
>
> > > The solution I posted should work and is safe. It may not seem very
> > > readable, but it is using Pythons internal parser to parse the passed
> > > in string into an abstract symbol tree (rather than code). Normally
> > > Python would just use the ast internally to create code. Instead I've
> > > written the code to do that. By avoiding anything but simple operators
> > > and literals it is guaranteed safe.
>
> > Just wondering ... how safe would:
>
> >  eval(s, {"__builtins__":None}, {} )
>
> > be? From my testing it seems that it parses out numbers properly (int
> > and float) and does simple math like +, -, **, etc. It doesn't do
> > functions like int(), sin(), etc ... but that is fine for my puposes.
>
> > Just playing a bit, it seems to give the same results as your code using
> > ast does. I may be missing something!
>
> Probably you do; within a couple of minutes I came up with this:
>
> >>> s = """
>
> ... (t for t in 42 .__class__.__base__.__subclasses__()
> ...  if t.__name__ == 'file').next()('/etc/passwd')
> ... """>>> eval(s, {"__builtins__":None}, {} )
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in 
> IOError: file() constructor not accessible in restricted mode
>
> Not an exploit yet but I wouldn't be surprised if there is one. Unless
> you fully trust your users, an ast-based approach is your best bet.
>
> George

You can get access to any new-style class that has been loaded. This
exploit works on my machine (Windows XP).

[code]
# This assumes that ctypes was loaded, but keep in mind any classes
# that have been loaded are potentially accessible.

import ctypes

s = """
(
t for t in 42 .__class__.__base__.__subclasses__()
if t.__name__ == 'LibraryLoader'
).next()(
(
t for t in 42 .__class__.__base__.__subclasses__()
if t.__name__ == 'CDLL'
).next()
).msvcrt.system('dir') # replace 'dir' with something nasty
"""

eval(s, {"__builtins__":None}, {})
[/code]

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


Re: Making wxPython a standard module?

2008-06-12 Thread David C. Ullrich
In article <[EMAIL PROTECTED]>,
 "Andrea Gavana" <[EMAIL PROTECTED]> wrote:

> Hi Diez & All,
> 
> > And on a personal note: I find it *buttugly*.
> 
> Do you mind explaining "why" you find it *buttugly*? 

My guess would be that "buttugly" is a colloquialism
meaning "exquisitely lovely". 

>I am asking just
> out of curiosity, obviously. I am so biased towards wxPython that I
> won't make any comment on this thread in particular, but I am curious
> to know why some people find it "ugly" or "bad" or whatever. It has
> its own bugs and missing features, of course, but it is one of the
> major GUI player in the arena, together with PyQt and PyGTK.
> 
> Andrea.
> 
> "Imagination Is The Only Weapon In The War Against Reality."
> http://xoomer.alice.it/infinity77/

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


Re: regex for balanced parentheses?

2008-06-12 Thread David C. Ullrich
In article 
<[EMAIL PROTECTED]>,
 Paul McGuire <[EMAIL PROTECTED]> wrote:

> Parsing TeX is definitely not for the faint-of-heart!  You might try
> something like QuotedString('$', escQuote='$$') in pyparsing.  (I've
> not poked at TeX or its ilk since the mid-80's so my TeXpertise is
> long rusted away.)

Thanks. Not actually parsing TeX, just going through and
making little changes to a few things. Easier since I wrote
the original crap so I know that various things don't come
up (for example _every_ % is the start of a comment and
_none_ of those comments is actually important, they're
all just old stuff commented out.)

> I know of two projects that have taken on the problem using pyparsing
> - one is the mathtext module in John Hunter's matplotlib, and Tim
> Arnold posted some questions on the subject a while back - try
> googling for "pyparsing tex" for further leads.
> 
> -- Paul

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


Re: re quiz

2008-06-12 Thread David C. Ullrich
In article <[EMAIL PROTECTED]>,
 Johannes Bauer <[EMAIL PROTECTED]> wrote:

> David C. Ullrich schrieb:
> 
> >> -- care to tell us what "a certain re.sub" is, and
> >> false in what way?
> > 
> > Read the OP.
> 
> Well, aren't you funny. Maybe you should have referenced the other 
> thread so one can find the OP?

What other thread? OP is sometimes Original Poster and
sometimes Original Post. In the original post in this
very thread I gave an quote from the docs and an example
illustrating the answer to the question I was asked.

Ok, I guess it's hard to find the top of the thread.
I wanted to replace a certain pattern with r"\remark{Hint}".
I didn't understand why that didn't work until I read
the bit of the docs that I quoted in my original post:

(**) "If repl is a string, any backslash escapes in it are 
processed. That is, "\n" is converted to a single newline 
character, "\r" is converted to a linefeed, and so forth."

> Regards,
> Johannes

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


Re: Making wxPython a standard module?

2008-06-12 Thread John Salerno
"Andrea Gavana" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Whether the wxPython style is "Pythonic" or not (whatever "Pythonic"
> means), this is a one-degree-above-insignificant issue for me. What I
> care is the eye pleasing look of my apps and how easy it is to code
> with a GUI framework. wxPython gives me both, the rest is just
> academic discussion.

Don't worry, I love wxPython with an almost disturbing intensity! ;) 


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


Re: Simple and safe evaluator

2008-06-12 Thread bvdp

Matimus wrote:

On Jun 11, 9:16 pm, George Sakkis <[EMAIL PROTECTED]> wrote:

On Jun 11, 8:15 pm, bvdp <[EMAIL PROTECTED]> wrote:




Matimus wrote:

The solution I posted should work and is safe. It may not seem very
readable, but it is using Pythons internal parser to parse the passed
in string into an abstract symbol tree (rather than code). Normally
Python would just use the ast internally to create code. Instead I've
written the code to do that. By avoiding anything but simple operators
and literals it is guaranteed safe.

Just wondering ... how safe would:
 eval(s, {"__builtins__":None}, {} )
be? From my testing it seems that it parses out numbers properly (int
and float) and does simple math like +, -, **, etc. It doesn't do
functions like int(), sin(), etc ... but that is fine for my puposes.
Just playing a bit, it seems to give the same results as your code using
ast does. I may be missing something!

Probably you do; within a couple of minutes I came up with this:


s = """

... (t for t in 42 .__class__.__base__.__subclasses__()
...  if t.__name__ == 'file').next()('/etc/passwd')
... """>>> eval(s, {"__builtins__":None}, {} )

Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in 
IOError: file() constructor not accessible in restricted mode

Not an exploit yet but I wouldn't be surprised if there is one. Unless
you fully trust your users, an ast-based approach is your best bet.

George


You can get access to any new-style class that has been loaded. This
exploit works on my machine (Windows XP).

[code]
# This assumes that ctypes was loaded, but keep in mind any classes
# that have been loaded are potentially accessible.

import ctypes

s = """
(
t for t in 42 .__class__.__base__.__subclasses__()
if t.__name__ == 'LibraryLoader'
).next()(
(
t for t in 42 .__class__.__base__.__subclasses__()
if t.__name__ == 'CDLL'
).next()
).msvcrt.system('dir') # replace 'dir' with something nasty
"""

eval(s, {"__builtins__":None}, {})
[/code]

Matt


Yes, this is probably a good point. But, I don't see this as an exploit 
in my program. Again, I could be wrong ... certainly not the first time 
that has happened :)


In my case, the only way a user can use eval() is via my own parsing 
which restricts this to a limited usage. So, the code setting up the 
eval() exploit has to be entered via the "safe" eval to start with. So, 
IF the code you present can be installed from within my program's 
scripts ... then yes there can be a problem. But for the life of me I 
don't see how this is possible. In my program we're just looking at 
single lines in a script and doing commands based on the text. 
Setting/evaluating macros is one "command" and I just want a method to 
do something like "Set X 25 * 2" and passing the "25 * 2" string to 
python works. If the user creates a script with "Set X os.system('rm 
*')" and I used a clean eval() then we could have a meltdown ... but if 
we stick with the eval(s, {"__builtins__":None}, {}) I don't see how the 
malicious script could do the class modifications you suggest.


I suppose that someone could modify my program code and then cause my 
eval() to fail (be unsafe). But, if we count on program modifications to 
be doorways to exploits then we might as well just pull the plug.


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


Re: get keys with the same values

2008-06-12 Thread David C. Ullrich
In article 
<[EMAIL PROTECTED]>,
 Nader <[EMAIL PROTECTED]> wrote:

> On Jun 12, 1:41 pm, David C. Ullrich <[EMAIL PROTECTED]> wrote:
> > On Thu, 12 Jun 2008 03:58:53 -0700 (PDT), Nader <[EMAIL PROTECTED]>
> > wrote:
> >
> > >Hello,
> >
> > >I have a dictionary and will get all keys which have the same values.
> >
> > >d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)}
> >
> > That's not a dictionary, it's a syntax error. If you actually
> > have a dictionary you could say
> >
> > d = {'a' : 1, 'b' : 3, 'c' : 2,'d' : 3,'e' : 1,'f' : 4}
> >
> > dd = {}
> >
> > for key, value in d.items():
> >   try:
> > dd[value].append(key)
> >   except KeyError:
> > dd[value] = [key]
> >
> > Possibly dd is now what you really want; if you really
> > want what you said you want you could use
> >
> > [l for l in dd.values() if len(l) > 1]
> >
> > >I will something as :
> >
> > >d.keys(where their values are the same)
> >
> > >With this statement I can get two lists for this example:
> > >l1= ['a','e']
> > >l2=['b','d']
> >
> > >Would somebody tell me how I can do it?
> >
> > >Regards,
> > >Nader
> >
> > David C. Ullrich
> 
> Thank for your type about the syntax error. This an example example,
> the keys of my dictionary are tuples:
> d = {(37.75, 42.22): 1 , (37.51, 40.02): 3 (45.55, 24.27): 4 (47.08,
> 30.99) : 1}
> 
> But what I will is to get all keys which has the same valus.

That's exactly what the code I posted does.

> And not
> the keys that have value more than 1!

It doesn't do that. Or if you prefer, it doesn't do that!

Instead of looking at it and trying to figure out what it does,
which of course can be tricky, try _running_ the code.
Then print dd. Then print [l for l in dd.values() if len(l) > 1] .

> 
> Nader

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


  1   2   >