Re: [OT] Re: are there some special about '\x1a' symbol

2009-01-14 Thread Gabriel Genellina
En Tue, 13 Jan 2009 22:04:33 -0200, Terry Reedy   
escribió:



Gabriel Genellina wrote:
En Mon, 12 Jan 2009 12:00:16 -0200, John Machin   
escribió:



I didn't think your question was stupid. Stupid was (a) CP/M recording
file size as number of 128-byte sectors, forcing the use of an in-band
EOF marker for text files (b) MS continuing to regard Ctrl-Z as an EOF
decades after people stopped writing Ctrl-Z at the end of text files.

 This is called "backwards compatibility" and it's a good thing :)


But it does not have to be the default or only behavior to be available.


Sure. And it isn't - there are many flags to open and fopen to choose  
from...
The C89 standard (the language used to compile CPython) guarantees *only*  
that printable characters, tab, and newline are preserved in a text file;  
everything else may or may not appear when it is read again. Even  
whitespace at the end of a line may be dropped. Binary files are more  
predictable...


Delphi recognizes the EOF marker when reading a text file only inside the  
file's last 128-byte block -- this mimics the original CP/M behavior  
rather closely. I thought the MSC runtime did the same, but no, the EOF  
marker is recognized anywhere. And Python inherits that (at least in 2.6  
-- I've not tested with 3.0)


--
Gabriel Genellina

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Carl Banks
On Jan 14, 1:40 am, Steven D'Aprano
 wrote:
> On Tue, 13 Jan 2009 20:17:08 -0800, Carl Banks wrote:
> > On Jan 13, 9:50 pm, Carl Banks  wrote:
> >> The cultural impact that would have on the community is far worse,
> >> IMHO, than any short-sighted benefits like being able to catch an
> >> accidental usage of an internal variable. Trust would be replaced by
> >> mistrust, and programming in Python would go from a pleasant experience
> >> to constant antagonism.
>
> > And I'll give you a perfect example:
>
> > XML-DOM versus ElementTree
>
> > XML-DOM is the sort of standard that is borne of a culture that values
> > encapsulation, strict type safety, and so on.  It's the way it is
> > because designers were allowed to distrust the user, and the culture
> > said that it was good to distrust the user.  Consequently, the interface
> > is a pain to use, with all kinds of boilerplate and iterator types and
> > such.
>
> > ElementTree was borne out of an environment where implementors are
> > forced to trust the user.  As a consequence it was free to create an
> > interface that was natural and straightforward and pleasant to use,
> > without having to be guarded.
>
> Which is all well and good, but there are circumstances where you *don't*
> want to trust arbitrary parts of your code to change other parts of your
> code, for good reason. In other words, you don't always want to trust
> your users.
>
> Forget copy protection and DRM. Think about the software controlling a
> radiation machine for cancer treatment, with a limit on the number of
> rads it fires at any one time. It would be disastrous for any arbitrary
> function in the machine's software to be able to mess with that limit,
> accidentally or deliberately. People will die if you get it wrong.

I'm on record saying Python shouldn't be used for systems with the
possibility of catastrophic failure: that's with or without
encapsulation.  Too much happening internally to account for it all.

Frankly I'm not sure that C++ and Java's encapsulation is good enough,
either.  Software-enforced encapsulation can be subverted, and
sometimes invalid access can happen from within the protection zone.
If something's that important, it needs to be running with redundancy
and lots and lots of fault tolerance, and it needs to have the hell
tested out of it.  If it's critically important, the code should be
storing the critical information in a separate data area with a higher
privledge level than the rest of the program.  The simpleminded
encapsulation schemes of C++ and Java are weak compared to these
methods, and probably wouldn't add much.

As I said, I've worked on flight control systems that didn't use any
data hiding at all.  Even if a drastic coding mistake like you
mentioned was able to make it though dozens of peer reviews and
hundreds of tests, it still might not result in catastrophic failure
because of all the fault tolerance built-in.



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


Re: pep 8 constants

2009-01-14 Thread Steven D'Aprano
On Tue, 13 Jan 2009 23:26:54 -0800, Brendan Miller wrote:

> I tend to use constants as a means of avoiding the proliferation of
> magic literals for maintenance reasons... Like say if your example of
> FOO would have been used in 10 places. Maybe it is more pythonic to
> simply denote such a thing as simply a normal variable? 

But it isn't a "normal variable", it's a named constant, or at least it 
would be if Python enforced constanticity. Or constantness. Or whatever.

> That doesn't
> seem to give a hint that it shouldn't be assigned a second time.

Absolutely. It's rather sad that I can do this:

import math
math.pi = 3.0

I like the ability to shoot myself in the foot, thank you very much, but 
I should at least get a warning when I'm about to do so:

math.PI = 3.0  # use God-like powers to change a constant




Changing the laws of physics, one fundamental constant at a time-ly y'rs,

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


Re: initialising a class by name

2009-01-14 Thread Krishnakant
Hi, 
So should I not use getattr()?
If I have one class in one module, then should I use global?
I found getattr() very easy to use, my only dowbt is that if there is
going to be one class per module then will it be a good idea?
some thing like module, class_name 
happy hacking.
Krishnakantt.
On Tue, 2009-01-13 at 23:55 -0800, Chris Rebert wrote:

> On Tue, Jan 13, 2009 at 11:49 PM, Krishnakant  wrote:
> > On Tue, 2009-01-13 at 21:51 -0800, Chris Rebert wrote:
> >> Assuming all the classes are in the same module as the main program:
> >>
> >> instance = vars()[class_name](args, to, init)
> >>
> > The classes are not in the same module.
> > Every glade window is coupled with one py file (module) containing one
> > class that has the events for the glade file.
> > Inshort, there is one class in one module and they are all seperate.
> >> Assuming the classes are all in the same module "mod", which is
> >> separate from the main program:
> >>
> >> instance = getattr(mod, class_name)(args, to, init)
> >>
> > Can you explain the difference between getattr and var()?
> 
> getattr(x, 'y') <==> x.y
> 
> vars() gives a dict representing the current accessible variable
> bindings (I should have instead recommended the related globals()
> function)
> globals() gives a dict representing the global variable bindings
> For example:
> #foo.py
> class Foo(object):
> #code here
> 
> Foo()
> #same as
> globals()['Foo']()
> #end of file
> 
> Cheers,
> Chris
> 

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


Re: initialising a class by name

2009-01-14 Thread Chris Rebert
On Wed, Jan 14, 2009 at 12:15 AM, Krishnakant  wrote:
> Hi,
> So should I not use getattr()?
> If I have one class in one module, then should I use global?
> I found getattr() very easy to use, my only dowbt is that if there is
> going to be one class per module then will it be a good idea?
> some thing like module, class_name
> happy hacking.
> Krishnakantt.

Aside from Steven's excellent idea, to use the getattr() technique
with your module scheme you'd probably also need to use __import__()
to dynamically import the right module.

Also, don't top-post. It makes following the conversation harder for readers.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com

> On Tue, 2009-01-13 at 23:55 -0800, Chris Rebert wrote:
>
>> On Tue, Jan 13, 2009 at 11:49 PM, Krishnakant  wrote:
>> > On Tue, 2009-01-13 at 21:51 -0800, Chris Rebert wrote:
>> >> Assuming all the classes are in the same module as the main program:
>> >>
>> >> instance = vars()[class_name](args, to, init)
>> >>
>> > The classes are not in the same module.
>> > Every glade window is coupled with one py file (module) containing one
>> > class that has the events for the glade file.
>> > Inshort, there is one class in one module and they are all seperate.
>> >> Assuming the classes are all in the same module "mod", which is
>> >> separate from the main program:
>> >>
>> >> instance = getattr(mod, class_name)(args, to, init)
>> >>
>> > Can you explain the difference between getattr and var()?
>>
>> getattr(x, 'y') <==> x.y
>>
>> vars() gives a dict representing the current accessible variable
>> bindings (I should have instead recommended the related globals()
>> function)
>> globals() gives a dict representing the global variable bindings
>> For example:
>> #foo.py
>> class Foo(object):
>> #code here
>>
>> Foo()
>> #same as
>> globals()['Foo']()
>> #end of file
>>
>> Cheers,
>> Chris
>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialising a class by name

2009-01-14 Thread Krishnakant

Hi steevan,
I liked this idea of dispatchTable.
is it possible to say some thing like 
inst = dispatchTable{"ham"}
according to me, inst will become the instance of class ham.
Another thing to note is that all the classes are in different modules.
So where do I create the dict of classes mapped with the name?
happy hacking.
Krishnakant. 
On Wed, 2009-01-14 at 07:50 +, Steven D'Aprano wrote:
> On Wed, 14 Jan 2009 11:16:58 +0530, Krishnakant wrote:
> 
> > hello all,
> > I have a strange situation where I have to load initiate an instance of
> > a class at run-time with the name given by the user from a dropdown
> > list.
> 
> Not strange at all.
> 
> > Is this possible in python and how?
> 
> Of course. Just use a dispatch table. Use a dict to map user strings to 
> classes:
> 
> 
> >>> class Spam(object): pass
> ...
> >>> class Ham(object): pass
> ...
> >>> dispatch_table = {"Spam": Spam, "Ham": Ham}
> >>> dispatch_table["Ham"]()
> <__main__.Ham object at 0xb7ea2f8c>
> 
> 
> The keys don't even have to be the name of the class, they can be 
> whatever input your users can give:
> 
> >>> dispatch_table["Yummy meat-like product"] = Spam
> >>> dispatch_table["Yummy meat-like product"]()
> <__main__.Spam object at 0xb7ea2f6c>
> 
> 
> You can even automate it:
> 
> >>> dispatch_table = {}
> >>> for name in dir():
> ... obj = globals()[name]
> ... if type(obj) == type:
> ... dispatch_table[name] = obj
> ...
> >>> dispatch_table
> {'Ham': , 'Spam': }
> 
> 
> 

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


Re: initialising a class by name

2009-01-14 Thread Steven D'Aprano
On Wed, 14 Jan 2009 13:19:23 +0530, Krishnakant wrote:

> On Tue, 2009-01-13 at 21:51 -0800, Chris Rebert wrote:
>> Assuming all the classes are in the same module as the main program:
>> 
>> instance = vars()[class_name](args, to, init)
>> 
> The classes are not in the same module. Every glade window is coupled
> with one py file (module) containing one class that has the events for
> the glade file. Inshort, there is one class in one module and they are
> all seperate.


Just import the classes you need, and dispatch on them.

import spammodule, hammodule
dispatch_table = {
"Spam": spammodule.Spamclass, "Ham": hammodule.Hamclass}

# later

obj = dispatch_table[ user_input ]()





>> Assuming the classes are all in the same module "mod", which is
>> separate from the main program:
>> 
>> instance = getattr(mod, class_name)(args, to, init)
>> 
> Can you explain the difference between getattr and var()?


They are completely different things. At an interactive prompt, type:

help(getattr)

help(var)

and read what they say.



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


MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread gumbah
I have this really strange problem. I hope someone can help:

I am trying to update a database like so:

UPDATE `tablename` set fieldx='test' WHERE flfieldx = null and fieldy
like '%certainvalue%'

My Python code looks like this:

fillsql = "UPDATE `tablename` set fieldx='test' WHERE flfieldx = null
and fieldy like '%%%s%%' " % certainvalue
print fillsql
cursor.execute(fillsql)

#also tried:
#cursor.execute("UPDATE `tablename` set fieldx='test' WHERE flfieldx =
null and fieldy like %s ", "%%%s%%" % certainvalue)

But it doesn't work... But when i copy and past the SQL (printed by
"print fillsql" line) and execute that in phpMyAdmin, it does work!!!

Can anyone tell me what i am doing wrong??

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


Re: read string in bits

2009-01-14 Thread John Machin
On Jan 14, 6:44 pm, ts  wrote:
> On Jan 14, 3:32 pm, Chris Rebert  wrote:
>
>
>
> > On Tue, Jan 13, 2009 at 11:21 PM, ts  wrote:
> > > hi, is there a way to read a character/string into bits in python?
>
> > > i understand that character is read in bytes. Do i have to write a
> > > function to convert it myself into 1010101 or there is a library in
> > > python that enable me to do that?
>
> > It's not quite clear to me what you mean, but here are 2 guesses:
> > - If you want to convert an ASCII character to its ASCII integer
> > value, use ord()
> > - If you want to convert an integer into a string of its base-2
> > representation, use bin() [requires Python 2.6, I think]
>
> > Cheers,
> > Chris
>
> > --
> > Follow the path of the Iguana...http://rebertia.com
>
> hi, bin() is what i'm looking for. But only python 2.4 is available to
> me. Is there a replacement of bin() in python 2.4?

No. You would have to write some code 8-(
This should give you some clues:

| Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit
(Intel)] on win32
| Type "help", "copyright", "credits" or "license" for more
information.
| >>> def char_as_number(char, base):
| ... assert 2 <= base <= 16
| ... n = ord(char)
| ... if not n:
| ... return '0'
| ... result = ''
| ... while n:
| ... n, r = divmod(n, base)
| ... result = '0123456789ABCDEF'[r] + result
| ... return result
| ...
| >>> [char_as_number(chr(x), 2) for x in (0, 1, 7, 8, 127, 128, 255)]
| ['0', '1', '111', '1000', '111', '1000', '']
| >>> [char_as_number(chr(x), 2).zfill(8) for x in (0, 1, 7, 8, 127,
128, 255)]
| ['', '0001', '0111', '1000', '0111',
'1000', '']
| >>> [char_as_number(chr(x), 16).zfill(2) for x in (0, 1, 7, 8, 127,
128, 255)]
| ['00', '01', '07', '08', '7F', '80', 'FF']
| >>> [char_as_number(chr(x), 8).zfill(3) for x in (0, 1, 7, 8, 127,
128, 255)]
| ['000', '001', '007', '010', '177', '200', '377']
| >>>

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


Re: read string in bits

2009-01-14 Thread Mark Smith
On Jan 14, 7:44 am, ts  wrote:
> On Jan 14, 3:32 pm, Chris Rebert  wrote:
>
>
>
> > On Tue, Jan 13, 2009 at 11:21 PM, ts  wrote:
> > > hi, is there a way to read a character/string into bits in python?
>
> > > i understand that character is read in bytes. Do i have to write a
> > > function to convert it myself into 1010101 or there is a library in
> > > python that enable me to do that?
>
> > It's not quite clear to me what you mean, but here are 2 guesses:
> > - If you want to convert an ASCII character to its ASCII integer
> > value, use ord()
> > - If you want to convert an integer into a string of its base-2
> > representation, use bin() [requires Python 2.6, I think]
>
> > Cheers,
> > Chris
>
> > --
> > Follow the path of the Iguana...http://rebertia.com
>
> hi, bin() is what i'm looking for. But only python 2.4 is available to
> me. Is there a replacement of bin() in python 2.4?

There's a recipe for this at ActiveState: 
http://code.activestate.com/recipes/219300/#c6
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialising a class by name

2009-01-14 Thread Krishnakant
On Wed, 2009-01-14 at 00:20 -0800, Chris Rebert wrote:
> Aside from Steven's excellent idea, to use the getattr() technique
> with your module scheme you'd probably also need to use __import__()
> to dynamically import the right module.
> 
I would generally import all the modules I would need at the top of the
main module.
then would use getattr(module,class_name) will that work?
or do I need to import in some other way?
happy hacking.
Krishnakant.

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


Re: read string in bits

2009-01-14 Thread Hendrik van Rooyen
 "Chris Rebert"  wrote:

> It's not quite clear to me what you mean, but here are 2 guesses:
> - If you want to convert an ASCII character to its ASCII integer
> value, use ord()
> - If you want to convert an integer into a string of its base-2
> representation, use bin() [requires Python 2.6, I think]

Another case:

>>> s = '1010101'
>>> int (s,2)
85
>>> 

Works almost anywhere, AFAIK.

- Hendrik

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


Re: are there some special about '\x1a' symbol

2009-01-14 Thread Hendrik van Rooyen

"Steve Holden"  wrote:

> Unknown wrote:
> > On 2009-01-12, John Machin  wrote:

> > I believe that "feature" was inherited by CP/M from DEC OSes
> > (RSX-11 or RSTS-11). AFAICT, all of CP/M's file I/O API
> > (including the FCB) was lifted almost directly from DEC's
> > PDP-11 stuff, which probably copied it from PDP-8 stuff.
> > 
> > Perhaps in the early 60's somebody at DEC had a reason.  The
> > really interesting thing is that we're still suffering because
> > of it 40+ years later.
> > 
> I suspect this is probably a leftover from some paper tape data formats,
> when it was easier to detect the end of a file with a sentinel byte than
> it was to detect run-off as end of file. It could easily date back to
> the PDP-8.

We can be kind of fortunate that the ASCII chars for field separator,
record separator, file separator, unit separator did not catch on in a big
way in file formatting.  (remembering the Pick OS running on Reality...)

- Hendrik


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


Re: initialising a class by name

2009-01-14 Thread Chris Rebert
On Wed, Jan 14, 2009 at 12:36 AM, Krishnakant  wrote:
> On Wed, 2009-01-14 at 00:20 -0800, Chris Rebert wrote:
>> Aside from Steven's excellent idea, to use the getattr() technique
>> with your module scheme you'd probably also need to use __import__()
>> to dynamically import the right module.
>>
> I would generally import all the modules I would need at the top of the
> main module.
> then would use getattr(module,class_name) will that work?

Yes, that is how you'd do it in that case.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: read string in bits

2009-01-14 Thread Mark Smith
On Jan 14, 7:44 am, ts  wrote:
> On Jan 14, 3:32 pm, Chris Rebert  wrote:
>
>
>
> > On Tue, Jan 13, 2009 at 11:21 PM, ts  wrote:
> > > hi, is there a way to read a character/string into bits in python?
>
> > > i understand that character is read in bytes. Do i have to write a
> > > function to convert it myself into 1010101 or there is a library in
> > > python that enable me to do that?
>
> > It's not quite clear to me what you mean, but here are 2 guesses:
> > - If you want to convert an ASCII character to its ASCII integer
> > value, use ord()
> > - If you want to convert an integer into a string of its base-2
> > representation, use bin() [requires Python 2.6, I think]
>
> > Cheers,
> > Chris
>
> > --
> > Follow the path of the Iguana...http://rebertia.com
>
> hi, bin() is what i'm looking for. But only python 2.4 is available to
> me. Is there a replacement of bin() in python 2.4?

There's a recipe at ActiveState: http://code.activestate.com/recipes/219300/#c6
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-14 Thread Steven D'Aprano
On Tue, 13 Jan 2009 23:06:58 +, Mark Wooding wrote:


> I'm going to move away from the formal semantics stuff and try a
> different tack.  Here's what I think is the defining property of
> pass-by-value (distilled from the formal approach I described earlier,
> but shorn of the symbolism):
> 
>   The callee's parameters are /new variables/, initialized /as if by
>   assignment/ from the values of caller's argument expressions.


Well, that's one way of looking at it, I guess. The problem is that when 
I do this:

x = "something"  # just an example, not necessarily a string
y = x

Does the line y=x create a new variable? Depends on what you mean by 
variable. If you mean a new name, symbol or whatever, then obviously yes. 

But if you mean a new value, namely the string "something", then not 
necessarily. In Pascal (and C?) those bytes are copied, giving two 
independent values which just happen to be equal. In Python, both x and y 
refer to the same string, and I choose the term deliberately. See, I'm 
not *entirely* against the use of referring to references, when 
appropriate. I think we just differ on when we think it's appropriate.

Which I guess brings us back to your earlier assertion (I think it was 
you) that people aren't confused about argument passing, they're confused 
about assignment. 

[...]

> But! (you claim) ...
> 
>> Python simply can't be pass-by-value, because it doesn't behave like
>> pass-by-value in other languages (particularly C and Pascal).
> 
> Ah! (say I) but assignment in C and Pascal looks different from the way
> it looks in C

I'm sorry, that confuses me. Assignment in C looks different from the way 
it looks in C? I guess the second C should be Python.

> -- and in exactly the same way that argument passing looks
> different.  And there, I think, I'm going to rest my case.
> 
> I'm sorry I took so long to distill these thoughts.  Thank you for
> putting up with my theoretical meanderings on the way.

And thank you for not kill-filing me when tempers were getting short.



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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Russ P.
On Jan 13, 11:51 pm, Paul Rubin  wrote:
> Carl Banks  writes:
> > At GE there was no encapsulation in sight on any system I worked on.
> > In fact, our engine simulation was a special-purpose object-oriented
> > language with--get this--no private variables.  Some other systems I
> > worked on didn't even use scoping, let alone encapsulation.
>
> Where my officemate used to work, the simulation stuff was written in
> Matlab, but the actual flight stuff was written in Ada.  I wonder
> if GE did something similar.

I was going to suggest the same thing. An engine *simulation* is one
thing; the actual engine control code is another. And the interface
between the engine control code and the rest of the flight software is
yet another. The FMS should be setting the throttle level, but I doubt
it should be fooling around with the guts of the engine control
software.
--
http://mail.python.org/mailman/listinfo/python-list


RE: Could you suggest optimisations ?

2009-01-14 Thread Barak, Ron
Hi Terry,

-Original Message-
From: Terry Reedy [mailto:tjre...@udel.edu]
Sent: Wednesday, January 14, 2009 01:57
To: python-list@python.org
Subject: Re: Could you suggest optimisations ?

Barak, Ron wrote:
> Hi,
>
> In the attached script, the longest time is spent in the following
> functions (verified by psyco log):

I cannot help but wonder why and if you really need all the rigamorole with 
file pointers, offsets, and tells instead of

for line in open(...):
   do your processing.

I'm building a database of the found events in the logs (those records between 
the first and last regexs in regex_array).
The user should then be able to navigate among these events (among other 
functionality).
This is why I need the tells and offsets, so I'd know the place in the logs 
where an event starts/ends.

Bye,
Ron.

>
> def match_generator(self,regex):
> """
> Generate the next line of self.input_file that
> matches regex.
> """
> generator_ = self.line_generator()
> while True:
> self.file_pointer = self.input_file.tell()
> if self.file_pointer != 0:
> self.file_pointer -= 1
> if (self.file_pointer + 2) >= self.last_line_offset:
> break
> line_ = generator_.next()
> print "%.2f%%   \r" % (((self.last_line_offset -
> self.input_file.tell()) / (self.last_line_offset * 1.0)) * 100.0),
> if not line_:
> break
> else:
> match_ = regex.match(line_)
> groups_ = re.findall(regex,line_)
> if match_:
> yield line_.strip("\n"), groups_
>
> def get_matching_records_by_regex_extremes(self,regex_array):
> """
> Function will:
> Find the record matching the first item of regex_array.
> Will save all records until the last item of regex_array.
> Will save the last line.
> Will remember the position of the beginning of the next line in
> self.input_file.
> """
> start_regex = regex_array[0]
> end_regex = regex_array[len(regex_array) - 1]
>
> all_recs = []
> generator_ = self.match_generator
>
> try:
> match_start,groups_ = generator_(start_regex).next()
> except StopIteration:
> return(None)
>
> if match_start != None:
> all_recs.append([match_start,groups_])
>
> line_ = self.line_generator().next()
> while line_:
> match_ = end_regex.match(line_)
> groups_ = re.findall(end_regex,line_)
> if match_ != None:
> all_recs.append([line_,groups_])
> return(all_recs)
> else:
> all_recs.append([line_,[]])
> line_ = self.line_generator().next()
>
> def line_generator(self):
> """
> Generate the next line of self.input_file, and update
> self.file_pointer to the beginning of that line.
> """
> while self.input_file.tell() <= self.last_line_offset:
> self.file_pointer = self.input_file.tell()
> line_ = self.input_file.readline()
> if not line_:
> break
> yield line_.strip("\n")
>
> I was trying to think of optimisations, so I could cut down on
> processing time, but got no inspiration.
> (I need the "print "%.2f%%   \r" ..." line for user's feedback).
>
> Could you suggest any optimisations ?
> Thanks,
> Ron.
>
>
> P.S.: Examples of processing times are:
>
> * 2m42.782s  on two files with combined size of792544 bytes
>   (no matches found).
> * 28m39.497s on two files with combined size of 4139320 bytes
>   (783 matches found).
>
> These times are quite unacceptable, as a normal input to the program
> would be ten files with combined size of ~17MB.
>
>
> --
> --
>
> --
> http://mail.python.org/mailman/listinfo/python-list


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


Re: Read binary file and dump data in

2009-01-14 Thread Santiago Romero

> If you are reading arbitrary bytes then it will likely not always "look"
> like integers. What you probably meant is:
>
> for i in data:
>    print "%d, " % ord(i)

 That's it! :-)

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


Re: executing multiple functions in background simultaneously

2009-01-14 Thread Aaron Brady
On Jan 13, 7:02 pm, Catherine Moroney
 wrote:
> Hello everybody,
>
> I know how to spawn a sub-process and then wait until it
> completes.  I'm wondering if I can do the same thing with
> a Python function.
>
> I would like to spawn off multiple instances of a function
> and run them simultaneously and then wait until they all complete.
> Currently I'm doing this by calling them as sub-processes
> executable from the command-line.  Is there a way of accomplishing
> the same thing without having to make command-line executables
> of the function call?
>
> I'm primarily concerned about code readability and ease of
> programming.  The code would look a lot prettier and be shorter
> to boot if I could spawn off function calls rather than
> subprocesses.
>
> Thanks for any advice,
>
> Catherine

'multiprocessing' does what you mentioned, as others said.  The
abstraction layer is solid, which makes your code pretty.  However, it
just creates a command line like this:

'"c:\\programs\\python26\\python.exe" "-c" "from
multiprocessing.forking import main; main()" "--multiprocessing-fork"
"1916"'

The handle '1916' is a pipe used to read further instructions.  The
arrive in 'main()' in the form of a pickled (serialized) dictionary.
In it, the 'main_path' key contains the path to your program.  'main
()' calls the 'prepare()' function, which calls 'imp.find_module',
using that path.  Pretty sophisticated.

You can do it yourself by creating your own command line.  Create a
subprocess by this command line (untested & lots of caveats):

'"c:\\programs\\python26\\python.exe" "-c" "from myprogram import
myfunc; myfunc()"'

But you have practically no communication with it.  If you need
parameters, you can include them on the command line, since you're
building it yourself (untested & highly vulnerable):

'"c:\\programs\\python26\\python.exe" "-c" "from myprogram import
myfunc; myfunc( literal1, literal2 )"'

For a return value, unless it can be a simple exit code, you'll need a
communication channel.  For it, a socket wouldn't be bad, or a pipe if
you're not on Windows (include the port or descriptor on the command
line).  (Even with 'multiprocessing', you're limited to pickleable
objects, however, I believe.)
--
http://mail.python.org/mailman/listinfo/python-list


PYTHON HTTP POST

2009-01-14 Thread lilanidhaval
Hi,

I need one complete example of how to do a http post to any site.
I have tried making a POST to google but all I am returned with is a
405 error.
I don't want to use Pygoogle as I want to try and do this with other
sites.
I am also having problems inputing with the param
I have tried Mechanize. There are no problems with getting data only
posting.

>>> headers = {'Content-Type': 'text/html; charset=ISO-8859-1',
... 'User-Agent':'Mozilla/4.0',
... 'Content-Length':'7'}
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("POST","/search",params,headers)
>>> r2 =  conn.getresponse()
>>> print r2.status, r2.reason
405 Method Not Allowed

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


Re: initialising a class by name

2009-01-14 Thread Steve Holden
Krishnakant wrote:
> hello all,
> I have a strange situation where I have to load initiate an instance of
> a class at run-time with the name given by the user from a dropdown
> list.
> Is this possible in python and how?
> To make things clear, let me give the real example.
> there is an inventory management system and products belong to different
> categories.
> There are predefined categories in the database and for each category
> there is a module which contains a class made out of pygtk.
> This means what class gets instantiated and displayed in the gui depends
> on the choice a user makes in the dropdown.
> Now, I could have created a list of if conditions for all the categories
> as in 
> if categorySelection == "books":
>   Books = BookForm()
> 
> However this is a problem because when there will be more than 100
> categories there will be that many if conditions and this will make the
> code uggly.
> so my idea is to name the class exactly after the name of the category
> so that when the user selects a category that name is used to initialise
> the instance of that class.
> So is it possible to initialise an instance of a class given its name
> from a variable?
> thanks and 
> Happy hacking.
> Krishnakant. 
> 
You don't need to have the names of the classes related to anything in
the interface. Just use a list of classes, and have the user interface
return the correct index for each class. Then (supposing the selection
by the user is seln) use

  Books = classes[seln]()

If the classes are all in different modules, import them before creating
the list of classes.

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

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Russ P.
On Jan 13, 11:40 pm, Steven D'Aprano
 wrote:

> But, gosh darn it, wouldn't it be nice to program the critical parts of
> your code in "strict Python", and leave the rest as "trusting Python",
> instead of having to use Java for the lot just to get strictness in the
> critical parts? If only there was a way to do this, and ensure people
> won't abuse it.

Yes, that would indeed be nice. I am certainly not the only one who
could use a language that is excellent for both research prototyping
*and* the final, safety-critical system. Then perhaps the prototype
could just be cleaned up and "hardened" for the end product rather
than rewritten in another language -- by programmers in another state
who may fail to understand many of the details that the prototype
developer agonized over.

I don't know if such a versatile language could even exist, but it
would sure be valuable. Maybe it's like asking for a football player
who can excel as both a wide receiver and a guard. But players who
weigh 280 pounds and run a 4.4 40 are hard to find.
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread John Machin
On Jan 14, 7:31 pm, gumbah  wrote:
> I have this really strange problem. I hope someone can help:
>
> I am trying to update a database like so:
>
> UPDATE `tablename` set fieldx='test' WHERE flfieldx = null and fieldy
> like '%certainvalue%'
>
> My Python code looks like this:
>
> fillsql = "UPDATE `tablename` set fieldx='test' WHERE flfieldx = null
> and fieldy like '%%%s%%' " % certainvalue

call this trial 1

> print fillsql
> cursor.execute(fillsql)
>
> #also tried:
> #cursor.execute("UPDATE `tablename` set fieldx='test' WHERE flfieldx =
> null and fieldy like %s ", "%%%s%%" % certainvalue)

call this trial 2

>
> But it doesn't work... But when i copy and past the SQL (printed by
> "print fillsql" line) and execute that in phpMyAdmin, it does work!!!

You don't say what "doesn't work" means ... did you get exceptions, or
just silently not updating?

>
> Can anyone tell me what i am doing wrong??

Well the "trial 1" method is guaranteed not to work if certainvalue
contains an apostrophe e.g. "O'Reilly". In any case, you should never
build your own SQL statement like that; use the "trial 2" method -- it
will do whatever is necessary in the way of reformatting or escaping
your input.

I know near nothing about mySQLdb, but here are some comments based on
general SQL experience:
(1) `tablename` isn't SQL syntax that I've seen before; perhaps it
works in phpMyAdmin but not in cursor.execute()
(2) similarly = NULL ... I'd expect IS NULL
(3) It is updating but your script and your phpMyAdmin session are
pointing at different instances of the database
(4) For trial 2 method, shouldn't the 2nd arg of cursor.execute()
should be a sequence e.g. ("%%%s%%" % certainvalue, ) ?

HTH
John

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


Re: PYTHON HTTP POST

2009-01-14 Thread koranthala
Does google accept POST?

Anyways, if you dont need to post files, you can use urlencode itself.
def encode_formdata(fields):
body = urllib.urlencode(dict())
content_type = "application/x-www-form-urlencoded"
return content_type, body

If you need to post files too, then you will have to use multipart
data
def encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form
fields.
files is a sequence of (name, filename, value) elements for data
to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s";
filename="%s"' % (key, filename))
L.append('Content-Type: %s' % mimetypes.guess_type(filename)
[0] or 'application/octet-stream'
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body

Since POST files doesnt work with urllib, you might have to use
httplib - or go for very high level tools like twisted.
I here show an example with httplib.

def post(host, selector, fields, files):
if files:
   content_type, body = encode_multipart_formdata(fields, files)
else:
   content_type, body = encode_formdata(fields)

h = httplib.HTTPConnection(host)
#Spoof Mozilla
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4',
'Content-Type': content_type
}
h.request('POST', selector, body, headers)
res = h.getresponse()
return res.status, res.reason, res.read()

Please note that you can use multipart whether or not files are there,
but parsing multipart usually is slower.

Hope this helps.

lilanidha...@gmail.com wrote:
> Hi,
>
> I need one complete example of how to do a http post to any site.
> I have tried making a POST to google but all I am returned with is a
> 405 error.
> I don't want to use Pygoogle as I want to try and do this with other
> sites.
> I am also having problems inputing with the param
> I have tried Mechanize. There are no problems with getting data only
> posting.
>
> >>> headers = {'Content-Type': 'text/html; charset=ISO-8859-1',
> ... 'User-Agent':'Mozilla/4.0',
> ... 'Content-Length':'7'}
> >>> conn = httplib.HTTPConnection("www.google.com")
> >>> conn.request("POST","/search",params,headers)
> >>> r2 =  conn.getresponse()
> >>> print r2.status, r2.reason
> 405 Method Not Allowed
>
> Regards,
> Dhaval
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-14 Thread Mark Wooding
Steven D'Aprano  wrote:
> > Ah! (say I) but assignment in C and Pascal looks different from the way
> > it looks in C
> 
> I'm sorry, that confuses me. Assignment in C looks different from the way 
> it looks in C? I guess the second C should be Python.

Yes, you're right.  Stupid mistake on my part.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialising a class by name

2009-01-14 Thread Krishnakant
On Wed, 2009-01-14 at 04:09 -0500, Steve Holden wrote:
> > 
> You don't need to have the names of the classes related to anything in
> the interface. Just use a list of classes, and have the user interface
> return the correct index for each class. Then (supposing the selection
> by the user is seln) use
> 
>   Books = classes[seln]()
> 
> If the classes are all in different modules, import them before creating
> the list of classes.
> 
Is there a way to get the list of all the classes in the package?
I mean is there a way to build a list of modules  from some global
variable which can be accessed and then looped through.
happy hacking.
Krishnakant.

> regards
>  Steve

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


Re: PYTHON HTTP POST

2009-01-14 Thread koranthala
On Jan 14, 2:21 pm, koranth...@gmail.com wrote:
> Does google accept POST?
>
> Anyways, if you dont need to post files, you can use urlencode itself.
> def encode_formdata(fields):
>         body = urllib.urlencode(dict())
>         content_type = "application/x-www-form-urlencoded"
>         return content_type, body
>
> If you need to post files too, then you will have to use multipart
> data
> def encode_multipart_formdata(fields, files):
>     """
>     fields is a sequence of (name, value) elements for regular form
> fields.
>     files is a sequence of (name, filename, value) elements for data
> to be uploaded as files
>     Return (content_type, body) ready for httplib.HTTP instance
>     """
>     BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'
>     CRLF = '\r\n'
>     L = []
>     for (key, value) in fields:
>         L.append('--' + BOUNDARY)
>         L.append('Content-Disposition: form-data; name="%s"' % key)
>         L.append('')
>         L.append(value)
>     for (key, filename, value) in files:
>         L.append('--' + BOUNDARY)
>         L.append('Content-Disposition: form-data; name="%s";
> filename="%s"' % (key, filename))
>         L.append('Content-Type: %s' % mimetypes.guess_type(filename)
> [0] or 'application/octet-stream'
>         L.append('')
>         L.append(value)
>     L.append('--' + BOUNDARY + '--')
>     L.append('')
>     body = CRLF.join(L)
>     content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
>     return content_type, body
>
> Since POST files doesnt work with urllib, you might have to use
> httplib - or go for very high level tools like twisted.
> I here show an example with httplib.
>
> def post(host, selector, fields, files):
>     if files:
>        content_type, body = encode_multipart_formdata(fields, files)
>     else:
>        content_type, body = encode_formdata(fields)
>
>     h = httplib.HTTPConnection(host)
>     #Spoof Mozilla
>     headers = {
>         'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
> rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4',
>         'Content-Type': content_type
>         }
>     h.request('POST', selector, body, headers)
>     res = h.getresponse()
>     return res.status, res.reason, res.read()
>
> Please note that you can use multipart whether or not files are there,
> but parsing multipart usually is slower.
>
> Hope this helps.
>
> lilanidha...@gmail.com wrote:
> > Hi,
>
> > I need one complete example of how to do a http post to any site.
> > I have tried making a POST to google but all I am returned with is a
> > 405 error.
> > I don't want to use Pygoogle as I want to try and do this with other
> > sites.
> > I am also having problems inputing with the param
> > I have tried Mechanize. There are no problems with getting data only
> > posting.
>
> > >>> headers = {'Content-Type': 'text/html; charset=ISO-8859-1',
> > ...         'User-Agent':'Mozilla/4.0',
> > ...         'Content-Length':'7'}
> > >>> conn = httplib.HTTPConnection("www.google.com")
> > >>> conn.request("POST","/search",params,headers)
> > >>> r2 =  conn.getresponse()
> > >>> print r2.status, r2.reason
> > 405 Method Not Allowed
>
> > Regards,
> > Dhaval
>
>

oops - Forgot to mention that POSTing files mechanism is taken from a
recipe in active state -
http://code.activestate.com/recipes/146306/
--
http://mail.python.org/mailman/listinfo/python-list


Why this code is working?

2009-01-14 Thread Hussein B
Hey,
Why this code is working?

>>> def f1( ):
...  x = 88
...  f2(x)
...
>>> def f2(x):
...  print x
...
>>> f1( )
88

Thanks.

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


Re: initialising a class by name

2009-01-14 Thread Krishnakant
On Wed, 2009-01-14 at 00:39 -0800, Chris Rebert wrote:
> On Wed, Jan 14, 2009 at 12:36 AM, Krishnakant  wrote:
> > On Wed, 2009-01-14 at 00:20 -0800, Chris Rebert wrote:
> >> Aside from Steven's excellent idea, to use the getattr() technique
> >> with your module scheme you'd probably also need to use __import__()
> >> to dynamically import the right module.
> >>
> > I would generally import all the modules I would need at the top of the
> > main module.
> > then would use getattr(module,class_name) will that work?
> 
> Yes, that is how you'd do it in that case.
> 
By the way, is there a kind of global list of modules/classes which are
maintained in a package once the program is loaded into memory?
happy hacking.
Krishnakant.

> Cheers,
> Chris
> --
> Follow the path of the Iguana...
> http://rebertia.com

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


Re: Why this code is working?

2009-01-14 Thread Bruno Desthuilliers

Hussein B a écrit :

Hey,
Why this code is working?


def f1( ):

...  x = 88
...  f2(x)
...

def f2(x):

...  print x
...

f1( )

88




Well... Because it is correct ?

What make you think it _shouldn't_ work ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread gumbah
Hi John,

thanks a lot for your quick reply!

I tried all of your suggestions but none of them work... I have a clue
on why it is failing: MySQLdb seems to quote the % characters or
something...

Even when i do:
cursor.execute("UPDATE tablename set fieldx='test' WHERE flfieldx is
null and fieldy like '%therealvalue%' "

or:
cursor.execute("UPDATE tablename set fieldx='test' WHERE flfieldx is
null and fieldy like '%%therealvalue%%' " # escaping the %

it is not updating the database...

Maybe I am completely overlooking something, but I am pretty lost
here... Googling this it seems as if no one is using "LIKE '%value%'"
type queries with Python & mySQL...

Anyone any other thoughts?

regards,
Joost


On 14 jan, 10:14, John Machin  wrote:
> On Jan 14, 7:31 pm, gumbah  wrote:
>
> > I have this really strange problem. I hope someone can help:
>
> > I am trying to update a database like so:
>
> > UPDATE `tablename` set fieldx='test' WHERE flfieldx = null and fieldy
> > like '%certainvalue%'
>
> > My Python code looks like this:
>
> > fillsql = "UPDATE `tablename` set fieldx='test' WHERE flfieldx = null
> > and fieldy like '%%%s%%' " % certainvalue
>
> call this trial 1
>
> > print fillsql
> > cursor.execute(fillsql)
>
> > #also tried:
> > #cursor.execute("UPDATE `tablename` set fieldx='test' WHERE flfieldx =
> > null and fieldy like %s ", "%%%s%%" % certainvalue)
>
> call this trial 2
>
>
>
> > But it doesn't work... But when i copy and past the SQL (printed by
> > "print fillsql" line) and execute that in phpMyAdmin, it does work!!!
>
> You don't say what "doesn't work" means ... did you get exceptions, or
> just silently not updating?
>
>
>
> > Can anyone tell me what i am doing wrong??
>
> Well the "trial 1" method is guaranteed not to work if certainvalue
> contains an apostrophe e.g. "O'Reilly". In any case, you should never
> build your own SQL statement like that; use the "trial 2" method -- it
> will do whatever is necessary in the way of reformatting or escaping
> your input.
>
> I know near nothing about mySQLdb, but here are some comments based on
> general SQL experience:
> (1) `tablename` isn't SQL syntax that I've seen before; perhaps it
> works in phpMyAdmin but not in cursor.execute()
> (2) similarly = NULL ... I'd expect IS NULL
> (3) It is updating but your script and your phpMyAdmin session are
> pointing at different instances of the database
> (4) For trial 2 method, shouldn't the 2nd arg of cursor.execute()
> should be a sequence e.g. ("%%%s%%" % certainvalue, ) ?
>
> HTH
> John

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


Re: Why this code is working?

2009-01-14 Thread Hussein B
On Jan 14, 11:55 am, Bruno Desthuilliers  wrote:
> Hussein B a écrit :
>
> > Hey,
> > Why this code is working?
>
>  def f1( ):
> > ...      x = 88
> > ...      f2(x)
> > ...
>  def f2(x):
> > ...      print x
> > ...
>  f1( )
> > 88
>
> Well... Because it is correct ?
>
> What make you think it _shouldn't_ work ?

Because def2 is defined after def1 in an interpreted language, not
compiled.
--
http://mail.python.org/mailman/listinfo/python-list


Re: why cannot assign to function call

2009-01-14 Thread Mark Wooding
Aaron Brady  wrote:

> On Jan 13, 5:06 pm, Mark Wooding  wrote:
> snip
> > I'm going to move away from the formal semantics stuff and try a
> > different tack.  Here's what I think is the defining property of
> > pass-by-value (distilled from the formal approach I described earlier,
> > but shorn of the symbolism):
> >
> >   The callee's parameters are /new variables/, initialized /as if by
> >   assignment/ from the values of caller's argument expressions.
> 
> In other words, the same as assignment in that language.

It's the same as assignment of /values/ to /fresh variables/.  It's
important to specify that argument expressions are fully evaluated, and
that nothing gets overwritten in the process.

So the difference between Python and C is that C copies values during
assignment, but Python doesn't.  Therefore the argument passing works
the same way.

> > Because its argument passing works the same way as its assignment.
> 
> That would be called pass-by-assignment.  But you've just postponed
> explaining yourself.  Stop delegating and work.

Huh?  I'm really at a loss to know what you want me to do.

I can't help it if people are confused over the phrase `pass-by-value',
beyond trying to explain what it means using clear definitions.  The
`value' part means that argument expressions are /evaluated/ (turned
into values), which forces applicative-order semantics rather than (say)
normal-order.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why this code is working?

2009-01-14 Thread Peter Otten
Hussein B wrote:

> Why this code is working?
> 
 def f1( ):
> ...  x = 88
> ...  f2(x)
> ...
 def f2(x):
> ...  print x
> ...
 f1( )
> 88

The name 'f2' is not resolved once when the f1 function is created. Instead
Python looks for a global name 'f2' each time f1 is executed.

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


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread gumbah
Yep, also tried that. Weird thing is that I get no errors, it's just
silently not updating...

On 14 jan, 11:06, Peter Otten <__pete...@web.de> wrote:
> gumbah wrote:
> > I tried all of your suggestions but none of them work... I have a clue
> > on why it is failing: MySQLdb seems to quote the % characters or
> > something...
>
> > Even when i do:
> > cursor.execute("UPDATE tablename set fieldx='test' WHERE flfieldx is
> > null and fieldy like '%therealvalue%' "
> > it is not updating the database...
>
> > Maybe I am completely overlooking something, but I am pretty lost
> > here... Googling this it seems as if no one is using "LIKE '%value%'"
> > type queries with Python & mySQL...
>
> > Anyone any other thoughts?
>
> Did you call the connection object's commit() method?
>
> Peter

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


Parent module not loaded error

2009-01-14 Thread Ståle Undheim
I have a pretty strange error that I can't figure out the cause off.
This is in a Django app.

I am using berkelydb, with secondary databases for indexing. The
secondary databases are associated with a callback that uses cPickle
to serialize index values. The problem is that cPickle.dumps(value)
fails when I run it through mod_wsgi or mod_python on the deployment
server (Ubuntu Linux 8.10), but works fine when when I use Djangos
runserver on the same computer. Also, on my own computer (Ubuntu Linux
8.10), it works fine through mod_python.

Each time I call on cPickle.dumps(value) I get:
SystemError("Parent module 'd4' not loaded",)

Using sys.exc_info() I get no type or traceback, just that exception.
The callstack as far as I can figure is:

django
view
bsddb.put
indexer callback
cPickle.dumps

cPickle.loads works fine within the callback, I can also use
cPickle.dumps() outside the indexer callback. But inside the callback,
I need to use normal pickle instead. I just want to know why. I am
assuming it has something to do with the fact that I go from python to
C (bsddb) back to python (indexer callback) and back to C (cPickle).
It is still strange then that cPickle.loads() work, but not
cPickle.dumps(). I am also only storing integer values when I get this
error, so no fancy list, dictionaries or objects.
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread gumbah
Aahh the conn.commit() DID the trick!!

I tried that before, but then it failed at another point. I got it
working now! Thanks a lot Peter and John!!

cheers!

On 14 jan, 11:14, gumbah  wrote:
> Yep, also tried that. Weird thing is that I get no errors, it's just
> silently not updating...
>
> On 14 jan, 11:06, Peter Otten <__pete...@web.de> wrote:
>
> > gumbah wrote:
> > > I tried all of your suggestions but none of them work... I have a clue
> > > on why it is failing: MySQLdb seems to quote the % characters or
> > > something...
>
> > > Even when i do:
> > > cursor.execute("UPDATE tablename set fieldx='test' WHERE flfieldx is
> > > null and fieldy like '%therealvalue%' "
> > > it is not updating the database...
>
> > > Maybe I am completely overlooking something, but I am pretty lost
> > > here... Googling this it seems as if no one is using "LIKE '%value%'"
> > > type queries with Python & mySQL...
>
> > > Anyone any other thoughts?
>
> > Did you call the connection object's commit() method?
>
> > Peter

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


os system command not found

2009-01-14 Thread codicedave
Hi all!
I installed a external program called infomap using the classical
procedure

./configure
make
sudo make install

 and it works perfectly in Terminal (Os x) using both bash and tcsh
shell

admins-macbook-pro-2:~ unil$ infomap-build

Usage: infomap-build [-w working_dir] [-p param_file]
   [-D var_1=val_1 ... -D var_N=val_N]
   (-s single_corpus_file | -m multi_file_list)
   


 but when I call it from python using os.system or subprocess.call I
get the message "sh: infomap-build: command not found".

Do you know why?

Many thanks

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


Re: Parent module not loaded error

2009-01-14 Thread Graham Dumpleton
On Jan 14, 9:20 pm, Ståle Undheim  wrote:
> I have a pretty strange error that I can't figure out the cause off.
> This is in a Django app.
>
> I am using berkelydb, with secondary databases for indexing. The
> secondary databases are associated with a callback that uses cPickle
> to serialize index values. The problem is that cPickle.dumps(value)
> fails when I run it throughmod_wsgior mod_python on the deployment
> server (Ubuntu Linux 8.10), but works fine when when I use Djangos
> runserver on the same computer. Also, on my own computer (Ubuntu Linux
> 8.10), it works fine through mod_python.
>
> Each time I call on cPickle.dumps(value) I get:
> SystemError("Parent module 'd4' not loaded",)
>
> Using sys.exc_info() I get no type or traceback, just that exception.
> The callstack as far as I can figure is:
>
> django
> view
> bsddb.put
> indexer callback
> cPickle.dumps
>
> cPickle.loads works fine within the callback, I can also use
> cPickle.dumps() outside the indexer callback. But inside the callback,
> I need to use normal pickle instead. I just want to know why. I am
> assuming it has something to do with the fact that I go from python to
> C (bsddb) back to python (indexer callback) and back to C (cPickle).
> It is still strange then that cPickle.loads() work, but not
> cPickle.dumps(). I am also only storing integer values when I get this
> error, so no fancy list, dictionaries or objects.

Where is module 'd4'? Is that one of yours defined inside of your
Django project?

One of the problems with Django runserver is that the parent of the
site directory and the site directory are effectively starting points
for searching for modules, even though neither is explicitly listed in
sys.path. The parent is used because runserver does momentarily add
parent to sys.path to import site package root, after which it removes
directory from sys.path. The site directory itself is used because for
runserver that is the current working directory and imports look there
automatically.

End result is that modules inside of site can be imported either via
site package root, or direct. For example, if d4.py was at same level
as settings.py file and site was called mysite, you could import it as
mysite.d4 or just d4. This is bad because means you could end up with
two copies of a module imported under the different name references.

If they way the pickle was done in application was such that reference
was via d4, and then when you deployed to mod_python or mod_wsgi you
only added parent directory of site to Python path, then it will not
be able to find d4, since at that point would only be found as
mysite.d4.

If this is the case, add the site directory to Python path by setting
PythonPath for mod_python or sys.path in WSGI script file for
mod_wsgi. Better still, fix up your code so module references in code,
ie., urls.py, or anywhere else, are always done by site package root
reference and not direct. Ie., such that it uses mysite.d4 and not
just d4.

Would that seem about right?

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


Re: Implementing file reading in C/Python

2009-01-14 Thread David Bolen
Johannes Bauer  writes:

> Yup, I changed the Python code to behave the same way the C code did -
> however overall it's not much of an improvement: Takes about 15 minutes
> to execute (still factor 23).

Not sure this is completely fair if you're only looking for a pure
Python solution, but to be honest, looping through a gazillion
individual bytes of information sort of begs for trying to offload
that into a library that can execute faster, while maintaining the
convenience of Python outside of the pure number crunching.

I'd assume numeric/numpy might have applicable functions, but I don't
use those libraries much, whereas I've been using OpenCV recently for
a lot of image processing work, and it has matrix/histogram support,
which seems to be a good match for your needs.

For example, assuming the OpenCV library and ctypes-opencv wrapper, add
the following before the file I/O loop:

from opencv import *

# Histogram for each file chunk
hist = cvCreateHist([256], CV_HIST_ARRAY, [(0,256)])

then, replace (using one of your posted methods as a sample):

datamap = { }
for i in data:
datamap[i] = datamap.get(i, 0) + 1

array = sorted([(b, a) for (a, b) in datamap.items()], reverse=True)
most = ord(array[0][1])

with:

matrix = cvMat(1, len(data), CV_8UC1, data)
cvCalcHist([matrix], hist)
most = cvGetMinMaxHistValue(hist,
min_val = False, max_val = False,
min_idx = False, max_idx = True)

should give you your results in a fraction of the time.  I didn't run
with a full size data file, but for a smaller one using smaller chunks
the OpenCV varient ran in about 1/10 of the time, and that was while
leaving all the other remaining Python code in place.

Note that it may not be identical results to some of your other
methods in the case of multiple values with the same counts, as the
OpenCV histogram min/max call will always pick the lower value in such
cases, whereas some of your code (such as above) will pick the upper
value, or your original code depended on the order of information
returned by dict.items.

This sort of small dedicated high performance choke point is probably
also perfect for something like Pyrex/Cython, although that would
require a compiler to build the extension for the histogram code.

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


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread Steve Holden
gumbah wrote:
> I have this really strange problem. I hope someone can help:
> 
> I am trying to update a database like so:
> 
> UPDATE `tablename` set fieldx='test' WHERE flfieldx = null and fieldy
> like '%certainvalue%'
> 
> My Python code looks like this:
> 
> fillsql = "UPDATE `tablename` set fieldx='test' WHERE flfieldx = null
> and fieldy like '%%%s%%' " % certainvalue
> print fillsql
> cursor.execute(fillsql)
> 
> #also tried:
> #cursor.execute("UPDATE `tablename` set fieldx='test' WHERE flfieldx =
> null and fieldy like %s ", "%%%s%%" % certainvalue)
> 
> But it doesn't work... But when i copy and past the SQL (printed by
> "print fillsql" line) and execute that in phpMyAdmin, it does work!!!
> 
> Can anyone tell me what i am doing wrong??
> 
1. You can't test for equality with NULL.

2. You don't have quote marks around the LIKE argument.

cursor.execute("UPDATE `tablename` set fieldx='test' WHERE flfieldx IS
NULL and fieldy like '%s' ", "%%%s%%" % certainvalue)

*might* work.

3. I can't be certain my experience with PostgreSQL extends to MySQl,
but I have done experiments which prove to my satisfaction that it isn't
possible to parameterize LIKE arguments. So the only way to do it
appears to be to build the query yourself. This means that you will need
to make sure the string is made "safe", typically by replacing each
occurrence of the string "'" with "''" to retain the syntactic integrity
of the SQL statement. So finally, try

cursor.execute("""UPDATE tablename set fieldx='test'
  WHERE flfieldx IS NULL
  AND fieldy LIKE '%%%s%%'""" %
  certainvalue.replace("'", "''"))

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

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


Re: initialising a class by name

2009-01-14 Thread Willi Richert
Hi,

try the following exemplarily for the os module

import os, types
[(c, klass) for (c,klass) in os.__dict__.items() if 
type(klass)==types.ClassType]

will print: [('_Environ', )]

Regards,
wr

Am Mittwoch, 14. Januar 2009 10:55:27 schrieb Krishnakant:
> On Wed, 2009-01-14 at 00:39 -0800, Chris Rebert wrote:
> > On Wed, Jan 14, 2009 at 12:36 AM, Krishnakant  wrote:
> > > On Wed, 2009-01-14 at 00:20 -0800, Chris Rebert wrote:
> > >> Aside from Steven's excellent idea, to use the getattr() technique
> > >> with your module scheme you'd probably also need to use __import__()
> > >> to dynamically import the right module.
> > >
> > > I would generally import all the modules I would need at the top of the
> > > main module.
> > > then would use getattr(module,class_name) will that work?
> >
> > Yes, that is how you'd do it in that case.
>
> By the way, is there a kind of global list of modules/classes which are
> maintained in a package once the program is loaded into memory?
> happy hacking.
> Krishnakant.
>
> > Cheers,
> > Chris
> > --
> > Follow the path of the Iguana...
> > http://rebertia.com
>
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Parent module not loaded error

2009-01-14 Thread Ståle Undheim
On Jan 14, 11:31 am, Graham Dumpleton 
wrote:
> On Jan 14, 9:20 pm, Ståle Undheim  wrote:
>
>
>
> > I have a pretty strange error that I can't figure out the cause off.
> > This is in a Django app.
>
> > I am using berkelydb, with secondary databases for indexing. The
> > secondary databases are associated with a callback that uses cPickle
> > to serialize index values. The problem is that cPickle.dumps(value)
> > fails when I run it throughmod_wsgior mod_python on the deployment
> > server (Ubuntu Linux 8.10), but works fine when when I use Djangos
> > runserver on the same computer. Also, on my own computer (Ubuntu Linux
> > 8.10), it works fine through mod_python.
>
> > Each time I call on cPickle.dumps(value) I get:
> > SystemError("Parent module 'd4' not loaded",)
>
> > Using sys.exc_info() I get no type or traceback, just that exception.
> > The callstack as far as I can figure is:
>
> > django
> > view
> > bsddb.put
> > indexer callback
> > cPickle.dumps
>
> > cPickle.loads works fine within the callback, I can also use
> > cPickle.dumps() outside the indexer callback. But inside the callback,
> > I need to use normal pickle instead. I just want to know why. I am
> > assuming it has something to do with the fact that I go from python to
> > C (bsddb) back to python (indexer callback) and back to C (cPickle).
> > It is still strange then that cPickle.loads() work, but not
> > cPickle.dumps(). I am also only storing integer values when I get this
> > error, so no fancy list, dictionaries or objects.
>
> Where is module 'd4'? Is that one of yours defined inside of your
> Django project?
>

d4 is the root project name. This message occurs in d4/views.py.

Here is how I set up my wsgi.py - which is in the d4/ folder:
  sys.path.append(path.join(path.dirname(__file__), '..'))

  os.environ['DJANGO_SETTINGS_MODULE'] = 'd4.settings'
  application = django.core.handlers.wsgi.WSGIHandler()

> One of the problems with Django runserver is that the parent of the
> site directory and the site directory are effectively starting points
> for searching for modules, even though neither is explicitly listed in
> sys.path. The parent is used because runserver does momentarily add
> parent to sys.path to import site package root, after which it removes
> directory from sys.path. The site directory itself is used because for
> runserver that is the current working directory and imports look there
> automatically.
>
> End result is that modules inside of site can be imported either via
> site package root, or direct. For example, if d4.py was at same level
> as settings.py file and site was called mysite, you could import it as
> mysite.d4 or just d4. This is bad because means you could end up with
> two copies of a module imported under the different name references.

Everywhere in the code, the imports refer to d4.something.something.
All urls.py files refer to the full package names. The test code where
I am running this is actually quit minimal.

> If they way the pickle was done in application was such that reference
> was via d4, and then when you deployed to mod_python or mod_wsgi you
> only added parent directory of site to Python path, then it will not
> be able to find d4, since at that point would only be found as
> mysite.d4.
>

I use "import cPickle as pickle" at the top off my views file. So I
don't reference imports from other files.

> If this is the case, add the site directory to Python path by setting
> PythonPath for mod_python or sys.path in WSGI script file for
> mod_wsgi. Better still, fix up your code so module references in code,
> ie., urls.py, or anywhere else, are always done by site package root
> reference and not direct. Ie., such that it uses mysite.d4 and not
> just d4.
>
> Would that seem about right?

Unfortunatly, at least to me, it seems that all code is allready
correctly using packagenames. The views.py file where I am testing
this is a simple file that doesn't depend on anything else in the
project. It only imports a set of system modules for testing and info.
The only "dependency" is really the urls.py file, which does refer to
all the views as "d4.views.somemethod".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parent module not loaded error

2009-01-14 Thread Graham Dumpleton
On Jan 14, 9:41 pm, Ståle Undheim  wrote:
> On Jan 14, 11:31 am, Graham Dumpleton 
> wrote:
>
>
>
> > On Jan 14, 9:20 pm, Ståle Undheim  wrote:
>
> > > I have a pretty strange error that I can't figure out the cause off.
> > > This is in a Django app.
>
> > > I am using berkelydb, with secondary databases for indexing. The
> > > secondary databases are associated with a callback that uses cPickle
> > > to serialize index values. The problem is that cPickle.dumps(value)
> > > fails when I run it throughmod_wsgior mod_python on the deployment
> > > server (Ubuntu Linux 8.10), but works fine when when I use Djangos
> > > runserver on the same computer. Also, on my own computer (Ubuntu Linux
> > > 8.10), it works fine through mod_python.
>
> > > Each time I call on cPickle.dumps(value) I get:
> > > SystemError("Parent module 'd4' not loaded",)
>
> > > Using sys.exc_info() I get no type or traceback, just that exception.
> > > The callstack as far as I can figure is:
>
> > > django
> > > view
> > > bsddb.put
> > > indexer callback
> > > cPickle.dumps
>
> > > cPickle.loads works fine within the callback, I can also use
> > > cPickle.dumps() outside the indexer callback. But inside the callback,
> > > I need to use normal pickle instead. I just want to know why. I am
> > > assuming it has something to do with the fact that I go from python to
> > > C (bsddb) back to python (indexer callback) and back to C (cPickle).
> > > It is still strange then that cPickle.loads() work, but not
> > > cPickle.dumps(). I am also only storing integer values when I get this
> > > error, so no fancy list, dictionaries or objects.
>
> > Where is module 'd4'? Is that one of yours defined inside of your
> > Django project?
>
> d4 is the root project name. This message occurs in d4/views.py.
>
> Here is how I set up my wsgi.py - which is in the d4/ folder:
>   sys.path.append(path.join(path.dirname(__file__), '..'))
>
>   os.environ['DJANGO_SETTINGS_MODULE'] = 'd4.settings'
>   application = django.core.handlers.wsgi.WSGIHandler()
>
> > One of the problems with Django runserver is that the parent of the
> > site directory and the site directory are effectively starting points
> > for searching for modules, even though neither is explicitly listed in
> > sys.path. The parent is used because runserver does momentarily add
> > parent to sys.path to import site package root, after which it removes
> > directory from sys.path. The site directory itself is used because for
> > runserver that is the current working directory and imports look there
> > automatically.
>
> > End result is that modules inside of site can be imported either via
> > site package root, or direct. For example, if d4.py was at same level
> > as settings.py file and site was called mysite, you could import it as
> > mysite.d4 or just d4. This is bad because means you could end up with
> > two copies of a module imported under the different name references.
>
> Everywhere in the code, the imports refer to d4.something.something.
> All urls.py files refer to the full package names. The test code where
> I am running this is actually quit minimal.
>
> > If they way the pickle was done in application was such that reference
> > was via d4, and then when you deployed to mod_python or mod_wsgi you
> > only added parent directory of site to Python path, then it will not
> > be able to find d4, since at that point would only be found as
> > mysite.d4.
>
> I use "import cPickle as pickle" at the top off my views file. So I
> don't reference imports from other files.
>
> > If this is the case, add the site directory to Python path by setting
> > PythonPath for mod_python or sys.path in WSGI script file for
> > mod_wsgi. Better still, fix up your code so module references in code,
> > ie., urls.py, or anywhere else, are always done by site package root
> > reference and not direct. Ie., such that it uses mysite.d4 and not
> > just d4.
>
> > Would that seem about right?
>
> Unfortunatly, at least to me, it seems that all code is allready
> correctly using packagenames. The views.py file where I am testing
> this is a simple file that doesn't depend on anything else in the
> project. It only imports a set of system modules for testing and info.
> The only "dependency" is really the urls.py file, which does refer to
> all the views as "d4.views.somemethod".

As a test, just prior to where unpickle is done, do:

  import sys
  import d4

  print >> sys.stderr, "d4.__name__", dr.__name__
  print >> sys.stderr, "d4.__file__", dr.__file__

This will just confirm that manual import works and what values of
those attributes are. The messages will end up in Apache error log for
that virtual host or main server error log as appropriate.

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Bruno Desthuilliers

Russ P. a écrit :
(snip)

I think the issue here is the distinction between hacking and software
engineering. I may be misusing the term "hacking," but I do not mean
it in a pejoritive sense. I just mean getting things done fast without
a lot of concern for safety, security, and long-term maintainability
and scalability.


I do feel concerned by these issues.


I'm not a computer scientist, but it seems to me that
Python is great for hacking and good for software engineering, but it
is not ideal for software engineering.

What Paul is suggesting, I think, is that Python should move in the
direction of software engineering. Whether that can be done without
compromising its hacking versatility is certainly a valid question,
but if it can be done, then why not do it?

Certainly one basic principle of software engineering is data
encapsulation. Tacking new attributes onto class instances all over
the place


There's a clear distinction between "making wise use of dynamicity" and 
"tacking new attributes onto class instances all over the place".



may be convenient and useful in many cases, but it is not
consistent with good software engineering.


simplicity is "good software engineering". Accidental complexity is not. 
Dynamism _can_ greatly reduce accidental complexity.




If the programmer could
somehow disallow it in certain classes,


Already possible - you just have to provide your own implementation of 
__setattr__.



that could be useful,
providing that those who wish to continue doing it would be free to do
so. If class attributes could somehow be declared private,


The important point is to make implementation distinct from interface - 
which we already know how to do -, and sometimes to prevent _accidental_ 
overriding of some critical implementation attributes - which is also 
already implemented. Enforcing access restriction is, from experience, 
just pointless.


"""
patient : doctor, when I do this, it hurts
doctor : well, don't do it, then.
"""
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'Import sys' succeeds in C++ embedded code, but module is not fully visible

2009-01-14 Thread Ben Sizer
On Jan 14, 1:55 am, Ivan Illarionov  wrote:
> Ben Sizer  wrote:
> > What am I doing wrong?
>
> What are you trying to achieve?
> If you want to modify sys.path I suggest using Python/C API directly:

No, I don't want to do anything with sys.path apart from see it. I
just wanted my original question answered, not a guess at my intent
and a solution for something I'm not doing. ;)  Thanks though!

Again - why can I not reference sys from within the function?

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


Re: PYTHON HTTP POST

2009-01-14 Thread dhaval
The action part of the field is not set to anything.
I need any site with working example that accepts POST.

On Jan 14, 2:21 pm, koranth...@gmail.com wrote:
> Does google accept POST?
>
> Anyways, if you dont need to post files, you can use urlencode itself.
> def encode_formdata(fields):
> body = urllib.urlencode(dict())
> content_type = "application/x-www-form-urlencoded"
> return content_type, body
>
> If you need to post files too, then you will have to use multipart
> data
> def encode_multipart_formdata(fields, files):
> """
> fields is a sequence of (name, value) elements for regular form
> fields.
> files is a sequence of (name, filename, value) elements for data
> to be uploaded as files
> Return (content_type, body) ready for httplib.HTTP instance
> """
> BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'
> CRLF = '\r\n'
> L = []
> for (key, value) in fields:
> L.append('--' + BOUNDARY)
> L.append('Content-Disposition: form-data; name="%s"' % key)
> L.append('')
> L.append(value)
> for (key, filename, value) in files:
> L.append('--' + BOUNDARY)
> L.append('Content-Disposition: form-data; name="%s";
> filename="%s"' % (key, filename))
> L.append('Content-Type: %s' % mimetypes.guess_type(filename)
> [0] or 'application/octet-stream'
> L.append('')
> L.append(value)
> L.append('--' + BOUNDARY + '--')
> L.append('')
> body = CRLF.join(L)
> content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
> return content_type, body
>
> Since POST files doesnt work with urllib, you might have to use
> httplib - or go for very high level tools like twisted.
> I here show an example with httplib.
>
> def post(host, selector, fields, files):
> if files:
>content_type, body = encode_multipart_formdata(fields, files)
> else:
>content_type, body = encode_formdata(fields)
>
> h = httplib.HTTPConnection(host)
> #Spoof Mozilla
> headers = {
> 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
> rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4',
> 'Content-Type': content_type
> }
> h.request('POST', selector, body, headers)
> res = h.getresponse()
> return res.status, res.reason, res.read()
>
> Please note that you can use multipart whether or not files are there,
> but parsing multipart usually is slower.
>
> Hope this helps.
>
> lilanidha...@gmail.com wrote:
> > Hi,
>
> > I need one complete example of how to do a http post to any site.
> > I have tried making a POST to google but all I am returned with is a
> > 405 error.
> > I don't want to use Pygoogle as I want to try and do this with other
> > sites.
> > I am also having problems inputing with the param
> > I have tried Mechanize. There are no problems with getting data only
> > posting.
>
> > >>> headers = {'Content-Type': 'text/html; charset=ISO-8859-1',
> > ... 'User-Agent':'Mozilla/4.0',
> > ... 'Content-Length':'7'}
> > >>> conn = httplib.HTTPConnection("www.google.com")
> > >>> conn.request("POST","/search",params,headers)
> > >>> r2 =  conn.getresponse()
> > >>> print r2.status, r2.reason
> > 405 Method Not Allowed
>
> > Regards,
> > Dhaval

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Marc 'BlackJack' Rintsch
On Wed, 14 Jan 2009 07:14:06 +, Steven D'Aprano wrote:

> On Wed, 14 Jan 2009 15:25:38 +1000, James Mills wrote:
> 
>> On Wed, Jan 14, 2009 at 3:11 PM, Russ P. 
>> wrote: (...)
>> 
 Give me one use-case where you strictly require that members of an
 object be private and their access enforced as such ?
>>>
>>> You're kidding, right? Think about a ten-million line program being
>>> developed by 100 developers.
>> 
>> No I"m sorry this is not a valid use-case.
> 
> Why not? Just saying it isn't doesn't make it not.

Because "developer" means people who don't mess with implementation 
details.  So they respect the leading underscore convention.  No use case 
for enforced access restriction.

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


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread John Machin
On Jan 14, 8:55 pm, gumbah  wrote:
> Hi John,
>
> thanks a lot for your quick reply!

Please don't top-post.
Please answer the question """You don't say what "doesn't work"
means ... did you get exceptions, or just silently not updating?"""

>
> I tried all of your suggestions but none of them work... I have a clue
> on why it is failing: MySQLdb seems to quote the % characters or
> something...
>
> Even when i do:
> cursor.execute("UPDATE tablename set fieldx='test' WHERE flfieldx is
> null and fieldy like '%therealvalue%' "

Please stop stuffing around with the 'trial 1' method.

What SQL data type is fieldy?
What Python datatype is therealvalue coming from?
Do this:
   print type(realvalue), repr(realvalue)
Are you sure that the datatypes are compatible? Is there perhaps a
Unicode encoding problem?

Try this:
cursor.execute("select fieldy from tablename")
# dig out a sample result
print type(sample_result), repr(sample_result)
print therealvalue in sample_result

I suggest that you avoid UPDATE and the supersensitive fieldy none of
whose values you can reveal, and try the code on a column with simple
noncontroversial data e.g. if you have an address table with the U.S.
state code in it, we can try a simple query to find all addresses that
are in a state that contains some letter:
state_letter = "A"
sql = "select address_id, state from address where state like %s"
cursor.execute(sql, ("%" + state_letter + "%", ))
That would be my best shot at getting it to work. It is based on this:
http://mail.python.org/pipermail/python-list/2003-August/218382.html

If that works, try applying it to a query on fieldy and then to your
original problem.

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


Re: Standard IPC for Python?

2009-01-14 Thread sturlamolden
On Jan 13, 5:25 pm, Laszlo Nagy  wrote:

> I would like to develop some module for Python for IPC. Socket
> programming howto recommends that for local communication, and I
> personally experienced problems with TCP (see my previous post: "Slow
> network").

There are plenty of different IPC mechanisms available in
multiprocessing.


> I was looking for semaphores and shared memory, but it is not in the
> standard lib.

Take a look at:

- multiprocessing.Array and multiprocessing.Value

- mmap.mmap with 0 or -1 as the first argument (Windows and Linux,
respectively)

- pywin32 on Windows (not standard lib)



> I was also thinking about unix domain sockets, but it is
> not available under windows.

Unix domain sockets are called 'named pipes' under Windows. Look for
it in multiprocessing or pywin32.



> The question is: what is the standard way to implement fast and portable
> IPC with Python?

form multiprocessing import Queue




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


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread John Machin
On Jan 14, 9:22 pm, gumbah  wrote:
> Aahh the conn.commit() DID the trick!!
>
> I tried that before, but then it failed at another point. I got it
> working now! Thanks a lot Peter and John!!

For the benefit of future searchers, can you please tell us which
varieties of cursor.execute() it works on -- copy/paste the code that
was run, please, rather than some possibly vague/ambiguous
narrative :-)
and do please try it using a parameterised method ("trial 2"), because
that's much more prefereable to build-your-own SQL ("trial 1") if both
work.

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


PYTHON HTTP POST WORKING EXAMPLE NEEDED

2009-01-14 Thread dhaval
Hi,

Can someone please give me an example of a working python post?
for example using the site http://www.cookiemag.com/

Thanks in advance,
Dhaval
--
http://mail.python.org/mailman/listinfo/python-list


Re: PYTHON HTTP POST WORKING EXAMPLE NEEDED

2009-01-14 Thread dhaval
On Jan 14, 4:11 pm, dhaval  wrote:
> Hi,
>
> Can someone please give me an example of a working python post?
> for example using the sitehttp://www.cookiemag.com/
>
> Thanks in advance,
> Dhaval

I have tried to look at the code at
http://code.activestate.com/recipes/146306/
I can't make any sense out of it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Re: problem calling method

2009-01-14 Thread pieterprovoost
The parent is called like this (I didn't copy that line):

def __init__(self, *args, **kwds):
 # begin wxGlade: MyFrame.__init__
 kwds["style"] = wx.DEFAULT_FRAME_STYLE
 wx.Frame.__init__(self, *args, **kwds)

The frame works fine and so does the button, but somehow I cannot call the 
sendmail method from the event handler...

-- James Mills wrote : 
On Wed, Jan 14, 2009 at 11:28 AM,   wrote:
> class MyFrame(wx.Frame):
>def __init__(self, *args, **kwds):

It might be helpful here if you called
the parent __init__. Like so:

class MyFrame(wx.Frame):
   def __init__(self, *args, **kwds):
  super(MyFrame, self).__init__(*args, **kwargs)

...

cheers
James
--



--
This message was sent on behalf of pieterprovo...@gmail.com at 
openSubscriber.com
http://www.opensubscriber.com/message/python-list@python.org/11236393.html
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] SWIG 1.3.37

2009-01-14 Thread Haoyu Bai
This is the SWIG with Python 3.0 support! :)

*** ANNOUNCE: SWIG 1.3.37 (13 January 2009) ***

http://www.swig.org


We're pleased to announce SWIG-1.3.37, the latest installment in the
SWIG development effort.  SWIG-1.3.37 includes a number of bug fixes
and enhancements.

What is SWIG?
-

SWIG is a software development tool that reads C/C++ header files and
generates the wrapper code needed to make C and C++ code accessible
from other languages including Perl, Python, Tcl, Ruby, PHP, Java,
Scheme (Guile, MzScheme, CHICKEN), Ocaml, Lua, Pike, C#, Modula-3,
Octave, R,
Common Lisp (CLISP, Allegro CL, CFFI, UFFI). SWIG can also export its parse
tree in the form of XML and Lisp s-expressions.  Major applications of
SWIG include generation of scripting language extension modules, rapid
prototyping, testing, and user interface development for large C/C++
systems.

Availability:
-
The release is available for download on Sourceforge at

http://prdownloads.sourceforge.net/swig/swig-1.3.37.tar.gz

A Windows version is also available at

http://prdownloads.sourceforge.net/swig/swigwin-1.3.37.zip

What's New?
===

SWIG-1.3.37 summary:
- Python 3 support added
- SWIG now ships with a version of ccache that can be used with SWIG.
 This enables the files generated by SWIG to be cached so that repeated
 use of SWIG on unchanged input files speeds up builds quite considerably.
- PHP 4 support removed and PHP support improved in general
- Improved C# array support
- Numerous Allegro CL improvements
- Bug fixes/enhancements for Python, PHP, Java, C#, Chicken, Allegro CL,
 CFFI, Ruby, Tcl, Perl, R, Lua.
- Other minor generic bug fixes and enhancements

Release numbers
---
With SWIG-1.3, we are adopting an odd/even version numbering scheme for
SWIG.  Odd version numbers (1.3, 1.5, 1.7, etc...) are considered to
be development releases.  Even numbers (1.4,1.6,1.8) are stable
releases.  The current 1.3 effort is working to produce a stable 2.0
release.  A stable 2.0 release will not be made until it can
accompanied by fully updated documentation.  In the meantime, we will
continue to make periodic 1.3.x releases.

Please report problems with this release to the swig-dev mailing list,
details at http://www.swig.org/mail.html.

--- The SWIG Developers
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Carl Banks
On Jan 14, 2:44 am, "Russ P."  wrote:
> On Jan 13, 11:51 pm, Paul Rubin  wrote:
>
> > Carl Banks  writes:
> > > At GE there was no encapsulation in sight on any system I worked on.
> > > In fact, our engine simulation was a special-purpose object-oriented
> > > language with--get this--no private variables.  Some other systems I
> > > worked on didn't even use scoping, let alone encapsulation.
>
> > Where my officemate used to work, the simulation stuff was written in
> > Matlab, but the actual flight stuff was written in Ada.  I wonder
> > if GE did something similar.
>
> I was going to suggest the same thing.

I thought you were done wasting time with this nonsense.

> An engine *simulation* is one
> thing; the actual engine control code is another.

Guess what systems I worked on that didn't even use scoping?  I wrote
code for the GP7000 (equipped on some Airbus 380s) and the F-136
(which will be equipped on some F-35 fighters) engine controllers.
Neither one used any data hiding.  The language was C (not C++), but
it was generated from schematic diagrams.

Would you like to adopt GE's practice of schematic-generated C with no
namespaces or data hiding?  No?  Then don't be telling me I have to
embrace Boeing's.


Carl Banks



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


Re: sys.stdout.write()'s bug or doc bug?

2009-01-14 Thread Steven D'Aprano
On Sun, 11 Jan 2009 19:38:48 -0800, Aahz wrote:

> In article
> ,
> Qiangning Hong   wrote:
>>
>>So, my question is, as sys.stdout IS a file object, why it does not use
>>its encoding attribute to convert the given unicode?  An implementation
>>bug? A documenation bug?
> 
> Please file a bug on bugs.python.org -- that's the only way this can be
> tracked.


Done:

http://bugs.python.org/issue4947


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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Terry Reedy

Paul Rubin wrote:

"James Mills"  writes:

You do realize this is a model and not strictly a requirement. Quite
a few things in Python are done merely by convention.
Don't get caught up.


But, if something is done by convention, then departing from the
convention is by definition unconventional.  If you do something
unconventional in a program, it could be on purpose for a reason, or
it could be by accident indicating a bug.  


I don't understand why some folks spew such violent rhetoric against
the idea of augmenting Python with features to alert you automatically
when you depart from the convention, so that you can check that the
departure is actually what you wanted.  A lot of the time, I find, the
departures are accidental and automated checks would save me
considerable debugging.


The question is where such checks should be.  Guido prefers separate 
checkers (PyChecker, PyLint) rather than in the interpreter.  If you 
think they are incomplete, help improve one of them.


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


Re: PYTHON HTTP POST WORKING EXAMPLE NEEDED

2009-01-14 Thread Diez B. Roggisch
dhaval wrote:

> On Jan 14, 4:11 pm, dhaval  wrote:
>> Hi,
>>
>> Can someone please give me an example of a working python post?
>> for example using the sitehttp://www.cookiemag.com/
>>
>> Thanks in advance,
>> Dhaval
> 
> I have tried to look at the code at
> http://code.activestate.com/recipes/146306/
> I can't make any sense out of it.

 - don't SHOUT.
 - don't open up new threads 2 hours after you asked the first time with the
*same* question.
 - show code of your actual efforts. This is not the "free code snippets
producing system."
 - read this: http://www.catb.org/~esr/faqs/smart-questions.html

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


Re: Parent module not loaded error

2009-01-14 Thread Ståle Undheim
On Jan 14, 11:48 am, Graham Dumpleton 
wrote:
> As a test, just prior to where unpickle is done, do:
>
>   import sys
>   import d4
>
>   print >> sys.stderr, "d4.__name__", dr.__name__
>   print >> sys.stderr, "d4.__file__", dr.__file__
>
> This will just confirm that manual import works and what values of
> those attributes are. The messages will end up in Apache error log for
> that virtual host or main server error log as appropriate.

d4.__name__ d4
d4.__file__ /home/petromarker/django-apps/d4/src/d4/../d4/__init__.pyc

It's the same both before and after the exception.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Standard IPC for Python?

2009-01-14 Thread Laszlo Nagy



There are plenty of different IPC mechanisms available in
multiprocessing.
  
It is good for a special case: a tree of processes, forked from a main 
process. multiprocessing.Queue cannot be used as a general message queue 
between arbitrary processes.

- mmap.mmap with 0 or -1 as the first argument (Windows and Linux,
respectively)
  
Which lacks synchronization between processes. (How do you notify the 
other process? How can the other process wait until notified?)


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


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread John Machin
On Jan 14, 9:42 pm, Steve Holden  wrote:

> 3. I can't be certain my experience with PostgreSQL extends to MySQl,
> but I have done experiments which prove to my satisfaction that it isn't
> possible to parameterize LIKE arguments. So the only way to do it
> appears to be to build the query yourself. This means that you will need
> to make sure the string is made "safe", typically by replacing each
> occurrence of the string "'" with "''" to retain the syntactic integrity
> of the SQL statement. So finally, try
>
> cursor.execute("""UPDATE tablename set fieldx='test'
>                   WHERE flfieldx IS NULL
>                   AND fieldy LIKE '%%%s%%'""" %
>                   certainvalue.replace("'", "''"))

It appears possible to parameterise LIKE arguments in sqlite3:
8<--- code
import sqlite3
tests = [
["select * from foo", None],
["select * from foo where text like '%o%'", None],
["select * from foo where text like ?", "o"],
["select * from foo where text like ?", "a"],
]
conn = sqlite3.connect("c:/junk/sql_like/foodb")
curs = conn.cursor()
for testno, test in enumerate(tests):
sql, parm = test
print "\n=== Test %d ===" % (testno + 1)
print "sql =", sql
print "parm =", parm
if parm is None:
curs.execute(sql)
else:
arg2 = "%" + parm + "%"
curs.execute(sql, (arg2, ))
results = curs.fetchall()
print "results:", results
8<--- output

=== Test 1 ===
sql = select * from foo
parm = None
results: [(u'alpha',), (u'bravo',), (u'charlie',), (u'delta',),
(u'echo',), (u'foxtrot',)]

=== Test 2 ===
sql = select * from foo where text like '%o%'
parm = None
results: [(u'bravo',), (u'echo',), (u'foxtrot',)]

=== Test 3 ===
sql = select * from foo where text like ?
parm = o
results: [(u'bravo',), (u'echo',), (u'foxtrot',)]

=== Test 4 ===
sql = select * from foo where text like ?
parm = a
results: [(u'alpha',), (u'bravo',), (u'charlie',), (u'delta',)]

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Steven D'Aprano
On Wed, 14 Jan 2009 10:53:33 +, Marc 'BlackJack' Rintsch wrote:

> On Wed, 14 Jan 2009 07:14:06 +, Steven D'Aprano wrote:
> 
>> On Wed, 14 Jan 2009 15:25:38 +1000, James Mills wrote:
>> 
>>> On Wed, Jan 14, 2009 at 3:11 PM, Russ P. 
>>> wrote: (...)
>>> 
> Give me one use-case where you strictly require that members of an
> object be private and their access enforced as such ?

 You're kidding, right? Think about a ten-million line program being
 developed by 100 developers.
>>> 
>>> No I"m sorry this is not a valid use-case.
>> 
>> Why not? Just saying it isn't doesn't make it not.
> 
> Because "developer" means people who don't mess with implementation
> details.  So they respect the leading underscore convention.  No use
> case for enforced access restriction.


O rly? *raise eyebrow*

http://www.clausbrod.de/cgi-bin/view.pl/Blog/
WebHome#DefinePrivatePublic20080413_This

or http://snipurl.com/a0ujm

Sometimes developers have to work around encapsulation in their own code:
http://www.gamedev.net/community/forums/topic.asp?topic_id=386856

Sometimes they do it just because they can:

http://java-interview-faqs.blogspot.com/2008/08/hacking-by-reflection-
accessing-private.html
or http://snipurl.com/a0tox

And try this:

http://www.google.com/codesearch?q=%22%23define+private+public%22



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


Re: Standard IPC for Python?

2009-01-14 Thread sturlamolden
On Jan 14, 12:47 pm, Laszlo Nagy  wrote:

> multiprocessing.Queue cannot be used as a general message queue
> between arbitrary processes.

Then e.g. use Listener and Client in multiprocessing.connection to
create a named pipe (AF_PIPE). Or use win32pipe.CreateNamedPipe from
pywin32.


> - mmap.mmap with 0 or -1 as the first argument (Windows and Linux,
> > respectively)
>
> Which lacks synchronization between processes.

It gives you access to shared memory. You must obviously use
synchronization objects for synchronization.



> (How do you notify the
> other process? How can the other process wait until notified?)

multiprocessing.Event
multiprocessing.Lock
win32event.CreateEvent
win32event.SetEvent
win32event.CreateMutex

etc.















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


Re: Why this code is working?

2009-01-14 Thread Steven D'Aprano
On Wed, 14 Jan 2009 01:57:48 -0800, Hussein B wrote:

>> Well... Because it is correct ?
>>
>> What make you think it _shouldn't_ work ?
> 
> Because def2 is defined after def1 in an interpreted language, not
> compiled.

Python is compiled.

What do you think the c in .pyc stands for? And what do you think the 
compile() function does?

It's just not compiled to machine code. It's compiled to byte code.



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


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread Peter Otten
gumbah wrote:

> I tried all of your suggestions but none of them work... I have a clue
> on why it is failing: MySQLdb seems to quote the % characters or
> something...
> 
> Even when i do:
> cursor.execute("UPDATE tablename set fieldx='test' WHERE flfieldx is
> null and fieldy like '%therealvalue%' "

> it is not updating the database...
> 
> Maybe I am completely overlooking something, but I am pretty lost
> here... Googling this it seems as if no one is using "LIKE '%value%'"
> type queries with Python & mySQL...
> 
> Anyone any other thoughts?

Did you call the connection object's commit() method?

Peter

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


Re: Why this code is working?

2009-01-14 Thread Hussein B
On Jan 14, 2:21 pm, Steven D'Aprano  wrote:
> On Wed, 14 Jan 2009 01:57:48 -0800, Hussein B wrote:
> >> Well... Because it is correct ?
>
> >> What make you think it _shouldn't_ work ?
>
> > Because def2 is defined after def1 in an interpreted language, not
> > compiled.
>
> Python is compiled.
>
> What do you think the c in .pyc stands for? And what do you think the
> compile() function does?
>
> It's just not compiled to machine code. It's compiled to byte code.
>
> --
> Steven

Yes I know Python programs can be compiled but when I do:
python Script1.py
Did Python compile Script1 into the memory?
--
http://mail.python.org/mailman/listinfo/python-list


Re: os system command not found

2009-01-14 Thread Steven D'Aprano
On Wed, 14 Jan 2009 02:25:52 -0800, codicedave wrote:

> Hi all!
> I installed a external program called infomap using the classical
> procedure
> 
> ./configure
> make
> sudo make install
> 
>  and it works perfectly in Terminal (Os x) using both bash and tcsh
> shell

What happens when you call it using the sh shell (which is not 
necessarily aliased to bash)?



[...]
>  but when I call it from python using os.system or subprocess.call I
> get the message "sh: infomap-build: command not found".
> 
> Do you know why?

Possibly sh uses a different path to bash and can't find infomap-build.



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


Re: Why this code is working?

2009-01-14 Thread Benjamin Kaplan
On Wed, Jan 14, 2009 at 7:59 AM, Hussein B  wrote:

> On Jan 14, 2:21 pm, Steven D'Aprano  cybersource.com.au> wrote:a
> > On Wed, 14 Jan 2009 01:57:48 -0800, Hussein B wrote:
> > >> Well... Because it is correct ?
> >
> > >> What make you think it _shouldn't_ work ?
> >
> > > Because def2 is defined after def1 in an interpreted language, not
> > > compiled.
> >
> > Python is compiled.
> >
> > What do you think the c in .pyc stands for? And what do you think the
> > compile() function does?
> >
> > It's just not compiled to machine code. It's compiled to byte code.
> >
> > --
> > Steven
>
> Yes I know Python programs can be compiled but when I do:
> python Script1.py
> Did Python compile Script1 into the memory?
>  --
>

yes it does, but not in the way you are thinking. Python compiles to its
byte code as needed, not at the start of the program. Because Python is
dynamic, you can change things on the fly. For instance, this code is
perfectly valid

def f2(x) :
   print x

def f1() :
   f2(88)

f1() #prints 88

def f2(x) :
   print x/2

f1() #prints 44

Because the code can change on the fly, Python looks for f2 every time f1 is
called, not when it first sees the function. This is the beauty of a dynamic
language.

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Benjamin Kaplan
On Wed, Jan 14, 2009 at 7:07 AM, Steven D'Aprano <
st...@remove-this-cybersource.com.au> wrote:

> On Wed, 14 Jan 2009 10:53:33 +, Marc 'BlackJack' Rintsch wrote:
>
> > On Wed, 14 Jan 2009 07:14:06 +, Steven D'Aprano wrote:
> >
> >> On Wed, 14 Jan 2009 15:25:38 +1000, James Mills wrote:
> >>
> >>> On Wed, Jan 14, 2009 at 3:11 PM, Russ P. 
> >>> wrote: (...)
> >>>
> > Give me one use-case where you strictly require that members of an
> > object be private and their access enforced as such ?
> 
>  You're kidding, right? Think about a ten-million line program being
>  developed by 100 developers.
> >>>
> >>> No I"m sorry this is not a valid use-case.
> >>
> >> Why not? Just saying it isn't doesn't make it not.
> >
> > Because "developer" means people who don't mess with implementation
> > details.  So they respect the leading underscore convention.  No use
> > case for enforced access restriction.
>
>
> O rly? *raise eyebrow*
>
> http://www.clausbrod.de/cgi-bin/view.pl/Blog/
> WebHome#DefinePrivatePublic20080413_This
>
> or http://snipurl.com/a0ujm
>
> Sometimes developers have to work around encapsulation in their own code:
> http://www.gamedev.net/community/forums/topic.asp?topic_id=386856
>
> Sometimes they do it just because they can:
>
> http://java-interview-faqs.blogspot.com/2008/08/hacking-by-reflection-
> accessing-private.html
> or http://snipurl.com/a0tox
>
> And try this:
>
> http://www.google.com/codesearch?q=%22%23define+private+public%22
>




I think you actually just proved his point- the access restrictions are
pointless. If there are ways to access private variables, then aren't they
just private by convention as well? The only difference with Python is that,
rather than going through the introspection (which Python does better than
Java anyway) to get the variables, all you have to do is type that leading
underscore. Either way, you know you're doing something you shouldn't.


--
Steven

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


Re: Why this code is working?

2009-01-14 Thread Diez B. Roggisch
r wrote:

> Listen Hussien,

Granted, with a name of "r", spelling it wrong is hard, and thus you might
not be trained in the art of spelling names proper. But I suggest you try
your best. After all, you posts lack so much in content, you could at least
excel in form...

> In python you do not have to worry about what order this is, what type
> to declare that, my friend your bonds are cut. Be happy with your
> freedom and stop complaining about it. I guess where i come from
> freedom is second nature so i took to python pretty quick.

What's that condescending nonsense to mean?  What do you know of the
heritage and living circumstances of the OP? And since when is a choice of
typing-system correlated with the political and social aspects of a
society - you care to prove that?

And where did the OP "complain"? He merely wondered.

I'm well aware that you are a piece of trolling d.t. But this goes a bit
to far, Mr.

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


Re: ctype problem

2009-01-14 Thread Nick Craig-Wood
Grimson  wrote:
>  hello out there,
>  I have a problem with c-types.
>  I made a c-library, which expects a pointer to a self defined structure.
> 
>  let the funtion call myfunction(struct interface* iface)
> 
>  and the struct:
>  struct interface
>  {
>  int a;
>  int b;
>  char *c;
>  }
> 
>  the Python ctype port of this structur would be:
> 
>  class INTERFACE(Structure):
>  _fields_ = [("a" c_int),
>("b",c_int),
>("c", c_char)]
> 
>  in my python-struct a create a instance of INTERFACE
> 
>  myiface = INTERFACE()
>  myiface.a = ctypes.c_int(80)
>  myiface.b = ctypes.c_int(22)
>  ...
>  than I make a pointer onto it.
>  p_iface = ctypes.pointer(myiface)
>  and I tried it also with a reference
>  r_iface = ctypes.byref(myiface)
> 
>  but neither myclib.myfunction(p_iface) nor myclib.myfunction(r_iface)
>  works properly. The function is been called but it reads only zeros (0)
>  for each parameter (member in the struct).
> 
>  Where is my fault?

You didn't (or you didn't show) defining the argument types of the
function.

myclib = CDLL("myclib.so") # or whatever
myclib.myfunction.argtypes = [ POINTER(INTERFACE) ]
myclib.myfunction.restype = c_int # or whatever

If you do that then you should be able to pass in myiface directly or
byref(myiface).

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: are there some special about '\x1a' symbol

2009-01-14 Thread Grant Edwards
On 2009-01-14, Steve Holden  wrote:
> Unknown wrote:
>> On 2009-01-12, John Machin  wrote:
>> 
>>> I didn't think your question was stupid. Stupid was (a) CP/M recording
>>> file size as number of 128-byte sectors, forcing the use of an in-band
>>> EOF marker for text files (b) MS continuing to regard Ctrl-Z as an EOF
>>> decades after people stopped writing Ctrl-Z at the end of text files.
>> 
>> I believe that "feature" was inherited by CP/M from DEC OSes
>> (RSX-11 or RSTS-11). AFAICT, all of CP/M's file I/O API
>> (including the FCB) was lifted almost directly from DEC's
>> PDP-11 stuff, which probably copied it from PDP-8 stuff.
>> 
>> Perhaps in the early 60's somebody at DEC had a reason.  The
>> really interesting thing is that we're still suffering because
>> of it 40+ years later.
>> 
> I suspect this is probably a leftover from some paper tape data formats,
> when it was easier to detect the end of a file with a sentinel byte than
> it was to detect run-off as end of file. It could easily date back to
> the PDP-8.

You're probably right.  That's why the "delete" character is
all 1's (all holes).  It's easy to punch more holes --
un-punching them is pretty arduous.

-- 
Grant

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


Re: why cannot assign to function call

2009-01-14 Thread Aaron Brady
On Jan 14, 3:51 am, Mark Wooding  wrote:
> Aaron Brady  wrote:
> > On Jan 13, 5:06 pm, Mark Wooding  wrote:
> > snip
> > > I'm going to move away from the formal semantics stuff and try a
> > > different tack.  Here's what I think is the defining property of
> > > pass-by-value (distilled from the formal approach I described earlier,
> > > but shorn of the symbolism):
>
> > >   The callee's parameters are /new variables/, initialized /as if by
> > >   assignment/ from the values of caller's argument expressions.
>
> > In other words, the same as assignment in that language.
>
> It's the same as assignment of /values/ to /fresh variables/.  It's
> important to specify that argument expressions are fully evaluated, and
> that nothing gets overwritten in the process.
>
> So the difference between Python and C is that C copies values during
> assignment, but Python doesn't.  Therefore the argument passing works
> the same way.

That interferes with Joe's claim that the value of a variable is a
memory address.  I think you'd have better luck sticking with "pass-by-
assignment".

A Java reference and a C++ reference are different things, somewhat
regrettably.

> > > Because its argument passing works the same way as its assignment.
>
> > That would be called pass-by-assignment.  But you've just postponed
> > explaining yourself.  Stop delegating and work.
>
> Huh?  I'm really at a loss to know what you want me to do.

You were remarkably civil about that.  I regretted it as soon as I
sent it.  You keep wanting to say "but it's just a reference, it's
just a reference".  But all that does is put more burden on the fellow
that explains what a reference is.  It took me years to grasp
pointers... possibly all the way up until comp. architecture class.
(As such, I find you're shirking.)

> I can't help it if people are confused over the phrase `pass-by-value',
> beyond trying to explain what it means using clear definitions.  The
> `value' part means that argument expressions are /evaluated/ (turned
> into values), which forces applicative-order semantics rather than (say)
> normal-order.

I can't believe it's taken this long, including October's discussion
( and especially with my dual (not duel, ha!) in
Philosophy ), but I'd finally like to quote the manuals.

"An object's identity never changes once it has been created."
"The value of some objects can change."
- http://docs.python.org/reference/datamodel.html

Therefore, an object's value is not its identity.  (Its identity is
something other than its value.)  You might get away with 'pass-by-
identity'.

After 'X= [1, 2, 3]', X refers to an object.  You can change two
things: (1) the fact that X refers to that object, (2) that object.

In 'X= None' and 'del X', you change the fact that X refers to that
object.  In 'X[:]= [4, 5, 6]' and 'X.pop()', you change the object.

Explanatory note: It really takes two sentences to say that.  'X
refers to an object.  You can change the object, or change the fact
that X refers to it.'  If you try to say it in one sentence, the
distinction collapses:  'You can change (1) the object that X refers
to, or (2) the object that X refers to.'  Irony!

'X' is a key in a namespace.

namespace[ 'X' ]= [1, 2, 3]
namespace[ 'Y' ]= namespace[ 'X' ]
del namespace[ 'X' ]

No matter how hard you try, if you don't have both of two things,
'namespace' and '"X"', you can't change namespace[ 'X' ].

And back to the OP (long since gone, naturally): You can do:
f()[:]= [1, 2, 3]
As well as:
f().replace( [1, 2, 3] )
As well as:
f().contents= [1, 2, 3]

The particular thing s/he wanted isn't one of these.

Lastly, I think it would do you and Joe good to ignore some details,
when thinking about beginners.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Re: are there some special about '\x1a' symbol

2009-01-14 Thread Grant Edwards
On 2009-01-14, Gabriel Genellina  wrote:
> En Tue, 13 Jan 2009 22:04:33 -0200, Terry Reedy   
> escribió:
>
>> Gabriel Genellina wrote:
>>> En Mon, 12 Jan 2009 12:00:16 -0200, John Machin   
>>> escribió:
>>>
 I didn't think your question was stupid. Stupid was (a) CP/M recording
 file size as number of 128-byte sectors, forcing the use of an in-band
 EOF marker for text files (b) MS continuing to regard Ctrl-Z as an EOF
 decades after people stopped writing Ctrl-Z at the end of text files.
>>>  This is called "backwards compatibility" and it's a good thing :)
>>
>> But it does not have to be the default or only behavior to be available.
>
> Sure. And it isn't

It _is_ the default behavior on some systems.  The default file
mode when you open a file in C or in Python is "text" mode.  In
text mode, Windows interprets a ctrl-Z as EOF, doesn't it?

-- 
Grant

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


can someone tell me why this doesn't work please python 3

2009-01-14 Thread garywood
def ask_ok(prompt, retries=4, complaint="Yes or no, please!"):
while True:
password = input("enter something")
if password in ('y', 'ye', 'yes'): return True
if password in ('n', 'no', 'nope'): return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print(complaint)--
http://mail.python.org/mailman/listinfo/python-list


Re: pep 8 constants

2009-01-14 Thread Benjamin Kaplan
On Wed, Jan 14, 2009 at 3:13 AM, Steven D'Aprano <
ste...@remove.this.cybersource.com.au> wrote:

> On Tue, 13 Jan 2009 23:26:54 -0800, Brendan Miller wrote:
>
> > I tend to use constants as a means of avoiding the proliferation of
> > magic literals for maintenance reasons... Like say if your example of
> > FOO would have been used in 10 places. Maybe it is more pythonic to
> > simply denote such a thing as simply a normal variable?
>
> But it isn't a "normal variable", it's a named constant, or at least it
> would be if Python enforced constanticity. Or constantness. Or whatever.
>
> > That doesn't
> > seem to give a hint that it shouldn't be assigned a second time.
>
> Absolutely. It's rather sad that I can do this:
>
> import math
> math.pi = 3.0
>
> I like the ability to shoot myself in the foot, thank you very much, but
> I should at least get a warning when I'm about to do so:
>
> math.PI = 3.0  # use God-like powers to change a constant


(OT)

You don't need God-like powers to do that. God already did it (it's in the
bible somewhere, I don't remember where)
And the Indiana state legislature thinks that doing that changing the value
of pi is a perfectly legitimate action. (I guess they arrest all circles
whose circumfrence:diameter ratio doesn't conform to the new value ???)
http://en.wikipedia.org/wiki/Indiana_Pi_Bill

>
>
>
>
>
> Changing the laws of physics, one fundamental constant at a time-ly y'rs,
>
> --
> Steven
>  --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: os system command not found

2009-01-14 Thread codicedave
On 14 Gen, 13:16, Steven D'Aprano  wrote:
> On Wed, 14 Jan 2009 02:25:52 -0800, codicedave wrote:
> > Hi all!
> > I installed a external program called infomap using the classical
> > procedure
>
> > ./configure
> > make
> > sudo make install
>
> >  and it works perfectly in Terminal (Os x) using both bash and tcsh
> > shell
>
> What happens when you call it using the sh shell (which is not
> necessarily aliased to bash)?
>
> [...]
>
> >  but when I call it from python using os.system or subprocess.call I
> > get the message "sh: infomap-build: command not found".
>
> > Do you know why?
>
> Possibly sh uses a different path to bash and can't find infomap-build.
>
> --
> Steven

in infocmpinfotocap  installer
indent infokeyinstallinstmodsh
indxbibinfomap-build  install-info   instruments
info   infomap-installinstall_name_tool
sh-3.2$ infomap-build

Usage: infomap-build [-w working_dir] [-p param_file]
   [-D var_1=val_1 ... -D var_N=val_N]
   (-s single_corpus_file | -m multi_file_list)
   

sh-3.2$

I am not able to figure out why..

any idea?

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


Re: os system command not found

2009-01-14 Thread Diez B. Roggisch
codicedave wrote:

> On 14 Gen, 13:16, Steven D'Aprano  cybersource.com.au> wrote:
>> On Wed, 14 Jan 2009 02:25:52 -0800, codicedave wrote:
>> > Hi all!
>> > I installed a external program called infomap using the classical
>> > procedure
>>
>> > ./configure
>> > make
>> > sudo make install
>>
>> > and it works perfectly in Terminal (Os x) using both bash and tcsh
>> > shell
>>
>> What happens when you call it using the sh shell (which is not
>> necessarily aliased to bash)?
>>
>> [...]
>>
>> > but when I call it from python using os.system or subprocess.call I
>> > get the message "sh: infomap-build: command not found".
>>
>> > Do you know why?
>>
>> Possibly sh uses a different path to bash and can't find infomap-build.
>>
>> --
>> Steven
> 
> in infocmpinfotocap  installer
> indent infokeyinstallinstmodsh
> indxbibinfomap-build  install-info   instruments
> info   infomap-installinstall_name_tool
> sh-3.2$ infomap-build
> 
> Usage: infomap-build [-w working_dir] [-p param_file]
>[-D var_1=val_1 ... -D var_N=val_N]
>(-s single_corpus_file | -m multi_file_list)
>
> 
> sh-3.2$
> 
> I am not able to figure out why..
> 
> any idea?

How about you give the full path to the executable? Might be that the PATH
isn't set correctly. If you installed the software by yourself, it is very
likely that it ended up in 

/usr/local/bin

instead of /usr/bin, and the former might not be part of the PATH-variable.

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


Re: initialising a class by name

2009-01-14 Thread Sion Arrowsmith
Krishnakant   wrote:
>By the way, is there a kind of global list of modules/classes which are
>maintained in a package once the program is loaded into memory?

sys.modules is a dict of loaded module objects, keyed by module name.
So:

>>> getattr(sys.modules["sys"], "version_info")
(2, 5, 0, 'final', 0)

-- 
\S -- si...@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
--
http://mail.python.org/mailman/listinfo/python-list


Twisted Trial - Framework for Test

2009-01-14 Thread wladimir

Hi,

Somebody have some tutorial or examples using Twisted Trial??

-- 
View this message in context: 
http://www.nabble.com/Twisted-Trial---Framework-for-Test-tp21456710p21456710.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: LGPL license for Qt 4.5

2009-01-14 Thread drobi...@gmail.com
On Jan 14, 7:57 am, sturlamolden  wrote:
> According to a Norwegian publication, Nokia will release Qt under LGPL
> as of version 4.5.
>
> If I had stocks in Riverbank Computing ltd., I would sell them now...
>
> For the rest of us, this is fantastic news.
>
> http://digi.no/php/art.php?id=800922

http://www.qtsoftware.com/about/licensing

Not sure what this means for PyQt
--
http://mail.python.org/mailman/listinfo/python-list


Re: LGPL license for Qt 4.5

2009-01-14 Thread sturlamolden
On Jan 14, 3:11 pm, "drobi...@gmail.com"  wrote:
> On Jan 14, 7:57 am, sturlamolden  wrote:
>
> > According to a Norwegian publication, Nokia will release Qt under LGPL
> > as of version 4.5.
>
> > If I had stocks in Riverbank Computing ltd., I would sell them now...
>
> > For the rest of us, this is fantastic news.
>
> >http://digi.no/php/art.php?id=800922
>
> http://www.qtsoftware.com/about/licensing
>
> Not sure what this means for PyQt

It means that:
- If Riverbank keep their dual GPL licensing scheme, somebody else
will make an LGPL 'QtPython' instead.
- If Riverbank change PyQt to LGPL, they will loose most of their
revenue form PyQt.

In either case, Qt will be available under the same licensing terms as
wxWidgets.

As of today, the main reason to prefer wxPython over PyQt is the
license. With an LGPL'd Qt, I'd rather ask what this will mean for
wxPython.











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


Re: Understanding search queries, semantics, and "Meaning" ...aren't we all looking for meaning?

2009-01-14 Thread Aahz
In article <82372457-2503-4682-96b3-37540328b...@w39g2000prb.googlegroups.com>,
 <5lvqbw...@sneakemail.com> wrote:
>
>I have Section 4.4.1 of SICP rattling around in my head (database
>queries), and I'm trying to come up with a simple dictionary-based
>database in Python to represent circuit diagrams.  My main confusion
>isn't one of implementation, but a matter of "big thinking",
>fundamentally, about the problem. Please don't suggest using a SQL
>library, as I'm looking to learn to fish, so to speak, and to learn a
>bit about the biology of fish.

Having read the rest of your conversation with Jonathan, I'm going to
suggest a related book that I think may help you approach this from a
different angle: _Mastering Regular Expressions_ by Jeffrey Friedl.  (I
haven't gone through SICP myself, so I can't be sure that it's relevant,
but it covers the topic of transforming search criteria into executable
statements -- and it will almost certainly be useful to you even if it's
not relevant to your current problem.)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
--
http://mail.python.org/mailman/listinfo/python-list


Re: os system command not found

2009-01-14 Thread Daniel da Silva
On Jan 14, 5:25 am, codicedave  wrote:
> Hi all!
> I installed a external program called infomap using the classical
> procedure
>
> ./configure
> make
> sudo make install
>
>  and it works perfectly in Terminal (Os x) using both bash and tcsh
> shell
>
> admins-macbook-pro-2:~ unil$ infomap-build
>
> Usage: infomap-build [-w working_dir] [-p param_file]
>        [-D var_1=val_1 ... -D var_N=val_N]
>        (-s single_corpus_file | -m multi_file_list)
>        
>
>  but when I call it from python using os.system or subprocess.call I
> get the message "sh: infomap-build: command not found".
>
> Do you know why?
>
> Many thanks
>
> Davide

Type "which infomap-build" from the command line to find out where
infomap-build is.
--
http://mail.python.org/mailman/listinfo/python-list


pyjamas 0.4p1 release

2009-01-14 Thread Luke Kenneth Casson Leighton
This is a minor patch release of pyjamas 0.4p1, the
Python-to-Javascript compiler and Python Web UI Widgets
Toolkit.

What is Pyjamas for?  Pyjamas allows a developer to create
U.I applications in python as if the Web Browser was a Desktop
Widget Set toolkit platform (like pygtk2, pywxWidgets and pyqt4,
only much simpler, and more powerful). No knowledge of javascript
programming is required: the python-to-javascript compiler
takes care of the conversion between python and javascript,
and the U.I widget set takes care of all the browser and AJAX
incompatibilities.

Why don't I find that exciting?  The significance of pyjamas
takes a while to sink in.  Or you're not a UI developer.
Or you've never been asked to write an identical app that
works on both the desktop and all major web browsers.
If you're a python developer who has followed the history
of web application development of the past decade, with
much frustration and disappointment, is overwhelmed
by Javascript, AJAX and the demands of the
"Web 2.00o0ooo0 Revverlushun", then Pyjamas is
something that you should consider investigating.

Pyjamas 0.4p1 Bug-fixes (and accidental Features)

Significant bugs fixed include HorizontalPanel's remove()
function, SimplePanel's clear() function, and sprintf
with multiple arguments ("%s %d" % ("hello", 2) will now
work)

Dialog Box now has modal functionality (thanks to jurgen
kartnaller).

HorizontalSplitPanel has been added, although both the
horizontal and vertical panels operate correctly on
Mozilla-based browsers, but Safari and IE need volunteers
to work on them.

Several more examples have also been added, including
a spreadsheet-like GridEdit example; a Transparent SVG
canvas clock widget (that actually tells the time); an
"Information Hierarchy" example that could be used as
the basis for an online cooperative spreadsheet editor;
Erik Westra's "Showcase" source code which provides
and shows the source of the 30 widgets being demo'd;
and a few other minor examples.

Discussion:
  http://groups.google.com/group/pyjamas-dev/

Bugs:
  http://code.google.com/p/pyjamas/issues/list

Downloads:
  https://sourceforge.net/project/showfiles.php?group_id=239074
  http://code.google.com/p/pyjamas/downloads/list

Web site:
  http://pyjs.org (pyjamas javascript compiler and UI widget set)
  http://pyjd.org (sister project, pyjamas-desktop)
--
http://mail.python.org/mailman/listinfo/python-list


Re: can someone tell me why this doesn't work please python 3

2009-01-14 Thread Gary M. Josack

garywood wrote:

def ask_ok(prompt, retries=4, complaint="Yes or no, please!"):
while True:
password = input("enter something")
if password in ('y', 'ye', 'yes'): return True
if password in ('n', 'no', 'nope'): return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print(complaint)


--
http://mail.python.org/mailman/listinfo/python-list
  
Well since you didn't give an error I'm going to assume your problems 
are as follows:

* Use raw_input() instead of input() # input evals the input received.
* pass prompt as the argument to raw_input so that your prompt gets set 
# might want to give prompt a default value

* password.lower() so Y, YE, YES, N, NO, NOPE also work for input
--
http://mail.python.org/mailman/listinfo/python-list


Re: can someone tell me why this doesn't work please python 3

2009-01-14 Thread Ben Kaplan



On Jan 14, 2009, at 9:44 AM, "Gary M. Josack"  wrote:


garywood wrote:

def ask_ok(prompt, retries=4, complaint="Yes or no, please!"):
   while True:
   password = input("enter something")
   if password in ('y', 'ye', 'yes'): return True
   if password in ('n', 'no', 'nope'): return False
   retries = retries - 1
   if retries < 0:
   raise IOError('refusenik user')
   print(complaint)
---
-

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

Well since you didn't give an error I'm going to assume your  
problems are as follows:

* Use raw_input() instead of input() # input evals the input received.
* pass prompt as the argument to raw_input so that your prompt gets  
set # might want to give prompt a default value

* password.lower() so Y, YE, YES, N, NO, NOPE also work for input
--
http://mail.python.org/mailman/listinfo/python-list


Did you miss the python 3 part? Raw_input was removed and input now  
behaves like raw_input did in 2.x

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


Re: can someone tell me why this doesn't work please python 3

2009-01-14 Thread Gary M. Josack

Ben Kaplan wrote:



On Jan 14, 2009, at 9:44 AM, "Gary M. Josack"  wrote:


garywood wrote:

def ask_ok(prompt, retries=4, complaint="Yes or no, please!"):
   while True:
   password = input("enter something")
   if password in ('y', 'ye', 'yes'): return True
   if password in ('n', 'no', 'nope'): return False
   retries = retries - 1
   if retries < 0:
   raise IOError('refusenik user')
   print(complaint)
---
-

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

Well since you didn't give an error I'm going to assume your problems 
are as follows:

* Use raw_input() instead of input() # input evals the input received.
* pass prompt as the argument to raw_input so that your prompt gets 
set # might want to give prompt a default value

* password.lower() so Y, YE, YES, N, NO, NOPE also work for input
--
http://mail.python.org/mailman/listinfo/python-list


Did you miss the python 3 part? Raw_input was removed and input now 
behaves like raw_input did in 2.x
Ah, yes. Subject got truncated on my little laptop screen. Either way, 
more information is needed to diagnose the problem.

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


Re: Why this code is working?

2009-01-14 Thread Bruno Desthuilliers

Hussein B a écrit :

On Jan 14, 11:55 am, Bruno Desthuilliers  wrote:

Hussein B a écrit :


Hey,
Why this code is working?

def f1( ):

...  x = 88
...  f2(x)
...

def f2(x):

...  print x
...

f1( )

88

Well... Because it is correct ?

What make you think it _shouldn't_ work ?


Because def2 is defined after def1 in an interpreted language, not
compiled.


CPython actually compiles to byte-code, which is then executed.

But anyway: even if it was fully interpreted, the fact that f2 is 
defined after f1 should not matter - what matters is that name f2 exists 
(and is bound to a callable taking a single mandatory argument) when f1 
is actually _called_.


>>> def f1():
... x = 42
... f2(x)
...
>>> f1()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in f1
NameError: global name 'f2' is not defined
>>> def f2(x):
... print x
...
>>> f1()
42
>>> def f2(x):
... print "pikaboo"
...
>>> f1()
pikaboo
>>>
>>> del f2
>>> f1()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in f1
NameError: global name 'f2' is not defined
>>>

HTH



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


Re: Why this code is working?

2009-01-14 Thread Bruno Desthuilliers

Hussein B a écrit :

On Jan 14, 2:21 pm, Steven D'Aprano  wrote:

On Wed, 14 Jan 2009 01:57:48 -0800, Hussein B wrote:

Well... Because it is correct ?
What make you think it _shouldn't_ work ?

Because def2 is defined after def1 in an interpreted language, not
compiled.

Python is compiled.


(snip)
>

Yes I know Python programs can be compiled


wrt/ CPython: s/can be/are/


but when I do:
python Script1.py
Did Python compile Script1 into the memory?


Yes. Only (imported) modules are automatically saved as .pyc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: are there some special about '\x1a' symbol

2009-01-14 Thread Mel
Steve Holden wrote:
> Unknown wrote:
>> On 2009-01-12, John Machin  wrote:
>>> I didn't think your question was stupid. Stupid was (a) CP/M recording
>>> file size as number of 128-byte sectors, forcing the use of an in-band
>>> EOF marker for text files (b) MS continuing to regard Ctrl-Z as an EOF
>>> decades after people stopped writing Ctrl-Z at the end of text files.

>> I believe that "feature" was inherited by CP/M from DEC OSes
>> (RSX-11 or RSTS-11). AFAICT, all of CP/M's file I/O API
>> (including the FCB) was lifted almost directly from DEC's
>> PDP-11 stuff, which probably copied it from PDP-8 stuff.
>> Perhaps in the early 60's somebody at DEC had a reason.  The
>> really interesting thing is that we're still suffering because
>> of it 40+ years later.

> I suspect this is probably a leftover from some paper tape data formats,
> when it was easier to detect the end of a file with a sentinel byte than
> it was to detect run-off as end of file. It could easily date back to
> the PDP-8.

Perhaps, although in ASCII it's the SUB symbol: "A control character that is
used in the place of a character that is recognized to be invalid or in
error or that cannot be represented on a given device." [Wikipedia].  There
were other codes defined for End-of-Text and File-Separator.  Unless the
protocol were one of DEC's own.  The fact that it's
Ctrl-last-letter-of-the-alphabet makes me suspect that it was picked in a
pretty informal way.

Mel.

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


Re: can someone tell me why this doesn't work please python 3

2009-01-14 Thread Michael Hartl

garywood schrieb:

def ask_ok(prompt, retries=4, complaint="Yes or no, please!"):
while True:
password = input("enter something")
if password in ('y', 'ye', 'yes'): return True
if password in ('n', 'no', 'nope'): return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print(complaint)


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

What's your problem, anyway? It seems to work perfectly fine, except that
you ignore the prompt variable.
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialising a class by name

2009-01-14 Thread Nick Craig-Wood
Krishnakant  wrote:
>  I liked this idea of dispatchTable.
>  is it possible to say some thing like 
>  inst = dispatchTable{"ham"}
>  according to me, inst will become the instance of class ham.
>  Another thing to note is that all the classes are in different modules.
>  So where do I create the dict of classes mapped with the name?

You could use a metaclass which will get round the problem, provided
all the classes have a common baseclass, eg

class BaseThing(object):
registry = {}
class __metaclass__(type):
def __init__(cls, name, bases, dict):
cls.registry[cls.__name__] = cls

class ThingOne(BaseThing):
pass

class ThingTwo(BaseThing):
pass

class ThingThree(BaseThing):
pass

print BaseThing.registry["ThingOne"]
print BaseThing.registry["ThingTwo"]
print BaseThing.registry["ThingThree"]

Which prints





-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb LIKE '%%%s%%' problem

2009-01-14 Thread Marco Mariani

Steve Holden wrote:


3. I can't be certain my experience with PostgreSQL extends to MySQl,
but I have done experiments which prove to my satisfaction that it isn't
possible to parameterize LIKE arguments. So the only way to do it
appears to be to build the query yourself.


Or using Postgres through SQLAlchemy.

Actually, the only thing SQLAlchemy cannot do (yet) is withstand a 
zombie army.

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Paul Rubin
Bruno Desthuilliers  writes:
> > If the programmer could
> > somehow disallow it in certain classes,
> 
> Already possible - you just have to provide your own implementation of
> __setattr__.

Part of the idea of non-dynamic attribute sets is to make the program
run faster, not slower.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Luis Zarrabeitia
On Wednesday 14 January 2009 02:22:45 am Paul Rubin wrote:
> 2. There is also nothing inherent in a dynamic OO language that says
> that class descriptors have to be mutable, any more than strings have
> to be mutable (Python has immutable strings).  I agree that being able
> to modify class descriptors at runtime is sometimes very useful.  The
> feature shouldn't be eliminated from Python or else it wouldn't be
> Python any more.  But those occasions are rare enough that having to
> enable the feature by saying (e.g.) "@dynamic" before the class
> definition doesn't seem like a problem, both for encapsulation

Why don't you do it backwards?
You *can* implement a metaclass that will remove the dynasmism from its 
instances. Do it - I can give you a starting point if you wish.

But most of us are very happy with the dynamic nature of python... I chose 
python _because_ of it.

> and because it can also improve performance.

Btw, for performance, there is __slots__, with the side-effect that it forbids 
attribute creation 'on the fly'.

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Mel
Russ P. wrote:

> On Jan 13, 11:40 pm, Steven D'Aprano
>  wrote:
> 
>> But, gosh darn it, wouldn't it be nice to program the critical parts of
>> your code in "strict Python", and leave the rest as "trusting Python",
>> instead of having to use Java for the lot just to get strictness in the
>> critical parts? If only there was a way to do this, and ensure people
>> won't abuse it.
> 
> Yes, that would indeed be nice. I am certainly not the only one who
> could use a language that is excellent for both research prototyping
> *and* the final, safety-critical system. Then perhaps the prototype
> could just be cleaned up and "hardened" for the end product rather
> than rewritten in another language -- by programmers in another state
> who may fail to understand many of the details that the prototype
> developer agonized over.

You might have a look at Business Shell 
which is based on Ada.

Mel.

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-14 Thread Luis Zarrabeitia
On Tuesday 13 January 2009 09:57:04 pm Terry Reedy wrote:
> Russ P. wrote:
> public = no leading underscore
> private = one leading underscore
> protected = two leading underscores

Aren't the last two reversed?

protected = one leading underscore 
[both you and your subclasses should access it]
private = two leading underscores   (name munging) 
[only you should access - implementation detail.]

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >