Re: Why Doesn't XP Pro Show Size, Time and Date Mod of a Created File?

2009-12-08 Thread Gerhard Häring
W. eWatson wrote:
> I created a folder, and wrote a file to it. When I look at what files
> are in it, they are correct. However, The Size, Type, and Date Mod are
> not shown. Why am I missing those columns? I'm writing files with a
> suffix of dat, which seem only to match up with video CD movie.

That's probably a Windows Explorer thing. The column may be hidden or
moved away to the far right.

As far as Python is concerned, you can fetch this kind of information
with the stat() function of the os module.

import os, time
stat_info = os.stat("x")
print "size:", stat_info.st_size
print "modification time:", time.strftime("%Y-%m-%d %H:%M",
time.localtime(stat_info.st_mtime))

-- Gerhard

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


Re: Graph library for Python

2009-12-08 Thread geremy condra
On Mon, Dec 7, 2009 at 11:28 PM, geremy condra  wrote:
> On Mon, Dec 7, 2009 at 6:28 PM, M.-A. Lemburg  wrote:
>> geremy condra wrote:
>>> On Mon, Dec 7, 2009 at 2:51 PM, M.-A. Lemburg  wrote:
 geremy condra wrote:
> How interested are you in a C port of graphine? I haven't had
> any specific requests for it, but if its something you need I
> can shuffle it towards the top of the to do pile.

 There are two main reasons for a C implementation:

  1. performance

  2. memory footprint

 These are important when using graphs with lots of nodes or
 when using lots of graphs or operations on graphs in tight
 loops.

 However, to get such a new type into the core, you need to start
 a PEP process and hash out the API some more, esp. with respect
 to integration with the other core types, such as dictionaries
 and lists of tuples for both creation and as alternative
 representation.
>>>
>>> I'm happy to start the PEP process, but will need some
>>> guidance, as I've never written a PEP before.
>>
>> Some pointers to get you started:
>>
>> PEPs in general:
>> http://www.python.org/dev/peps/pep-0001/
>> http://www.python.org/dev/peps/pep-0009/
>>
>> Adding modules to the standard lib:
>> http://www.python.org/dev/peps/pep-0002/
>>
>> (though, in reality, you'd probably only be patching the
>> collections.py module, I guess)
>
> Thanks, I'll go over these a little later.
>
 Some other comments (in no particular order):

  * the "name" default of using id(node) is not ideal, since
   id(node) will return the address of the object and that
   can be subject to reuse within the lifetime of the process;
   using a global (thread-safe) counter would be safer
>>>
>>> Good idea. I'm going to start a branch on the repo to
>>> handle the changes you mention.
>>>
  * Graph.__init__ should be able to take a list or set
   of nodes and edges as initializer
>>>
>>> The format of this will need to be thought all the way
>>> through before being implemented. To date, we haven't
>>> come up with anything completely satisfactory, but
>>> AFAIK everybody involved is still open to suggestions
>>> on this.
>>
>> I wasn't thinking of anything clever :-) ...
>>
>> g = Graph(
>>      [Node("a"), Node("b"), Node("c")],
>>      [Edge(Node("a"), Node("b"), "ab"),
>>       Edge(Node("a"), Node("c"), "ac"),
>>       Edge(Node("b"), Node("c"), "bc"),
>>      ])
>>
>> The main motivation here is to get lists, sets and dicts
>> play nice together.
>
> Generally, we've tried to discourage people from instantiating
> nodes and edges directly, in favor of having them controlled
> through the graph. Maybe something along the lines of:
>
> g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b', 'c')])
>
> ?
>
  * Graph.__setitem__ could be mapped to .add_node() for
   convenience
>>>
>>> This may be a question of playing around with it. ATM I'm
>>> not sold on the idea, but I'll implement it and see how it
>>> turns out in practice.
>>
>> Thinking about it some more, I agree, it's not all that useful.
>>
  * Graph.__length__ could be mapped to .size() for
   convenience
>>>
>>> We decided not to do this due to the ambiguity between
>>> whether .size() or .order() was the intended operation,
>>> and looking back I'm not sure that was entirely unjustified.
>>> Do you see there being any confusion on that score?
>>
>> There is an ambiguity here, indeed. My thinking was that
>> the edges define the graph and can be mapped to a dictionary,
>> e.g.
>>
>> d = {"ab": ("a", "b"),
>>     "ac": ("a", "c"),
>>     "bc": ("b", "c")}
>>
>> len(d) == 3
>> len(g) == 3
>>
>> A graph without edges is also what you typically call an empty
>> graph, ie.
>>
>> if not g:
>>    print 'empty'
>>
>> http://mathworld.wolfram.com/EmptyGraph.html
>>
>> Still, perhaps it's better to just not go down this route.
>
> I'd rather avoid it if possible, since there are many
> potential interpretations of this in different contexts.
> Again, I'm open to to the idea, but not convinced.
>
  * Graph.__iter__ could be mapped to an iterator using
   the fastest traversal method for the graph nodes
   (ie. order does not matter, it's only important that
   all nodes are found as fast as possible)
>>>
>>> Again, it seems ambiguous as to whether nodes or
>>> edges are the intended target here, and while the
>>> API can obviously dictate that, it seems a bit like
>>> a case of "in the face of ambiguity, refuse the
>>> temptation to guess" to me.
>>
>> Right, but sometimes "practicalty beats purity" ;-) We had
>> the same situation for dictionaries and then decided that
>> iteration over keys would be more natural than iterating over
>> items (key, value) or values.
>>
>> It's also important to note that:
>>
>>        for n in g: print n
>>
>> and
>>
>>        n in g
>>
>> match up in terms of semantics.
>>
>> Since n in g already uses the 

Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread John Machin
On Dec 8, 6:56 pm, Dennis Lee Bieber  wrote:
> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old 
> declaimed the following in gmane.comp.python.general:
>
> > For Kannada project .txt(not .doc) is used, my requirement is to have one
> > space between two characters in Notepad file.  In MSword there is provision
> > to make space between two characters under "Font" and  can be saved as *.doc
> > *  But when tried to save as* .txt*  all formatting will disappear. I could
> > not understand how to do in notepad. Even tried copy and paste from doc to
> > notepad but failed.
>
> > In this context, I request you kindly for small python program - to make or
>
>         Excuse me -- you want one of US to supply you with a program that
> will be used for YOUR entry to some job site? (At least, that's what I
> seem to be finding for "Kannada project")

http://en.wikipedia.org/wiki/Kannada_script

I think "project" means any piece of software ...

>
> > insert space between two characters in the text file.
>
>         How difficult is it to read a file character by character, and write
> a file containing that character and a space?

Perhaps there are some subtleties of which we are unaware ...

I would be very surprised if the OP could not find on a forum much
closer to home more people who know more about using Indic scripts on
computers than here.
-- 
http://mail.python.org/mailman/listinfo/python-list


whitespace in xml output

2009-12-08 Thread wadi wadi
Hi all,

I am creating some xml output using minidom and saving it to a file using
doc.writexml()
The output however is as follows:




bill catman




Is there a way to save xml output in a file such as xml is formatted the
right way? I mean with the right indentation and the elements values with no
white spaces?



  bill catman



Thanks for your help.
WN
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert string function to string method?

2009-12-08 Thread Bruno Desthuilliers

Dr. Phillip M. Feldman a écrit :

Bruno- You've made some excellent suggestions, and I'm always grateful for
the opportunity to learn.


Glad to know I've been of any help !-)


 My revised code appears below.  Philllip

def strip_pairs(s, open='([{\'"', close=')]}\'"'):
   """
   OVERVIEW

   This function strips matching pairs of characters from the beginning and
   end of the input string `s`.  If `s` begins with a character in `open`
and
   ends with the corresponding character in `close` (see below), both are
   removed from the string. This process continues until no further matching
   pairs can be removed.

   INPUTS

   `open` and `close`: These arguments, which must be equal-length strings,
   specify matching start-of-scope and end-of-scope characters.  The same
   character may appear in both `open` and `close`; single and double quotes
   conventionally match themselves.  By default, `open` contains a left
   parenthesis, left square bracket, left curly bracket, single quote, and
   double quote), and `close` contains the corresponding characters."""

   if not isinstance(s,(str,unicode)):
  raise TypeError, '`s` must be a string (str or unicode).'


Might be a bit more helpful (for the programmer using your function) to 
specify what 's' actually is. Also, the recommanded way to raise 
exceptions is to use the 'call' syntax, ie:



if not isinstance(s,(str,unicode)):
   raise TypeError("'s' must be a str or unicode, got '%s'" % type(s))



   if not isinstance(open,(str,unicode)) or not
isinstance(close,(str,unicode)):
  raise TypeError, '`open` and `close` must be strings (str or
unicode).'


Mmmm I still wonder why you wouldn't accept a tuple or list of chars 
here.



   if len(open) != len(close): raise ValueError, \
 '\'open\' and \'close\' arguments must be equal-length strings.'

   while len(s) >= 2:

  # Check whether first character of `s` is in `open`:
  i= open.find(s[0])

  # If `s` does not begin with a character from `open`, there are no
more
  # pairs to be stripped:
  if i == -1: break


wrt/ readability, it might be better to put the break statement on it's 
own line - but you can probably count this one as more of a personnal 
preference than a guideline !-)



  # If `s` does not begin and end with matching characters, there are no
  # more pairs to be stripped:
  if s[-1] != close[i]: break

  # Strip the first and last character from `s`:
  s= s[1:-1]
   return s





Steven (D'Aprano) posted a possibly interesting implementation. Might be 
worth timeit'ing both.



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


Upcoming Python Classes in New York

2009-12-08 Thread Steve Holden
Holden Web is pleased to announce three upcoming classes in New York
city the week of January 18.

Jan 18-20Introduction to Python (3 days) - Steve Holden
http://holdenweb.com/py/introclass/

Jan 21 .NET: IronPython from the Ground Up (1 day) - Michael Foord
http://holdenweb.com/py/ironpython/

Jan 22 Practical Django Skills (1 day) - Jacob Kaplan-Moss
http://holdenweb.com/py/practicaldjango/

Our current course offerings are always listed at

  http:/holdenweb.com/py/training/

We also present on-site and/or custom classes - please contact us for
further information.

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


Re: whitespace in xml output

2009-12-08 Thread Lutz Horn
Hi,

wadi wadi  wrote:
> I am creating some xml output using minidom and saving it to a file
> using doc.writexml()

Could you please add some code of *how* you add the content "bill
catman" to the "Author" element? It seems as if whitespace is an issue
here.

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


Re: How decoupled are the Python frameworks?

2009-12-08 Thread Martin Sand Christensen
J Kenneth King  writes:
> [...] (though it sounds like cherrypy would be very good at separating
> dispatching from application code).

True. In CherryPy, each page is represented by one method (the 'default'
method is an exception, but that's not for this discussion). This method
is expected to return a string representing the page/resource that the
user requested. At this simple level, CherryPy can be considered more or
less just a HTTP server and dispatcher.

However, we all know that this isn't where it ends. When we want to
handle cookies, we need framework-specific code. When we want to return
something other than HTML, we need framework-specific code. The list
goes on.

However, with a reasonable coding style, it can be quite practical to
separate strict application code from the framework-specific code. Here
the one-method,-one-page principle is a great help. For instance, we
quite often use decorators for such things as authentication and role
checking, which is both very practical and technically elegant. For
instance, if a user must have a CAS single sign-on identity AND, say,
the administrator role, we'd do as follows:

@cas
@role('administrator')
def protectedpage(self, ...):
# stuff

If the user isn't currently signed in to our CAS, he'll be redirected to
the sign-in page and, after signing in, is returned to the page he
originally requested. The role decorator checks his privileges (based on
his CAS credentials) and either allows or denies him access. This adds
up to a LOT of framework-specific code that's been very easily factored
out. The CAS and role modules behind the decorators are, in turn,
generic frameworks that we've merely specialised for CherryPy. At some
point we'll get around to releasing some code. :-)

As a slight aside, allow me to recommend Meld3 as a good templating
library. It's basically ElementTree with a lot of practical templating
stuff on top, so it's not a mini-language unto itself, and you don't
embed your code in the page.

-- 
Martin Sand Christensen
IT Services, Dept. of Electronic Systems
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread steve


On 12/08/2009 02:19 PM, John Machin wrote:

[...snip...]

Perhaps there are some subtleties of which we are unaware ...

I would be very surprised if the OP could not find on a forum much
closer to home more people who know more about using Indic scripts on
computers than here.


That's true. I'd recommend that the original poster, posts the query at the 
bangalore python user group mailing list:


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

...alongwith some additional details of the requirements. I am sure they 
wouldn't mind reading and replying to the question in kannada itself.


After all Kannada is the language of the sate of Karnataka, of which Bangalore 
(or Bengaluru as it is known these days) is the capital city.


cheers,
- steve
--
random non tech spiel: http://lonetwin.blogspot.com/
tech randomness: http://lonehacks.blogspot.com/
what i'm stumbling into: http://lonetwin.stumbleupon.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread 74yrs old
Steve,
Thanks for the recommendation. In fact, I was not aware of Bangalore Python
User Group till I received your email.  I am very much thankful to you Sir,
With Regards,
-sriranga(77yrsold)

On Tue, Dec 8, 2009 at 4:12 PM, steve  wrote:

>
> On 12/08/2009 02:19 PM, John Machin wrote:
>
>> [...snip...]
>>>
>> Perhaps there are some subtleties of which we are unaware ...
>>
>> I would be very surprised if the OP could not find on a forum much
>> closer to home more people who know more about using Indic scripts on
>> computers than here.
>>
>
> That's true. I'd recommend that the original poster, posts the query at the
> bangalore python user group mailing list:
>
> http://mail.python.org/mailman/listinfo/bangpypers
>
> ...alongwith some additional details of the requirements. I am sure they
> wouldn't mind reading and replying to the question in kannada itself.
>
> After all Kannada is the language of the sate of Karnataka, of which
> Bangalore (or Bengaluru as it is known these days) is the capital city.
>
> cheers,
> - steve
> --
> random non tech spiel: http://lonetwin.blogspot.com/
> tech randomness: http://lonehacks.blogspot.com/
> what i'm stumbling into: http://lonetwin.stumbleupon.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How decoupled are the Python frameworks?

2009-12-08 Thread Lie Ryan

On 12/8/2009 9:11 PM, Martin Sand Christensen wrote:

If the user isn't currently signed in to our CAS, he'll be redirected to
the sign-in page and, after signing in, is returned to the page he
originally requested. The role decorator checks his privileges (based on
his CAS credentials) and either allows or denies him access. This adds
up to a LOT of framework-specific code that's been very easily factored
out. The CAS and role modules behind the decorators are, in turn,
generic frameworks that we've merely specialised for CherryPy. At some
point we'll get around to releasing some code. :-)


In the end, it is the developer's responsibility not to write something 
too tightly coupled with their framework, isn't it?

(or at least to minimize the framework-specific code to a certain area)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How decoupled are the Python frameworks?

2009-12-08 Thread Diez B. Roggisch
shocks wrote:

> Hi
> 
> I'm getting back into Python after a long break.  I've been developing
> large enterprise apps solely with Adobe Flex (ActionScript) for the
> past couple years.  During that time I've used a number of 'MVC'
> frameworks to glue the bits together - among them Cairngorm, a
> modified implementation of Cairngorm using the Presentation Model
> pattern, PureMVC, Mate (an IOC container but with an MVC
> implementation) and Parsley (IOC but you have to roll-you-own MVC).
> During that time I've been in large teams (30 Flex + 30 Java) to small
> teams (2 Flex + 1 Java).  The motivation of these frameworks is the
> decouple your concerns, allowing your apps to be more scalable, easier
> to test, and  supposedly easier to maintain.  Some do the decoupling
> better job than others, but there is also the question of "how
> decoupled is your code from the framework"?  It's all well and good
> having something clever working behind the scenes wiring and routing
> everything together, but I wonder where this leaves the code base if
> the framework, which was selected at the beginning of the project, is
> replaced with something else months or years later (i.e. the framework
> just doesn't scale as expected, the community involvement dies and
> it's no longer maintained properly, etc).  I've seen it happen and
> I've been experienced the pain of detangling massive amounts of code
> which is full of framework specific imports, methods and boilerplate
> code.  And then there's updating the unit tests!
> 
> My question is how good are the current crop of Python frameworks?
> I've used Django twice in production and didn't like that much.  The
> implementation is Django specific for starters.  I've picked up Pylons
> and I'm trying that out.  I'm not sure how well it fares?  I do feel a
> bit uneasy about the code generation that some of the Python
> frameworks do.  Pylons creates something like 20 files for a
> 'helloworld'.  It does do some great things out of the box, but I
> wonder where that leaves your own code.  After spending 3-6 months on
> your Pylons webapp, how easy is it to move to something else?  Maybe
> one of the Python IOC once they mature.  What are some good techniques
> people are using to future (framework) proof their apps?
> 
> I'm interested to hear people experiences with the various frameworks
> and how decoupled their code is from them.  The best of the current
> Flex frameworks for me is Parsley.  The only noticeable Parlsey code
> is an '[Inject]' meta tag here and there and a couple import
> statements.  All the complicated object creation and messaging is done
> higher up the chain.

I think the Pylons and maybe even TurboGears2 stack are pretty good
regarding decoupling. This stems from them bundling "best-of-breed"
solutions for e.g. ORM (SQLAlchemy), session-handling, HTML-widgets,
templating and so forth together. So in theory, and to a large extend in
practice, you can rip out individual components and replace them with ones
you prefer, and of course this overall design makes things more decoupled.

*However* there is only so much a framework can and does do when it's
supposed to stay out of your way. I for one think that e.g. the
repoze.who/what stack is an example of an over-generalization that leads to
much more hassle than it's worth it, all for the alledged advantages of
total decoupling and pluggability.

Mark Christensen wrote a blog-post about the whole coupling/de-coupling
issue:

http://compoundthinking.com/blog/index.php/2009/11/28/coupling-django-style/

Essentially, getting things *done* now is very important, and making
developers permanently jump through hoops just so they avoid coupling leads
eventually to something that is your own webframework - without the benefit
of participating on evolution of a common one that occasionally forces you
to adapt.

Diez


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


Re: How decoupled are the Python frameworks?

2009-12-08 Thread Martin Sand Christensen
Lie Ryan  writes:

> In the end, it is the developer's responsibility not to write
> something too tightly coupled with their framework, isn't it? (or at
> least to minimize the framework-specific code to a certain area)

That's a good summary of my point. However, I have very little
experience with other frameworks than CherryPy, so I do not want to draw
any general conclusions. My programmer's instincts say that it's true,
though.

-- 
Martin Sand Christensen
IT Services, Dept. of Electronic Systems
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Duplicates of third-party libraries

2009-12-08 Thread Lie Ryan

On 12/8/2009 3:25 PM, Martin P. Hellwig wrote:

Ben Finney wrote:

"Martin P. Hellwig"  writes:




Along with the duplication this introduces, it also means that any bug
fixes — even severe security fixes — in the third-party code will not be
addressed in your duplicate.


I disagree, what you need is:
- An automated build system for your deliveries, something you should
have anyway
- An method of tracking versions of your dependencies, again something
you should have anyway
- And a policy that you incorporate bug fixes from your dependencies in
your deliveries, something you should do anyway if you are serious about
your product.


I disagree, what you should have is an Operating System with a package 
management system that addresses those issues. The package management 
must update your software and your dependencies, and keep track of 
incompatibilities between you and your dependencies.


The package management systems have in many popular Linux distro is 
close to it. The point is, those issues should not be your issue in the 
first place; the OS is the one in charge of coordination between 
multiple software (or else why would we have an OS for?).


In the Windows\b\b\b\b\b\b\b Real world, some OS let off *their 
responsibility* and told their users to manage dependency by their own. 
Obviously most users don't have the knowledge to do so, and the undue 
burden then goes to software developers. A software ideally shouldn't 
need to care about how the machine is configured ("Separation of Concern").


I never liked the idea of each software to have its own software 
updater, they are sign of bloated software. There should ideally be one 
software updater in the system ("Don't Repeat Yourself"). Many automatic 
updater by big companies is configured to run on computer startup and 
doesn't shutdown without an order from the Task Manager. They then 
reinstall their autorun entry in the registry when the user deletes 
them, trying to outsmart the user since they think the user is just 
ain't smart enough.


In my Windows computer, the only software I give my blessing to 
auto-update is the antivirus; anything else just bloats the system. A 
good-behaviored software would just notify me about update (e.g. 
OpenOffice and Pidgin), and even then only when I'm using the software 
(not every time you open your computer).


I'm glad I don't have such chaos when using my Gentoo or Ubuntu, the 
system software updater handles all those just fine.

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


Re: Graph library for Python

2009-12-08 Thread Robin Becker

geremy condra wrote:
...


I don't have a problem with adding this if there's a strong desire for it,
but at the moment I'm leaning towards a wait-and-see approach, for
all the reasons you described.

Geremy Condra


I don't want to sound pessimistic, but graph and digraph theory has a lot of 
history, especially in computer science. There are already very many 
implementations eg


http://code.google.com/p/igraph
http://www.boost.org/doc/libs/release/libs/graph
http://ernst-schroeder.uni.lu/Digraph/doc/
http://code.google.com/p/python-graph
http://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph-module.html

and many others..some of the above already seem to be very useful.

Is there reason to suppose that any one representation of graphs or digraphs is 
so good we need to add it to python?


Even for fairly common algorithms eg Dijkstra's shortest path there doesn't seem 
to be complete agreement on how to implement them; for the details of how 
nodes/edges/paths should be stored and efficiently manipulated there is huge 
variety.


Wait seems like a good policy.
--
Robin Becker

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


Re: Duplicates of third-party libraries

2009-12-08 Thread Martin P. Hellwig

Lie Ryan wrote:


Yes from an argumentative perspective you are right.
But given the choice of being right and alienate the fast majority of my 
potential user base, I rather be wrong.


For me the 'Although practicality beats purity' is more important than 
trying to beat a dead horse that is a platform independent package 
manager actively supported by all mayor operating systems.


But hey if it works for you, great!

--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread John Machin
On Dec 8, 9:42 pm, steve  wrote:
> On 12/08/2009 02:19 PM, John Machin wrote:
>
> >> [...snip...]
> > Perhaps there are some subtleties of which we are unaware ...
>
> > I would be very surprised if the OP could not find on a forum much
> > closer to home more people who know more about using Indic scripts on
> > computers than here.
>
> That's true. I'd recommend that the original poster, posts the query at the
> bangalore python user group mailing list:
>
> http://mail.python.org/mailman/listinfo/bangpypers
>
> ...alongwith some additional details of the requirements. I am sure they
> wouldn't mind reading and replying to the question in kannada itself.
>
> After all Kannada is the language of the sate of Karnataka, of which Bangalore
> (or Bengaluru as it is known these days) is the capital city.

Off-list, I've already solicited assistance for the OP from a
prominent bangpyper.

Cheers,
John


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


Re: Duplicates of third-party libraries

2009-12-08 Thread David Cournapeau
On Tue, Dec 8, 2009 at 9:02 PM, Lie Ryan  wrote:

>
> I disagree, what you should have is an Operating System with a package
> management system that addresses those issues. The package management must
> update your software and your dependencies, and keep track of
> incompatibilities between you and your dependencies.

This has many problems as well: you cannot install/update softwares
without being root, there are problems when you don't have the right
version, when the library/code is not packaged, etc... Don't get me
wrong, I am glad that things like debian, rpm exist, but it is no
panacea. There are simply no silver bullet to the deployment problem,
and difference cases/user target may require different solutions.

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


Re: python proxy checker ,change to threaded version

2009-12-08 Thread Lie Ryan

On 12/8/2009 8:43 AM, Rhodri James wrote:


def run(self):
result = func(*func_args) # matching run_in_thread param names
callback(result, *callback_args)

Neat, but I think you mean

if callback is not None:
callback(result, *callback_args)

for that last line.


how about:
import threading

def run_in_thread( func, func_args=[], callback=lambda r,*a: None, 
callback_args=[] ):

class MyThread ( threading.Thread ):
def run ( self ):
result = func(*func_args)
callback(result, *callback_args)
MyThread().start()


(and for me, I'd )
--
http://mail.python.org/mailman/listinfo/python-list


Re: IO Gurus: what are the differences between these two methods?

2009-12-08 Thread Ulrich Eckhardt
dpapathanasiou wrote:
> I have two methods for writing binaries files: the first works with
> data received by a server corresponding to a file upload, and the
> second works with data sent as email attachments.

Hmmm, no. Looking at your code, the first of your functions actually treats
its argument as a stream, while the second one treats it like a byte buffer
(as str object, to be precise).

> The odd thing is, they're not interchangeable: if I use the first one
> to saved data parsed from an email attachment, it fails; similarly,
> the second function fails when dealing with an uploaded file data.

There is nothing odd about that, they are different functions working with
different things.

> What are the critical differences?
> 
> def write_binary_file (folder, filename, f, chunk_size=4096):
[...]
> for file_chunk in read_buffer(f, chunk_size):
> file_obj.write(file_chunk)
[...]
> def write_binary_file (folder, filename, filedata):
[...]
> file_obj.write(filedata)

BTW: You could have reduced the code yourself before posting. You might have
seen the difference yourself then! Further, I'm curious, do you have any
non-binary files anywhere? =)

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread r0g
Dennis Lee Bieber wrote:
> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old 
> declaimed the following in gmane.comp.python.general:
> 
>> For Kannada project .txt(not .doc) is used, my requirement is to have one

>> In this context, I request you kindly for small python program - to make or
> 
>   Excuse me -- you want one of US to supply you with a program that
> will be used for YOUR entry to some job site? (At least, that's what I
> seem to be finding for "Kannada project")
> 


Well it is only a 2 line program and he did ask nicely after all, if you
begrudge him it then feel free to not answer, righteous indignation
rarely helps anyone.

Dear OP...

Put the following 2 lines into a file and save it as spacer.py

import sys
print ' '.join([e for e in open(sys.argv[1], 'r').read()])


Then open a terminal window and 'cd' to the same folder you just saved
the spacer.py file in. Type...

python spacer.py inputfile.txt > outputfile.txt

This will run inputfile.txt through the space adding program we have
just saved and then 'pipe' the output of that into a new file outputfile.txt

Hope this helps,


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


Re: Duplicates of third-party libraries

2009-12-08 Thread Lie Ryan

On 12/9/2009 12:02 AM, David Cournapeau wrote:

On Tue, Dec 8, 2009 at 9:02 PM, Lie Ryan  wrote:


I disagree, what you should have is an Operating System with a package
management system that addresses those issues. The package management must
update your software and your dependencies, and keep track of
incompatibilities between you and your dependencies.


This has many problems as well: you cannot install/update softwares
without being root,


A package manager with setuid, though dangerous, can run without being 
root. Some package manager (e.g. Gentoo's Portage w/ prefix) allow user 
to set to install in a non-default directory (one that doesn't require 
root access).



there are problems when you don't have the right version,


That's the whole point of package management system! A package 
management system are not just plain software installers (like MSI and 
NSIS), they go beyond and figure out the "right version" of your 
dependencies.


In many package management system, bleeding edge packages are run by 
testers that will figure out the dependency your software requires. If 
you are nice (it is your responsibility anyway), you can save them some 
work by telling them the dependency version you've tested your software 
with.


> when the library/code is not packaged, etc...

Don't worry, the majority of users are willing to wait a few weeks until 
the library/code gets packaged. Some even _refuses_ to use anything 
younger than a couple of years.


> Don't get me wrong, I am glad that things like debian, rpm exist,
> but it is no panacea

They're not; but software developers should maximize functionality 
provided by package managers rather than trying to build their own 
ad-hoc updater and dependency manager.


> There are simply no silver bullet to the
> deployment problem, and difference cases/user target may require
> different solutions.

The only thing that package managers couldn't provide is for the 
extremist bleeding edge; those that want the latest and the greatest in 
the first few seconds the developers releases them. The majority of 
users don't fall into that category, most users are willing to wait a 
few weeks to let all the just-released bugs sorted out and wait till the 
package (and their dependencies) stabilize.

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


Re: Graph library for Python

2009-12-08 Thread Steven D'Aprano
On Tue, 08 Dec 2009 03:06:29 -0500, geremy condra wrote:

[snip 215 lines of quoted-quoted-quoted-quoted-quoted text]

In the future, would you mind trimming the unneeded quoting from your 
post? There's no need to duplicate the *entire* conversation in *every* 
post, and it is awfully AOL-like of you to have 215 lines of text, with 
up to five levels of quotation, followed by two lines of new content.

Thank you.


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


Re: python proxy checker ,change to threaded version

2009-12-08 Thread r0g
Lie Ryan wrote:
> On 12/8/2009 8:43 AM, Rhodri James wrote:
>>>
>>> def run(self):
>>> result = func(*func_args) # matching run_in_thread param names
>>> callback(result, *callback_args)
>> Neat, but I think you mean
>>
>> if callback is not None:
>> callback(result, *callback_args)
>>
>> for that last line.
> 
> how about:
> import threading
> 
> def run_in_thread( func, func_args=[], callback=lambda r,*a: None,
> callback_args=[] ):
> class MyThread ( threading.Thread ):
> def run ( self ):
> result = func(*func_args)
> callback(result, *callback_args)
> MyThread().start()
> 
> 
> (and for me, I'd )


Cool, that's a neat trick I'd never have thought of. I think the 2 line
alternative might be a little more pythonic though, in terms of
readability & simplicity...

if callback:
callback(result, *callback_args)

That could be because I'm not terribly au fait with the whole lambda
calculus thing though. What say those who are comfortable with it?
Obvious or oblique?

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


Re: Duplicates of third-party libraries

2009-12-08 Thread Grant Edwards
On 2009-12-08, Martin P. Hellwig  wrote:

> - In the ideal world, a upgrade of a dependency won't break
>   your program, in reality users fear upgrading dependencies
>   because they don't know for sure it won't result in a dll
>   hell type of problem.

In my experience with binary-based distros (RedHat, Windows,
Debian, etc.), upgrading libraries broke things as often as
not.  I've had significantly better results with Gentoo.
However, were I shipping a significant product that dependended
up updates to external libraries, I'd be very worried.

It also seems like a lot of work to provide the product in all
of the different package-management formats used by customers.
Even considering the extra updates that might be required for
library fixes, shipping a single stand-alone system sounds like
a lot less work.

-- 
Grant Edwards   grante Yow! JAPAN is a WONDERFUL
  at   planet -- I wonder if we'll
   visi.comever reach their level of
   COMPARATIVE SHOPPING ...
-- 
http://mail.python.org/mailman/listinfo/python-list


no module named error

2009-12-08 Thread Joe
I am trying to write/run a python script which imports from another
script which is located in my /usr/lib64/python2.6/site-packages/ dir,
but getting the following error.

$ python ./mytest.py
Traceback (most recent call last):
  File "./mytest.py", line 45, in 
  from moda import *
File "/usr/lib64/python2.6/site-packages/moda.py", line 7, in

import _moda
ImportError: No module named _moda


The script moda.py exists. My script is:

#!/usr/bin/python

import sys

from moda import *

def main(args = sys.argv[1:]):
print 'test'

if __name__ == '__main__' :
main()

Any idea what I'm doing wrong?
-- 
http://mail.python.org/mailman/listinfo/python-list


relative imports with the __import__ function

2009-12-08 Thread Chris Colbert
I have package tree that looks like this:

main.py
package
__init__.py
configuration.ini
server
__init__.py
xmlrpc_server.py
controller.py
reco

segmentation
__init__.py
red_objects.py



main.py launches an instance of xmlrpc_server.py which, in turn,
imports controller.py.
controller.py reads configuration.ini to determine which
module/function to import from the segmentation directory and
subsequently use.

that config file specifies the module as 'red_objects' and the
function as 'segment_red'.

I am trying to dynamically import that module and func using the
__import__ statement but keep getting empty module errors.

In the following code segment, the failing code is uncommented, but
the commented code works fine:

seg_mod = 'red_objects'
smod = __import__('..segmentation.%s' % seg_mod, fromlist=[seg_func], level=-1)

#from ..segmentation import red_objects
#smod = red_objects

I have tried all sorts of values for the 'level' kwarg as well as
everywhich variation of the dotted relative notation.

I'm assuming i'm missing something fundamental on the import resolution...

As an aside, I would like to move main.py inside of the package
directory, but I dont know if that is possible with what i'm trying to
do here.

Thanks for any help.

Cheers!

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


Re: no module named error

2009-12-08 Thread Diez B. Roggisch
Joe wrote:

> I am trying to write/run a python script which imports from another
> script which is located in my /usr/lib64/python2.6/site-packages/ dir,
> but getting the following error.
> 
> $ python ./mytest.py
> Traceback (most recent call last):
>   File "./mytest.py", line 45, in 
>   from moda import *
> File "/usr/lib64/python2.6/site-packages/moda.py", line 7, in
> 
> import _moda
> ImportError: No module named _moda
> 
> 
> The script moda.py exists. My script is:

But it's searching for _moda.*, most probably a binary extension. Does that
exist, and if yes, has it the proper architecture or is it maybe 32 bit?

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


Re: Duplicates of third-party libraries

2009-12-08 Thread Martin P. Hellwig

Lie Ryan wrote:



The only thing that package managers couldn't provide is for the 
extremist bleeding edge; those that want the latest and the greatest in 
the first few seconds the developers releases them. The majority of 
users don't fall into that category, most users are willing to wait a 
few weeks to let all the just-released bugs sorted out and wait till the 
package (and their dependencies) stabilize.


Well you majority of your users still fall into my category of minority, 
as most of my paid support clients use windows, although I use Ubuntu as 
my main developer machine.


--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: no module named error

2009-12-08 Thread Joe
> But it's searching for _moda.*, most probably a binary extension. Does that
> exist, and if yes, has it the proper architecture or is it maybe 32 bit?

I'm just going by an example script. moda is a package I was given that
is written in C and has some python bindings and does run 64-bit. I'm on
gentoo. I'm not sure it's installed correctly, but it did come w/ a
setup.py, and I ran 'setup.py install' and it seemed to have installed
correctly.

$ sudo python ./setup.py install
running install
running build
running build_py
running install_lib
running install_egg_info
Removing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info
Writing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info

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


Re: no module named error

2009-12-08 Thread Diez B. Roggisch
Joe wrote:

>> But it's searching for _moda.*, most probably a binary extension. Does
>> that exist, and if yes, has it the proper architecture or is it maybe 32
>> bit?
> 
> I'm just going by an example script. moda is a package I was given that
> is written in C and has some python bindings and does run 64-bit. I'm on
> gentoo. I'm not sure it's installed correctly, but it did come w/ a
> setup.py, and I ran 'setup.py install' and it seemed to have installed
> correctly.
> 
> $ sudo python ./setup.py install
> running install
> running build
> running build_py
> running install_lib
> running install_egg_info
> Removing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info
> Writing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info

You didn't answer my question. Did it install the _moda.* file the moda.py
is searching for? 

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


Re: SUB-MATRIX extraction

2009-12-08 Thread Jon Clements
On Dec 8, 1:36 pm, Pierre  wrote:
> Hello,
>
> let b = array([ [0,1,2] , [3,4,5] , [6,7,8] ])
>
> How can I easily extract the submatrix [ [0 ,1], [3, 4]] ?
>
> One possiblity is : b[[0,1],:][:,[0,1]] but it is not really easy !
>
> Thanks.

x = numpy.array([ [0,1,2], [3,4,5], [6,7,8] ])
print x[0:2,:2]
>>> array([[0, 1],
   [3, 4]])

Check out http://www.scipy.org/Tentative_NumPy_Tutorial

hth,

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


Re: Generators.

2009-12-08 Thread Jorge Cardona
2009/12/7 Taylor :
> On Dec 7, 1:29 pm, Jorge Cardona  wrote:
>> 2009/12/7 Lie Ryan :
>>
>>
>>
>> > On 12/7/2009 7:22 AM, Jorge Cardona wrote:
>>
>> >> Hi,
>>
>> >> I was trying to create a function that receive a generator and return
>> >> a list but that each elements were computed in a diferent core of my
>> >> machine. I start using islice function in order to split the job in a
>> >> way that if there is "n" cores each "i" core will compute the elements
>> >> i,i+n,i+2n,..., but islice has a weird (to me) behavior, look:
>>
>> > it's nothing weird, python just do what you're telling it to:
>>
>> > transform all x in X with f(x)
>>
>> >> g = (f(x) for x in X)
>>
>> > then slice the result of that
>>
>> >> print(list(x for x in islice(g,0,None,2)))
>>
>> When i wrote that first line of code i thought that i was creating a
>> generator that will later compute  the elements of X with function f,
>> if i will like to transform them immediately i would use [] instead
>> (), so, the result is not where i want to slice, even so, is exactly
>> the same to slice, after or before, the only difference is that after
>> the compute i'm losing 5 in unnecessary execution of the function f.
>>
>> > what you want to do is to slice before you transform:
>>  g = (x for x in islice(X, 0, None, 2))
>>  print(list(f(x) for x in g))
>> > eval: 0
>> > eval: 2
>> > eval: 4
>> > eval: 6
>> > eval: 8
>> > [0, 2, 4, 6, 8]
>>
>> What i want to do is a function that receive any kind of generator and
>> execute it in several cores (after a fork) and return the data, so, i
>> can't slice the set X before create the generator.
>>
>>
>>
>> >> islice execute the function at the generator and drop the elements
>> >> that aren't in the slice. I found that pretty weird, the way that i
>> >> see generators is like an association between and indexing set (an
>> >> iterator or another generator) and a computation that is made indexed
>> >> by the indexing set, and islice is like a "transformation" on the
>> >> indexing set,it doesn't matter the result of the function, the slice
>> >> should act only on the indexing set, some other "transformation" like
>> >> takewhile act on the result so, the execution it has to be made, but
>> >> in the islice, or other "transformation" that act only in the indexing
>> >> set, the function shouldn't be executed at each element, but only on
>> >> that new set that result of the application of the "transformation" on
>> >> the original set.
>>
>> > that seems like an extremely lazy evaluation, I don't know if even a true
>> > lazy language do that. Python is a strict language, with a few laziness
>> > provided by generators, in the end it's still a strict language.
>>
>> Yes, it looks like lazy evaluation, but, i don't see why there is not
>> a better control over the iterable associated to a generator, even
>> with Python that is a strict language, it will increase the
>> functionality of it, and the performance too, imagine that you pass a
>> function that takes 1 sec in run, and for several reason you can't
>> slice before (as the smp function that i want to create), the final
>> performance with the actual islice it gets really reduced
>> Just creating the separation between those transformation that act on
>> the index(islice, or tee) on those that act on the result(dropwhile,
>> takewhile, etc.) the control could be fine enough to increase
>> usability (that's the way i think right now), and you will be able to
>> combine generator without lose performance.
>>
>> >> Well, it works for what i need, but is not very neat, and i think that
>> >> there it should be a formal way to act on the base indexing iterator,
>> >> such way exists? Is there a better approach to get what i need?
>>
>> > Reverse your operation.
>> > --
>> >http://mail.python.org/mailman/listinfo/python-list
>>
>> --
>> Jorge Eduardo Cardona
>> jorgeecard...@gmail.com
>> jorgeecardona.blogspot.com
>> 
>> Linux registered user  #391186
>> Registered machine    #291871
>> 
>
> What would you have your islice do for the following generator?
>
> def fib(n):
>    a,b=0,1
>    for x in range(n):
>        a,b=b,a+b
>        yield a
>
> In order for some value it yields to be correct, it needs execute all
> the previous times. If it happens that some of the results aren't
> used, they are thrown out. As is, using your islice (on, say, fib(10))
> gives a KeyError for the key '.0'.
> Point is, generators don't work that way. You aren't guaranteed to be
> able to jump around, only to find the next value. If you need to split
> a particular generator up into parts that can be computed separately,
> your best bet is probably to rewrite that generator.

yes, it doesn't work with that example, f_locals has only the n
argument. Let me rewrite the islice like this:

def islice(iterable, *args):
s = slice(*args)

# search the deepest iter (Base i

Re: Duplicates of third-party libraries

2009-12-08 Thread Grant Edwards
On 2009-12-08, Martin P. Hellwig  wrote:
> Lie Ryan wrote:
>
>> 
>> The only thing that package managers couldn't provide is for the 
>> extremist bleeding edge; those that want the latest and the greatest in 
>> the first few seconds the developers releases them. The majority of 
>> users don't fall into that category, most users are willing to wait a 
>> few weeks to let all the just-released bugs sorted out and wait till the 
>> package (and their dependencies) stabilize.
>
> Well you majority of your users still fall into my category of minority, 
> as most of my paid support clients use windows,

Does windows even _have_ a library dependancy system that lets
an application specify which versions of which libraries it
requires?

> although I use Ubuntu as my main developer machine.

-- 
Grant Edwards   grante Yow! My life is a patio
  at   of fun!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Python as career

2009-12-08 Thread Bruno Desthuilliers

joy99 a écrit :
(snip)


I was thinking if I need to know Django,any good RDBMS(I know only MS-
Access)


Any job in IT will (well... "should") indeed require
a decent knowledge of the relational thery / algebra, relational 
database design (normal forms etc), SQL, and working knowledge with at 
least one "major RDBMS (oracle or postgresql) and possibly the 
ubiquitous (in the web world) MySQL gizmo.


Django and/or Rail might be a good idea too, but most of the 
"enterprise" stuff is still done in Java :(

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


Re: Duplicates of third-party libraries

2009-12-08 Thread Martin P. Hellwig

Grant Edwards wrote:


Does windows even _have_ a library dependancy system that lets
an application specify which versions of which libraries it
requires?


Well you could argue that easy_install does it a bit during install.
Then there is 'Windows Side By Side' (winsxs) system which sorta does it 
during run time.


--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: SUB-MATRIX extraction

2009-12-08 Thread Martin P. Hellwig

Jon Clements wrote:

On Dec 8, 1:36 pm, Pierre  wrote:

Hello,

let b = array([ [0,1,2] , [3,4,5] , [6,7,8] ])

How can I easily extract the submatrix [ [0 ,1], [3, 4]] ?

One possiblity is : b[[0,1],:][:,[0,1]] but it is not really easy !

Thanks.


x = numpy.array([ [0,1,2], [3,4,5], [6,7,8] ])
print x[0:2,:2]

array([[0, 1],

   [3, 4]])

Check out http://www.scipy.org/Tentative_NumPy_Tutorial

hth,

Jon.


Yeah numpy is great like that and is the most obvious and probably the 
most right solution, however I'd like to mention if you are going to do 
a lot of stuff that is going to look an awful lot like SQL, perhaps it 
is easier to pump it in a (in :memory:) sqlite table and use it that 
way. Chances are though that you are far better of with numpy.


--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: relative imports with the __import__ function

2009-12-08 Thread Peter Otten
Chris Colbert wrote:

> I have package tree that looks like this:
> 
> main.py
> package
> __init__.py
> configuration.ini
> server
> __init__.py
> xmlrpc_server.py
> controller.py
> reco
> 
> segmentation
> __init__.py
> red_objects.py
> 
> 
> 
> main.py launches an instance of xmlrpc_server.py which, in turn,
> imports controller.py.
> controller.py reads configuration.ini to determine which
> module/function to import from the segmentation directory and
> subsequently use.
> 
> that config file specifies the module as 'red_objects' and the
> function as 'segment_red'.
> 
> I am trying to dynamically import that module and func using the
> __import__ statement but keep getting empty module errors.


> I'm assuming i'm missing something fundamental on the import resolution...

After some experimentation it turns out you have to provide some context for 
__import__() to determine the absolute location of the requested module. The 
required bit of information is the current module's __name__ attribute which 
you can provide via the globals parameter:

def import_segmentation(name):
return getattr(__import__("segmentation." + name, level=2, 
globals=globals()), name)

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


Re: Generators.

2009-12-08 Thread Jorge Cardona
2009/12/8 Lie Ryan :
> First, I apologize for rearranging your message out of order.
>
> On 12/8/2009 5:29 AM, Jorge Cardona wrote:

 islice execute the function at the generator and drop the elements
 that aren't in the slice. I found that pretty weird, the way that i
 see generators is like an association between and indexing set (an
 iterator or another generator) and a computation that is made indexed
 by the indexing set, and islice is like a "transformation" on the
 indexing set,it doesn't matter the result of the function, the slice
 should act only on the indexing set, some other "transformation" like
 takewhile act on the result so, the execution it has to be made, but
 in the islice, or other "transformation" that act only in the indexing
 set, the function shouldn't be executed at each element, but only on
 that new set that result of the application of the "transformation" on
 the original set.
>>>
>>> that seems like an extremely lazy evaluation, I don't know if even a true
>>> lazy language do that. Python is a strict language, with a few laziness
>>> provided by generators, in the end it's still a strict language.
>>>
>>
>> Yes, it looks like lazy evaluation, but, i don't see why there is not
>> a better control over the iterable associated to a generator, even
>> with Python that is a strict language, it will increase the
>> functionality of it, and the performance too, imagine that you pass a
>> function that takes 1 sec in run, and for several reason you can't
>> slice before (as the smp function that i want to create), the final
>> performance with the actual islice it gets really reduced
>> Just creating the separation between those transformation that act on
>> the index(islice, or tee) on those that act on the result(dropwhile,
>> takewhile, etc.) the control could be fine enough to increase
>> usability (that's the way i think right now), and you will be able to
>> combine generator without lose performance.
>
> Theoretically yes, but the semantic of generators in python is they work on
> an Iterable (i.e. objects that have __iter__), instead of a Sequence (i.e.
> objects that have __getitem__). That means semantically, generators would
> call obj.__iter__() and call the iter.__next__() and do its operation for
> each items returned by the iterator's iterable's __next__().
>
> The lazy semantic would be hard to fit the current generator model without
> changing the semantics of generator to require a Sequence that supports
> indexing.
>

Why?

The goal is add a formal way to separate the transformation of a
generator in those that act on the indexing set and those that act on
the result set.

Well, a little (and not so elaborated) example could be:

from itertools import islice


class MyGenerator:
def __init__(self, function, indexing_set):
self._indexing_set = (x for x in indexing_set)
self._function = function

def indexing_set(self):
return (x for x in self._indexing_set)

def result_set(self):
return (self._function(x) for x in self.indexing_set())

def function(self):
return self._function

def f(x):
print("eval: %d"%x)
return x

def myslice(iterable, *args):
return MyGenerator(iterable.f, islice(iterable.indexing_set(),*args))


g = MyGenerator(f, xrange(10))
print(list(g.result_set()))

g = MyGenerator(f, xrange(10))
new_g = myslice(g,0,None,2)
print(list(new_g.result_set()))

that returns:

eval: 0
eval: 1
eval: 2
eval: 3
eval: 4
eval: 5
eval: 6
eval: 7
eval: 8
eval: 9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
eval: 0
eval: 2
eval: 4
eval: 6
eval: 8
[0, 2, 4, 6, 8]

I don't see why is needed add a sequence to support the indexing, but
some separation feature of the base components of the generator
(function, indexing_set).

>> Yes, it looks like lazy evaluation, but, i don't see why there is not
>> a better control over the iterable associated to a generator, even
>> with Python that is a strict language
>
> You can control the laziness by making it explicitly lazy:
>
> from functools import partial
> def f(x):
>    print("eval: %d"%x)
>    return x
>
> X = range(10)
> g = (partial(f, x) for x in X)
>
> print(list(x() for x in islice(g,0,None,2)))
> # # or without partial:
> # g = ((lambda: f(x)) for x in X)
> # print(list(f() for f in islice(g,0,None,2)))
>

I keep here the problem in that i shouldn't be able to define the
original generator because the function receive the already defined
generator.

> In a default-strict language, you have to explicitly say if you want lazy
> execution.
>
>> What i want to do is a function that receive any kind of generator and
>> execute it in several cores (after a fork) and return the data, so, i
>> can't slice the set X before create the generator.
>
> beware that a generator's contract is to return a valid iterator *once*
> only. You can use itertools.tee() to create more generators, but tee built a
> list of the results inter

Determine PyArg_ParseTuple parameters at runtime?

2009-12-08 Thread Nikolaus Rath
Hello,

I want to create an extension module that provides an interface to a
couple of C functions that take arguments of type struct iovec, struct
stat, struct flock, etc (the FUSE library, in case it matters).

Now the problem is that these structures contain attributes of type
fsid_t, off_t, dev_t etc. Since I am receiving the values for these
attributes from the Python caller, I have to convert them to the correct
type using PyArg_ParseTuple.

However, since the structs are defined in a system-dependent header
file, when writing the code I do not know if on the target system, e.g.
off_t will be of type long, long long or unsigned long, so I don't know
which format string to pass to PyArg_ParseTuple.


Are there any best practices for handling this kind of situation? I'm at
a loss right now.

The only thing that comes to my mind is to, e.g., to compare
sizeof(off_t) to sizeof(long) and sizeof(long long) and thereby
determine the correct bit length at runtime. But this does not help me
to figure out if it is signed or unsigned, or (in case of other
attributes than off_t) if it is an integer at all.


Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: no module named error

2009-12-08 Thread Joe
Diez B. Roggisch wrote:
> Joe wrote:
> 
>>> But it's searching for _moda.*, most probably a binary extension. Does
>>> that exist, and if yes, has it the proper architecture or is it maybe 32
>>> bit?
>> I'm just going by an example script. moda is a package I was given that
>> is written in C and has some python bindings and does run 64-bit. I'm on
>> gentoo. I'm not sure it's installed correctly, but it did come w/ a
>> setup.py, and I ran 'setup.py install' and it seemed to have installed
>> correctly.
>>
>> $ sudo python ./setup.py install
>> running install
>> running build
>> running build_py
>> running install_lib
>> running install_egg_info
>> Removing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info
>> Writing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info
> 
> You didn't answer my question. Did it install the _moda.* file the moda.py
> is searching for? 
> 
> Diez


Yeah, that's what I meant when I said the file exists above. There's a
moda.py in /usr/lib64/python2.6/site-packages/moda.py.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: no module named error

2009-12-08 Thread Diez B. Roggisch
Joe wrote:

> Diez B. Roggisch wrote:
>> Joe wrote:
>> 
 But it's searching for _moda.*, most probably a binary extension. Does
 that exist, and if yes, has it the proper architecture or is it maybe
 32 bit?
>>> I'm just going by an example script. moda is a package I was given that
>>> is written in C and has some python bindings and does run 64-bit. I'm on
>>> gentoo. I'm not sure it's installed correctly, but it did come w/ a
>>> setup.py, and I ran 'setup.py install' and it seemed to have installed
>>> correctly.
>>>
>>> $ sudo python ./setup.py install
>>> running install
>>> running build
>>> running build_py
>>> running install_lib
>>> running install_egg_info
>>> Removing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info
>>> Writing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info
>> 
>> You didn't answer my question. Did it install the _moda.* file the
>> moda.py is searching for?
>> 
>> Diez
> 
> 
> Yeah, that's what I meant when I said the file exists above. There's a
> moda.py in /usr/lib64/python2.6/site-packages/moda.py.

Please, read my post *carefully*. moda.py imports a file _moda.* (most
probably _moda.so), which seems *not* to be there.

Please verify that it exists and has the proper architecture.

This is your output:

"""
        File "/usr/lib64/python2.6/site-packages/moda.py", line 7, in

            import _moda
            ImportError: No module named _moda
"""
 ^

_moda, *not* moda.


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


Re: In lista infinita?

2009-12-08 Thread Andreas Waldenburger
On Tue, 08 Dec 2009 17:39:13 +0100 andrea 
wrote:

> Ho notato che i generatori anche se infiniti non si lamentano se usati
> in modo potenzialmente "pericoloso".
> [...]
> Altri miglioramenti/utilizzi trasversali?

Maybe. But I'm sure it.comp.lang.python might help you better. And from
the looks of it, you seem to have started a similar thread there
(called "Generatori infiniti").

Generally, you'll fare better with English (even broken English will be
fine.) in this group. It's just nicer for everyone if they can
understand all messages and not feel left out.

Anyway, good luck with your question. I didn't understand a whole lot
of it, but I guess you want to test for membership in an infinite
list/generator. Yes, possible in principle, but obviously eats memory
for larger generators. Also, consumes the generators, which is also a
factor.

/W

-- 
INVALID? DE!

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


Re: IO Gurus: what are the differences between these two methods?

2009-12-08 Thread Lie Ryan

On 12/8/2009 4:12 AM, dpapathanasiou wrote:

I have two methods for writing binaries files: the first works with
data received by a server corresponding to a file upload, and the
second works with data sent as email attachments.

The odd thing is, they're not interchangeable: if I use the first one
to saved data parsed from an email attachment, it fails; similarly,
the second function fails when dealing with an uploaded file data.

What are the critical differences?


Those code reeks for refactoring. If you're lucky enough to be in python 
2.6 or above, use the io module to wrap the string in second function in 
a file-like object.

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


Re: no module named error

2009-12-08 Thread Joe
> 
> Please verify that it exists and has the proper architecture.
> 


Ah, ok, I thought those were one in the same. But I do have that file in
another directory elsewhere and I have that directory in my
LD_LIBRARY_PATH var.

Shouldn't that be enough to do it?



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


Re: no module named error

2009-12-08 Thread Joe
Just to clarify, I have "_moda.la" sitting in another directory which is
included in my LD_LIBRARY_PATH. And it is built for the 64bit arch.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: no module named error

2009-12-08 Thread Diez B. Roggisch
Joe wrote:

> Just to clarify, I have "_moda.la" sitting in another directory which is
> included in my LD_LIBRARY_PATH. And it is built for the 64bit arch.

No, the import-mechanism of python doesn't take LD_LIBRARY_PATH into
account, and even if it did - _moda.la is a simple archive-file, not a
shared library. It can't be dynamically loaded. Something in your
build-process is not working.

I suggest you 

 - clean out the source package from everything in there except the original
distribution - maybe simply removing & unpacking is the best idea.

 - build the package again, and post the *full* output. This might give us a
clue.

Alternatively, if it's possible to share the module, do that.

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


Re: Brent's variation of a factorization algorithm

2009-12-08 Thread Gabriel Genellina

En Fri, 27 Nov 2009 12:36:29 -0300, n00m  escribió:


Maybe someone'll make use of it:


def gcd(x, y):
if y == 0:
return x
return gcd(y, x % y)

def brent(n): ...


A better place to publish this code would be the Python Cookbook:  
http://code.activestate.com


--
Gabriel Genellina

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


Re: Python3: Sane way to deal with broken encodings

2009-12-08 Thread Martin v. Loewis
> Thus my Python script dies a horrible death:
> 
>   File "./update_db", line 67, in 
> for line in open(tempfile, "r"):
>   File "/usr/local/lib/python3.1/codecs.py", line 300, in decode
> (result, consumed) = self._buffer_decode(data, self.errors, final)
> UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position
> 3286: unexpected code byte
> 
> This is well and ok usually, but I'd like to be able to tell Python:
> "Don't worry, some idiot encoded that file, just skip over such
> parts/replace them by some character sequence".
> 
> Is that possible? If so, how?

As Benjamin says: if you pass errors='replace' to open, then it will
replace the faulty characters; if you pass errors='ignore', it will
skip over them.

Alternatively, you can open the files in binary ('rb'), so that no
decoding will be attempted at all, or you can specify latin-1 as
the encoding, which means that you can decode all files successfully
(though possibly not correctly).

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


Re: Graph library for Python

2009-12-08 Thread geremy condra
On Tue, Dec 8, 2009 at 7:27 AM, Robin Becker  wrote:
> geremy condra wrote:
> ...
>>
>> I don't have a problem with adding this if there's a strong desire for it,
>> but at the moment I'm leaning towards a wait-and-see approach, for
>> all the reasons you described.
>>
>> Geremy Condra
>
> I don't want to sound pessimistic, but graph and digraph theory has a lot of
> history, especially in computer science.

Of course it does- the rich set of problem-solving tools provided
by theoretical computer science and mathematical graph theory
are what make graphs so useful, which is why I'm advocating
that they be in the standard library.

>There are already very many
> implementations eg
>
> http://code.google.com/p/igraph
> http://www.boost.org/doc/libs/release/libs/graph
> http://ernst-schroeder.uni.lu/Digraph/doc/
> http://code.google.com/p/python-graph
> http://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph-module.html
>
> and many others..some of the above already seem to be very useful.

I suspect that part of the reason there are so many implementations
is because graphs are a) useful and b) not in the standard library.

> Is there reason to suppose that any one representation of graphs or digraphs
> is so good we need to add it to python?

I think there are several implementations that would meet the
standards for code quality, and both graphine and python-graph
are full-featured, easy to use, pure python graph libraries. Any
one of them would be a credit to the standard library.

> Even for fairly common algorithms eg Dijkstra's shortest path there doesn't
> seem to be complete agreement on how to implement them; for the details of
> how nodes/edges/paths should be stored and efficiently manipulated there is
> huge variety.

Of course there are. Different authors envision different use
cases, and select their data structures and algorithms
appropriately. That doesn't imply that none of them are
appropriate for the common case, which is what we would
be targeting here.

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


Re: Brent's variation of a factorization algorithm

2009-12-08 Thread MRAB

Gabriel Genellina wrote:

En Fri, 27 Nov 2009 12:36:29 -0300, n00m  escribió:


Maybe someone'll make use of it:


def gcd(x, y):
if y == 0:
return x
return gcd(y, x % y)

def brent(n): ...


A better place to publish this code would be the Python Cookbook: 
http://code.activestate.com



An iterative alternative is:

def gcd(x, y):
while y != 0:
x, y = y, x % y
return x

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


Re: can someone explain 'super' to me?

2009-12-08 Thread Gabriel Genellina
En Sat, 05 Dec 2009 07:27:54 -0300, Michael   
escribió:



From the docs about the built-in function super:



super( type[, object-or-type])

Return the superclass of type. [...]


You won't get anywhere from the docs in this case, unfortunately. Start by  
reading these three articles by Michele Simionato:

http://www.artima.com/weblogs/viewpost.jsp?thread=236275
and also the famous "Python super() considered harmful":
http://fuhm.net/super-harmful/


It seems like it can return either a class or an instance of a class.
Like
super( C, self)
is like casting self as superclass C.


Not really - I hope you'll understand what that means after reading the  
above articles, feel free to ask again then.



However if you omit the second argument entirely you get a class.


Those "unbound" super objects are rare; you probably won't need them.  
They're discussed in M.S. article, though.


--
Gabriel Genellina

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


My Darned Image Again

2009-12-08 Thread Victor Subervi
Hi;
I'm having trouble loading my image again. Here's my code:

  for pic in pics:
sql = 'update %s set %s=%s where SKU=%s;' % (store, colNamesPics[i],
'%s', sku)
sql = sql, (MySQLdb.Binary(pics[int(i)]),)
cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),))
print sql
i += 1

Here's the beginning of what it prints to screen:

('update products set pic1=%s where SKU=prodSKU1;', (array('c',
'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08

It throws this error:

 /var/www/html/angrynates.com/cart/addEdit.py
  102   db.commit()
  103   cursor.close()
  104
  105 addEdit()
  106
addEdit = 
 /var/www/html/angrynates.com/cart/addEdit.py in addEdit()
   88 sql = sql, (MySQLdb.Binary(pics[int(i)]),)
   89 print sql
   90 cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),))
   91 i += 1
   92   except MySQLdb.IntegrityError:
cursor = , cursor.execute = >, sql = ('update products
set pic1=%s where SKU=prodSKU1;', (array('c', ['\xff', '\xd8', '\xff',
'\xe0', '\x00', ...]),)), global MySQLdb = , MySQLdb.Binary =
, pics =
['\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12...f\x0b\xe5\xf9\x8b\xefR\xe7\xa1\xa2\xa3#"+)f8\x08EjZh\xff\x007\xcd\xde\xb5S\xc8\xdb\xf2&\xd3\xe9V!PO\xa5d\xf5W\xb8\xf9-\xb9\xff\xd9'],
builtin int = , i = 0
 /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in
execute(self=, query=('update products set
pic1=%s where SKU=prodSKU1;', (array('c', ['\xff', '\xd8', '\xff', '\xe0',
'\x00', ...]),)), args=(array('c', ['\xff', '\xd8', '\xff', '\xe0', '\x00',
...]),))
  144 db = self._get_db()
  145 charset = db.character_set_name()
  146 query = query.encode(charset)
  147 if args is not None:
  148 query = query % db.literal(args)
query = ('update products set pic1=%s where SKU=prodSKU1;', (array('c',
['\xff', '\xd8', '\xff', '\xe0', '\x00', ...]),)), query.encode undefined,
charset = 'latin1'

AttributeError: 'tuple' object has no attribute 'encode'
  args = ("'tuple' object has no attribute 'encode'",)

What do?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Pyro 3.10 released

2009-12-08 Thread Irmen de Jong

Hi,

Pyro 3.10 has been released!

Pyro is a an advanced and powerful Distributed Object Technology system 
written entirely in Python, that is designed to be very easy to use.

Have a look at http://pyro.sourceforge.net for more information.

Highlights of this release are:
- improvements in the SSL configuration
- uses new-style classes so super() now works in Pyro objects
- various minor bugfixes

As always the detailed changes are in the changes chapter in the manual.
Please read this for more details and info before upgrading.

You can download Pyro 3.10 from sourceforge: 
http://sourceforge.net/projects/pyroor from PyPI 
http://pypi.python.org/pypi/Pyro/



Enjoy,

Irmen de Jong


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


Re: My Darned Image Again

2009-12-08 Thread MRAB

Victor Subervi wrote:

Hi;
I'm having trouble loading my image again. Here's my code:

  for pic in pics:
sql = 'update %s set %s=%s where SKU=%s;' % (store, colNamesPics[i], 
'%s', sku)


After this, 'sql' will be a string.


sql = sql, (MySQLdb.Binary(pics[int(i)]),)


After this, 'sql' will be a tuple.


cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),))

[snip]

You're passing 'sql', which is a tuple, as the query. What was the
purpose of the previous line?
--
http://mail.python.org/mailman/listinfo/python-list


Problem using commands.getoutput()

2009-12-08 Thread J
Reading up on ways to run commands in a shell and capture output...

So I was looking at os.exec*() and that's not the correct thing here.
If I understand the docs correctly, the os.exec*() functions actually
end the calling program and replace it with the program called by
os.exec*() even as far as giving the new process the calling process's
PID:

"These functions all execute a new program, replacing the current
process; they do not return. On Unix, the new executable is loaded
into the current process, and will have the same process id as the
caller. Errors will be reported as OSError exceptions."

So from there, I found the commands module and getoutput() which
again, if I'm right, is supposed to run a command in a shell, and
return the output of that command a string.

commands.getoutput() is this:

def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import os
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts = 0
if text[-1:] == '\n': text = text[:-1]
return sts, text

or at least it calls this function, and returns text, ignorint sts...

However, when I try using it, I get this:
>>> print commands.getoutput('dir')
'{' is not recognized as an internal or external command,
operable program or batch file.
>>>

Which looks like it's choking on the format of the "pipe = os.popen"
line, but that's just a guess... because this works:

p = os.popen('dir','r')
p.read()
p.close()

So what's the point of the commands module, or is that one that only
works in Linux, and not Windows?  I can do what I want, I think, by
using os.popen(), but I wanted to know if there was a better way of
doing it.

Cheers,
Jeff

-- 

Jonathan Swift  - "May you live every day of your life." -
http://www.brainyquote.com/quotes/authors/j/jonathan_swift.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My Darned Image Again

2009-12-08 Thread Carsten Haese
Victor Subervi wrote:
> Hi;
> I'm having trouble loading my image again. Here's my code:
> 
>   for pic in pics:
> sql = 'update %s set %s=%s where SKU=%s;' % (store,
> colNamesPics[i], '%s', sku)
> sql = sql, (MySQLdb.Binary(pics[int(i)]),)
> cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),))
> print sql
> i += 1

Oh boy, programming by accident strikes again. Your immediate problem is
the line <> wherein you're
reassigning the name <> to become a 2-tuple consisting of the
string formerly known as <> and the 1-tuple containing the picture
contents. That line has no business being there. Delete it.

There are also some stylistic problems in your code that aren't actually
wrong, but they make my toenails curl in horror. Please allow me to
improve your code.

First of all, you're iterating over <>, and assigning the name
<> to each one, but you're not referring to that name anywhere.
Instead, you use an artificial index counter (<>), which you're then
using to look up the i-th picture. Of course, you need <> to look up
the i-th column name. Instead, you should do a parallel iteration that
iterates over the column name and the picture simultaneously. Look in my
code below for the line containing <> to see how that's done.

Also, you should only use string interpolation to build the parts of the
query that aren't values. In other words, only the variable table and
column names should be put into the query via string interpolation. The
sku should be passed as a parameter. Also, you should just use "%%s" to
get a literal "%s" through the interpolation step instead of
interpolating "%s" into %s markers.

Putting all that together, I'd rewrite your code above as follows:


for (column_name, pic) in zip(colNamesPics, pics):
query = ("update %s set %s = %%s where SKU=%%s" %
(store, column_name) )
parameters = (MySQLdb.Binary(pic), sku)
cursor.execute(query, parameters)


There, that's much less cluttered.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: My Darned Image Again

2009-12-08 Thread Victor Subervi
On Tue, Dec 8, 2009 at 3:28 PM, MRAB  wrote:

> Victor Subervi wrote:
>
>> Hi;
>> I'm having trouble loading my image again. Here's my code:
>>
>>  for pic in pics:
>>sql = 'update %s set %s=%s where SKU=%s;' % (store,
>> colNamesPics[i], '%s', sku)
>>
>
> After this, 'sql' will be a string.
>
>
> sql = sql, (MySQLdb.Binary(pics[int(i)]),)
>>
>
> After this, 'sql' will be a tuple.
>
>
> cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),))
>>
> [snip]
>
> You're passing 'sql', which is a tuple, as the query. What was the
> purpose of the previous line?
>

To print stuff out to screen. I don't know what happened, but when I pulled
that out, it threw a familiar error that alerted me to quote the last
variable (SKU="%s") and the blob went straight in. Thanks!
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem using commands.getoutput()

2009-12-08 Thread Jerry Hill
On Tue, Dec 8, 2009 at 2:31 PM, J  wrote:
>
> So what's the point of the commands module, or is that one that only
> works in Linux, and not Windows?

At the very top of http://docs.python.org/library/commands.html it
says "Platforms: Unix", so yes, it's Unix-only.

> I can do what I want, I think, by
> using os.popen(), but I wanted to know if there was a better way of
> doing it.

Also at the top of that same bit of documentation is this: "The
subprocess module provides more powerful facilities for spawning new
processes and retrieving their results. Using the subprocess module is
preferable to using the commands module."

I would start with http://docs.python.org/library/subprocess.html and
http://www.doughellmann.com/PyMOTW/subprocess/ for more information
about the subprocess module and how it works.

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


Re: Problem using commands.getoutput()

2009-12-08 Thread J
On Tue, Dec 8, 2009 at 14:44, Jerry Hill  wrote:

> At the very top of http://docs.python.org/library/commands.html it
> says "Platforms: Unix", so yes, it's Unix-only.

That sound you hear is me beating my head against the table now...
sigh... I was too wrapped up in reading the actual code to notice the
comments...

> Also at the top of that same bit of documentation is this: "The
> subprocess module provides more powerful facilities for spawning new
> processes and retrieving their results. Using the subprocess module is
> preferable to using the commands module."
>
> I would start with http://docs.python.org/library/subprocess.html and
> http://www.doughellmann.com/PyMOTW/subprocess/ for more information
> about the subprocess module and how it works.

And thanks for the pointer to subprocess.  I'll read over that (ALL of
it) and learn some more...  right now I'm doing it just using
os.popen() and dumping the read() results to a list, but I'm all for
learning different ways of accomplishing the task.  I do appreciate
the info!

Jeff



-- 

Samuel Goldwyn  - "I'm willing to admit that I may not always be
right, but I am never wrong." -
http://www.brainyquote.com/quotes/authors/s/samuel_goldwyn.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread Dave Angel



r0g wrote:

Dennis Lee Bieber wrote:
  

On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old 
declaimed the following in gmane.comp.python.general:



For Kannada project .txt(not .doc) is used, my requirement is to have one
  


  

In this context, I request you kindly for small python program - to make or
  

Excuse me -- you want one of US to supply you with a program that
will be used for YOUR entry to some job site? (At least, that's what I
seem to be finding for "Kannada project")





Well it is only a 2 line program and he did ask nicely after all, if you
begrudge him it then feel free to not answer, righteous indignation
rarely helps anyone.

Dear OP...

Put the following 2 lines into a file and save it as spacer.py

import sys
print ' '.join([e for e in open(sys.argv[1], 'r').read()])


Then open a terminal window and 'cd' to the same folder you just saved
the spacer.py file in. Type...

python spacer.py inputfile.txt > outputfile.txt

This will run inputfile.txt through the space adding program we have
just saved and then 'pipe' the output of that into a new file outputfile.txt

Hope this helps,


Roger Heathcote.

  
That seems a bit dangerous to give to a beginner at Python, without 
discussing Unicode issues.  If he's in Python 3.x, and if the default 
encoder is ASCII, which it seems to be most places, then he'll quickly 
get a conversion error for some character.  And if it's some other 8 bit 
form, he might not get an error,  but find that a space is inserted 
between two of the bytes of a UTF-8 code.


DaveA

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


Re: Does Python mess with the (unicode) code page?

2009-12-08 Thread Gabriel Genellina

En Thu, 03 Dec 2009 15:38:28 -0300, Roy Smith  escribió:

We've got a windows executable which used to get run out of a shell  
script

(Cygwin bash) and is now being run with subprocess.Popen().  The windows
app is misbehaving.  To make a long story short, the guy who wrote the  
code

in question says,

it's all based on the return values of the WinAPI calls GetACP and  
GetOEMCP
[...] so maybe Python is doing something like setting the active code  
page

and OEM code page prior to the point when they "exec" stuff?


Does Python do these things?  I'm using Python 2.5.1.


Not that I know of (also, I don't know of any way to programmatically  
alter GetACP and GetOEMCP, they're global system settings).


A console application should use the console functions GetConsoleCP and  
GetConsoleOutputCP; Python itself calls them to derive sys.stdin.encoding  
and sys.stdout.encoding respectively, but only queries the value, never  
sets it. GetConsoleCP isn't necesarily the same as GetOEMCP.


--
Gabriel Genellina

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


Re: My Darned Image Again

2009-12-08 Thread Carsten Haese
Victor Subervi wrote:
> I don't know what happened, but when I
> pulled that out, it threw a familiar error that alerted me to quote the
> last variable (SKU="%s") and the blob went straight in. Thanks!

The fact that you had to quote the SKU value indicates to me that it's
an alphanumeric value (or worse), which means you should really heed the
advice I've given in my other response on this thread: Use parameter
binding instead of string interpolation to provide the SKU value. That
way, regardless of what craziness the SKU value contains, the syntactic
integrity of your database query is not in danger.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Exception classes don't follow pickle protocol, problems unpickling

2009-12-08 Thread Irmen de Jong

On 7-12-2009 10:12, Peter Otten wrote:


So there are 2 problems: the pickle protocol isn't used when exception
objects (or instances of classes derived from Exception) are pickled, and
during unpickling, it then
crashes because it calls __init__  with the wrong amount of parameters.
(why is it bothering with __init__ anyway? Aren't exceptions new style
classes?)


The __reduce__() method is called when you pickle an object. It returns an
argument tuple and a factory. For exceptions that factory is the class which
is why __init__() is called when the object is unpickled.


I didn't realize exceptions are treated as "objects pickle know nothing 
about" (or 'extension types'). They weren't in Python 2.4 at least :)


So I was expecting them to follow the pickle protocol for normal Python 
types, and didn't look past __getnewargs__ and __getinitargs__...




This started happening in Python 2.5, Python 2.4 works without error.

What is causing this?


I think Exceptions need special treatment because they have state that is
not stored in the instance __dict__.


How can I best solve this error?


You could override __reduce__() to call __getstate__(). I don't see the need
for __getnewargs__() because exceptions aren't immutable.

Peter


Thanks, that was enlightening.
I never had to deal with __reduce__ before :)

--irmen


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


Trying to set up dictionary to map to functions

2009-12-08 Thread Randy Belt
Hi,

I have a small test program written trying to set up a dictionary that
points keys to functions.  It is working.  However, in the process of
creating it I noticed a weird problem.  The problem is that this IS WORKING
and I think it shouldn't be.

~ Here is the input config file code ~  its called config.file and is
referenced from the script.

[MAPS]
relmap = 1
posmap = 1
asnmap = 1

~ Here is the code that is working but I feel that it shouldn't be ~

import ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.file")
sections = config.sections()
print config.options('MAPS')
def posmap():
print "posmap function"
def relmap():
print "relmap function"
def asnmap():
print "asnmap function"
for value in config.options('MAPS'):
value
map_library = {
   'posmap': posmap()
  ,'relmap': relmap()
  ,'asnmap': asnmap()
  }

~ Output ~

['posmap', 'relmap', 'asnmap']
posmap function
relmap function
asnmap function

~ The reason I'm confused is because when I change the code (Take away the
map_library dictionary)

import ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.file")
sections = config.sections()
print config.options('MAPS')
def posmap():
print "posmap function"
def relmap():
print "relmap function"
def asnmap():
print "asnmap function"
for value in config.options('MAPS'):
value

~ The output is the following ~

['posmap', 'relmap', 'asnmap']

Is this defaulting to the dictionary and making it work?  In the first set
of code I don't reference the map at all but it still seems to know where to
look?  I am considerably new to Python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Request for solution

2009-12-08 Thread Gabriel Genellina
En Mon, 07 Dec 2009 21:59:42 -0300, 74yrs old   
escribió:



For Kannada project .txt(not .doc) is used, my requirement is to have
one space between two characters in Notepad file.  In MSword there is
provision to make space between two characters under "Font" and  can be
saved as _.doc_  But when tried to save as_ .txt_  all formatting will
disappear. I could not understand how to do in notepad. Even tried copy
and paste from doc to notepad but failed.

In this context, I request you kindly for small Python program - to make
or insert space between two characters in the _text_ file. (I have
installed Fedora-11 and also ubuntu9.04)

example: *F o r  K a n n a d a  p r o j e c t . t x t(n o t .d o c)  i
s  u s e d,  m y  r e q u i r e m e n t   i s  t o  h a v e  o n e  s p
a c e  b e t w e e n  t w o  c h a r a c t e r s  i n  t h e  t e x t.*


Suppose you have the desided text in a string:

py> txt = """For Kannada project .txt(not .doc) is used,
... my requirement is to have
... one space between two characters in Notepad file."""

You can insert one space between each caracter by using:

py> " ".join(txt)
'F o r   K a n n a d a   p r o j e c t   . t x t ( n o t   . d o c )   i  
s   u s
 e d ,   \n m y   r e q u i r e m e n t   i s   t o   h a v e \n o n e   s  
p a c
 e   b e t w e e n   t w o   c h a r a c t e r s   i n   N o t e p a d   f  
i l e

 .'

and then write the resulting text into a file as usual.

--
Gabriel Genellina

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


Re: Graph library for Python

2009-12-08 Thread Carl Banks
On Dec 8, 4:27 am, Robin Becker  wrote:
> Is there reason to suppose that any one representation of graphs or digraphs 
> is
> so good we need to add it to python?

One of them bothered to write a PEP proposing its inclusion?


> Even for fairly common algorithms eg Dijkstra's shortest path there doesn't 
> seem
> to be complete agreement on how to implement them; for the details of how
> nodes/edges/paths should be stored and efficiently manipulated there is huge
> variety.
>
> Wait seems like a good policy.

Geremy's team seems to balance open-mindedness with not being a
pushover quite well; given this, and that they took initiative, I am
satisfied that they will do a good job designing it for the general
case.

Also, "Now is better than never."

(And before anyone gives the obvious retort, please consider if you
really think it's happening "right now".)


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


Re: hola

2009-12-08 Thread Gabriel Genellina
En Sun, 06 Dec 2009 19:48:28 -0300, Chris Rebert   
escribió:

2009/12/6 franki fuentes cueto :


hola soy un pequeño programador y quiesiera pedirles ayuda para  
programar en

python, no se si me podrian mandar ejemplos para poder empezar, y como
terminarlo para que se ejecute, me entiendes , aver sime ayudan gracias


Esta lista de discusión es en Inglés.

Hay una lista de discusión en Español aqui:
http://listas.aditel.org/listinfo/python-es


Y también:
http://news.gmane.org/gmane.org.user-groups.python.argentina/

--
Gabriel Genellina

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


Re: Trying to set up dictionary to map to functions

2009-12-08 Thread Peter Otten
Randy Belt wrote:

> I have a small test program written trying to set up a dictionary that
> points keys to functions.  It is working.  However, in the process of
> creating it I noticed a weird problem.  The problem is that this IS
> WORKING and I think it shouldn't be.
> 
> ~ Here is the input config file code ~  its called config.file and is
> referenced from the script.
> 
> [MAPS]
> relmap = 1
> posmap = 1
> asnmap = 1
> 
> ~ Here is the code that is working but I feel that it shouldn't be ~
> 
> import ConfigParser
> config = ConfigParser.ConfigParser()
> config.read("config.file")
> sections = config.sections()
> print config.options('MAPS')
> def posmap():
> print "posmap function"
> def relmap():
> print "relmap function"
> def asnmap():
> print "asnmap function"
> for value in config.options('MAPS'):
> value
> map_library = {
>'posmap': posmap()
>   ,'relmap': relmap()
>   ,'asnmap': asnmap()
>   }

I can only guess what you are trying to do here. A dictionary like

d = {"key": func()}

is equivaluent to

value = func()
d = {"key": value}

i. e. you put the function's result into the dict, not the function itself. 
You can verify that for your program -- if you remove one of the three 
entries from the config file it will still invoke all three functions.

If you want the config file to control which functions should be invoke 
change your code as follows:

map_library = {"posmap": posmap, "relmap": relmap, "asnmap": asnmap}
for value in config.options("MAPS"):
map_library[value]()

Peter

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


Re: hola

2009-12-08 Thread Gabriel Genellina
En Sun, 06 Dec 2009 19:48:28 -0300, Chris Rebert   
escribió:

2009/12/6 franki fuentes cueto :


hola soy un pequeño programador y quiesiera pedirles ayuda para  
programar en

python, no se si me podrian mandar ejemplos para poder empezar, y como
terminarlo para que se ejecute, me entiendes , aver sime ayudan gracias


Esta lista de discusión es en Inglés.

Hay una lista de discusión en Español aqui:
http://listas.aditel.org/listinfo/python-es


Y también:
http://news.gmane.org/gmane.org.user-groups.python.argentina/

--
Gabriel Genellina

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


Re: Trying to set up dictionary to map to functions

2009-12-08 Thread Dave Angel

Randy Belt wrote:

Hi,

I have a small test program written trying to set up a dictionary that
points keys to functions.  It is working.  However, in the process of
creating it I noticed a weird problem.  The problem is that this IS WORKING
and I think it shouldn't be.

~ Here is the input config file code ~  its called config.file and is
referenced from the script.

[MAPS]
relmap = 1
posmap = 1
asnmap = 1

~ Here is the code that is working but I feel that it shouldn't be ~

import ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.file")
sections = config.sections()
print config.options('MAPS')
def posmap():
print "posmap function"
def relmap():
print "relmap function"
def asnmap():
print "asnmap function"
for value in config.options('MAPS'):
value
map_library = {
   'posmap': posmap()
  ,'relmap': relmap()
  ,'asnmap': asnmap()
  }

~ Output ~

['posmap', 'relmap', 'asnmap']
posmap function
relmap function
asnmap function

~ The reason I'm confused is because when I change the code (Take away the
map_library dictionary)

import ConfigParser
config = ConfigParser.ConfigParser()
config.read("config.file")
sections = config.sections()
print config.options('MAPS')
def posmap():
print "posmap function"
def relmap():
print "relmap function"
def asnmap():
print "asnmap function"
for value in config.options('MAPS'):
value

~ The output is the following ~

['posmap', 'relmap', 'asnmap']

Is this defaulting to the dictionary and making it work?  In the first set
of code I don't reference the map at all but it still seems to know where to
look?  I am considerably new to Python

  
I don't blame you for being confused.  You're doing two things wrong 
which has the side effect of making it seem to be working.  The reason 
it isn't obvious is that you happen to use the same ordering in your 
config.file as you use initializing map_library.


Your initialization code for map_library is incorrect.  You're actually 
calling each of those three functions during that line, and they each do 
their printing.  However, this has nothing to do with the entries in 
config.options.  If you want to be really surprised, try printing 
map_libary.  It should have values of None for each of the three keys.



I suggest you move the three defs and the map_library initialization 
near the beginning of your script (just after the imports).  Precede it 
with an import sys, and follow it with a sys.exit(0), and run just that 
portion.  You'll see that it prints out the three lines already.  What 
you actually want is not to execute each function, but to create each 
function object.  So change the line as follows:


map_library = {
  'posmap': posmap
 ,'relmap': relmap
 ,'asnmap': asnmap
 }

Note that I don't use parentheses, so the functions are not executing yet.

Now (when you remove the sys.exit()), let's look at your for-loop.  For 
each item in the list, you do exactly nothing.  That's probably where 
you want to be calling the elements of map_library.  And since we moved 
its initialization earlier, we can actually do that, as I'm sure you 
were about to do.


DaveA

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


Re: How to create a docstring for a module?

2009-12-08 Thread Gabriel Genellina

En Sun, 06 Dec 2009 23:51:30 -0300, alex23  escribió:

"Phillip M. Feldman"  wrote:



It does seem as though IPython could be a bit more clever about this.


I disagree. I _like_ that IPython is only reporting on the current
state of the interpreter and not trying to second guess what I meant.


If the user asks for documentation on xyz via "?xyz" and xyz is not
defined, then I'd like to see IPython check for a module named "xyz" and
if it exists, extract and display the docstring.


How would you recommend IPython distinguish between which "xyz" you
meant: the one in site-packages, the one in some package on the python
path, or the one in the folder you're running IPython from?


The "xyz" that would be imported by executing "import xyz", I'd say.
The standard interpreter does that:

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500
 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more in
formation.
py> help("poplib")
Help on module poplib:

NAME
poplib - A POP3 client class.
...

--
Gabriel Genellina

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


Re: Graph library for Python

2009-12-08 Thread Rhodri James
On Tue, 08 Dec 2009 04:28:05 -, geremy condra   
wrote:



On Mon, Dec 7, 2009 at 6:28 PM, M.-A. Lemburg  wrote:



I wasn't thinking of anything clever :-) ...

g = Graph(
 [Node("a"), Node("b"), Node("c")],
 [Edge(Node("a"), Node("b"), "ab"),
  Edge(Node("a"), Node("c"), "ac"),
  Edge(Node("b"), Node("c"), "bc"),
 ])

The main motivation here is to get lists, sets and dicts
play nice together.


Generally, we've tried to discourage people from instantiating
nodes and edges directly, in favor of having them controlled
through the graph. Maybe something along the lines of:

g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b',  
'c')])


?


That works fine for simple cases like this, but starts getting unpleasant  
if you want to initialise with attributes.  Under those circumstances  
using Node and Edge explicitly is much cleaner.  The only extra I'd  
suggest is allowing is_directed as a keyword argument, so you can set the  
default for all edges if you want to.


g = Graph(
nodes=[Node("a", colour="red"),
   Node("b", colour="white"),
   Node("c", colour="blue")],
edges=[Edge("a", "b", "ab", weight=2),
   Edge("a", "c", "ac", is_directed=True),
   Edge("b", "c", "bc", style="dotted")],
is_directed=True)

I could see a use for this tracking a database structure using a constant  
graph, hence all set up in one go for preference.


--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


switch

2009-12-08 Thread hong zhang
List,

Python does not have switch statement. Any other option does similar work?
Thanks for help.

--henry


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


Re: switch

2009-12-08 Thread Chris Rebert
On Tue, Dec 8, 2009 at 5:53 PM, hong zhang  wrote:
> Python does not have switch statement. Any other option does similar work?

Yes, a dictionary with functions as values:
http://simonwillison.net/2004/May/7/switch/

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


Re: Generators.

2009-12-08 Thread Lie Ryan

On 12/9/2009 3:52 AM, Jorge Cardona wrote:

2009/12/8 Lie Ryan:

First, I apologize for rearranging your message out of order.

Theoretically yes, but the semantic of generators in python is they work on
an Iterable (i.e. objects that have __iter__), instead of a Sequence (i.e..
objects that have __getitem__). That means semantically, generators would
call obj.__iter__() and call the iter.__next__() and do its operation for
each items returned by the iterator's iterable's __next__().

The lazy semantic would be hard to fit the current generator model without
changing the semantics of generator to require a Sequence that supports
indexing.



Why?

The goal is add a formal way to separate the transformation of a
generator in those that act on the indexing set and those that act on
the result set.




Well, that's just a pretty convoluted way to reverse the order of the 
operation (hey, why not reverse it altogether?). Nevertheless, it still 
requires a semantic change in that all generators must be able to 
produce the underlying stream, which is not always the case. Take this 
small example:


def foo(x):
i = 0
while True:
yield i
i += 1

What would you propose the .indexing_set to be? Surely not the same as 
.result_set? How would you propose to skip over and islice such 
generator? without executing the in-betweens?



from functools import partial
def f(x):
print("eval: %d"%x)
return x

X = range(10)
g = (partial(f, x) for x in X)

print(list(x() for x in islice(g,0,None,2)))
# # or without partial:
# g = ((lambda: f(x)) for x in X)
# print(list(f() for f in islice(g,0,None,2)))



I keep here the problem in that i shouldn't be able to define the
original generator because the function receive the already defined
generator.


In a default-strict language, you have to explicitly say if you want lazy
execution.


What i want to do is a function that receive any kind of generator and
execute it in several cores (after a fork) and return the data, so, i
can't slice the set X before create the generator.


beware that a generator's contract is to return a valid iterator *once*
only. You can use itertools.tee() to create more generators, but tee built a
list of the results internally.


Oh, yes, i used tee first, but i note then that I wasn't using the
same iterator in  the same process, so, when the fork is made I can
use the initial generator in different processes without this problem,
so tee is not necessary in this case.


You would have to change tee as well:

>>> import itertools
>>> def foo(x):
... print('eval: %s' % x)
... return x + 1
...
>>> l = [1, 2, 3, 4, 5, 6, 7]
>>> it = iter(l)
>>> it = (foo(x) for x in it)
>>> a, b = itertools.tee(it)
>>> # now on to you
>>> it_a = itertools.islice(a, 0, None, 2)
>>> it_b = itertools.islice(b, 1, None, 2)
>>> next(it_b)
eval: 1
eval: 2
3
>>> next(it_b)
eval: 3
eval: 4
5
>>> next(it_b)
eval: 5
eval: 6
7
--
http://mail.python.org/mailman/listinfo/python-list


Re: switch

2009-12-08 Thread Benjamin Kaplan
On Tue, Dec 8, 2009 at 8:53 PM, hong zhang  wrote:
> List,
>
> Python does not have switch statement. Any other option does similar work?
> Thanks for help.
>


Use a dict instead, where the keys are the different cases and the
values are usually callable objects (such as functions)
options = {"a" : do_a, "b",do_b, "c", do_c}

option = "a"

try :
options[option]()
except KeyError :
do_default()





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


Re: switch

2009-12-08 Thread rzzzwilson
On Dec 9, 1:00 pm, Benjamin Kaplan  wrote:
> On Tue, Dec 8, 2009 at 8:53 PM, hong zhang  wrote:
> > List,
>
> > Python does not have switch statement. Any other option does similar work?
> > Thanks for help.
>
> Use a dict instead, where the keys are the different cases and the
> values are usually callable objects (such as functions)
> options = {"a" : do_a, "b",do_b, "c", do_c}
>
> option = "a"
>
> try :
>     options[option]()
> except KeyError :
>     do_default()
>
> > --henry
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>

Even better (well, shorter!):
options = {"a" : do_a, "b",do_b, "c", do_c}
options.get(option, do_default)()

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


Re: switch

2009-12-08 Thread zeph
>
> Even better (well, shorter!):
> options = {"a" : do_a, "b",do_b, "c", do_c}
> options.get(option, do_default)()
>

You can also make it something callable like so, which is a little
more compact if you need to reuse it a lot:

>>> def do_a(x): print "a:", x
...
>>> def do_b(x): print "b:", x
...
>>> def do_c(x): print "c:", x
...
>>> do_something = {"a":do_a, "b":do_b, "c": do_c}.get
>>> do_something('a')(4)
a: 4
>>> do_something('c')(5)
c: 5
>>> do_something

>>> do_something('d')
>>> do_something('d')(5)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'NoneType' object is not callable
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread r0g
Dave Angel wrote:
> 
> 
> r0g wrote:
>> Dennis Lee Bieber wrote:
>>  
>>> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old 
>>> declaimed the following in gmane.comp.python.general:
>>>
>>>
 For Kannada project .txt(not .doc) is used, my requirement is to
 have one
   
>> 
>>  
 In this context, I request you kindly for small python program - to
 make or
   
>>> Excuse me -- you want one of US to supply you with a program that
>>> will be used for YOUR entry to some job site? (At least, that's what I
>>> seem to be finding for "Kannada project")
>>>
>>> 
>>
>>
>> Well it is only a 2 line program and he did ask nicely after all, if you
>> begrudge him it then feel free to not answer, righteous indignation
>> rarely helps anyone.
>>
>> Dear OP...
>>
>> Put the following 2 lines into a file and save it as spacer.py
>>
>> import sys
>> print ' '.join([e for e in open(sys.argv[1], 'r').read()])
>>
>>
>> Then open a terminal window and 'cd' to the same folder you just saved
>> the spacer.py file in. Type...
>>
>> python spacer.py inputfile.txt > outputfile.txt
>>
>> This will run inputfile.txt through the space adding program we have
>> just saved and then 'pipe' the output of that into a new file
>> outputfile.txt
>>
>> Hope this helps,
>>
>>
>> Roger Heathcote.
>>
>>   
> That seems a bit dangerous to give to a beginner at Python, without
> discussing Unicode issues.  If he's in Python 3.x, and if the default
> encoder is ASCII, which it seems to be most places, then he'll quickly
> get a conversion error for some character.  And if it's some other 8 bit
> form, he might not get an error,  but find that a space is inserted
> between two of the bytes of a UTF-8 code.
> 
> DaveA
> 



He said he's running the latest python and fedora, AFAIK the default for
these systems is still the 2 series, not 3.


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


Re: Graph library for Python

2009-12-08 Thread geremy condra
On Tue, Dec 8, 2009 at 8:42 PM, Rhodri James
 wrote:
> On Tue, 08 Dec 2009 04:28:05 -, geremy condra 
> wrote:
>
>> On Mon, Dec 7, 2009 at 6:28 PM, M.-A. Lemburg  wrote:
>
>>> I wasn't thinking of anything clever :-) ...
>>>
>>> g = Graph(
>>>     [Node("a"), Node("b"), Node("c")],
>>>     [Edge(Node("a"), Node("b"), "ab"),
>>>      Edge(Node("a"), Node("c"), "ac"),
>>>      Edge(Node("b"), Node("c"), "bc"),
>>>     ])
>>>
>>> The main motivation here is to get lists, sets and dicts
>>> play nice together.
>>
>> Generally, we've tried to discourage people from instantiating
>> nodes and edges directly, in favor of having them controlled
>> through the graph. Maybe something along the lines of:
>>
>> g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b',
>> 'c')])
>>
>> ?
>
> That works fine for simple cases like this, but starts getting unpleasant if
> you want to initialise with attributes.  Under those circumstances using
> Node and Edge explicitly is much cleaner.  The only extra I'd suggest is
> allowing is_directed as a keyword argument, so you can set the default for
> all edges if you want to.
>
> g = Graph(
>    nodes=[Node("a", colour="red"),
>           Node("b", colour="white"),
>           Node("c", colour="blue")],
>    edges=[Edge("a", "b", "ab", weight=2),
>           Edge("a", "c", "ac", is_directed=True),
>           Edge("b", "c", "bc", style="dotted")],
>    is_directed=True)
>
> I could see a use for this tracking a database structure using a constant
> graph, hence all set up in one go for preference.

While I agree with the rationale, I think we need to find another way.
Aesthetics aside, directly instantiating edges by giving only node names
requires that the edge be aware of what graph its in to provide expected
behavior, which creates a bit of a chicken-or-the-egg dilemma.

How about this: the constructor can take any type of iterable, and
assumes that it follows my earlier format unless it specifies a .items()
method, in which case it takes the values as follows:

g = Graph(
nodes={'a':{'colour':'red'},
   'b':{'colour':'white'},
   'c':{'colour':'blue'}},
edges={('a', 'b'):{'name':'ab', 'weight':2},
   ('a', 'c'):{'name':'ac'},
   ('b', 'c'):{'name':'bc', 'style':'dotted'}}
)

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


Re: switch

2009-12-08 Thread Kee Nethery
I string together a bunch of elif statements to simulate a switch

if foo == True:
blah
elif bar == True:
blah blah
elif bar == False:
blarg
elif 

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


Re: switch

2009-12-08 Thread Asun Friere
On Dec 9, 4:02 pm, Kee Nethery  wrote:
> I string together a bunch of elif statements to simulate a switch
>
> if foo == True:
>         blah
> elif bar == True:
>         blah blah
> elif bar == False:
>         blarg
> elif 


This code is probably symptomatic of poor design. (Not to mention that
your condition tests).  For which reason python has no 'case'
statement and why no decent OO language should.

It is a principle of OO design that "an object should know what to do
itself."  Rather running an object though a series of tests, it is
better to send the object a message, relying on polymorphism or duck-
typing, and deal with any exceptions thrown.

Generally if you find yourself wanting to use a 'case' statement or
writing a series of if/elif which involves more than say, three,
elifs, condsider whether you cannot use a double
dispatch mechanism instead.

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


Re: Brent's variation of a factorization algorithm

2009-12-08 Thread Gabriel Genellina
En Tue, 08 Dec 2009 15:51:29 -0300, MRAB   
escribió:

Gabriel Genellina wrote:

En Fri, 27 Nov 2009 12:36:29 -0300, n00m  escribió:


def gcd(x, y):
if y == 0:
return x
return gcd(y, x % y)

def brent(n): ...
 A better place to publish this code would be the Python Cookbook:  
http://code.activestate.com



An iterative alternative is:

def gcd(x, y):
 while y != 0:
 x, y = y, x % y
 return x


(note that the interesting part was the snipped code, the brent()  
function...)


--
Gabriel Genellina

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


Re: switch

2009-12-08 Thread Steven D'Aprano
On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote:

> I string together a bunch of elif statements to simulate a switch
> 
> if foo == True:
>   blah
> elif bar == True:
>   blah blah
> elif bar == False:
>   blarg
> elif 


Are you sure you want to test for equality with True and False? Generally 
one should write that as:

if foo:
blah
elif bar:
blah blah
elif not bar:
blarg
...




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


Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread Dave Angel

r0g wrote:

Dave Angel wrote:
  

r0g wrote:


Dennis Lee Bieber wrote:
 
  

On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old 
declaimed the following in gmane.comp.python.general:

   


For Kannada project .txt(not .doc) is used, my requirement is to
have one
  
  


 
  

In this context, I request you kindly for small python program - to
make or
  
  

Excuse me -- you want one of US to supply you with a program that
will be used for YOUR entry to some job site? (At least, that's what I
seem to be finding for "Kannada project")




Well it is only a 2 line program and he did ask nicely after all, if you
begrudge him it then feel free to not answer, righteous indignation
rarely helps anyone.

Dear OP...

Put the following 2 lines into a file and save it as spacer.py

import sys
print ' '.join([e for e in open(sys.argv[1], 'r').read()])


Then open a terminal window and 'cd' to the same folder you just saved
the spacer.py file in. Type...

python spacer.py inputfile.txt > outputfile.txt

This will run inputfile.txt through the space adding program we have
just saved and then 'pipe' the output of that into a new file
outputfile.txt

Hope this helps,


Roger Heathcote.

  
  

That seems a bit dangerous to give to a beginner at Python, without
discussing Unicode issues.  If he's in Python 3.x, and if the default
encoder is ASCII, which it seems to be most places, then he'll quickly
get a conversion error for some character.  And if it's some other 8 bit
form, he might not get an error,  but find that a space is inserted
between two of the bytes of a UTF-8 code.

DaveA






He said he's running the latest python and fedora, AFAIK the default for
these systems is still the 2 series, not 3.


Roger.

  
That's even worse.  As far as I can tell, the code will never do what he 
wants in Python 2.x.   The Kannada text file is full of Unicode 
characters in some encoding, and if you ignore the encoding, you'll just 
get garbage.



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


Re: switch

2009-12-08 Thread Steven D'Aprano
On Tue, 08 Dec 2009 21:36:23 -0800, Asun Friere wrote:

> On Dec 9, 4:02 pm, Kee Nethery  wrote:
>> I string together a bunch of elif statements to simulate a switch
>>
>> if foo == True:
>>         blah
>> elif bar == True:
>>         blah blah
>> elif bar == False:
>>         blarg
>> elif 
> 
> 
> This code is probably symptomatic of poor design. (Not to mention that
> your condition tests).  For which reason python has no 'case' statement
> and why no decent OO language should.

That's a provocative statement.



> It is a principle of OO design that "an object should know what to do
> itself."  Rather running an object though a series of tests, it is
> better to send the object a message, relying on polymorphism or duck-
> typing, and deal with any exceptions thrown.

Perhaps that's true, but you'll note that the example given above doesn't 
run a single object through a series of tests, but runs a series of tests 
on DIFFERENT objects, to find the first which matches.

But putting that aside, I find myself wondering how you would deal with 
the following switch-like series of tests.


def print_grades(score):
if not 0 <= score <= 100:
raise ValueError("score must be between 0 and 100")
if score < 50:
print "You have failed."
consider_suspension()
elif score == 50:
print "You have just passed by the skin of your teeth."
elif score < 60:
print "You have scored a D. You need to try harder."
elif score < 70:
print "You have scored a C."
elif score < 80:
print "You have scored a B. Well done."
elif score < 100:
print "Congratulations, you have scored an A."
else:
assert score == 100
print "You have scored a PERFECT 100% SCORE!!!"
if not evidence_of_cheating():
call_newspapers()


Obviously that could, with a non-trivial amount of work, be turned into a 
dictionary dispatch, but is the benefit worth the extra effort?

 
> Generally if you find yourself wanting to use a 'case' statement or
> writing a series of if/elif which involves more than say, three, elifs,
> condsider whether you cannot use a double
> dispatch mechanism instead.

I don't see how a series of tests on a single object is comparable to the 
double-dispatch example given.



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


Re: switch

2009-12-08 Thread Asun Friere
On Dec 9, 5:12 pm, Steven D'Aprano
 wrote:
> On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote:
> > I string together a bunch of elif statements to simulate a switch
>
> > if foo == True:
> >    blah
> > elif bar == True:
> >    blah blah
> > elif bar == False:
> >    blarg
> > elif 
>
> Are you sure you want to test for equality with True and False? Generally
> one should write that as:
>
> if foo:
>     blah
> elif bar:
>     blah blah
> elif not bar:
>     blarg
> ...
>
> --
> Steven

I was going to point that out, but thought it a little OT.  One might
also mention that testing for "if foo is None :" is a special case.
I'm also having a bit of a problem imagining what the subsequent
conditions must be which make testing "elif not bar" subsequent to
testing "elif bar" necessary, but that's just me.

Back OT, one would hope not to encounter python code with a long chain
of elifs like that.  Probably the design should be improved, or where
this would be overkill, use the dictionary trick.

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


Re: python bijection

2009-12-08 Thread Gabriel Genellina
En Sat, 28 Nov 2009 06:30:44 -0300, Joshua Bronson   
escribió:

On Nov 27, 9:36 pm, "Gabriel Genellina" 
wrote:
En Fri, 27 Nov 2009 15:12:36 -0300, Francis Carr  
 escribió:


> After much tinkering, I think I have a simpler solution.  Just make
> the inverse mapping accessible via an attribute, -AND- bind the
> inverse of -THAT- mapping back to the original.  The result is a
> python dict with NO NEW METHODS except this inverse-mapping
> attribute.  I have posted it on code.activestate.com as  href="http://code.activestate.com/recipes/576968/";>Recipe 576968:
> Flipdict -- python dict that also maintains a one-to-one inverse
> mapping



Just a couple of comments:

Instead of:
self._flip = dict.__new__(self.__class__)
I'd write:
self._flip = self.__class__()
unless I'm missing something (but see the next point).


How would this not cause infinite recursion?


That goes under "unless I'm missing something" ;)
You're right, it would cause infinite recursion. Not a good idea...

Also, although Python's GC is able to handle them, I prefer to avoid  
circular references like those between x and x._flip.  Making  
self._flip a weak reference (and dereferencing it in the property)  
should be enough.


If both self._flip and self._flip._flip are weak references, no strong
references to the inverse mapping survive leaving the constructor
scope. Unless I'm missing something, only one of these can be a weak
reference, and then you'd have to do something like this in the
property to prevent "TypeError: FlipDict is not callable":

@property
def flip(self):
try:
# we're an inverse, self._flip is a weak reference
return self._flip()
except TypeError:
# we're a forward mapping, self._flip is a strong
reference
return self._flip


Yes - although I'd explicitely test for a weakref object:

def flip(self):
_flip = self._flip
if isinstance(_filp, weakref.ref):
return _flip()
return _flip

and probably all those internal references to self._flip should become  
self.flip too; I've not tested the code but I think it *should* work...


--
Gabriel Genellina

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


Re: Request for py program to insert space between two characters and saved as text?

2009-12-08 Thread r0g
Dave Angel wrote:
> r0g wrote:
>> Dave Angel wrote:
>>  
>>> r0g wrote:
>>>
 Dennis Lee Bieber wrote:
  
  
> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old 
> declaimed the following in gmane.comp.python.general:
>
>   
>> For Kannada project .txt(not .doc) is used, my requirement is to
>> have one
>> 
 
  
  
>> In this context, I request you kindly for small python program - to
>> make or
>> 
> Excuse me -- you want one of US to supply you with a program that
> will be used for YOUR entry to some job site? (At least, that's what I
> seem to be finding for "Kannada project")
>
> 
 Well it is only a 2 line program and he did ask nicely after all, if
 you
 begrudge him it then feel free to not answer, righteous indignation
 rarely helps anyone.

 Dear OP...

 Put the following 2 lines into a file and save it as spacer.py

 import sys
 print ' '.join([e for e in open(sys.argv[1], 'r').read()])


 Then open a terminal window and 'cd' to the same folder you just saved
 the spacer.py file in. Type...

 python spacer.py inputfile.txt > outputfile.txt

 This will run inputfile.txt through the space adding program we have
 just saved and then 'pipe' the output of that into a new file
 outputfile.txt

 Hope this helps,


 Roger Heathcote.

 
>>> That seems a bit dangerous to give to a beginner at Python, without
>>> discussing Unicode issues.  If he's in Python 3.x, and if the default
>>> encoder is ASCII, which it seems to be most places, then he'll quickly
>>> get a conversion error for some character.  And if it's some other 8 bit
>>> form, he might not get an error,  but find that a space is inserted
>>> between two of the bytes of a UTF-8 code.
>>>
>>> DaveA
>>>
>>> 
>>
>>
>>
>> He said he's running the latest python and fedora, AFAIK the default for
>> these systems is still the 2 series, not 3.
>>
>>
>> Roger.
>>
>>   
> That's even worse.  As far as I can tell, the code will never do what he
> wants in Python 2.x.   The Kannada text file is full of Unicode
> characters in some encoding, and if you ignore the encoding, you'll just
> get garbage.
> 
> 

Ah, fair enough. In my defence though I never saw the original post or
this kannada.txt file as my newsserver is not so much with the
reliability. I guess it's naive to assume an english .txt file is going
to be in ASCII these days eh?

I've yet to try python 3 yet either, this whole Unicode thing looks like
it could be a total nightmare! :(

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