Re: How to pass class instance to a method?
On Sunday, November 25, 2012 7:11:29 AM UTC-5, ALeX inSide wrote:
> How to "statically type" an instance of class that I pass to a method of
> other instance?
>
>
>
> I suppose there shall be some kind of method decorator to treat an argument
> as an instance of class?
>
>
>
> Generally it is needed so IDE (PyCharm) can auto-complete instance's methods
> and properties.
>
>
>
> Pseudo-python-code example:
>
>
>
> i = MyClass()
>
>
>
> xxx(i, 1, 2);
>
>
>
> ...
>
> def xxx(self, MyClass myclass, number, foobar):
>
>myclass.classsmethod() #myclass - is an instance of known class
I'm not sure I understand exactly what you sre asking.Python uses "duck
typing". As far as Python is concerned, you can pass in any class object and
so long as it has the needed methods, it'll suffice ("If it walks like a duck
and it quacks like a duck, then it is a duck."). The down side to that is
that if you hand an object as an argument and the method you pass doesn't
behave like the expected method class would, then bad things may happen at run
time. It would be a bit of a hassle to check types to make sure things at
least smell OK before execution goes possibly awry, but you are certainly free
to write guard code that makes those sort of checks.
My reply here is a bit different from the other replies I see so far. I worry
that may mean I mis-understood your question.Has this been at all helpful
an answer?
--
http://mail.python.org/mailman/listinfo/python-list
Re: python on iPad (PyPad)
On Apr 10, 1:48 am, Matt Schinckel wrote: > On Apr 9, 2:13 pm, Jon Dowdall wrote: > > > Hi All, > > > Sorry for the blatant advertising but hope some of you may be interested > > to know that I've created an iPad application containing the python > > interpreter and a simple execution environment. It's available in iTunes > > athttp://itunes.apple.com/us/app/pypad/id428928902?mt=8# > > > I wanted to have python available 'on the go' without carrying a laptop. > > The current implementation is based on my need to test simple python > > functions in an isolated environment. I hope to add more iOS specific > > capabilities if there is enough interest. > > > Enjoy... > > > Jon Dowdall > > I know this sound shallow, but you really need a nicer icon. > > Otherwise, I'm quite excited about this. It will certainly be better > than my current workflow of connecting via ssh to a server just to run > python code. > > Matt. There's a Pypad on SourceForge, but it is flagged as no longer under active development. Dead or just sleeping? Is this Pypad distinct from that old one on SourceForge? Or a revival? OpenSource? Drew -- http://mail.python.org/mailman/listinfo/python-list
Blank rows resulting from simple csv script
Hi all -
I've written a simple script to read a .csv file and then write out
rows to a new file only if the value in the 4th column is a 0. Here's
the code:
import csv
reader = csv.reader(open('table_export.csv','rb'))
writer = csv.writer(open('new_jazz.csv','w'))
for row in reader:
if row[3] == '0':
writer.writerow(row)
This is writing out the correct rows, however it is writing a blank
row between each of the rows written out. Any ideas?
Thanks,
Drew
--
http://mail.python.org/mailman/listinfo/python-list
Blank rows resulting from simple csv script
Hi all -
I've written a simple script to read a .csv file and then write out
rows to a new file only if the value in the 4th column is a 0. Here's
the code:
import csv
reader = csv.reader(open('table_export.csv','rb'))
writer = csv.writer(open('new_jazz.csv','w'))
for row in reader:
if row[3] == '0':
writer.writerow(row)
This is writing out the correct rows, however it is writing a blank
row between each of the rows written out. Any ideas?
Thanks,
Drew
--
http://mail.python.org/mailman/listinfo/python-list
Simple csv read/write
Ok, I'm trying to do the simplest read/write from one csv file to
another. For some reason, every other row on the output file is a
blank row. What am I doing wrong?
import csv
reader = csv.reader(open('current.csv'))
writer = csv.writer(open('new.csv','w'))
for line in reader:
writer.writerow(line)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Simple csv read/write
On Apr 24, 8:35 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On 25/04/2007 8:27 AM, Drew wrote:
>
> > Ok, I'm trying to do the simplest read/write from one csv file to
> > another. For some reason, every other row on the output file is a
> > blank row. What am I doing wrong?
>
> > import csv
>
> > reader = csv.reader(open('current.csv'))
> > writer = csv.writer(open('new.csv','w'))
>
> > for line in reader:
> > writer.writerow(line)
>
> 1. Try reading the responses already posted to your previous questions.
>
> 2. Try reading the documentation; for each of csv.reader and csv.writer,
> it says "If csvfile is a file object, it must be opened with the 'b'
> flag on platforms where that makes a difference."
My apologies to the rest of the list, issues with groups.google.com
cause the multiple posts.
--
http://mail.python.org/mailman/listinfo/python-list
Iterating across a filtered list
All -
I'm currently writing a toy program as I learn python that acts as a
simple address book. I've run across a situation in my search function
where I want to iterate across a filtered list. My code is working
just fine, but I'm wondering if this is the most "elegant" way to do
this. Essentially, I'm searching the dict self.contacts for a key that
matches the pattern entered by the user. If so, I print the value
associated with that key. A pastie to the method is below, any help/
advice is appreciated:
http://pastie.caboo.se/46647
Side note: I'm learning python after ruby experience. In ruby I would
do something like:
contacts.find_all{|name,contact| name =~ /search/}.each{|name,contact|
puts contact}
--
http://mail.python.org/mailman/listinfo/python-list
Re: Iterating across a filtered list
On Mar 13, 2:42 pm, Paul Rubin <http://[EMAIL PROTECTED]> wrote:
> If I can decipher your Ruby example (I don't know Ruby), I think you
> want:
>
>for name,contact in contacts.iteritems():
> if re.search('search', name):
> print contact
>
> If you just want to filter the dictionary inside an expression, you
> can use a generator expression:
>
> d = ((name,contact) for (name,contact) in contacts.iteritems() \
> if re.search('search', name))
>
> print '\n'.join(d) # prints items from filtered dict, one per line
>
> Note that d is an iterator, which means it mutates when you step
> through it.
Paul -
You're exactly on the mark. I guess I was just wondering if your first
example (that is, breaking the if statement away from the iteration)
was preferred rather than initially filtering and then iterating.
However, you're examples make a lot of sense are are quite helpful.
Thanks,
Drew
--
http://mail.python.org/mailman/listinfo/python-list
dict.items() vs dict.iteritems and similar questions
When is it appropriate to use dict.items() vs dict.iteritems. Both seem to work for something like: for key,val in mydict.items(): print key,val for key,val in mydict.iteritems(): print key,val Also, when is it appropriate to use range() vs xrange(). From my understanding, xrange() essentially gives you an iterator across a range, so it should be used when iterating. Should you only use range() when want to physically store the range as a list? Thanks, Drew -- http://mail.python.org/mailman/listinfo/python-list
Re: dict.items() vs dict.iteritems and similar questions
On Mar 14, 11:44 am, Laurent Pointal <[EMAIL PROTECTED]> wrote: > Both work, you may prefer xrange/iteritems for iteration on large > collections, you may prefer range/items when processing of the result > value explicitly need a list (ex. calculate its length) or when you are > going to manipulate the original container in the loop. > > A+ > > Laurent. Laurent - Extremely helpful, exactly what I was looking for. Thanks, Drew -- http://mail.python.org/mailman/listinfo/python-list
Re: dict.items() vs dict.iteritems and similar questions
On Mar 14, 2:53 pm, [EMAIL PROTECTED] wrote: > >> When is it appropriate to use dict.items() vs dict.iteritems. > > Laurent> Both work, you may prefer xrange/iteritems for iteration on > Laurent> large collections... > > I find "iter" to be extremely ugly and hope to avoid using them > altogether until they are gone in Py3k. > > Skip Skip - Ugly, maybe, but don't you take a decent performance hit when loading the entire dict into memory at once? Especially if the dict is large? -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a list to a dictionary
On Mar 14, 4:52 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> res_dict = dict((r.get_id(), r) for r in res_list)
I'm using Python2.5 and it seems that this only gives me a hash with
the first id and first record. Am I doing something wrong?
>>> class Person():
... def __init__(self):
... self.id = 5
...
>>> mylist = []
>>> for i in range(100):
... mylist.append(Person())
...
>>> mydict = dict((r.id,r) for r in mylist)
>>> mydict
{5: <__main__.Person instance at 0x00A99EE0>}
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Converting a list to a dictionary
On Mar 14, 4:43 pm, "Samuel" <[EMAIL PROTECTED]> wrote: > What this does is it maps the id to the object. In your case, you only > have one id. > > -Samuel This is interesting behavior, but may not be what the original poster intended. If I understand correctly, this means that if more than one object shares the same id, only one copy will be created in the dict. Is this correct? -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a list to a dictionary
On Mar 14, 4:52 pm, "Samuel" <[EMAIL PROTECTED]> wrote: > On Mar 14, 9:48 pm, "Drew" <[EMAIL PROTECTED]> wrote: > > > This is interesting behavior, but may not be what the original poster > > intended. > > I am the original poster :). > > > If I understand correctly, this means that if more than one > > object shares the same id, only one copy will be created in the dict. > > Is this correct? > > Yes. Dictionaries are just hashes; you can't have the same key twice. > > Bye, > -Sam Doh! *Hangs head in shame and walks away slowly...* Thanks for you gracious response :) -- http://mail.python.org/mailman/listinfo/python-list
Code Explaination: Spelling correction code
I recently saw this website: http://www.norvig.com/spell-correct.html All the code makes sense to me save one line: def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) I understand (from seeing a ruby version of the code) that the goal here is to rerun the edits1 method on each member of the set returned by running edits1 on the initial word. However, I'm confused how the for within a for works. Can anyone help shed some light on this for me? -- http://mail.python.org/mailman/listinfo/python-list
Re: Code Explaination: Spelling correction code
On Apr 11, 11:27 pm, Steven Bethard <[EMAIL PROTECTED]> wrote: > Drew wrote: > > I recently saw this website:http://www.norvig.com/spell-correct.html > > > All the code makes sense to me save one line: > > > def known_edits2(word): > > return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in > > NWORDS) > > This is the same as: > > result = set() > for e1 in edits1(word): > for e2 in edits1(e1): > if e2 in NWORDS: > result.add(e2) > return result > > The thing between the ``set(`` and ``)`` is called a generator > comprehension if you'd like to look into it further. > > STeVe Steve - Thanks for the response. I'm somewhat familiar with generator/list comprehension but was unsure how multiple statements were evaluated when chained together. From your explanation, I'm assuming they are evaluated from the "inside out" rather than left to right or right to left. Does the mean that the comprehension on the inside is always evaluated first? Thanks, Drew -- http://mail.python.org/mailman/listinfo/python-list
Re: Code Explaination: Spelling correction code
On Apr 12, 10:28 am, Steven Bethard <[EMAIL PROTECTED]> wrote: > Drew wrote: > > On Apr 11, 11:27 pm, Steven Bethard <[EMAIL PROTECTED]> wrote: > >> Drew wrote: > >>> def known_edits2(word): > >>> return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in > >>> NWORDS) > > >> This is the same as: > > >> result = set() > >> for e1 in edits1(word): > >> for e2 in edits1(e1): > >> if e2 in NWORDS: > >> result.add(e2) > >> return result > > >> The thing between the ``set(`` and ``)`` is called a generator > >> comprehension if you'd like to look into it further. > > > Thanks for the response. I'm somewhat familiar with generator/list > > comprehension but was unsure how multiple statements were evaluated > > when chained together. From your explanation, I'm assuming they are > > evaluated from the "inside out" rather than left to right or right to > > left. > > > Does the mean that the comprehension on the inside is always evaluated > > first? > > Not really (at least for the most literal interpretation of ``evaluated > first``). I find it easiest to think of translating them into regular > for loops by adding the appropriate indentation. > > Starting with: > > (e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) > > Adding newlines: > > (e2 > for e1 in edits1(word) > for e2 in edits1(e1) > if e2 in NWORDS) > > Adding indentation: > > (e2 > for e1 in edits1(word) > for e2 in edits1(e1) > if e2 in NWORDS) > > Moving the add/append to the bottom: > > for e1 in edits1(word) > for e2 in edits1(e1) > if e2 in NWORDS > e2 > > Adding the remaining boiler-plate: > > result = set() > for e1 in edits1(word): > for e2 in edits1(e1): > if e2 in NWORDS: > result.add(e2) > > So multiple for- and if-expressions are evaluated in the same order that > they would normally be in Python, assuming the proper whitespace was added. > > HTH, > > STeVe Wow, thanks for having the patience to write that out. This makes perfect sense now. -Drew -- http://mail.python.org/mailman/listinfo/python-list
FastCGI on Windows: socket.fromfd() support?
Microsoft's IIS server recently added native support for FastCGI. The big roadblock to Python support seems to be that socket.fromfd() doesn't work on Windows. Are there any plans to add this or similar functionality to the Windows build? Thanks, Drew -- http://mail.python.org/mailman/listinfo/python-list
multiple file deletes using ftp.delete
Hi all
I'm fairly new to python so please forgive my lack of comprehension of
the obvious.
I'm writing a script to ftp files to a server. This script will run
weekly. Part of the script first deletes the previous weeks files. The
problem is I'm never sure of the exact number and full name of the
files that need to be deleted. All the files start with the same string
but have different extensions (eg drew.1 drew.2 drew.tmp drew.hlp). So
I was wondering if anybody knows how to use a wild card similar to * in
UNIX to do the delete? Something like:
ftp.delete("drew.*")
Any help or suggestions would be greatly appreciated.
Drew Dowling
--
http://mail.python.org/mailman/listinfo/python-list
Re: multiple file deletes using ftp.delete
On Jan 19, 11:16 pm, "Drew" <[EMAIL PROTECTED]> wrote:
> Hi all
> I'm fairly new to python so please forgive my lack of comprehension of
> the obvious.
>
> I'm writing a script to ftp files to a server. This script will run
> weekly. Part of the script first deletes the previous weeks files. The
> problem is I'm never sure of the exact number and full name of the
> files that need to be deleted. All the files start with the same string
> but have different extensions (eg drew.1 drew.2 drew.tmp drew.hlp). So
> I was wondering if anybody knows how to use a wild card similar to * in
> UNIX to do the delete? Something like:
>
> ftp.delete("drew.*")
>
> Any help or suggestions would be greatly appreciated.
>
> Drew Dowling
I should have summed if up thus: I'm trying to find a way to issue the
ftp mdelete command in python.
--
http://mail.python.org/mailman/listinfo/python-list
List Behavior when inserting new items
I'm looking to add an element to list of items, however I'd like to add it at a specific index greater than the current size: list = [1,2,3] list.insert(10,4) What I'd like to see is something like: [1,2,3,,4] However I see: [1,2,3,4] Is there any way to produce this kind of behavior easily? Thanks, Drew -- http://mail.python.org/mailman/listinfo/python-list
Re: List Behavior when inserting new items
> What is your actual usecase? > > diez The issue is that I don't know how long the list will eventually be. Essentially I'm trying to use a 2D list to hold lines that I will eventually print to the screen. Blank elements in the list will be printed as spaces. I suppose every time I add an element, I could find the difference between the size of the list and the desired index and fill in the range between with " " values, however I just wanted to see if there was a more natural way in the language. Thanks, Drew -- http://mail.python.org/mailman/listinfo/python-list
Re: List Behavior when inserting new items
> > Is there any way to produce this kind of behavior easily?Hints: > >>> [None] * 5 > [None, None, None, None, None] > >>> [1, 2, 3, None] + [10] > [1, 2, 3, None, 10] > > HTH That is exactly what I was looking for. I'm actually working on some problems at http://codgolf.com. I find it helps me to learn a language and I'm coming from ruby where arrays have subtle differences from python's lists. Thanks for all the helpful responses. -- http://mail.python.org/mailman/listinfo/python-list
Re: for -- else: what was the motivation?
the fuck? On Sat, Oct 22, 2022 at 9:06 AM Peter J. Holzer wrote: > On 2022-10-19 12:10:52 +1100, Chris Angelico wrote: > > On Wed, 19 Oct 2022 at 12:01, Peter J. Holzer wrote: > > > On 2022-10-17 09:25:00 +0200, Karsten Hilbert wrote: > > > > http://literateprogramming.com/ > > > > > > Right. That's one of the inspirations for my comment. > > > > > > But literate programming is of course still very much rooted in the > > > "linear text representation" paradigm. You have one definite source > > > which is a linear text. > > > > > > In a world of IDEs, databases and hypertext that's probably not the > best > > > we can do. As Raymond Hettinger would say, "there must be a better > way". > > > > > > It would be very different from mainstream programming languages, > > > however. And ideally you would want it to integrate with a lot of other > > > infrastructure. So that alone might make it a non-starter, even if it > > > was really good (which realistically early iterations wouldn't be). > > > > There are special-purpose languages like Scratch which are not simple > > text in that form. > > Yes, I know. > > It has a different goal though: Scratch tries to establish a friendly > learning environment. Get rid of typing and syntax errors that beginners > find so frustrating. > > What I'm interested in is an enviroment for developing medium-sized real > applications. Somewhere in the several person-months to several > person-years of effort, hundreds of user-stories, maybe thousands of > bug-reports and change-requests over its life-time. > > The people using such a system/language would be professional > programmers. They probably don't need much help to get the syntax of a > for loop right. What they do need, though: > > * Cross-reference between requirements and code. (Yes, you can write > comments, yes, you will hopefully have meaningful commit messages. > Still, I see a lot of room for improvements there) > * Cross-references between related parts of the code. (Yes, many IDEs > can jump to the definition of an instance or list all instances of a > definiton, But sometimes the relationship isn't that mechanic. And > yes, you can use comments fpr that, too) > * Views which highlight some parts of the code and omit others. (Folding > editors do that in a very limited fashion) > * For example, I might want to see only the code proper when I'm > focusing on an algorithm or I might want to see lots of context > (type definitions, requirements, test results, ...) > * Classes often have quite a lot of methods with no natural order. > Being able to view only a subset of them in some custom order may > help. > * Going back to the core idea of literate programming: Especially > views which show some requirement(s) together with the code that > implements them plus some explanation why that implementation was > chosen. > > Presented like this, it's clear that the "language" (i.e. the file > format) is probably the smallest part of the problem. How the user can > view the program, how they can edit it, and how to keep the whole thing > manageable is a much bigger question. And it would probably be a good > idea to start at the system level and not at the language level. > > > > My Twitch channel bot has a command executor whose language, if you > > call it that, is basically JSON - and the way to edit those commands > > is very Scratch-inspired. > > I designed a graphical filter language for database queries once. The idea > was that you could combine various operations (selects, projections, > grouping, transformations, ...) into pipelines via a web interface. We > did implement it (sadly it wasn't me who did it), and it turned out to > be a lot harder than I thought to make that actually usable. > > And of course there have been lots of CASE tools over the years. That > seems to have been mostly a fad of 90s. Still, there were some good > ideas there (although not alway implemented well), and something bubbles > back up every now and then. > > hp > > -- >_ | Peter J. Holzer| Story must make more sense than reality. > |_|_) || > | | | [email protected] |-- Charles Stross, "Creative writing > __/ | http://www.hjp.at/ | challenge!" > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Changing size of Win2k/XP console?
SetConsoleWindowInfo looks like a better candidate. See http://tinyurl.com/budzk (I.e. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/setconsolewindowinfo.asp) Haven't tried it though. Good luck! -- http://mail.python.org/mailman/listinfo/python-list
Re: tuple to string?
''.join((chr(e) for e in (0x73, 0x70, 0x61, 0x6D))) -- http://mail.python.org/mailman/listinfo/python-list
Re: retrieve data from 2 database
For a start, asking a better question will get better answers: http://www.catb.org/~esr/faqs/smart-questions.html Googling for python odbc gives this as the first result: http://www.python.org/windows/win32/odbc.html In general, how you compare database tables will depend a lot on the nature of the tables: e.g. are you comparing names to names, rows to rows, apples to oranges, etc.? -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding
Well, using the open function in Python doesn't launch any application
associated with the file (such as Media Player). It just makes the
contents of the file accessible to your Python code. Also, I think
using file("C:\file.txt") is now preferred to open("C:\file.txt").
To answer the specific question of how to play a music file in Python,
search Google Groups for: pygame.mixer.music.load("music.mp3")
That will bring up a useful thread. Note that you will need to install
a module such as pygame or pymedia; they are not in the standard
library.
In general, I would also recommend some of the many good Python
tutorials. Some are listed here:
http://wiki.python.org/moin/BeginnersGuide
Good luck!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Hiding
Ah, good point, thanks. Must stop forgetting that "C:\file.txt" is bad. The whole open()/file() clairification is useful too. The Python docs for the file() constructor simply state that, "File objects ... can be created with the built-in constructor file() described in section 2.1, 'Built-in Functions.'" (http://python.org/doc/2.4.1/lib/bltin-file-objects.html) That's followed by a footnote that states, "file() is new in Python 2.2. The older built-in open() is an alias for file()." At first sight, that to me suggests that open() has been somewhat deprecated by file(). However, the description of many of the file methods on the same page refers to opening files using open(), e.g.: "mode: The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter." It all becomes relatively clear in section 2.1, "Built-in Functions" where the entry for file() states, "The file() constructor is new in Python 2.2 and is an alias for open(). Both spellings are equivalent. The intent is for open() to continue to be preferred for use as a factory function which returns a new file object. The spelling, file is more suited to type testing (for example, writing 'isinstance(f, file)')." I guess that clears it up. Though perhaps the Python doc for the file() constructor should add that open() is the preferred general-purpose way to open a file or file-like object? Thanks again -- http://mail.python.org/mailman/listinfo/python-list
Re: Documentation
The standard pydoc module is very useful. A simple example of how you
could use it:
>>> import pydoc
>>> mymodule = pydoc.importfile(r"C:\My Py\my_foo.py")
>>> html = pydoc.html.page(pydoc.describe(mymodule),
>>> pydoc.html.document(mymodule))
>>> open("foo.html", "w").write(html)
Then you have a nice foo.html document for your module.
The above isn't necessarily the best way to use pydoc though it's
useful for a single-file bunch of classes. The documentation on pydoc
seems pretty sketchy, but reading the pydoc.py file is a good way to
learn how to use it.
--
http://mail.python.org/mailman/listinfo/python-list
Re: What is Python?!
Roy Smith wrote: "there's a system called Jython, which lets you compile Java source to Python byte code." Don't you have that the wrong way 'round? From the Jython website: "Jython is an implementation of the high-level, dynamic, object-oriented language Python written in 100% Pure Java, and seamlessly integrated with the Java platform. It thus allows you to run Python on any Java platform." In the case of Jython you could perhaps say that Python bytecode is "exactly like Java". However, in the case of regular Python, it's closer to say that Python bytecode is much the same _idea_ as Java bytecode. Jason -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorta noob question - file vs. open?
Both your code snippets above work should work OK. If it seems like a file isn't being written, maybe you should specify its full path so you are sure about where to check for it. On the file-or-open question, the Python docs state, "The intent is for open() to continue to be preferred for use as a factory function which returns a new file object." I happen to know that because it was clarified for me recently by a few posters in this informative thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/fbc7fbacf0866763 (which didn't start out as a file-or-open discussion, but there you go). Hope this helps, Jason -- http://mail.python.org/mailman/listinfo/python-list
python-list history
Hello folks, I’m interested in digging up some Python mailing list archives from ages past. Google Groups’ archive goes sporadically back to ’94, but clearly the list is older. Does any one have a lead on where I could get an archive of the very oldest posts to this list? Drew -- https://mail.python.org/mailman/listinfo/python-list
Re: Installing ssdeep on Portable Python
Were you able to solve this problem? I am also seeing this On Thursday, March 20, 2014 at 2:22:19 PM UTC-4, [email protected] wrote: > Portable Python 2.7 for Windows, the Python application have dependency on > ssdeep-2.10, which is a binary exe. > > The ssdeep (libfuzzy) installation example was shown for Linux platform only: > > a) libfuzzy can be installed via apt-get: > > $ sudo apt-get install libfuzzy2 > > b) to install libfuzzy from source, download the gzipped tarball from > http://ssdeep.sourceforge.net/#download, then run: > > $ tar -zxvf ssdeep-2.10.tar.gz > $ cd ssdeep-2.10 && ./configure && make && sudo make install > - > I need install it on PortablePython for Windows, so it's not clear how to > make this: where should be placed ssdeep Windows binary files, that Python > application can found it? -- https://mail.python.org/mailman/listinfo/python-list
Re: Guido at Google
And I have around one year to wait for Ruby to get rid of the nasty syntax copied from Perl and make it look as beautiful as Python Then I'll consider switching. ;) Ummm, I'm sorry, did you say clean reflective meta-model??? So this: caller[0] =~ /in `([^']+)'/ ? $1 : '(anonymous)' vs. the python example: filename, line, fname, source = traceback.extract_stack(limit=2)[0] return fname is what you call clean?? Hmmm ... interesting. -- http://mail.python.org/mailman/listinfo/python-list
Zenoss Version 0.22.3 Available
09-18-2006 Announcing Zenoss Version 0.22.3 All, Version 0.22.3 of Zenoss is available for download. Version 0.22.3 is a dot release of version 0.22.0, which added several new features, including: * Support for Nagios Plugins (zenagios) * Addition of a GUI for the selection of Alerting Rules * Adds Email alerts with configurable body text * Automated maintenance windows * Allows the assignment of users to the systems they manage Zenoss Version 0.22.3 provides several minor bug fixes and enhancements, including: * Use of latin-1 encoding when calling xml-rpc * Improved handling of Unicode items * Repaired bad zenagios heartbeat timeout * Corrected zenagios unpack of config (component and eventKey were backward) * Take off newline when reading configfile values * Fixed additional date-time zone problems Download Links: * Source: http://www.zenoss.org/download/latest/src * Zenwin: http://www.zenoss.org/download/latest/zenwin * Documentation: http://www.zenoss.org/download/latest/docs * Release Notes: http://www.zenoss.org/download/latest/relnotes Project Blurb: Zenoss is Python-based, network/systems monitoring application that offers a single integrated package for end to end monitoring (discovery, configuration, availability, performance, events, alerts) of resources across the stack (servers, applications, networks, environment, etc...). Zenoss was recognized as one of the "Top 10 Open Source Projects to Watch" by Network World in August of 2006. (http://www.zenoss.org/ about/news_items/articles/nw-10towatch) Zenoss is currently hiring talented Zope & Python developers. Join the team! http://www.zenoss.org/jobs. Enjoy, Drew Project Zenoss [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: converting sqlite return values
Hi, You can use the built-in function "eval" to return how Python evaluates your string. For example: >>> eval( '(1,2,3,4)' ) (1, 2, 3, 4) In other words, eval will take your string that looks like a tuple, and return an actual tuple object. Note that the 'u' prefix in your string will cause an error if you pass it to eval, so you should drop that, e.g.: >>> utuple = 'u(1,2,3,4)' >>> eval( utuple[1:] ) (1, 2, 3, 4) In general, though, converting your strings/tuples back and forth like this might not be the best idea, depending on the situation. If the numbers represent consistent items, like (price, tax, code, quantity), then you would do better to use a field for each item in your database and insert/fetch the numbers appropriately. Storing whole Python objects in single database fields isn't unheard of, but in general you should only do it when you really need to do it. When you do, there are various Python modules to help, though I haven't used this approach much myself. Jason -- http://mail.python.org/mailman/listinfo/python-list
Re: How to move optparse from main to function?
As pointed out, the module documentation is helpful.
For your 'test' option, I don't think 'action="count"' is the best
action. 'Test' is basically an on/off option, so why count it? I would
use:
parser.add_option("-t", "--test", action="store_true",
dest="optparse_test", default=False, help="testing optparse")
Then your code can use
if options.optparse_test == True: ...
or briefer:
if options.optparse_test: ...
As for putting the optparse code into a function, I sometimes use:
def parserSetup():
"""Return a configured option parser for this program."""
parser = OptionParser()
parser.add_option( ... your option stuff ... )
parser.add_option( ... )
return parser
if __name__=="__main__":
parser = parserSetup()
(options, args) = parser.parse_args()
# Then in your case:
if options.optparse_test: ...
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to move optparse from main to function?
You're welcome! As usual, each of us is free to write the code whichever way works best for the particular problem at hand. That's why the module documentation often avoids advocating here-is-the-one-best-way-to-do-it. I just like sticking all the option setup stuff in a single function because it's conceptually all the same and it makes the main() function or whatever read shorter. It's partly down to experience, what little of it I can claim. Good luck! -- http://mail.python.org/mailman/listinfo/python-list
Re: CGI on Windows
I believe you're experiencing a bug that I also encountered, and for which there is a patch. See: http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1110478 Fixing os.py as described in the patch fixed all my CGI-related problems. Hope it does for you too! Jason -- http://mail.python.org/mailman/listinfo/python-list
Re: CGI on Windows
Rainer Mansfeld wrote: > Jason Drew wrote: > > I believe you're experiencing a bug that I also encountered, and for > > which there is a patch. See: > > http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1110478 > > > > Fixing os.py as described in the patch fixed all my CGI-related > > problems. Hope it does for you too! > > > > Jason > > > > It did! > > Thanks a lot Jason. > You just saved my mental health. > >Rainer You're welcome! (And thanks too to June Kim and Martin v. Löwis for posting and fixing the bug, respectively, I think.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
It seems strange to want to set the values in actual variables: a, b,
c, ..., aa, ab, ..., aaa, ..., ...
Where do you draw the line?
A function seems more reasonable. "In terms of lines of code" here is
my terse way of doing it:
nrFromDg = lambda dg: sum(((ord(dg[x])-ord('a')+1) * (26 **
(len(dg)-x-1)) for x in xrange(0, len(dg
Then, for example
nrFromDg("bc")
gives
55
and
nrFromDg("aaa")
gives
703
and so on for whatever you want to evaluate.
This is efficient in terms of lines of code, but of course the function
is evaluating ord("a") and len(dg) multiple times, so it's not the most
efficient in terms of avoiding redundant calculations. And
nrFromDg("A") gives you -31, so you should really force dg into
lowercase before evaluating it. Oh, and it's pretty hard to read that
lambda expression.
"Least amount of code" == "best solution"
False
--
http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
We weren't really backwards; just gave a full solution to a half-stated
problem.
Bill, you've forgotten the least-lines-of-code requirement :-)
Mine's still a one-liner (chopped up so line breaks don't break it):
z = lambda cp: (int(cp[min([i for \
i in xrange(0, len(cp)) if \
cp[i].isdigit()]):])-1,
sum(((ord(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp[i].isdigit()])][x])-ord('A')+1) \
* (26 ** (len(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp[i].isdigit()])])-x-1)) for x in \
xrange(0, len(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp[i].isdigit()])]-1)
print z("B14")
# gives (13, 1)
Maybe brevity isn't the soul of wit after all ...
--
http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
Oh yeah, oops, thanks. (I mean the line continuations, not the alleged sin against man and nature, an accusation which I can only assume is motivated by jealousy :-) Or fear? They threw sticks at Frankenstein's monster too. And he turned out alright. My elegant "line" of code started out without the enclosing parentheses; forgot I didn't need the \s when I embraced it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
Er, yes! It's REALLY ugly! I was joking (though it works)! I retract it
from the code universe. (But patent pending nr. 4040404.)
Here's how I really would convert your (row_from_zero, col_from_zero)
tuple to spreadsheet "A1" coords, in very simple and easy to read code.
##def tuple2coord(tupl):
##def colnr2digraph(colnr):
##if colnr <= 26:
##return chr(ord('A') + colnr-1)
##m = colnr % 26
##if m == 0:
##m = 26
##h = (colnr - m) / 26
##return colnr2digraph(h) + colnr2digraph(m)
##
##rowfromzero, colfromzero = tupl
##row = rowfromzero+1
##col = colfromzero+1
##return colnr2digraph(col) + str(row)
##
##print tuple2coord((13,702))
### gives AAA14
### (because the tuple counts rows and columns from zero)
Note that this allows column nrs of any size, not just up to "ZZ". If
you really know the column limit is ZZ, then a lookup dictionary would
be a more efficient speed-wise solution. (Though I'd still use my nice
recursive no-brainer colnr2digraph function to populate the
dictionary.)
P.S. the line that says
h = (colnr - m) / 26
could really, in current Python, be just
h = colnr / 26
but the former is more language- and future-neutral.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
Sorry, scratch that "P.S."! The act of hitting Send seems to be a great way of realising one's mistakes. Of course you need colnr - m for those times when m is set to 26. Remembered that when I wrote it, forgot it 2 paragraphs later! -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert from numbers to letters
Hey, that's good. Thanks Steve. Hadn't seen it before. One to use. Funny that Pythonwin's argument-prompter (or whatever that feature is called) doesn't seem to like it. E.g. if I have def f(tupl): print tupl Then at the Pythonwin prompt when I type f( I correctly get "(tupl)" in the argument list pop-up box. But if I have def f((a, b)): print a, b then when I type f( I just get "(.0)" in the argument list pop-up box. Or with def f(p, q, (a, b)): pass Pythonwin prompts with "(p, q, .4)" However in each case the help() function correctly lists all the arguments. Strange. I'll check if it's a known "feature". This is with "PythonWin 2.4 (#60, Feb 9 2005, 19:03:27) [MSC v.1310 32 bit (Intel)] on win32." -- http://mail.python.org/mailman/listinfo/python-list
MySQL newsgroup proposal.
ANNOUNCEMENT: A RFD (REQUEST FOR DISCUSSION) has been posted for the creation of a new Usenet newsgroup: comp.databases.mysql The proposal and related discussion can be read in the Usenet group news.groups ... feel free to weigh in and make any suggestions you may have. Message-ID: <[EMAIL PROTECTED]> Link: http://makeashorterlink.com/?Z1061363B -- Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: Lists in classes
Thanks for clearing up the other incorrect answers! In true Python
fashion, I would also remind everyone of the *documentation* - in
particular the Python tutorial. These are very elementary mistakes to
be making - even worse as part of attempted answers.
The Python tutorial is at http://docs.python.org/tut/tut.html
In particular see the section on classes: http://docs.python.org/tut/node11.html
Note however that the tutorial doesn't show the current best practice
of subclassing your classes from "object", i.e.
class MyClass(object):
#...etc...
-Jason
On Jul 12, 11:51 am, Wildemar Wildenburger <[EMAIL PROTECTED]>
wrote:
> Bart Ogryczak wrote:
> > On 12 jul, 17:23, Jeremy Lynch <[EMAIL PROTECTED]> wrote:
>
> >> Hello,
>
> >> Learning python from a c++ background. Very confused about this:
>
> >>
> >> class jeremy:
> >> list=[]
>
> > You've defined list (very bad choice of a name, BTW), as a class
> > variable. To declare is as instance variable you have to prepend it
> > with "self."
>
> Ouch!
>
> 'self' is *not* a reserved ord in python, it doesn't do anything. So
> just popping 'self' in front of something doesn't bind it to an instance.
> Here is how it works:
>
> class Jeremy(object): # you better inherit from 'object' at all times
> classlist = [] # class variable
> def __init__(self): # "constructor"
> self.instancelist = [] # instance variable
> def add_item(self, item):
> self.instancelist.append(item)
>
> 'self' is the customary name for the first argument of any instance
> method, which is always implicitly passed when you call it. I think it
> translates to C++'s 'this' keyword, but I may be wrong. Simply put: The
> first argument in an instance-method definition (be it called 'self' or
> otherwise) refers to the current instance.
> Note however that you don't explicitly pass the instance to the method,
> that is done automatically:
>
> j = Jeremy() # Jeremy.__init__ is called at this moment, btw
> j.add_item("hi") # See? 'item' is the first arg you actually pass
>
> I found this a bit confusing at first, too, but it's actually very
> clean, I think.
> /W
--
http://mail.python.org/mailman/listinfo/python-list
Re: simple regular expression problem
You just need a one-character addition to your regex:
regex = re.compile(r'', re.S)
Note, there is now a question mark (?) after the .*
By default, regular expressions are "greedy" and will grab as much
text as possible when making a match. So your original expression was
grabbing everything between the first opening tag and the last closing
tag. The question mark says, don't be greedy, and you get the
behaviour you need.
This is covered in the documentation for the re module.
http://docs.python.org/lib/module-re.html
Jason
On Sep 17, 9:00 am, duikboot <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am trying to extract a list of strings from a text. I am looking it
> for hours now, googling didn't help either.
> Could you please help me?
>
> >>>s = """
> >>>\n\n28996\n\n\n28997\n"""
> >>> regex = re.compile(r'', re.S)
> >>> L = regex.findall(s)
> >>> print L
>
> ['organisatie>\n28996\n
> \n\n28997\n
> I expected:
> [('organisatie>\n28996\n
> \n), (\n28997\n organisatie')]
>
> I must be missing something very obvious.
>
> Greetings Arjen
--
http://mail.python.org/mailman/listinfo/python-list
Re: simple regular expression problem
You're welcome!
Also, of course, parsing XML is a very common task and you might be
interested in using one of the standard modules for that, e.g.
http://docs.python.org/lib/module-xml.parsers.expat.html
Then all the tricky parsing work has been done for you.
Jason
On Sep 17, 9:31 am, duikboot <[EMAIL PROTECTED]> wrote:
> Thank you very much, it works. I guess I didn't read it right.
>
> Arjen
>
> On Sep 17, 3:22 pm, Jason Drew <[EMAIL PROTECTED]> wrote:
>
> > You just need a one-character addition to your regex:
>
> > regex = re.compile(r'', re.S)
>
> > Note, there is now a question mark (?) after the .*
>
> > By default, regular expressions are "greedy" and will grab as much
> > text as possible when making a match. So your original expression was
> > grabbing everything between the first opening tag and the last closing
> > tag. The question mark says, don't be greedy, and you get the
> > behaviour you need.
>
> > This is covered in the documentation for the re
> > module.http://docs.python.org/lib/module-re.html
>
> > Jason
>
> > On Sep 17, 9:00 am, duikboot <[EMAIL PROTECTED]> wrote:
>
> > > Hello,
>
> > > I am trying to extract a list of strings from a text. I am looking it
> > > for hours now, googling didn't help either.
> > > Could you please help me?
>
> > > >>>s = """
> > > >>>\n\n28996\n\n\n28997\n"""
> > > >>> regex = re.compile(r'', re.S)
> > > >>> L = regex.findall(s)
> > > >>> print L
>
> > > ['organisatie>\n28996\n
> > > \n\n28997\n
> > > I expected:
> > > [('organisatie>\n28996\n
> > > \n), (\n28997\n > > organisatie')]
>
> > > I must be missing something very obvious.
>
> > > Greetings Arjen
--
http://mail.python.org/mailman/listinfo/python-list
Re: greatest and least of these...
What do you mean when you say the menu doesn't kick in? Do you get an
exception, or does simply nothing happen?
Before the if statements, you should put "print choice" so you can see
what value is being returned by the input function. Also maybe "print
type(choice)" for a bit more inspection.
Speaking of which, you should probably be using something like
"int(raw_input())" instead of just "input()" - if you read the help on
the two functions you should see why.
Hope this helps.
Jason
On Oct 23, 11:56 am, Shawn Minisall <[EMAIL PROTECTED]> wrote:
> I just wrote a program to let the user input a series of whole numbers
> and tell them which is least and which is greatest based off of a menu.
> However, the menu isn't kicking in after they pick a number. I included
> a while statement for a loop just for the menu and compared it to my
> other programs that have a similar setup and are working, but I'm
> stumped. Here's the program...
>
> def main():
>
> #define and initialize variables
> #choice as int
> choice = 0
> #number as int
> number = 0
>
> #intro
> print "WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM!"
> print
>
> #Menu loop
> while choice != 2:
> #display menu
> print "Please choose from the following menu: "
> print "1. Enter a number"
> print "2. Exit"
> print
>
> #prompt user for their menu choice
> choice = input("Enter your choice here: ")
>
> #if statements to determine which choice
> if choice == 1:
> nums = []
> while number >=0:
> nums.append(number)
> number = input("Please enter a number.")
>
> elif choice == 2:
> print "Have a great day!"
>
> if len(nums) > 0:
> print "The smallest number that you entered was:",min(nums)
> print "The largest number that you entered was:",max(nums)
>
> else:
> #invalid
> print "Invalid selection. Enter either one or two."
> print
>
> Also, if they quit the program with choice #2 and entered numbers, it
> should display the greatest and least of them. If they just started and
> didn't enter anything and want to quit, I get an error message saying
> UnboundLocalError: local variable 'nums' referenced before assignment.
> Isn't the if statement supposed to keep python from going there since if
> they didn't enter any input, the length of the list should just be zero.
--
http://mail.python.org/mailman/listinfo/python-list
filter func chaining
I am trying to chain filter functions together so I created these 2 functions. def AndChain(*filters): return (lambda asset: reduce((lambda r, f: apply(f, asset) and r), filters)) def OrChain(*filters): return (lambda asset: reduce((lambda r, f: apply(f, asset) or r), filters)) Where filters are simply functions that take a single argument and return true or false. My intention is to use these functions like this: f = AndChain(AssetTypeFilter(), CurrencyFilter()) filteredCol = filter(f, col) I am receiving the following error (where Asset is the type of items in my collection) Traceback (most recent call last): File , line 0, in ##44 File c:\proj\ofts\com.oakwoodft.ofts.compliance\complianceframework\filters\assetfilters.py, line 5, in is not enumerable Am I going about this totally wrong? Is there a better solution? Thanks. Drew Schaeffer -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help improving number guessing game
On Dec 15, 1:29 pm, feba wrote: > 6; can anyone think of anything else to add on to/do with this game? > With the minr/maxr display, multiplayer, score keeping, and > automation, I'm just about all of ideas. All I can think of left to > add is 3 and 4 player modes, or a fork where player 2 can't win > (kekekekeke. Though I'm not sure how to do it...), both of which I > feel are somewhat pointless for a game like this. If I can't learn > anything more from it, I will probably go back to reading python > guides for a bit, and then try to make something else. Well, if you want to aim for several more rounds of refinement, how about having the game allow many players identified by name and have it keep records in a file: player name, number of times played, best score, best elapsed time for game completion - for each player. Can you do it in such a way that multiple people on different PC's can all play the game at the same time and not scribble over each other's scores? One approach would be to insist that the player's computers be able to share access to a particular directory, perhaps using a network mount of a disk from somewhere. A fancier approach would be to have a score keeping "service" that runs somewhere and each player's computer uses the network to interact with that score keeping service. Besides the game playing front end to the score keeping service, maybe you should have an administrative front end to the score keeping service to allow you to delete the names of deceased game players. (The only thing keeping him on his perch were tiny little nails through his feet). Can just anyone play the game or does the administrator have to add their name as an authorized player to the score keeping service before they are allowed to play? Is it "Scout's honor" that palyers are who they say they are, or is there some kind of authentication for a player to "prove" their identify before they are allowed to play? I remember many years ago back in graduate school, a friend implemented a clone of "pong" with record keeping. People would sit with that stupid game into the middle of the night striving to improve their standings in the best score display. May be more addictive with a "harder" game than this number guessing game but having your score being visible to other players can be powerful motivation to strive for better scores. If only my friend had figured out a way to have the little DEC GT40 demand quarters if the player wanted to play again, he'd have had most of his tuition nicely covered. If your mind is ready to try something completely different, another thing you could strive to do is change the game from a "tty" interface to something more screen oriented. e.g. instead of having a prompt for "play again (y or n):" you'd have buttons on the screen that the player can click that say "quit" or "start new game". Note that the player might decide to click on either of those buttons at any time, not just after they have completed a game. Python has several many different libraries that would give you a basis for building such a "graphical user interface" (GUI) version of your game, but I'm not experienced enough to tell you which GUI package you should look into. Not so much related to the business of making a niftier game, but another area you might want to look into is change management (e.g. "subversion") so you can track the evolution and refinement of your source code over time. The player-visible part of that is perhaps just to have something that announces which revision of the game they are running such that you can tell from that which revision of the source code to look at if you are tracking down a fix for a problem they have encountered and reported to you. Drew -- http://mail.python.org/mailman/listinfo/python-list
