Re: Best way to protect my new commercial software.
On Dec 10, 8:15 am, farsheed <[EMAIL PROTECTED]> wrote: > I wrote a software and I want to protect it so can not be cracked > easily. I wrote it in python and compile it using py2exe. what is the > best way in your opinion? Don't. This is a fight you already lost. Besides, people who crack software are either students with no money or people who never buy software. Students who crack your software today might be your customers tomorrow. If your software is a real hassle to crack, they will crack your competitor's app and use it. Wouldn't you rather have them use your app? They might be talking about it to their friends. -- http://mail.python.org/mailman/listinfo/python-list
Job Offer: Python Ninja or Pirate!
Etsy is an online marketplace for buying and selling all things handmade: clothing, music, furniture, software, jewelry, robots. We launched on June 18, 2005, and ever since then have been empowering our users to make a living doing what they love most. Just a few months ago, we found a few amazingly talented ninjas and even a few swarthy pirates. The team is doing wonderfully, and we're hoping to add a few more adventure-loving souls to our ranks. You'll be using python, javascript and other technologies to whip up innovative web applications in many challenging and interesting domains: social and community, ecommerce, search, and even software development. We're also in the process of redesigning and developing our web stack to allow us to scale into outer space while still providing a fun and productive programming environment. You'll likely end up working on our: in-house orm, customized cherrypy environment, jinja templates, django-like form processing library, lucene integration, twisted-based communications protocol, or kick-ass high-performance memcached library. Required: * 5+ years of web development experience * 3+ years of writing production-level code with a dynamic language (python, ruby, lisp, smalltalk, OO javascript, etc) * Strong OOP skills * Understanding of dynamic language idioms and patterns * Ability and willingness to pick up other languages and technologies Desired: * Ability to write python code idiomatically * Lives in New York City * Experience with javascript * Experience with java, postgresql and/or php Neat: * Plays guitar hero Challenge: A valid response will be either a solution to the problem below, or a link to some code of which you are particularly proud. Problem: In the dynamic language of your choice, write a short program that will: 1. define a list of the following user ids 42346, 77290, 729 (you can hardcode these, but it should still work with more or less ids) 2. retrieve an xml document related to each user at this url "http:// api.etsy.com/feeds/xml_user_details.php?id=" 3. retrieve the data contained in the city element from each xml document 4. keep a running total of how many users are found in each city 5. display the total count of users living in each city You can assume user ids are valid and that the url is available. The output should look something like: Charlotte: 1 New York: 2 You can find out more about etsy at http://www.etsy.com or http://blog.etsy.com/jobs/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: My very first python web app (no framework)
On 9 Dic, 15:43, [EMAIL PROTECTED] wrote:
> This is my first Python web pseudo-app: "you give me some data, I give
> you func(data)". I'm on a shared host with mod_fastcgi so I installed
> a virtual python environment + flup (no middleware now, just wsgi
> server).
>
> = dispatch.fcgi =
> from fcgi import WSGIServer
> import sys, cgi, cgitb,os
> import myfunctions
>
> def myapp(environ, start_response):
> start_response('200 OK', [('Content-Type', 'text/html')])
> write = []
> write.append (myfunctions.func1(par1,par2))
> write.append (myfunctions.func2(par1,par2))
> # [...]
> write.append (myfunctions.funcn(par1,par2))
> return [write]
>
> if __name__=="__main__":
> WSGIServer(myapp).run()
>
>
> == myfunctions.py ==
> def func1(a,b):
> return a
> def func2(a,b):
> return b
>
>
> Is it the right way to go? Is it safe in a web production
> environment ? Is it thread-friendly (since flup is threaded) ?
>
> tnx
Any hint ?
--
http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
On Dec 9, 1:15 am, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Richard Jones a écrit : > > > > > Bruno Desthuilliers wrote: > > >>class A(object): > >> @apply > >> def a(): > >> def fget(self): > >> return self._a > >> def fset(self, val): > >> self._a = val > >> return property(**locals()) > >> def __init__(self): > >> self.a = "foo" > > > That property setup seems overly complicated. As far as I can see, it only > > avoids defining the setter in the class namespace, > > Yes. That's mosly the point. > > > yet is more complicated > > and obfuscated to boot ;) > > Well, that's your POV, so what can I say ? It's indeed a bit hackish, > and requires a couple minutes of attention the first time you see it. > And you just have to learn it once !-) > > Now I'd certainly prefer something like: > > class A(object): > @propget > def a(self): > return self._a > @propset > def a(self, val): > self._a = val > > But until there's something similar *builtin*, I'll stick to the @apply > trick. I like Guido's proposal for read/write properties. http://mail.python.org/pipermail/python-dev/2007-November/075182.html It works pretty well and is readable. -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On Dec 9, 10:54 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Dec 10, 9:43 am, "Just Another Victim of the Ambient Morality" > > <[EMAIL PROTECTED]> wrote: > > I'm looking for a linked list implementation. Something iterable with > > constant time insertion anywhere in the list. > > It's on the shelf between the jar of phlogiston and the perpetual > motion machine. I recommend a quick glance at any article on linked list. Here's one: http://en.wikipedia.org/wiki/Linked_list -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
abusing exceptions for continuations
i've had this strange idea of using the exception's traceback (which holds the stack frame) to enable functional continuations, meaning, raise some special exception which will be caught by a reactor/ scheduler/framework, which could later revive it by restoring the frame. i'm thinking of using the generator's implementation (some minimal support on the c-side) has this been tried before? what were the results? thanks, -tomer -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
Thanks. But I ask this question technically, I mean I know nothing is uncrackable and popular softwares are not well protected. But my software is not that type and I don't want this specific software popular. It is some kind of in house tool and I want to copy protect it. this is very complicated tool and not useful for many people. indeed this is an animation manging tool I wrote for my company. So if you have any idea that what is the best way to do it, I'll appreciate that. -- http://mail.python.org/mailman/listinfo/python-list
Re: setdefaultencoding error
thank you very much I have solved -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get module globals into a class ?
stef mientki wrote: > hello, > > this question may look a little weird, > but I want to create library shells that are a simple as possible. > > So I've a module where one base class is defined, > which looks like this (and might be complex) > > base_class_file.py > class brick_base ( object ) : > > > now I've a lot of library files, > in each library file are a lot of classes, > and each library-file, has some specific parameters, like "library_color", > so something like this: > > library_file.py > library_color = ... > > class brick_do_something1( brick_base ) : > init : > self.Library_Color = Library_Color > > > class brick_do_something2( brick_base ) : > init : > self.Library_Color = Library_Color > > > Now this works fine, ... > ... but the statement "self.Library_Color = Library_Color" > is completely redundant, because it should be in every class of every > librray file. > So I would like to move this statement to the base-class-file, > but I can't figure out how to accomplish that. You can use a hack like class Base(object): def __init__(self): module = __import__(self.__module__) self.library_color = module.library_color But I think it's better to add another level to the class hierarchy: class BrickBase(object): def __init__(self): self.library_color = self.library_color class LibraryBase(BrickBase): library_color = "blue" class BrickDoSomethingN(LibraryBase): pass (all untested) Peter -- http://mail.python.org/mailman/listinfo/python-list
RE: I'm missing something here with range vs. xrange
>You can't imagine why someone might prefer an iterative solution over >a greedy one? Depending on the conditions, the cost of creating the >list can be a greater or a lesser part of the total time spent. Actual >iteration is essentially the same cost for both. Try looking at memory >usage while you're running these tests. I can imagine why someone would want to use in iterative solution. What I don't understand is why there's so little difference between the two. Here's what I think is going on; To do a range(100) 1. Allocate a big chunk of memory 2. Fill the memory with the range of integers 3. Setup an index into the memory array 4. Every time the program asks for the next item, bump the memory index by one, get the value and return it. To do an xrange(1000) 1. Set up a counter 2. Every time the program asks for the next item, increment the counter and return it. I guess I thought that between these two methods, the second would be dramatically faster. An order of magnitude faster. My surprise is that it's not. That's why I figured I'm missing something because the above steps don't seem to describe what's going on. Hence, the title, "I'm missing something". -- http://mail.python.org/mailman/listinfo/python-list
RE: I'm missing something here with range vs. xrange
>You bring up an excellent point. It might seem like I'm actually running on >a Macbook Pro with an Intel Core 2 Duo at 2.33 GHz with 2 GB of ram. Err... Uhh... What I meant to say was "It might seem like I'm running on an old slow POS but I'm actually running on a Macbook Pro..." Sorry, me flunk english and don't speek too good. -- http://mail.python.org/mailman/listinfo/python-list
a way to keep track of # of clicks
Is there a way to keep track of the number of times someone clicks on a menu item in a prorgam? What I want to do is make the rectangle disappear after they click on it at the main menu 3 times so visually show them they can't do it any longer. Since I appended the button to a main menu list, I would think undrawing it would have something like pop.mainMenuList[8] in it after they click on it three times. (not in succession, after it takes them to the questions screen and then back to the main menu) Any suggestions? thx -- http://mail.python.org/mailman/listinfo/python-list
Re: a strange SyntaxError
> self.numlines = self.config['numlines'] > > self.w = 520 > self.h = 12*self.numfeeds*(self.numlines+1) why extra ident here? -- Vladimir Rusinov GreenMice Solutions: IT-решения на базе Linux http://greenmice.info/ -- http://mail.python.org/mailman/listinfo/python-list
Converting HTML TO PDF using PYTHON
Please tell me if we can convert a html file into a pdf using python..i am using Python 2.3.4.Regards, ---ViNOJ DAViS--- Get the freedom to save as many mails as you wish. Click here to know how. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On Dec 10, 9:55 am, farsheed <[EMAIL PROTECTED]> wrote: > Thanks. But I ask this question technically, I mean I know nothing is > uncrackable and popular softwares are not well protected. But my > software is not that type and I don't want this specific software > popular. > It is some kind of in house tool and I want to copy protect it. this > is very complicated tool and not useful for > many people. indeed this is an animation manging tool I wrote for my > company. So if you have any idea that what is the best way to do it, > I'll appreciate that. Oh, then sorry, I never gave much thought to it. If you're not afraid of legal troubles, you could have it silently phone home so you can know how many apps are in use at any moment. Given the scale of your app, it should be feasible for you to simply contact users who didn't pay and kindly ask them to pay. The fact that pyc files are so easily de-compiled makes app protection pretty hard... -- http://mail.python.org/mailman/listinfo/python-list
Re: searching a value of a dict (each value is a list)
Adonis Vargas: > Also, you should never use reserved words like 'dict' this creates > confusion and can cause Python to misbehave since you are rebinding the > name. > Adonis Vargas After hearing this suggestion for the 300th time, I think it may be the moment to fix this problem in Python3, and make the Python compiler issue a syntax error if someone tries to reassign such kind of words, like dict, set, etc. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Guide me on Apache Virtual server+mod_python
thanks a lot. I am still trying to get it working. I think i will have to register those subdomains in CISCO as the hostame of same ip somehow. For the same configuration, I can have those subdomains.domain.ext open in my localhost, but from other system, I can't access it. No comments or error discriptions right now from my side. I would like to work a little more to get to some point and then let you all know what exactly the problem is. Again, thanks a lot for the help. On Dec 5, 2007 7:31 PM, Ravi Kumar <[EMAIL PROTECTED]> wrote: > HI, > I am sorry for OT here. But I search google, could not quench my thrist, > so came here, and for single question, I don't want to subscribe in Apache > Newsgroup. > The problem is : > i wwant to implement a mod_python based Website + Reporting Application on > my system. > > In the domain, my system is : mysys.domain.com > Now, I want to implement two subdomains on my apache server: > http://www.site.com > http://report.site.com > Means two or multiple subdomains on same Apache Server. > Only one IP Address and NIC is allocated in System (can't go for two IPs). > Network has CISCO Routers . > So can you please guide me a little, on how to do it. I just need some > pointers and I will start finding them on Google. > > > -- > -=Ravi=- I am definitely not an expert, but no one else answered so here is how I did it. Look in the apache2 directory: 'conf'. then the subdirectory: 'extra' for the file: httpd-vhosts.conf. It contains sample code that you can use. This may not be exactly like your installation. I am using Apache2Triad. What you want is something like this: ServerName report.site.com ServerAlias report.site.com DocumentRoot /apache2triad/htdocs/www.domain.com ServerAdmin [EMAIL PROTECTED] ErrorDocument 403 http://www.site.com/403.htm ErrorDocument 404 http://www.site.com/404.htm There are some other related code changes. Just search httpd.conf and the vhosts file for virtual and hosts and you should find all the code you need commented. Also, google has many tutorials. I did this about 6 years ago so I don't remember where I got the information, but there were many references. Note that you can have as many virtual hosts as you want with one IP, but (to my knowledge) you cannot have SSL on more than one web site with one IP unfortunately. Some guru needs to do this. - Show quoted text - - Original Message - From: "Ravi Kumar" <[EMAIL PROTECTED]> To: Sent: Wednesday, December 05, 2007 6:01 AM Subject: [OT] Guide me on Apache Virtual server+mod_python HI, I am sorry for OT here. But I search google, could not quench my thrist, so came here, and for single question, I don't want to subscribe in Apache Newsgroup. The problem is : i wwant to implement a mod_python based Website + Reporting Application on my system. In the domain, my system is : mysys.domain.com Now, I want to implement two subdomains on my apache server: http://www.site.com http://report.site.com Means two or multiple subdomains on same Apache Server. Only one IP Address and NIC is allocated in System (can't go for two IPs). Network has CISCO Routers . So can you please guide me a little, on how to do it. I just need some pointers and I will start finding them on Google. -- -=Ravi=- -- http://mail.python.org/mailman/listinfo/python-list -- -=Ravi=- -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On Dec 10, 7:37 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > On Dec 9, 10:54 pm, John Machin <[EMAIL PROTECTED]> wrote: > > > On Dec 10, 9:43 am, "Just Another Victim of the Ambient Morality" > > > <[EMAIL PROTECTED]> wrote: > > > I'm looking for a linked list implementation. Something iterable with > > > constant time insertion anywhere in the list. > > > It's on the shelf between the jar of phlogiston and the perpetual > > motion machine. > > I recommend a quick glance at any article on linked list. > Here's one:http://en.wikipedia.org/wiki/Linked_list > A rather silly way of describing it ... of course once you have done a search to find where to insert a new element, it takes a trivial constant time to insert the new element into the linked list. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting Excel time-format (hours since 1.1.1901)
On 9 Dez., 18:38, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > On Dec 9, 8:52�am, Dirk Hagemann <[EMAIL PROTECTED]> wrote: > > > > > On 7 Dez., 22:36, John Machin <[EMAIL PROTECTED]> wrote: > > > > On Dec 8, 12:20 am, Dirk Hagemann <[EMAIL PROTECTED]> wrote: > > > > > Hello, > > > > > From a zone-file of a Microsoft Active Directory integrated DNS server > > > > I get the date/time of the dynamic update entries in a format, which > > > > is as far as I know the hours since january 1st 1901. > > > > As Tim Golden has guessed, it is the number of hours since > > > 1601-01-01T00:00:00. Weird but true. See (for > > > example)http://www.netpro.com/forum/messageview.cfm?catid=15&threadid=457 > > > > > For Example: the number 3566839 is 27.11.07 7:00. > > > > Y2K bug! The number 3566839 is a representation of > > > 2007-11-27T07:00:00. > > > > > To calculate this in > > > >ExcelI use this: > > > > ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0) �(put > > > > 3566839 in field A1 and switch the format of the result-field to the > > > > corresponding date-time format). > > > > "01.01.1901" => date(1901, 1, 1) > > > > (A1/24-(REST(A1;24)/24)) => (A1/24-(MOD(A1,24)/24)) > > > which simplifies to INT(A1/24) > > > > ZEIT(REST(A1;24);0;0) => TIME(MOD(A1,24),0,0) > > > > This is a convoluted way of writing DATE(1901, 1, 1) + A1 / 24 > > > > Your result is "correct" apart from the century. This is the result of > > > two canceling errors (1) yours in being 3 centuries out of kilter (2) > > > Microsoft's in perpetuating the Lotus 123 "1900 is a leap year" bug. > > > > If you must calculate this inExcel, this formula might be better: > > > > =DATE(2001, 1, �1) + A1 / 24 - 146097 > > > > (146097 is the number of days in a 400-year cycle, 400 * 365 + 100 - 4 > > > + 1) > > > > > You might guess what I need now: I want to calculate this somehow in > > > > python. > > > > > Sorry, but I couldn't find anything in the module time or something > > > > else to get this calculated. > > > > > Does anyone know how to convert this time in python to something > > > > usable or how to convert this formula in python? > > > > One very slight change to what Tim Golden suggested: make the result a > > > datetime, not a date. > > > > >>> dnsdatetime2py = lambda x: datetime.datetime(1601,1,1,0,0,0) + > > > >>> datetime.timedelta(hours=x) > > > >>> dnsdatetime2py(3566839) # your example > > > > datetime.datetime(2007, 11, 27, 7, 0)>>> dnsdatetime2py(3554631) # > > > example in cited web posting > > > > datetime.datetime(2006, 7, 6, 15, 0) > > > > HTH, > > > John > > > YES - that's it! > > Thanks a lot to John, Tim and all the others who helped me to handle > > this time format!!! > > > I was irritated by the date of 01.01.1901 in the Excel formula, but in > > the end it was obvious that it has to be hours since 1601. Who knows > > how Excel calculates in the background... > > Everyone knows. Excel assumes an integer is > DAYS SINCE 1900 and all it's calculations > are based on that assumption. > > It's YOUR fault if you give Excel an integer > that represents HOURS SINCE 1601, so don't > expect meaningful calculations from Excel if > you give it an incorrect data type. > > > > > Enjoy the sunday and have a great week! > > Dirk Sorry, but then I seem not to belong to "everyone". And it was not me who created this Excel-formula, I just posted it as a kind of help. And actually I just asked if somebody knows something about this time- format and how to convert it. I think I already wrote that I did a mistake and not Excel. -- http://mail.python.org/mailman/listinfo/python-list
Re: searching a value of a dict (each value is a list)
On 12월10일, 오후12시18분, Adonis Vargas <[EMAIL PROTECTED]>
wrote:
> Seongsu Lee wrote:
> > Hi,
>
> > I have a dictionary with million keys. Each value in the
> > dictionary has a list with up to thousand integers.
> > Follow is a simple example with 5 keys.
>
> > dict = {1: [1, 2, 3, 4, 5],
> >2: [10, 11, 12],
> >90: [100, 101, 102, 103, 104, 105],
> >91: [20, 21, 22],
> >99: [15, 16, 17, 18, 19]}
>
> > I want to find out the key value which has a specific
> > integer in the list of its value. For example, if I search
> > 104 in the list, 90 must be returned.
>
> > How can I do this with Python? Ideas?
>
> You can try this:
>
> items = {1: [1, 2, 3, 4, 5],
> 2: [10, 11, 12],
> 90: [100, 101, 102, 103, 104, 105],
> 91: [20, 21, 22],
> 99: [15, 16, 17, 18, 19]}
>
> def findItem(item, dictionary):
> for key, value in dictionary.iteritems():
> if item in value:
> print key, value
>
> findItem(104, items)
>
> This will allow you to work with the existing dataset without needing to
> duplicate it. It will print all occurrances.
Hi,
Yes, it works. But I think it works in O(n * m), doesn't it?
(n is # of keys in the dictionary and m is # of items in the list.)
So, we need to create a reverse index. (a reverse dictionary) or
need something better at least, I think.
> Also, you should never use reserved words like 'dict' this creates
> confusion and can cause Python to misbehave since you are rebinding the
> name.
Yep. :)
> Hope this helps.
>
> Adonis Vargas- 따온 텍스트 숨기기 -
>
> - 따온 텍스트 보기 -
--
http://mail.python.org/mailman/listinfo/python-list
Re: dictionary of dictionaries
kettle wrote:
> On Dec 9, 5:49 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Sun, 09 Dec 2007 00:35:18 -0800, kettle wrote:
>> > Hi,
>> > I'm wondering what the best practice is for creating an extensible
>> > dictionary-of-dictionaries in python?
>>
>> > In perl I would just do something like:
>>
>> > my %hash_of_hashes;
>> > for(my $i=0;$i<10;$i++){
>> > for(my $j=0;$j<10;$j++){
>> >${$hash_of_hashes{$i}}{$j} = int(rand(10));
>> > }
>> > }
>>
>> > but it seems to be more hassle to replicate this in python. I've
>> > found a couple of references around the web but they seem cumbersome.
>> > I'd like something compact.
>>
>> Use `collections.defaultdict`:
>>
>> from collections import defaultdict
>> from random import randint
>>
>> data = defaultdict(dict)
>> for i in xrange(11):
>> for j in xrange(11):
>> data[i][j] = randint(0, 10)
>>
>> If the keys `i` and `j` are not "independent" you might use a "flat"
>> dictionary with a tuple of both as keys:
>>
>> data = dict(((i, j), randint(0, 10)) for i in xrange(11) for j in xrange(11))
>>
>> And just for completeness: The given data in the example can be stored in a
>> list of lists of course:
>>
>> data = [[randint(0, 10) for dummy in xrange(11)] for dummy in xrange(11)]
>>
>> Ciao,
>> Marc 'BlackJack' Rintsch
>
> Thanks for the heads up. Indeed it's just as nice as perl. One more
> question though, this defaultdict seems to only work with python2.5+
> in the case of python < 2.5 it seems I have to do something like:
> #!/usr/bin/python
> from random import randint
>
> dict_dict = {}
> for x in xrange(10):
> for y in xrange(10):
> r = randint(0,10)
> try:
> dict_dict[x][y] = r
> except:
> if x in dict_dict:
> dict_dict[x][y] = r
> else:
> dict_dict[x] = {}
> dict_dict[x][y] = r
You can clean that up a bit:
from random import randrange
dict_dict = {}
for x in xrange(10):
dict_dict[x] = dict((y, randrange(11)) for y in xrange(10))
> what I really want to / need to be able to do is autoincrement the
> values when I hit another word. Again in perl I'd just do something
> like:
>
> my %my_hash;
> while(){
> chomp;
> @_ = split(/\s+/);
> grep{$my_hash{$_}++} @_;
> }
>
> and this generalizes transparently to a hash of hashes or hash of a
> hash of hashes etc. In python < 2.5 this seems to require something
> like:
>
> for line in file:
> words = line.split()
> for word in words:
> my_dict[word] = 1 + my_dict.get(word, 0)
>
> which I guess I can generalize to a dict of dicts but it seems it will
> require more if/else statements to check whether or not the higher-
> level keys exist. I guess the real answer is that I should just
> migrate to python2.5...!
Well, there's also dict.setdefault()
>>> pairs = ["ab", "ab", "ac", "bc"]
>>> outer = {}
>>> for a, b in pairs:
... inner = outer.setdefault(a, {})
... inner[b] = inner.get(b, 0) + 1
...
>>> outer
{'a': {'c': 1, 'b': 2}, 'b': {'c': 1}}
and it's not hard to write your own defaultdict
>>> class Dict(dict):
... def __getitem__(self, key):
... return self.get(key, 0)
...
>>> d = Dict()
>>> for c in "abbbcdeafgh": d[c] += 1
...
>>> d
{'a': 2, 'c': 1, 'b': 3, 'e': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1}
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Re: a strange SyntaxError
John Machin wrote: > As viewed with Google Groups, lines 40/41, 63/69, and 89 are indented 8 > spaces more than they should be. > > When I save your file and try to run it, I get this: C:\junk>coolgenie.py > File "C:\junk\coolgenie.py", line 40 > self.w = 520 > ^ > IndentationError: unexpected indent > > Possibilities: > (1) Your file contains junk like tabs or no-break spaces. Use a text > editor that will not mask what is really there to find the junk and edit > it out. As a first step towards sanity, make sure that your current editor is configured to use a tabwidth of 8 spaces (it is probably set to 4 at the moment). You should then be able to at least see the offending lines. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
MonkeeSage a écrit : > On Dec 8, 4:11 pm, Bruno Desthuilliers (snip) >>> I think it muddies the water to say that a.a() and a.a are the same >>> thing--obviously they are not. >> Indeed. a.a yields the object bound to name 'a' in object a, while a.a() >> yields the value returned by calling the object bound to name 'a' in >> object a. >> >>> In the common case, the first is a >>> method, >> Nope, it's the value returned by the call to a callable - remember that >> in Python, the parens are the call operator, so the expression a.a() >> evals to the value returned by the call to a.a - which is either the >> method object returned by the collaboration of the lookup mechanism and >> the descriptor protocol or any other possible callable object bound to >> that name or returned by the lookup mechanism for that name. > > You're talking about the result of calling a.a() No, I'm talking about the result of calling a.a - which is what a.a() means !-) Jordan, I of course understand what you mean - but the way you express it is not coherent with how Python works. In Python, the expression a.a() *is* the result of calling a.a, period. >, I'm talking about > what the attribute "a" on the object "a" is. which is the value of expression "a.a". Whether this expression evals to a callable object or not, and wether this callable object is actually a method object or not is another question, mostly unrelated with the meaning of expression 'a.a'. > Which is a callable > attribute, which by definition is called a "method" in the standard > sense [1]. Still not. The fact that an attribute is callable doesn't make it a method. > You can make a distinction between a "method object" and > "any other possible callable object," but I wasn't using such a > distinction, I was using the standard definition. Which standard definition ? Obviously not Python's standard definition anyway !-) > So my point holds. > When you see a.a(), because of pythons calling convention "()" you > know that "a" is a method of object "a". No you don't. You know that a.a is callable, period. > The point is that just because the attributes are "looked up the same > way" or whatever, doesn't make them the same *kind* of attribute. Yes it does : they are all of kind 'object' !-) > To > say that all attributes are the same in python muddies the water. They > are the same in a generic sense that they are attributes, but not in > their particular qualities. Obviously not - but this is true for all known OOPL. Now from a technical POV, there are no separate slots, no compiler-or-interpreter special processing, nor nothing else special about 'methods', no special type, etc - the storage and lookup mechanisms are *exactly* the same for *all* attributes (leaving special features like __slots__ aside). All the "magic" in 'methods' is handled by the way the function type implements the descriptor protocol, and this can be reproduced by any other type, because it's just *one* possible use of lookup hooks (+, in this case, callable objects) - another possible use being the property type. IOW, what makes the difference is the specific implementation of the attribute's class, *not* the generic attribute storage/lookup mechanism. > Like saying "all humans are the same" -- > yes, in a general sense of being human. But to leave it at that is not > very helpful. > > [1] http://en.wikipedia.org/wiki/Method_%28computer_science%29 >>> and the second is a variable. >> The second is whatever the lookup mechanism will yield for this name. >> >>> Yes, you can do silly stuff, >>> such that this rule will not hold, but in general it does. Or am I >>> wrong? >> You're wrong. Python's "methods" are thin wrappers around an instance >> (or class) and a function. These wrappers are "built" *at lookup time* >> by the __get__ method of the function object itself when it's looked up >> as an attribute of a class, thanks to the lookup mechanism and the >> descriptor protocol. >> >> Now the fact that an attribute is callable doesn't make it a "method". >> >> Also, anyone can implement it's own callable type that will act as a >> true function - that is, implement the descriptor protocol to return a >> wrapper around the instance or class and the callable - without >> necessarily yielding an instance of types.MethodType. This is all fairly >> trivial. > > Again, I am using the common definition. This "common definition" is obviously not applicable to each and every language - at least when it comes to implementation !-) Mays I remind you that the OP question was about "how to distinguish methods from attributes". And the answer is that given Python's object model and implementation, there's no clear, definitive and unambiguous way to do so. > I understand that you can > make an attribute callable in different ways than just the standard > machinery of "def symbol(self):" (those other techniques are what I > was referring to above by "metaprogrammi
Importing functions that require parameters
Good afternoon. As a self-tutoring project I am writing a one-time-pad encrypt/decrypt script. I have completed the encryption portion and am working currently on the decryption algorithm. My goal is to have the encrypt and decrypt be individual modules vice two parts of the same. My problem, or perhaps more accurately, question, lies in importing a function from the otp_encrypt script. Here is the function I am attempting to call: def get_key(ptext): """Convert one-time-pad to uppercase, and strip spaces. On final line slice pad to match length of plain text. (OTP will not work if len(pad) != len(plaintext)""" ptext = upper_case(ptext) otp = # key removed just due to sheer length otp = string.upper(otp) new = "" for letter in otp: if letter in string.uppercase: new += letter return new[:len(ptext)] The parameter of get_key is sys.argv[1]. Now I understand why I'm getting the errors I'm getting (invalid syntax if I include () or ([parameter], or an IndexError if I don't include those), but my question is, is it feasible to import a function from a module when that function requires a parameter from elsewhere in the imported module? Or is it just better to just import * in all cases? -- http://mail.python.org/mailman/listinfo/python-list
Re: My very first python web app (no framework)
On 2007-12-10, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > On 9 Dic, 15:43, [EMAIL PROTECTED] wrote: >> Is it the right way to go? Is it safe in a web production >> environment ? Is it thread-friendly (since flup is threaded) ? >> >> tnx > > Any hint ? If you as author are asking, my bet is on "no" for safety. Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
Jack a écrit : > I understand that the standard Python distribution is considered > the C-Python. Howerver, the current C-Python is really a combination > of C and Python implementation. There are about 2000 Python files > included in the Windows version of Python distribution. I'm not sure > how much of the C-Python is implemented in C but I think the more > modules implemented in C, the better performance and lower memory > footprint it will get. > > I wonder if it's possible to have a Python that's completely (or at > least for the most part) implemented in C, just like PHP - I think > this is where PHP gets its performance advantage. Which "performance advantage" ??? > Or maybe I'm wrong > because the core modules that matter are already in C and those Python > files are really a think wrapper. Anyhow, if would be ideal if Python > has performance similar to Java, with both being interpreted languages. Neither Python nor Java are "interpreted languages", because there's no such thing as an "interpreted language" - being 'interpreted' (whatever the definition of 'interpreted') is a quality of an implementation, not of a language. wrt/ to CPython and Sun's Java implementation, they are both byte-code compiled - which, according to usual definitions, is not quite the same thing !-) Now most of the performance difference is due to Java being much less dynamic than Python, which allow both the compiler and the VM to do much more optimizations - specially JIT compilation. It's quite harder to implement such optimizations for a language as dynamic as Python (IIRC, some language/compiler gurus here mentionned that even compiling Python to native binary code would not buy that much gain). Actually, it seems that taking the opposite approach - that is, trying to implement as much as possible of Python in Python - would be more promising wrt/ possible JIT compilation, cf the Pypy project. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
On Dec 8, 6:45 pm, Jeremy C B Nicoll <[EMAIL PROTECTED]> wrote: > Steve Howell <[EMAIL PROTECTED]> wrote: > > > --- Jeremy C B Nicoll <[EMAIL PROTECTED]> wrote: > > > What command (in XP) does one need to issue to > > >syntaxcheck a saved python > > > script without running it? > > > Perhaps oversimplifying a bit, running "python" does a > >syntaxcheck, and if it passes, moves on the next > > steps of interpretation/execution. > > Ah, I've been using IDLE so far (but would probably prefer to write Python > in my normal text editor). In IDLE Alt-X syntax checks the saved copy of > the file being edited (at least it seems to), and I was wondering how to > replicate that elsewhere. I don't know of a command line tool to do that, but I hasten to point out that you have the source code of IDLE available so you could just figure out what it's doing and encapsulate that in a script. Regards, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
So you say there is not any trusted way? -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing functions that require parameters
On Dec 10, 12:41 pm, Matt_D <[EMAIL PROTECTED]> wrote:
> Good afternoon.
>
> As a self-tutoring project I am writing a one-time-pad encrypt/decrypt
> script. I have completed the encryption portion and am working
> currently on the decryption algorithm. My goal is to have the encrypt
> and decrypt be individual modules vice two parts of the same.
>
> My problem, or perhaps more accurately, question, lies in importing a
> function from the otp_encrypt script. Here is the function I am
> attempting to call:
>
> def get_key(ptext):
> """Convert one-time-pad to uppercase, and strip spaces. On final
> line slice pad to match length of plain text. (OTP will not work if
> len(pad) != len(plaintext)"""
> ptext = upper_case(ptext)
> otp = # key removed just due to sheer length
> otp = string.upper(otp)
> new = ""
> for letter in otp:
> if letter in string.uppercase:
> new += letter
> return new[:len(ptext)]
>
> The parameter of get_key is sys.argv[1]. Now I understand why I'm
> getting the errors I'm getting (invalid syntax if I include () or
> ([parameter], or an IndexError if I don't include those), but my
> question is, is it feasible to import a function from a module when
> that function requires a parameter from elsewhere in the imported
> module? Or is it just better to just import * in all cases?
How is it requiring parameters from the module you are calling ? Do
you mean you just want to import the get_key() function by itself and
leave the rest of the module ?
# get_key.py
import re
def get_key(ptext):
otp = # Seriously large key.
return ''.join(re.findall('[A-Z]', otp.upper())[:len(ptext)]
That's what your code looks like it's doing...
# otp_encrypt.py
from get_key import get_key
"""Alternatively you can do
import get_key
getkey = get_key.get_key
"""
I not entirely sure if that is of help to you.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On Dec 10, 9:55 am, farsheed <[EMAIL PROTECTED]> wrote: > Thanks. But I ask this question technically, I mean I know nothing is > uncrackable and popular softwares are not well protected. But my > software is not that type and I don't want this specific software > popular. Understood. > It is some kind of in house tool and I want to copy protect it. this > is very complicated tool and not useful for > many people. indeed this is an animation manging tool I wrote for my > company. So if you have any idea that what is the best way to do it, > I'll appreciate that. I'll state my agreement with the opinion usually given when these kinds of questions are asked: that determined people will find a way to run software if that software is distributed, and running software as a service is probably the only reliable way of concealing your code. If your code is in-house, there might be numerous dependencies on in-house services that would make the code useless to an outsider, and you could consider exploiting this aspect of your software. See this recent thread on this subject: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d00c8926c0da7df0 This is very much a frequently asked question (the last thread appeared about three days ago), so I've tidied up a Python Wiki page dealing with this topic: http://wiki.python.org/moin/HowDoYouProtectSource I trust this provides some answers. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On Mon, 10 Dec 2007 00:55:13 -0800, farsheed wrote: > Thanks. But I ask this question technically, I mean I know nothing is > uncrackable and popular softwares are not well protected. But my > software is not that type and I don't want this specific software > popular. Then make it as ugly and unusable as you can. Spend the time you planned for writing documentation for this task. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
> So you say there is not any trusted way? You cannot distribute any program with the expectation that it cannot be reverse engineered. Despite what various protection companies would have folks believe. At some point, the user's CPU has to execute the code, and at that point, it can be intercepted, unwound, and intercepted. The *only* way to prevent people from reverse engineering your code (until quantum computing becomes a household standard) is to never give your code to them. Keep it on your servers and only allow users to access your service, not your code. Or, you could just trust your customers to adhere to your licensing terms (with this little thing called "the law" to back you up, as long as your licensing terms are legal). Then just distribute your software and spend your energies making a better product rather than chasing a quixotic dream of protection. Customers prefer not to be treated as criminals. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: __iadd__ useless in sub-classed int
On 2007-12-06, samwyse <[EMAIL PROTECTED]> wrote: > On Dec 6, 1:12 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > And that's my complaint. The value in is being replaced by > something almost, but not quite, identical to the original value. > Python's internal implementation of __iadd__ for isn't returning >, it's returning a new value belonging to the super-class. My > whole point is overloading was that I'd hoped to avoid having to > write a bunch of methods to perform in-place modifications. Looks > like I stuck, however. I think you don't want this. Suppose I keep track of addition information (eg a boolean "is_even = value == value//2") Since the base class doesn't know about this, it may return an incorrect instance. Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing functions that require parameters
On Dec 10, 9:41 pm, Matt_D <[EMAIL PROTECTED]> wrote: > Good afternoon. > > As a self-tutoring project I am writing a one-time-pad encrypt/decrypt > script. I have completed the encryption portion and am working > currently on the decryption algorithm. My goal is to have the encrypt > and decrypt be individual modules vice two parts of the same. > > My problem, or perhaps more accurately, question, lies in importing a > function from the otp_encrypt script. Here is the function I am > attempting to call: > > def get_key(ptext): > """Convert one-time-pad to uppercase, and strip spaces. On final > line slice pad to match length of plain text. (OTP will not work if > len(pad) != len(plaintext)""" > ptext = upper_case(ptext) > otp = # key removed just due to sheer length > otp = string.upper(otp) > new = "" > for letter in otp: > if letter in string.uppercase: > new += letter > return new[:len(ptext)] > > The parameter of get_key is sys.argv[1]. Now I understand why I'm > getting the errors I'm getting (invalid syntax if I include () or > ([parameter], or an IndexError if I don't include those), but my > question is, is it feasible to import a function from a module when > that function requires a parameter from elsewhere in the imported > module? "requires a parameter from elsewhere in the imported module" is a concept I don't understand. Here is what I think that you need to do in your main script: import sys import otp_encrypt the_key = opt_encrypt.get_key(sys.argv[1]) If that isn't what you want, you'll need to explain the sentence that starts "Now I understand", with examples of what you have tried. BTW, how is the uppercase function different from string.upper, and why aren't you using string methods e.g. otp = otp.upper() ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On Dec 9, 10:43 pm, "Jack" <[EMAIL PROTECTED]> wrote: > > http://blog.snaplogic.org/?p=55 There's some choice nonsense here, albeit on a different topic: "Coding for wxwidgets, using a QT or GTK bridge, or using TCL/TK is hardly an optimal solution when writing complex graphical applications, and Java wins in this area, despite there comically being many problems with the look and feel of Java applications." Clearly an individual who hasn't actually used any of the Python GUI development solutions, given the choice of words: "bridge", "hardly an optimal solution"; virtually intimating that you'd be doing malloc/ free or new/delete all the time. Plus throwaway remarks of the form "XYZ wins" tend to suggest beliefs with little substance and a continual need for self-reassurance on such matters. Anyway, back to the topic at hand... > Here's an article that shows the new version of Ruby is > faster than Python in some aspects (they are catching up :) > > http://antoniocangiano.com/2007/11/28/holy-shmoly-ruby-19-smokes-pyth... It's evident that the next mainstream version of Ruby will have various optimisations around recursive operations - something that has generally been rejected for CPython. Of course, the mainstream Ruby implementation has had a lot of scope for improvement: http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=all What disappoints me somewhat is that most of the people interested in taking Python performance to the next level are all outside (or on the outer fringes of) the CPython core development group: PyPy and Shed Skin are mostly distinct technologies; Psyco integrates with CPython but hasn't improved the "out of the box" situation; Pyrex is really a distinct tool, being more like a convenient wrapper generator than a bolt-on high performance engine for CPython. Language implementations like that of Lua have seen more progress on integrating solutions for performance, it would seem. As for a C-Python of the form requested, I suppose tools like Shed Skin and RPython fit the bill somewhat, if a transparent solution is needed where one writes in Python and it magically becomes fairly efficient C or C++. Otherwise, Pyrex provides more explicit control over what gets written in C and what remains in Python. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
It seems that I've got a short-circuit somewhere here. I understand that everything is an object and the the storage/lookup system is object-agnostic, and that it is only the descriptors (or "tags" as I called them generically) that determine how an attribute is bound, whether it is bound at all, whether it is even callable, and so forth. So, when I say that all callable attributes (or to be more precise, all callable attributes bound to objects other than toplevel) are "methods," what am I missing? You said "the difference [between a callable attribute and a method] is the specific implementation of the attribute's class"...but this almost sounds like type-by-primitive (a method is a method when it derives from a certain base class), or type-by-behavior (a method is a method when it behaves in a certain way, e.g., responds in a certain way to a query). Is this correct? Shouldn't it be type-by-capability/ interface--i.e., it implements the protocol of a callable, therefore, formally, it is not meaningfully different from any other callable (quacks like a duck and all)? I guess what I'm asking is, in what way is a "method" (or "function") semantically different from a home-brewed callable I concoct and bind to an object (or toplevel)? What is the distinction that I'm missing? Ps. wrt your last comment, isn't a class object in essence a factory method? Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On Dec 10, 6:26 am, Tim Chase <[EMAIL PROTECTED]> wrote: > > So you say there is not any trusted way? > > You cannot distribute any program with the expectation that it > cannot be reverse engineered. [snip] >From the OP's post, it seemed likely to me that the OP was asked by a misguided management to make sure it was "reverse-engineer-proof". So any attempt to convince the OP may be aimed at the wrong person. Misguided as they are, sometimes you have to placate these people. So, are there any ways to make it "harder" to reverse engineer a program? Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On Dec 10, 8:15 am, farsheed <[EMAIL PROTECTED]> wrote: > I wrote a software and I want to protect it so can not be cracked > easily. I wrote it in python and compile it using py2exe. what is the > best way in your opinion? I used SoftwarePassport ( http://www.siliconrealms.com/ ) for exactly this. I have found it to be very complete, with many possible scheme: trial period, multiple licence schemes, lock on hardware, moveable installation, ... Although it will not stop a highly dedicated hacker, it will raise the barrier very high for breaking the protected software. A few of the memory protection were incompatible with py2exe, so you need to carefully test your program. But for me, it was a breeze to setup and use. -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of perl's Pod::Usage?
On 2007-12-08, Neil Cerutti wrote: > On 2007-12-08, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: >> On Fri, 7 Dec 2007 20:12:21 +, Adam Funk <[EMAIL PROTECTED]> >> declaimed the following in comp.lang.python: >> >>> I'm using to using Pod::Usage in my Perl programs (a snipped example >>> is shown below, if you're interested) to generate a little man page >>> when they are called with the -h option. >>> >>> Is there an equivalent in Python? >>> >> I'd suggest you look in the Python references for docstring and/or >> __doc__ > > I found the example incomprehensible, so I looked it up in > perldoc. Sorry about that! POD is a mark-up language that Perl's Pod::Usage module can translate into man pages (and other documentation formats). So what I'm really after is an easy way to generate something that looks like a man page. > Anyhow, Python doesn't have it. Combining printing > various verboseness of usage messages with setting exit codes > with calling the exit function seems a little bizarre. > > But I believe optparse will handle parsing arguments and printing > usage messages, though not, I think, setting verbosity levels and > exiting the program. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of perl's Pod::Usage?
On 2007-12-08, Dennis Lee Bieber wrote: > On Fri, 7 Dec 2007 20:12:21 +, Adam Funk <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > >> I'm using to using Pod::Usage in my Perl programs (a snipped example >> is shown below, if you're interested) to generate a little man page >> when they are called with the -h option. >> >> Is there an equivalent in Python? >> > I'd suggest you look in the Python references for docstring and/or > __doc__ Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
> So, are there any ways to make it "harder" to reverse engineer a
> program?
In addition to the standby of
-Don't distribute your program (SaaS)
I'll add to the list:
-Only distribute your program to people too non-technical to
consider reverse-engineering
-Don't document your program (or even better, *mis*document your
program)
-Write Lovecraftian code ("import goto" comes to mind) designed
to make reverse-engineers go insane trying to figure out what you
were thinking
-In your Python, drop to in-line assembly language "for
business-logic optimization". Only targeting specific models of
obscure processor architectures helps minimize your audience.
-Write software that does nothing of interest/value/use
Just a couple ideas to get an enterprising young coder off on the
right track ;)
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Error when executing the library reference echo server example
Hi. Python newbie speaking,
I've copy/pasted the example of the echo server that comes in the IDLE
documentation ("Python Library Reference" section 17.2.3) to see how
the sockets work. The only change I've made is in the host address
which I've set to 'localhost' in the client. You can see the complete
code below the message.
When I run it I get the following error:
Traceback (most recent call last):
File "C:\Python25\eclient.py", line 11, in
data = s.recv(1024)
error: (10053, 'Software caused connection abort')
Is the example wrong? In this case, Where can I find a working
example? Have I messed up the example putting 'localhost'? (don't
think so, because I tried with '127.0.0.1' and I got the same error).
And the big one, Why I get the error and how can I avoid it in future
applications?
Lot of thanks in advance!!
---CODE---
# Echo server program
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 50001 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
___
# Echo client program
import socket
HOST = 'localhost'# The remote host
PORT = 50001 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
[EMAIL PROTECTED] wrote:
[...]
>> But I'm experiencing some strange jumps in the data (seismic data is
>> mostly quite smooth at 40 Hz sampling rate). I think I did some mistake
>> in the byte order...
>
> Probably. In your code sample, when you pad it to 32-bits, why are you
> inserting every third byte, instead of the most significant one?
Hm, I'm not that good when we go the the very basics. A good friend of mine
(Robert, now you don't need to go on reading this thread) helped me a lot,
but finally I got a bit confused. ;)
> Maybe the following will work:
>
> if sign:
> s = struct.unpack('>i','%c%c%c%c' % (chr(0xFF),s0,s1,s2))[0]
> else:
> s = struct.unpack('>i','%c%c%c%c' % (chr(0x00),s0,s1,s2))[0]
Perfect! Today I got a bit of c code - the results are identical. :)
Thanks to all of you,
Mario
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
Hendrik van Rooyen wrote: > "Mario M. Mueller" <[EMAIL PROTECTED]> wrote: > > >> I uploaded a short sample data file under >> http://www.FastShare.org/download/test.bin - maybe one can give me >> another hint... In a full data example max value is 1179760 (in case one >> looks only at the eye-cathing "65535"+- values). > > I clicked on the link and got nothing but rubbish trying to predict how > old I would get, so I gave up and am flying blind. Sorry, it's a one click hoster. I cannot tell anything about this rubbish - I use Adblock Plus. :) > Some A to D's are not two's complement, but have strange formats with an > independent sign bit in the highest order. > > And of course there is big and little endian - so there are something like > 2x2 = 4 things to try - twos compl. big and little, and signed big and > little. > > Unless there is a protocol interfering - how do you know, in the byte > stream, where a value starts and stops - is it cr,lf delimited? I have files containing only the data. Marek's fix to my code solves the challenge. Mario -- http://mail.python.org/mailman/listinfo/python-list
GUI development with 3D view
Hi, I'm looking for quite some time now for a gui library for python, which allows me to display 3D graphics. Main OS is windows, Mac OS X and Linux would be nice to have. I want to use python 2.5. My first try was wx + pyOpenGL but there are no working binaries for python 2.5. I simply have to display some dialogs for data input and a 3D scene with lots of arrows. No fancy mesh and scene handling is needed. Is there an alternative to wx+pyOpenGL? regards, Achim -- http://mail.python.org/mailman/listinfo/python-list
Re: Error when executing the library reference echo server example
On Dec 10, 2:16 pm, [EMAIL PROTECTED] wrote:
> Hi. Python newbie speaking,
>
> I've copy/pasted the example of the echo server that comes in the IDLE
> documentation ("Python Library Reference" section 17.2.3) to see how
> the sockets work. The only change I've made is in the host address
> which I've set to 'localhost' in the client. You can see the complete
> code below the message.
>
> When I run it I get the following error:
> Traceback (most recent call last):
> File "C:\Python25\eclient.py", line 11, in
> data = s.recv(1024)
> error: (10053, 'Software caused connection abort')
>
> Is the example wrong? In this case, Where can I find a working
> example? Have I messed up the example putting 'localhost'? (don't
> think so, because I tried with '127.0.0.1' and I got the same error).
> And the big one, Why I get the error and how can I avoid it in future
> applications?
>
> Lot of thanks in advance!!
>
> ---CODE---
> # Echo server program
> import socket
>
> HOST = '' # Symbolic name meaning the local host
> PORT = 50001 # Arbitrary non-privileged port
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind((HOST, PORT))
> s.listen(10)
> conn, addr = s.accept()
> print 'Connected by', addr
> while 1:
> data = conn.recv(1024)
> if not data: break
> conn.send(data)
> conn.close()
> ___
>
> # Echo client program
> import socket
>
> HOST = 'localhost'# The remote host
> PORT = 50001 # The same port as used by the server
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.connect((HOST, PORT))
> s.send('Hello, world')
> data = s.recv(1024)
> s.close()
> print 'Received', repr(data)
I copy/pasted your code and ran it without any faults. Are you using
any firewall software that could be causing the connection to be
terminated ?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Error when executing the library reference echo server example
On Mon, 10 Dec 2007 04:16:03 -0800 (PST), [EMAIL PROTECTED] wrote:
>Hi. Python newbie speaking,
>
>I've copy/pasted the example of the echo server that comes in the IDLE
>documentation ("Python Library Reference" section 17.2.3) to see how
>the sockets work. The only change I've made is in the host address
>which I've set to 'localhost' in the client. You can see the complete
>code below the message.
>
>When I run it I get the following error:
> Traceback (most recent call last):
> File "C:\Python25\eclient.py", line 11, in
> data = s.recv(1024)
> error: (10053, 'Software caused connection abort')
>
>Is the example wrong? In this case, Where can I find a working
>example? Have I messed up the example putting 'localhost'? (don't
>think so, because I tried with '127.0.0.1' and I got the same error).
>And the big one, Why I get the error and how can I avoid it in future
>applications?
>
>Lot of thanks in advance!!
You're seeing the expected behavior. The example doesn't take care to
handle any error conditions. It has other bugs as well, such as not
checking the return value of socket.send().
Here's a different echo example:
http://twistedmatrix.com/projects/core/documentation/examples/#auto0
Jean-Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On 2007-12-10, Neil Cerutti <[EMAIL PROTECTED]> wrote: > On 2007-12-09, Just Another Victim of the Ambient Morality ><[EMAIL PROTECTED]> wrote: >> I'm looking for a linked list implementation. Something >> iterable with constant time insertion anywhere in the list. I >> was wondering if deque() is the class to use or if there's >> something else. Is there? > > The deque is implemented as a list of arrays. See 5.12.1 > Recipes for the trick of using rotate to delete an item from > within the deque. The docs don't spell out the efficiency (in > terms of O notation) of the rotate method, though. You'll have > check the source, or perhaps Raymond is reading and could > explain. I take that back. As pretty much indicated in the docs, rotate is implemented as a series of pushes and pops. It doesn't renumber the nodes--I assumed renumbering might be technically possible and cheap. Even if rotating were O(1), I suppose removal of an item would still be o(n/k), with k being the size of the subarrays, making deletion remain O(n) at the end of the day. Anyhow, implementing linked lists in Python is not challenging, but they don't work well with Python iterators, which aren't suitable for a linked list's purposes--so you have to give up the happy-joy for loop syntax in favor of Python's frowny-sad while loops. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Achim Domma wrote: > Hi, > > I'm looking for quite some time now for a gui library for python, > which allows me to display 3D graphics. Main OS is windows, Mac OS X > and Linux would be nice to have. I want to use python 2.5. My first > try was wx + pyOpenGL but there are no working binaries for python > 2.5. I simply have to display some dialogs for data input and a 3D > scene with lots of arrows. No fancy mesh and scene handling is needed. > > Is there an alternative to wx+pyOpenGL? The usual suspects - mainly Qt, possibly Tk (not sure if there is a python-available version of open gl canvasses for Tk) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: searching a value of a dict (each value is a list)
On Dec 10, 3:50 am, Seongsu Lee <[EMAIL PROTECTED]> wrote:
> On 12월10일, 오후12시18분, Adonis Vargas <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > Seongsu Lee wrote:
> > > Hi,
>
> > > I have a dictionary with million keys. Each value in the
> > > dictionary has a list with up to thousand integers.
> > > Follow is a simple example with 5 keys.
>
> > > dict = {1: [1, 2, 3, 4, 5],
> > >2: [10, 11, 12],
> > >90: [100, 101, 102, 103, 104, 105],
> > >91: [20, 21, 22],
> > >99: [15, 16, 17, 18, 19]}
>
> > > I want to find out the key value which has a specific
> > > integer in the list of its value. For example, if I search
> > > 104 in the list, 90 must be returned.
>
> > > How can I do this with Python? Ideas?
>
> > You can try this:
>
> > items = {1: [1, 2, 3, 4, 5],
> > 2: [10, 11, 12],
> > 90: [100, 101, 102, 103, 104, 105],
> > 91: [20, 21, 22],
> > 99: [15, 16, 17, 18, 19]}
>
> > def findItem(item, dictionary):
> > for key, value in dictionary.iteritems():
> > if item in value:
> > print key, value
>
> > findItem(104, items)
>
> > This will allow you to work with the existing dataset without needing to
> > duplicate it. It will print all occurrances.
>
> Hi,
>
> Yes, it works. But I think it works in O(n * m), doesn't it?
> (n is # of keys in the dictionary and m is # of items in the list.)
> So, we need to create a reverse index. (a reverse dictionary) or
> need something better at least, I think.
>
> > Also, you should never use reserved words like 'dict' this creates
> > confusion and can cause Python to misbehave since you are rebinding the
> > name.
>
> Yep. :)
>
> > Hope this helps.
>
> > Adonis Vargas- 따온 텍스트 숨기기 -
>
> > - 따온 텍스트 보기 -
If I'm not mistaken, building a reverse dictionary like that will be
O(n*m) because dict/list access is O(n) (ammortized). Somebody correct
me if I'm wrong. In that case, it really depends on how you will use
the dict to see whether you get any benefit from building the reversed
dict. If you want to do several lookups, then the initial overhead
(speed/memory) of building the reversed dict might be worth it so that
you can just run lookups at O(n). But if you only need it once, it is
a waste of time and space to create a reverse dict when your access
time is the same for the lookup as for building the reversed dict.
If you do need more than one lookup, it would also be a good
optimization strategy to build the reverse dict in parallel, as you
execute the first search; that way you can combine the time spent on
building the reverse dict and the lookup, to get a total of O(n*m)
rather than O(n^2*m). The first search is "free" since you need the
reverse dict anyway.
Regards,
Jordan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
MonkeeSage a écrit :
> It seems that I've got a short-circuit somewhere here. I understand
> that everything is an object and the the storage/lookup system is
> object-agnostic, and that it is only the descriptors (or "tags" as I
> called them generically)
"descriptor" is a protocol - an interface if you prefer. It's a way for
a class attribute to hook into the lookup mechanism, and it's
implemented by the property type - to provide a basic support for
computed attributes - and the function type - to provide the machinery
that turns a function into a method.
> that determine how an attribute is bound,
> whether it is bound at all, whether it is even callable,
An object is callable if it implement the __call__ method (for the
commonly admitted definition of 'method' !-).
> and so forth.
> So, when I say that all callable attributes (or to be more precise,
> all callable attributes bound to objects other than toplevel)
You mean "other than a module" ?
> are
> "methods," what am I missing?
All callable attributes that are either bound to an instance or don't
implement the descriptor protocol the way the function type do.
> You said "the difference [between a callable attribute and a method]
> is the specific implementation of the attribute's class"...but this
> almost sounds like type-by-primitive
It isn't.
> (a method is a method when it
> derives from a certain base class), or type-by-behavior (a method is a
> method when it behaves in a certain way, e.g., responds in a certain
> way to a query).
Bingo.
> Is this correct? Shouldn't it be type-by-capability/
> interface--i.e., it implements the protocol of a callable, therefore,
> formally, it is not meaningfully different from any other callable
> (quacks like a duck and all)?
The answer is in how the function type implements the descriptor
protocol. For an attribute to "become" a method when looked up, this
attribute has to implement the descriptor protocol so that it's __get__
method returns either a BoundMethod (or any equivalent) when looked up
on the instance and an UnboundMethod (or any equivalent) when looked up
on the class (I'll save you the details about classmethods etc).
Now since the method type is mostly trivial to implement, the fact that
an attribute lookup doesn't return an instance of Method doesn't
necessarily imply it's not one - so the truth is that an attribute is a
method if it behaves like one !-)
> I guess what I'm asking is, in what way is a "method" (or "function")
Python's 'methods' are really thin wrappers around an object, it's class
and a function. In the common use case, one of these wrappers is
instanciated each time you lookup a function that's a class attributes.
> semantically different from a home-brewed callable I concoct and bind
> to an object (or toplevel)? What is the distinction that I'm missing?
Implement your own callable that doesn't implement the descriptor
protocol, bind it to a class, instanciate your class, lookup this
attribute. You'll get the original attribute, not a method. Or bind a
function to an *instance*, and look it up - here again, you wont get a
method, but the original function object.
Now you can of course label this a static method if you want !-)
If you want a custom callable to be usable as a method, you have to
implement the descriptor protocol like the function type do.
> Ps. wrt your last comment, isn't a class object in essence a factory
> method?
Not quite - even if you can use it that way. In fact, the real factory
method is the __new__ method of the class - that is, the proper constructor.
A class object is an object that is responsible for:
* creating instances of itself (and as such, it is indeed a factory -
but a factory object, not a factory method)
* providing class attributes and mro to these instances (lookup rules
here: a name not found in the instance's __dict__ will be looked up in
the class, then in classes in the mro - unless of course the class
implements __getattr__ or __getattribute__, in which case all bets are
off).
caveat : all this describes the 'new-style' object model. The 'classic'
('old-style') object model works a bit differently.
> Regards,
> Jordan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Job Offer: Python Ninja or Pirate!
Please post on the job forum! On Dec 10, 2007 9:14 AM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Etsy is an online marketplace for buying and selling all things > handmade: clothing, music, furniture, > software, jewelry, robots. We launched on June 18, 2005, and ever > since then have been empowering our > users to make a living doing what they love most. > > Just a few months ago, we found a few amazingly talented ninjas and > even a few swarthy pirates. The team is doing wonderfully, and we're > hoping to add a few more adventure-loving souls to our ranks. You'll > be using python, javascript and other technologies to whip up > innovative web applications in many challenging and interesting > domains: social and community, ecommerce, search, and even software > development. > > We're also in the process of redesigning and developing our web stack > to allow us to scale into outer space > while still providing a fun and productive programming environment. > You'll likely end up working on our: in-house orm, customized cherrypy > environment, jinja templates, django-like form processing library, > lucene integration, twisted-based communications protocol, or kick-ass > high-performance memcached library. > > Required: > * 5+ years of web development experience > * 3+ years of writing production-level code with a dynamic language > (python, ruby, lisp, smalltalk, > > OO javascript, etc) > * Strong OOP skills > * Understanding of dynamic language idioms and patterns > * Ability and willingness to pick up other languages and technologies > > Desired: > * Ability to write python code idiomatically > * Lives in New York City > * Experience with javascript > * Experience with java, postgresql and/or php > > Neat: > * Plays guitar hero > > > Challenge: > A valid response will be either a solution to the problem below, or a > link to some code of which you > are particularly proud. > > Problem: In the dynamic language of your choice, write a short program > that will: > 1. define a list of the following user ids 42346, 77290, 729 (you can > hardcode these, but it should > still work with more or less ids) > 2. retrieve an xml document related to each user at this url "http:// > api.etsy.com/feeds/xml_user_details.php?id=" > 3. retrieve the data contained in the city element from each xml > document > 4. keep a running total of how many users are found in each city > 5. display the total count of users living in each city > > You can assume user ids are valid and that the url is available. The > output should look something > like: > > Charlotte: 1 > New York: 2 > > You can find out more about etsy at http://www.etsy.com or > http://blog.etsy.com/jobs/index.html > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
Neil Cerutti wrote: > [linked lists] don't work well with Python iterators, which aren't > suitable for a linked list's purposes--so you have to give up the > happy-joy for loop syntax in favor of Python's frowny-sad while loops. You can always move the while-loop into a generator and use for-loops happily ever after. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing functions that require parameters
On Dec 10, 2:46 pm, John Machin <[EMAIL PROTECTED]> wrote: > "requires a parameter from elsewhere in the imported module" is a > concept I don't understand. > > Here is what I think that you need to do in your main script: > > import sys > import otp_encrypt > the_key = opt_encrypt.get_key(sys.argv[1]) > > If that isn't what you want, you'll need to explain the sentence that > starts "Now I understand", with examples of what you have tried. When I try: from otp_encrypt import get_key I get: --- IndexErrorTrace C:\WINDOWS\system32\ in () 62 cipher += letter 63 return cipher 64 ---> 65 print final(sys.argv[1]) 66 IndexError: list index out of range In [13]: from otp_encrypt import get_key() I know why I'm getting the error -- I'm importing a function from a module in iPython with a sys.argv parameter. No big mystery there. > BTW, how is the uppercase function different from string.upper, and > why aren't you using string methods e.g. otp = otp.upper() > ? To be honest, I think I tried it once, but probably left off the (). When I got an error I more than likely changed it to string.upper(otp) and since it worked I didn't worry about it. This is like the second full script I've actually finished so I'm trying to get all my functionality in first before I start optimizing the script. While I'm sure things like this are obvious to you, I've only been coding for a week so any questions like, "Why did you do x when y is much better?" can probably be answered with, "Stupid newb." Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On Dec 9, 3:23 pm, [EMAIL PROTECTED] (Aahz) wrote: > In article <[EMAIL PROTECTED]>, > > Jack <[EMAIL PROTECTED]> wrote: > > >I understand that the standard Python distribution is considered > >the C-Python. Howerver, the current C-Python is really a combination > >of C and Python implementation. There are about 2000 Python files > >included in the Windows version of Python distribution. I'm not sure > >how much of the C-Python is implemented in C but I think the more > >modules implemented in C, the better performance and lower memory > >footprint it will get. > > Prove it. ;-) > > Seriously, switching to more C code will cause development to bog down > because Python is so much easier to write than C. > > >I wonder if it's possible to have a Python that's completely (or at > >least for the most part) implemented in C, just like PHP - I think > >this is where PHP gets its performance advantage. Or maybe I'm wrong > >because the core modules that matter are already in C and those Python > >files are really a think wrapper. Anyhow, if would be ideal if Python > >has performance similar to Java, with both being interpreted languages. > > Could you provide some evidence that Python is slower than Java or PHP? > -- > Aahz ([EMAIL PROTECTED]) <*>http://www.pythoncraft.com/ > > "Typing is cheap. Thinking is expensive." --Roy Smith I'd like to provide some evidence that Python is *faster* than Java. EVE online...emulate that in JAVA please. -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Mon, 10 Dec 2007 03:56:10 -0800, MonkeeSage wrote:
> So, when I say that all callable attributes (or to be more precise, all
> callable attributes bound to objects other than toplevel) are "methods,"
> what am I missing?
Everything that isn't a method but is callable.
class Callable(object):
def __call__(self):
return oct(id(self))
class Foo(object):
aclass = type('Parrot', (object,), {})
atype = int
ainstance = Callable()
afunction = None # this is tricky...
def __init__(self): # a method
self.afunction = lambda n: n+1
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Dec 10, 7:19 am, Bruno Desthuilliers wrote:
> MonkeeSage a écrit :
>
> > It seems that I've got a short-circuit somewhere here. I understand
> > that everything is an object and the the storage/lookup system is
> > object-agnostic, and that it is only the descriptors (or "tags" as I
> > called them generically)
>
> "descriptor" is a protocol - an interface if you prefer. It's a way for
> a class attribute to hook into the lookup mechanism, and it's
> implemented by the property type - to provide a basic support for
> computed attributes - and the function type - to provide the machinery
> that turns a function into a method.
>
> > that determine how an attribute is bound,
> > whether it is bound at all, whether it is even callable,
>
> An object is callable if it implement the __call__ method (for the
> commonly admitted definition of 'method' !-).
>
> > and so forth.
> > So, when I say that all callable attributes (or to be more precise,
> > all callable attributes bound to objects other than toplevel)
>
> You mean "other than a module" ?
>
> > are
> > "methods," what am I missing?
>
> All callable attributes that are either bound to an instance or don't
> implement the descriptor protocol the way the function type do.
>
> > You said "the difference [between a callable attribute and a method]
> > is the specific implementation of the attribute's class"...but this
> > almost sounds like type-by-primitive
>
> It isn't.
>
> > (a method is a method when it
> > derives from a certain base class), or type-by-behavior (a method is a
> > method when it behaves in a certain way, e.g., responds in a certain
> > way to a query).
>
> Bingo.
>
> > Is this correct? Shouldn't it be type-by-capability/
> > interface--i.e., it implements the protocol of a callable, therefore,
> > formally, it is not meaningfully different from any other callable
> > (quacks like a duck and all)?
>
> The answer is in how the function type implements the descriptor
> protocol. For an attribute to "become" a method when looked up, this
> attribute has to implement the descriptor protocol so that it's __get__
> method returns either a BoundMethod (or any equivalent) when looked up
> on the instance and an UnboundMethod (or any equivalent) when looked up
> on the class (I'll save you the details about classmethods etc).
>
> Now since the method type is mostly trivial to implement, the fact that
> an attribute lookup doesn't return an instance of Method doesn't
> necessarily imply it's not one - so the truth is that an attribute is a
> method if it behaves like one !-)
>
> > I guess what I'm asking is, in what way is a "method" (or "function")
>
> Python's 'methods' are really thin wrappers around an object, it's class
> and a function. In the common use case, one of these wrappers is
> instanciated each time you lookup a function that's a class attributes.
>
> > semantically different from a home-brewed callable I concoct and bind
> > to an object (or toplevel)? What is the distinction that I'm missing?
>
> Implement your own callable that doesn't implement the descriptor
> protocol, bind it to a class, instanciate your class, lookup this
> attribute. You'll get the original attribute, not a method. Or bind a
> function to an *instance*, and look it up - here again, you wont get a
> method, but the original function object.
>
> Now you can of course label this a static method if you want !-)
>
> If you want a custom callable to be usable as a method, you have to
> implement the descriptor protocol like the function type do.
>
> > Ps. wrt your last comment, isn't a class object in essence a factory
> > method?
>
> Not quite - even if you can use it that way. In fact, the real factory
> method is the __new__ method of the class - that is, the proper constructor.
>
> A class object is an object that is responsible for:
> * creating instances of itself (and as such, it is indeed a factory -
> but a factory object, not a factory method)
> * providing class attributes and mro to these instances (lookup rules
> here: a name not found in the instance's __dict__ will be looked up in
> the class, then in classes in the mro - unless of course the class
> implements __getattr__ or __getattribute__, in which case all bets are
> off).
>
> caveat : all this describes the 'new-style' object model. The 'classic'
> ('old-style') object model works a bit differently.
>
> > Regards,
> > Jordan
Thank you kindly Bruno. You're answers have been very informative. I
thought I understand how python was operating, but I see that I have
some misconceptions. I honestly did read through the reference manual
when I started learning python a couple years ago, but I'm not the
most patient person by nature, and it seems that I was so happy with a
shiny new language, that I imported some foreign concepts into the
picture and glossed over many of the details of pythons object model.
I'm going to give the "Data Model" section a thorough going-over
again, and try to pay more
Re: Importing functions that require parameters
Matt_D wrote: >> import sys >> import otp_encrypt >> the_key = opt_encrypt.get_key(sys.argv[1]) >> >> If that isn't what you want, you'll need to explain the sentence that >> starts "Now I understand", with examples of what you have tried. > > When I try: > > from otp_encrypt import get_key > > I get: > > --- > IndexErrorTrace > > C:\WINDOWS\system32\ in > Q:\python\my pys\otp_encrypt.py in () > 62 cipher += letter > 63 return cipher > 64 > ---> 65 print final(sys.argv[1]) > 66 > > IndexError: list index out of range > > In [13]: from otp_encrypt import get_key() > > I know why I'm getting the error -- I'm importing a function from a > module in iPython with a sys.argv parameter. No big mystery there. No you don't know -- you are trying to use a module that is meant to work as a stand-alone script as a library. As a python module is executed when it is imported, so is the print statement in line 65. To prohibit execution of the script-only parts use an if-suite, e. g.: def get_key(...): # ... if __name__ == "__main__": print final(sys.argv[1]) Now the print statement will be executed if you invoke your script from the command line $ python otp_encrypt.py but not by import otp_encrypt where the value of __name__ is "otp_encrypt". Peter -- http://mail.python.org/mailman/listinfo/python-list
detecting disc serial number without win32
Hi, I have to run a python script on a Linux machine. This script was developed on a windows workstation and it uses the win32 library to detect the cd (or dvd) serial number (in the - format). How can I change the script to do the same task on linux? I found an old post on the same task [ "(Joliet) volume name and serial number" on 26 Feb 2003 ] but without answer... Any chance there is now a way of implement such a low-level feature? TIA! bye, PiErre -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Diez B. Roggisch wrote: > Achim Domma wrote: > [snip] >> >> Is there an alternative to wx+pyOpenGL? > > The usual suspects - mainly Qt, possibly Tk (not sure if there is a > python-available version of open gl canvasses for Tk) > > Diez togl is a Tk/OpenGL widget that can be used with python as well. I think it is included in PyOpenGL. It is quite easy to use iirc, but I've got no idea how it works with windows. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ruby's Template Engine for Python
On Dec 8, 3:24 pm, Samuel <[EMAIL PROTECTED]> wrote: > On Sat, 08 Dec 2007 13:06:15 -0800, Steve Howell wrote: > > This is what I came up with: > > >http://pylonshq.com/pastetags/form_remote_tag > > I see that Pylons uses a standard templating systems with all the JS > renderers hooked into it as standard template function calls. That's > great, now I just have to find the piece of code that provides those > callbacks. > > Ah, here it is: > > >http://pylonshq.com/WebHelpers/module-webhelpers.html > > And there I go, easily adding the same functionality to any template > system of my choice. That was easier than I expected. > > Thanks for your help ;-)! > > -Samuel I think TurboGears does something similar using the Kid template system. You might find those useful as well: http://www.kid-templating.org/language.html http://turbogears.org/ Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
MonkeeSage a écrit : > On Dec 10, 7:19 am, Bruno Desthuilliers I'm going to give the "Data Model" section a thorough going-over > again, and try to pay more attention this time(!) ;) Also make sure you read the docs about new-style classes, the descriptor protocol and metaclasses. > Just as a side-note, it's interesting that even through my > misunderstandings I've been able to use python to great effect (I've > translated several fairly complex apps to python, using decorators, > CPS and other fairly "advanced" techniques, and it "Just Worked"). > Heh. Nice language. :) Indeed !-) > Anyway, thanks again for your time an patience. Thanks *you* for your patience - I'm certainly not the best teacher here !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Job Offer: Python Ninja or Pirate!
> Challenge:
> A valid response will be either a solution to the problem below, or a
> link to some code of which you
> are particularly proud.
>
> Problem: In the dynamic language of your choice, write a short program
> that will:
> 1. define a list of the following user ids 42346, 77290, 729 (you can
> hardcode these, but it should
> still work with more or less ids)
> 2. retrieve an xml document related to each user at this url "http://
> api.etsy.com/feeds/xml_user_details.php?id="
> 3. retrieve the data contained in the city element from each xml
> document
> 4. keep a running total of how many users are found in each city
> 5. display the total count of users living in each city
>
> You can assume user ids are valid and that the url is available. The
> output should look something
> like:
>
> Charlotte: 1
> New York: 2
i wanted to make it a one liner, but i had to import modules :(
import sys, xml, urllib
dummy = [sys.stdout.write(city + ': ' + str(num) + '\n') for city, num in
set([[(a, o.count(a)) for a in p] for o, p in [2*tuple([[city for city in
((xml.dom.minidom.parseString(urllib.urlopen('http://api.etsy.com/feeds/xml_user_details.php?id='
+ str(id)).read()).getElementsByTagName('city')[0].childNodes + [(lambda
t: (setattr(t, 'data', 'no city'),
t))(xml.dom.minidom.Text())[1]])[0].data.lower().replace(' ', ' ') for id
in [71234, 71234, 71234, 71234, 71234, 71234, 42792])]])]][0])]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Importing functions that require parameters
On Dec 10, 4:49 pm, Peter Otten <[EMAIL PROTECTED]> wrote: > > Peter Thanks, Peter. You answered my question precisely. I'm successfully encrypting and decrypting now. Thank you again. R, Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On 2007-12-10, Peter Otten <[EMAIL PROTECTED]> wrote: > Neil Cerutti wrote: >> [linked lists] don't work well with Python iterators, which >> aren't suitable for a linked list's purposes--so you have to >> give up the happy-joy for loop syntax in favor of Python's >> frowny-sad while loops. > > You can always move the while-loop into a generator and use > for-loops happily ever after. Python's iterators are unsuitable for mutating the linked list while iterating--the only major application of linked lists. Wrapping in a generator won't allow you to use for loop syntax, unless I'm missing something, which has often happened. # x is a linked list object, containing random numbers. # delete even numbers x_iter = x.begin() while x_iter != x.end(): if x_iter.value % 2 == 0: x_iter = x.delete(x_iter) # or x_iter.delete() as an iter mutating op? else: x_iter.advance() Of course, a linked lists type would be obliged to provide a filter method instead. C++ "solved" this difficulty by making all containers equally awkward to work with. ;-) -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: searching a value of a dict (each value is a list)
On 2007-12-10, MonkeeSage <[EMAIL PROTECTED]> wrote: > If I'm not mistaken, building a reverse dictionary like that will be > O(n*m) because dict/list access is O(n) (ammortized). Somebody correct > me if I'm wrong. In that case, it really depends on how you will use > the dict to see whether you get any benefit from building the reversed > dict. If you want to do several lookups, then the initial overhead > (speed/memory) of building the reversed dict might be worth it so that > you can just run lookups at O(n). It also depends on if the dictionary shall be mutated between reverse lookups. > But if you only need it once, it is a waste of time and space > to create a reverse dict when your access time is the same for > the lookup as for building the reversed dict. > > If you do need more than one lookup, it would also be a good > optimization strategy to build the reverse dict in parallel, as > you execute the first search; that way you can combine the time > spent on building the reverse dict and the lookup, to get a > total of O(n*m) rather than O(n^2*m). The first search is > "free" since you need the reverse dict anyway. It wouldn't be merely an optimization if reverse lookups and mutations were interleaved. -- Neil Cerutti You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
MonkeeSage a écrit :
> On Dec 9, 6:23 pm, MonkeeSage <[EMAIL PROTECTED]> wrote:
>> Hi Bruno,
>>
>> I think that we've been having a mainly "semantic" (pun intended)
>> dispute. I think you're right, that we've been using the same words
>> with different meanings.
Fine. So we may have a chance to get out there !-)
(snip)
>> I would like to (try to) clarify a little about my use of wording. By
>> "attribute" I was referring to a member of an object (*other than*
>> toplevel). I was of course using "method" to refer to callable
>> attributes (and I would use "function" for callable attributes bound
>> to toplevel), and I was using "variable" to refer to non-callable
>> attributes. By "tagging" I meant that attributes without a
>> "tag" (e.g., __call__) are not included in the MRO for an object; they
>> must be "tagged" as something other than a "variable".
Nope. We've been thru the distinction between a callable attribute and a
methodin another nearby thread, so won't come back on this. wrt/ mro,
it's being used for *all* attributes. That is, the look up rule for an
attribute is :
1. instance's __dict__
2. class's __dict__
3. all classes __dict__s in the class's mro
NB : not taking __getattribute__ and __getattr__ hooks into account here.
>> As for ruby, I think the opcodes will help me clarify...
Not for me, sorry - my time to deal with my own ignorance !-)
require 'parse_tree'
>> => true
ParseTree.translate(%q{
>> class A
>> def foo
>> "bar"
>> end
>> end
>> A.new.foo})
>>
>> => [:block, [:class, :A, nil, [:scope, [:defn, :foo, [:scope, [:block,
>> [:args], [:str, "bar"]], [:call, [:call,
>> [:const, :A], :new], :foo]]
>>
>> Notice that #new and #foo are both CALL ops. All attribute access is
>> CALL (i.e., "method"). There really is no such thing as a non-callable
>> "attribute" in ruby.
For a definition of attribute being different from 'member variable'.
But what we disagreed was more about the definitions of 'attribute' and
'callable' !-)
>> Given this, I see the addition the instance variable also being an
>> attribute as a *huge* difference between the ruby code and your
>> initial example. An attribute can be named the same as an lval and
>> return or set the value of the lval (e.g., @a), but it's no different
>> from any other method.
You still have both a member variable and an 'attribute'. And the member
variable is stored in the instance, while the 'attribute' (that is, the
getter and setter methods) are stored with the class. From this POV,
this is the equivalent of the Python snippet using a property.
>> But at the same time, I can see how my python example can be seen as
>> *wildly* different (WTF?) as well.
The WTF was about the class attribute. Did you try it with a mutable
object instead of a string, and more than one instance ?-)
>> Maybe there is no easy way to
>> provide a true formally equivalent translation due to the
>> implementation differences of the languages
That's why I think the important point here is the semantic, not the
implementation (while talking about the method/non-method distinction in
Python is clearly about implementation).
>> Anyhow, sorry for the confusion.
You don't have to be sorry. We're both guilty (if guilty of anything)
and honestly, I tend to be a bit on the nit-pick side, which sometimes
doesn't help.
> Ps. To answer a question you asked, "callable" objects don't generally
> implement a #call method--just Proc objects and method references
> [class Method instances] do, which even though they have a #call
> method, aren't usually considered "callable" since you can't call them
> directly--the #call method could as easily be named #run or #evaluate
> or whatever. Accessing a name in ruby basically does something like:
> VCALL name (== if parens on name like a() skip to call step, otherwise
> check for LVAL in scope and return value if found, otherwise FCALL/
> CALL and return result). You can use the #define_method method to
> create a new "callable."
Thanks for the precisions.
regards,
--
http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Hi! > no idea how it works with windows. On XP: fine. On Vista: very difficult... @+ MCI -- http://mail.python.org/mailman/listinfo/python-list
Re: Error when executing the library reference echo server example
On Dec 10, 1:48 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Mon, 10 Dec 2007 04:16:03 -0800 (PST), [EMAIL PROTECTED] wrote:
> >Hi. Python newbie speaking,
>
> >I've copy/pasted the example of the echo server that comes in the IDLE
> >documentation ("Python Library Reference" section 17.2.3) to see how
> >the sockets work. The only change I've made is in the host address
> >which I've set to 'localhost' in the client. You can see the complete
> >code below the message.
>
> >When I run it I get the following error:
> > Traceback (most recent call last):
> > File "C:\Python25\eclient.py", line 11, in
> > data = s.recv(1024)
> > error: (10053, 'Software caused connection abort')
>
> >Is the example wrong? In this case, Where can I find a working
> >example? Have I messed up the example putting 'localhost'? (don't
> >think so, because I tried with '127.0.0.1' and I got the same error).
> >And the big one, Why I get the error and how can I avoid it in future
> >applications?
>
> >Lot of thanks in advance!!
>
> You're seeing the expected behavior. The example doesn't take care to
> handle any error conditions. It has other bugs as well, such as not
> checking the return value of socket.send().
>
> Here's a different echo example:
>
> http://twistedmatrix.com/projects/core/documentation/examples/#auto0
>
> Jean-Paul
I tried it in Linux and it worked fine so I've been trying different
things as the code seems to be correct.
Finally, I've found that if both server and client are run from IDLE,
the thing crashes with the mentioned error. But if the server is run
within a shell and the client within IDLE (or another shell) it works
perfectly. Therefore I suppose the problem is in IDLE (or in my actual
IDLE version) and not in the code.
Thanks for your answers Chris and Jean-Paul.
--
http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Méta-MCI (MVP) wrote: >> no idea how it works with windows. > > On XP: fine. > On Vista: very difficult... Hello Captain Obvious :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
Robin Becker wrote: >> Ok. Still, I would write it as >> >> #if defined(__LITTLE_ENDIAN__) >> #undef WORDS_BIGENDIAN >> #elif defined(__BIG_ENDIAN__) >> #undef WORDS_BIGENDIAN >> #define WORDS_BIGENDIAN 1 >> #endif >> >> Regards, >> Martin > I'm never sure if undef gives an error if the variable isn't defined, > but that is cleaner > > thanks for the assistance Just like to say my testee/victim reports great success with the above snippet inserted into the right config file. Thanks to all. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to protect my new commercial software.
On Dec 10, 6:17 am, Tim Chase <[EMAIL PROTECTED]> wrote:
> > So, are there any ways to make it "harder" to reverse engineer a
> > program?
>
> In addition to the standby of
>
> -Don't distribute your program (SaaS)
>
> I'll add to the list:
>
> -Only distribute your program to people too non-technical to
> consider reverse-engineering
>
> -Don't document your program (or even better, *mis*document your
> program)
>
> -Write Lovecraftian code ("import goto" comes to mind) designed
> to make reverse-engineers go insane trying to figure out what you
> were thinking
>
> -In your Python, drop to in-line assembly language "for
> business-logic optimization". Only targeting specific models of
> obscure processor architectures helps minimize your audience.
>
> -Write software that does nothing of interest/value/use
>
> Just a couple ideas to get an enterprising young coder off on the
> right track ;)
>
> -tkc
Don't forget pyobfuscate:
http://www.lysator.liu.se/~astrand/projects/pyobfuscate/
http://bitboost.com/
Fun to play with...although not necessarily much more "secure".
Mike
--
http://mail.python.org/mailman/listinfo/python-list
Text file handling in python
Hello, I am tring to access a text file in random acess way, that is, using f.tell() and f.seek() to seek a certain position in the text file. f.seek() does not seem to work properly, the file is opened in a read universal 'rU' mode. Thank you very much, Nora. __ Sent from Yahoo! Mail - a smarter inbox http://uk.mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
Instead of linking records together via some key, I first try out a dictionary of lists. The list for each dictionary key would be the same as a list with a single, forward link. If you have relatively few records per key, it works well. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
On 10 Dez., 15:24, "Méta-MCI \(MVP\)" <[EMAIL PROTECTED]> wrote: > Hi! > > > no idea how it works with windows. > > On XP: fine. > On Vista: very difficult... > > @+ > > MCI Also with Python 2.5? If PyOpenGL would work with Python 2.5, I could use wx too. But I could not get it to work with 2.5 on windows. Achim -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Achim Domma wrote: > On 10 Dez., 15:24, "Méta-MCI \(MVP\)" > <[EMAIL PROTECTED]> wrote: >> Hi! >> >> > no idea how it works with windows. >> >> On XP: fine. >> On Vista: very difficult... >> >> @+ >> >> MCI > > Also with Python 2.5? If PyOpenGL would work with Python 2.5, I could > use wx too. But I could not get it to work with 2.5 on windows. I was under the impression that PyOpenGL is ctypes-based in the new versions? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
Bruno,
Please explain why the NOP import is a GoodThing. Use small words
please. I'm not as young as I used to be.
I didn't know about reload(), but now that I'm informed on that point
I'm still using
os.remove('foo.pyc')
reload(foo)
A single command to do that would be nice.
Martin
Bruno Desthuilliers wrote:
> [EMAIL PROTECTED] a �crit :
> > Thanks for all the help. Thought I'd spend my newbie days right in the
> > Python shell (there's lots to test when you're just starting) but I
> > guess that's not going to happen.
> >
> > Everyone told me to get out of the Python shell, one way or another.
>
> Everyone told you to not use the shell that way - which is not exactly
> the same thing. The shell is just great for exploring things. Like
> quicly testing APIs, expressions, syntax etc before or while coding, or
> inspecting the state after execution of your code (using the -i option),
> etc... A common (AFAICT) practice is to have some 'test setup' code in
> a .py file, that you use to import the modules under test and init a
> couple vars, then launch this script with the -i option. Emacs
> python-mode let you start a python shell in another frame, and eval
> either your whole file or just parts of it in this shell.
>
> > OK. But this means that every execution must first load Python, then
> > import my stuff.
>
> Just like it does with Java - but it might be much faster.
>
> > Import becoming a NOP after first use in the shell is
> > a six-legged feature, at best.
>
> import becoming (almost) a NOP after first effective import is the
> RightThing(tm) to do. If you want to reload a module, you have to ask
> for it explicitely - using reload(module). But this won't affect already
> instanciated objects, and can lead to very strange situations - hence
> the common pattern of the setup script + the -i option.
--
http://mail.python.org/mailman/listinfo/python-list
array.shape() gives TypeError: 'tuple' object is not callable
Hi gys -- I am looking at Numpy but getting this error when I try to get array sizes. I'm using Ubuntu Edgy with standard repositories and scipy. Any ideas? Am I doing something wrong or is it my install of scipy? $ python Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from numpy import * >>> a=array([[1,2],[3,4]]) >>> a array([[1, 2], [3, 4]]) >>> a.shape() Traceback (most recent call last): File "", line 1, in ? TypeError: 'tuple' object is not callable >>> thanks charles -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
[EMAIL PROTECTED] wrote:
> Bruno,
>
> Please explain why the NOP import is a GoodThing. Use small words
> please. I'm not as young as I used to be.
Because otherwise every import would result in overhead without any benefit.
Think of a module like this:
A_GLOBAL_VARIABLE = extremely_costly_initialization_of_cache_contents()
You only want that to happen once.
> I didn't know about reload(), but now that I'm informed on that point
> I'm still using
>
> os.remove('foo.pyc')
> reload(foo)
>
> A single command to do that would be nice.
You can create your own function that does this.
def better_reload(module):
import os
if os.path.exists(module.__file__) and module.__file__[-3:] == 'pyc':
os.remove(module.__file__) # attention - you might want more checks
reload(module)
Then you can put that into a file, e.g.
~/.pythonrc
and point the environment-variable PYTHONSTARTUP to that file.
Diez
--
http://mail.python.org/mailman/listinfo/python-list
Re: array.shape() gives TypeError: 'tuple' object is not callable
On Dec 10, 5:22 pm, Charles Fox <[EMAIL PROTECTED]> wrote: > Hi gys -- I am looking at Numpy but getting this error when I try to > get array sizes. I'm using Ubuntu Edgy with standard repositories and > scipy. Any ideas? Am I doing something wrong or is it my install of > scipy? > > $ python > Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> > from numpy import * > >>> a=array([[1,2],[3,4]]) > >>> a > > array([[1, 2], >[3, 4]])>>> a.shape() > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'tuple' object is not callable > > > > thanks > use a.shape instead. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to merge/sort two sorted lists?...
On Dec 6, 2:01 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote: > On Dec 6, 9:30 am, Aaron Watters <[EMAIL PROTECTED]> wrote: > > See recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491285 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305269 I previously noted in that I found the first recipe slow and obscure. Raymond pointed out privately that it is designed to minimize memory requirements when merging possibly many files from a filesystem. It does that very well, and I apologize for the offensive tone of my comment. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=cryptic+code+performance+hacks -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
Neil Cerutti <[EMAIL PROTECTED]> wrote: > Python's iterators are unsuitable for mutating the linked list > while iterating--the only major application of linked lists. > Wrapping in a generator won't allow you to use for loop syntax, > unless I'm missing something, which has often happened. It is certainly possible to have a linked list implementation which supports mutation while iterating. Here's a simple example: import random class LinkedElement(object): def __init__(self, value, next): self.value = value self.next = next class LinkedList(object): def __init__(self, aList): nxt = None for el in reversed(aList): nxt = LinkedElement(el, nxt) self._cursor = self._list = LinkedElement(None, nxt) def delete(self, element): assert self._cursor.next is element self._cursor.next = self._cursor.next.next def __iter__(self): self._cursor = el = self._list while el.next: nxt = el.next yield nxt if nxt is el.next: self._cursor = el = nxt def test(): ll = LinkedList([random.randint(1,1000) for i in range(10)]) for el in ll: if el.value%2==0: ll.delete(el) print [el.value for el in ll] if __name__=='__main__': test() Support for deleting elements other than the current one, and insertBefore/insertAfter methods is left as an exercise. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fill In a Form Automatically
Thanks! Mechanize looks really cool :)) Victor On Dec 7, 2007 4:11 PM, Ismail Dönmez <[EMAIL PROTECTED]> wrote: > Friday 07 December 2007 22:06:23 tarihinde Victor Subervi şunları > yazmıştı: > > Hi; > > I'm trying to fill in a Zope form automatically. I have this script, > which > > works great for creating the page...but how do I write to it? > > Use Mechanize [0]. > > [0] http://wwwsearch.sourceforge.net/mechanize/ > > -- > Never learn by your mistakes, if you do you may never dare to try again. > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: searching a value of a dict (each value is a list)
On Dec 10, 8:31 am, Neil Cerutti <[EMAIL PROTECTED]> wrote: > On 2007-12-10, MonkeeSage <[EMAIL PROTECTED]> wrote: > > > If I'm not mistaken, building a reverse dictionary like that will be > > O(n*m) because dict/list access is O(n) (ammortized). Somebody correct > > me if I'm wrong. In that case, it really depends on how you will use > > the dict to see whether you get any benefit from building the reversed > > dict. If you want to do several lookups, then the initial overhead > > (speed/memory) of building the reversed dict might be worth it so that > > you can just run lookups at O(n). > > It also depends on if the dictionary shall be mutated between > reverse lookups. > > > But if you only need it once, it is a waste of time and space > > to create a reverse dict when your access time is the same for > > the lookup as for building the reversed dict. > > > If you do need more than one lookup, it would also be a good > > optimization strategy to build the reverse dict in parallel, as > > you execute the first search; that way you can combine the time > > spent on building the reverse dict and the lookup, to get a > > total of O(n*m) rather than O(n^2*m). The first search is > > "free" since you need the reverse dict anyway. > > It wouldn't be merely an optimization if reverse lookups and > mutations were interleaved. > > -- > Neil Cerutti > You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor Well true, but you enter a whole other level of complexity in that case...something like Theta(log(n*(m-n))). I might have calculated that incorrectly, but that just goes to show how complex a lookup is(!) in such a case. Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: searching a value of a dict (each value is a list)
On Dec 10, 8:31 am, Neil Cerutti <[EMAIL PROTECTED]> wrote: > On 2007-12-10, MonkeeSage <[EMAIL PROTECTED]> wrote: > > > If I'm not mistaken, building a reverse dictionary like that will be > > O(n*m) because dict/list access is O(n) (ammortized). Somebody correct > > me if I'm wrong. In that case, it really depends on how you will use > > the dict to see whether you get any benefit from building the reversed > > dict. If you want to do several lookups, then the initial overhead > > (speed/memory) of building the reversed dict might be worth it so that > > you can just run lookups at O(n). > > It also depends on if the dictionary shall be mutated between > reverse lookups. > > > But if you only need it once, it is a waste of time and space > > to create a reverse dict when your access time is the same for > > the lookup as for building the reversed dict. > > > If you do need more than one lookup, it would also be a good > > optimization strategy to build the reverse dict in parallel, as > > you execute the first search; that way you can combine the time > > spent on building the reverse dict and the lookup, to get a > > total of O(n*m) rather than O(n^2*m). The first search is > > "free" since you need the reverse dict anyway. > > It wouldn't be merely an optimization if reverse lookups and > mutations were interleaved. > > -- > Neil Cerutti > You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor Well true, but you enter a whole other level of complexity in that case...something like Theta(log(n*(m-n))). I might have calculated that incorrectly, but that just goes to show how complex a lookup is(!) in such a case. Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On 2007-12-10, Duncan Booth <[EMAIL PROTECTED]> wrote: > Neil Cerutti <[EMAIL PROTECTED]> wrote: >> Python's iterators are unsuitable for mutating the linked list >> while iterating--the only major application of linked lists. >> Wrapping in a generator won't allow you to use for loop >> syntax, unless I'm missing something, which has often >> happened. > > It is certainly possible to have a linked list implementation > which supports mutation while iterating. Here's a simple > example: > > import random > > class LinkedElement(object): > def __init__(self, value, next): > self.value = value > self.next = next > > class LinkedList(object): > def __init__(self, aList): > nxt = None > for el in reversed(aList): > nxt = LinkedElement(el, nxt) > self._cursor = self._list = LinkedElement(None, nxt) > > > def delete(self, element): > assert self._cursor.next is element > self._cursor.next = self._cursor.next.next > > def __iter__(self): > self._cursor = el = self._list > while el.next: > nxt = el.next > yield nxt > if nxt is el.next: > self._cursor = el = nxt > > def test(): > ll = LinkedList([random.randint(1,1000) for i in range(10)]) > > for el in ll: > if el.value%2==0: > ll.delete(el) > > print [el.value for el in ll] > > > if __name__=='__main__': > test() > > Support for deleting elements other than the current one, and > insertBefore/insertAfter methods is left as an exercise. Making an object its own iterator for files, but not for a container. After the deletions, you can never iterate again. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: searching a value of a dict (each value is a list)
On Dec 10, 9:45 am, MonkeeSage <[EMAIL PROTECTED]> wrote: > On Dec 10, 8:31 am, Neil Cerutti <[EMAIL PROTECTED]> wrote: > > > > > On 2007-12-10, MonkeeSage <[EMAIL PROTECTED]> wrote: > > > > If I'm not mistaken, building a reverse dictionary like that will be > > > O(n*m) because dict/list access is O(n) (ammortized). Somebody correct > > > me if I'm wrong. In that case, it really depends on how you will use > > > the dict to see whether you get any benefit from building the reversed > > > dict. If you want to do several lookups, then the initial overhead > > > (speed/memory) of building the reversed dict might be worth it so that > > > you can just run lookups at O(n). > > > It also depends on if the dictionary shall be mutated between > > reverse lookups. > > > > But if you only need it once, it is a waste of time and space > > > to create a reverse dict when your access time is the same for > > > the lookup as for building the reversed dict. > > > > If you do need more than one lookup, it would also be a good > > > optimization strategy to build the reverse dict in parallel, as > > > you execute the first search; that way you can combine the time > > > spent on building the reverse dict and the lookup, to get a > > > total of O(n*m) rather than O(n^2*m). The first search is > > > "free" since you need the reverse dict anyway. > > > It wouldn't be merely an optimization if reverse lookups and > > mutations were interleaved. > > > -- > > Neil Cerutti > > You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor > > Well true, but you enter a whole other level of complexity in that > case...something like Theta(log(n*(m-n))). I might have calculated > that incorrectly, but that just goes to show how complex a lookup > is(!) in such a case. > > Regards, > Jordan Sorry for the double-post...google is being beligerant right now. -- http://mail.python.org/mailman/listinfo/python-list
Re: help with pyparsing
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
Paul McGuire wrote:
> On Dec 9, 11:01 pm, Prabhu Gurumurthy <[EMAIL PROTECTED]> wrote:
>> -BEGIN PGP SIGNED MESSAGE-
>> Hash: SHA1
>>
>> All,
>>
>> I have the following lines that I would like to parse in python using
>> pyparsing, but have some problems forming the grammar.
>>
>> Line in file:
>> table const { 207.135.103.128/26, 207.135.112.64/29 }
>> table persist { ! 10.200.2/24, 10.200/22 }
>> table const { 192.168/16, ! 172.24.1/29, 172.16/12, 169.254/16 }
>> table persist { 10.202/22 }
>> table const { 10.206/22 }
>> table const { \
>>10.205.1/24, \
>>169.136.241.68, \
>>169.136.241.70, \
>>169.136.241.71, \
>>169.136.241.72, \
>>169.136.241.75, \
>>169.136.241.76, \
>>169.136.241.77, \
>>169.136.241.78, \
>>169.136.241.79, \
>>169.136.241.81, \
>>169.136.241.82, \
>>169.136.241.85 }
>>
>> I have the following grammar defn.
>>
>> tableName = Word(alphanums + "-" + "_")
>> leftClose = Suppress("<")
>> rightClose = Suppress(">")
>> key = Suppress("table")
>> tableType = Regex("persist|const")
>> ip4Address = OneOrMore(Word(nums + "."))
>> ip4Network = Group(ip4Address + Optional(Word("/") +
>> OneOrMore(Word(nums
>> temp = ZeroOrMore("\\" + "\n")
>> tableList = OneOrMore(Optional("\\") |
>>ip4Network | ip4Address | Suppress(",") | Literal("!"))
>> leftParen = Suppress("{")
>> rightParen = Suppress("}")
>>
>> table = key + leftClose + tableName + rightClose + tableType + \
>> leftParen + tableList + rightParen
>>
>> I cannot seem to match sixth line in the file above, i.e table name with
>> KS, how do I form the grammar for it, BTW, I still cannot seem to ignore
>> comments using table.ignore(Literal("#") + restOfLine), I get a parse error.
>>
>> Any help appreciated.
>> Thanks
>> Prabhu
>
> Prabhu -
>
> This is a good start, but here are some suggestions:
>
> 1. ip4Address = OneOrMore(Word(nums + "."))
>
> Word(nums+".") will read any contiguous set of characters in the
> string nums+".", so OneOrMore is not necessary for reading in an
> ip4Address. Just use:
>
> ip4Address = Word(nums + ".")
>
>
> 2. ip4Network = Group(ip4Address + Optional(Word("/") +
> OneOrMore(Word(nums
>
> Same comment, OneOrMore is not needed for the added value to the
> ip4Address:
>
> ip4Network = Group(ip4Address + Optional(Word("/") + Word(nums
>
>
> 3. tableList = OneOrMore(Optional("\\") |
>ip4Network | ip4Address | Suppress(",") |
> Literal("!"))
>
> The list of ip4Networks is just a comma-delimited list, with some
> entries preceded with a '!' character. It is simpler to use
> pyparsing's built-in helper, delimitedList, as in:
>
> tableList = Group( delimitedList(Group("!"+ip4Network)|ip4Network) )
>
>
> Yes, I know, you are saying, "but what about all those backslashes?"
> The backslashes look like they are just there as line continuations.
> We can define an ignore expression, so that the table expression, and
> all of its contained expressions, will ignore '\' characters as line
> continuations:
>
> table.ignore( Literal("\\") + LineEnd() )
>
> And I'm not sure why you had trouble with ignoring '#' + restOfLine,
> it works fine in the program below.
>
> If you make these changes, your program will look something like this:
>
> tableName = Word(alphanums + "-" + "_")
> leftClose = Suppress("<")
> rightClose = Suppress(">")
> key = Suppress("table")
> tableType = Regex("persist|const")
> ip4Address = Word(nums + ".")
> ip4Network = Group(ip4Address + Optional(Word("/") + Word(nums)))
> tableList = Group(delimitedList(Group("!"+ip4Network)|ip4Network))
> leftParen = Suppress("{")
> rightParen = Suppress("}")
>
> table = key + leftClose + tableName + rightClose + tableType + \
> leftParen + tableList + rightParen
> table.ignore(Literal("\\") + LineEnd())
> table.ignore(Literal("#") + restOfLine)
>
> # parse the input line, and pprint the results
> result = OneOrMore(table).parseString(line)
> from pprint import pprint
> pprint(result.asList())
>
> Prints out:
> ['ALINK',
> 'const',
> [['207.135.103.128', '/', '26'], ['207.135.112.64', '/', '29']],
> 'INTRANET',
> 'persist',
> [['!', ['10.200.2', '/', '24']], ['10.200', '/', '22']],
> 'RFC_1918',
> 'const',
> [['192.168', '/', '16'],
> ['!', ['172.24.1', '/', '29']],
> ['172.16', '/', '12'],
> ['169.254', '/', '16']],
> 'DIALER',
> 'persist',
> [['10.202', '/', '22']],
> 'RAVPN',
> 'const',
> [['10.206', '/', '22']],
> 'KS',
> 'const',
> [['10.205.1', '/', '24'],
> ['169.136.241.68'],
> ['169.136.241.70'],
> ['169.136.241.71'],
> ['169.136.241.72'],
> ['169.136.241.75'],
> ['169.136.241.76'],
> ['169.136.241.77'],
> ['169.136.241.78'],
> ['169.136.241.79'],
> ['169.136.241.81'],
> ['169.136.241.82'],
> ['169.136.241.85']]]
>
> -- Paul
Awesome, thanks a lot will try it today and will
Re: Error when executing the library reference echo server example
On Mon, 10 Dec 2007 06:38:57 -0800 (PST), [EMAIL PROTECTED] wrote: > [snip] > >I tried it in Linux and it worked fine so I've been trying different >things as the code seems to be correct. >Finally, I've found that if both server and client are run from IDLE, >the thing crashes with the mentioned error. But if the server is run >within a shell and the client within IDLE (or another shell) it works >perfectly. Therefore I suppose the problem is in IDLE (or in my actual >IDLE version) and not in the code. It's certainly true that it may work better in some environments, and it is definitely true that many programs/libraries don't work as expected when run from IDLE. However, that doesn't mean that the example is correct. Keep in mind that handling error conditions is an important part of writing correct programs. You can't rely on everything always going right all the time. Even if you stick with the socket module, you should make sure to handle exceptions from socket calls and always check the return value of the send method. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
On Dec 9, 2007 5:11 AM, Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > On Dec 9, 12:15 am, Bruno Desthuilliers > <[EMAIL PROTECTED]> wrote: > > Richard Jones a écrit : > > > > > > > > > Bruno Desthuilliers wrote: > > > > >>class A(object): > > >> @apply > > >> def a(): > > >> def fget(self): > > >> return self._a > > >> def fset(self, val): > > >> self._a = val > > >> return property(**locals()) > > >> def __init__(self): > > >> self.a = "foo" > > > > > That property setup seems overly complicated. As far as I can see, it only > > > avoids defining the setter in the class namespace, > > > > Yes. That's mosly the point. > > > > > yet is more complicated > > > and obfuscated to boot ;) > > > > Well, that's your POV, so what can I say ? It's indeed a bit hackish, > > and requires a couple minutes of attention the first time you see it. > > And you just have to learn it once !-) > > Perhaps 'return property(fget, fset)' would be easier to make sense of > than **locals() > > > Now I'd certainly prefer something like: > > > > class A(object): > > @propget > > def a(self): > > return self._a > > @propset > > def a(self, val): > > self._a = val > > > > But until there's something similar *builtin*, I'll stick to the @apply > > trick. > > At first sight, I like the look of this. Obviously I can't provide a > builtin implementation, but there's an easy way to achieve this. It > uses sys._getframe but there is no need to fiddle with metaclasses: > Something very like this will be in 3k, and I believe is also being backported to 2.6. See python-dev archives for more. -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
On Dec 9, 10:54 pm, John Machin <[EMAIL PROTECTED]> wrote: > On Dec 10, 9:43 am, "Just Another Victim of the Ambient Morality" > > <[EMAIL PROTECTED]> wrote: > > I'm looking for a linked list implementation. Something iterable with > > constant time insertion anywhere in the list. > > It's on the shelf between the jar of phlogiston and the perpetual > motion machine. lol! -- Ant. -- http://mail.python.org/mailman/listinfo/python-list
Dumb newbie back in shell
OK, it's a scripting language.
>>> def g():
...os.remove('tokeneizer.pyc')
...reload( tokeneizer )
...tokeneizer.tokenize('sample_decaf.d')
...
>>>
But that gets me to:
... line 110, in get_toks
UnboundLocalError: local variable 'line_ptr' referenced before
assignment
Here's a bit of the code, with line #s
...
68 global line_ptr
69 global char_ptr
...
75 line_ptr = 0
76 char_ptr = 0
...
109 def get_toks( text ):
110 while line_ptr < last_line:
...
So when is a global var global?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Is a "real" C-Python possible?
On Dec 9, 1:14 pm, "Jack" <[EMAIL PROTECTED]> wrote: > I wonder if it's possible to have a Python that's completely (or at > least for the most part) implemented in C, just like PHP - I think > this is where PHP gets its performance advantage. Or maybe I'm wrong > because the core modules that matter are already in C and those Python > files are really a think wrapper. Anyhow, if would be ideal if Python > has performance similar to Java, with both being interpreted languages. -1 This would seriously muck-up the evolution of the language. Having a few building blocks written in C provides a basis for writing very fast pure python (for example, sets, heapq, itertools). Beyond those building blocks, it is a step backwards to write in C. Also, if you really need performance, the traditional solutions are to use tools like Psyco or Pyrex. Raymond -- http://mail.python.org/mailman/listinfo/python-list
SOAPpy server shutting down?
I have a soap server I am running on an OS X Server using SOAPpy. To
start the server I am running
server = SOAPpy.SOAPServer(('IPADDRESS", PORT), namespace=NAMESPACE)
server.serve_forever()
I am starting the server manually in the background by running from
the command line as follows:
./mySOAPServer.py &
However, when I log out of my ssh session, the server often stops
working. I have not been able to find a consistent amount of time it
will stay up, however it always seems to go down after an hour or so.
Any ideas on how to prevent this or take care of the problem. So far
all I could come up with is running a cron job to check for the
process, then start it if it is not running. However, in the
production environment I need this to be running 24/7 so I can't
really afford any down time. I would need to run my cron job every
minute or so to get the most up-time possible and would like to avoid
this.
Any ideas? Thanks.
--
http://mail.python.org/mailman/listinfo/python-list
Re: detecting disc serial number without win32
PiErre wrote: > I have to run a python script on a Linux machine. This script was > developed on a windows workstation and it > uses the win32 library to detect the cd (or dvd) serial number (in the > - format). > How can I change the script to do the same task on linux? > I found an old post on the same task [ "(Joliet) volume name and > serial number" on 26 Feb 2003 ] > but without answer... Hey, that was my first post on c.l.py. After that underwhelming response I took to answering posts :-) > Any chance there is now a way of implement such a low-level feature? On Ubuntu there is the python-cddb package http://packages.ubuntu.com/gutsy/python/python-cddb providing DiskID.disk_id(), and retrieving CD titles etc. works fine. However, comparing the disk IDs with the serial numbers in that Access-DB of yore, they differ -- so back to square one. Older not wiser, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm missing something here with range vs. xrange
On Dec 7, 2007 8:58 PM, Joe Goldthwaite <[EMAIL PROTECTED]> wrote: > >You can't imagine why someone might prefer an iterative solution over > >a greedy one? Depending on the conditions, the cost of creating the > >list can be a greater or a lesser part of the total time spent. Actual > >iteration is essentially the same cost for both. Try looking at memory > >usage while you're running these tests. > > I can imagine why someone would want to use in iterative solution. What I > don't understand is why there's so little difference between the two. > Here's what I think is going on; > > To do a range(100) > > 1. Allocate a big chunk of memory > 2. Fill the memory with the range of integers > 3. Setup an index into the memory array > 4. Every time the program asks for the next item, bump >the memory index by one, get the value and return it. > No. What range does is create and return a list of integers. The iteration is a separate step, and is traditional list iteration. In longhand, for x in range(y): looks something like this: range = [] #this loop happens in C and is super-fast for small values of y, it #gets much much slower when y gets out of the range of pre-allocated list pools #and the small integer cache while y >= 0: range.append(y) y -= 1 for x in range: #blah List iteration works more or less as you describe, since it's implemented in C. What you describe is more or less how psyco optimizes the use of range(), though. > To do an xrange(1000) > > 1. Set up a counter > 2. Every time the program asks for the next item, increment > the counter and return it. > This is essentially correct, but remember that it's constructing and returning an int object each time. This is exactly the same thing that the range() constructor does, it just happens lazily. > I guess I thought that between these two methods, the second would be > dramatically faster. An order of magnitude faster. My surprise is that it's > not. That's why I figured I'm missing something because the above steps > don't seem to describe what's going on. Hence, the title, "I'm missing > something". > The creation of the xrange object is massively faster - at least an order of magnitude. However, once you actually iterate over both of them you're normalizing almost all of the overhead that range has. The advantage of xrange is the reduced memory pressure (and the improved performance that often entails). -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI development with 3D view
Diez B. Roggisch wrote: ... > I was under the impression that PyOpenGL is ctypes-based in the new > versions? > It is, but I haven't had the time to do a new release and check it on a Windows box. There are minor fixes in CVS that *should* IIRC make us run better on those Windows machines that have problems with the 3.x alphas so far. Tempus fugit, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
On Mon, 10 Dec 2007 08:31:01 -0800, MartinRinehart wrote: > But that gets me to: > > ... line 110, in get_toks > UnboundLocalError: local variable 'line_ptr' referenced before > assignment > > Here's a bit of the code, with line #s > > ... > 68 global line_ptr > 69 global char_ptr > ... > 75 line_ptr = 0 > 76 char_ptr = 0 > ... > 109 def get_toks( text ): > 110 while line_ptr < last_line: > ... > So when is a global var global? When you declare it ``global`` *in the function*. ``global`` on module level has no effect. IMHO that should emit at least a warning… Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
[EMAIL PROTECTED] a écrit :
> OK, it's a scripting language.
For which definition of "scripting language" ?-)
def g():
> ...os.remove('tokeneizer.pyc')
> ...reload( tokeneizer )
> ...tokeneizer.tokenize('sample_decaf.d')
> ...
>
> But that gets me to:
>
> ... line 110, in get_toks
> UnboundLocalError: local variable 'line_ptr' referenced before
> assignment
>
> Here's a bit of the code, with line #s
>
> ...
> 68 global line_ptr
> 69 global char_ptr
> ...
> 75 line_ptr = 0
> 76 char_ptr = 0
> ...
> 109 def get_toks( text ):
> 110 while line_ptr < last_line:
> ...
> So when is a global var global?
Short answer : never !-)
Long answer:
First point: "global" really means "module level" - there's no
"application global" namespaces.
Second point: every name declared as the top-level is global - according
to the above definition. So there's no need to declare them as such. The
only place where you need the global statement is when you want to
rebind a module-level name from within a function. And it's in this
function that you need to declare the name as global.
FWIW, this is documented.
Last point: Python is not C, and it definitively doesn't have pointers.
Trying to write C in Python is a waste of time and an experiment in
frustration (just like trying to write language XXX in language YYY for
any distinct values of XXX and YYY).
HTH
--
http://mail.python.org/mailman/listinfo/python-list
Re: Are Python deques linked lists?
Neil Cerutti wrote: > On 2007-12-10, Duncan Booth <[EMAIL PROTECTED]> wrote: >> def test(): >> ll = LinkedList([random.randint(1,1000) for i in range(10)]) >> >> for el in ll: >> if el.value%2==0: >> ll.delete(el) >> >> print [el.value for el in ll] >> >> >> if __name__=='__main__': >> test() >> >> Support for deleting elements other than the current one, and >> insertBefore/insertAfter methods is left as an exercise. > > Making an object its own iterator [works] for files, but not for a > container. After the deletions, you can never iterate again. Look at the test code again -- there is a second iteration after the deletions (the list comprehension). However, you will get into trouble if you try to run two simultaneous iterations over the same LinkedList, so there is room for another exercise ;) Peter -- http://mail.python.org/mailman/listinfo/python-list
