Beautifulsoup html parsing - nested tags
Hi all, I am trying to parse some html string with BeatifulSoup. The string is, Tax Base Amount rtables=soup.findAll(re.compile('table$')) The rtables is, [ Tax Base Amount , ] The tr inside the blocktable are appearing inside the table, while blocktable contains nothing. Is there any way, I can get the tr in the right place (inside blocktable) ? -- Regards, S.Selvam SG E-ndicus Infotech Pvt Ltd. http://e-ndicus.com/ " I am because we are " -- http://mail.python.org/mailman/listinfo/python-list
Re: Beautifulsoup html parsing - nested tags
On Wed, Jan 5, 2011 at 2:58 PM, Selvam wrote: > Hi all, > > I am trying to parse some html string with BeatifulSoup. > > The string is, > > > > > > > > Tax > > Base > > Amount > > > > > > > > rtables=soup.findAll(re.compile('table$')) > > The rtables is, > > [ > > > > > > Tax > > Base > > Amount > > , > ] > > > > The tr inside the blocktable are appearing inside the table, while > blocktable contains nothing. > > Is there any way, I can get the tr in the right place (inside blocktable) ? > > -- > Regards, > S.Selvam > SG E-ndicus Infotech Pvt Ltd. > http://e-ndicus.com/ > > " I am because we are " > Replying to myself, BeautifulSoup.BeautifulSoup.NESTABLE_TABLE_TAGS['tr'].append('blocktable') adding this, solved the issue. -- Regards, S.Selvam SG E-ndicus Infotech Pvt Ltd. http://e-ndicus.com/ " I am because we are " -- http://mail.python.org/mailman/listinfo/python-list
Graphing API,
Is there a graphing API, someone suggests? -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphing API,
you can check pywebgraph On Wed, Jan 5, 2011 at 3:49 PM, Slie wrote: > Is there a graphing API, someone suggests? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Nitin Pawar -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Jan 5, 6:48 pm, "Octavian Rasnita" wrote: > From: "Tomasz Rola" > > > On Tue, 4 Jan 2011, Dan M wrote: > > >> As to choice between Python and PHP, I would say learn anything but PHP. > >> Even Perl has fewer tentacles than PHP. > > > However, the quality of code depends heavily on who writes it. My > > impression is that more folks of "I did it and it works so it is good, > > right?" attitude can be found among Perl/PHP crowd (compared to Python or > > Ruby or...). The reason is probably the "easyness" of those languages > > (mostly because of tons of readymade code on the net) which - wrongly - > > suggests they are already "there", no need to learn anymore. > > Yes you are right. Perl is much flexible than all other languages and there > was written a lot of bad code in the past that can now be found on the net, > beeing very hard for a newbie to find only the good examples and tutorials. > > But Perl offers many helpful modules for testing the apps so for good > programmers there is not true the idea of "it works so it's ok". > > Usually we compare the languages although we always think to all aditional > modules and libraries we can use with them for creating apps. > Thinking this way, Perl is better than Python for creating web apps, because > Catalyst framework is more advanced than the frameworks for Python and it is > more flexible even than Ruby on Rails, DBIx::Class ORM is a very advanced > ORM and a very clean one and Perl web apps can use strong templating systems > and form processors, unicode is a native code for Perl for a long time and > so on. > > So how good is the language depends on what you need to use it for. > > (But I hope that this won't start a language war, because I have just done > the same on a Perl mailing list telling about some Perl disadvantages > towards Python :) > > Octavian My two cents, I am understanding python far better by learning scheme. Didn't intentionally set out to achieve that as a goal just a by product. An excelent resource http://htdp.org and using the racket scheme ide(as much of an ide as idle), simple thorough well explained concepts via worked examples and a very encouraging and enthusiastic mail group, much like this list. I would so love a book like that for python but after i complete htdp I may not need it. Regards Sayth -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Tue, 04 Jan 2011 12:20:42 -0800, Google Poster wrote: > The indentation-as-block is unique, Not at all. It's also used in occam, Miranda, Haskell and F#. -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphing API,
On Wed, Jan 5, 2011 at 2:19 AM, Slie wrote: > Is there a graphing API, someone suggests? matplotlib: http://matplotlib.sourceforge.net/ Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem inserting an element where I want it using lxml
On 01/05/2011 02:47 AM, Stefan Behnel wrote: ... Looks trivial to me. ;) ... ".iter()" gives you a recursive iterator that will also yield the "something" Element in your case, thus the incorrect counting. You only want the children, so you should iterate over the Element itself. Thanks Stephan. I went home and went to sleep and woke up in the middle of the night and thought, wait a minute, iter() is giving me a depth first list of elements but insert() is indexing children of the parent. I think I must have been up too late. There is an .index() method on Elements that does what you want to achieve here. However, the right way to do it is to use ".addnext()". http://codespeak.net/lxml/api/lxml.etree._Element-class.html Stefan Those are exactly the functions I wanted. I didn't see them (and still don't) in the Python ElementTree documentation and thought I had to use parent.insert(). Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem inserting an element where I want it using lxml
On 01/05/2011 01:16 AM, Josh English wrote: Here's a trimmed down version of how I did this (using ElementTree standalone, but the API should be the same) This is from a class definition and the _elem attribute is a link to an ElementTree.Element object. ... def _add_elem(self, tagName, text, attrib ={}): """_add_elem(tagName, text, attrib={}) Adds a child element in the appropriate place in the tree. Raises an IndexError if the checker does not allow an addition child of tagName. """ last_child = None for child in self._elem.findall('.//%s' % tagName): last_child = child if last_child is None: new_child = ET.SubElement(self._elem, tagName, attrib) else: new_child = ET.Element(tagName, attrib) self._elem.insert(self._elem._children.index(last_child)+1, new_child) new_child.text=str(text) return new_child I don't think you need to count the instances of the bingo node (unless you want to prevent too many from being added in). Josh Thanks Josh. It looks like lxml adds some incredibly useful extensions to ElementTree that I will use. See Stephan's reply. Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On 2011-01-04 12:53:02 -0800, Alan Meyer said: I confess that I haven't used PHP so someone correct me if I'm wrong. [snip] +1 You're pretty much on the ball with your description. I might summarize it as: PHP (PHP: Hypertext Processor) is a templating language with a significant enough standard library for aspirations of general-purpose scripting. Python is a general-purpose scripting language with numerous templating languages, let alone the terrifyingly large standard library. ;) Yes, PHP has templating language syntaxes like Smarty, but you're running a template parser within another template parser... A fairly common sarcastic quote is: "You aren't a real Python programmer until you write your own [coroutine framework | web framework | templating language | ...]!" I've done all three, and this probably does not make me a good person. ;) The coroutine framework was a hack to see how they work through experimentation, but I'm quite proud of the web framework and templating system! :D - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Which coding style is better? public API or private method inside class definition
On Jan 4, 8:46 pm, Inyeol wrote: > For example: I'm writing simple class: > > class Numbers: > def __init__(self, numbers): > self._numbers = numbers > def get_all(self): > for number in self._numbers: > yield number > > If I want to add another method for yielding even numbers only, I may > use: > > def get_even(self): > for numbers in self._numbers: > if numbers % 2 == 0: > yield number > > or, I can use public method 'get_all' instead of using private > attribute '_numbers', like: > > def get_even(self): > for numbers in self.get_all(): > if numbers % 2 == 0: > yield number > > Which coding style do you prefer? I'm more toward public API way, > since it requires less code change if I refactor private data > structure later. > Plz give pros and cons of these. Using Public API makes it easier to subclass, if you want to redefine the meaning of "all" somehow. The main reason to avoid Public API is to get performance benefits (most Python built-in classes access the internal structure directly for this reason). There are occasions where a function really needs to access the internals and not the "visible" value. Also, in Python it's reasonable to consider an instance variable to be part of the public interface of a class, because backwards- incompatible changes can be avoided using properties. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
Nobody wrote: > On Tue, 04 Jan 2011 12:20:42 -0800, Google Poster wrote: > >> The indentation-as-block is unique, > > Not at all. It's also used in occam, Miranda, Haskell and F#. > Also Yaml. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphing API,
On 2011-01-05, Slie wrote: > Is there a graphing API, someone suggests? You should check the archives, variations of this question get asked a lot. I use GNUplot to do my graphing. I simply pipe it commands and data through the subprocess module; but, there are libraries available for interacting with it. Posts here also indicate that Google offers a web service based API for generating graphs. I have never actually used it; but, the documentation seems to be clear enough to get it working without too much trouble. -- http://mail.python.org/mailman/listinfo/python-list
why generator assigned to slice?
hi!!! i found this when i read the source of a program in python: self.__chunks[start:end] = (chunk for i in xrange(start, end)) and also this: self.__lines[line:line] = (None for i in xrange(count)) what utility has to assign a generator to a slice??? ?the *final result* isn't the same as this?: self.__chunks[start:end] = [chunk for i in xrange(start, end)] self.__chunks[line:line] = [None for i in xrange(count)] thanks!!! ana p.d. excuse my english -- http://mail.python.org/mailman/listinfo/python-list
Re: why generator assigned to slice?
ana sanchez wrote: > i found this when i read the source of a program in python: > > self.__chunks[start:end] = (chunk for i in xrange(start, end)) > what utility has to assign a generator to a slice??? ?the *final > result* isn't the same as this?: > > self.__chunks[start:end] = [chunk for i in xrange(start, end)] Whoever used the first variant probably was hoping that it was either faster or used less peak memory. I think the latter is wrong, and the former can easily be checked: $ python -m timeit -s'chunk = "yadda"; chunks = range(100); start = 20; end = 50' 'chunks[start:end] = (chunk for i in xrange(start, end))' 10 loops, best of 3: 9.02 usec per loop $ python -m timeit -s'chunk = "yadda"; chunks = range(100); start = 20; end = 50' 'chunks[start:end] = [chunk for i in xrange(start, end)]' 10 loops, best of 3: 4.16 usec per loop $ python -m timeit -s'chunk = "yadda"; chunks = range(100); start = 20; end = 50' 'chunks[start:end] = [chunk]*(end-start)' 100 loops, best of 3: 1.02 usec per loop -- http://mail.python.org/mailman/listinfo/python-list
dictionary as attribute of a class...
Hallo list, here again I have a problem whose solution might be very obvious, but I really cannot see it: I have a class having as attribute a dictionary whose keys are names and values are instance of another class. This second class has in turn as an attribute a dictionary. I want a function of the first class that can change value of one of the second class instance's dictionary. however I cannot do it without modifying this attribute for ALL the instance of the second class contained in the first class' dictionary. What I'm doing wrong? the code: ### ###can i change a dictionary attribute of an instantated object without affectin all the instances of that object? class mistClass(): def __init__(self,name,cDict={}): print 'mistClass ',name,' Init' self._name=name self._cDict=cDict def setName(self,n): self._name=n def getName(self): return self._name ##def setDict(self,one,two): ##self._cDict['one']=one ##self._cDict['two']=two def setDict(self,listK,listV): assert len(listK)==len(listV) for k,v in zip(listK,listV): self._cDict[k]=v def getDict(self): return self._cDict class mistClassContainer(): def __init__(self,name,dict_of_mistclass={}): print 'init mistClassContainer ',name self._name=name self._DOM=dict_of_mistclass def add_mistclass(self,mc): for el in mc: self._DOM[el]=mistClass(el) ##def mod_mistclasscDict(self,mc,one,two): ##self._DOM[mc].setDict(one,two) def mod_mistclasscDict(self,mc,lK,lV): self._DOM[mc].setDict(lK,lV) a=mistClassContainer('firsmistclasscontainer') a.add_mistclass(['mc1','mc2','mc3','mc4','mc5','mc6']) print 'before modification' for el in a._DOM.iterkeys(): print a._DOM[el].getDict() print a._DOM[el].getName() a.mod_mistclasscDict('mc1',['one','two'],['modone','modtwo']) print 'after modification' for el in a._DOM.iterkeys(): print a._DOM[el].getDict() print a._DOM[el].getName() b=mistClass('mc7') print b.getDict() print b.getName() b.setName('modified name') b.getName() for el in a._DOM.iterkeys(): print a._DOM[el].getName() -- http://mail.python.org/mailman/listinfo/python-list
Re: Which coding style is better? public API or private method inside class definition
Inyeol wrote: For example: I'm writing simple class: class Numbers: def __init__(self, numbers): self._numbers = numbers def get_all(self): for number in self._numbers: yield number If I want to add another method for yielding even numbers only, I may use: def get_even(self): for numbers in self._numbers: if numbers % 2 == 0: yield number or, I can use public method 'get_all' instead of using private attribute '_numbers', like: def get_even(self): for numbers in self.get_all(): if numbers % 2 == 0: yield number Which coding style do you prefer? I'm more toward public API way, since it requires less code change if I refactor private data structure later. Plz give pros and cons of these. - Unless you already know that you'll need to refactor the structure later, there's no need to anticipate => unnecessary optimization - Using public API deos not necessarily make refactoring easier. Let me explain, public APIs are meant to be called by external objects. These APIs may need to do some things that internal computing doesn't. For instance, let's say you add a logging statement in the get_all() method. Every call triggers a log entry. Does the get_even method want to log this call ? Maybe not. In that particular case, using the internal strucutre is preferable. - If you agree to the statement that readability > edition, then you should care more about writing clean and concise code, than refactorable ( :D ) code. Using self._numbers raises less questions to the reader. Though I admit that question raised by get_all are answered in 5 seconds (the question being 'If he used an method instead of _numbers, this method must do something special') - In fine, it doesn't really matter in the example you gave above. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary as attribute of a class...
On Wed, Jan 5, 2011 at 10:07 AM, tinauser wrote: > Hallo list, > here again I have a problem whose solution might be very obvious, but > I really cannot see it: > I have a class having as attribute a dictionary whose keys are names > and values are instance of another class. > This second class has in turn as an attribute a dictionary. > I want a function of the first class that can change value of one of > the second class instance's dictionary. > however I cannot do it without modifying this attribute for ALL the > instance of the second class contained in the first class' dictionary. > What I'm doing wrong? > This is one of the biggest gotchas in Python. Default arguments are only evaluated *once*, when the function/method is declared. Not every time the function is called. Every instance of mistClass that didn't specify a separate cDict gets the same object as its cDict. The solution is to use a sentinel value (either None or a single object and use an "is" comparison) and create a new dict in the constructor if the default argument is still the sentinel. > class mistClass(): > def __init__(self,name,cDict={}): > print 'mistClass ',name,' Init' > self._name=name > self._cDict=cDict > should be changed to sentinel = object() class mistClass : def __init__(self, name, cDict=sentinel) : print 'mistClass ',name,' Init' self._name=name if cDict is not sentinel : self._cDict=cDict else : self._cDict = {} > class mistClassContainer(): > def __init__(self,name,dict_of_mistclass={}): > print 'init mistClassContainer ',name > self._name=name > self._DOM=dict_of_mistclass > and do the same thing with this one. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On 2011-01-05, Tomasz Rola wrote: > On Tue, 4 Jan 2011, Roy Smith wrote: >> Alan Meyer wrote: >>> On 1/4/2011 4:22 PM, Google Poster wrote: >>> The syntax reminds me of Lots of Interspersed Silly Parentheses (L.I.S.P.), but without the parentheses. >>> >>> I haven't heard that version before. The one I heard was: >>> >>> "Lots of Irritating Single Parentheses". >> >> Long Involved Stupid Parentheses. > > Heh. One day, guys, when you have nothing better to do, try writing a > parser for Lisp-like language (Common Lisp, Scheme, whatever). After that, > do the same with some other language of your preference (Python, Java, > whatever). Compare time and code spent... I've heard that justification many times, but I think it's 200% specious. 1) How often is a compiler for language X written? 2) How often is source code written in language X? 3) How often is that source code in language X read/modified? If you compare those numbers you'll realize that optimizing for case 1 at the expense of cases 2 & 3 is just plain stupid. Perhaps there is somebody on the planet who finds Lisp as easy to read/modify as Python, but I've never met him/her and never have you... Optimizing a language for the ease of the compiler writer is like saying, sure, that car is expensive to buy, expensive to run, doesn't work well, and tends to kill a lot of people, but it took less time to design! -- Grant Edwards grant.b.edwardsYow! I know things about at TROY DONAHUE that can't gmail.comeven be PRINTED!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Wed, 5 Jan 2011, flebber wrote: > My two cents, I am understanding python far better by learning scheme. > Didn't intentionally set out to achieve that as a goal just a by > product. An excelent resource http://htdp.org and using the racket > scheme ide(as much of an ide as idle), simple thorough well explained > concepts via worked examples and a very encouraging and enthusiastic > mail group, much like this list. > > I would so love a book like that for python but after i complete htdp > I may not need it. Agreed. I freezed my Racket usage while it was called DrScheme but I keep my eye on it ever since. It is really nice and well designed environment. It took me by a storm, which I cannot say about Idle ;-) . I also agree that every Python programmer could gain something valuable by at least trying it, as well as reading their docs and mailing list for a while. Or every programmer regardless of his/her current language. HTDP is interesting book, pity I couldn't read it when it might have made a bigger difference to my development. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_r...@bigfoot.com ** -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary as attribute of a class...
tinauser wrote: > Hallo list, > here again I have a problem whose solution might be very obvious, but > I really cannot see it: > I have a class having as attribute a dictionary whose keys are names > and values are instance of another class. > This second class has in turn as an attribute a dictionary. > I want a function of the first class that can change value of one of > the second class instance's dictionary. > however I cannot do it without modifying this attribute for ALL the > instance of the second class contained in the first class' dictionary. > What I'm doing wrong? > > the code: > > ### > ###can i change a dictionary attribute of an instantated object > without affectin all the instances of that object? > > class mistClass(): > def __init__(self,name,cDict={}): When you don't provide a cDict argument the default is used which is the same for every instance. Change the above to def __init__(self, name, cDict=None): if cDict is None: cDict = {} > class mistClassContainer(): > def __init__(self,name,dict_of_mistclass={}): Same here. > def setName(self,n): > self._name=n > > def getName(self): > return self._name Python has properties, so you don't need this just-in-case getter/setter nonsense. > for k,v in zip(listK,listV): > self._cDict[k]=v Make that self._cDict.update(zip(listK, listV)) By the way, not everyone loves Hungarian notation... -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary as attribute of a class...
On Jan 5, 4:34 pm, Peter Otten <__pete...@web.de> wrote: > tinauser wrote: > > Hallo list, > > here again I have a problem whose solution might be very obvious, but > > I really cannot see it: > > I have a class having as attribute a dictionary whose keys are names > > and values are instance of another class. > > This second class has in turn as an attribute a dictionary. > > I want a function of the first class that can change value of one of > > the second class instance's dictionary. > > however I cannot do it without modifying this attribute for ALL the > > instance of the second class contained in the first class' dictionary. > > What I'm doing wrong? > > > the code: > > > ### > > ###can i change a dictionary attribute of an instantated object > > without affectin all the instances of that object? > > > class mistClass(): > > def __init__(self,name,cDict={}): > > When you don't provide a cDict argument the default is used which is the > same for every instance. Change the above to > > def __init__(self, name, cDict=None): > if cDict is None: > cDict = {} > > > class mistClassContainer(): > > def __init__(self,name,dict_of_mistclass={}): > > Same here. > > > def setName(self,n): > > self._name=n > > > def getName(self): > > return self._name > > Python has properties, so you don't need this just-in-case getter/setter > nonsense. > > > for k,v in zip(listK,listV): > > self._cDict[k]=v > > Make that > > self._cDict.update(zip(listK, listV)) > > By the way, not everyone loves Hungarian notation... Thanks both for the reply, I'll take some time to digest so to avoid further error in the future.Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On 2011-01-05, Grant Edwards wrote: > Optimizing a language for the ease of the compiler writer is > like saying, sure, that car is expensive to buy, expensive to > run, doesn't work well, and tends to kill a lot of people, but > it took less time to design! A simple to parse syntax has non-trivial benefits. It makes a macro system feasible. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Creating custom Python objects from C code
I have read through all the documentation here: http://docs.python.org/extending/newtypes.html I have not seen any documentation anywhere else explaining how to create custom defined objects from C. I have this need to create custom objects from C and pass them as arguments to a function call. Question 1: how am I to create those objects from C code? The other thing I would like to know is how I can create helper functions in my extension so they can be created and manipulated easily. I am thinking along the lines of the built-in helper functions PyList_New and PyList_Append. Once I have an answer to question 1, the problem won't be creating the helper functions, but making them available from something built with distutils. To use the builtin python functions from C I need to link against python27.lib but when I create my own package using distutils it creates dll or pyd files. Question 2: How do I make C helper functions that are part of my extension available to other C projects in the same way that PyList_*, PyString_*, PyInt_* functions are available? Is it possible to have distutils make a .lib file for me? Thanks, ~Eric -- http://mail.python.org/mailman/listinfo/python-list
Re: Which coding style is better? public API or private method inside class definition
On 2011-01-05, Inyeol wrote: > For example: I'm writing simple class: > > class Numbers: > def __init__(self, numbers): > self._numbers = numbers > def get_all(self): > for number in self._numbers: > yield number > > If I want to add another method for yielding even numbers only, > I may use: > > def get_even(self): > for numbers in self._numbers: > if numbers % 2 == 0: > yield number > > or, I can use public method 'get_all' instead of using private > attribute '_numbers', like: > > def get_even(self): > for numbers in self.get_all(): > if numbers % 2 == 0: > yield number > > Which coding style do you prefer? I'm more toward public API > way, since it requires less code change if I refactor private > data structure later. Plz give pros and cons of these. Decoupling a member function from its own internal state would be of little benefit. However, decoupling an interface from its implementation can be a good idea. Python provides inheritance and the NotImplmented exception to help with that. Duck-typing is another popular approach. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating custom Python objects from C code
On Wed, 5 Jan 2011 11:27:02 -0500 Eric Frederich wrote: > I have read through all the documentation here: > > http://docs.python.org/extending/newtypes.html > > I have not seen any documentation anywhere else explaining how to > create custom defined objects from C. > I have this need to create custom objects from C and pass them as > arguments to a function call. What do you mean? Create instances of a type defined in Python code? The C API is not very different from Python-land. When you want to instantiate a type, just call that type (as a PyObject pointer) with the right arguments (using PyObject_Call() and friends). Whether that type has been defined in C or in Python does not make a difference. > Question 2: How do I make C helper functions that are part of my > extension available to other C projects in the same way that PyList_*, > PyString_*, PyInt_* functions are available? > Is it possible to have distutils make a .lib file for me? I don't know. I'd say "probably" :S Otherwise you can use the PyCapsule system, but that seems quite a bit more involved: http://docs.python.org/c-api/capsule.html Regards Antoine. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Wed, 5 Jan 2011, Grant Edwards wrote: > On 2011-01-05, Tomasz Rola wrote: > > On Tue, 4 Jan 2011, Roy Smith wrote: > >> Alan Meyer wrote: > >>> On 1/4/2011 4:22 PM, Google Poster wrote: > >>> > The syntax reminds me of Lots of Interspersed Silly Parentheses > (L.I.S.P.), but without the parentheses. > >>> > >>> I haven't heard that version before. The one I heard was: > >>> > >>> "Lots of Irritating Single Parentheses". > >> > >> Long Involved Stupid Parentheses. > > > > Heh. One day, guys, when you have nothing better to do, try writing a > > parser for Lisp-like language (Common Lisp, Scheme, whatever). After that, > > do the same with some other language of your preference (Python, Java, > > whatever). Compare time and code spent... > > I've heard that justification many times, but I think it's 200% > specious. > > 1) How often is a compiler for language X written? > > 2) How often is source code written in language X? > > 3) How often is that source code in language X read/modified? > > If you compare those numbers you'll realize that optimizing for case 1 > at the expense of cases 2 & 3 is just plain stupid. You are right here. OTOH, a parser or even a compiler are just nice examples of non-trivial code. IMHO, the more non-trivial task one is trying to perform with a language, the more one appreciates language features that seem nonsense for less trivial programs. While in theory one can do the same job with a shovel and an excavator, in practice one should use the right tool depending on the job. Trying to get a car from a snowdrift with excavator requires a lot of attention and caution. It is easy (even if tiring) task for a man with a shovel. So one could extrapolate from this, that using excavator is ridiculous compared to using shovel. However, building dams or digging mile-long trenches with a shovel is not only ridicule but a sign of bad planning or desperation. And maybe even an incompetence. Now, how often they are building dams, trenches and other nontrivial constructions? I would hypothesise that in a society well developed, this happens quite often. Maybe even once every two days. The truth is, once you have an excavator, you don't shy away from using it and you more often than not are open for doing non-trivial assignments. > Perhaps there is > somebody on the planet who finds Lisp as easy to read/modify as > Python, but I've never met him/her and never have you... Here you are wrong. I meet the guy every day in a mirror. Now you have met him, too. I doubt, however, that I am so extraordinary as to be just one on the whole planet. > Optimizing a language for the ease of the compiler writer is like > saying, sure, that car is expensive to buy, expensive to run, doesn't > work well, and tends to kill a lot of people, but it took less time to > design! I guess every compiled language designed so far has been somewhat optimised for compilation by it's designers. If you say that some language, like Common Lisp, had been optimised for compiler at the expense of human programmer, I disagree. I find programing in CL to be nice experience, maybe even a refreshing one. From what I have read about Lisp history so far, your claims don't match the facts (at least facts as I know them). True, it requires some learning. AFAIK, nobody has to learn, so it is purely voluntary effort. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_r...@bigfoot.com ** -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Tue, 4 Jan 2011, Roy Smith wrote: > There. Now that I've tossed some gasoline on the language wars fire, > I'll duck and run in the other direction :-) May I suggest a better strategy? Run first, duck next :-). Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_r...@bigfoot.com ** -- http://mail.python.org/mailman/listinfo/python-list
Re: Which coding style is better? public API or private method inside class definition
-BEGIN PGP SIGNED MESSAGE- Hash: SHA256 Sorry for OT, but this is actually a question of mine > if numbers % 2 == 0: wouldn't the following be faster? > if numbers & 1 == 0: JK -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.10 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iF4EAREIAAYFAk0ko1oACgkQfD3PECtxdkWzPAD+LD32NzjjDm8gb8qVFydIT693 ORuhRaYZOriaf+36/yMBAIREiarQAJ2ZYX8NPyHS2ns22PkEEEAkC98OYf1CkhwK =tg7G -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
RE: Qt with PyDev
Seen both, but do I need to install the binaries or add a link in Pydev to PySide source-code? Date: Tue, 4 Jan 2011 07:09:53 -0800 From: gher...@islandtraining.com To: python-list@python.org Subject: Re: Qt with PyDev On 01/04/2011 12:00 AM, RP Khare wrote: I installed Aptana PyDev plugin to Aptana Studio 3 Beta. I want to write my first GUI application using Python and I want to use Qt for it. How to integrate Qt into PyDev, or is there any other alternative IDE to work with Qt? element Font font-family font-size font-style font-variant font-weight letter-spacing line-height text-decoration text-align text-indent text-transform white-space word-spacing color Background bg-attachment bg-color bg-image bg-position bg-repeat Box width height border-top border-right border-bottom border-left margin padding max-height min-height max-width min-width outline-color outline-style outline-width Positioning position top bottom right left float display clear z-index List list-style-image list-style-type list-style-position Table vertical-align border-collapse border-spacing caption-side empty-cells table-layout Effects text-shadow -webkit-box-shadow border-radius Other overflow cursor visibility ... Rohit See either of these packages: PyQt: http://qt.nokia.com/products/ PySide: http://www.p
Re: Which coding style is better? public API or private method inside class definition
Jacek Krysztofik wrote: > Sorry for OT, but this is actually a question of mine >> if numbers % 2 == 0: > wouldn't the following be faster? >> if numbers & 1 == 0: You can answer that and similar questions yourself with the timeit module: $ python -m timeit -s'm, n = 1234, 1235' 'm % 2 == 0; n % 2 == 0' 100 loops, best of 3: 0.377 usec per loop $ python -m timeit -s'm, n = 1234, 1235' 'm & 1 == 0; n & 1 == 0' 100 loops, best of 3: 0.298 usec per loop So yes, a binary and seems to be faster. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On 05/01/2011 10:44, Nobody wrote: On Tue, 04 Jan 2011 12:20:42 -0800, Google Poster wrote: The indentation-as-block is unique, Not at all. It's also used in occam, Miranda, Haskell and F#. Don't forget about ABC. -- http://mail.python.org/mailman/listinfo/python-list
Re: RE: Qt with PyDev
On Jan 5, 2011 12:15 PM, "Rohit Coder" wrote: > > Seen both, but do I need to install the binaries or add a link in Pydev to PySide source-code? > You need to install the binaries. Doing that will put the pyside libraries in a location where Python and Pydev can find them automatically. > > Date: Tue, 4 Jan 2011 07:09:53 -0800 > From: gher...@islandtraining.com > To: python-list@python.org > Subject: Re: Qt with PyDev > > > On 01/04/2011 12:00 AM, RP Khare wrote: >> >> I installed Aptana PyDev plugin to Aptana Studio 3 Beta. I want to write my first GUI application using Python and I want to use Qt for it. How to integrate Qt into PyDev, or is there any other alternative IDE to work with Qt? >> element >> Font >> font-family >> font-size >> font-style >> font-variant >> font-weight >> letter-spacing >> line-height >> text-decoration >> text-align >> text-indent >> text-transform >> white-space >> word-spacing >> color >> Background >> bg-attachment >> bg-color >> bg-image >> bg-position >> bg-repeat >> Box >> width >> height >> border-top >> border-right >> border-bottom >> border-left >> margin >> padding >> max-height >> min-height >> max-width >> min-width >> outline-color >> outline-style >> outline-width >> Positioning >> position >> top >> bottom >> right >> left >> float >> display >> clear >> z-index >> List >> list-style-image >> list-style-type >> list-style-position >> Table >> vertical-align >> border-collapse >> border-spacing >> caption-side >> empty-cells >> table-layout >> Effects >> text-shadow >> -webkit-box-shadow >> border-radius >> Other >> overflow >> cursor >> visibility >> >> ... >> Rohit > > > See either of these packages: > PyQt: http://qt.nokia.com/products/ > PySide: http://www.pyside.org/ > > Either one should work with PyDev. > > Gary Herron > > > > -- http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Which coding style is better? public API or private method inside class definition
Inyeol writes: > def get_all(self): > for number in self._numbers: > yield number I think def get_all(self): return iter(self._numbers) is more direct. -- http://mail.python.org/mailman/listinfo/python-list
Help with code-lists and strings
Dear all, You folks will probably hear from me more often in the next few months. I hope some of you have time help me on occassion. Actually, a volunteer mentor would be greatly appreciated:) I am learning python and came across an excercise where i need to use lists to strip words from a sentence; starting with those containing one or more uppercase letters, followed by words with lower case letters. When I try, i get words in the order they were written:(* *I tried if statements, but unsuccessful. This has to be very easy to you experts, but I am clueless ( still rocket science to me) :( #Below is my shot at it: s=input("Write a sentence: ") list=s.strip().split() for word in list: list2 = (word.isupper() or word.istitle()) print (word) else print (word) -- http://mail.python.org/mailman/listinfo/python-list
Re: Just Starting in on programming
http://www.openbookproject.net/thinkCSpy/ ? -- http://mail.python.org/mailman/listinfo/python-list
RE: Help with code-lists and strings
You take a sentence and break it up into words, storing it in a list named "list". Then, for each word in the list, you set list2 to a boolean value of true or false, depending on the result of isupper() and istitle(). Note that the variable "list2" does not refer to a list. It refers to whatever the result of the "or" operation is. Finally, you print out the word from the original, unordered list. You never do anything at all with list2. At least, that what I think is happening, but I am by no means a Python expert. Here's a suggestion: Try writing out what you want to do in plain English, but formatted sort of like a Python script would be. (This is generally called "pseudocode". It looks like a computer language, but it isn't.) Once you've got that, use it as a framework to write your Python code. Good luck! RobR From: python-list-bounces+rob.richardson=rad-con@python.org [mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of Cathy James Sent: Wednesday, January 05, 2011 12:57 PM To: python-list@python.org Subject: Help with code-lists and strings Dear all, You folks will probably hear from me more often in the next few months. I hope some of you have time help me on occassion. Actually, a volunteer mentor would be greatly appreciated:) I am learning python and came across an excercise where i need to use lists to strip words from a sentence; starting with those containing one or more uppercase letters, followed by words with lower case letters. When I try, i get words in the order they were written:( I tried if statements, but unsuccessful. This has to be very easy to you experts, but I am clueless ( still rocket science to me) :( #Below is my shot at it: s=input("Write a sentence: ") list=s.strip().split() for word in list: list2 = (word.isupper() or word.istitle()) print (word) else print (word) -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating custom Python objects from C code
Eric Frederich, 05.01.2011 17:27: I have read through all the documentation here: http://docs.python.org/extending/newtypes.html I have not seen any documentation anywhere else explaining how to create custom defined objects from C. At this point, it is best to take a look at Cython *before* continuing your struggle to solve problems that you wouldn't even have become aware of if you had used it right away. I have this need to create custom objects from C and pass them as arguments to a function call. Question 1: how am I to create those objects from C code? In Cython: obj = SomeType() or (in some truly performance critical cases): obj = SomeType.__new__(SomeType) The other thing I would like to know is how I can create helper functions in my extension so they can be created and manipulated easily. Either functions or static methods would work here. It's up to you to make a suitable design choice. I am thinking along the lines of the built-in helper functions PyList_New and PyList_Append. Once I have an answer to question 1, the problem won't be creating the helper functions, but making them available from something built with distutils. To use the builtin python functions from C I need to link against python27.lib but when I create my own package using distutils it creates dll or pyd files. Cython has an embedding mode ("--embed" option) that generates a suitable main() function to embed the Python interpreter in your module. That might work for you as is, or it will at least show you the required C code that you can adapt as you see fit. Question 2: How do I make C helper functions that are part of my extension available to other C projects in the same way that PyList_*, PyString_*, PyInt_* functions are available? Cython allows you to mark C functions and Python extension types with the "api" keyword and generates suitable header files and import/export code for them that you can use both from C and from other Cython generated modules. It automatically uses PyCObject in older Python versions and PyCapsule in Py2.7 and Py3.1+. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with code-lists and strings
On 1/5/2011 12:57 PM, Cathy James wrote: I am learning python and came across an excercise where i need to use lists to strip words from a sentence; starting with those containing one or more uppercase letters, followed by words with lower case letters. When writing code, it is good to start with one or more input-output pairs that constitute a test. For example, what, exactly, do you want to result from "Some special words are ALLCAPS, TitleCase, and MIXed." It is also good to think about all relevant cases. Note the following: >>> 'MIXed'.isupper() or 'MIXed'.istitle() False Do you want punctuation stripped off words? You might skip that at first. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
On Tue, Jan 4, 2011 at 11:31 PM, Tim Roberts wrote: > Zdenko wrote: >> >>Please, can anybody write me a simple recursive matrix multiplication >>using multiple threads in Python, or at least show me some guidelines >>how to write it myself > > Matrix multiplication is not generally done recursively. There's no > conceptual gain. It makes more sense iteratively. It may not be that common, but there is at least one significant advantage: Cache obliviousness. http://www.catonmat.net/blog/mit-introduction-to-algorithms-part-fourteen -- http://mail.python.org/mailman/listinfo/python-list
Re: opinion: comp lang docs style
On 01/04/2011 11:29 PM, Steven D'Aprano wrote: > On Tue, 04 Jan 2011 15:17:37 -0800, ru...@yahoo.com wrote: > >>> If one wants to critique the 'Python Docs', especially as regards to >>> usefulness to beginners, one must start with the Tutorial; and if one >>> wants to use if statements as an example, one must start with the >>> above. >> >> No. The language reference (LR) and standard library reference (SLR) >> must stand on their own merits. It is nice to have a good tutorial for >> those who like that style of learning. But it should be possible for a >> programmer with a basic understanding of computers and some other >> programming languages to understand how to program in python without >> referring to tutorials, explanatory websites, commercially published >> books, the source code, etc. > > No it shouldn't. That's what the tutorial is for. The language reference > and standard library reference are there to be reference manuals, not to > teach beginners Python. Yes it should. That's not what the tutorial is for. The (any) tutorial is for people new to python, often new to programming, who have the time and a learning style suitable for sitting down and going through a slow step-by-step exposition, much as one would get in a classroom. That is a perfectly valid way for someone in that target audience to learn python. Your (and Terry's) mistake is to presume that it is appropriate for everyone, perhaps because it worked for you personally. There is a large class of potential python users for whom a tutorial is highly suboptimal -- people who have some significant programming experience, who don't have the time or patience required to go through it getting information serially bit by bit, or whos learning style is, "don't spoon feed me, just tell me concisely what python does", who fill in gaps on a need-to-know basis rather than linearly. I (and many others) don't need or want an explanation of how to use lists as a stack! A language reference manual should completely and accurately describe the language it documents. (That seems fairly obvious to me although there will be differing opinions of how precise one needs to be, etc.) Once it meets that minimum standard, it's quality is defined by how effectively it transfers that information to its target audience. A good reference manual meets the learning needs of the target audience above admirably. I learned Perl (reputedly more difficult to learn than Python) from the Perl manpages and used it for many many years before I ever bought a Perl book. I learned C mostly from Harbison and Steele's "C: A Reference". Despite several attempts at python using its reference docs, I never got a handle on it until I forked out money for Beazley's book. There is obviously nothing inherently "difficult" about python -- it's just that python's reference docs are written for people who already know python. Since limiting their scope that narrowly is not necessary, as other languages show, it is fair to say that python's reference docs are poorer. > In any case, your assumption that any one documentation work should stand > on its own merits is nonsense -- *nothing* stands alone. Everything > builds on something else. Technical documentation is no different: it > *must* assume some level of knowledge of its readers -- should it be > aimed at Python experts, or average Python coders, or beginners, or > beginners to programming, or at the very least is it allowed to assume > that the reader already knows how to read? > > You can't satisfy all of these groups with one document, because their > needs are different and in conflict. This is why you have different > documentation -- tutorials and reference manuals and literate source code > and help text are all aimed at different audiences. Expecting one > document to be useful for all readers' needs is like expecting one data > type to be useful for all programming tasks. I defined (roughly) the target audience I was talking about when I wrote "for a programmer with a basic understanding of computers and some other programming languages". Let's dispense with the 6th-grade arguments about people who don't know how to read, etc. > Reasonable people might disagree on what a particular documentation work > should target, and the best way to target it, but not on the need for > different documentation for different targets. As I hope I clarified above, that was exactly my point too. There is a significant, unsatisfied gap between the audience that a tutorial aims at, and the audience that the reference docs as currently written seem to be aimed at. Since other language manuals incorporate this gap audience more or less sucessfully in their reference manuals, python's failure to do so is justification for calling them poor. (Of course they are poor in lots of other ways too but my original response was prompted by the erroneous claim that good (in my sense above) reference manuals were unnecessary becaus
Re: opinion: comp lang docs style
On 01/05/2011 12:23 AM, Alice Bevan–McGregor wrote: > > On 2011-01-04 22:29:31 -0800, Steven D'Aprano said: > > >> >> In any case, your assumption that any one documentation work should stand >> >> on its own merits is nonsense -- *nothing* stands alone. > > > > +1 I responded more fully in my response to Steven but you like he is taking "stand on it's own merits" out of context. The context I gave was someone who wants a complete and accurate description of python and who understands programming with other languages but not python. > > How many RFCs still in use today don't start with: > > >> >> The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", >> >> "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this >> >> document are to be interpreted as described in RFC 2119 RFC 2119 is incorporated in the others by reference. It is purely a matter of technical convenience that those definitions, which are common to hundreds of RFCs, are factored out to a single common location. RFC 2119 is not a tutorial. > > I posted a response on the article itself, rather than pollute a > > mailing list with replies to a troll. The name calling was a rather > > large hint as to the intention of the "opinion", either that or whoever > > translated the article (man or machine) was really angry at the time. > > ;) I can hint to my neighbor that his stereo is too loud by throwing a brick through his window. Neither that nor calling people arrogant ignoramus is acceptable in polite society. I am not naive, nor not shocked that c.l.p is not always polite, and normally would not have even commented on it except that 1) Terry Reedy is usually more polite and thoughtful, and 2) Xah Lee's post was not a troll -- it was a legitimate comment on free software documentation (including specifically python's) and while I don't agree with some of his particulars, the Python docs would be improved if some of his comments were considered rather than dismissed with mindless epithets like troll and arrogant ignoramus. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating custom Python objects from C code
On Wed, Jan 5, 2011 at 11:39 AM, Antoine Pitrou wrote: > On Wed, 5 Jan 2011 11:27:02 -0500 > Eric Frederich wrote: >> I have read through all the documentation here: >> >> http://docs.python.org/extending/newtypes.html >> >> I have not seen any documentation anywhere else explaining how to >> create custom defined objects from C. >> I have this need to create custom objects from C and pass them as >> arguments to a function call. > > What do you mean? Create instances of a type defined in Python code? > > The C API is not very different from Python-land. When you want to > instantiate a type, just call that type (as a PyObject pointer) with the > right arguments (using PyObject_Call() and friends). Whether that type > has been defined in C or in Python does not make a difference. No, the custom types are defined in C. I need to create the objects in C. I need to pass those custom C objects created in C to a python function via PyObject_CallObject(pFunc, pArgs). -- http://mail.python.org/mailman/listinfo/python-list
Attaching C++ libraries to Python app.
Is it possible to use C++ libraries within a Python application? I am planning to write an encryption program and want to use GnuPG C++ libraries.elementFontfont-familyfont-sizefont-stylefont-variantfont-weightletter-spacingline-heighttext-decorationtext-aligntext-indenttext-transformwhite-spaceword-spacingcolorBackgroundbg-attachmentbg-colorbg-imagebg-positionbg-repeatBoxwidthheightborder-topborder-rightborder-bottomborder-leftmarginpaddingmax-heightmin-heightmax-widthmin-widthoutline-coloroutline-styleoutline-widthPositioningpositiontopbottomrightleftfloatdisplayclearz-indexListlist-style-imagelist-style-typelist-style-positionTablevertical-alignborder-collapseborder-spacingcaption-sideempty-cellstable-layoutEffectstext-shadow-webkit-box-shadowborder-radiusOtheroverflowcursorvisibility ...Rohit. -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphing API,
Thank you, I will defiantly look into that. On Jan 5, 2011, at 4:32 AM, Tim Harig wrote: > On 2011-01-05, Slie wrote: >> Is there a graphing API, someone suggests? > > You should check the archives, variations of this question get asked > a lot. > > I use GNUplot to do my graphing. I simply pipe it commands and data > through the subprocess module; but, there are libraries available for > interacting with it. > > Posts here also indicate that Google offers a web service based API for > generating graphs. I have never actually used it; but, the documentation > seems to be clear enough to get it working without too much trouble. > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Wed, Jan 5, 2011 at 9:26 AM, MRAB wrote: > On 05/01/2011 10:44, Nobody wrote: >> >> On Tue, 04 Jan 2011 12:20:42 -0800, Google Poster wrote: >> >>> The indentation-as-block is unique, >> >> Not at all. It's also used in occam, Miranda, Haskell and F#. >> > Don't forget about ABC. Just to round out the list: ISWIM ("invented" the concept) Boo (via Python heritage) Cobra (via Python heritage) BuddyScript Curry Genie Nemerle (not by default) Pliant PROMAL Spin XL Source: http://en.wikipedia.org/wiki/Off-side_rule Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Attaching C++ libraries to Python app.
You don't need to reinvent the wheel: http://www.dlitz.net/software/pycrypto/ Am Mi, 5.01.2011, 22:21 schrieb Rohit Coder: > > Is it possible to use C++ libraries within a Python application? I am > planning to write an encryption program and want to use GnuPG C++ > libraries.elementFontfont-familyfont-sizefont-stylefont-variantfont-weightletter-spacingline-heighttext-decorationtext-aligntext-indenttext-transformwhite-spaceword-spacingcolorBackgroundbg-attachmentbg-colorbg-imagebg-positionbg-repeatBoxwidthheightborder-topborder-rightborder-bottomborder-leftmarginpaddingmax-heightmin-heightmax-widthmin-widthoutline-coloroutline-styleoutline-widthPositioningpositiontopbottomrightleftfloatdisplayclearz-indexListlist-style-imagelist-style-typelist-style-positionTablevertical-alignborder-collapseborder-spacingcaption-sideempty-cellstable-layoutEffectstext-shadow-webkit-box-shadowborder-radiusOtheroverflowcursorvisibility > ...Rohit. > -- > http://mail.python.org/mailman/listinfo/python-list > -- MfG, Stefan Sonnenberg-Carstens IT Architect -- http://mail.python.org/mailman/listinfo/python-list
Re: opinion: comp lang docs style
On 1/5/2011 12:10 PM ru...@yahoo.com said... A language reference manual should completely and accurately describe the language it documents. (That seems fairly obvious to me although there will be differing opinions of how precise one needs to be, etc.) Once it meets that minimum standard, it's quality is defined by how effectively it transfers that information to its target audience. A good reference manual meets the learning needs of the target audience above admirably. I learned Perl (reputedly more difficult to learn than Python) from the Perl manpages and used it for many many years before I ever bought a Perl book. I learned C mostly from Harbison and Steele's "C: A Reference". Despite several attempts at python using its reference docs, I never got a handle on it until I forked out money for Beazley's book. Hmm... I suspect most of us with prior programming experience simply worked the tutorial and immediately put python into play, digging deeper as necessary. Further, absolute beginners at programming are not likely to learn programming from a man page, nor should anyone expect the tutorial to be sufficient for their needs. I agree that as far as the specific details around the edges and corner cases go, it would be nice to have a single reference that provides those answers at the level you need (ala postscript's redbook imo), but I find this group serves well to fill the gaps when I can't easily find what I need. Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Attaching C++ libraries to Python app.
On 1/5/11 3:44 PM, Stefan Sonnenberg-Carstens wrote: Am Mi, 5.01.2011, 22:21 schrieb Rohit Coder: Is it possible to use C++ libraries within a Python application? I am planning to write an encryption program and want to use GnuPG C++ You don't need to reinvent the wheel: http://www.dlitz.net/software/pycrypto/ Wrong wheel. http://pyme.sourceforge.net/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
RE: Attaching C++ libraries to Python app.
I am just asking. In future I may need to import any C++ library, not a Crypto, but some other. Is it possible? > Date: Wed, 5 Jan 2011 22:44:15 +0100 > Subject: Re: Attaching C++ libraries to Python app. > From: stefan.sonnenb...@pythonmeister.com > To: passionate_program...@hotmail.com > CC: python-list@python.org > > You don't need to reinvent the wheel: > > http://www.dlitz.net/software/pycrypto/ > > Am Mi, 5.01.2011, 22:21 schrieb Rohit Coder: > > > > Is it possible to use C++ libraries within a Python application? I am > > planning to write an encryption program and want to use GnuPG C++ > > libraries.elementFontfont-familyfont-sizefont-stylefont-variantfont-weightletter-spacingline-heighttext-decorationtext-aligntext-indenttext-transformwhite-spaceword-spacingcolorBackgroundbg-attachmentbg-colorbg-imagebg-positionbg-repeatBoxwidthheightborder-topborder-rightborder-bottomborder-leftmarginpaddingmax-heightmin-heightmax-widthmin-widthoutline-coloroutline-styleoutline-widthPositioningpositiontopbottomrightleftfloatdisplayclearz-indexListlist-style-imagelist-style-typelist-style-positionTablevertical-alignborder-collapseborder-spacingcaption-sideempty-cellstable-layoutEffectstext-shadow-webkit-box-shadowborder-radiusOtheroverflowcursorvisibility > > ...Rohit. > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > MfG, > > Stefan Sonnenberg-Carstens > > IT Architect elementFontfont-familyfont-sizefont-stylefont-variantfont-weightletter-spacingline-heighttext-decorationtext-aligntext-indenttext-transformwhite-spaceword-spacingcolorBackgroundbg-attachmentbg-colorbg-imagebg-positionbg-repeatBoxwidthheightborder-topborder-rightborder-bottomborder-leftmarginpaddingmax-heightmin-heightmax-widthmin-widthoutline-coloroutline-styleoutline-widthPositioningpositiontopbottomrightleftfloatdisplayclearz-indexListlist-style-imagelist-style-typelist-style-positionTablevertical-alignborder-collapseborder-spacingcaption-sideempty-cellstable-layoutEffectstext-shadow-webkit-box-shadowborder-radiusOtheroverflowcursorvisibility -- http://mail.python.org/mailman/listinfo/python-list
Streaming templating languages for use as WSGI body.
Howdy! I'm trying to find a templating engine whose templates can be consumed directly as a WSGI response body iterable. So far I haven't been very successful with Google; the engines I've found universally generate a monolithic rendered string. Bonus points for templating engines that support flush() mechanics internally to allow developer-chosen 'break points' in the iterable. Bonus points++ if it can somehow calculate the response body length without generating the whole thing monolithically. ;) - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with code-lists and strings
On Wed, 05 Jan 2011 14:58:05 -0500, Terry Reedy wrote: > On 1/5/2011 12:57 PM, Cathy James wrote: > >> I am learning python and came across an excercise where i need to use >> lists to strip words from a sentence; starting with those containing >> one or more uppercase letters, followed by words with lower case >> letters. > > When writing code, it is good to start with one or more input-output > pairs that constitute a test. For example, what, exactly, do you want to > result from > "Some special words are ALLCAPS, TitleCase, and MIXed." > > It is also good to think about all relevant cases. Note the following: > >>> 'MIXed'.isupper() or 'MIXed'.istitle() > False > > Do you want punctuation stripped off words? You might skip that at > first. In python it's best to build up you functional needs. So two steps. First a nand (negative 'and' operation). Then wrap that with a function to create two strings of your list element, you''re calling 'word'. By the way, list is reserved word, like string. Don't get in the bad habit of using it. def nand( a, b ): """nand has to vars. Both must be strings """ return( ( not eval( a ) ) and ( not eval( b ) ) ) Eval of 'Abcd'.isupper() returns False. Ditto 'Abcd'.islower(); negate both results, 'and' values, return. Now wrap 'nand' in packaging an you're cooking with grease. def mixed_case( str ): return nand( "'%s'.islower()" % str , "'%s'.isupper()" % str ) or if that's too advanced/compact, try ... def mixed_case( str ): # nand() needs strings a = "'%s'.isupper()" % str b = "'%s'.islower()" % str res = nand( a, b ) return res >>> mixed_case('Abcd' ) True >>> mixed_case('ABCD' ) False >>> mixed_case('abcd' ) False Good luck Steven Howe -- http://mail.python.org/mailman/listinfo/python-list
Help with a Python coding question
I want to use Python to find all "\n" terminated strings in a PDF file, ideally returning string starting addresses. Anyone willing to help? -- - --- -- - Posted with NewsLeecher v4.0 Final Web @ http://www.newsleecher.com/?usenet --- - -- - -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a Python coding question
On 1/5/2011 3:12 PM kanth...@woh.rr.com said... I want to use Python to find all "\n" terminated strings in a PDF file, ideally returning string starting addresses. Anyone willing to help? pdflines = open(r'c:\shared\python_book_01.pdf').readlines() sps = [0] for ii in pdflines: sps.append(sps[-1]+len(ii)) Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a Python coding question
On Wed, Jan 5, 2011 at 4:45 PM, Emile van Sebille wrote: > On 1/5/2011 3:12 PM kanth...@woh.rr.com said... > > I want to use Python to find all "\n" terminated >> strings in a PDF file, ideally returning string >> starting addresses. Anyone willing to help? >> > > pdflines = open(r'c:\shared\python_book_01.pdf').readlines() > sps = [0] > for ii in pdflines: sps.append(sps[-1]+len(ii)) > > Emile > > > -- > http://mail.python.org/mailman/listinfo/python-list > Bear in mind that pdf files often have compressed objects in them. If that is the case, then I would recommend opening the pdf in binary mode and figuring out how to deflate the correct objects before doing any searching. PyPDF is a package that might help with this though it could use some updating. -- http://mail.python.org/mailman/listinfo/python-list
Importing modules from miscellaneous folders
On a Windows PC, I would like to be able to store modules in topic-specific foldersinstead of in Python26/Lib/site-packages, and then import into an IPython session those modules and the functions in them. To test this, I have made a toy module: --- """ toy_module.py This is for testing the importing of modules from folders other than "Lib". The first statement below is from Langtangen, Primer, p.143. At allows running the module as a program, as well as importing it as a module. """ if __name__ == '__main__' : def double_it (a) : b = 2.*a print 'double_it in toy_module: a = ', a, ', b = ', b return b def triple_it (a) : b = 3.*a print 'triple_it in toy_module: a = ', a, ', b = ', b return b --- I have tried many ways of importing this module and its functions, but all of them have failed. In the IPython session below, the failures have been flagged for easy identification by "<<<". --- Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.10.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: # Test importing from other than Lib. In [2]: # 2011-01-05 In [3]: function_dir = 'G:\\Python_2010-12\\JH_Python_Functions' In [4]: # That is for the PC at work. In [5]: import os In [6]: os.getcwd() Out[6]: 'C:\\Documents and Settings\\Hornstein' In [7]: os.chdir(function_dir) In [8]: os.getcwd() Out[8]: 'G:\\Python_2010-12\\JH_Python_Functions' In [9]: import toy_module In [10]: result1 = toy_module.double_it(3.) --- AttributeError Traceback (most recent call last) G:\Python_2010-12\JH_Python_Functions\ in () AttributeError: 'module' object has no attribute 'double_it' <<< 1 In [11]: from toy_module import double_it as twox --- ImportError Traceback (most recent call last) G:\Python_2010-12\JH_Python_Functions\ in () ImportError: cannot import name double_it <<< 2 In [12]: IsFileThere = os.isfile('toy_module.py') --- AttributeError Traceback (most recent call last) G:\Python_2010-12\JH_Python_Functions\ in () AttributeError: 'module' object has no attribute 'isfile' In [13]: IsFileThere = os.path.isfile('toy_module.py') In [14]: IsFileThere Out[14]: True In [15]: filelist = os.listdir(function_dir) In [16]: filelist Out[16]: ['arc_to_-pitopi.py', 'arc_to_0to2pi.py', 'ClustersOfGalaxiesUtils.py', 'ClustersOfGalaxiesUtils.py.txt', 'ClustersOfGalaxiesUtils.Test.2010-08-04.1.txt', 'CosmolFns.py.txt', 'CosmolGeom_SmoothedMatter_CL.py.txt', 'Distances_z.py.txt', 'extract_text_line.py', 'JH.PythonExperimentsOnWindows.2011-01-03.txt', 'LAMBDA_calc.py', 'loop_to_sum.example.py', 'number_theory.py', 'omega_plasma_radHz.py', 'README.txt', 'Sampletxt.IPython.txt', 'Sampletxt.txt', 'script2_1.py', 'synchRadn.py.txt', 'toy_module.py', 'toy_module.pyc', 'uv2D.Feb14-06.py', 'VariablesInFile.py', 'VariablesInFile.pyc', 'VLA_beamwidths.py', 'z_cosmol.py'] In [17]: import glob In [18]: pyfilelist = glob.glob('*.py') In [19]: pyfilelist Out[19]: ['arc_to_-pitopi.py', 'arc_to_0to2pi.py', 'ClustersOfGalaxiesUtils.py', 'extract_text_line.py', 'LAMBDA_calc.py', 'loop_to_sum.example.py', 'number_theory.py', 'omega_plasma_radHz.py', 'script2_1.py', 'toy_module.py', 'uv2D.Feb14-06.py', 'VariablesInFile.py', 'VLA_beamwidths.py', 'z_cosmol.py'] In [20]: # Try changing the Python search path. In [21]: import sys In [22]: sys.path Out[22]: ['', 'C:\\Python26\\scripts', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\IPython/Extensions', u'C:\\Documents and Settings\\Hornstein\\_ipython'] In [23]: sys.path.append(function_dir) In [24]: sys.path Out[24]: ['', 'C:\\Python26\\scripts', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\IPython/Extensions', u'C:\\Documents and Settings\\Hornstein\\_ipython', 'G:\\Python_2010-12\\JH_Python_Functions'] In [25]: import toy_module In [26]: result1 = toy_module.double_it(3.) --- AttributeError Traceback (mos
Searching Python-list
I was wondering if anyone could tell me how to search through the Archives otter then manually looking through each month. -- http://mail.python.org/mailman/listinfo/python-list
Re: Interrput a thread
On Jan 4, 10:53 pm, John Nagle wrote: > There are systems where there's support designed in for thread > abort. LISP/Scheme systems tend to support it. QNX, the real-time > OS, has well worked out thread-abort semantics at the C level. > (QNX has really good features for "not getting stuck", like the > ability to put a time limit on any system call.) Yes, but "not getting stuck" and ending the thread execution is only one small part of the problem (and arguably the least significant). What we really want is a way to abort without harming other threads of execution, which is the hard part. QNX doesn't ipso facto make that easier. Functionality like time limits on system calls is more about latency guarantees and priority than "getting stuck" in a deadlock sense. > What you'd really like in Python is the ability for one thread > to be able to force an exception in another thread, plus a > mechanism for locking out such exceptions for critical sections. > It's not worth having, though, in a system where you can really only > run one thread at a time. Exceptions and critical sections are rather fundamentally incompatible, hence the absurd amount of gymnastics .NET goes through to attempt to make ThreadAbortException functional (and still fails rather miserably). If you had STM or 'antitry' blocks, then exceptions might be a semi-saneish way to abort a thread. Without either, I'm not entirely convinced of the utility. Only allowing the exception to be thrown from defined cancellation points is much better (ala POSIX threads), but diminishes the utility for things that are mostly grinding away in userspace. Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: Streaming templating languages for use as WSGI body.
Not sure if it's bad form to respond to your own posts, but here goes. ;) Coding up a quick hack of a templating engine, I've produced this: http://pastie.textmate.org/private/ws5jbeh1xyeaqtrhahevqw (The implementation of the engine itself is a base class that overrides __call__ and __getitem__, with __unicode__ serializing in one block, the norm for templating engines, and .render(encoding='ascii') returning a generator using cStringIO for internal buffering.) I even have a light-weight widget system based on it, now. E.g. class Input(Widget): type_ = None @property def template(self): return tag.input ( type_ = self.type_, name = self.name, id = self.name + '-field', value = self.value, **self.args ) I'll polish it and package it up. :) - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching Python-list
In article <6113bae4-29bb-416a-820f-cfcb0688d...@gmail.com>, Slie wrote: > I was wondering if anyone could tell me how to search through the Archives > otter then manually looking through each month. One way is to use the mirror of the mailing list at gmane.org: http://dir.gmane.org/gmane.comp.python.general -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching Python-list
On 2011-01-05 17:31:13 -0800, Slie said: I was wondering if anyone could tell me how to search through the Archives otter then manually looking through each month. Grab a Usenet news reader (such as Thunderbird or Unison), point it at: nntps://news.gmane.org/gmane.comp.python.general I can rather quickly search through articles using this interface (let alone keep my e-mail clear of mailing lists) and even post. :) - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a Python coding question
Does this work for binary files? (Like PDFs) -- - --- -- - Posted with NewsLeecher v4.0 Final Web @ http://www.newsleecher.com/?usenet --- - -- - -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a Python coding question
Your code only shows the first 488 bytes of the file? -- - --- -- - Posted with NewsLeecher v4.0 Final Web @ http://www.newsleecher.com/?usenet --- - -- - -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with code-lists and strings
Thank you all for your help. 1) I need to list words with uppercase first, then those with lower case; I used istitle() and isupper (don't know the method for mixed case yet) 2) Steve, it's a compliment that you though I'd undersand your code, but I only know conditional statements, started on lists, not functions yet. nand is still Greek to me right now. 3) If someone input "Thank you my FOLKS, i want the output to print words with upper case first: Thank FOLKS you my 3) Can someone help me make my code work in a very simple way. I am still learning, but watch this space colleagues; I may be helping you guys in a few months ;) Thanks to all who took their time to help. Future Python Expert, Cathy. My initial code: s=input("Write a sentence: ") list=s.strip().split() for word in list: list2 = (word.isupper() or word.istitle()) print (word) else print (word) On Wed, Jan 5, 2011 at 7:35 PM, wrote: > Send Python-list mailing list submissions to >python-list@python.org > > To subscribe or unsubscribe via the World Wide Web, visit >http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to >python-list-requ...@python.org > > You can reach the person managing the list at >python-list-ow...@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > Today's Topics: > > 1. Re: Help with code-lists and strings (GrayShark) > 2. Help with a Python coding question (kanth...@woh.rr.com) > 3. Re: Help with a Python coding question (Emile van Sebille) > 4. Re: Help with a Python coding question (Justin Peel) > 5. Importing modules from miscellaneous folders (Jshgwave) > 6. Searching Python-list (Slie) > 7. Re: Interrput a thread (Adam Skutt) > > > -- Forwarded message -- > From: GrayShark > To: python-list@python.org > Date: Wed, 05 Jan 2011 16:56:40 -0600 > Subject: Re: Help with code-lists and strings > On Wed, 05 Jan 2011 14:58:05 -0500, Terry Reedy wrote: > > > On 1/5/2011 12:57 PM, Cathy James wrote: > > > >> I am learning python and came across an excercise where i need to use > >> lists to strip words from a sentence; starting with those containing > >> one or more uppercase letters, followed by words with lower case > >> letters. > > > > When writing code, it is good to start with one or more input-output > > pairs that constitute a test. For example, what, exactly, do you want to > > result from > > "Some special words are ALLCAPS, TitleCase, and MIXed." > > > > It is also good to think about all relevant cases. Note the following: > > >>> 'MIXed'.isupper() or 'MIXed'.istitle() > > False > > > > Do you want punctuation stripped off words? You might skip that at > > first. > > In python it's best to build up you functional needs. So two steps. First > a nand (negative 'and' operation). Then wrap that with a function to create > two strings of your list element, you''re calling 'word'. By the way, > list is reserved word, like string. Don't get in the bad habit of using it. > > def nand( a, b ): >"""nand has to vars. Both must be strings """ >return( ( not eval( a ) ) and ( not eval( b ) ) ) > > Eval of 'Abcd'.isupper() returns False. Ditto 'Abcd'.islower(); negate both > results, 'and' values, return. > > Now wrap 'nand' in packaging an you're cooking with grease. > def mixed_case( str ): >return nand( "'%s'.islower()" % str , "'%s'.isupper()" % str ) > > or if that's too advanced/compact, try ... > def mixed_case( str ): ># nand() needs strings >a = "'%s'.isupper()" % str >b = "'%s'.islower()" % str >res = nand( a, b ) >return res > > >>> mixed_case('Abcd' ) > True > >>> mixed_case('ABCD' ) > False > >>> mixed_case('abcd' ) > False > > Good luck > Steven Howe > > > > -- Forwarded message -- > From: kanth...@woh.rr.com > To: python-list@python.org > Date: Wed, 05 Jan 2011 17:12:13 -0600 > Subject: Help with a Python coding question > I want to use Python to find all "\n" terminated > strings in a PDF file, ideally returning string > starting addresses. Anyone willing to help? > > > -- > - --- -- - > Posted with NewsLeecher v4.0 Final > Web @ http://www.newsleecher.com/?usenet > --- - -- - > > > > > -- Forwarded message -- > From: Emile van Sebille > To: python-list@python.org > Date: Wed, 05 Jan 2011 15:45:36 -0800 > Subject: Re: Help with a Python coding question > On 1/5/2011 3:12 PM kanth...@woh.rr.com said... > >> I want to use Python to find all "\n" terminated >> strings in a PDF file, ideally returning string >> starting addresses. Anyone willing to help? >> > > pdflines = open(r'c:\shared\python_book_01.pdf').readlines() > sps = [0] > for ii in pdflines: sps.append(sps[-1]+len(ii)) > > Emile > > > > > -- Forwarded message --
Re: Help with code-lists and strings
On 01/-10/-28163 02:59 PM, GrayShark wrote: < In python it's best to build up you functional needs. So two steps. First a nand (negative 'and' operation). Then wrap that with a function to create two strings of your list element, you''re calling 'word'. By the way, list is reserved word, like string. Don't get in the bad habit of using it. def nand( a, b ): """nand has to vars. Both must be strings """ return( ( not eval( a ) ) and ( not eval( b ) ) ) Two problems with that. One is that you've defined a NOR function, but called it nand(). The other is using eval. There's no need for it, and it's both slow and risky. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Google Chart API, HTTP POST request format.
http://code.google.com/apis/chart/docs/post_requests.html Google will return a chart in your browser from a URL that you have built. If your URL is bigger then 2K characters it will allow you to submit POST requests. They gives examples of HTML, JavaScript, and PHP POST requests. Is there a way I can submit a request with Python? Or possibly submit the HTML, JavaScript or PHP using python?(That was a long shot thought). If I do that I would need to find out what to do with the .PNG it gives me. Am I headed in the right direction, is the above paragraph about submitting an HTML form from my program even logical? I have read several examples on python post requests but I'm not sure mine needs to be that complicated. Thank You, -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing modules from miscellaneous folders
On Wed, Jan 5, 2011 at 8:08 PM, Jshgwave wrote: > > On a Windows PC, I would like to be able to store modules in > topic-specific foldersinstead of in Python26/Lib/site-packages, > and then import into an IPython session those modules and the > functions in them. > > To test this, I have made a toy module: > > --- > > """ > toy_module.py > > This is for testing the importing of modules from folders > other than "Lib". > > The first statement below is from Langtangen, Primer, p.143. > At allows running the module as a program, as well as > importing it as a module. > """ > > > if __name__ == '__main__' : > You've misunderstood what this statement does. Any python script can be executed as a program. In fact, all Python modules are scripts. Upon running or importing them, they are executed. Anything at the top level is run. If a module is imported, it's __name__ attribute will be the name of the script. If the module is run as a script, it's __name__ will be "__main__". By checking to see if the __name__ == "__main__", you can have certain code only run if the script is run as a program, as opposed to being imported as a module. The def statement in python is an executable statement, not a declaration. The function does not exist until after the def statement is executed. Because your functions are only created if __name__ == "__main__", they don't exist when __name__ == "toy_module", which is the case when you import it in the ipython shell. That's what's causing your error. -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching Python-list
On 1/5/2011 5:31 PM Slie said... I was wondering if anyone could tell me how to search through the Archives otter then manually looking through each month. http://groups.google.com To limit the results to this group, prepend group:comp.lang.python to your search terms. Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a Python coding question
On 1/5/2011 5:55 PM Bubba said... Does this work for binary files? (Like PDFs) I don't know what you want -- pdf's are not line oriented so searching for \n's is sketchy from the get go. I figured this was homework to test something Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a Python coding question
On 1/5/2011 6:24 PM Bubba said... Your code only shows the first 488 bytes of the file? add 'rb' to the open statement... >>> pdflines = open(r'c:\shared\python_book_01.pdf','rb').readlines() >>> sps = [0] >>> for ii in pdflines: sps.append(sps[-1]+len(ii)) Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching Python-list
On Jan 5, 2011, at 8:31 PM, Slie wrote: > I was wondering if anyone could tell me how to search through the Archives > otter then manually looking through each month. Do a Google search and include this term: site:mail.python.org/pipermail/python-list/ e.g. to search for banana: http://www.google.com/search?q=site:mail.python.org%2Fpipermail%2Fpython-list%2F+banana HTH Philip -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with code-lists and strings
Apologies if this comes through twice, I'm having problems with my news client and/or provider. On Wed, 05 Jan 2011 16:56:40 -0600, GrayShark wrote: > In python it's best to build up you functional needs. So two steps. > First a nand (negative 'and' operation). Then wrap that with a function > to create two strings of your list element, you''re calling 'word'. By > the way, list is reserved word, like string. Don't get in the bad habit > of using it. Speaking of bad habits: > def nand( a, b ): > """nand has to vars. Both must be strings """ > return( ( not eval( a ) ) and ( not eval( b ) ) ) What is the purpose of the two calls to eval, other than potentially introducing serious security bugs, being slow, and raising exceptions? def nand(a, b): return not (a and b) is faster and safer, and less likely to cause annoyance if somebody manages to fool you into executing something similar to: nand("0", "__import__('os').system('# r m -rf /')") More safely, and works on both Linux and Windows: nand("0", "__import__('os').system('dir .')") > Eval of 'Abcd'.isupper() returns False. Ditto 'Abcd'.islower(); negate > both results, 'and' values, return. > > Now wrap 'nand' in packaging an you're cooking with grease. Eww. Greasy food. I think the idiom you are thinking of is "now you're cooking with gas", gas cooking being cleaner, faster and easier than cooking with wood. > def mixed_case( str ): > return nand( "'%s'.islower()" % str , "'%s'.isupper()" % str ) I'm afraid that's incorrect, because it returns True for strings that aren't mixed case: >>> mixed_case("123") True as well as strings that can't be mixed anything on account of being a single character: >>> mixed_case("!") True A better solution would be: def ismixed(s): seen_upper = seen_lower = False for c in s: if c.isupper(): seen_upper = True if c.islower(): seen_lower = True if seen_upper and seen_lower: return True return False which should return True if and only if the string contains both lowercase and uppercase characters. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Chart API, HTTP POST request format.
On 2011-01-06, Slie wrote: [reformated to <80 columns per RFC 1855 guidelines] > I have read several examples on python post requests but I'm not sure > mine needs to be that complicated. >From the HTML example on the page you posted: you can retreive the same chart from Python: Python 3.1.2 (r312:79147, Oct 9 2010, 00:16:06) [GCC 4.4.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib.request, urllib.parse >>> params = urllib.parse.urlencode({'cht':'lc', 'chtt':'This is | my >>> chart', ... 'chs':'600x200', 'chxt':'x,y', 'chd':'t:40,20,50,20,100'}) >>> chart = urllib.request.urlopen('https://chart.googleapis.com/chart', ... data = params).read() >>> chartFile = open("chart.png", 'wb') >>> chartFile.write(chart) 10782 >>> chartFile.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Chart API, HTTP POST request format.
On Wed, Jan 5, 2011 at 7:36 PM, Slie wrote: > > http://code.google.com/apis/chart/docs/post_requests.html > > Google will return a chart in your browser from a URL that you have built. If > your URL is bigger then 2K characters it will allow you to submit POST > requests. > > They gives examples of HTML, JavaScript, and PHP POST requests. Is there a > way I can submit a request with Python? Or possibly submit the HTML, > JavaScript or PHP using python?(That was a long shot thought). If I do that I > would need to find out what to do with the .PNG it gives me. > > Am I headed in the right direction, is the above paragraph about submitting > an HTML form from my program even logical? You should probably first try one of the existing Python wrappers for Google's chart API and see if that meets your needs: http://code.google.com/p/google-chartwrapper/ http://pygooglechart.slowchop.com/ Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with code-lists and strings
On Wed, Jan 5, 2011 at 6:39 PM, Cathy James wrote: > > Thank you all for your help. > 1) I need to list words with uppercase first, then those with lower case; I > used istitle() and isupper (don't know the method for mixed case yet) > 2) Steve, it's a compliment that you though I'd undersand your code, but I > only know conditional statements, started on lists, not functions yet. nand > is still Greek to me right now. > 3) If someone input "Thank you my FOLKS, i want the output to print words > with upper case first: > > Thank > FOLKS > you > my > > 3) Can someone help me make my code work in a very simple way. I am still > learning, but watch this space colleagues; I may be helping you guys in a few > months ;) > > Thanks to all who took their time to help. > Future Python Expert, > Cathy. > > My initial code: > > s=input("Write a sentence: ") > list=s.strip().split() > for word in list: > list2 = (word.isupper() or word.istitle()) > print (word) > else print (word) > > On Wed, Jan 5, 2011 at 7:35 PM, wrote: >> >> Send Python-list mailing list submissions to >> python-l...@python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> http://mail.python.org/mailman/listinfo/python-list >> or, via email, send a message with subject or body 'help' to >> python-list-requ...@python.org >> >> You can reach the person managing the list at >> python-list-ow...@python.org >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Python-list digest..." >> >> Today's Topics: Note: Avoid replying to digests in the future, or at least trim off the irrelevant posts when doing so. You may want to switch to a non-digest subscription; this can be done at http://mail.python.org/mailman/listinfo/python-list (login and edit your subscription options). Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Chart API, HTTP POST request format.
I tried to use "pygooglechart.py" and I have been trying to get it set up all day actually along with several other graphing API's. I just found out that there is a problem with numpy and python 3.1 that is why I moved from the API's. Should I change version just for these library's? Should I be learning Python on 3.1? Awesome! On Wed, Jan 5, 2011 at 7:52 PM, Chris Rebert wrote: > On Wed, Jan 5, 2011 at 7:36 PM, Slie wrote: > > > > http://code.google.com/apis/chart/docs/post_requests.html > > > > Google will return a chart in your browser from a URL that you have > built. If your URL is bigger then 2K characters it will allow you to submit > POST requests. > > > > They gives examples of HTML, JavaScript, and PHP POST requests. Is there > a way I can submit a request with Python? Or possibly submit the HTML, > JavaScript or PHP using python?(That was a long shot thought). If I do that > I would need to find out what to do with the .PNG it gives me. > > > > Am I headed in the right direction, is the above paragraph about > submitting an HTML form from my program even logical? > > You should probably first try one of the existing Python wrappers for > Google's chart API and see if that meets your needs: > http://code.google.com/p/google-chartwrapper/ > http://pygooglechart.slowchop.com/ > > Cheers, > Chris > -- > http://blog.rebertia.com > -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Chart API, HTTP POST request format.
Thank you for showing me the POST request, I will defiantly learn a lot from that. On Wed, Jan 5, 2011 at 7:26 PM, Tim Harig wrote: > On 2011-01-06, Slie wrote: > [reformated to <80 columns per RFC 1855 guidelines] > > I have read several examples on python post requests but I'm not sure > > mine needs to be that complicated. > > >From the HTML example on the page you posted: > > > > > > > > > > > you can retreive the same chart from Python: > >Python 3.1.2 (r312:79147, Oct 9 2010, 00:16:06) >[GCC 4.4.4] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> import urllib.request, urllib.parse >>>> params = urllib.parse.urlencode({'cht':'lc', 'chtt':'This is | my >>>> chart', >... 'chs':'600x200', 'chxt':'x,y', 'chd':'t:40,20,50,20,100'}) >>>> chart = urllib.request.urlopen('https://chart.googleapis.com/chart > ', >... data = params).read() >>>> chartFile = open("chart.png", 'wb') >>>> chartFile.write(chart) >10782 >>>> chartFile.close() > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Chart API, HTTP POST request format.
On 01/06/2011 12:16 AM, Garland Fulton wrote: > I tried to use "pygooglechart.py" and I have been trying to get it set > up all day actually along with several other graphing API's. > > I just found out that there is a problem with numpy and python 3.1 that > is why I moved from the API's. Should I change version just for > these library's? > > Should I be learning Python on 3.1? > > Awesome! > > [snip] I swapped from 3 to 2.6 a while back, better support for modules, and not really losing much in the way of features. ~Corey Richardson -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Chart API, HTTP POST request format.
> On Wed, Jan 5, 2011 at 7:52 PM, Chris Rebert wrote: >> On Wed, Jan 5, 2011 at 7:36 PM, Slie wrote: >> > >> > http://code.google.com/apis/chart/docs/post_requests.html >> > >> > Google will return a chart in your browser from a URL that you have >> > built. If your URL is bigger then 2K characters it will allow you to submit >> > POST requests. >> > >> > They gives examples of HTML, JavaScript, and PHP POST requests. Is there >> > a way I can submit a request with Python? Or possibly submit the HTML, >> > JavaScript or PHP using python?(That was a long shot thought). If I do that >> > I would need to find out what to do with the .PNG it gives me. >> > >> > Am I headed in the right direction, is the above paragraph about >> > submitting an HTML form from my program even logical? >> >> You should probably first try one of the existing Python wrappers for >> Google's chart API and see if that meets your needs: >> http://code.google.com/p/google-chartwrapper/ >> http://pygooglechart.slowchop.com/ On Wed, Jan 5, 2011 at 9:16 PM, Garland Fulton wrote: > I tried to use "pygooglechart.py" and I have been trying to get it set up > all day actually along with several other graphing API's. > I just found out that there is a problem with numpy and python 3.1 that is > why I moved from the API's. Should I change version just for > these library's? > Should I be learning Python on 3.1? Most third-party libraries have yet to be ported to Python 3.1 (with a few notable exceptions). If you actually want to write non-(toy/demo/trivial) programs, you should probably use Python 2.x. Python 3.1 is fine for learning the basics of the language; once you've done that, learning the Python 2.x differences and wart workarounds is not hard. (Also, in the future, please don't top-post.) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Chart API, HTTP POST request format.
On Wed, Jan 5, 2011 at 7:52 PM, Chris Rebert wrote: > On Wed, Jan 5, 2011 at 7:36 PM, Slie wrote: > > > > http://code.google.com/apis/chart/docs/post_requests.html > > > > Google will return a chart in your browser from a URL that you have > built. If your URL is bigger then 2K characters it will allow you to submit > POST requests. > > > > They gives examples of HTML, JavaScript, and PHP POST requests. Is there > a way I can submit a request with Python? Or possibly submit the HTML, > JavaScript or PHP using python?(That was a long shot thought). If I do that > I would need to find out what to do with the .PNG it gives me. > > > > Am I headed in the right direction, is the above paragraph about > submitting an HTML form from my program even logical? > > You should probably first try one of the existing Python wrappers for > Google's chart API and see if that meets your needs: > http://code.google.com/p/google-chartwrapper/ > http://pygooglechart.slowchop.com/ > > Cheers, > Chris > -- > http://blog.rebertia.com > Google Chart Wrapper is compatible with 3.1 and i have been looking all day for something like this. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Attaching C++ libraries to Python app.
Am 05.01.2011 23:44, schrieb Rohit Coder: I am just asking. In future I may need to import any C++ library, not a Crypto, but some other. Is it possible? Yes. There are at least five possible ways: - Handcode the interface and glue code (http://docs.python.org/extending) - use SWIG to autogenerate (mostly) the interface (http://www.swig.org) - using BOOST's python interface (http://www.boost.org/doc/libs/1_45_0/libs/python/doc/index.html) - using ctypes module for runtime interaction (like and use it a _lot_, very cool for rapid prototyping :-) http://docs.python.org/library/ctypes.html) - cython (different approach, implements a python subset, http://cython.org) I used SWIG and ctypes in the past, as it seems (for me) the easiest way. > Date: Wed, 5 Jan 2011 22:44:15 +0100 > Subject: Re: Attaching C++ libraries to Python app. > From: stefan.sonnenb...@pythonmeister.com > To: passionate_program...@hotmail.com > CC: python-list@python.org > > You don't need to reinvent the wheel: > > http://www.dlitz.net/software/pycrypto/ > > Am Mi, 5.01.2011, 22:21 schrieb Rohit Coder: > > > > Is it possible to use C++ libraries within a Python application? I am > > planning to write an encryption program and want to use GnuPG C++ > > libraries.elementFontfont-familyfont-sizefont-stylefont-variantfont-weightletter-spacingline-heighttext-decorationtext-aligntext-indenttext-transformwhite-spaceword-spacingcolorBackgroundbg-attachmentbg-colorbg-imagebg-positionbg-repeatBoxwidthheightborder-topborder-rightborder-bottomborder-leftmarginpaddingmax-heightmin-heightmax-widthmin-widthoutline-coloroutline-styleoutline-widthPositioningpositiontopbottomrightleftfloatdisplayclearz-indexListlist-style-imagelist-style-typelist-style-positionTablevertical-alignborder-collapseborder-spacingcaption-sideempty-cellstable-layoutEffectstext-shadow-webkit-box-shadowborder-radiusOtheroverflowcursorvisibility > > ...Rohit. -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > MfG, > > Stefan Sonnenberg-Carstens > > IT Architect element Font font-family font-size font-style font-variant font-weight letter-spacing line-height text-decoration text-align text-indent text-transform white-space word-spacing color Background bg-attachment bg-color bg-image bg-position bg-repeat Box width height border-top border-right border-bottom border-left margin padding max-height min-height max-width min-width outline-color outline-style outline-width Positioning position top bottom right left float display clear z-index List list-style-image list-style-type list-style-position Table vertical-align border-collapse border-spacing caption-side empty-cells table-layout Effects text-shadow -webkit-box-shadow border-radius Other overflow cursor visibility -- http://mail.python.org/mailman/listinfo/python-list
Re: Google Chart API, HTTP POST request format.
On Wed, Jan 5, 2011 at 7:26 PM, Tim Harig wrote: > On 2011-01-06, Slie wrote: > [reformated to <80 columns per RFC 1855 guidelines] > > I have read several examples on python post requests but I'm not sure > > mine needs to be that complicated. > > >From the HTML example on the page you posted: > > > > > > > > > > > you can retreive the same chart from Python: > >Python 3.1.2 (r312:79147, Oct 9 2010, 00:16:06) >[GCC 4.4.4] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >>>> import urllib.request, urllib.parse >>>> params = urllib.parse.urlencode({'cht':'lc', 'chtt':'This is | my >>>> chart', >... 'chs':'600x200', 'chxt':'x,y', 'chd':'t:40,20,50,20,100'}) >>>> chart = urllib.request.urlopen('https://chart.googleapis.com/chart > ', >... data = params).read() >>>> chartFile = open("chart.png", 'wb') >>>> chartFile.write(chart) >10782 >>>> chartFile.close() > -- > http://mail.python.org/mailman/listinfo/python-list > Hope this isn't to stupid, For the chart = urllib.request.urlopen('https://chart.googleapis.com/chart', data = params).read() Where would I find information on why and what the ).read() part does. Thank you, -- http://mail.python.org/mailman/listinfo/python-list