Re: sqlobject issue/question...
On Dec 29, 12:27 pm, "bruce" <[EMAIL PROTECTED]> wrote: > hi > > i'm playing around, researching sqlobject, and i notice that it appears to > require the use of "id" in each tbl it handles in the database. > > if i already have a db schema, and it doesn't use 'id' as an auto-generated > field, does that mean that i can't use/implement sqlobject. > > is there a way to overide this function/behavior... > > thanks If you want to use all the power in sqlobject you will need the "id" , you may get away without having one if you use the build in raw sql facility exclusively , but then again you probably would not need sqlobject anyway. You also might want to take a look at sqlalchemy . Whichever you choose, if you are used to write complex queries in sql it will take some time to wrap your mind around any of them. Db -- http://mail.python.org/mailman/listinfo/python-list
Re: Pivot Table/Groupby/Sum question
On Dec 29, 11:51 am, [EMAIL PROTECTED] wrote: > John would you mind walking me through your class in normal speak? Yes. > I > only have a vague idea of why it works and this would help me a lot to > get a grip on classes and this sort of particular problem. It's about time you got a *concrete* idea of how something works. Grab a pencil and a large piece of paper, pretend you are python.exe and follow through what happens when it executes ptab = SimplePivotTable(...) and the ptab.add_item(..) loop with this set of data: data = [ ['Bob', 'Morn', 240], ['Bob', 'Aft', 300], ['Bob', 'Morn', 40], ] with the goal of being able to say what is in ptab.cell_dict and understanding how it got there. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Cheat sheet
Alaric ha scritto: > Nicely done! I would suggest you put your website address on it and a revision > number so that as it gains use on te web, people can find the "latest" > version. That's a good idea, thank you :) -- GreyFox -- http://mail.python.org/mailman/listinfo/python-list
Re: Cheat sheet
Michele Simionato wrote: > Python 2.4.4 (#2, Oct 4 2007, 22:02:31) file is open > True > > Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) file is open > False > > Nowadays file is no more an alias for open. curious... maybe it's me, but I can't find a "What's New in Python" where this is said... also, in 2.6 docs (and also in 2.5) remains this footer: http://docs.python.org/dev/library/stdtypes.html#id14 http://www.python.org/doc/2.5/lib/bltin-file-objects.html#foot4449 file() is new in Python 2.2. The older built-in open() is an alias for file(). -- Under construction -- http://mail.python.org/mailman/listinfo/python-list
Re: Cheat sheet
Scott David Daniels ha scritto: > Riccardo T. wrote: >> Maybe I'll add __builtin__ and os in place of the type hierarchy, but >> I'm not sure about that. However, not in the next release. What do you >> think about? > > How about: > top line w/ __builtin__, os, os.path (and no contents -- inspire > further reading). I'm sorry, but what do you mean with "top line w/"? -- http://mail.python.org/mailman/listinfo/python-list
Re: Cheat sheet
ZeD ha scritto: > Michele Simionato wrote: > >> Python 2.4.4 (#2, Oct 4 2007, 22:02:31) > file is open >> True >> >> Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) > file is open >> False >> >> Nowadays file is no more an alias for open. > > curious... maybe it's me, but I can't find a "What's New in Python" where > this is said... also, in 2.6 docs (and also in 2.5) remains this footer: > > http://docs.python.org/dev/library/stdtypes.html#id14 > http://www.python.org/doc/2.5/lib/bltin-file-objects.html#foot4449 > > file() is new in Python 2.2. The older built-in open() is an alias for > file(). That's strange... however, since there are no doubts about open(), I'll use that :) -- GreyFox -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
George Neuner schrieb: > I know not everyone > works in RT, but I can't possibly be alone in developing applications > that are hard to restart effectively. Indeed. An additional case is interactive applications where setting up the situation to be tested requires several time-consuming steps. Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
joining rows
hi every body, I have two columns in a file separted by tabs If the column1 is common in the row1 and row2 then it should be column 2 should be displayed in the single line. eg: col 1 col2 A1 A2 A3 B1 C 2 D 3 D 4 The result should be A1|2|3 B1 C2 D3|4 What should I do to get my results -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
Joachim Durchholz <[EMAIL PROTECTED]> writes: > Indeed. An additional case is interactive applications where setting > up the situation to be tested requires several time-consuming steps. At least for web development, there are a lot of automated tools that mimic user input, just for this purpose. -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP: How to implement listing al 'Employees'.
On 28 dec, 19:42, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Fri, 28 Dec 2007 04:05:59 -0800 (PST), Petar <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > I was just wondering. > > > What if you have a 'Employees' class and you want to list all the > > employees. Currenlty i'm seeing to possibilities: > > > - create a 'listAll' function inside the class which returns all the > > employees in a array. > > - create multiple instances, putting them in a array, by calling the > > Employees class multiple times in a loop (thus not creating a listAll > > function in the class). > > > What is the better way of doing this? And should a class always > > reference only on 'item'? > > Bottom-up responses... > > Unless you are contaminated by Java's need for a class to hold > static functions, classes are just templates for an undefined object. > You create an instance of the class to create a defined object. It is > not common in Python to create a class that is not meant to be > instantiated at least once (something that is just static methods is > probably easier implemented as an import module with plain functions and > module level globals). > > Now, by "name", an "Employees" (plural s) class, to me, implies a > class to represent a group of employees -- as a group! It would NOT have > methods or members (both of which are just attributes in generic Python > hissing) that refer to information about any specific employee -- such > information should be part of an "Employee" (no S) class. > > aDept = Employees(dept="Finance") > aDept.manager = Employee(name="John Dont", ID=3141596, phone="123-4567") > aDept.addEmployee(Employee(name=)) > aDept.addEmployee(Employee(...)) > ... > Note that this does not enforce any particular storage concept. The > Employees (with the S) class could be using a list to store each > employee, or a dictionary (maybe keyed by ID), or even an RDBM with a > join (where one has tables for, say, department, employee, and > intersection linking department to employee): > > select e.* from employees as e > inner join dept_employee as de > on de.empID = e.ID > inner join departments as d > on d.id = de.deptID > where d.name = "Finance"; > > aBody = aDept.employee(id=) > > aDept.removeEmployee(id=...) > > aDept.printEmployees() > > If all you need is a "list" of raw employees, with no meaning > associated to the list... Then just use a list... > > aList = [] > aList.append(Employee(name=...)) > aList.append(Employee(...)) > > for e in aList: > e.printEmployee() > -- > Wulfraed Dennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ I'm sorry if my question wasn't clear enough. But I think it has been answered. Let me explain how I got to this question. I had written een Article class which handled the articles that I had. On a certain page I wanted to show all the articles. That got me wondering about what to do. Should I make a method in my Article.class which returned multiple articles, or should I just use my current Article.class and fill a list (with a loop) with articles. The first solution thus meaning writing another method, the latter method to just use the current Article.class and call it multiple times. The post of Dennis made me realize of another solution though. To create another class called Articles which return multiple articles. The only problem I forsee with this that's it's gonna be a very empty class. Thank you all for your response, it has pointed me in the right direction. -- http://mail.python.org/mailman/listinfo/python-list
Professional Grant Proposal Writing Workshop (January 2008: Portland State University)
The Grant Institute's Grants 101: Professional Grant Proposal Writing Workshop will be held at Portland State University, January 22 -24, 2008. Interested development professionals, researchers, faculty, and graduate students should register as soon as possible, as demand means that seats will fill up quickly. Please forward, post, and distribute this e-mail to your colleagues and listservs. All participants will receive certification in professional grant writing from the Institute. For more information call (888) 824 - 4424 or visit The Grant Institute at www.thegrantinstitute.com. Please find the program description below: The Grant Institute Grants 101: Professional Grant Proposal Writing Workshop will be held at Portland State University Portland, Oregon January 22 - 24, 2008 8:00 AM - 5:00 PM The Grant Institute's Grants 101 course is an intensive and detailed introduction to the process, structure, and skill of professional proposal writing. This course is characterized by its ability to act as a thorough overview, introduction, and refresher at the same time. In this course, participants will learn the entire proposal writing process and complete the course with a solid understanding of not only the ideal proposal structure, but a holistic understanding of the essential factors, which determine whether or not a program gets funded. Through the completion of interactive exercises and activities, participants will complement expert lectures by putting proven techniques into practice. This course is designed for both the beginner looking for a thorough introduction and the intermediate looking for a refresher course that will strengthen their grant acquisition skills. This class, simply put, is designed to get results by creating professional grant proposal writers. Participants will become competent program planning and proposal writing professionals after successful completion of the Grants 101 course. In three active and informative days, students will be exposed to the art of successful grant writing practices, and led on a journey that ends with a masterful grant proposal. Grants 101 consists of three (3) courses that will be completed during the three-day workshop. (1) Fundamentals of Program Planning This course is centered on the belief that "it's all about the program." This intensive course will teach professional program development essentials and program evaluation. While most grant writing "workshops" treat program development and evaluation as separate from the writing of a proposal, this class will teach students the relationship between overall program planning and grant writing. (2) Professional Grant Writing Designed for both the novice and experienced grant writer, this course will make each student an overall proposal writing specialist. In addition to teaching the basic components of a grant proposal, successful approaches, and the do's and don'ts of grant writing, this course is infused with expert principles that will lead to a mastery of the process. Strategy resides at the forefront of this course's intent to illustrate grant writing as an integrated, multidimensional, and dynamic endeavor. Each student will learn to stop writing the grant and to start writing the story. Ultimately, this class will illustrate how each component of the grant proposal represents an opportunity to use proven techniques for generating support. (3) Grant Research At its foundation, this course will address the basics of foundation, corporation, and government grant research. However, this course will teach a strategic funding research approach that encourages students to see research not as something they do before they write a proposal, but as an integrated part of the grant seeking process. Students will be exposed to online and database research tools, as well as publications and directories that contain information about foundation, corporation, and government grant opportunities. Focusing on funding sources and basic social science research, this course teaches students how to use research as part of a strategic grant acquisition effort. Registration $597.00 tuition includes all materials and certificates. Each student will receive: *The Grant Institute Certificate in Professional Grant Writing *The Grant Institute's Guide to Successful Grant Writing *The Grant Institute Grant Writer's Workbook with sample proposals, forms, and outlines Registration Methods 1) On-Line - Complete the online registration form at www.thegrantinstitute.com under Register Now. We'll send your confirmation by e-mail. 2) By Phone - Call (888) 824 - 4424 to register by phone. Our friendly Program Coordinators will be happy to assist you and answer your questions. 3) By E-mail - Send an e-mail with your name, organization, and basic contact information to [EMAIL PROTECTED] and we will reserve your slot and send your Confirmation Packet. You have received this inv
Re: Python DLL in Windows Folder
On 27 Dez., 05:49, Tim Roberts <[EMAIL PROTECTED]> wrote: > It's true that mallocing in one CRT DLL and freeing in another can cause > problems, but in Python, I don't think that can happen. Proper Python > add-ins call Python APIs to create and destroy objects, so only the Python > runtime will manage the memory. There is at least one actual problem I came across in an application linked with MSVCR 8.0, loading the Python DLL linked against MSVCR 7.1. When running a Python file using one of the PyRun_File[1] functions, the passed file handle has to be created from the embedding application. This handle is incompatible with the C file handling functions used by the C runtime of the Python DLL, which causes it to crash when calling PyRun_File. regards, Michael Doppler [1] http://docs.python.org/api/veryhigh.html -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP: How to implement listing al 'Employees'.
On Sat, 29 Dec 2007 01:53:38 -0800, Petar wrote: > The post of Dennis made me realize of another solution though. To > create another class called Articles which return multiple articles. > The only problem I forsee with this that's it's gonna be a very empty > class. Then maybe it should not be a class. Maybe a function returning `Article`\s would be enough. This is not Java, not everything has to be stuffed into classes. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python DLL in Windows Folder
> There is at least one actual problem I came across in an application > linked with MSVCR 8.0, loading the Python DLL linked against MSVCR > 7.1. When running a Python file using one of the PyRun_File[1] > functions, the passed file handle has to be created from the embedding > application. This handle is incompatible with the C file handling > functions used by the C runtime of the Python DLL, which causes it to > crash when calling PyRun_File. Indeed. That is one of the main reasons to remove that API in Py3k. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: joining rows
Hi On Dec 29, 2007 3:08 PM, Beema shafreen <[EMAIL PROTECTED]> wrote: > hi every body, > > I have two columns in a file separted by tabs > > If the column1 is common in the row1 and row2 then it should be column > 2 should be displayed in the single line. > eg: > col 1 col2 > A1 > A2 > A3 > B1 > C 2 > D 3 > D 4 > The result should be > > A1|2|3 > B1 > C2 > D3|4 > > What should I do to get my results > > Looking at the answer u require , u can clearly make a dictionary if list datastructure! where dictionary keys are A,B, C ,D and corresponding values are list if items (ie., 1,2,3 ...) Once u have such a dict loaded, its kust a matter of accessing that list via a key and display it joined! HTH KM > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: getting n items at a time from a generator
On Dec 29, 2007 2:18 AM, Tim Roberts <[EMAIL PROTECTED]> wrote: > Kugutsumen <[EMAIL PROTECTED]> wrote: > > > >I am relatively new the python language and I am afraid to be missing > >some clever construct or built-in way equivalent to my 'chunk' > >generator below. > > I have to say that I have found this to be a surprisingly common need as > well. Would this be an appropriate construct to add to itertools? > Something similar is already contained in the itertools recipes page. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
difference between `x in list` and `list.index(x)` for instances of a new-style class
Hello, I have some code that stops when trying to find a graph in a list of similar graphs:: (Pydb) list 110try: 111canonical = self.base[self.base.index(graph)] 112except ValueError: 113raise ValueError, \ 114 "Cannot find canonical representative for graph `%s`." \ 115 -> % (repr(graph),) 116 The list `self.base` contains "canonical" forms of the graphs and the `graph` object must compare equal to some item of the list, which indeed it does:: (Pydb) p graph == self.base[27] True (Pydb) p graph in self.base True However, I cannot directly get the index of the canonical graph (the number "27" above was found by manual inspection):: (Pydb) self.base.index(graph) *** ValueError: list.index(x): x not in list All graphs are instances of a `Graph` new-style class that implements comparison operators `__eq__` and `__ne__`, but no other rich-compare stuff. I'm using Python 2.5:: Python 2.5 (release25-maint, Dec 9 2006, 16:17:58) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2 So my question is: what are the implementation differences between `x in list` and `list.index(x)` and why can one report that an item is in the list while the other cannot find its index? Should I add something to the `Graph` class so that `index` works? Thanks for any hint! -- Riccardo Murri, via Galeazzo Alessi 61, 00176 Roma -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlobject issue/question...
bruce schrieb: > hi > > i'm playing around, researching sqlobject, and i notice that it appears to > require the use of "id" in each tbl it handles in the database. > > if i already have a db schema, and it doesn't use 'id' as an auto-generated > field, does that mean that i can't use/implement sqlobject. > > is there a way to overide this function/behavior... ORMs are best used not to map, but to model the data-structures. If you already have a schema and have to keep it, SQLAlchemy might be a better choice. Diez -- http://mail.python.org/mailman/listinfo/python-list
Brussels Python Interest/Users Group
Hi Pythonistas, Is anyone interested in forming a Brussels(Belgium) area Python User Group ? I am not aware of any python focused group in this area. Language could be whatever fits the bill (English/French/Dutch/...) Focus would be python, ironpython/silverlight, scipy, ORMs, web frameworks, and whatever is of interest to us. Interested ? Please post on this thread. Seb -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
George Neuner writes: > On Fri, 28 Dec 2007 12:54:57 -0800, John Nagle <[EMAIL PROTECTED]> > wrote: > >>Actually, the ability to "fix a running program" [in Lisp] isn't >>that useful in real life. It's more cool than useful. Editing a >>program from a break was more important back when computers were slower >>and just rerunning from the beginning was expensive. > > Speak for yourself. > > The ability to patch a running program is very useful for certain > types of embedded applications. Not every program having high > availability requirements can be restarted quickly, or can be > implemented reasonably using multiple servers or processes to allow > rolling restarts. And in applications like IDEs, dynamically loaded functions are very important. Improving Emacs is vastly easier because Emacs Lisp is interpreted. You can make a small change to a function and quickly determine its effect. That's one reason (among many others :) I have not switched to GPS (which is written in Ada). -- -- Stephe -- http://mail.python.org/mailman/listinfo/python-list
Re: Pivot Table/Groupby/Sum question
Patrick, in your first posting you are writing "... I'm trying to learn how to make pivot tables from some excel sheets...". Can you be more specific please? AFIK Excel offers very good support for pivot tables. So why to read tabular data from the Excel sheet and than transform it to pivot tabel in Python? Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove namespace declaration from ElementTree in lxml
Zero Piraeus wrote: >> You can try this: >> >>root = etree.parse(...).getroot() >>new_root = etree.Element(root.tag, root.attrib) >>new_root[:] = root[:] >> >> Note, however, that this will not copy root-level PIs or internal DTD >> subsets. >> But you can copy PIs and comments by hand. > > Thanks. I considered copying the tree, but didn't bother trying it as > I would expect it to be fairly expensive. Maybe no more expensive than > a regex though. I'll take a look ... It's not actually copying the tree, but it does create a new document, a new root element, and then moves the root children over from the original document, which also involves reference adaptations throughout the entire tree. So it does not come for free. I'd be interested if you can come up with numbers how it compares to the string replacement. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlobject issue/question...
On Dec 28, 11:27 pm, "bruce" <[EMAIL PROTECTED]> wrote: > i'm playing around, researching sqlobject, and i notice that it appears to > require the use of "id" in each tbl it handles in the database. > is there a way to overide this function/behavior... there better be such way. An ORM that does not allow you to override what the primary keys are called would be quite limited. Look at sqlmeta data: http://www.sqlobject.org/SQLObject.html#class-sqlmeta i. -- http://mail.python.org/mailman/listinfo/python-list
Re: difference between `x in list` and `list.index(x)` for instances of a new-style class
On 28 dic, 20:12, Riccardo Murri <[EMAIL PROTECTED]> wrote: > The list `self.base` contains "canonical" forms of the graphs and the > `graph` object must compare equal to some item of the list, which > indeed it does:: > > (Pydb) p graph == self.base[27] > True > > (Pydb) p graph in self.base > True > > However, I cannot directly get the index of the canonical graph (the > number "27" above was found by manual inspection):: > > (Pydb) self.base.index(graph) > *** ValueError: list.index(x): x not in list > > All graphs are instances of a `Graph` new-style class that implements > comparison operators `__eq__` and `__ne__`, but no other rich-compare > stuff. > > I'm using Python 2.5:: > > Python 2.5 (release25-maint, Dec 9 2006, 16:17:58) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2 > > So my question is: what are the implementation differences between `x > in list` and `list.index(x)` and why can one report that an item is in > the list while the other cannot find its index? Should I add > something to the `Graph` class so that `index` works? (I've checked on 2.5.1 but I don't see any relevant differences with the 2.5 version). Looking at the source for both methods, they only use the __eq__ operator, but there is a slight difference: while one evaluates list[i]==x, the other reverses the operands. If your __eq__ is not reflexive, that could explain the difference. class Graph(object): def __init__(self, *items): self.items = items def __eq__(self, other): if len(self.items)>len(other.items): return False return self.items == other.items[:len(self.items)] py> List = [Graph(1,2,3), Graph(4,5,6), Graph(1,2,3,4)] py> g = Graph(1,2) py> g in List True py> List.index(g) Traceback (most recent call last): File "", line 1, in ValueError: list.index(x): x not in list py> List[0]==g False py> g==List[0] True In your example, see if self.base[27]==graph is still True. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
Rico Secada <[EMAIL PROTECTED]> wrote: > > Second, I need some advice. > http://www.nondot.org/sabre/Mirrored/AdvProgLangDesign/ Learn, or better said understand, those and then choose wisely. Lisp throws lambda calculus right into your face, which is a good thing. Scheme might be the better choice, it's lexically scoped: http://mitpress.mit.edu/sicp/ There are also video lectures with people with funny hats speaking wise words. For lisp, (and also a good read if you go for scheme, same with the wizard book above the different way round), the book of choice is http://www.paulgraham.com/acl.html Python is Yet Another Scripting Language, borrowing concepts from more advanced languages. You might want to go for the real thing instead, although it's certainly nice. Haskell is to scheme what a basketball basket is to a trash bin. It's typed strictly and pure, but with some effort you will also be able to throw your trash through the basket as well as find a trash bin big enough for your ball . -- (c) this sig last receiving data processing entity. Inspect headers for past copyright information. All rights reserved. Unauthorised copying, hiring, renting, public performance and/or broadcasting of this signature prohibited. -- http://mail.python.org/mailman/listinfo/python-list
Re: joining rows
> A1
> A2
> A3
> B1
> C 2
> D 3
> D 4
> The result should be
>
> A1|2|3
> B1
> C2
> D3|4
>
> What should I do to get my results
Well, it depends on whether the resulting order matters. If not,
you can use KM's suggestion of a dictionary:
results = {}
for line in file('in.txt'):
k,v = line.rstrip('\n').split('\t')
results.setdefault(k, []).append(v)
for k,v in results.iteritems():
print k, '|'.join(v)
If, however, order matters, you have to do it in a slightly
buffered manner. It makes a difference when your input looks like
A 1
B 2
A 3
which should yield its own input, rather than "A 1|3". In this case
last_key = ''
values = []
for line in file('in.txt'):
k,v = line.rstrip('\n').split('\t')
if last_key != k:
if last_key:
print last_key, '|'.join(values)
last_key = k
values = [v]
else:
values.append(v)
if last_key:
print last_key, '|'.join(values)
should do the job. Which, if you like, can be reduced to a sed
one-liner
sed ':a;N;s/^\([^\t]\+\)\(.*\)\n\1\t\+\(.*\)/\1\2|\3/;ta;P;D'
...if it doesn't make your modem hang up on you, or if line-noise
assembly-language is your thing ;)
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: Tab indentions on different platforms?
* xkenneth (Fri, 28 Dec 2007 14:51:04 -0800 (PST)) > I seem to be having problems with running my python code, written on > a Mac, on Linux and Windows boxes. You seem to have problems or you do have problems? > It seems like the problem has to do with tab indention, Why does it seem and what does seem? > particularly I've noticed that my code will completely ignore try > statements. Statements are never ignored: they error or they don't. > Has anyone had a similar problem? It doesn't matter how a particular editor (note, that's not an OS thing!) displays indents. If you use only tabs or spaces that's just fine. I'd personally go for spaces because: 1. I don't like things I cannot see (control characters) 2. I never had problems with spaces but plenty with tabs Thorsten -- http://mail.python.org/mailman/listinfo/python-list
do i need to create new rgbimage class
hi am a beginner in python and PIL .I need to read an RGB 8 bit image (am using jpeg )and pack the rgb color values into a double value so i can store the image as a list of pixelvalues.From my application i should be able to call rgbimage1.getpixellist() to retrieve the double values of an image. Do i need to create a new class for this?I made something like class myrgbimage: def __init__(self,filename): def _readimage(self): im=Image.open(filename) self._readImage(filename) self._wd,self._ht=im.size for y in range(self._ht): for x in range(self._wd): r,g,b=im.getpixel((x,y)) pval=self.rgbTodoubleval((r,g,b)) self._pixellist.append(pval) def rgbTodoubleval(self,(r,g,b)): alpha=255 pixelvalue=(alpha<<24)|(r<<16 )|( g<<8) | b return pixelvalue the way i am currently using this is to create instances using filenames and then retrieving the list of pixelvalues in the image. like for z in imagefilenamelist: myimage=myrgbimage(z) imagelist.append(z) so later on i can take each instance and get its width,height and pixellist and work with them..anyway the code takes too much time and I wish to know if i can get these 'packed pixelvalues' straight away without using the above class jim -- http://mail.python.org/mailman/listinfo/python-list
Re: i18n questions
* Donn Ingle (Fri, 28 Dec 2007 20:01:48 +0200)
> I'm 100% new to this i18n lark and my approach so far has been to create
> a .mo file per module in my app.
> My thinking was, why load one huge .mo file when a single module only needs
> a few strings? Since then, it seems, I have made the wrong decision.
>
> For example I have module A that imports module B. Each one does this:
>
> gettext.install( domain, localedir, unicode = True )
> lang = gettext.translation(domain, localedir, languages = [ loc ] )
> lang.install(unicode = True )
>
> (where doman is the name of the module, so "A" and "B")
>
> The problem is that domain "A" loads and then import B happens and so
> the "lang" reference (I think) gets replaced by domain "B" -- the result is
> that module A can only translate strings that are in domain "B".
>
> How does one 'merge' gettext.translations objects together? Or is that
> insane?
>
> What's the best way to handle a project with multiple domain.mo files?
I can give you just general advice how I dealt with
internationalization in my example app. "scipt" is the main app with
its own mo file and imports optparse which has again its own mo file
#
gettext.textdomain('optparse')
gettext.install('script', unicode = True)
from optparse import OptionParser, \
OptionGroup
# [...]
Thorsten
--
http://mail.python.org/mailman/listinfo/python-list
Howto on callbacks, queues and good design patterns
Hi there. As a newbie, I need to learn about callbacks and queues(syntax and examples) working together. At work we talk a lot about design patterns. Does any of you know a good site about that or any good books from Amazon? I started using python at work in the summer 2007. I think I know the stuff, but I need to expand my understanding of the more complex programming techniques. Thanks in advance. /Karneevor -- http://mail.python.org/mailman/listinfo/python-list
Re: Pivot Table/Groupby/Sum question
On Dec 29, 3:00 pm, [EMAIL PROTECTED] wrote: > Patrick, > > in your first posting you are writing "... I'm trying to learn how to > make pivot tables from some excel sheets...". Can you be more specific > please? AFIK Excel offers very good support for pivot tables. So why > to read tabular data from the Excel sheet and than transform it to > pivot tabel in Python? > > Petr Yes, I realize Excel has excellent support for pivot tables. However, I hate how Excel does it and, for my particular excel files, I need them to be formated in an automated way because I will have a number of them over time and I'd prefer just to have python do it in a flash than to do it every time with Excel. >It's about time you got a *concrete* idea of how something works. Absolutely right. I tend to take on ideas that I'm not ready for, in the sense that I only started using Python some months ago for some basic tasks and now I'm trying on some more complicated ones. With time, though, I will get a concrete idea of what python.exe does, but, for someone who studied art history and not comp sci, I'm doing my best to get a handle on all of it. I think a pad of paper might be a good way to visualize it. -- http://mail.python.org/mailman/listinfo/python-list
Re: i18n questions
Thorsten Kampe wrote:
> gettext.textdomain('optparse')
> gettext.install('script', unicode = True)
They speak of a 'global' domain in the docs, but (as is my usual beef with
the Python docs -- see PHP docs for sterling help) there is no clarity.
It *sounds* like there can be a .mo file for *everything* and then one can
also install others on a per-script/module basis, as your code seems to
suggest.
All very confusing.
I have had an entire day to stew and I spent it combining all my po files
into one big file. Now I install that once, and efficiency be damned.
Still, I'm interested in what's possible and I'll give your approach a
whirl.
Don't let the thread die yet, c'mon you i18n boffins!
Thanks,
\d
--
http://mail.python.org/mailman/listinfo/python-list
Re: Pivot Table/Groupby/Sum question
> Yes, I realize Excel has excellent support for pivot tables. However, > I hate how Excel does it and, for my particular excel files, I need > them to be formated in an automated way because I will have a number > of them over time and I'd prefer just to have python do it in a flash > than to do it every time with Excel. > Patrick, Few more questions: - Where the data come from (I mean: are your data in Excel already when you get them)? - If your primary source of data is the Excel file, how do you read data from the Excel file to Python (I mean did you solve this part of the task already)? Petr -- http://mail.python.org/mailman/listinfo/python-list
Optional code segment delimiter?
Is it possible to use optional delimiters other than tab and colons?
For example:
if this==1 {
print this
}
And is there an alternate delimiter for statements other than the
newline?
print this;print that; #for example
I know I'll probably get yelled at for this question, but I would just
like to know.
Regards,
Ken
--
http://mail.python.org/mailman/listinfo/python-list
Re: Optional code segment delimiter?
On Sat, 29 Dec 2007 09:20:00 -0800, xkenneth wrote: > Is it possible to use optional delimiters other than tab and colons? No. > And is there an alternate delimiter for statements other than the > newline? > > print this;print that; #for example Yes. But both are reasons to yell at you. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Bizarre behavior with mutable default arguments
I've found some bizzare behavior when using mutable values (lists,
dicts, etc) as the default argument of a function. I want to get the
community's feedback on this. It's easiest to explain with code.
This example is trivial and has design issues, but it demonstrates a
problem I've seen in production systems:
def main(argv = ['TESTING']):
'print out arguments with BEGIN and END'
argv.insert(1, "BEGIN")
argv.append("END")
for arg in argv: print arg
if __name__ == '__main__':
from sys import argv, exit
exit(main(argv))
Now lets try this out at the terminal:
>>> import example
>>> example.main()
BEGIN
TESTING
END
>>> example.main(["TESTING"])
BEGIN
TESTING
END
>>> example.main()
BEGIN
BEGIN
TESTING
END
END
>>> example.main(["TESTING"])
BEGIN
TESTING
END
The function does different things if you call it with ["TESTING"] as
the argument, even though that is identical to the default value!! It
seems that default values are only allocated once. If the default
value is mutable and is changed during the function's execution, this
has the side effect of making the default value change on each
subsequent execution.
Is this functionality intended? It seems very unintuitive. This has
caused a bug in my programs twice so far, and both times I was
completely mystified until I realized that the default value was
changing.
I'd like to draw up a PEP to remove this from py3k, if I can get some
community backing.
--Buck
--
http://mail.python.org/mailman/listinfo/python-list
Re: joining rows
On Dec 29, 10:22 am, Tim Chase <[EMAIL PROTECTED]> wrote: > If, however, order matters, you have to do it in a slightly > buffered manner. > Can be reduced to a sed one-liner I think the original version works just as well for both cases. Your sed version however does need the order you mention. Makes it no less mind-bending though ... once I saw it I knew I had to try it :-) i. -- http://mail.python.org/mailman/listinfo/python-list
Mix different C source files into a single one
Hi, I have a C program split into different source files. I am trying a new compiler and for some reason it only accepts a single source file. So I need to "mix" all my different C source files into a single one. Do you know about some type of python script able to do this kind of task ? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
> Is this functionality intended? Google for "Python mutable default arguments" (you can actually leave out Python). It's part of the language semantics, yes. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: joining rows
on a second read ... I see that you mean the case that should only join consecutive lines with the same key -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
Paul Rubin schrieb: > Joachim Durchholz <[EMAIL PROTECTED]> writes: >> Indeed. An additional case is interactive applications where setting >> up the situation to be tested requires several time-consuming steps. > > At least for web development, there are a lot of automated tools that > mimic user input, just for this purpose. Yes, but it still takes time to run to the point you want. Plus you'd need to integrate such a tool with the debugger. Plus you'd need to record the user actions, save them somewhere, and recall them. None of that is rocket science, of course, but I have yet to see such a thing. (It would be nice to have it though.) However, for web applications, I found a far easier variant: I just reload the page being debugged. (I have to make sure that the backend is in the same state when reloading, but that's usually easy to accomplish.) So web pages are one area where code modification during debugging is less important. Desktop programs with a large internal state are an entirely different kettle of fish, of course. Regards, Jo -- http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
On Dec 29, 12:50 pm, bukzor <[EMAIL PROTECTED]> wrote: > Is this functionality intended? It seems very unintuitive. This has > caused a bug in my programs twice so far, and both times I was > completely mystified until I!realized that the default value was > changing. it is only unintuitive when you do not know about it once you realize how it works and what it does it can actually be very useful i. -- http://mail.python.org/mailman/listinfo/python-list
Re: Howto on callbacks, queues and good design patterns
> I started using python at work in the summer 2007. I think I know the > stuff, but I need to expand my understanding of the more complex > programming techniques. There are various materials on Python and design patterns; just google. I particularly recommend the talk by Alex Martelli. He gave this talk several times; one recorded instance was at Google TechTalk. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
På Sat, 29 Dec 2007 19:16:09 +0100, skrev Joachim Durchholz <[EMAIL PROTECTED]>: > However, for web applications, I found a far easier variant: I just > reload the page being debugged. (I have to make sure that the backend is > in the same state when reloading, but that's usually easy to accomplish.) > So web pages are one area where code modification during debugging is > less important. > Haveyou looked at selenium? I quote: Selenium is a test tool for web applications. Selenium tests run directly in a browser, just as real users do. And they run in Internet Explorer, Mozilla and Firefox on Windows, Linux, and Macintosh. No other test tool covers such a wide array of platforms. Browser compatibility testing. Test your application to see if it works correctly on different browsers and operating systems. The same script can run on any Selenium platform. System functional testing. Create regression tests to verify application functionality and user acceptance. There is also a Lisp interface cl-selesium though I can't find the code on the net now. -- John Thingstad -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional code segment delimiter?
On Dec 29, 10:20 am, xkenneth <[EMAIL PROTECTED]> wrote:
> Is it possible to use optional delimiters other than tab and colons?
>
> For example:
>
> if this==1 {
> print this
> }
Certainly, it's very possible. Here's how to do it:
1. Download the python source code (easy)
2. Modify the parser as needed (hard)
3. Re-apply your patches to each additional version of Python that
gets released (hard)
Alternatively:
1. Write a script in regular Python/Perl/Ruby/Bash-script to convert
your code into real Python. (Bonus: This may give you the write-
compile-run cycle that some C/C++ programmers desperately crave!)
Or, another alternative:
1. Get used to using indention.
2. Use a Python-aware editor to automatically add the proper number
of indenting spaces for you.
3. If you feel the urge to use braces, write in Java until
thoroughly sick of them. If you don't feel the bile rising in your
throat, it's too soon to come back to Python.
>
> And is there an alternate delimiter for statements other than the
> newline?
>
> print this;print that; #for example
>>> print "This" ; print "That"
This
That
>>>
That wasn't so hard, now was it? Just remember that clarity beats
compactness any day. The semicolon doesn't even save you any
keystrokes if you're using a Python-aware editor. People who feel the
need to write a program on a single line will be rightfully mocked by
other Pythonistas. How is:
print "This"; print "That"
better than:
print "This"
print "That"
I know which one is easier for me to read.
>
> I know I'll probably get yelled at for this question, but I would just
> like to know.
>
> Regards,
> Ken
No yelling, but a little snickering from some of us.
--Jason
--
http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
På Sat, 29 Dec 2007 18:58:30 +0100, skrev Arnaud Delobelle <[EMAIL PROTECTED]>: > On Dec 29, 3:11 pm, Achim Schneider <[EMAIL PROTECTED]> wrote: > [...] >> Lisp throws lambda calculus right into your face, which is a good >> thing. Scheme might be the better choice, it's lexically >> scoped:http://mitpress.mit.edu/sicp/ >> There are also video lectures with people with funny hats speaking wise >> words. > > Common Lisp has lexical scoping as well (although defvar allows you to > declare dynamically scoped variables). > > -- > Arnaud > More precisely defvar, defparameter, progv and (declare (special var)) create variables with dynamic scope. let and let* do as you said use a lexical scope. (unless you use a declare as above) -- John Thingstad -- http://mail.python.org/mailman/listinfo/python-list
Re: Optional code segment delimiter?
xkenneth wrote:
> Is it possible to use optional delimiters other than tab and colons?
>
> For example:
>
> if this==1 {
> print this
> }
Heheheh..
--
--
http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
On Dec 29, 1:11 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > Google for "Python mutable default arguments" and a mere 30 minutes later this thread is already one of the results that come up -- http://mail.python.org/mailman/listinfo/python-list
pdf library.
Hi, I am looking for a pdf library that will give me a list of pages where new chapters start. Can someone point me to such a module ? Regards, Shriphani P. -- http://mail.python.org/mailman/listinfo/python-list
Re: joining rows
> on a second read ... I see that you mean the case that should only
> join consecutive lines with the same key
Yes...there are actually three cases that occur to me:
1) don't care about order, but want one row for each key (1st value)
2) do care about order, and don't want disjoint runs of duplicate
keys to be smashed together
3) do care about order, and do want disjoint runs to be smashed
together (presumably outputting in the key-order as they were
encountered in the file...if not, you'd have to clarify)
My original post addresses #1 and #2, but not #3. Some tweaks to
my solution for #1 should address #3:
results = {}
order = []
for line in file('in.txt'):
k,v = line.rstrip('\n').split('\t')
if k not in results:
order.append(k)
results.setdefault(k, []).append(v)
for k in order:
print k, '|'.join(results[k])
#2 does have the advantage that it can process large (multi-gig)
streams of data without bogging down as it behaves like the sed
version, processing only a window at a time and retaining only
data for consecutively matching lines.
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
Here's the answer to the question:
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects
It looks like Guido disagrees with me, so the discussion is closed.
For the record, I still think the following would be an improvement to
py3k:
In python25:
def f(a=None):
if a is None: a = []
...
In py3k becomes:
def f(a=[])
...
In python25 (this function from the FAQ linked above):
def f(a, _cache={}):
# Callers will never provide a third parameter for this function.
(then why is it an argument?)
...
In py3k becomes:
_cache = {}
def f(a):
global _cache
...
This follows the "explicit is better" and "one best way" principles of
Python, and greatly improves the intuitiveness. Also since the first
example is much more common, it reduces the overall verbosity of the
language.
Just my parting two cents,
--Buck
--
http://mail.python.org/mailman/listinfo/python-list
Re: Howto on callbacks, queues and good design patterns
Nel mezzo del cammin di nostra vita, mi ritrovai con Michael Bernhard Arp
Sørensen che diceva:
> Hi there.
>
> As a newbie, I need to learn about callbacks and queues(syntax and
> examples) working together.
>
> At work we talk a lot about design patterns. Does any of you know a good
> site about that or any good books from Amazon?
>
Hello,
I think the best way to understanding queues and callbacks is to learn
Twisted. That's a very big framework for asynchronous network
programming; it's completely callback based.
For more info you should visit the Twisted Matrix website: http://
twistedmatrix.com/trac/
There also a good documentation, but it's a few embedded, so you need to
looking for that with care:-)
Good 2008 and have fun!
--
"Le opinioni dei fanatici prescindono dai fatti"
python -c "print 'bG9ybWF5bmFAZ21haWwuY29t'.decode('base64')"
--
http://mail.python.org/mailman/listinfo/python-list
Re: getting n items at a time from a generator
[ Terry Jones ] [ ... ] > Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705 > > def chop(iterable, length=2): > return izip(*(iter(iterable),) * length) Is this *always* guaranteed by the language to work? Should the iterator returned by izip() change the implementation and evaluate the underlying iterators in, say, reverse order, the solution would no longer function, would it? Or is it something the return value of izip() would never do? (I am just trying to understand the solution, not criticize it. Took a while to parse the argument(s) to izip in the example). ivr -- <+Kaptein-Dah> igorr: for få parenteser <+Kaptein-Dah> igorr: parenteser virker som lubrication under iterasjon <+Kaptein-Dah> igorr: velkjent -- http://mail.python.org/mailman/listinfo/python-list
Re: Mix different C source files into a single one
Horacius ReX wrote: > Hi, > > I have a C program split into different source files. I am trying a > new compiler and for some reason it only accepts a single source file. > So I need to "mix" all my different C source files into a single one. > > Do you know about some type of python script able to do this kind of > task ? No, but bash and friends can: cat *.c > newfile.c If you're stuck working with windows, the copy command can also concatenate files. After concatenating the files, editing the file to remove/merge #include directives would work. Any compiler that can only deal with a single source file is of course extremely limited in what it can do, so this manual process shouldn't be too bad for short programs (all that this compiler can really deal with). > > Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: getting n items at a time from a generator
Hi Igor > "Igor" == Igor V Rafienko <[EMAIL PROTECTED]> writes: >> Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) >> p705 >> >> def chop(iterable, length=2): >> return izip(*(iter(iterable),) * length) Igor> Is this *always* guaranteed by the language to work? Should the Igor> iterator returned by izip() change the implementation and evaluate Igor> the underlying iterators in, say, reverse order, the solution would Igor> no longer function, would it? Or is it something the return value of Igor> izip() would never do? Igor> (I am just trying to understand the solution, not criticize it. Took Igor> a while to parse the argument(s) to izip in the example). I had to look at it a bit too. I actually deleted the comment I wrote about it in my own code before posting it here and decided to simply say "consider" in the above instead :-) As far as I understand it, you're right. The docstring for izip doesn't guarantee that it will pull items from the passed iterables in any order. So an alternate implementation of izip might produce other results. If it did them in reverse order you'd get each n-chunk reversed, etc. Terry -- http://mail.python.org/mailman/listinfo/python-list
Re: getting n items at a time from a generator
> > def chop(iterable, length=2): > > return izip(*(iter(iterable),) * length) > > Is this *always* guaranteed by the language to work? Yes! Users requested this guarantee, and I agreed. The docs now explicitly guarantee this behavior. Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: getting n items at a time from a generator
> > Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705
>
> > def chop(iterable, length=2):
> > return izip(*(iter(iterable),) * length)
>
> However, chop ignores the remainder of the data in the example.
There is a recipe in the itertools docs which handles the odd-length
data at the end:
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'),
('g','x','x')"
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
Raymond
--
http://mail.python.org/mailman/listinfo/python-list
Re: Optional code segment delimiter?
On Dec 29, 12:41 pm, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
> xkenneth wrote:
> > Is it possible to use optional delimiters other than tab and colons?
>
> > For example:
>
> > if this==1 {
> > print this
> > }
>
>
>
> Heheheh..
Wow! I never thought of (ab)using encodings like that. And sure
enough, it's perfectly legal to write:
# -*- encoding: rot-13 -*-
cevag h"Uryyb, jbeyq!"
--
http://mail.python.org/mailman/listinfo/python-list
Re: Mix different C source files into a single one
On Dec 30, 5:05 am, Horacius ReX <[EMAIL PROTECTED]> wrote: > Hi, > > I have a C program split into different source files. I am trying a > new compiler and for some reason it only accepts a single source file. The relevance of this question to this newsgroup is zero, but ... Smashing all of your source files into one is an "interesting" reaction to the perceived problem. Consider these alternatives: 1. Abandon any further trialling of this new compiler ... which new compiler is it? Which compiler are you currently using? 2. Use "make" or something similar to automate the process of compiling each changed source file followed by a linking step. 3. Write yourself a shell script that compiles each source file and then links it. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: pdf library.
On Dec 29, 12:54 pm, Shriphani <[EMAIL PROTECTED]> wrote: > Hi, > I am looking for a pdf library that will give me a list of pages where > new chapters start. Can someone point me to such a module ? ReportLab (ReportLab) might help. > Regards, > Shriphani P. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mix different C source files into a single one
On Dec 29, 12:05 pm, Horacius ReX <[EMAIL PROTECTED]> wrote: > Hi, > > I have a C program split into different source files. I am trying a > new compiler and for some reason it only accepts a single source file. > So I need to "mix" all my different C source files into a single one. That sounds like one crumy compiler. > > Do you know about some type of python script able to do this kind of > task ? No, but we can write one: import sys if __name__ == "__main__": glob = "" for file in sys.argv[1:-1]: glob += "\n" + open(file, "r").read() open(sys.argv[-1], "w").write(glob) It's stupid, but it'll work for basic tasks. (I would actually just use cat; that's what it's for. :)) > > Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Mix different C source files into a single one
On 2007-12-29, Horacius ReX <[EMAIL PROTECTED]> wrote: > I have a C program split into different source files. I am > trying a new compiler and for some reason it only accepts a > single source file. That's pretty much the way they all work. > So I need to "mix" all my different C source files into a > single one. You compile them individually, then you link the object files together. > Do you know about some type of python script able to do this > kind of task ? $ man make -- Grant -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
> "Brad" == byte8bits <[EMAIL PROTECTED]> writes: Brad> Best of luck in finding skilled, affordable Ada programmers Brad> outside of major cities. Which is why it may be a good idea to learn it and earn a lot of $$$ :) -- http://mail.python.org/mailman/listinfo/python-list
Fate of itertools.dropwhile() and itertools.takewhile()
I'm considering deprecating these two functions and would like some feedback from the community or from people who have a background in functional programming. * I'm concerned that use cases for the two functions are uncommon and can obscure code rather than clarify it. * I originally added them to itertools because they were found in other functional languages and because it seemed like they would serve basic building blocks in combination with other itertools allow construction of a variety of powerful, high-speed iterators. The latter may have been a false hope -- to date, I've not seen good recipes that depend on either function. * If an always true or always false predicate is given, it can be hard to break-out of the function once it is running. * Both functions seem simple and basic until you try to explain them to someone else. Likewise, when reading code containing dropwhile(), I don't think it is self-evident that dropwhile() may have a lengthy start-up time. * Since itertools are meant to be combined together, the whole module becomes easier to use if there are fewer tools to choose from. These thoughts reflect my own experience with the itertools module. It may be that your experience with them has been different. Please let me know what you think. Raymond -- http://mail.python.org/mailman/listinfo/python-list
error on importing variable value
I can't figure out why this doesn't work. Any ideas appreciated.
conn = MySQLdb.connect (db = "vocab")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
gives:
server version: 5.0.44-log
but
import defs
conn = MySQLdb.connect (defs.connect)
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
where defs.py is
connect = 'db = "vocab"'
gives:
Traceback (most recent call last):
File "./add_words", line 17, in ?
conn = MySQLdb.connect (defs.connect)
File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line
74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py",
line 170, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2005, 'Unknown MySQL server host
\'db = "vocab"\' (3)')
--
http://mail.python.org/mailman/listinfo/python-list
CGI, MySQL & Python
I'm new to programming and I'm trying to find some answers. I wrote a few python cgi scripts for my website all of which access a mysql db on 'localhost'. My question is, Is it a bad idea to have my username and password for my db coded in my script? Is there a better way to make sure that information can't be acessed? Obviously I wan't to make sure that my *.py can't be downloaded from /cgi-bin and give anyone access to my db's. Cory -- http://mail.python.org/mailman/listinfo/python-list
Re: pdf library.
On Dec 29, 11:54 am, Shriphani <[EMAIL PROTECTED]> wrote: > Hi, > I am looking for a pdf library that will give me a list of pages where > new chapters start. Can someone point me to such a module ? > Regards, > Shriphani P. pyPdf may help you with that: http://pybrary.net/pyPdf/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
On Sat, 29 Dec 2007 11:14:30 -0800, bukzor wrote:
> In python25 (this function from the FAQ linked above):
> def f(a, _cache={}):
> # Callers will never provide a third parameter for this function.
> (then why is it an argument?)
The caller might want to provide it's own pre-prepared cache. Say, for
testing.
I think that this behaviour is a little unintuitive, and by a little I
mean a lot. Nevertheless, I am used to it, and I don't see any reason to
change it. There's very little about programming that is intuitive --
there's no intuitive reason to think that dictionary lookups are O(1)
while list lookups are O(n).
In the absence of a better solution, I'm very comfortable with keeping
the behaviour as is. Unfortunately, there's no good solution in Python to
providing functions with local storage that persists across calls to the
function:
(1) Use a global variable.
cache = {}
def foo():
global cache
print cache
(2) Use a function attribute.
def foo():
print foo.cache
foo.cache = {}
def foo():
try:
foo.cache
except AttributeError:
foo.cache = {}
print foo.cache
(3) Use an argument that isn't actually an argument.
def foo(cache={}):
print cache
#1, the global variable, is probably the worst solution of the lot.
Global variables are rightly Considered Harmful.
#2 has the disadvantages that you initialize the value *after* you write
the code that relies on it. Either that, or you waste time on every call
checking to see it if has been initialized. Also, like recursive
functions, it is difficult to rename the function.
#3 is, I think, the least-worse solution, but I would hardly call it
ideal.
> _cache = {}
> def f(a):
> global _cache
> ...
>
> This follows the "explicit is better" and "one best way" principles of
> Python,
Declaring an argument is equally explicit.
And you are confused -- the Zen doesn't say "one best way". People so
often get it wrong.
The Zen says:
"There should be one-- and PREFERABLY only one --OBVIOUS way to do it."
(Emphasis added.)
At least you're not saying "there should be only one way to do it". I
give you credit for that!
> and greatly improves the intuitiveness. Also since the first
> example is much more common, it reduces the overall verbosity of the
> language.
I question that it is "much more common". How do you know? Where's your
data?
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: Fate of itertools.dropwhile() and itertools.takewhile()
On Dec 29, 6:10 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote: > These thoughts reflect my own experience with the itertools module. > It may be that your experience with them has been different. Please > let me know what you think. first off, the itertools module is amazing, thanks for creating it. It changed the way I think about programming. In fact nowadays I start all my programs with: from itertools import * which may not be the best form, but I got tired of importing every single function individually or writing out the module name. Now I never needed the dropwhile() and takewhile() functions, but that may not mean much. For quite a while I never needed the repeat() function either. It even looked nonsensical to have an iterator that simply repeats the same thing over and over. One day I had to solve a problem that needed repeat() and made me really understand what it was for and got to marvel at a just how neat the solution was. i. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tab indentions on different platforms?
On Sat, 29 Dec 2007 15:29:25 +, Thorsten Kampe wrote: > I'd personally go for spaces because: > > 1. I don't like things I cannot see (control characters) You can see spaces but not tabs? Your editor is pretty weird. In all the editors I've every used, both spaces and tabs show up as empty white space. (Or coloured space if I set the editor to use a coloured background.) > 2. I never had problems with spaces but plenty with tabs Periodically, I ask on this list what problems people have with tabs. (I'm fully aware that mixing tabs and spaces is a Bad Thing.) I've had little luck getting any answer except "Tabs are bad, m'kay?". I'm only aware of two problems that some people run into due to the consistent use of tabs rather than spaces. * Some news clients don't display tabs correctly, thus making it hard to copy and paste code direct out of the news reader into your source; (But of course if you copy code using spaces, and the number of space characters used per indent level doesn't match your source code, you'll have problems too.) * Some applications "helpfully" convert tabs into spaces, thus meaning that when copy code from them, you end up with spaces instead of tabs. What problems have you had with tabs that aren't related to buggy applications or users that mix tabs and spaces? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
On Sat, 29 Dec 2007 09:50:53 -0800, bukzor wrote: > I've found some bizzare behavior when using mutable values (lists, > dicts, etc) as the default argument of a function. This FAQ is so Frequently Asked that I sometimes wonder if Python should, by default, print a warning when it compiles a function with a list or dict as as default value. There's precedence for such a thing: the sum() built-in (un)helpfully raises an exception if you try to use it on strings. I say unhelpfully because the one time I wanted to use sum() on strings was specifically to demonstrate the difference between O(n**2) behaviour and O(n). I was quite put out that Python, which normally allows you to shoot yourself in the foot if you insist, was so unnecessarily protective in this case. Give me a warning, if you wish, but don't stop me. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
sqlobject question...
hi... this continues my investigation of python/sqlobject, as it relates to the need to have an id, which is auto-generated. per various sites/docs on sqlobject, it appears that you can override the id, by doing something similar to the following: def foo(SQLObject): def _init(self, id, connection=None): id = str(id) SQLObject._init(self, id, connection) cat=StringCol() dog=StringCol() however, no matter what i do, i can't seem to insert anything into "id" so that i can use the "id" any thoughts/comments/pointers, code samples would be helpful!!! thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlobject question...
bruce wrote: > hi... > > this continues my investigation of python/sqlobject, as it relates to the > need to have an id, which is auto-generated. > > per various sites/docs on sqlobject, it appears that you can override the > id, by doing something similar to the following: > > def foo(SQLObject): > def _init(self, id, connection=None): > id = str(id) > SQLObject._init(self, id, connection) > > cat=StringCol() > dog=StringCol() > > > however, no matter what i do, i can't seem to insert anything into "id" so > that i can use the "id" > > any thoughts/comments/pointers, code samples would be helpful!!! > > thanks SQLObject may do something weird, but normally the init method is named "__init__", not "_init". Try changing that. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Fate of itertools.dropwhile() and itertools.takewhile()
On Sat, 29 Dec 2007 15:10:24 -0800, Raymond Hettinger wrote: > * Both functions seem simple and basic until you try to explain them to > someone else. Oh I don't know about that. The doc strings seem to do an admirable job to me. Compared to groupby(), the functions are simplicity themselves. > Likewise, when reading code containing dropwhile(), I > don't think it is self-evident that dropwhile() may have a lengthy > start-up time. *scratches head in confusion* It isn't? I can understand somebody *under*estimating the start-up time (perhaps because they overestimate how quickly dropwhile() can iterate through the items). But surely it is self-evident that a function which drops items has to drop the items before it can start returning? > * Since itertools are meant to be combined together, the whole module > becomes easier to use if there are fewer tools to choose from. True, but on the other hand a toolbox with too few tools is harder to use than one with too many tools. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: error on importing variable value
On 29 dic, 20:31, [EMAIL PROTECTED] wrote:
> I can't figure out why this doesn't work. Any ideas appreciated.
>
> conn = MySQLdb.connect (db = "vocab")
> cursor = conn.cursor ()
> cursor.execute ("SELECT VERSION()")
> row = cursor.fetchone ()
> print "server version:", row[0]
> cursor.close ()
> conn.close ()
>
> gives:
>
> server version: 5.0.44-log
>
> but
>
> import defs
> conn = MySQLdb.connect (defs.connect)
> [...]
> where defs.py is
>
> connect = 'db = "vocab"'
>
> gives:
>
> Traceback (most recent call last):
> _mysql_exceptions.OperationalError: (2005, 'Unknown MySQL server host
> \'db = "vocab"\' (3)')
Try this:
defs.py:
dbname = "vocab"
import defs
conn = MySQLdb.connect(db=defs.dbname)
BTW, please read the Style Guide at http://www.python.org/dev/peps/pep-0008
- in particular, I feel space before an opening parens rather
annoying. But it's just a matter of style.
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: Fate of itertools.dropwhile() and itertools.takewhile()
Almost every day I write code that uses itertools, so I find it very useful, and its functions fast. Removing useless things and keeping things tidy is often positive. But I can't tell you what to remove. Here are my usages (every sub-list is sorted by inverted frequency usage): I use often or very often: groupby( iterable[, key]) imap( function, *iterables) izip( *iterables) ifilter( predicate, iterable) islice( iterable, [start,] stop [, step]) I use once in while: cycle( iterable) chain( *iterables) count( [n]) repeat( object[, times]) I have used probably one time or few times: starmap( function, iterable) tee( iterable[, n=2]) ifilterfalse( predicate, iterable) Never used so far: dropwhile( predicate, iterable) takewhile( predicate, iterable) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Choosing a new language
On Sat, 29 Dec 2007 23:56:12 +0100 Samuel Tardieu <[EMAIL PROTECTED]> wrote: > > "Brad" == byte8bits <[EMAIL PROTECTED]> writes: > > Brad> Best of luck in finding skilled, affordable Ada programmers > Brad> outside of major cities. > > Which is why it may be a good idea to learn it and earn a lot of $$ > $ :) I have yet to see a job offering in which Ada is wanted, atleast in my country there is none. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
> I think that this behaviour is a little unintuitive, and by a little I > mean a lot. Thanks for acknowledging it. > I question that it is "much more common". How do you know? Where's your > data? I did a dumb grep of my Python25/Lib folder and found 33 occurances of the first pattern above. (Use None as the default value, then check for None and assign empty list/dict) Although I spent at least double the amount of time looking for the second pattern, I found no occurances. (Use dict/list as default value and modify it in place.) Every single function that used a list or dict as a default value treated these variables as read-only. However, I did find two new ways to accomplish the above (further violating the Zen). /c/Python25/Lib/site-packages/wx-2.8-msw-ansi/wx/lib/ customtreectrl.py: def FillArray(self, item, array=[]): if not array: array = [] /c/Python25/Lib/site-packages/wx-2.8-msw-ansi/wx/lib/floatcanvas/ FloatCanvas.py: def __init__(self, ObjectList=[], InForeground = False, IsVisible = True): self.ObjectList = list(ObjectList) --Buck -- http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
Just for completeness, the mutable default value problem also affects
classes:
class c:
def __init__(self, list = []):
self.list = list
self.list.append("LIST END")
def __repr__(self):
return "" % self.list
>>> import example2
>>> print example2.c()
>>> print example2.c([])
>>> print example2.c()
>>> print example2.c([])
Again, we get different results if we supply an argument that is
identical to the default value. There are many instances in the
standard library where class values are assigned directly from the
initializer, which has list or dict default values, so there is chance
for errors cropping up here.
The error scenario is this:
1. Use a mutable value as default value in a class constructor.
2. Assign class property from constructor arguments.
3. Instantiate class using default value.
4. Modify class property in place.
5. Instantiate (again) class using default value.
The second instance will behave strangely because data from the first
instance has leaked over. The standard library is not affected because
it avoids one of these five steps. Most classes simply don't have
mutable default values (1). Those that do generally treat them as read-
only (4). Some classes are not useful using the default values (3).
Some classes are not useful to be instantiated twice (5). The classes
that don't avoid the problem at one of these four steps have to avoid
it at (2) by using one of the three above patterns.
--Buck
--
http://mail.python.org/mailman/listinfo/python-list
Re: Tab indentions on different platforms?
Steven D'Aprano <[EMAIL PROTECTED]> writes: > On Sat, 29 Dec 2007 15:29:25 +, Thorsten Kampe wrote: > > > I'd personally go for spaces because: > > > > 1. I don't like things I cannot see (control characters) > > You can see spaces but not tabs? Your editor is pretty weird. In all > the editors I've every used, both spaces and tabs show up as empty > white space. (Or coloured space if I set the editor to use a > coloured background.) Though Thorsten could have been clearer, "thing that is not a space character but shows up as white space" is a near-enough approximation of "thing I cannot see". > > 2. I never had problems with spaces but plenty with tabs > > Periodically, I ask on this list what problems people have with > tabs. (I'm fully aware that mixing tabs and spaces is a Bad Thing.) > I've had little luck getting any answer except "Tabs are bad, > m'kay?". Posit: White space is most often achieved by the user inserting a sequence of space characters (U+0020). Posit: Tab characters (U+0009) are, in a majority of environments, rendered visually indistinguishable from a sequence of space characters. Corollary: most readers will, when seeing a stretch of white space on a line, default to assuming that it represents a sequence of space (U+0020) characters. Corollary: So when a file containing either spaces or tabs is edited in such an environment, the common way chosen by the user to get to the same indentation level as existing lines is to prepend space characters (using the spacebar or the Tab key or whatever facility the editor provides) until the indentation lines up visually -- remembering the caveat that tabs and space-sequences are visually indistinguishable in many environments. Argument: The user will get an unexpected result when they do the obvious thing (prepend space characters) in a tabs-only file. With existing spaces-only files, the obvious way to get matching indentation gives the expected result. Conclusion: Thus, using tabs-only is inferior to using spaces-only for indentation, because it violates the Principle of Least Astonishment http://en.wikipedia.org/wiki/Principle_of_least_astonishment>. -- \ "I object to doing things that computers can do." —Olin | `\ Shivers | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Tab indentions on different platforms?
Thorsten Kampe wrote: > * xkenneth (Fri, 28 Dec 2007 14:51:04 -0800 (PST)) >> I seem to be having problems with running my python code, written on >> a Mac, on Linux and Windows boxes. > > You seem to have problems or you do have problems? > >> It seems like the problem has to do with tab indention, It really should be a syntax error in Python to mix leading tabs and leading spaces in the same file. One can argue over which to use, but a file with both usually leads to trouble. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Tab indentions on different platforms?
On Dec 30, 3:48 pm, John Nagle <[EMAIL PROTECTED]> wrote: > Thorsten Kampe wrote: > > * xkenneth (Fri, 28 Dec 2007 14:51:04 -0800 (PST)) > >> I seem to be having problems with running my python code, written on > >> a Mac, on Linux and Windows boxes. > > > You seem to have problems or you do have problems? > > >> It seems like the problem has to do with tab indention, > > It really should be a syntax error in Python to mix > leading tabs and leading spaces in the same file. One can argue over > which to use, but a file with both usually leads to trouble. > It can be made to do so: prompt> python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): [snip] -t : issue warnings about inconsistent tab usage (-tt: issue errors) [snip] Further advice to the OP: run python with the -t (or -tt) option and see what you get. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fate of itertools.dropwhile() and itertools.takewhile()
On Dec 30, 12:10 am, Raymond Hettinger <[EMAIL PROTECTED]> wrote: > I'm considering deprecating these two functions and would like some > feedback from the community or from people who have a background in > functional programming. I am with Steven D'Aprano when he says that takewhile and dropwhile are clear enough. On the other hand, in my code base I have exactly zero occurrences of takewhile and dropwhile, even if I tend to use the itertools quite often. That should be telling. If my situations is common, that means that takewhile and dropwhile are useless in practice and should be deprecated. But I will wait for other respondents. It may just be that I never needed them. I presume you did scans of large code bases and you did not find occurrences of takewhile and dropwhile, right? Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Bizarre behavior with mutable default arguments
On Dec 30, 3:21 pm, bukzor <[EMAIL PROTECTED]> wrote: > Just for completeness, the mutable default value problem also affects > classes: Simply, because methods are functions, and can have default arguments. You don't need to nail *another* zillion theses to the cathedral door :-) -- http://mail.python.org/mailman/listinfo/python-list
