content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python - Number of Significant Digits in results of division Newbie here. I have the following code: myADC = 128 maxVoltage = 5.0 maxADC = 255.0 VoltsPerADC = maxVoltage/maxADC myVolts = myADC * VoltsPerADC print "myADC = {0: >3}".format(myADC) print "VoltsPerADC = {0: >7}".format(VoltsPerADC) print VoltsPerADC print "myVolts = {0: >7}".format(myVolts) print myVolts This outputs the following: myADC = 128 VoltsPerADC = 0.0196078 0.0196078431373 myVolts = 2.5098 2.50980392157 I have been searching for an explanation of how the number of significant digits is determined by default, but have had trouble locating an explanation that makes sense to me. This link link text suggests that by default the "print" statement prints numbers to 10 significant figures, but that does not seem to be the case in my results. How are the number of significant digits/precision determined? Can someone shed some light on this for me. Thanks in advance for your time and patience. A: The precision is determined by the hardware. Python uses hardware floats (actually doubles) for its floats. The implications are discussed in the tutorial: http://docs.python.org/tutorial/floatingpoint.html If you want more control over precision and rounding, you should consider using the decimal module. A: In general, if the documentation isn't at python.org, it is not authoritative. If you look at print it will tell you that floating point numbers are first converted to strings and float will tell you (as Thomas noted) that the machine native double type is how floats are stored and that the language makes no guarantees about significant digits.
Python - Number of Significant Digits in results of division
Newbie here. I have the following code: myADC = 128 maxVoltage = 5.0 maxADC = 255.0 VoltsPerADC = maxVoltage/maxADC myVolts = myADC * VoltsPerADC print "myADC = {0: >3}".format(myADC) print "VoltsPerADC = {0: >7}".format(VoltsPerADC) print VoltsPerADC print "myVolts = {0: >7}".format(myVolts) print myVolts This outputs the following: myADC = 128 VoltsPerADC = 0.0196078 0.0196078431373 myVolts = 2.5098 2.50980392157 I have been searching for an explanation of how the number of significant digits is determined by default, but have had trouble locating an explanation that makes sense to me. This link link text suggests that by default the "print" statement prints numbers to 10 significant figures, but that does not seem to be the case in my results. How are the number of significant digits/precision determined? Can someone shed some light on this for me. Thanks in advance for your time and patience.
[ "The precision is determined by the hardware. Python uses hardware floats (actually doubles) for its floats. The implications are discussed in the tutorial: http://docs.python.org/tutorial/floatingpoint.html\nIf you want more control over precision and rounding, you should consider using the decimal module.\n", "In general, if the documentation isn't at python.org, it is not authoritative. If you look at print it will tell you that floating point numbers are first converted to strings and float will tell you (as Thomas noted) that the machine native double type is how floats are stored and that the language makes no guarantees about significant digits. \n" ]
[ 6, 0 ]
[]
[]
[ "digits", "division", "floating_point", "format", "python" ]
stackoverflow_0002559835_digits_division_floating_point_format_python.txt
Q: wxPython: Sending a signal to several widgets I am not even sure how to ask this question. I want something that is like the wxPython event system, but a bit different. I'll try to explain. When there is a certain change in my program (a "tree change", never mind what that is,) I want to send a signal to all the widgets in my program, notifying them that a "tree change" has occurred, and they should change their display in response. How do I do this? It sounds a little bit like wxPython events, but not really, since events don't spread to all widgets, as far as I know. What would be a good way to do this? A: You can write your own publish-subscribe mechanism which can be as simple as this: def register(self, callback): self.callbacks.append(callback) def emit(self, eventName): for callback in self.callbacks: callback(eventName) Anybody interested in listening to event registers a function with central registry and then you can emit a event to interested parties, you can improve it further by having to register for a specific event, having multiple registrars, unregister, error checking etc Alternatively you can use wxPython's wx.lib.pubsub module or other python libraries like PyPubsub , PyDispatcher A: check out the observer design pattern. you need to implement the widgets as an observers . and the signal sender as the subject. so whenever it the subject sends a signal, all the observers will be notified. check this out for more info about observers
wxPython: Sending a signal to several widgets
I am not even sure how to ask this question. I want something that is like the wxPython event system, but a bit different. I'll try to explain. When there is a certain change in my program (a "tree change", never mind what that is,) I want to send a signal to all the widgets in my program, notifying them that a "tree change" has occurred, and they should change their display in response. How do I do this? It sounds a little bit like wxPython events, but not really, since events don't spread to all widgets, as far as I know. What would be a good way to do this?
[ "You can write your own publish-subscribe mechanism which can be as simple as this:\ndef register(self, callback):\n self.callbacks.append(callback)\n\ndef emit(self, eventName):\n for callback in self.callbacks:\n callback(eventName)\n\nAnybody interested in listening to event registers a function with central registry and then you can emit a event to interested parties, you can improve it further by having to register for a specific event, having multiple registrars, unregister, error checking etc\nAlternatively you can use wxPython's wx.lib.pubsub module or other python libraries like PyPubsub , PyDispatcher\n", "check out the observer design pattern.\nyou need to implement the widgets as an observers . and the signal sender as the subject. so whenever it the subject sends a signal, all the observers will be notified. \n check this out for more info about observers \n" ]
[ 6, 0 ]
[]
[]
[ "event_handling", "events", "python", "signals", "wxpython" ]
stackoverflow_0002546814_event_handling_events_python_signals_wxpython.txt
Q: Python check if object is in list of objects I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list. I thought I could simply do for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both lists" However this does not seem to work. Although if I do: if item1.title == item2.title: it works okay. I have more attributes than this though so don't really want to do 1 big if statement comparing all the attributes if I don't have to. Can anyone give me help or advise on what I can do to find the objects which appear in both lists. Thanks A: Assuming that your object has only a title attribute which is relevant for equality, you have to implement the __eq__ method as follows: class YourObject: [...] def __eq__(self, other): return self.title == other.title Of course if you have more attributes that are relevant for equality, you must include those as well. You might also consider implementing __ne__ and __cmp__ for consistent behaviour. A: In case the objects are not the same instance, you need to implement the __eq__ method for python to be able to tell when 2 objects are actually equal. Of course that most library types, such as strings and lists already have __eq__ implemented, which may be the reason comparing titles works for you (are they strings?). For further information see the python documentation. Here is a random example for __eq__. A: set intersection will do for that. >>> x=[1,2,3,4] >>> y=[3,4,5,6] >>> for i in set(x) & set(y): ... print "item %d in both lists" %i ... item 3 in both lists item 4 in both lists A: Finding objects who appear in both lists: l1 = [1,2,3,4,5] l2 = [3,4,5] common = set(l1).intersection(set(l2)) Combine this with the __eq__ implementation on the object as the others suggested. A: You need to write an __eq__ function to define how to compare objects for equality. If you want sorting, then yo should have a __cmp__ function, and it makes the most sense to implement __eq__ in terms of __cmp__. def __eq__(self, other): return cmp(self, other) == 0 You should probably also implement __hash__, and you definitely should if you plan to put your objects into a set or dictionary. The default __hash__ for objects is id(), which effectively makes all objects unique(i.e. uniqueness is not based on object contents). I wrote a base class/interface for a class that does this sort of equivalence comparison. You may find it useful: class Comparable(object): def attrs(self): raise Exception("Must be implemented in concrete sub-class!") def __values(self): return (getattr(self, attr) for attr in self.attrs()) def __hash__(self): return reduce(lambda x, y: 37 * x + hash(y), self.__values(), 0) def __cmp__(self, other): for s, o in zip(self.__values(), other.__values()): c = cmp(s, o) if c: return c return 0 def __eq__(self, other): return cmp(self, other) == 0 def __lt__(self, other): return cmp(self, other) < 0 def __gt__(self, other): return cmp(self, other) > 0 if __name__ == '__main__': class Foo(Comparable): def __init__(self, x, y): self.x = x self.y = y def attrs(self): return ('x', 'y') def __str__(self): return "Foo[%d,%d]" % (self.x, self.y) def foo_iter(x): for i in range(x): for j in range(x): yield Foo(i, j) for a in foo_iter(4): for b in foo_iter(4): if a<b: print "%(a)s < %(b)s" % locals() if a==b: print "%(a)s == %(b)s" % locals() if a>b: print "%(a)s > %(b)s" % locals() The derived class must implement attrs() that returns a tuple or list of the object's attributes that contribute to its identity (i.e. unchanging attributes that make it what it is). Most importantly, the code correctly handles equivalence where there are multiple attributes, and this is old school code that is often done incorrectly. A: matches = [x for x in listA if x in listB] A: Try the following: list1 = [item1, item2, item3] list2 = [item3, item4, item5] for item in list1: if item in list2: print "item %s in both lists" % item
Python check if object is in list of objects
I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list. I thought I could simply do for item1 in list1: for item2 in list2: if item1 == item2: print "item %s in both lists" However this does not seem to work. Although if I do: if item1.title == item2.title: it works okay. I have more attributes than this though so don't really want to do 1 big if statement comparing all the attributes if I don't have to. Can anyone give me help or advise on what I can do to find the objects which appear in both lists. Thanks
[ "Assuming that your object has only a title attribute which is relevant for equality, you have to implement the __eq__ method as follows:\nclass YourObject:\n [...]\n def __eq__(self, other):\n return self.title == other.title\n\nOf course if you have more attributes that are relevant for equality, you must include those as well. You might also consider implementing __ne__ and __cmp__ for consistent behaviour.\n", "In case the objects are not the same instance, you need to implement the __eq__ method for python to be able to tell when 2 objects are actually equal.\nOf course that most library types, such as strings and lists already have __eq__ implemented, which may be the reason comparing titles works for you (are they strings?).\nFor further information see the python documentation.\nHere is a random example for __eq__.\n", "set intersection will do for that.\n>>> x=[1,2,3,4]\n>>> y=[3,4,5,6]\n>>> for i in set(x) & set(y):\n... print \"item %d in both lists\" %i\n...\nitem 3 in both lists\nitem 4 in both lists\n\n", "Finding objects who appear in both lists:\nl1 = [1,2,3,4,5]\nl2 = [3,4,5]\ncommon = set(l1).intersection(set(l2))\n\nCombine this with the __eq__ implementation on the object as the others suggested.\n", "You need to write an __eq__ function to define how to compare objects for equality. If you want sorting, then yo should have a __cmp__ function, and it makes the most sense to implement __eq__ in terms of __cmp__.\ndef __eq__(self, other):\n return cmp(self, other) == 0\n\nYou should probably also implement __hash__, and you definitely should if you plan to put your objects into a set or dictionary. The default __hash__ for objects is id(), which effectively makes all objects unique(i.e. uniqueness is not based on object contents).\nI wrote a base class/interface for a class that does this sort of equivalence comparison. You may find it useful:\nclass Comparable(object):\n def attrs(self):\n raise Exception(\"Must be implemented in concrete sub-class!\")\n def __values(self):\n return (getattr(self, attr) for attr in self.attrs())\n def __hash__(self):\n return reduce(lambda x, y: 37 * x + hash(y), self.__values(), 0)\n def __cmp__(self, other):\n for s, o in zip(self.__values(), other.__values()):\n c = cmp(s, o)\n if c:\n return c\n return 0\n def __eq__(self, other):\n return cmp(self, other) == 0\n def __lt__(self, other):\n return cmp(self, other) < 0\n def __gt__(self, other):\n return cmp(self, other) > 0\n\nif __name__ == '__main__':\n class Foo(Comparable):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n def attrs(self):\n return ('x', 'y')\n def __str__(self):\n return \"Foo[%d,%d]\" % (self.x, self.y)\n\n def foo_iter(x):\n for i in range(x):\n for j in range(x):\n yield Foo(i, j)\n\n for a in foo_iter(4):\n for b in foo_iter(4):\n if a<b: print \"%(a)s < %(b)s\" % locals()\n if a==b: print \"%(a)s == %(b)s\" % locals()\n if a>b: print \"%(a)s > %(b)s\" % locals()\n\nThe derived class must implement attrs() that returns a tuple or list of the object's attributes that contribute to its identity (i.e. unchanging attributes that make it what it is). Most importantly, the code correctly handles equivalence where there are multiple attributes, and this is old school code that is often done incorrectly.\n", "matches = [x for x in listA if x in listB]\n\n", "Try the following:\nlist1 = [item1, item2, item3]\nlist2 = [item3, item4, item5]\nfor item in list1:\n if item in list2:\n print \"item %s in both lists\" % item\n\n" ]
[ 39, 10, 5, 4, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002559083_python.txt
Q: Python: re-initialize a function's default value for subsequent calls to the function I have a function that calls itself to increment and decrement a stack. I need to call it a number of times, and I'd like it to work the same way in subsequent calls but, as expected, it doesn't re-use the default value. I've read that this is a newbie trap and I've seen suggested solutions, but I haven't been able to make any solution work. It would be nice to be able to "fun.reset" def a(x, stack = [None]): print x,' ', stack if x > 5: temp = stack.pop() if x <=5: stack.append(1) if stack == []: return a(x + 1) print a(0) print a(2) #second call print a(3) #third call I expected this to work, but it doesn't. print a(0, [None]) print a(2, [None]) #second call print a(3, [None]) #third call Can I reset the function to it's initial state? Any help would be appreciated. A: Just pass stack explicitly when doing recursive call: def a(x, stack=None): if stack is None: stack = [None] ... a(x + 1, stack) A: def a(x, stack = None): if stack is None: stack = [None] ... A: This problem happens because you modify the default argument, which is mutable. As in Kai's answer, one usually solves this by not modifying the default argument.
Python: re-initialize a function's default value for subsequent calls to the function
I have a function that calls itself to increment and decrement a stack. I need to call it a number of times, and I'd like it to work the same way in subsequent calls but, as expected, it doesn't re-use the default value. I've read that this is a newbie trap and I've seen suggested solutions, but I haven't been able to make any solution work. It would be nice to be able to "fun.reset" def a(x, stack = [None]): print x,' ', stack if x > 5: temp = stack.pop() if x <=5: stack.append(1) if stack == []: return a(x + 1) print a(0) print a(2) #second call print a(3) #third call I expected this to work, but it doesn't. print a(0, [None]) print a(2, [None]) #second call print a(3, [None]) #third call Can I reset the function to it's initial state? Any help would be appreciated.
[ "Just pass stack explicitly when doing recursive call:\ndef a(x, stack=None):\n if stack is None:\n stack = [None]\n ...\n a(x + 1, stack)\n\n", "def a(x, stack = None):\n if stack is None:\n stack = [None]\n ...\n\n", "This problem happens because you modify the default argument, which is mutable. As in Kai's answer, one usually solves this by not modifying the default argument.\n" ]
[ 4, 3, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002560697_function_python.txt
Q: cache.fetch in Django? Does Django caching have a method similar to Rails' cache.fetch? (http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#M001023) The rails cache fetch works like: cache.fetch("my_key") { // return what I want to put in my_key if it is empty "some_value" } It's useful because it checks the cache, and returns the value of the cache if it is there. If not, it will store "some_value" in the cache, and then return "some_value". Is there an equivalent of this in Django? If not, what would the Python syntax for this look like if I were to implement such a function? A: I think the code you would have to write would be like this: (EDIT) def get_value(param1,param2): return "value %s - %s " % (str(param1),str(param2)) def fetch(key,val_function,**kwargs) val = cache.get(key) if not val: val = val_function(**kwargs) cache.set(key,val) return val and you would call it like this: fetch('key',get_value,param1='first',param2='second') A: Julian's code is quite good but doesn't take positional args (when you want to use sorted() for example). Here's my fix: def get_value(param1,param2): return "value %s - %s " % (str(param1),str(param2)) def fetch(key,val_function, *args, **kwargs) val = cache.get(key) if not val: val = val_function(*args, **kwargs) cache.set(key,val) return val A: Well to get a default value if the key does not exits you can provide a second parameter: cache.get('key', 'default') cache.get() can take a default argument. This specifies which value to return if the object doesn't exist in the cache. To save the default value in cache if the key does not exist, you can provide your custom cache backend. E.g. this extends the db cache backend (but works the same with others): from django.core.cache.backends import db class CustomCache(db.CacheClass): def get(self, key, default=None): result = super(CustomCache, self).get(key, default) if result == default: self.add(key, default) return default return result But I don't think that this adds any value. Update: In response to the comment on the other post: Yes it compares the default value with the returned value and if both are equal, the value gets added to the cache. But cache.add only sets the new value if the key is not already in the cache (contrast to cache.set which always overrides): To add a key only if it doesn't already exist, use the add() method. It takes the same parameters as set(), but it will not attempt to update the cache if the key specified is already present.
cache.fetch in Django?
Does Django caching have a method similar to Rails' cache.fetch? (http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#M001023) The rails cache fetch works like: cache.fetch("my_key") { // return what I want to put in my_key if it is empty "some_value" } It's useful because it checks the cache, and returns the value of the cache if it is there. If not, it will store "some_value" in the cache, and then return "some_value". Is there an equivalent of this in Django? If not, what would the Python syntax for this look like if I were to implement such a function?
[ "I think the code you would have to write would be like this: (EDIT)\ndef get_value(param1,param2):\n return \"value %s - %s \" % (str(param1),str(param2))\n\ndef fetch(key,val_function,**kwargs)\n val = cache.get(key)\n if not val:\n val = val_function(**kwargs)\n cache.set(key,val)\n return val\n\nand you would call it like this:\nfetch('key',get_value,param1='first',param2='second')\n\n", "Julian's code is quite good but doesn't take positional args (when you want to use sorted() for example). Here's my fix:\ndef get_value(param1,param2):\n return \"value %s - %s \" % (str(param1),str(param2))\n\ndef fetch(key,val_function, *args, **kwargs)\n val = cache.get(key)\n if not val:\n val = val_function(*args, **kwargs)\n cache.set(key,val)\n return val\n\n", "Well to get a default value if the key does not exits you can provide a second parameter:\ncache.get('key', 'default')\n\n\ncache.get() can take a default argument. This specifies which value to return if the object doesn't exist in the cache.\n\nTo save the default value in cache if the key does not exist, you can provide your custom cache backend. E.g. this extends the db cache backend (but works the same with others):\nfrom django.core.cache.backends import db\n\nclass CustomCache(db.CacheClass):\n\n def get(self, key, default=None):\n result = super(CustomCache, self).get(key, default)\n\n if result == default:\n self.add(key, default)\n return default\n\n return result\n\nBut I don't think that this adds any value.\nUpdate:\nIn response to the comment on the other post: Yes it compares the default value with the returned value and if both are equal, the value gets added to the cache. But cache.add only sets the new value if the key is not already in the cache (contrast to cache.set which always overrides):\n\nTo add a key only if it doesn't already exist, use the add() method. It takes the same parameters as set(), but it will not attempt to update the cache if the key specified is already present.\n\n" ]
[ 4, 2, 0 ]
[]
[]
[ "caching", "django", "fetch", "python", "ruby_on_rails" ]
stackoverflow_0002214330_caching_django_fetch_python_ruby_on_rails.txt
Q: Beginner having a problem with classes I'm working through O'Reilly's "Learning Python" and having a problem with classes. I think I understand the concept, but in practice have stumbled upon this problem. Fron page 88-89: >>> class Worker: def __innit__(self, name, pay): self.name=name self.pay=pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay*=(1.0+percent) Then the book says "Calling the class like a function generates instances of a new type ...etc" and gives this example. bob = Worker('Bob Smith', 50000) This gives me this error: TypeError: this constructor takes no arguments. And then I start muttering profanities. So what am I doing wrong here? Thanks for the help. A: David, you've mis-typed __init__ The correct spelling is this: def __init__(self, name, pay): self.name=name self.pay=pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay*=(1.0+percent) A: One misspelling: it's __init__, not __innit__ -- just one n. You also have some indentation problems but I think those may be due to just copy-and-paste issues, or else you'd be getting SyntaxErrors before the TypeError you relate;-). So your code should probably be: class Worker(object): def __init__(self, name, pay): self.name=name self.pay=pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay*=(1.0+percent) I've also added the (object) to class Worker -- in Python 3.* it doesn't matter, but in 2.* it does (and even in 3.* it doesn't hurt, anyway;-). This makes the class "new style", which doesn't matter at very elementary levels but will as soon as you start wanting to do anything "cool and interesting" such as adding properties;-). A: You wrote __innit__ instead of __init__. In this way, you declared just another method in the class, not the special method called the constructor, which is by definition named __init__. This causes Python to generate a default constructor taking no arguments, hence the error message.
Beginner having a problem with classes
I'm working through O'Reilly's "Learning Python" and having a problem with classes. I think I understand the concept, but in practice have stumbled upon this problem. Fron page 88-89: >>> class Worker: def __innit__(self, name, pay): self.name=name self.pay=pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay*=(1.0+percent) Then the book says "Calling the class like a function generates instances of a new type ...etc" and gives this example. bob = Worker('Bob Smith', 50000) This gives me this error: TypeError: this constructor takes no arguments. And then I start muttering profanities. So what am I doing wrong here? Thanks for the help.
[ "David, you've mis-typed __init__\nThe correct spelling is this:\ndef __init__(self, name, pay):\n self.name=name\n self.pay=pay\ndef lastName(self):\n return self.name.split()[-1]\ndef giveRaise(self, percent):\n self.pay*=(1.0+percent)\n\n", "One misspelling: it's __init__, not __innit__ -- just one n.\nYou also have some indentation problems but I think those may be due to just copy-and-paste issues, or else you'd be getting SyntaxErrors before the TypeError you relate;-).\nSo your code should probably be:\nclass Worker(object):\n def __init__(self, name, pay):\n self.name=name\n self.pay=pay\n def lastName(self):\n return self.name.split()[-1]\n def giveRaise(self, percent):\n self.pay*=(1.0+percent)\n\nI've also added the (object) to class Worker -- in Python 3.* it doesn't matter, but in 2.* it does (and even in 3.* it doesn't hurt, anyway;-). This makes the class \"new style\", which doesn't matter at very elementary levels but will as soon as you start wanting to do anything \"cool and interesting\" such as adding properties;-).\n", "You wrote __innit__ instead of __init__.\nIn this way, you declared just another method in the class, not the special method called the constructor, which is by definition named __init__. This causes Python to generate a default constructor taking no arguments, hence the error message.\n" ]
[ 8, 5, 2 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002560997_class_python.txt
Q: How should I use try...except while defining a function? I find I've been confused by the problem that when I needn't to use try..except.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example: class mongodb(object): def getRecords(self,tname,conditions=''): try: col = eval("self.db.%s" %tname) recs = col.find(condition) return recs except Exception,e: #here make some error log with e.message What I thought is ,exceptions may be raised everywhere and I have to use try to get them. And my question is,is it a good practice to use it everywhere when defining functions?If not are there any principles for it?Help would be appreciated! Regards A: This (catching all possible exceptions very broadly) is indeed considered bad practice. You'll mask the real reason for the exception. Catch only 'explicitely named' types of exceptions (which you expect to happen and you can/will handle gracefully). Let the rest (unexpected ones) bubble as they should. You can log these (uncaught) exceptions (globally) by overriding sys.excepthook: import sys import traceback # ... def my_uncaught_exception_hook(exc_type, exc_value, exc_traceback): msg_exc = "".join( \ traceback.format_exception(exc_type, exc_value, exc_traceback) ) # ... log here... sys.excepthook = my_uncaught_exception_hook # our uncaught exception hook A: That may not be the best thing to do. Whole point of exceptions is that you can catch them on very different level than it's raised. It's best to handle them in the place where you have enough information to make something useful with them (that is very application and context dependent). For example code below can throw IOError("[Errno 2] No such file or directory"): def read_data(filename): return open(filename).read() In that function you don't have enough information to do something with it, but in place where you actually using this function, in case of such exception, you may decide to try different filename or display error to the user, or something else: try: data = read_data('data-file.txt') except IOError: data = read_data('another-data-file.txt') # or show_error_message("Data file was not found.") # or something else A: You must find a balance between several goals: An application should recover from as many errors as possible by itself. An application should report all unrecoverable errors with enough detail to fix the cause of the problem. Errors can happen everywhere but you don't want to pollute your code with all the error handling code. Applications shouldn't crash To solve #3, you can use an exception hook. All unhandled exceptions will cause the current transaction to abort. Catch them at the highest level, roll back the transaction (so the database doesn't become inconsistent) and either throw them again or swallow them (so the app doesn't crash). You should use decorators for this. This solves #4 and #1. The solution for #2 is experience. You will learn with time what information you need to solve problems. The hard part is to still have the information when an error happens. One solution is to add debug logging calls in the low level methods. Another solution is a dictionary per thread in which you can store some bits and which you dump when an error happens. A: another option is to wrap a large section of code in a try: except: (for instance in a web application, one specific GUI page) and then use sys.exc_info() to print out the error and also the stack where it occurred import sys import traceback try: #some buggy code x = ?? except: print sys.exc_info()[0] #prints the exception class print sys.exc_info()[1] #prints the error message print repr(traceback.format_tb(sys.exc_info()[2])) #prints the stack
How should I use try...except while defining a function?
I find I've been confused by the problem that when I needn't to use try..except.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example: class mongodb(object): def getRecords(self,tname,conditions=''): try: col = eval("self.db.%s" %tname) recs = col.find(condition) return recs except Exception,e: #here make some error log with e.message What I thought is ,exceptions may be raised everywhere and I have to use try to get them. And my question is,is it a good practice to use it everywhere when defining functions?If not are there any principles for it?Help would be appreciated! Regards
[ "This (catching all possible exceptions very broadly) is indeed considered bad practice. You'll mask the real reason for the exception.\nCatch only 'explicitely named' types of exceptions (which you expect to happen and you can/will handle gracefully). Let the rest (unexpected ones) bubble as they should.\nYou can log these (uncaught) exceptions (globally) by overriding sys.excepthook:\nimport sys\nimport traceback\n# ...\n\ndef my_uncaught_exception_hook(exc_type, exc_value, exc_traceback):\n msg_exc = \"\".join( \\\n traceback.format_exception(exc_type, exc_value, exc_traceback) )\n # ... log here...\n\nsys.excepthook = my_uncaught_exception_hook # our uncaught exception hook\n\n", "That may not be the best thing to do. Whole point of exceptions is that you can catch them on very different level than it's raised. It's best to handle them in the place where you have enough information to make something useful with them (that is very application and context dependent).\nFor example code below can throw IOError(\"[Errno 2] No such file or directory\"):\ndef read_data(filename):\n return open(filename).read()\n\nIn that function you don't have enough information to do something with it, but in place where you actually using this function, in case of such exception, you may decide to try different filename or display error to the user, or something else:\ntry:\n data = read_data('data-file.txt')\nexcept IOError:\n data = read_data('another-data-file.txt')\n # or\n show_error_message(\"Data file was not found.\")\n # or something else\n\n", "You must find a balance between several goals:\n\nAn application should recover from as many errors as possible by itself.\nAn application should report all unrecoverable errors with enough detail to fix the cause of the problem.\nErrors can happen everywhere but you don't want to pollute your code with all the error handling code.\nApplications shouldn't crash\n\nTo solve #3, you can use an exception hook. All unhandled exceptions will cause the current transaction to abort. Catch them at the highest level, roll back the transaction (so the database doesn't become inconsistent) and either throw them again or swallow them (so the app doesn't crash). You should use decorators for this. This solves #4 and #1.\nThe solution for #2 is experience. You will learn with time what information you need to solve problems. The hard part is to still have the information when an error happens. One solution is to add debug logging calls in the low level methods.\nAnother solution is a dictionary per thread in which you can store some bits and which you dump when an error happens.\n", "another option is to wrap a large section of code in a try: except: (for instance in a web application, one specific GUI page) and then use sys.exc_info() to print out the error and also the stack where it occurred\nimport sys\nimport traceback\ntry:\n #some buggy code \n x = ??\nexcept:\n print sys.exc_info()[0] #prints the exception class\n print sys.exc_info()[1] #prints the error message\n print repr(traceback.format_tb(sys.exc_info()[2])) #prints the stack\n\n" ]
[ 5, 5, 4, 1 ]
[]
[]
[ "exception", "function", "python" ]
stackoverflow_0002560137_exception_function_python.txt
Q: Google Books API - How do I separate Book from Book Edition? I'm using Google Book Search API to add missings bits and pieces to my database. Problem is that The API gives me back a list of book editions, and not reference to the original book itself. The data I'm trying to get is this: Original title: The Hobbit Original year of publication: 1937 Can anyone help? Just in case anyone asks: I'm developing this in Python. A: Try with this snippet: entry = self.service.get_by_google_id("XV0NAQAAIAAJ") print entry.dc_title[0].text print entry.date.text Result is: The hobbit 1937
Google Books API - How do I separate Book from Book Edition?
I'm using Google Book Search API to add missings bits and pieces to my database. Problem is that The API gives me back a list of book editions, and not reference to the original book itself. The data I'm trying to get is this: Original title: The Hobbit Original year of publication: 1937 Can anyone help? Just in case anyone asks: I'm developing this in Python.
[ "Try with this snippet:\nentry = self.service.get_by_google_id(\"XV0NAQAAIAAJ\")\nprint entry.dc_title[0].text\nprint entry.date.text\n\nResult is:\nThe hobbit\n1937\n" ]
[ 1 ]
[]
[]
[ "google_api", "python" ]
stackoverflow_0002299589_google_api_python.txt
Q: A Question about using jython when run a receving socket in python I have not a lot of knowledge of python and network programming. Currently I am trying to implement a simple application which can receive a text message sent by the user, fetch some information from the google search api, and return the results via text message to the user. This application will continue to listening to the users messages and reply immediately. How I get the text short message sent by the user? It's a program named fetion from the mobile supplier in China. The client side fetion, just like a instant communication tool, can send/receive messages to/from other people who are using mobile to receive/send SMS. I am using a open source python program that simulates the fetion program. So basically I can use this python program to communate with others who using cell phone via SMS. My core program is based on java, so I need to take this python program into java environment. I am using jython, and now I am available to send messages to users by some lines of java codes. But the real question is the process of receving from users via SMS. In python code, a new thread is created to continuously listen to the user. It should be OK in Python, but when I run the similar process in Jython, the following exception occurs: Exception in thread Thread:Traceback (most recent call last): File "D:\jython2.5.1\Lib\threading.py", line 178, in _Thread__bootstrap self.run() File "<iostream>", line 1389, in run File "<iostream>", line 1207, in receive File "<iostream>", line 1207, in receive File "<iostream>", line 150, in recv File "D:\jython2.5.1\Lib\select.py", line 223, in native_select pobj.register(fd, POLLIN) File "D:\jython2.5.1\Lib\select.py", line 104, in register raise _map_exception(jlx) error: (20000, 'socket must be in non-blocking mode') The line 150 in the python code is as follows: def recv(self,timeout=False): if self.login_type == "HTTP": time.sleep(10) return self.get_offline_msg() pass else: if timeout: infd,outfd,errfd = select([self.__sock,],[],[],timeout)//<---line 150 here else: infd,outfd,errfd = select([self.__sock,],[],[]) if len(infd) != 0: ret = self.__tcp_recv() num = len(ret) d_print(('num',),locals()) if num == 0: return ret if num == 1: return ret[0] for r in ret: self.queue.put(r) d_print(('r',),locals()) if not self.queue.empty(): return self.queue.get() else: return "TimeOut" Because of I am not very familiar with python, especially the socket part, and also new in Jython use, I really need your help or only advice or explanation. Thank you very much! A: As stated on the jython select documentaion page, only sockets in non-blocking mode can be multiplexed on jython, in contrast to cpython, where sockets can be either blocking or non-blocking. http://wiki.python.org/jython/SelectModule#Onlysocketsinnon-blockingmodecanbemultiplexed This is a limitation of Java that jython can do nothing to change. There is a special function in the jython select module for this exact situation, the cpython_compatible_select function. You don't show the import of the select module in your code above, but based on what I see, you must be doing an import like this from select import select If you replace that import with this from select import cpython_compatible_select as select Then everything should work fine. Lastly, please make sure to read the "Warnings" section on the select module documentation page. A: The error states that you have tried to call select on a socket that is set (by default) to block waiting for input. The portable way to make it non-blocking is to find where self.__sock is created and call socket.setblocking(0) on it. You could call - in principle - setblocking in recv prior to the select call but it would be confusing to the reader. As these are direct calls to the low-level socket routines, this isn't strictly a Python question but one about the operation of the socket system call as appropriate for your platform.
A Question about using jython when run a receving socket in python
I have not a lot of knowledge of python and network programming. Currently I am trying to implement a simple application which can receive a text message sent by the user, fetch some information from the google search api, and return the results via text message to the user. This application will continue to listening to the users messages and reply immediately. How I get the text short message sent by the user? It's a program named fetion from the mobile supplier in China. The client side fetion, just like a instant communication tool, can send/receive messages to/from other people who are using mobile to receive/send SMS. I am using a open source python program that simulates the fetion program. So basically I can use this python program to communate with others who using cell phone via SMS. My core program is based on java, so I need to take this python program into java environment. I am using jython, and now I am available to send messages to users by some lines of java codes. But the real question is the process of receving from users via SMS. In python code, a new thread is created to continuously listen to the user. It should be OK in Python, but when I run the similar process in Jython, the following exception occurs: Exception in thread Thread:Traceback (most recent call last): File "D:\jython2.5.1\Lib\threading.py", line 178, in _Thread__bootstrap self.run() File "<iostream>", line 1389, in run File "<iostream>", line 1207, in receive File "<iostream>", line 1207, in receive File "<iostream>", line 150, in recv File "D:\jython2.5.1\Lib\select.py", line 223, in native_select pobj.register(fd, POLLIN) File "D:\jython2.5.1\Lib\select.py", line 104, in register raise _map_exception(jlx) error: (20000, 'socket must be in non-blocking mode') The line 150 in the python code is as follows: def recv(self,timeout=False): if self.login_type == "HTTP": time.sleep(10) return self.get_offline_msg() pass else: if timeout: infd,outfd,errfd = select([self.__sock,],[],[],timeout)//<---line 150 here else: infd,outfd,errfd = select([self.__sock,],[],[]) if len(infd) != 0: ret = self.__tcp_recv() num = len(ret) d_print(('num',),locals()) if num == 0: return ret if num == 1: return ret[0] for r in ret: self.queue.put(r) d_print(('r',),locals()) if not self.queue.empty(): return self.queue.get() else: return "TimeOut" Because of I am not very familiar with python, especially the socket part, and also new in Jython use, I really need your help or only advice or explanation. Thank you very much!
[ "As stated on the jython select documentaion page, only sockets in non-blocking mode can be multiplexed on jython, in contrast to cpython, where sockets can be either blocking or non-blocking.\nhttp://wiki.python.org/jython/SelectModule#Onlysocketsinnon-blockingmodecanbemultiplexed\nThis is a limitation of Java that jython can do nothing to change.\nThere is a special function in the jython select module for this exact situation, the cpython_compatible_select function.\nYou don't show the import of the select module in your code above, but based on what I see, you must be doing an import like this\nfrom select import select\nIf you replace that import with this\nfrom select import cpython_compatible_select as select\nThen everything should work fine.\nLastly, please make sure to read the \"Warnings\" section on the select module documentation page.\n", "The error states that you have tried to call select on a socket that is set (by default) to block waiting for input. The portable way to make it non-blocking is to find where self.__sock is created and call socket.setblocking(0) on it.\nYou could call - in principle - setblocking in recv prior to the select call but it would be confusing to the reader. As these are direct calls to the low-level socket routines, this isn't strictly a Python question but one about the operation of the socket system call as appropriate for your platform.\n" ]
[ 2, 1 ]
[]
[]
[ "jython", "nonblocking", "python", "sockets" ]
stackoverflow_0002532943_jython_nonblocking_python_sockets.txt
Q: Problem with python class Hi I am new to Python and as a part of my assignment I have written the following class import nltk.stem.api class BanglaStemmer(nltk.stem.api.StemmerI): suffixList = ['\xef\xbb\xbf\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa7\x87\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x8b\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa7\x87\n', '\xe0\xa7\x87\xe0\xa6\x9b\n', '\xe0\xa6\xa4\xe0\xa7\x87\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa7\x87\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa6\x9b\xe0\xa6\xbf\n', '\xe0\xa6\x9b\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\x9b\n', '\xe0\xa6\xa4\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa6\xa4\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xa4\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xac\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa7\x81\xe0\xa6\xa8\n', '\xe0\xa7\x81\xe0\xa6\x95\n', '\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa6\xac\xe0\xa7\x87\n', '\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa6\xac\xe0\xa6\xbf\n', '\xe0\xa6\xa4\xe0\xa6\xbf\n', '\xe0\xa6\xb2\n', '\xe0\xa6\xa4\n', '\xe0\xa7\x8b\n', '\xe0\xa6\xbf\n', '\xe0\xa7\x87\n', '\xe0\xa7\x8d\n', '\xe0\xa6\x87\n', '\xe0\xa6\xac\n', '\xe0\xa6\xb8\n', '\xe0\xa6\xa8\n', '\xe0\xa6\x95\n', '\xe0\xa6\x93\n', '\xe0\xa7\x9f\n'] def stem(self,token): for suffix in suffixList: if token.endswith(suffix): return token[:-len(suffix)] return token The problem is that when I try to compile run it by creating an instance and calling the stem() function with a parameter , it says that the suffixList is not defined. Couldn't figure out what's the problem. Is there a different way in which the class variables have to be declared ? please help A: for suffix in suffixList: should be for suffix in self.suffixList: Unlike a lot of OOP languages, Python requires you to qualify class members inside the class methods. A: You can use BanglaStemmer.suffixList or self.suffixList to access the variable. Plain suffixList would only work on a local (defined in the function) or a global (defined in the module) variable. A: In Python, unlike most other languages, you always have to explicitely reference the instance of which you want to access a member (or "attribute" in Python). This instance is always passed as the first parameter to your methods; this is the reason why this first parameter is called self by convention. suffixList in your case is a class attribute, i.e. it is shared by all instances of the class (unless redefined). So you access it with self.suffixList.
Problem with python class
Hi I am new to Python and as a part of my assignment I have written the following class import nltk.stem.api class BanglaStemmer(nltk.stem.api.StemmerI): suffixList = ['\xef\xbb\xbf\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa7\x87\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x8b\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\n', '\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa7\x87\n', '\xe0\xa7\x87\xe0\xa6\x9b\n', '\xe0\xa6\xa4\xe0\xa7\x87\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa6\xbf\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\xe0\xa7\x87\n', '\xe0\xa6\x9a\xe0\xa7\x8d\xe0\xa6\x9b\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\n', '\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa6\x9b\xe0\xa6\xbf\n', '\xe0\xa6\x9b\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\x9b\n', '\xe0\xa6\xa4\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa6\xa4\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xb2\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xa4\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xac\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa7\x87\xe0\xa6\xa8\n', '\xe0\xa6\xbf\xe0\xa6\xb8\n', '\xe0\xa7\x81\xe0\xa6\xa8\n', '\xe0\xa7\x81\xe0\xa6\x95\n', '\xe0\xa6\xb2\xe0\xa7\x87\n', '\xe0\xa6\xac\xe0\xa7\x87\n', '\xe0\xa6\xb2\xe0\xa6\xbf\n', '\xe0\xa6\xac\xe0\xa6\xbf\n', '\xe0\xa6\xa4\xe0\xa6\xbf\n', '\xe0\xa6\xb2\n', '\xe0\xa6\xa4\n', '\xe0\xa7\x8b\n', '\xe0\xa6\xbf\n', '\xe0\xa7\x87\n', '\xe0\xa7\x8d\n', '\xe0\xa6\x87\n', '\xe0\xa6\xac\n', '\xe0\xa6\xb8\n', '\xe0\xa6\xa8\n', '\xe0\xa6\x95\n', '\xe0\xa6\x93\n', '\xe0\xa7\x9f\n'] def stem(self,token): for suffix in suffixList: if token.endswith(suffix): return token[:-len(suffix)] return token The problem is that when I try to compile run it by creating an instance and calling the stem() function with a parameter , it says that the suffixList is not defined. Couldn't figure out what's the problem. Is there a different way in which the class variables have to be declared ? please help
[ "for suffix in suffixList:\n\nshould be\nfor suffix in self.suffixList:\n\nUnlike a lot of OOP languages, Python requires you to qualify class members inside the class methods.\n", "You can use BanglaStemmer.suffixList or self.suffixList to access the variable. Plain suffixList would only work on a local (defined in the function) or a global (defined in the module) variable.\n", "In Python, unlike most other languages, you always have to explicitely reference the instance of which you want to access a member (or \"attribute\" in Python). This instance is always passed as the first parameter to your methods; this is the reason why this first parameter is called self by convention.\nsuffixList in your case is a class attribute, i.e. it is shared by all instances of the class (unless redefined). So you access it with self.suffixList.\n" ]
[ 6, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002561469_python.txt
Q: Once I know the basic elements and syntax of Python, what should I do? Well, I have read several user guides and watched dozens and dozens of video tutorials on how to program with Python, and feel pretty confident about writing simple applications for it. My main point in my question is, where would I be able to learn more advanced programming knowledge about Python? A: How simple of applications are you making? Have you gone through the exercises in Google's Python Class? I highly recommend going through those. If you really know what you are doing, you should breeze through them. If not, then you'll be learning some valuable skills and becoming a little more experienced in Python. After that, it depends on what your end goals are with Python. If you don't have any goals then you should work on setting some goals and making some small applications to develop your skills in the areas that go well with those goals. Also, a good way to learn more about Python is to try to answer the questions posted on here about Python. Even if you don't find the best answer, reading other people's answers will help you as well as the process of trying to find the answer. A: You could try something like Python Cookbook or Python Challenge. But your question is a little too vague. Why did you learn Python? What kind of problems are you looking at solving? Based on the answer to that, I can direct you to various modules like os, sys, Tkinter, etc A: You have given yourself an answer: and feel pretty confident about writing simple applications for it go ahead and write more complex applications! The issue here is that you do not feel challenged, and you assume that you are done with your basic learning. Just find what to do! Simplify a process (say, file management), retrieve data from Internet (say, the last 25 twitter posts about Python), consolidate your mail clients into a single command line application, etc. The MOST productive thing you could do (assuming you really don't have problems of your own), is to find an open source Python project (say, Matplotlib) and become a contributor. You will quickly realize that Python is beautiful, but it is a beast nevertheless. If you still feel unchallenged, contact me and I will send you a ton of stuff to code which, believe me, is not easy. Good luck! A: my favorite way in learning python is ( learning through projects ). put yourself a goal , like a software for example ( 6 years ago when i started to learn python i picked a messenger . so i had to read more about sockets, network programming , and interfaces libraries ) . start with it , look for examples and resources to learn more . then do it. the key is NOT TO GIVE UP and keep trying and searching until you make it . . this can be fastest and the most efficient way in learning any programming language . good luck ;) A: If you like puzzles, you might check out Project Euler. It has a variety of interesting puzzles (some easy, some much harder) that take some logic and programming to solve. (Often you have to find a clever way to solve them, since brute-force methods will take forever.) If you're at all interested in web development you might look into Django. It's a very nice web framework that lets you use Python; it's mature and quite powerful. I also second Arrieta's suggestion of finding an open-source Python project and looking into getting involved. You can find a list of such projects on GitHub, freshmeat, and SourceForge, among others.
Once I know the basic elements and syntax of Python, what should I do?
Well, I have read several user guides and watched dozens and dozens of video tutorials on how to program with Python, and feel pretty confident about writing simple applications for it. My main point in my question is, where would I be able to learn more advanced programming knowledge about Python?
[ "How simple of applications are you making? Have you gone through the exercises in Google's Python Class? I highly recommend going through those. If you really know what you are doing, you should breeze through them. If not, then you'll be learning some valuable skills and becoming a little more experienced in Python. \nAfter that, it depends on what your end goals are with Python. If you don't have any goals then you should work on setting some goals and making some small applications to develop your skills in the areas that go well with those goals. \nAlso, a good way to learn more about Python is to try to answer the questions posted on here about Python. Even if you don't find the best answer, reading other people's answers will help you as well as the process of trying to find the answer.\n", "You could try something like Python Cookbook or Python Challenge.\nBut your question is a little too vague. Why did you learn Python? What kind of problems are you looking at solving? Based on the answer to that, I can direct you to various modules like os, sys, Tkinter, etc\n", "You have given yourself an answer:\n\nand feel pretty confident about\n writing simple applications for it\n\ngo ahead and write more complex applications! \nThe issue here is that you do not feel challenged, and you assume that you are done with your basic learning. Just find what to do! Simplify a process (say, file management), retrieve data from Internet (say, the last 25 twitter posts about Python), consolidate your mail clients into a single command line application, etc.\nThe MOST productive thing you could do (assuming you really don't have problems of your own), is to find an open source Python project (say, Matplotlib) and become a contributor. You will quickly realize that Python is beautiful, but it is a beast nevertheless.\nIf you still feel unchallenged, contact me and I will send you a ton of stuff to code which, believe me, is not easy.\nGood luck!\n", "my favorite way in learning python is ( learning through projects ). \nput yourself a goal , like a software for example ( 6 years ago when i started to learn python i picked a messenger . so i had to read more about sockets, network programming , and interfaces libraries ) . start with it , look for examples and resources to learn more . then do it.\nthe key is NOT TO GIVE UP and keep trying and searching until you make it . \n. this can be fastest and the most efficient way in learning any programming language .\ngood luck ;)\n", "If you like puzzles, you might check out Project Euler. It has a variety of interesting puzzles (some easy, some much harder) that take some logic and programming to solve. (Often you have to find a clever way to solve them, since brute-force methods will take forever.)\nIf you're at all interested in web development you might look into Django. It's a very nice web framework that lets you use Python; it's mature and quite powerful.\nI also second Arrieta's suggestion of finding an open-source Python project and looking into getting involved. You can find a list of such projects on GitHub, freshmeat, and SourceForge, among others.\n" ]
[ 3, 2, 2, 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002513260_python_wxpython.txt
Q: How do I define a SWIG typemap for a reference to pointer? I have a Publisher class written in C++ with the following two methods: PublishField(char* name, double* address); GetFieldReference(char* name, double*& address); Python bindings for this class are being generated using SWIG. In my swig .i file I have the following: %pointer_class(double*, ptrDouble); This lets me publish a field that is defined in a Python variable: value = ptrDouble() value.assign(10.0) PublishField("value", value.cast()) Trying to using the GetFieldReference method results in a TypeError however: GetFieldReference("value", newValue) I think I need to create a typemap for the double*& that returns a ptrDouble, but I am not quite sure what that would look like. A: Here is a working solution that I came up with. Add a wrapper function to the swig.i file: %inline %{ double * GetReference(char* name, Publisher* publisher) { double* ptr = new double; publisher->GetFieldReference(name, ptr); return ptr; } %} Now from Python I can use the following: value = ptrDouble.frompointer(GetFieldReference("value", publisher) A: This typemap should solve the problem - // Typemaps for double *& %typemap(in) double *& (double *ppDouble = NULL) %{ $1 = &ppDouble ; %} %typemap(argout) double *& { *(double **)&jarg2 = *$1; } %typemap(javain) double *& "$javainput" You may need to check if assigning jarg2 (in 'argout' typemap) with required double value is correct or jarg1 should be assigned rather.
How do I define a SWIG typemap for a reference to pointer?
I have a Publisher class written in C++ with the following two methods: PublishField(char* name, double* address); GetFieldReference(char* name, double*& address); Python bindings for this class are being generated using SWIG. In my swig .i file I have the following: %pointer_class(double*, ptrDouble); This lets me publish a field that is defined in a Python variable: value = ptrDouble() value.assign(10.0) PublishField("value", value.cast()) Trying to using the GetFieldReference method results in a TypeError however: GetFieldReference("value", newValue) I think I need to create a typemap for the double*& that returns a ptrDouble, but I am not quite sure what that would look like.
[ "Here is a working solution that I came up with.\nAdd a wrapper function to the swig.i file:\n%inline %{\n double * GetReference(char* name, Publisher* publisher)\n {\n double* ptr = new double;\n publisher->GetFieldReference(name, ptr);\n return ptr;\n }\n%}\n\nNow from Python I can use the following:\nvalue = ptrDouble.frompointer(GetFieldReference(\"value\", publisher)\n\n", "This typemap should solve the problem - \n// Typemaps for double *&\n%typemap(in) double *& (double *ppDouble = NULL) %{\n$1 = &ppDouble ;\n%}\n\n%typemap(argout) double *& {\n*(double **)&jarg2 = *$1;\n}\n\n%typemap(javain) double *& \"$javainput\"\n\nYou may need to check if assigning jarg2 (in 'argout' typemap) with required double value is correct or jarg1 should be assigned rather.\n" ]
[ 1, 0 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0001499569_c++_python_swig.txt
Q: Querying many to many fields in django In the models there is a many to many fields as, from emp.models import Name def info(request): name = models.ManyToManyField(Name) And in emp.models the schema is as class Name(models.Model): name = models.CharField(max_length=512) def __unicode__(self): return self.name Now when i want to query a particular id say for ex: info= info.objects.filter(id=a) for i in info: logging.debug(i.name) //gives an error how should the query be to get the name Thanks.. A: info.name is ManyToManyField so if you want all Name objects associated with it you have to use .all() method on it. Only then you'll get list (queryset) of Name objects: info_list = info.objects.filter(id=a) for info_object in info_list: for name_object in info_object.name.all(): print name_object.name A: Lukasz is right, but just so you know, it doesn't make sense to filter on an id unless you use info.object.filet(id__in=a) and a is a list of some sort. If you filter on a single id, you should be using objects.get(**kwargs) first of all, and it will return that specific Info instance instead of a QuerySet.
Querying many to many fields in django
In the models there is a many to many fields as, from emp.models import Name def info(request): name = models.ManyToManyField(Name) And in emp.models the schema is as class Name(models.Model): name = models.CharField(max_length=512) def __unicode__(self): return self.name Now when i want to query a particular id say for ex: info= info.objects.filter(id=a) for i in info: logging.debug(i.name) //gives an error how should the query be to get the name Thanks..
[ "info.name is ManyToManyField so if you want all Name objects associated with it you have to use .all() method on it. Only then you'll get list (queryset) of Name objects:\ninfo_list = info.objects.filter(id=a)\nfor info_object in info_list:\n for name_object in info_object.name.all():\n print name_object.name\n\n", "Lukasz is right, but just so you know, it doesn't make sense to filter on an id unless you use info.object.filet(id__in=a) and a is a list of some sort. If you filter on a single id, you should be using objects.get(**kwargs) first of all, and it will return that specific Info instance instead of a QuerySet.\n" ]
[ 3, 1 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0002559909_django_django_models_django_views_python.txt
Q: Python - Execute Process -> Block till it exits & Suppress Output I'm using the following to execute a process and hide its output from Python. It's in a loop though, and I need a way to block until the sub process has terminated before moving to the next iteration. subprocess.Popen(["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) A: Use subprocess.call(). From the docs: subprocess.call(*popenargs, **kwargs) Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Edit: subprocess.call() uses wait(), and wait() is vulnerable to deadlocks (as Tommy Herbert pointed out). From the docs: Warning: This will deadlock if the child process generates enough output to a stdout or stderr pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that. So if your command generates a lot of output, use communicate() instead: p = subprocess.Popen( ["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() A: If you don't need output at all you can pass devnull to stdout and stderr. I don't know if this can make a difference but pass a bufsize. Using devnull now subprocess.call doesn't suffer of deadlock anymore import os import subprocess null = open(os.devnull, 'w') subprocess.call(['ls', '-lR'], bufsize=4096, stdout=null, stderr=null)
Python - Execute Process -> Block till it exits & Suppress Output
I'm using the following to execute a process and hide its output from Python. It's in a loop though, and I need a way to block until the sub process has terminated before moving to the next iteration. subprocess.Popen(["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
[ "Use subprocess.call(). From the docs:\n\nsubprocess.call(*popenargs, **kwargs)\n Run command with arguments. Wait for command to complete, then\n return the returncode attribute.\n The arguments are the same as for the\n Popen constructor.\n\nEdit:\nsubprocess.call() uses wait(), and wait() is vulnerable to deadlocks (as Tommy Herbert pointed out). From the docs:\n\nWarning: This will deadlock if the\n child process generates enough output\n to a stdout or stderr pipe such that\n it blocks waiting for the OS pipe\n buffer to accept more data. Use\n communicate() to avoid that.\n\nSo if your command generates a lot of output, use communicate() instead:\np = subprocess.Popen(\n [\"scanx\", \"--udp\", host],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\nout, err = p.communicate()\n\n", "If you don't need output at all you can pass devnull to stdout and stderr. I don't know if this can make a difference but pass a bufsize. Using devnull now subprocess.call doesn't suffer of deadlock anymore\nimport os\nimport subprocess\n\nnull = open(os.devnull, 'w')\nsubprocess.call(['ls', '-lR'], bufsize=4096, stdout=null, stderr=null)\n\n" ]
[ 7, 7 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0002561902_python_subprocess.txt
Q: How to sort a list alphabetically and have additional lists sorted in the same order I have 3 lists, each with equal elements: email addresses, salaries and IDs I'd like to sort the email addresses alphabetically and in some way sort the other 2 lists (salaries and IDs). E.g., Emails: z@company.com a@company.com Salaries: 50000 60000 IDs: 2 1 The puzzle: I'd like to sort Emails such that a@c.com is first and z@c.com is last and Salaries is 60000 then 50000 and IDs is 1 then 2. Additional detail: 1. Length of lists are the same and can be longer than two elements. 2. I will subsequently pass IDs to functions to retrieve further lists. Those lists won't need sorting as they will adopt the order of the IDs list. A: Try: emails = ["z@c.com", "a@c.com"] salaries = [50, 60] ids = [2, 1] intermediate = zip(emails, salaries, ids) intermediate.sort() result = zip(*intermediate) A: This is essentially ebo's solution, made to a one-liner with the user of sorted() rather than list.sort, and multiple lvalues in the assignement to get the individual list (named as the original but with an s_ prefix) directly. >>> email = ['z@company.com', 'a@company.com'] >>> salaries = [50000, 60000] >>> ids = [2,1] >>> s_email, s_salaries, s_ids = zip(*sorted(zip(email, salaries, ids))) >>> s_email ('a@company.com', 'z@company.com') >>> s_salaries (60000, 50000) >>> s_ids (1, 2) >>> A: Assuming that each email ID is unique, then this will work: sortedEmails = emails[:] sortedEmails.sort() sortedSalaries = [] for email in sortedEmails: i = emails.index(email) sortedSalaries.append(salaries[i]) Hope that helps
How to sort a list alphabetically and have additional lists sorted in the same order
I have 3 lists, each with equal elements: email addresses, salaries and IDs I'd like to sort the email addresses alphabetically and in some way sort the other 2 lists (salaries and IDs). E.g., Emails: z@company.com a@company.com Salaries: 50000 60000 IDs: 2 1 The puzzle: I'd like to sort Emails such that a@c.com is first and z@c.com is last and Salaries is 60000 then 50000 and IDs is 1 then 2. Additional detail: 1. Length of lists are the same and can be longer than two elements. 2. I will subsequently pass IDs to functions to retrieve further lists. Those lists won't need sorting as they will adopt the order of the IDs list.
[ "Try:\nemails = [\"z@c.com\", \"a@c.com\"]\nsalaries = [50, 60]\nids = [2, 1]\n\nintermediate = zip(emails, salaries, ids)\nintermediate.sort()\n\nresult = zip(*intermediate)\n\n", "This is essentially ebo's solution, made to a one-liner with the user of sorted() rather than list.sort, and multiple lvalues in the assignement to get the individual list (named as the original but with an s_ prefix) directly.\n>>> email = ['z@company.com', 'a@company.com']\n>>> salaries = [50000, 60000]\n>>> ids = [2,1]\n\n>>> s_email, s_salaries, s_ids = zip(*sorted(zip(email, salaries, ids)))\n\n>>> s_email\n('a@company.com', 'z@company.com')\n>>> s_salaries\n(60000, 50000)\n>>> s_ids\n(1, 2)\n>>>\n\n", "Assuming that each email ID is unique, then this will work:\nsortedEmails = emails[:]\nsortedEmails.sort()\n\nsortedSalaries = []\nfor email in sortedEmails:\n i = emails.index(email)\n sortedSalaries.append(salaries[i])\n\nHope that helps\n" ]
[ 5, 3, 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0002562714_list_python_sorting.txt
Q: cannot append Model.objects.all() I cannot run ['abc'].append( MyModel.objects.all() ) since it generates exception 'NoneType' object is not iterable if MyModel has no entry. any workaround or something like ? : in c++ edit: my statement is actually ','.join([ str(e) for e in ['abc','def'].append( MyModel.objects.all() ) ]) it seems that the problem is caused by append() returning NoneType. I solved this by creating a variable to hold the list and then extend() it A: how about: ['abc'].append( MyModel.objects.all() or []) A: It might be best to be explicit rather than implicit (and avoid using the short circuit propoerties of or which can lead to errors: my_objects = MyModel.objects.all() if my_objects: [a,b,c].extend(my_objects) A: Model.objects.all() is a QuerySet and that is iterable (see the source). Passing an iterator to list.extend works just fine: The contents of the iterator is unrolled nicely onto the end of the list. NB: passing it to list.append puts the iterator object itself into the list, so most likely you want to extend(). A: None is returned from the append method, which takes place in place. In other words, your statement is equivalent to [str(e) for e in None] which naturally raises a NoneType exception. The solution is have a separate statement for the append or extend method, then follow blokeley's advice to be explicit. A: Shouldn't it be += instead of append?
cannot append Model.objects.all()
I cannot run ['abc'].append( MyModel.objects.all() ) since it generates exception 'NoneType' object is not iterable if MyModel has no entry. any workaround or something like ? : in c++ edit: my statement is actually ','.join([ str(e) for e in ['abc','def'].append( MyModel.objects.all() ) ]) it seems that the problem is caused by append() returning NoneType. I solved this by creating a variable to hold the list and then extend() it
[ "how about: \n['abc'].append( MyModel.objects.all() or [])\n\n", "It might be best to be explicit rather than implicit (and avoid using the short circuit propoerties of or which can lead to errors:\nmy_objects = MyModel.objects.all()\nif my_objects:\n [a,b,c].extend(my_objects)\n\n", "Model.objects.all() is a QuerySet and that is iterable (see the source). Passing an iterator to list.extend works just fine: The contents of the iterator is unrolled nicely onto the end of the list.\nNB: passing it to list.append puts the iterator object itself into the list, so most likely you want to extend().\n", "None is returned from the append method, which takes place in place. In other words, your statement is equivalent to \n[str(e) for e in None]\n\nwhich naturally raises a NoneType exception. The solution is have a separate statement for the append or extend method, then follow blokeley's advice to be explicit.\n", "Shouldn't it be += instead of append?\n" ]
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0002560178_django_django_models_django_queryset_python.txt
Q: How to implement simple sessions for Google App Engine? Here is a very basic class for handling sessions on App Engine: """Lightweight implementation of cookie-based sessions for Google App Engine. Classes: Session """ import os import random import Cookie from google.appengine.api import memcache _COOKIE_NAME = 'app-sid' _COOKIE_PATH = '/' _SESSION_EXPIRE_TIME = 180 * 60 class Session(object): """Cookie-based session implementation using Memcached.""" def __init__(self): self.sid = None self.key = None self.session = None cookie_str = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(cookie_str) if self.cookie.get(_COOKIE_NAME): self.sid = self.cookie[_COOKIE_NAME].value self.key = 'session-' + self.sid self.session = memcache.get(self.key) if self.session: self._update_memcache() else: self.sid = str(random.random())[5:] + str(random.random())[5:] self.key = 'session-' + self.sid self.session = dict() memcache.add(self.key, self.session, _SESSION_EXPIRE_TIME) self.cookie[_COOKIE_NAME] = self.sid self.cookie[_COOKIE_NAME]['path'] = _COOKIE_PATH print self.cookie def __len__(self): return len(self.session) def __getitem__(self, key): if key in self.session: return self.session[key] raise KeyError(str(key)) def __setitem__(self, key, value): self.session[key] = value self._update_memcache() def __delitem__(self, key): if key in self.session: del self.session[key] self._update_memcache() return None raise KeyError(str(key)) def __contains__(self, item): try: i = self.__getitem__(item) except KeyError: return False return True def _update_memcache(self): memcache.replace(self.key, self.session, _SESSION_EXPIRE_TIME) I would like some advices on how to improve the code for better security. Note: In the production version it will also save a copy of the session in the datastore. Note': I know there are much more complete implementations available online though I would like to learn more about this subject so please don't answer the question with "use that" or "use the other" library. A: Here is a suggestion for simplifying your implementation. You are creating a randomized temporary key that you use as the session's key in the memcache. You note that you will be storing the session in the datastore as well (where it will have another key). Why not randomize the session's datastore key, and then use that as the one and only key, for both the database and the memcache (if necessary)? Does this simplification introduce any new security issues? Here's some code for creating a randomized datastore key for the Session model: # Get a random integer to use as the session's datastore ID. # (So it can be stored in a cookie without being 'guessable'.) random.seed(); id = None; while None==id or Session.get_by_id( id ): id = random.randrange( sys.maxint ); seshKey = db.Key.from_path( 'Session', id ); session = Session( key = seshKey ); To get the ID from the session (i.e. to store in the cookie) use: sid = session.key().id(); To retrieve the session instance after the 'sid' has been read from the cookie: session = Session.get_by_id( sid ); A: Here are a couple of additional security measures you could add. First, I think it is pretty common to use information stored in the session instance to validate each new request. For example, you could verify that the IP address and user-agent don't change during a session: newip = str( request.remote_addr ); if sesh.ip_addr != newip: logging.warn( "Session IP has changed to %s." % newip); newua = rh.request.headers.get( 'User-Agent', None ); if sesh.agent != newua: logging.warn( "Session UA has changed to %s." % newua ); Also, perhaps it would be better to prevent the session from being renewed indefinitely? I think that sites such as Google will eventually ask you to sign-in again if you try to keep a session going for a long time. I guess it would be easy to slowly decrease the _SESSION_EXPIRE_TIME each time the session gets renewed, but that isn't really a very good solution. Ideally the choice of when to force the user to sign-in again would take into account the flow and security requirements of your site.
How to implement simple sessions for Google App Engine?
Here is a very basic class for handling sessions on App Engine: """Lightweight implementation of cookie-based sessions for Google App Engine. Classes: Session """ import os import random import Cookie from google.appengine.api import memcache _COOKIE_NAME = 'app-sid' _COOKIE_PATH = '/' _SESSION_EXPIRE_TIME = 180 * 60 class Session(object): """Cookie-based session implementation using Memcached.""" def __init__(self): self.sid = None self.key = None self.session = None cookie_str = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(cookie_str) if self.cookie.get(_COOKIE_NAME): self.sid = self.cookie[_COOKIE_NAME].value self.key = 'session-' + self.sid self.session = memcache.get(self.key) if self.session: self._update_memcache() else: self.sid = str(random.random())[5:] + str(random.random())[5:] self.key = 'session-' + self.sid self.session = dict() memcache.add(self.key, self.session, _SESSION_EXPIRE_TIME) self.cookie[_COOKIE_NAME] = self.sid self.cookie[_COOKIE_NAME]['path'] = _COOKIE_PATH print self.cookie def __len__(self): return len(self.session) def __getitem__(self, key): if key in self.session: return self.session[key] raise KeyError(str(key)) def __setitem__(self, key, value): self.session[key] = value self._update_memcache() def __delitem__(self, key): if key in self.session: del self.session[key] self._update_memcache() return None raise KeyError(str(key)) def __contains__(self, item): try: i = self.__getitem__(item) except KeyError: return False return True def _update_memcache(self): memcache.replace(self.key, self.session, _SESSION_EXPIRE_TIME) I would like some advices on how to improve the code for better security. Note: In the production version it will also save a copy of the session in the datastore. Note': I know there are much more complete implementations available online though I would like to learn more about this subject so please don't answer the question with "use that" or "use the other" library.
[ "Here is a suggestion for simplifying your implementation.\nYou are creating a randomized temporary key that you use as the session's key in the memcache. You note that you will be storing the session in the datastore as well (where it will have another key).\nWhy not randomize the session's datastore key, and then use that as the one and only key, for both the database and the memcache (if necessary)? Does this simplification introduce any new security issues?\nHere's some code for creating a randomized datastore key for the Session model:\n# Get a random integer to use as the session's datastore ID.\n# (So it can be stored in a cookie without being 'guessable'.)\nrandom.seed();\nid = None;\nwhile None==id or Session.get_by_id( id ):\n id = random.randrange( sys.maxint );\nseshKey = db.Key.from_path( 'Session', id ); \nsession = Session( key = seshKey );\n\nTo get the ID from the session (i.e. to store in the cookie) use:\nsid = session.key().id();\n\nTo retrieve the session instance after the 'sid' has been read from the cookie:\nsession = Session.get_by_id( sid );\n\n", "Here are a couple of additional security measures you could add.\nFirst, I think it is pretty common to use information stored in the session instance to validate each new request. For example, you could verify that the IP address and user-agent don't change during a session:\nnewip = str( request.remote_addr );\nif sesh.ip_addr != newip:\n logging.warn( \"Session IP has changed to %s.\" % newip);\nnewua = rh.request.headers.get( 'User-Agent', None );\nif sesh.agent != newua:\n logging.warn( \"Session UA has changed to %s.\" % newua );\n\nAlso, perhaps it would be better to prevent the session from being renewed indefinitely? I think that sites such as Google will eventually ask you to sign-in again if you try to keep a session going for a long time.\nI guess it would be easy to slowly decrease the _SESSION_EXPIRE_TIME each time the session gets renewed, but that isn't really a very good solution. Ideally the choice of when to force the user to sign-in again would take into account the flow and security requirements of your site.\n" ]
[ 5, 0 ]
[]
[]
[ "cookies", "google_app_engine", "python", "security", "session" ]
stackoverflow_0002560022_cookies_google_app_engine_python_security_session.txt
Q: Python creating a dictionary and swapping these into another file I have two tab delimited .csv file. From one.csv I have created a dictionary which looks like: 'EB2430': ' "\t"idnD "\t"yjgV "\t"b4267 "\n', 'EB3128': ' "\t"yagE "\t\t"b0268 "\n', 'EB3945': ' "\t"maeB "\t"ypfF "\t"b2463 "\n', 'EB3944': ' "\t"eutS "\t"ypfE "\t"b2462 "\n', I would like to insert the value of the dictionary into the second.csv file which looks like: "EB2430" 36.81 364 222 4 72 430 101 461 1.00E-063 237 "EB3128" 26.04 169 108 6 42 206 17 172 6.00E-006 45.8 "EB3945" 20.6 233 162 6 106 333 33 247 6.00E-005 42.4 "EB3944" 19.07 367 284 6 1 355 1 366 2.00E-023 103 With a resultant output tab delimited: 'EB2430' idnD yjgV b4267 36.81 364 222 4 72 430 101 461 1.00E-063 237 'EB3128' yagE b0268 26.04 169 108 6 42 206 17 172 6.00E-006 45.8 'EB3945' maeB ypfF b2463 20.6 233 162 6 106 333 33 247 6.00E-005 42.4 'EB3944' eutS ypfE b2462 19.07 367 284 6 1 355 1 366 2.00E-023 103 Here is my code for creating the dictionary: f = open ("one.csv", "r") g = open ("second.csv", "r") eb = [] desc = [] di = {} for line in f: for row in f: eb.append(row[1:7]) desc.append(row[7:]) di = dict(zip(eb,desc)) Sorry for it being so long-winded!! I've not been programming for long. Cheers! Sat A: It looks like you could more usefully use the Python standard library csv module here. rather than perform the text processing parts youself "manually". E.g.: import csv with open("one.csv", "r") as f: rows_one = list(csv.reader(f, delimiter='\t')) with open("second.csv", "r") as g: rows_two = list(csv.reader(g, delimiter='\t')) rows_totl = [r + s[1:] for r, s in zip(rows_one, rows_two)] with open("total.csv", "w") as h: csv.writer(h, delimiter='\t').writerows(rows_totl) The with statement is one of the jewels of Python 2.6 (it's also usable in 2.5, but only if you from __future__ import with_statement!-) -- as used here, it gives you an open file and ensures it gets closed as soon at the with body's done... plus, it has a zillion more uses, e.g. for locks and all sorts of your own custom-coded "context managers". A: May I suggest, instead of hand-parsing CSV file use csv that is built-in. It takes care of delimiters, character escaping etc. It's API is simple, too: import csv # Auto-detector of this particular CSV dialect (delimiters and such) dialect = csv.Sniffer().sniff(open('one.csv').read()) # csv.reader yields every row found in the file using the given dialect rows = csv.reader(open('one.csv'), dialect = dialect) # [list comprehension][2] resulting_dict = dict((row[0], row[1:]) for row in rows) You can refactor the code into a function and use it for both files (coding from memory, though, beware for errors). Now you've got two dicts for two files, let's say dict1 and dict2, you can combine them: combined_dict = dict((key, dict1[key] + dict2[key]) for key in dict2) Writing it to a .csv file is also straightforward: writer = csv.writer(open('second.csv', 'w'), delimiter = '\t') for key, values in combined_dict: writer.writerow(key, *values) Definitely check out the docs for the more detailed reference. Edit: My solution doesn't take line ordering into account (dict is unordered). There are two solutions: if you're running Python 3 or Python 2.7, use collections.OrderedDict otherwise, you need to store the order of the lines - for example, while reading the second file break the list comprehension into standard for statement and store the headers in a list. A: Have a look to csv module: import csv reader1 = csv.reader(open('input1.csv'), delimiter = '\t') reader2 = csv.reader(open('input2.csv'), delimiter = '\t') csvwriter = csv.writer(open('output.csv', 'w'),delimiter = '\t') while True: row1 = reader1.next() if row1: row2 = reader2.next() new_row = row2 + row1[1:] csvwriter.writerow(new_row) else: break
Python creating a dictionary and swapping these into another file
I have two tab delimited .csv file. From one.csv I have created a dictionary which looks like: 'EB2430': ' "\t"idnD "\t"yjgV "\t"b4267 "\n', 'EB3128': ' "\t"yagE "\t\t"b0268 "\n', 'EB3945': ' "\t"maeB "\t"ypfF "\t"b2463 "\n', 'EB3944': ' "\t"eutS "\t"ypfE "\t"b2462 "\n', I would like to insert the value of the dictionary into the second.csv file which looks like: "EB2430" 36.81 364 222 4 72 430 101 461 1.00E-063 237 "EB3128" 26.04 169 108 6 42 206 17 172 6.00E-006 45.8 "EB3945" 20.6 233 162 6 106 333 33 247 6.00E-005 42.4 "EB3944" 19.07 367 284 6 1 355 1 366 2.00E-023 103 With a resultant output tab delimited: 'EB2430' idnD yjgV b4267 36.81 364 222 4 72 430 101 461 1.00E-063 237 'EB3128' yagE b0268 26.04 169 108 6 42 206 17 172 6.00E-006 45.8 'EB3945' maeB ypfF b2463 20.6 233 162 6 106 333 33 247 6.00E-005 42.4 'EB3944' eutS ypfE b2462 19.07 367 284 6 1 355 1 366 2.00E-023 103 Here is my code for creating the dictionary: f = open ("one.csv", "r") g = open ("second.csv", "r") eb = [] desc = [] di = {} for line in f: for row in f: eb.append(row[1:7]) desc.append(row[7:]) di = dict(zip(eb,desc)) Sorry for it being so long-winded!! I've not been programming for long. Cheers! Sat
[ "It looks like you could more usefully use the Python standard library csv module here. rather than perform the text processing parts youself \"manually\". E.g.:\nimport csv\nwith open(\"one.csv\", \"r\") as f:\n rows_one = list(csv.reader(f, delimiter='\\t'))\nwith open(\"second.csv\", \"r\") as g:\n rows_two = list(csv.reader(g, delimiter='\\t'))\nrows_totl = [r + s[1:] for r, s in zip(rows_one, rows_two)]\nwith open(\"total.csv\", \"w\") as h:\n csv.writer(h, delimiter='\\t').writerows(rows_totl)\n\nThe with statement is one of the jewels of Python 2.6 (it's also usable in 2.5, but only if you from __future__ import with_statement!-) -- as used here, it gives you an open file and ensures it gets closed as soon at the with body's done... plus, it has a zillion more uses, e.g. for locks and all sorts of your own custom-coded \"context managers\".\n", "May I suggest, instead of hand-parsing CSV file use csv that is built-in. It takes care of delimiters, character escaping etc. It's API is simple, too:\nimport csv\n\n# Auto-detector of this particular CSV dialect (delimiters and such)\ndialect = csv.Sniffer().sniff(open('one.csv').read())\n\n# csv.reader yields every row found in the file using the given dialect\nrows = csv.reader(open('one.csv'), dialect = dialect)\n\n# [list comprehension][2]\nresulting_dict = dict((row[0], row[1:]) for row in rows)\n\nYou can refactor the code into a function and use it for both files (coding from memory, though, beware for errors).\nNow you've got two dicts for two files, let's say dict1 and dict2, you can combine them:\ncombined_dict = dict((key, dict1[key] + dict2[key]) for key in dict2)\n\nWriting it to a .csv file is also straightforward:\nwriter = csv.writer(open('second.csv', 'w'), delimiter = '\\t')\nfor key, values in combined_dict:\n writer.writerow(key, *values)\n\nDefinitely check out the docs for the more detailed reference.\nEdit: My solution doesn't take line ordering into account (dict is unordered). There are two solutions:\n\nif you're running Python 3 or Python 2.7, use collections.OrderedDict\notherwise, you need to store the order of the lines - for example, while reading the second file break the list comprehension into standard for statement and store the headers in a list.\n\n", "Have a look to csv module:\nimport csv\nreader1 = csv.reader(open('input1.csv'), delimiter = '\\t')\nreader2 = csv.reader(open('input2.csv'), delimiter = '\\t')\ncsvwriter = csv.writer(open('output.csv', 'w'),delimiter = '\\t')\nwhile True:\n row1 = reader1.next()\n if row1:\n row2 = reader2.next()\n new_row = row2 + row1[1:]\n csvwriter.writerow(new_row)\n else:\n break\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002563088_dictionary_python.txt
Q: Python script to get the data from the flex application I am making a simple Python CGI script that collects data(in xml format) from a flex application and I want to insert it into the mysql database . In perl The script is looks like the following... my @samplexml=$cgi->param("Items"); my $data=$xml->XMLin("@samplexml"); foreach my $e(@{$data->{Group}}) { my $sample="Insert into details(title,Parent,Istreeitem) Values('$e->{title}','$e->{Parent}','$e->{IsTreeItem}')"; my $sam=$dbo->prepare($sample); $sam->execute(); } But I want to know how to write these codes in pytrhon script.... Any one can help me? Thanks in advance. Nimmy. A: It should be fairly easy to convert this to a Python script. Setting the stage: Python has the cgi module. Get the Python-MySQL library (or an equivalent for whatever db you're using). Use Python's xml.etree to parse the incoming XML. You'd write a Python script that'd read the XML from the CGI variables, parse the xml using xml.etree, make a connection to the database, and execute your exact insert statement. The resulting script should look very similar to the above. A: If you're not bound to XML, you can consider pyAMF and flex's remoteobjects or other remoting facilities.
Python script to get the data from the flex application
I am making a simple Python CGI script that collects data(in xml format) from a flex application and I want to insert it into the mysql database . In perl The script is looks like the following... my @samplexml=$cgi->param("Items"); my $data=$xml->XMLin("@samplexml"); foreach my $e(@{$data->{Group}}) { my $sample="Insert into details(title,Parent,Istreeitem) Values('$e->{title}','$e->{Parent}','$e->{IsTreeItem}')"; my $sam=$dbo->prepare($sample); $sam->execute(); } But I want to know how to write these codes in pytrhon script.... Any one can help me? Thanks in advance. Nimmy.
[ "It should be fairly easy to convert this to a Python script. Setting the stage:\n\nPython has the cgi module.\nGet the Python-MySQL library (or an equivalent for whatever db you're using).\nUse Python's xml.etree to parse the incoming XML.\n\nYou'd write a Python script that'd read the XML from the CGI variables, parse the xml using xml.etree, make a connection to the database, and execute your exact insert statement. The resulting script should look very similar to the above.\n", "If you're not bound to XML, you can consider pyAMF and flex's remoteobjects or other remoting facilities.\n" ]
[ 0, 0 ]
[]
[]
[ "apache_flex", "cgi", "python" ]
stackoverflow_0002550637_apache_flex_cgi_python.txt
Q: Google App Engine (python): TemplateSyntaxError: 'for' statements with five words should end in 'reversed' This is using the web app framework, not Django. The following template code is giving me an TemplateSyntaxError: 'for' statements with five words should end in 'reversed' error when I try to render a dictionary. I don't understand what's causing this error. Could somebody shed some light on it for me? {% for code, name in charts.items %} <option value="{{code}}">{{name}}</option> {% endfor %} I'm rendering it using the following: class GenerateChart(basewebview): def get(self): values = {"datepicker":True} values["charts"] = {"p3": "3D Pie Chart", "p": "Segmented Pied Chart"} self.render_page("generatechart.html", values) class basewebview(webapp.RequestHandler): ''' Base class for all webapp.RequestHandler type classes ''' def render_page(self, filename, template_values=dict()): filename = "%s/%s" % (_template_dir, filename) path = os.path.join(os.path.dirname(__file__), filename) self.response.out.write(template.render(path, template_values)) A: This is using the web app framework, not Django. But framework apart, you must be using Django's templating -- and apparently in an old version, which does not support the "automatic unpacking" style of for -- probably the 0.96 version that's the default for App Engine. To use any part of more modern Django (including "just the templates") you must have a settings.py file and do: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from google.appengine.dist import use_library use_library('django', '1.1') as per the docs. After that you can from django import template and you'll be using the 1.1 version of Django's templating engine.
Google App Engine (python): TemplateSyntaxError: 'for' statements with five words should end in 'reversed'
This is using the web app framework, not Django. The following template code is giving me an TemplateSyntaxError: 'for' statements with five words should end in 'reversed' error when I try to render a dictionary. I don't understand what's causing this error. Could somebody shed some light on it for me? {% for code, name in charts.items %} <option value="{{code}}">{{name}}</option> {% endfor %} I'm rendering it using the following: class GenerateChart(basewebview): def get(self): values = {"datepicker":True} values["charts"] = {"p3": "3D Pie Chart", "p": "Segmented Pied Chart"} self.render_page("generatechart.html", values) class basewebview(webapp.RequestHandler): ''' Base class for all webapp.RequestHandler type classes ''' def render_page(self, filename, template_values=dict()): filename = "%s/%s" % (_template_dir, filename) path = os.path.join(os.path.dirname(__file__), filename) self.response.out.write(template.render(path, template_values))
[ "\nThis is using the web app framework,\n not Django.\n\nBut framework apart, you must be using Django's templating -- and apparently in an old version, which does not support the \"automatic unpacking\" style of for -- probably the 0.96 version that's the default for App Engine. To use any part of more modern Django (including \"just the templates\") you must have a settings.py file and do:\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\n\nfrom google.appengine.dist import use_library\nuse_library('django', '1.1')\n\nas per the docs. After that you can from django import template and you'll be using the 1.1 version of Django's templating engine.\n" ]
[ 13 ]
[]
[]
[ "django", "django_templates", "google_app_engine", "python" ]
stackoverflow_0002563365_django_django_templates_google_app_engine_python.txt
Q: Open Source Alternative to ASP.NET membership I'm currently supporting a Python web app with increasingly complicated user/role/permission management requirements. Currently, we are rolling our own user, groups, permissions, etc. code and supporting database. I'd like to find something like ASP.NET membership that can help manage user authentication and authorization, rather than risk security issues in continuing to create an increasingly complicated custom solution. Are there any similar projects out there worth taking a look at? A: If you are looking for off site user authentication you might want to consider openid. People have added openid support to cherrypy. If you are looking for more user management type code. I guess it depends on exactally what you are doing but others have done user management before, why not leverage off them. Skeletonz is a CMS written on top of cherrypy. If you are not wed to cherrypy you might also want to consider Pinax. It's built on Django with the idea of reusing work others have done so you don't have to do it again.
Open Source Alternative to ASP.NET membership
I'm currently supporting a Python web app with increasingly complicated user/role/permission management requirements. Currently, we are rolling our own user, groups, permissions, etc. code and supporting database. I'd like to find something like ASP.NET membership that can help manage user authentication and authorization, rather than risk security issues in continuing to create an increasingly complicated custom solution. Are there any similar projects out there worth taking a look at?
[ "If you are looking for off site user authentication you might want to consider openid. People have added openid support to cherrypy. \nIf you are looking for more user management type code. I guess it depends on exactally what you are doing but others have done user management before, why not leverage off them. Skeletonz is a CMS written on top of cherrypy. If you are not wed to cherrypy you might also want to consider Pinax. It's built on Django with the idea of reusing work others have done so you don't have to do it again. \n" ]
[ 1 ]
[]
[]
[ "asp.net_membership", "cherrypy", "ldap", "open_source", "python" ]
stackoverflow_0002563403_asp.net_membership_cherrypy_ldap_open_source_python.txt
Q: Pylons check for cookie on every page load I want to check whether or not a cookie is set with every page load in Pylons. Where's the best place to put this logic? Thanks! A: You can modify __call__ function in BaseController.
Pylons check for cookie on every page load
I want to check whether or not a cookie is set with every page load in Pylons. Where's the best place to put this logic? Thanks!
[ "You can modify __call__ function in BaseController.\n" ]
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002563528_pylons_python.txt
Q: Python urlparse, correct or incorrect? Python's urlparse function parses an url into six components (scheme, netloc, path and others stuff) Now I've found that parsing "example.com/path/file.ext" return no netloc but a path "example.com/path/file.ext". Should't it be netloc = "example.com" and path = "/path/file.ext"? Do we really need a "://" to determine wether or not a netloc exists? Python's ticket: http://bugs.python.org/issue8284 A: Without the scheme://, there's no guarantee that example.com is a domain. You could have a directory called example.com. Similarly, you could have a url 'omfgroflmao/path/file.ext', how would you know if 'omfgroflmao' is a machine on the local network (i.e. a netloc) or whether it's meant to be a path component? I can't see that the Python code is actually wrong, but perhaps the documentation needs to spell out explicitly the behaviour in such ambiguous circumstances (I haven't checked). A: example.com/path/file.ext is not URL. It's just some string. For example if you put <a href="example.com/path/file.ext"> into HTML page, it will not link to http://example.com/path/file.ext. It's just a shortcut provided by web browsers that you do not have to prepend the http://. You can not even use such URL as parameter for urllib2.urlopen() and similar functions.
Python urlparse, correct or incorrect?
Python's urlparse function parses an url into six components (scheme, netloc, path and others stuff) Now I've found that parsing "example.com/path/file.ext" return no netloc but a path "example.com/path/file.ext". Should't it be netloc = "example.com" and path = "/path/file.ext"? Do we really need a "://" to determine wether or not a netloc exists? Python's ticket: http://bugs.python.org/issue8284
[ "Without the scheme://, there's no guarantee that example.com is a domain. You could have a directory called example.com. Similarly, you could have a url 'omfgroflmao/path/file.ext', how would you know if 'omfgroflmao' is a machine on the local network (i.e. a netloc) or whether it's meant to be a path component?\nI can't see that the Python code is actually wrong, but perhaps the documentation needs to spell out explicitly the behaviour in such ambiguous circumstances (I haven't checked).\n", "example.com/path/file.ext is not URL. It's just some string. For example if you put <a href=\"example.com/path/file.ext\"> into HTML page, it will not link to http://example.com/path/file.ext. It's just a shortcut provided by web browsers that you do not have to prepend the http://. You can not even use such URL as parameter for urllib2.urlopen() and similar functions.\n" ]
[ 6, 1 ]
[]
[]
[ "python", "urlparse" ]
stackoverflow_0002563961_python_urlparse.txt
Q: Python: Taking an array and break it into subarrays based on some criteria I have an array of files. I'd like to be able to break that array down into one array with multiple subarrays, each subarray contains files that were created on the same day. So right now if the array contains files from March 1 - March 31, I'd like to have an array with 31 subarrays (assuming there is at least > 1 file for each day). In the long run, I'm trying to find the file from each day with the latest creation/modification time. If there is a way to bundle that into the iterations that are required above to save some CPU cycles, that would be even more ideal. Then I'd have one flat array with 31 files, one for each day, for the latest file created on each individual day. My current data structure is just a flat list of file names. A: If you need to split a list into list of lists by some criteria, have a look at itertools.groupby(). A: To get the files with the latest timestamps for each day, use a dict with days as keys and tuples of (filename, timestamp) as the values. Loop through all the files, and update the dict value for that day if the dict timestamp is less than the current file, or if no value for that day exists yet. A: Following up on Messa's answer, if your structure is like: files=[{'date': datetime(2010, 3, 1, 0, 0, 10), 'file': 'foo'}, {'date': datetime(2010, 3, 1, 12, 0, 10), 'file': 'bar'}, {'date': datetime(2010, 3, 2, 3, 5, 10), 'file': 'baz'}, {'date': datetime(2010, 3, 2, 3, 3, 10), 'file': 'foo'}] try something like: from itertools import groupby map(lambda x: next(x[1]), groupby(sorted(files, key=lambda x: x['date'], reverse=True), key=lambda x: datetime(x['date'].year, x['date'].month, x['date'].day))) which will give you: [{'date': datetime.datetime(2010, 3, 2, 3, 5, 10), 'file': 'baz'}, {'date': datetime.datetime(2010, 3, 1, 12, 0, 10), 'file': 'bar'}] Basically, it first sorts by date in reverse (sorted), then groups by date (groupby), then takes the first element of every group (next[1]).
Python: Taking an array and break it into subarrays based on some criteria
I have an array of files. I'd like to be able to break that array down into one array with multiple subarrays, each subarray contains files that were created on the same day. So right now if the array contains files from March 1 - March 31, I'd like to have an array with 31 subarrays (assuming there is at least > 1 file for each day). In the long run, I'm trying to find the file from each day with the latest creation/modification time. If there is a way to bundle that into the iterations that are required above to save some CPU cycles, that would be even more ideal. Then I'd have one flat array with 31 files, one for each day, for the latest file created on each individual day. My current data structure is just a flat list of file names.
[ "If you need to split a list into list of lists by some criteria, have a look at itertools.groupby().\n", "To get the files with the latest timestamps for each day, use a dict with days as keys and tuples of (filename, timestamp) as the values. Loop through all the files, and update the dict value for that day if the dict timestamp is less than the current file, or if no value for that day exists yet.\n", "Following up on Messa's answer, if your structure is like:\nfiles=[{'date': datetime(2010, 3, 1, 0, 0, 10), 'file': 'foo'}, \n {'date': datetime(2010, 3, 1, 12, 0, 10), 'file': 'bar'}, \n {'date': datetime(2010, 3, 2, 3, 5, 10), 'file': 'baz'}, \n {'date': datetime(2010, 3, 2, 3, 3, 10), 'file': 'foo'}]\n\ntry something like:\nfrom itertools import groupby\nmap(lambda x: next(x[1]), \n groupby(sorted(files, \n key=lambda x: x['date'],\n reverse=True), \n key=lambda x: datetime(x['date'].year, x['date'].month, x['date'].day)))\n\nwhich will give you:\n[{'date': datetime.datetime(2010, 3, 2, 3, 5, 10), 'file': 'baz'}, {'date': datetime.datetime(2010, 3, 1, 12, 0, 10), 'file': 'bar'}]\n\nBasically, it first sorts by date in reverse (sorted), then groups by date (groupby), then takes the first element of every group (next[1]).\n" ]
[ 5, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002563990_python.txt
Q: Integer to byte conversion Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python? A: Use bitwise mathematical operators, the "bytes" are already there: def int_to_rgb(n): b = (n & 0xff0000) >> 16 g = (n & 0x00ff00) >> 8 r = (n & 0x0000ff) return (r, g, b) A: You can bitwise & with 0xff to get the first byte, then shift 8 bits and repeat to get the other 3 bytes. Edit: For colors, you know you need the least significant three bytes. So, you can use a nicer approach: r = num & 0x0000ff g = (num & 0x00ff00) >> 8 b = (num & 0xff0000) >> 16 A: Here's an optimisation suggestion that applies in any language, and doesn't harm legibility. Instead of this: b = (n & 0xff0000) >> 16 g = (n & 0xff00) >> 8 r = (n & 0xff) use this: b = (n >> 16) & 0xff g = (n >> 8) & 0xff r = n & 0xff Two reasons: Having fewer constants is not slower, and may be faster. Having smaller constants is not slower, and may be faster -- in a language like C, a shorter machine instruction may be available; in a language like Python, the implementation is likely to pool small integers.
Integer to byte conversion
Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python?
[ "Use bitwise mathematical operators, the \"bytes\" are already there:\ndef int_to_rgb(n):\n b = (n & 0xff0000) >> 16\n g = (n & 0x00ff00) >> 8\n r = (n & 0x0000ff)\n return (r, g, b)\n\n", "You can bitwise & with 0xff to get the first byte, then shift 8 bits and repeat to get the other 3 bytes.\nEdit: For colors, you know you need the least significant three bytes. So, you can use a nicer approach:\nr = num & 0x0000ff\ng = (num & 0x00ff00) >> 8\nb = (num & 0xff0000) >> 16\n\n", "Here's an optimisation suggestion that applies in any language, and doesn't harm legibility.\nInstead of this:\nb = (n & 0xff0000) >> 16\ng = (n & 0xff00) >> 8\nr = (n & 0xff)\n\nuse this:\nb = (n >> 16) & 0xff\ng = (n >> 8) & 0xff\nr = n & 0xff\n\nTwo reasons: \nHaving fewer constants is not slower, and may be faster.\nHaving smaller constants is not slower, and may be faster -- in a language like C, a shorter machine instruction may be available; in a language like Python, the implementation is likely to pool small integers.\n" ]
[ 13, 2, 0 ]
[]
[]
[ "byte", "casting", "python" ]
stackoverflow_0002562308_byte_casting_python.txt
Q: Dynamic variable name in python I'd like to call a query with a field name filter that I wont know before run time... Not sure how to construct the variable name ...Or maybe I am tired. field_name = funct() locations = Locations.objects.filter(field_name__lte=arg1) where if funct() returns name would equal to locations = Locations.objects.filter(name__lte=arg1) Not sure how to do that ... A: You can create a dictionary, set the parameters and pass this to the function by unpacking the dictionary as keyword arguments: field_name = funct() params = {field_name + '__lte': arg1, # field_name should still contain string 'some_other_field_name': arg2} locations = Locations.objects.filter(**params) # is the same as (assuming field_name = 'some_name'): # Locations.objects.filter(some_name__lte=arg1, some_other_field_name=arg2)
Dynamic variable name in python
I'd like to call a query with a field name filter that I wont know before run time... Not sure how to construct the variable name ...Or maybe I am tired. field_name = funct() locations = Locations.objects.filter(field_name__lte=arg1) where if funct() returns name would equal to locations = Locations.objects.filter(name__lte=arg1) Not sure how to do that ...
[ "You can create a dictionary, set the parameters and pass this to the function by unpacking the dictionary as keyword arguments:\nfield_name = funct()\nparams = {field_name + '__lte': arg1, # field_name should still contain string\n 'some_other_field_name': arg2}\n\nlocations = Locations.objects.filter(**params)\n\n# is the same as (assuming field_name = 'some_name'):\n# Locations.objects.filter(some_name__lte=arg1, some_other_field_name=arg2)\n\n" ]
[ 11 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002564140_django_python.txt
Q: Server authorization with MD5 and SQL I currently have a SQL database of passwords stored in MD5. The server needs to generate a unique key, then sends to the client. In the client, it will use the key as a salt then hash together with the password and send back to the server. The only problem is that the the SQL DB has the passwords in MD5 already. Therefore for this to work, I would have to MD5 the password client side, then MD5 it again with the salt. Am I doing this wrong, because it doesn't seem like a proper solution. Any information is appreciated. A: You should use SSL to encrypt the connection, then send the password over plain text from the client. The server will then md5 and compare with the md5 hash in the database to see if they are the same. If so auth = success. MD5'ing the password on the client buys you nothing because a hacker with the md5 password can get in just as easy as if it was in plain text. A: It is not completely clear to me what are you asking, but python hashlib (read the FAQ) and wikipedia should get you to where ever you are going. For real world example in python check django authentication (the source).
Server authorization with MD5 and SQL
I currently have a SQL database of passwords stored in MD5. The server needs to generate a unique key, then sends to the client. In the client, it will use the key as a salt then hash together with the password and send back to the server. The only problem is that the the SQL DB has the passwords in MD5 already. Therefore for this to work, I would have to MD5 the password client side, then MD5 it again with the salt. Am I doing this wrong, because it doesn't seem like a proper solution. Any information is appreciated.
[ "You should use SSL to encrypt the connection, then send the password over plain text from the client. The server will then md5 and compare with the md5 hash in the database to see if they are the same. If so auth = success.\nMD5'ing the password on the client buys you nothing because a hacker with the md5 password can get in just as easy as if it was in plain text.\n", "It is not completely clear to me what are you asking, but python hashlib (read the FAQ) and wikipedia should get you to where ever you are going.\nFor real world example in python check django authentication (the source).\n" ]
[ 1, 0 ]
[]
[]
[ "authorization", "database", "md5", "python", "sql" ]
stackoverflow_0002564312_authorization_database_md5_python_sql.txt
Q: mysql-python stopped working This is a rather dumb question but i'am looking at a bizarre situation. I am running fedora and have python 2.6.5 installed. The other day i installed MySQL-python using yum (because i do not have the setuptools module so i cannot build it from source). Anyway yesterday i wrote my entire data access layer in python and it was running fine, i did test it. Today however it gives me an ImportError: No module named MySQLdb The only thing i ever changed was i installed eclipse and pyDev. Any ideas on what went wrong and how i fix it. I tried removing and re-installing MySql-python but that did not help. I did the following import sys print sys.path And it shows me all the paths which are basically pertaining to /usr/local/lib/python2.6 However i was trying to find where the MySQLdb module is installed and it seems that its installed in /usr/lib/python2.5/sitepackages Now i have no idea why it got installed there and why it was working earlier and why it stopped working now. Any ideas on how i should fix it. I did try copying the site-packages folder over to the python2.6 folder but that did not work Help!! A: If all else fails, go to http://sourceforge.net/projects/mysql-python/ and install the package manually. This should work reliably. A: Well it seems to be working if i run or debug something from within eclipse. As it has the 2.5 version set as the python interpreter. Does anyone know how i can set which python version to use in general on fedora. I'm sure i just have to set some path variable somewhere but not sure what!
mysql-python stopped working
This is a rather dumb question but i'am looking at a bizarre situation. I am running fedora and have python 2.6.5 installed. The other day i installed MySQL-python using yum (because i do not have the setuptools module so i cannot build it from source). Anyway yesterday i wrote my entire data access layer in python and it was running fine, i did test it. Today however it gives me an ImportError: No module named MySQLdb The only thing i ever changed was i installed eclipse and pyDev. Any ideas on what went wrong and how i fix it. I tried removing and re-installing MySql-python but that did not help. I did the following import sys print sys.path And it shows me all the paths which are basically pertaining to /usr/local/lib/python2.6 However i was trying to find where the MySQLdb module is installed and it seems that its installed in /usr/lib/python2.5/sitepackages Now i have no idea why it got installed there and why it was working earlier and why it stopped working now. Any ideas on how i should fix it. I did try copying the site-packages folder over to the python2.6 folder but that did not work Help!!
[ "If all else fails, go to http://sourceforge.net/projects/mysql-python/ and install the package manually. This should work reliably.\n", "Well it seems to be working if i run or debug something from within eclipse. As it has the 2.5 version set as the python interpreter.\nDoes anyone know how i can set which python version to use in general on fedora. I'm sure i just have to set some path variable somewhere but not sure what!\n" ]
[ 1, 0 ]
[]
[]
[ "configuration", "installation", "mysql", "python" ]
stackoverflow_0002562673_configuration_installation_mysql_python.txt
Q: Python mysql check for duplicate before insert here is the table CREATE TABLE IF NOT EXISTS kompas_url ( id BIGINT(20) NOT NULL AUTO_INCREMENT, url VARCHAR(1000), created_date datetime, modified_date datetime, PRIMARY KEY(id) ) I am trying to do INSERT to kompas_url table only if url is not exist yet any idea? thanks A: You can either find out whether it's in there first, by SELECTing by url, or you can make the url field unique: CREATE TABLE IF NOT EXISTS kompas_url ... url VARCHAR(1000) UNIQUE, ... ) This will stop MySQL from inserting a duplicate row, but it will also report an error when you try and insert. This isn't good—although we can handle the error, it might disguise others. To get around this, we use the ON DUPLICATE KEY UPDATE syntax: INSERT INTO kompas_url (url, created_date, modified_date) VALUES ('http://example.com', NOW(), NOW()) ON DUPLICATE KEY UPDATE modified_date = NOW() This allows us to provide an UPDATE statement in the case of a duplicate value in a unique field (this can include your primary key). In this case, we probably want to update the modified_date field with the current date. EDIT: As suggested by ~unutbu, if you don't want to change anything on a duplicate, you can use the INSERT IGNORE syntax. This simply works as follows: INSERT IGNORE INTO kompas_url (url, created_date, modified_date) VALUES ('http://example.com', NOW(), NOW()) This simply turns certain kinds of errors into warnings—most usefully, the error that states there will be a duplicate unique entry. If you place the keyword IGNORE into your statement, you won't get an error—the query will simply be dropped. In complex queries, this may also hide other errors that might be useful though, so it's best to make doubly sure your code is correct if you want to use it.
Python mysql check for duplicate before insert
here is the table CREATE TABLE IF NOT EXISTS kompas_url ( id BIGINT(20) NOT NULL AUTO_INCREMENT, url VARCHAR(1000), created_date datetime, modified_date datetime, PRIMARY KEY(id) ) I am trying to do INSERT to kompas_url table only if url is not exist yet any idea? thanks
[ "You can either find out whether it's in there first, by SELECTing by url, or you can make the url field unique:\nCREATE TABLE IF NOT EXISTS kompas_url\n ...\n url VARCHAR(1000) UNIQUE,\n ...\n)\n\nThis will stop MySQL from inserting a duplicate row, but it will also report an error when you try and insert. This isn't good—although we can handle the error, it might disguise others. To get around this, we use the ON DUPLICATE KEY UPDATE syntax:\nINSERT INTO kompas_url (url, created_date, modified_date)\nVALUES ('http://example.com', NOW(), NOW())\nON DUPLICATE KEY UPDATE modified_date = NOW()\n\nThis allows us to provide an UPDATE statement in the case of a duplicate value in a unique field (this can include your primary key). In this case, we probably want to update the modified_date field with the current date.\nEDIT: As suggested by ~unutbu, if you don't want to change anything on a duplicate, you can use the INSERT IGNORE syntax. This simply works as follows:\nINSERT IGNORE INTO kompas_url (url, created_date, modified_date)\nVALUES ('http://example.com', NOW(), NOW())\n\nThis simply turns certain kinds of errors into warnings—most usefully, the error that states there will be a duplicate unique entry. If you place the keyword IGNORE into your statement, you won't get an error—the query will simply be dropped. In complex queries, this may also hide other errors that might be useful though, so it's best to make doubly sure your code is correct if you want to use it.\n" ]
[ 9 ]
[]
[]
[ "insert", "mysql", "no_duplicates", "python" ]
stackoverflow_0002564568_insert_mysql_no_duplicates_python.txt
Q: Web-based game in Python + Django and client browser polling I am creating a text-based game that implements a basic model in which multiple (10+) players interact with data and one moderator watches them and sets certain environmental statistics that affect gameplay. Recently I have begun to familiarize myself with Django. It seems to me that it would be an excellent tool for creating a game quickly, particularly because the nature of my game depends largely on sets of data (which lends itself quite well to a database). I am wondering how to "push" changes made by the game moderator to the players (for example, the moderator can decide to display an image to all players). The game is turn-based, not real-time, but certain messages need to be pushed out in roughly real-time. My thoughts: I could have each player's browser poll a status periodically (say, every 30 seconds) to see if there is a message from a moderator. But this forces a lag and means different players might receive it at different times. And reducing this interval to <10 seems like a bad idea for the server. Is there a better way to inform clients of changes? Would you suggest something other than using a web framework like Django? Thanks! A: You could use long polling. Also, if you're creating a multiplayer game, it might be much easier and more efficient to use a server that's designed for long polling and multi-user interaction instead of using a standard HTTP server and framework. A: In addition to long polling mentioned by Matti, the HTTP server can also stream the data by basically using one really long response and never finishing the response (but continuing to push more data to the client). The client can continue to respond to data as it comes in. As you've concluded polling is probably a bad solution for any decently sized project. Before you can get started, you're going to want to have a fairly sound understanding of HTTP and Django. This type of technology is a little more bleeding edge and can be complex at times. There's an interesting project which is probably worth checking out: evserver. It's an HTTP server that supports asynchronous WSGI and will allow you do develop COMET-ish apps with Django. (Disclaimer: I haven't actually used evserver, but it's on my list of "cool stuff to try")
Web-based game in Python + Django and client browser polling
I am creating a text-based game that implements a basic model in which multiple (10+) players interact with data and one moderator watches them and sets certain environmental statistics that affect gameplay. Recently I have begun to familiarize myself with Django. It seems to me that it would be an excellent tool for creating a game quickly, particularly because the nature of my game depends largely on sets of data (which lends itself quite well to a database). I am wondering how to "push" changes made by the game moderator to the players (for example, the moderator can decide to display an image to all players). The game is turn-based, not real-time, but certain messages need to be pushed out in roughly real-time. My thoughts: I could have each player's browser poll a status periodically (say, every 30 seconds) to see if there is a message from a moderator. But this forces a lag and means different players might receive it at different times. And reducing this interval to <10 seems like a bad idea for the server. Is there a better way to inform clients of changes? Would you suggest something other than using a web framework like Django? Thanks!
[ "You could use long polling.\nAlso, if you're creating a multiplayer game, it might be much easier and more efficient to use a server that's designed for long polling and multi-user interaction instead of using a standard HTTP server and framework.\n", "In addition to long polling mentioned by Matti, the HTTP server can also stream the data by basically using one really long response and never finishing the response (but continuing to push more data to the client). The client can continue to respond to data as it comes in. As you've concluded polling is probably a bad solution for any decently sized project.\nBefore you can get started, you're going to want to have a fairly sound understanding of HTTP and Django. This type of technology is a little more bleeding edge and can be complex at times.\nThere's an interesting project which is probably worth checking out: evserver. It's an HTTP server that supports asynchronous WSGI and will allow you do develop COMET-ish apps with Django. (Disclaimer: I haven't actually used evserver, but it's on my list of \"cool stuff to try\")\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002563742_django_python.txt
Q: Better use a tuple or numpy array for storing coordinates I'm porting an C++ scientific application to python, and as I'm new to python, some problems come to my mind: 1) I'm defining a class that will contain the coordinates (x,y). These values will be accessed several times, but they only will be read after the class instantiation. Is it better to use an tuple or an numpy array, both in memory and access time wise? 2) In some cases, these coordinates will be used to build a complex number, evaluated on a complex function, and the real part of this function will be used. Assuming that there is no way to separate real and complex parts of this function, and the real part will have to be used on the end, maybe is better to use directly complex numbers to store (x,y)? How bad is the overhead with the transformation from complex to real in python? The code in c++ does a lot of these transformations, and this is a big slowdown in that code. 3) Also some coordinates transformations will have to be performed, and for the coordinates the x and y values will be accessed in separate, the transformation be done, and the result returned. The coordinate transformations are defined in the complex plane, so is still faster to use the components x and y directly than relying on the complex variables? Thank you A: In terms of memory consumption, numpy arrays are more compact than Python tuples. A numpy array uses a single contiguous block of memory. All elements of the numpy array must be of a declared type (e.g. 32-bit or 64-bit float.) A Python tuple does not necessarily use a contiguous block of memory, and the elements of the tuple can be arbitrary Python objects, which generally consume more memory than numpy numeric types. So this issue is a hands-down win for numpy, (assuming the elements of the array can be stored as a numpy numeric type). On the issue of speed, I think the choice boils down to the question, "Can you vectorize your code?" That is, can you express your calculations as operations done on entire arrays element-wise. If the code can be vectorized, then numpy will most likely be faster than Python tuples. (The only case I could imagine where it might not be, is if you had many very small tuples. In this case the overhead of forming the numpy arrays and one-time cost of importing numpy might drown-out the benefit of vectorization.) An example of code that could not be vectorized would be if your calculation involved looking at, say, the first complex number in an array z, doing a calculation which produces an integer index idx, then retrieving z[idx], doing a calculation on that number, which produces the next index idx2, then retrieving z[idx2], etc. This type of calculation might not be vectorizable. In this case, you might as well use Python tuples, since you won't be able to leverage numpy's strength. I wouldn't worry about the speed of accessing the real/imaginary parts of a complex number. My guess is the issue of vectorization will most likely determine which method is faster. (Though, by the way, numpy can transform an array of complex numbers to their real parts simply by striding over the complex array, skipping every other float, and viewing the result as floats. Moreover, the syntax is dead simple: If z is a complex numpy array, then z.real is the real parts as a float numpy array. This should be far faster than the pure Python approach of using a list comprehension of attribute lookups: [z.real for z in zlist].) Just out of curiosity, what is your reason for porting the C++ code to Python? A: A numpy array with an extra dimension is tighter in memory use, and at least as fast!, as a numpy array of tuples; complex numbers are at least as good or even better, including for your third question. BTW, you may have noticed that -- while questions asked later than yours were getting answers aplenty -- your was laying fallow: part of the reason is no doubt that asking three questions within a question turns responders off. Why not just ask one question per question? It's not as if you get charged for questions or anything, you know...!-)
Better use a tuple or numpy array for storing coordinates
I'm porting an C++ scientific application to python, and as I'm new to python, some problems come to my mind: 1) I'm defining a class that will contain the coordinates (x,y). These values will be accessed several times, but they only will be read after the class instantiation. Is it better to use an tuple or an numpy array, both in memory and access time wise? 2) In some cases, these coordinates will be used to build a complex number, evaluated on a complex function, and the real part of this function will be used. Assuming that there is no way to separate real and complex parts of this function, and the real part will have to be used on the end, maybe is better to use directly complex numbers to store (x,y)? How bad is the overhead with the transformation from complex to real in python? The code in c++ does a lot of these transformations, and this is a big slowdown in that code. 3) Also some coordinates transformations will have to be performed, and for the coordinates the x and y values will be accessed in separate, the transformation be done, and the result returned. The coordinate transformations are defined in the complex plane, so is still faster to use the components x and y directly than relying on the complex variables? Thank you
[ "In terms of memory consumption, numpy arrays are more compact than Python tuples.\nA numpy array uses a single contiguous block of memory. All elements of the numpy array must be of a declared type (e.g. 32-bit or 64-bit float.) A Python tuple does not necessarily use a contiguous block of memory, and the elements of the tuple can be arbitrary Python objects, which generally consume more memory than numpy numeric types.\nSo this issue is a hands-down win for numpy, (assuming the elements of the array can be stored as a numpy numeric type).\nOn the issue of speed, I think the choice boils down to the question, \"Can you vectorize your code?\"\nThat is, can you express your calculations as operations done on entire arrays element-wise. \nIf the code can be vectorized, then numpy will most likely be faster than Python tuples. (The only case I could imagine where it might not be, is if you had many very small tuples. In this case the overhead of forming the numpy arrays and one-time cost of importing numpy might drown-out the benefit of vectorization.)\nAn example of code that could not be vectorized would be if your calculation involved looking at, say, the first complex number in an array z, doing a calculation which produces an integer index idx, then retrieving z[idx], doing a calculation on that number, which produces the next index idx2, then retrieving z[idx2], etc. This type of calculation might not be vectorizable. In this case, you might as well use Python tuples, since you won't be able to leverage numpy's strength.\nI wouldn't worry about the speed of accessing the real/imaginary parts of a complex number. My guess is the issue of vectorization will most likely determine which method is faster. (Though, by the way, numpy can transform an array of complex numbers to their real parts simply by striding over the complex array, skipping every other float, and viewing the result as floats. Moreover, the syntax is dead simple: If z is a complex numpy array, then z.real is the real parts as a float numpy array. This should be far faster than the pure Python approach of using a list comprehension of attribute lookups: [z.real for z in zlist].)\nJust out of curiosity, what is your reason for porting the C++ code to Python?\n", "A numpy array with an extra dimension is tighter in memory use, and at least as fast!, as a numpy array of tuples; complex numbers are at least as good or even better, including for your third question. BTW, you may have noticed that -- while questions asked later than yours were getting answers aplenty -- your was laying fallow: part of the reason is no doubt that asking three questions within a question turns responders off. Why not just ask one question per question? It's not as if you get charged for questions or anything, you know...!-)\n" ]
[ 7, 3 ]
[]
[]
[ "arrays", "complex_numbers", "numpy", "python", "tuples" ]
stackoverflow_0002563773_arrays_complex_numbers_numpy_python_tuples.txt
Q: Best way to find similar items in python I have 1M numbers:N[], and 1 single number n, now I want to find in those 1M numbers that are similar to that single number, say an area of [n-10, n+10]. what's the best way in python to do this? Do I have to sort the 1M number and do an iteration? A: [x for x in N if n - 10 <= x <= n + 10] A: results=[x for x in numbers if x >= n-10 and x <= n+10] A: Another solution: is_close_to_n = lambda x: n-10 <= x <= n+10 result = filter(is_close_to_n, N) Generalizing a bit: def is_close_to(n): f = lambda x: n-10 <= x <= n+10 return f result12 = filter(is_close_to(12), N) result123 = filter(is_close_to(123), N) Do not sort. Sorting is, in general, O(n log n); brute-force searching is O(n).
Best way to find similar items in python
I have 1M numbers:N[], and 1 single number n, now I want to find in those 1M numbers that are similar to that single number, say an area of [n-10, n+10]. what's the best way in python to do this? Do I have to sort the 1M number and do an iteration?
[ "[x for x in N if n - 10 <= x <= n + 10]\n", "results=[x for x in numbers if x >= n-10 and x <= n+10]\n\n", "Another solution:\nis_close_to_n = lambda x: n-10 <= x <= n+10\nresult = filter(is_close_to_n, N)\n\nGeneralizing a bit:\ndef is_close_to(n):\n f = lambda x: n-10 <= x <= n+10\n return f\n\nresult12 = filter(is_close_to(12), N)\nresult123 = filter(is_close_to(123), N)\n\nDo not sort. Sorting is, in general, O(n log n); brute-force searching is O(n).\n" ]
[ 3, 1, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002564896_python_sorting.txt
Q: I want all three shapes on the same line...please help...! #Top half of triangle for rows in range (5): for row in range (12): print("-", end='') print() for row in range (5): stars=0 while stars<=row: print("*", end='') stars=stars+1 print() for row in range(5): star=4 while star>=row: print("*", end='') star=star-1 print() A: shape1 = [12*'-' for i in range(5)] # segments of rectangle shape2 = [i*'*' + (5-i)*' ' for i in range(1,5+1)] # segments of 1st triangle shape3 = [(5-i)*' ' + i*'*' for i in range(1,5+1)] # segments of 2nd triangle for line in zip(shape1, shape2, shape3): print(" ".join(line)) EDIT: verbose version, as requested (but I don't have python 3 here; the following code works in python 2.x, so you'll have to rework printing instructions a bit): for line in range(1, 5+1): # for each line for c in range (12): # print a bit of the first shape print '-', print " ", for c in range (line) : # a bit of the second print '*', for c in range (5-line): print ' ', print " ", for c in range (5+1-line): # and a bit of the third print '*', #for c in range (line): # print ' ', print A: First of all, your first print statement is syntactically wrong: print("-", end='') will throw a syntax error asking what end='' is. Nevertheless, if your problem is with the newline, then you can always remedy that with a comma (',') at the end of your print statement to skip the newline, for example: for i in range(5): print "Hello, World!",
I want all three shapes on the same line...please help...!
#Top half of triangle for rows in range (5): for row in range (12): print("-", end='') print() for row in range (5): stars=0 while stars<=row: print("*", end='') stars=stars+1 print() for row in range(5): star=4 while star>=row: print("*", end='') star=star-1 print()
[ "shape1 = [12*'-' for i in range(5)] # segments of rectangle\nshape2 = [i*'*' + (5-i)*' ' for i in range(1,5+1)] # segments of 1st triangle\nshape3 = [(5-i)*' ' + i*'*' for i in range(1,5+1)] # segments of 2nd triangle \n\nfor line in zip(shape1, shape2, shape3):\n print(\" \".join(line))\n\nEDIT: verbose version, as requested (but I don't have python 3 here; the following code works in python 2.x, so you'll have to rework printing instructions a bit):\nfor line in range(1, 5+1): # for each line\n for c in range (12): # print a bit of the first shape\n print '-',\n print \" \", \n\n for c in range (line) : # a bit of the second\n print '*',\n for c in range (5-line):\n print ' ',\n print \" \",\n\n for c in range (5+1-line): # and a bit of the third\n print '*',\n #for c in range (line):\n # print ' ',\n print\n\n", "First of all, your first print statement is syntactically wrong: print(\"-\", end='') will throw a syntax error asking what end='' is.\nNevertheless, if your problem is with the newline, then you can always remedy that with a comma (',') at the end of your print statement to skip the newline, for example:\nfor i in range(5):\n print \"Hello, World!\",\n\n" ]
[ 3, 0 ]
[]
[]
[ "nested_loops", "python", "python_3.x" ]
stackoverflow_0002564972_nested_loops_python_python_3.x.txt
Q: Control VLC from Python in Windows I'm running VLC (a media player) in Windows 7. Is there way to control (as in: play, pause, set volume) a running instance of VLC from Python? A: Yes, you can control it via telnet (with telnetlib). There are also libvlc bindings, but I'm not sure you can use that to control an existing VLC instance.
Control VLC from Python in Windows
I'm running VLC (a media player) in Windows 7. Is there way to control (as in: play, pause, set volume) a running instance of VLC from Python?
[ "Yes, you can control it via telnet (with telnetlib). There are also libvlc bindings, but I'm not sure you can use that to control an existing VLC instance.\n" ]
[ 4 ]
[ "As a general alternative to already mentioned solutions it's good to know about pywinauto\nUPDATE:\nCheck out swapy for a way to with pywinauto more easily.\n" ]
[ -1 ]
[ "python", "vlc", "windows" ]
stackoverflow_0002564815_python_vlc_windows.txt
Q: Pylons redirect to 404 error page What function to I use to redirect to the default 404 error page? Sample code appreciated. Thank you! A: abort(404) as mentioned in the quickwiki tutorial. See the docs for abort. A: 404 isn't something you redirect to; there's no distinct "404 page" with its own distinct URL. It's a status code that you send back in the HTTP response, instead of 200 (the code for a normal successful response). Actual redirects are also status codes, such as 301 or 307, that can be used instead of 200 or 404. Read about the status line in an HTTP response for more info.
Pylons redirect to 404 error page
What function to I use to redirect to the default 404 error page? Sample code appreciated. Thank you!
[ "abort(404) as mentioned in the quickwiki tutorial. See the docs for abort.\n", "404 isn't something you redirect to; there's no distinct \"404 page\" with its own distinct URL. It's a status code that you send back in the HTTP response, instead of 200 (the code for a normal successful response).\nActual redirects are also status codes, such as 301 or 307, that can be used instead of 200 or 404.\nRead about the status line in an HTTP response for more info.\n" ]
[ 3, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002565324_pylons_python.txt
Q: Adjust OSX System Audio Volume in Python I would like to adjust the system audio volume in OSX from a python script. This question about implementing keyboard shortcuts tells me how to do it in applescript, but I'd really like to do it from my python script without using os.system, popen, etc. Ideally I'd like to ramp up the volume slowly with some python code like this: set_volume(0) for i in range(50): set_volume(i*2) time.sleep(1) A: Use appscript to control the StandardAdditions scripting addition set volume command: >>> from osax import * >>> import time >>> sa = OSAX() >>> for i in range(50): ... sa.set_volume(i*2) ... time.sleep(1) ... >>>
Adjust OSX System Audio Volume in Python
I would like to adjust the system audio volume in OSX from a python script. This question about implementing keyboard shortcuts tells me how to do it in applescript, but I'd really like to do it from my python script without using os.system, popen, etc. Ideally I'd like to ramp up the volume slowly with some python code like this: set_volume(0) for i in range(50): set_volume(i*2) time.sleep(1)
[ "Use appscript to control the StandardAdditions scripting addition set volume command:\n>>> from osax import *\n>>> import time\n>>> sa = OSAX()\n>>> for i in range(50):\n... sa.set_volume(i*2)\n... time.sleep(1)\n... \n>>> \n\n" ]
[ 1 ]
[]
[]
[ "audio", "macos", "python", "volume" ]
stackoverflow_0002565204_audio_macos_python_volume.txt
Q: How use the google maps hand cursor in Python? I want to use the google maps hand cursor in Python but I don't know how to do it. I've downloaded the cursor but I only get to use the hand open, I also have a event that "closes" the hand when clicked but I don't know how can I change the style cursor on it. I say this because the google maps hand cursor has two style (the open and the closed hand). If you don't know how to use the other style you can also tell me how can I create another cursor where the close hand is the default style. If I have that, I only change the cursor and it's done. Thanks in advance :) A: Did you try just changing the cursor, i.e: myFrame.SetCursor(closedCursor) In the event handler for mouse-down? Then for mouse-up change it back again. myFrame is your container wx.Frame, and I suppose you already know how to load a cursor from a file. A: Use two cursors and change them on events as they need to be.
How use the google maps hand cursor in Python?
I want to use the google maps hand cursor in Python but I don't know how to do it. I've downloaded the cursor but I only get to use the hand open, I also have a event that "closes" the hand when clicked but I don't know how can I change the style cursor on it. I say this because the google maps hand cursor has two style (the open and the closed hand). If you don't know how to use the other style you can also tell me how can I create another cursor where the close hand is the default style. If I have that, I only change the cursor and it's done. Thanks in advance :)
[ "Did you try just changing the cursor, i.e:\nmyFrame.SetCursor(closedCursor)\n\nIn the event handler for mouse-down? Then for mouse-up change it back again. myFrame is your container wx.Frame, and I suppose you already know how to load a cursor from a file.\n", "Use two cursors and change them on events as they need to be.\n" ]
[ 0, 0 ]
[]
[]
[ "cursor", "python", "wxpython" ]
stackoverflow_0002565776_cursor_python_wxpython.txt
Q: Apply function to one element of a list in Python I'm looking for a concise and functional style way to apply a function to one element of a tuple and return the new tuple, in Python. For example, for the following input: inp = ("hello", "my", "friend") I would like to be able to get the following output: out = ("hello", "MY", "friend") I came up with two solutions which I'm not satisfied with. One uses a higher-order function. def apply_at(arr, func, i): return arr[0:i] + [func(arr[i])] + arr[i+1:] apply_at(inp, lambda x: x.upper(), 1) One uses list comprehensions (this one assumes the length of the tuple is known). [(a,b.upper(),c) for a,b,c in [inp]][0] Is there a better way? Thanks! A: Here is a version that works on any iterable and returns a generator: >>> inp = ("hello", "my", "friend") >>> def apply_nth(fn, n, iterable): ... return (fn(x) if i==n else x for (i,x) in enumerate(iterable)) ... >>> tuple(apply_nth(str.upper, 1, inp)) ('hello', 'MY', 'friend') You can extend this so that instead of one position you can give it a list of positions: >>> def apply_at(fn, pos_lst, iterable): ... pos_lst = set(pos_lst) ... return (fn(x) if i in pos_lst else x for (i,x) in enumerate(iterable)) ... >>> ''.join(apply_at(str.upper, [2,4,6,8], "abcdefghijklmno")) 'abCdEfGhIjklmno' A: >>> inp = "hello", "my", "friend" >>> index = 1 >>> inp[:index] + ( str.upper(inp[index]),) + inp[index + 1:] ('hello', 'MY', 'friend') Seems simple, the only thing you may need to know is that to make a single element tuple, do (elt,) A: Maybe some' like this? >>>inp = ("hello", "my", "friend") >>>out = tuple([i == 1 and x.upper() or x for (x,i) in zip(t,range(len(t)))]) >>> out ('hello', 'MY', 'friend') Note: rather than (x,i) in zip(t, range(len(t))) I should have thought of using the enumerate function : (i,x) in enumerate(t) Making it a bit more general: Rather than hard-coding the 1, we can place it in a variable. Also, by using a tuple for that purpose, we can apply the function to elements at multiple indexes. >>>inp = ("hello", "my", "friend") >>>ix = (0,2) >>>out = tuple([i in ix and x.upper() or x for (i, x) in enumerate(t)]) >>> out ('HELLO', 'my', 'FRIEND') Also, we can "replace" the zip()/enumerate() by map(), in something like out = tuple(map(lambda x,i : i == 1 and x.upper() or x, inp, range(len(inp)) ) ) Edit: (addressing comment about specifying the function to apply): Could be something as simple as: >>> f = str.upper # or whatever function taking a single argument >>> out = tuple(map(lambda x,i : i == 1 and f(x) or x, inp, range(len(inp)) ) ) Since we're talking about applying any function, we should mention the small caveat with the condition and if_true or if_false construct which is not exactly a substitute for the if/else ternary operator found in other languages. The limitation is that the function cannot return a value which is equivalent to False (None, 0, 0.0, '' for example). A suggestion to avoid this problem, is, with Python 2.5 and up, to use the true if-else ternary operator, as shown in Dave Kirby's answer (note the when_true if condition else when_false syntax of this operator) A: I commented in support of your first snippet, but here are a couple other ways for the record: (lambda (a,b,c): [a,b.upper(),c])(inp) (Won't work in Python 3.x.) And: [inp[0], inp[1].upper(), inp[2]] A: I don't understand if you want to apply a certain function to every element in the tuple that passes some test, or if you would like it to apply the function to any element present at a certain index of the tuple. So I have coded both algorithms: This is the algorithm (coded in Python) that I would use to solve this problem in a functional language like scheme: This function will identify the element identifiable by id and apply func to it and return a list with that element changed to the output of func. It will do this for every element identifiable as id: def doSomethingTo(tup, id): return tuple(doSomethingToHelper(list(tup), id)) def doSomethingToHelper(L, id): if len(L) == 0: return L elif L[0] == id: return [func(L[0])] + doSomethingToHelper(L[1:], id) else: return [L[0]] + doSomethingToHelper(L[1:], id) This algorithm will find the element at the index of the tuple and apply func to it, and stick it back into its original index in the tuple def doSomethingAt(tup, i): return tuple(doSomethingAtHelper(list(tup), i, 0)) def doSomethingAtHelper(L, index, i): if len(L) == 0: return L elif i == index: return [func(L[0])] + L[1:] else: return [L[0]] + doSomethingAtHelper(L[1:], index, i+1) A: i also like the answer that Dave Kirby gave. however, as a public service announcement, i'd like to say that this is not a typical use case for tuples -- these are data structures that originated in Python as a means to move data (parameters, arguments) to and from functions... they were not meant for the programmer to use as general array-like data structures in applications -- this is why lists exist. naturally, if you're needing the read-only/immutable feature of tuples, that is a fair argument, but given the OP question, this should've been done with lists instead -- note how there is extra code to either pull the tuple apart and put the resulting one together and/or the need to temporarily convert to a list and back.
Apply function to one element of a list in Python
I'm looking for a concise and functional style way to apply a function to one element of a tuple and return the new tuple, in Python. For example, for the following input: inp = ("hello", "my", "friend") I would like to be able to get the following output: out = ("hello", "MY", "friend") I came up with two solutions which I'm not satisfied with. One uses a higher-order function. def apply_at(arr, func, i): return arr[0:i] + [func(arr[i])] + arr[i+1:] apply_at(inp, lambda x: x.upper(), 1) One uses list comprehensions (this one assumes the length of the tuple is known). [(a,b.upper(),c) for a,b,c in [inp]][0] Is there a better way? Thanks!
[ "Here is a version that works on any iterable and returns a generator:\n>>> inp = (\"hello\", \"my\", \"friend\")\n>>> def apply_nth(fn, n, iterable):\n... return (fn(x) if i==n else x for (i,x) in enumerate(iterable))\n... \n>>> tuple(apply_nth(str.upper, 1, inp))\n('hello', 'MY', 'friend')\n\nYou can extend this so that instead of one position you can give it a list of positions:\n>>> def apply_at(fn, pos_lst, iterable):\n... pos_lst = set(pos_lst)\n... return (fn(x) if i in pos_lst else x for (i,x) in enumerate(iterable))\n... \n>>> ''.join(apply_at(str.upper, [2,4,6,8], \"abcdefghijklmno\"))\n'abCdEfGhIjklmno'\n\n", ">>> inp = \"hello\", \"my\", \"friend\"\n>>> index = 1\n>>> inp[:index] + ( str.upper(inp[index]),) + inp[index + 1:]\n('hello', 'MY', 'friend')\n\nSeems simple, the only thing you may need to know is that to make a single element tuple, do (elt,)\n", "Maybe some' like this?\n>>>inp = (\"hello\", \"my\", \"friend\")\n>>>out = tuple([i == 1 and x.upper() or x for (x,i) in zip(t,range(len(t)))])\n\n>>> out\n('hello', 'MY', 'friend')\n\nNote: rather than (x,i) in zip(t, range(len(t))) I should have thought of using the enumerate function : (i,x) in enumerate(t)\nMaking it a bit more general:\nRather than hard-coding the 1, we can place it in a variable.\nAlso, by using a tuple for that purpose, we can apply the function to elements at multiple indexes.\n>>>inp = (\"hello\", \"my\", \"friend\")\n>>>ix = (0,2)\n>>>out = tuple([i in ix and x.upper() or x for (i, x) in enumerate(t)])\n\n>>> out\n('HELLO', 'my', 'FRIEND')\n\nAlso, we can \"replace\" the zip()/enumerate() by map(), in something like\nout = tuple(map(lambda x,i : i == 1 and x.upper() or x, inp, range(len(inp)) ) )\n\n\nEdit: (addressing comment about specifying the function to apply):\nCould be something as simple as:\n>>> f = str.upper # or whatever function taking a single argument\n>>> out = tuple(map(lambda x,i : i == 1 and f(x) or x, inp, range(len(inp)) ) )\n\nSince we're talking about applying any function, we should mention the small caveat with the condition and if_true or if_false construct which is not exactly a substitute for the if/else ternary operator found in other languages. The limitation is that the function cannot return a value which is equivalent to False (None, 0, 0.0, '' for example). A suggestion to avoid this problem, is, with Python 2.5 and up, to use the true if-else ternary operator, as shown in Dave Kirby's answer (note the when_true if condition else when_false syntax of this operator)\n", "I commented in support of your first snippet, but here are a couple other ways for the record:\n(lambda (a,b,c): [a,b.upper(),c])(inp)\n\n(Won't work in Python 3.x.) And:\n[inp[0], inp[1].upper(), inp[2]]\n\n", "I don't understand if you want to apply a certain function to every element in the tuple that passes some test, or if you would like it to apply the function to any element present at a certain index of the tuple. So I have coded both algorithms:\nThis is the algorithm (coded in Python) that I would use to solve this problem in a functional language like scheme:\nThis function will identify the element identifiable by id and apply func to it and return a list with that element changed to the output of func. It will do this for every element identifiable as id:\ndef doSomethingTo(tup, id):\n return tuple(doSomethingToHelper(list(tup), id))\n\ndef doSomethingToHelper(L, id):\n if len(L) == 0:\n return L\n elif L[0] == id:\n return [func(L[0])] + doSomethingToHelper(L[1:], id)\n else:\n return [L[0]] + doSomethingToHelper(L[1:], id)\n\n\nThis algorithm will find the element at the index of the tuple and apply func to it, and stick it back into its original index in the tuple\ndef doSomethingAt(tup, i): \n return tuple(doSomethingAtHelper(list(tup), i, 0))\n\ndef doSomethingAtHelper(L, index, i):\nif len(L) == 0: \n return L\nelif i == index: \n return [func(L[0])] + L[1:]\nelse: \n return [L[0]] + doSomethingAtHelper(L[1:], index, i+1)\n\n", "i also like the answer that Dave Kirby gave. however, as a public service announcement, i'd like to say that this is not a typical use case for tuples -- these are data structures that originated in Python as a means to move data (parameters, arguments) to and from functions... they were not meant for the programmer to use as general array-like data structures in applications -- this is why lists exist. naturally, if you're needing the read-only/immutable feature of tuples, that is a fair argument, but given the OP question, this should've been done with lists instead -- note how there is extra code to either pull the tuple apart and put the resulting one together and/or the need to temporarily convert to a list and back.\n" ]
[ 7, 2, 2, 2, 0, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0002565249_list_comprehension_python.txt
Q: Q on Python serialization/deserialization What chances do I have to instantiate, keep and serialize/deserialize to/from binary data Python classes reflecting this pattern (adopted from RFC 2246 [TLS]): enum { apple, orange } VariantTag; struct { uint16 number; opaque string<0..10>; /* variable length */ } V1; struct { uint32 number; opaque string[10]; /* fixed length */ } V2; struct { select (VariantTag) { /* value of selector is implicit */ case apple: V1; /* VariantBody, tag = apple */ case orange: V2; /* VariantBody, tag = orange */ } variant_body; /* optional label on variant */ } VariantRecord; Basically I would have to define a (variant) class VariantRecord, which varies depending on the value of VariantTag. That's not that difficult. The challenge is to find a most generic way to build a class, which serializes/deserializes to and from a byte stream... Pickle, Google protocol buffer, marshal is all not an option. I made little success with having an explicit "def serialize" in my class, but I'm not very happy with it, because it's not generic enough. I hope I could express the problem. My current solution in case VariantTag = apple would look like this, but I don't like it too much import binascii import struct class VariantRecord(object): def __init__(self, number, opaque): self.number = number self.opaque = opaque def serialize(self): out = struct.pack('>HB%ds' % len(self.opaque), self.number, len(self.opaque), self.opaque) return out v = VariantRecord(10, 'Hello') print binascii.hexlify(v.serialize()) >> 000a0548656c6c6f Regards A: Two suggestions: For the variable length structure use a fixed format and just slice the result. Use struct.Struct e.g. If I've understood your formats correctly (is the length byte that appeared in your example but wasn't mentioned originally present in the other variant also?) >>> import binascii >>> import struct >>> V1 = struct.Struct(">H10p") >>> V2 = struct.Struct(">L10p") >>> def serialize(variant, n, s): if variant: return V2.pack(n,s) else: return V1.pack(n,s)[:len(s)+3] >>> print binascii.hexlify(serialize(False, 10, 'hello')) #V1 000a0568656c6c6f >>> print binascii.hexlify(serialize(True, 10, 'hello')) #V2 0000000a0568656c6c6f00000000 >>>
Q on Python serialization/deserialization
What chances do I have to instantiate, keep and serialize/deserialize to/from binary data Python classes reflecting this pattern (adopted from RFC 2246 [TLS]): enum { apple, orange } VariantTag; struct { uint16 number; opaque string<0..10>; /* variable length */ } V1; struct { uint32 number; opaque string[10]; /* fixed length */ } V2; struct { select (VariantTag) { /* value of selector is implicit */ case apple: V1; /* VariantBody, tag = apple */ case orange: V2; /* VariantBody, tag = orange */ } variant_body; /* optional label on variant */ } VariantRecord; Basically I would have to define a (variant) class VariantRecord, which varies depending on the value of VariantTag. That's not that difficult. The challenge is to find a most generic way to build a class, which serializes/deserializes to and from a byte stream... Pickle, Google protocol buffer, marshal is all not an option. I made little success with having an explicit "def serialize" in my class, but I'm not very happy with it, because it's not generic enough. I hope I could express the problem. My current solution in case VariantTag = apple would look like this, but I don't like it too much import binascii import struct class VariantRecord(object): def __init__(self, number, opaque): self.number = number self.opaque = opaque def serialize(self): out = struct.pack('>HB%ds' % len(self.opaque), self.number, len(self.opaque), self.opaque) return out v = VariantRecord(10, 'Hello') print binascii.hexlify(v.serialize()) >> 000a0548656c6c6f Regards
[ "Two suggestions:\n\nFor the variable length structure use a fixed format\nand just slice the result.\nUse struct.Struct\n\ne.g. If I've understood your formats correctly (is the length byte that appeared in your example but wasn't mentioned originally present in the other variant also?)\n>>> import binascii\n>>> import struct\n>>> V1 = struct.Struct(\">H10p\")\n>>> V2 = struct.Struct(\">L10p\")\n>>> def serialize(variant, n, s):\n if variant:\n return V2.pack(n,s)\n else:\n return V1.pack(n,s)[:len(s)+3]\n\n \n>>> print binascii.hexlify(serialize(False, 10, 'hello')) #V1\n000a0568656c6c6f\n>>> print binascii.hexlify(serialize(True, 10, 'hello')) #V2\n0000000a0568656c6c6f00000000\n>>> \n\n" ]
[ 0 ]
[]
[]
[ "binary", "python", "serialization" ]
stackoverflow_0002555705_binary_python_serialization.txt
Q: Matplotlib digit grouping (decimal separator) Basically, when generating plots with matplotlib, The scale on the y-axis goes into the millions. How do I turn on digit grouping (i.e. so that 1000000 displays as 1,000,000) or turn on the decimal separator? A: I don't think there's a built-in function to do this. (That's what i thought after i read your Q; i just checked and couldn't find one in the Documentation). In any event, it's easy to roll your own. (Below is a complete example--ie, it will generate an mpl plot with one axis having commified tick labels--although five lines of code are all you need to create custom tick labels--three (including import statement) for the function used to create the custom labels, and two lines to create the new labels and place them on the specified axis.) # first code a function to generate the axis labels you want # ie, turn numbers greater than 1000 into commified strings (12549 => 12,549) import locale locale.setlocale(locale.LC_ALL, 'en_US') fnx = lambda x : locale.format("%d", x, grouping=True) from matplotlib import pyplot as PLT import numpy as NP data = NP.random.randint(15000, 85000, 50).reshape(25, 2) x, y = data[:,0], data[:,1] fig = PLT.figure() ax1 = fig.add_subplot(111) ax1.plot(x, y, "ro") default_xtick = range(20000, 100000, 10000) # these two lines are the crux: # create the custom tick labels new_xtick = map(fnx, default_xtick) # set those labels on the axis ax1.set_xticklabels(new_xtick) PLT.show()
Matplotlib digit grouping (decimal separator)
Basically, when generating plots with matplotlib, The scale on the y-axis goes into the millions. How do I turn on digit grouping (i.e. so that 1000000 displays as 1,000,000) or turn on the decimal separator?
[ "I don't think there's a built-in function to do this. (That's what i thought after i read your Q; i just checked and couldn't find one in the Documentation). \nIn any event, it's easy to roll your own.\n(Below is a complete example--ie, it will generate an mpl plot with one axis having commified tick labels--although five lines of code are all you need to create custom tick labels--three (including import statement) for the function used to create the custom labels, and two lines to create the new labels and place them on the specified axis.)\n# first code a function to generate the axis labels you want \n# ie, turn numbers greater than 1000 into commified strings (12549 => 12,549)\n\nimport locale\nlocale.setlocale(locale.LC_ALL, 'en_US')\nfnx = lambda x : locale.format(\"%d\", x, grouping=True)\n\nfrom matplotlib import pyplot as PLT\nimport numpy as NP\n\ndata = NP.random.randint(15000, 85000, 50).reshape(25, 2)\nx, y = data[:,0], data[:,1]\n\nfig = PLT.figure()\nax1 = fig.add_subplot(111)\nax1.plot(x, y, \"ro\")\ndefault_xtick = range(20000, 100000, 10000)\n\n# these two lines are the crux:\n# create the custom tick labels\nnew_xtick = map(fnx, default_xtick)\n# set those labels on the axis\nax1.set_xticklabels(new_xtick)\n\nPLT.show()\n\n" ]
[ 3 ]
[]
[]
[ "data_visualization", "matplotlib", "python" ]
stackoverflow_0002564362_data_visualization_matplotlib_python.txt
Q: In Python, how to make data members visible to subclasses if not known when initializing an object? The title is a bit long, but it should be pretty straightforward for someone well-aware of python. I'm a python newbie. So, maybe i'm doing things in the wrong way. Suppose I have a class TreeNode class TreeNode(Node): def __init__(self, name, id): Node.__init__(self, name, id) self.children = [] and a subclass with a weight: class WeightedNode(TreeNode): def __init__(self,name, id): TreeNode.__init__(self, name, id) self.weight = 0 So far, i think I'm ok. Now, I want to add an object variable called father in TreeNode so that WeightedNode has also this member. The problem is that I don't know when initializing the object who is going to be the father. I set the father afterwards with this method in TreeNode : def set_father(self, father_node): self.father = father_node The problem is then when i'm trying to access self.father in Weighted: print 'Name %s Father %s '%(self.name, self.father.name) I obtain: AttributeError: WeightedNode instance has no attribute 'father' I thought that I could make father visible by doing something in TreeNode.__init__ but i wasn't able to find what. How can i do that ? Thanks. A: You could just initialize it with a default value: self.father = None That way the attribute will at least be recognized. And this is valid since at this point there really is no father. A: In response to your statement on Justin's answer, try this: print ' Name %s Father %s '%(str(self.name), str(self.father.name)) The str() command will get a string representation of an object even if it's None
In Python, how to make data members visible to subclasses if not known when initializing an object?
The title is a bit long, but it should be pretty straightforward for someone well-aware of python. I'm a python newbie. So, maybe i'm doing things in the wrong way. Suppose I have a class TreeNode class TreeNode(Node): def __init__(self, name, id): Node.__init__(self, name, id) self.children = [] and a subclass with a weight: class WeightedNode(TreeNode): def __init__(self,name, id): TreeNode.__init__(self, name, id) self.weight = 0 So far, i think I'm ok. Now, I want to add an object variable called father in TreeNode so that WeightedNode has also this member. The problem is that I don't know when initializing the object who is going to be the father. I set the father afterwards with this method in TreeNode : def set_father(self, father_node): self.father = father_node The problem is then when i'm trying to access self.father in Weighted: print 'Name %s Father %s '%(self.name, self.father.name) I obtain: AttributeError: WeightedNode instance has no attribute 'father' I thought that I could make father visible by doing something in TreeNode.__init__ but i wasn't able to find what. How can i do that ? Thanks.
[ "You could just initialize it with a default value:\nself.father = None\n\nThat way the attribute will at least be recognized. And this is valid since at this point there really is no father.\n", "In response to your statement on Justin's answer, try this:\nprint ' Name %s Father %s '%(str(self.name), str(self.father.name))\n\nThe str() command will get a string representation of an object even if it's None\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002566840_python.txt
Q: No module named difflib I want to execute python code from C# with following code. static void Main(string[] args) { ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile(@"F:\Script\extracter.py"); source.Execute(); } I have the problem at line source.Execute(), I got error "No module named difflib". What is wrong in my code? This is my python code (extracter.py). import re import itertools import difflib print "Hello" A: This looks like your engine does not have access to Python standard library - it does not see difflib.py. Either fix the sys.path or copy difflib.py from Python 2.6 to f:\script folder. re and itertools modules are written in C# and are part of IronPython.modules.dll - that's why importing them work.
No module named difflib
I want to execute python code from C# with following code. static void Main(string[] args) { ScriptEngine engine = Python.CreateEngine(); ScriptSource source = engine.CreateScriptSourceFromFile(@"F:\Script\extracter.py"); source.Execute(); } I have the problem at line source.Execute(), I got error "No module named difflib". What is wrong in my code? This is my python code (extracter.py). import re import itertools import difflib print "Hello"
[ "This looks like your engine does not have access to Python standard library - it does not see difflib.py. Either fix the sys.path or copy difflib.py from Python 2.6 to f:\\script folder.\nre and itertools modules are written in C# and are part of IronPython.modules.dll - that's why importing them work.\n" ]
[ 3 ]
[]
[]
[ "c#", "ironpython", "python", "scriptengine" ]
stackoverflow_0002564870_c#_ironpython_python_scriptengine.txt
Q: MacPorts manual port location I am installing one library for python from MacPorts. But macports version of the library is older than actual development svn version. Is it possible to specify a custom location for a port installation in MacPorts so I could install latest library from the developer's site? A: Have a look here, you have to install a local portfile repositories. A: If you simply want the latest version, couldn't you just not install the old version? If you are planning to build and deploy the svn version yourself and want to test it while not removing the old version, you might find virtualenv useful. It allows you to deploy a parallel Python environment with its own independent set of libraries. I'm still not clear on your requirements, so I hope the above helps somehow.
MacPorts manual port location
I am installing one library for python from MacPorts. But macports version of the library is older than actual development svn version. Is it possible to specify a custom location for a port installation in MacPorts so I could install latest library from the developer's site?
[ "Have a look here, you have to install a local portfile repositories.\n", "If you simply want the latest version, couldn't you just not install the old version?\nIf you are planning to build and deploy the svn version yourself and want to test it while not removing the old version, you might find virtualenv useful. It allows you to deploy a parallel Python environment with its own independent set of libraries.\nI'm still not clear on your requirements, so I hope the above helps somehow.\n" ]
[ 1, 0 ]
[]
[]
[ "macports", "python" ]
stackoverflow_0002566357_macports_python.txt
Q: "AttributeError: fileno" when attemping to import from pyevolve I just installed Pyevolve using easy_install and I am getting errors trying to run my first program. I first tried copy and pasting the source code of the first example but this is what I receive when I attempt to run it: Traceback (most recent call last): File "/home/corey/CTest/first_intro.py", line 3, in from pyevolve import G1DList File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/init.py", line 15, in File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/Consts.py", line 240, in import Selectors File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/Selectors.py", line 12, in File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/GPopulation.py", line 11, in File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/FunctionSlot.py", line 14, in File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/Util.py", line 20, in AttributeError: fileno I am running python 2.6 on Fedora 11 X86_64. Edit: After looking into it more if I run python from the command line it works but it only fails when I'm running IDLE. A: Have you tried to check out the Development version ? It's near of the RC1, so it is stable right now: svn co https://pyevolve.svn.sourceforge.net/svnroot/pyevolve/trunk pyevolve Your problem seems to be the paths, try uncompressing the "egg" file and put the "pyevolve" directory in the site-packages or inside your application directory.
"AttributeError: fileno" when attemping to import from pyevolve
I just installed Pyevolve using easy_install and I am getting errors trying to run my first program. I first tried copy and pasting the source code of the first example but this is what I receive when I attempt to run it: Traceback (most recent call last): File "/home/corey/CTest/first_intro.py", line 3, in from pyevolve import G1DList File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/init.py", line 15, in File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/Consts.py", line 240, in import Selectors File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/Selectors.py", line 12, in File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/GPopulation.py", line 11, in File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/FunctionSlot.py", line 14, in File "/usr/lib/python2.6/site-packages/Pyevolve-0.5-py2.6.egg/pyevolve/Util.py", line 20, in AttributeError: fileno I am running python 2.6 on Fedora 11 X86_64. Edit: After looking into it more if I run python from the command line it works but it only fails when I'm running IDLE.
[ "Have you tried to check out the Development version ? It's near of the RC1, so it is stable right now:\nsvn co https://pyevolve.svn.sourceforge.net/svnroot/pyevolve/trunk pyevolve\nYour problem seems to be the paths, try uncompressing the \"egg\" file and put the \"pyevolve\" directory in the site-packages or inside your application directory.\n" ]
[ 1 ]
[]
[]
[ "pyevolve", "python" ]
stackoverflow_0002565061_pyevolve_python.txt
Q: Python In-memory table What is the right way to forming in-memory table in python with direct lookups for rows and columns.I thought of using dict of dicts this way, class Table(dict): def __getitem__(self, key): if key not in self: self[key]={} return dict.__getitem__(self, key) table = Table() table['row1']['column1'] = 'value11' table['row1']['column2'] = 'value12' table['row2']['column1'] = 'value21' table['row2']['column2'] = 'value22' >>>table {'row1':{'column1':'value11','column2':'value12'},'row2':{'column1':'value21','column2':'value22'}} I had difficulty in looking up for values in columns. >>>'row1' in table True >>>'value11' in table['row1'].values() True Now how do I do lookup if 'column1' has 'value11' Is this method of forming tables wrong?Is there a better way to implement such tables with easier lookups?. A: I'd use an in-memory database with SQLite for this. The sqlite module is even in the standard library since Python 2.5, which means this doesn't even add much to your requirements. A: Now how do I do lookup if 'column1' has 'value11' any(arow['column1'] == 'value11' for arow in table.iteritems()) Is this method of forming tables wrong? No, it's just very "exposed", perhaps too much -- it could usefully be encapsulated in a class which exposes the methods you need, then the issue of how best to implement them does not affect all the rest of your application. Is there a better way to implement such tables with easier lookups? Once you have designed a class whose interface you'd like to use, you can experiment with very different implementation approaches and benchmark them on a workload that's representative of your usage pattern, so you can find out what's best for you (assuming table manipulation and lookup are a big part of your application's runtime, of course -- to find out, profile your app). I had similar but not identical needs in a large internal app I maintain at work, except that the row indices are integer (only the column names are strings), the column order is important, and the workload is more about "editing" the table (adding, removing, reordering rows or columns, renaming columns, etc). I started with a table exposing the functionality I needed, with the simplest rough-and-ready implementation internally (a list of dicts, plus a list of column names for the column ordering); and by now I have evolved it (independently of the actual "application-level" parts, but based on profiling and benchmarking thereof) to completely different implementations (currently based on numpy). I think you should proceed along similar lines: "clothe" your current implementation into a nice "interface" with all the methods you need, profile your app -- unless this table object is a performance bottleneck, you're done; if it is a bottleneck, you can optimize the implementation (experiment, measure, repeat;-) without disturbing any of the rest of your application. Inheriting from dict is not a good idea because you probably don't want to expose all of dict's rich functionality; plus, what you're doing is, roughly, an inefficient implementation of collections.defaultdict(dict). So, encapsulate the latter: import collections class Table(object): def __init__(self): self.d = collections.defaultdict(dict) def add(self, row, col, val): self.d[row][col] = val def get(self, row, col, default=None): return self.d[row].get(col, default) def inrow(self, row, col): return col in self.d[row] def incol(self, col, val): return any(x[col]==val for x in self.d.iteritems()) etc, etc -- write all the methods your app needs, with useful, short names, then maybe see if you can alias some of them as special methods if they're often used that way, e.g maybe (assuming Python 2.* -- requires slightly different syntax in 3.*): def __setitem__(self, (row, col), val): self.add(row, col, val) and so forth. Once you have the code working, then comes the right time for profiling, benchmarking, and -- just perhaps -- internal optimization of the implementation. A: A nested list should be able to do the job here. I would only use nested dictionaries if elements are spread thin across the grid. grid = [] for row in height: grid.append([]) for cell in width: grid[-1].append(value) Checking rows is easy: def valueInRow(value, row): return value in grid[row] Checking collumns takes a little more work, because the grid is a list of rows, not a list of collumns: def collumnIterator(collumn): height = len(grid) for row in xrange(height): yield grid[row][collumn] def valueInCollumn(value, collumn): return value in collumnIterator(collumn) A: Now how do I do lookup if 'column1' has 'value11' Are you asking about this? found= False for r in table: if table[r]['column1'] == 'value11' found= True break Is this what you're trying to do?
Python In-memory table
What is the right way to forming in-memory table in python with direct lookups for rows and columns.I thought of using dict of dicts this way, class Table(dict): def __getitem__(self, key): if key not in self: self[key]={} return dict.__getitem__(self, key) table = Table() table['row1']['column1'] = 'value11' table['row1']['column2'] = 'value12' table['row2']['column1'] = 'value21' table['row2']['column2'] = 'value22' >>>table {'row1':{'column1':'value11','column2':'value12'},'row2':{'column1':'value21','column2':'value22'}} I had difficulty in looking up for values in columns. >>>'row1' in table True >>>'value11' in table['row1'].values() True Now how do I do lookup if 'column1' has 'value11' Is this method of forming tables wrong?Is there a better way to implement such tables with easier lookups?.
[ "I'd use an in-memory database with SQLite for this. The sqlite module is even in the standard library since Python 2.5, which means this doesn't even add much to your requirements.\n", "\nNow how do I do lookup if 'column1'\n has 'value11'\n\nany(arow['column1'] == 'value11' for arow in table.iteritems())\n\nIs this method of forming tables\n wrong?\n\nNo, it's just very \"exposed\", perhaps too much -- it could usefully be encapsulated in a class which exposes the methods you need, then the issue of how best to implement them does not affect all the rest of your application.\n\nIs there a better way to implement\n such tables with easier lookups?\n\nOnce you have designed a class whose interface you'd like to use, you can experiment with very different implementation approaches and benchmark them on a workload that's representative of your usage pattern, so you can find out what's best for you (assuming table manipulation and lookup are a big part of your application's runtime, of course -- to find out, profile your app).\nI had similar but not identical needs in a large internal app I maintain at work, except that the row indices are integer (only the column names are strings), the column order is important, and the workload is more about \"editing\" the table (adding, removing, reordering rows or columns, renaming columns, etc). I started with a table exposing the functionality I needed, with the simplest rough-and-ready implementation internally (a list of dicts, plus a list of column names for the column ordering); and by now I have evolved it (independently of the actual \"application-level\" parts, but based on profiling and benchmarking thereof) to completely different implementations (currently based on numpy).\nI think you should proceed along similar lines: \"clothe\" your current implementation into a nice \"interface\" with all the methods you need, profile your app -- unless this table object is a performance bottleneck, you're done; if it is a bottleneck, you can optimize the implementation (experiment, measure, repeat;-) without disturbing any of the rest of your application.\nInheriting from dict is not a good idea because you probably don't want to expose all of dict's rich functionality; plus, what you're doing is, roughly, an inefficient implementation of collections.defaultdict(dict). So, encapsulate the latter:\nimport collections\n\nclass Table(object):\n def __init__(self):\n self.d = collections.defaultdict(dict)\n def add(self, row, col, val):\n self.d[row][col] = val\n def get(self, row, col, default=None):\n return self.d[row].get(col, default)\n def inrow(self, row, col):\n return col in self.d[row]\n def incol(self, col, val):\n return any(x[col]==val for x in self.d.iteritems())\n\netc, etc -- write all the methods your app needs, with useful, short names, then maybe see if you can alias some of them as special methods if they're often used that way, e.g maybe (assuming Python 2.* -- requires slightly different syntax in 3.*):\n def __setitem__(self, (row, col), val):\n self.add(row, col, val)\n\nand so forth. Once you have the code working, then comes the right time for profiling, benchmarking, and -- just perhaps -- internal optimization of the implementation.\n", "A nested list should be able to do the job here. I would only use nested dictionaries if elements are spread thin across the grid.\ngrid = []\nfor row in height:\n grid.append([])\n for cell in width:\n grid[-1].append(value)\n\nChecking rows is easy:\ndef valueInRow(value, row):\n return value in grid[row]\n\nChecking collumns takes a little more work, because the grid is a list of rows, not a list of collumns:\ndef collumnIterator(collumn):\n height = len(grid)\n for row in xrange(height):\n yield grid[row][collumn]\n\ndef valueInCollumn(value, collumn):\n return value in collumnIterator(collumn)\n\n", "\nNow how do I do lookup if 'column1' has 'value11' \n\nAre you asking about this?\nfound= False\nfor r in table:\n if table[r]['column1'] == 'value11'\n found= True\n break\n\nIs this what you're trying to do?\n" ]
[ 7, 7, 0, 0 ]
[]
[]
[ "python", "row" ]
stackoverflow_0002565415_python_row.txt
Q: Cassandra database, which python interface? I'm going to write the web portal using Cassandra databases. Can you advise me which python interface to use? thrift, lazygal or pycassa? Are there any benefits to use more complicated thrift then cleaner pycassa? What about performace - is the same (all of them are just the layer)? Thanks for any advice. A: Use pycassa if you don't know what to use. Use lazyboy if you want it to maintain indexes for you. It's significantly more complex.
Cassandra database, which python interface?
I'm going to write the web portal using Cassandra databases. Can you advise me which python interface to use? thrift, lazygal or pycassa? Are there any benefits to use more complicated thrift then cleaner pycassa? What about performace - is the same (all of them are just the layer)? Thanks for any advice.
[ "Use pycassa if you don't know what to use.\nUse lazyboy if you want it to maintain indexes for you. It's significantly more complex.\n" ]
[ 4 ]
[]
[]
[ "cassandra", "database", "python", "thrift" ]
stackoverflow_0002561804_cassandra_database_python_thrift.txt
Q: Python web development framework for python 3.1 user I have been learning python for some time now. While starting this "learning python" endeavor I decided to learn the latest and greatest 3.1 version of python. I regret this decision now because I wanted to try my hands on some of the python web development frameworks & it looks like many of them do not support 3.1 yet & it looks like it might take them years to support the new version of Python especially Django and TurboGears. This is really disappointing. Therefore, SO users, do you have any recommendation for a web framework for me that runs on 3.1 and supports some of the modern (I guess I will never learn ;-)) web framework features like MVC/ORM/URL Routing/Caching etc. A: How about trying Python2.7?, many of python 3.x features are backported to 2.7 recently, like OrderedDict, faster io modules, set comprehensions, dict comprehensions, etc... And Python 2.7 is running no problem at all with django 1.2 trunk version in my experience. In my opinion, learning new framework will take more time than switching from Python2.x to Python3.x, So choose one framework, and just keep using python 2.x and switch it to 3.x when the time come. A: Like the others, I would suggest you start with Python 2.6.x -- Python 2.7 will be released this summer although you can grab an alpha or beta version today. Although Python 3.x is backwards-incompatible with 2.x, Python syntax isn't going to be unrecognizable... pretty much everything is very similar to 2.x, but it's easy to break code when print changes from a statement to a function. So don't worry about Python 3 for now. As others have mentioned, you can get started right away with plenty of web frameworks that work in Python 2.x. Also, just because of the numbering, do NOT be fooled in thinking that Python 2 is obsolete in any way nor can you follow the timeline serially. In other words, Python 2.7 will be newer than both Python 3.0 and 3.1. (3.2 won't be released until the end of this year.) Again, Python 2 has NOT been EOL'd -- both 2.x and 3.x are being developed actively. The industrial world still runs on Python 2.x; the appearance of 3.x is a reminder that the next generation is here, and this is the time that all of the lower-level infrastructure and frameworks should begin their porting work so that we'll all eventually migrate. If you want to find out more about the relationships between Python 2, Python 3, and the changes/differences between the two as well as the timeline and migration, you can check out this online article I wrote earlier this year: "Python 3: The Evolution of a Programming Language" http://www.informit.com/articles/article.aspx?p=1328795 I also gave a talk on this same subject at PyCon 2010 in February. You can access the video and the slide preso here: http://us.pycon.org/2010/conference/schedule/event/29/ A: CherryPy 3.2 (still being worked on) will run on Python 3.x Bottle can also run on Python 3.x after using 2to3 on it. Easy to do and it does work. However, Bottle is not a 'complete framework' but it is easy to use. Edit: I have used Bottle in Python 3.1, stackless python 3.1 to be specific, for a game that I am slowly working on. But at work, I am just using Python 2.6 And soon I will be using Webpy. The site I work on is in PHP, but when I need to add a new feature, that I can easily separate from all the PHP code, I will do it in python. Even though I work with PHP almost everyday and use Python only a few times a month, I still can get things done faster in Python than PHP :) A: Python 2.6 and Python 3.1 are really not all that different, I simply suggest you learn both, especially since both branches of Python are going to coexist for a while... so best to just learn the slight differences. The document "What's New in Python 3.0" explains most of the differences between 2.6 and 3.0. A: There is ( are) actually a Django port to Py3k. http://bitbucket.org/loewis/django-3k/ I can also remember quite good of having read a thread about a University project of porting Django to py3k, on the django-developers mailing-list, but I can't find the thread at the moment. EDIT Oh here it is: https://bitbucket.org/fiji/django-3k/ The project is lead by students at the University of Toronto. :-) ENDEDIT Querying for something like "Django py3k port" brings up some useful results. Also look at these URLs: http://wiki.python.org/moin/PortingDjangoTo3k http://groups.google.com/group/django-developers/browse_thread/thread/bf9d8808ee5aadb4/ccceb8901addceff?lnk=gst&q=django++port+py3k#ccceb8901addceff
Python web development framework for python 3.1 user
I have been learning python for some time now. While starting this "learning python" endeavor I decided to learn the latest and greatest 3.1 version of python. I regret this decision now because I wanted to try my hands on some of the python web development frameworks & it looks like many of them do not support 3.1 yet & it looks like it might take them years to support the new version of Python especially Django and TurboGears. This is really disappointing. Therefore, SO users, do you have any recommendation for a web framework for me that runs on 3.1 and supports some of the modern (I guess I will never learn ;-)) web framework features like MVC/ORM/URL Routing/Caching etc.
[ "How about trying Python2.7?, many of python 3.x features are backported to 2.7 recently, like OrderedDict, faster io modules, set comprehensions, dict comprehensions, etc...\nAnd Python 2.7 is running no problem at all with django 1.2 trunk version in my experience.\nIn my opinion, learning new framework will take more time than switching from Python2.x to Python3.x, So choose one framework, and just keep using python 2.x and switch it to 3.x when the time come.\n", "Like the others, I would suggest you start with Python 2.6.x -- Python 2.7 will be released this summer although you can grab an alpha or beta version today.\nAlthough Python 3.x is backwards-incompatible with 2.x, Python syntax isn't going to be unrecognizable... pretty much everything is very similar to 2.x, but it's easy to break code when print changes from a statement to a function. So don't worry about Python 3 for now. As others have mentioned, you can get started right away with plenty of web frameworks that work in Python 2.x.\nAlso, just because of the numbering, do NOT be fooled in thinking that Python 2 is obsolete in any way nor can you follow the timeline serially. In other words, Python 2.7 will be newer than both Python 3.0 and 3.1. (3.2 won't be released until the end of this year.) Again, Python 2 has NOT been EOL'd -- both 2.x and 3.x are being developed actively.\nThe industrial world still runs on Python 2.x; the appearance of 3.x is a reminder that the next generation is here, and this is the time that all of the lower-level infrastructure and frameworks should begin their porting work so that we'll all eventually migrate.\nIf you want to find out more about the relationships between Python 2, Python 3, and the changes/differences between the two as well as the timeline and migration, you can check out this online article I wrote earlier this year:\n\"Python 3: The Evolution of a Programming Language\"\nhttp://www.informit.com/articles/article.aspx?p=1328795\nI also gave a talk on this same subject at PyCon 2010 in February. You can access the video and the slide preso here:\nhttp://us.pycon.org/2010/conference/schedule/event/29/\n", "CherryPy 3.2 (still being worked on) will run on Python 3.x\nBottle can also run on Python 3.x after using 2to3 on it. Easy to do and it does work. However, Bottle is not a 'complete framework' but it is easy to use.\nEdit:\nI have used Bottle in Python 3.1, stackless python 3.1 to be specific, for a game that I am slowly working on. But at work, I am just using Python 2.6 And soon I will be using Webpy. \nThe site I work on is in PHP, but when I need to add a new feature, that I can easily separate from all the PHP code, I will do it in python. Even though I work with PHP almost everyday and use Python only a few times a month, I still can get things done faster in Python than PHP :) \n", "Python 2.6 and Python 3.1 are really not all that different, I simply suggest you learn both, especially since both branches of Python are going to coexist for a while... so best to just learn the slight differences. The document \"What's New in Python 3.0\" explains most of the differences between 2.6 and 3.0.\n", "There is ( are) actually a Django port to Py3k.\nhttp://bitbucket.org/loewis/django-3k/\nI can also remember quite good of having read a thread about a University project of porting Django to py3k, on the django-developers mailing-list, but I can't find the thread at the moment.\nEDIT\nOh here it is:\nhttps://bitbucket.org/fiji/django-3k/\nThe project is lead by students at the University of Toronto. :-)\nENDEDIT\nQuerying for something like \"Django py3k port\" brings up some useful results.\nAlso look at these URLs:\n\nhttp://wiki.python.org/moin/PortingDjangoTo3k\nhttp://groups.google.com/group/django-developers/browse_thread/thread/bf9d8808ee5aadb4/ccceb8901addceff?lnk=gst&q=django++port+py3k#ccceb8901addceff\n\n" ]
[ 5, 3, 2, 1, 1 ]
[]
[]
[ "python", "web_frameworks" ]
stackoverflow_0002564822_python_web_frameworks.txt
Q: Decorator for determining HTTP response from a view I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far: from django.shortcuts import render_to_response from django.http import HttpResponse from django.template.loader import render_to_string def raw_response(template): def wrap(view): def response(request,*args,**kwargs): if request.method == "GET": try: if request.GET['raw'] == "1": render = HttpResponse(render_to_string(template,{}),content_type="text/plain") return render except Exception: render = render_to_response(template,{}) return render return response return wrap Currently, the {} is there just as a place holder. Ultimately, I'd like to be able to pass a dict like this: @raw_response('my_template_name.html') def view_name(request): render({"x":42}) Any assistance is appreciated. A: You just need to call view from within your decorator and use the context returned from that. if request.method == "GET": context = view(*args, **kwargs) try: if request.GET['raw'] == "1": render = HttpResponse( render_to_string(template, context), content_type="text/plain" ) return render and so on. Although I'm not sure what's supposed to happen if raw is not 1. A: Have your real view method return something sensible (a context dict in this case) and call it. def raw_response(template): def wrap(view): def response(request, *args, **kwargs): context = view(request, *args, **kwargs) if request.method == 'GET' and request.GET.get('raw', '0') == '1': return HttpResponse(render_to_string(template, context), content_type='text/plain') # POST or not raw return render_to_response(template, context) return response return wrap @raw_response('my_template_name.html') def view_name(request): return {'x': 42}
Decorator for determining HTTP response from a view
I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far: from django.shortcuts import render_to_response from django.http import HttpResponse from django.template.loader import render_to_string def raw_response(template): def wrap(view): def response(request,*args,**kwargs): if request.method == "GET": try: if request.GET['raw'] == "1": render = HttpResponse(render_to_string(template,{}),content_type="text/plain") return render except Exception: render = render_to_response(template,{}) return render return response return wrap Currently, the {} is there just as a place holder. Ultimately, I'd like to be able to pass a dict like this: @raw_response('my_template_name.html') def view_name(request): render({"x":42}) Any assistance is appreciated.
[ "You just need to call view from within your decorator and use the context returned from that.\nif request.method == \"GET\":\n context = view(*args, **kwargs)\n try:\n if request.GET['raw'] == \"1\":\n render = HttpResponse(\n render_to_string(template, context),\n content_type=\"text/plain\"\n )\n return render\n\nand so on. Although I'm not sure what's supposed to happen if raw is not 1.\n", "Have your real view method return something sensible (a context dict in this case) and call it.\ndef raw_response(template):\n def wrap(view):\n def response(request, *args, **kwargs):\n context = view(request, *args, **kwargs)\n if request.method == 'GET' and request.GET.get('raw', '0') == '1':\n return HttpResponse(render_to_string(template, context),\n content_type='text/plain')\n # POST or not raw\n return render_to_response(template, context)\n return response\n return wrap\n\n@raw_response('my_template_name.html')\ndef view_name(request):\n return {'x': 42}\n\n" ]
[ 0, 0 ]
[]
[]
[ "decorator", "django", "python" ]
stackoverflow_0002567570_decorator_django_python.txt
Q: Regex matching very slow I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format). I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks. So, my current pattern is BT.*?\((.*?)\).*?ET (with DOTMATCHALL set) to match something like: BT /F13 12 Tf 288 720 Td (ABC) Tj ET The only bit I want is the text ABC in the brackets. The above is only formatted like that to make it clear to see. In the deflated text it may be all in one line, it may not be. There is no gurantee that the BT/ET will be at the start of a line. There may be spaces and text before/after the bracketed section, there may not be. There will however, be only one bracketed section per BT/ET block. The above pattern works, but is really slow, I assume it is because the regex library is failing to match the pattern that matches the text between BT and the (ABC) many times. The regex is pre-compiled in an attempt to speed it up, but it seems negligible. How may I speed this up? A: How many of these blocks might appear in a document? Often slow Regex execution is the result of catastrophic backtracking, as described here: http://www.regular-expressions.info/catastrophic.html I don't know what regex technology you're using, but you could try to use lookaround assertions, as described here: http://www.regular-expressions.info/lookaround.html These allow you to first just match what you want, ABC inside parentheses, and then validate that it is preceded by some value and followed by some other value. A: Are you sure the regex is correct and pulls out ABC as a match? What language's regex engine is this? Using my regular expression debugger shows that: "BT.*?((.*?)).*?ET" doesn't pull out ABC and in fact must find the string 'ET' then backtrack back to find everything else. "BT.*?\\((.*?)\\).*?ET" works as expected with a single pass left to right. A: You can't just parse the PDF with a regex to extract the text. In most cases the text in inside compressed binary blobs or encoded. A PDF with the text shown like this is very much the exception. A: There's not really enough info for a definite answer--or maybe you're assuming we know more about PDF than you do. Are there always parenthesized chunks inside these BT...ET sections? Is there always only one of them? Is the BT or ET always at the beginning of a line? If so, I would suggest (?m)^BT[^()]*\((.*?)\)[^()]*?^ET If I knew how PDF represented literal parentheses, I could probably come up with something more efficient. EDIT: According to the PDF spec, literal parentheses have to be escaped with a backslash, and there are a bunch of other backslash-escape sequences. So try this: (?s)\bBT\b[^()]*\(((?:[^()\\]*(?:\\.[^()\\]*)*))\) This part--[^()\\]*(?:\\.[^()\\]*)*--matches a block of text which may contain escaped characters (including parens), but not unescaped parens. I know it looks ugly, but it's the most efficient way, since Python doesn't support atomic groups or possessive quantifiers. (?s) allows . to match newlines, and \bBT\b makes sure the BT isn't part of a longer "word". I'm reasonably confident that this is all I need to match all of the actual text content, so I don't bother matching the stuff after the closing paren. A: here's one without regex. simple string parsing using Python internals. >>> xtract=""" ... BT ... /F13 12 Tf ... 288 720 Td ... (ABC) Tj ... ET ... ... """ >>> for chunk in xtract.split("ET"): ... if "BT" in chunk: ... for brace in chunk.split(")"): ... if "(" in brace: ... print brace[brace.find("(")+1:] ... ABC A: Since there will be only one bracketed expression between a BT and an ET, you could try the following regular expression for speed: r"(?s)\bBT\b[^(]*\(([^)]*)\).*?\bET\b"
Regex matching very slow
I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format). I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks. So, my current pattern is BT.*?\((.*?)\).*?ET (with DOTMATCHALL set) to match something like: BT /F13 12 Tf 288 720 Td (ABC) Tj ET The only bit I want is the text ABC in the brackets. The above is only formatted like that to make it clear to see. In the deflated text it may be all in one line, it may not be. There is no gurantee that the BT/ET will be at the start of a line. There may be spaces and text before/after the bracketed section, there may not be. There will however, be only one bracketed section per BT/ET block. The above pattern works, but is really slow, I assume it is because the regex library is failing to match the pattern that matches the text between BT and the (ABC) many times. The regex is pre-compiled in an attempt to speed it up, but it seems negligible. How may I speed this up?
[ "How many of these blocks might appear in a document?\nOften slow Regex execution is the result of catastrophic backtracking, as described here: http://www.regular-expressions.info/catastrophic.html\nI don't know what regex technology you're using, but you could try to use lookaround assertions, as described here:\nhttp://www.regular-expressions.info/lookaround.html\nThese allow you to first just match what you want, ABC inside parentheses, and then validate that it is preceded by some value and followed by some other value.\n", "Are you sure the regex is correct and pulls out ABC as a match? What language's regex engine is this? Using my regular expression debugger shows that:\n\"BT.*?((.*?)).*?ET\" doesn't pull out ABC and in fact must find the string 'ET' then backtrack back to find everything else.\n\"BT.*?\\\\((.*?)\\\\).*?ET\" works as expected with a single pass left to right.\n", "You can't just parse the PDF with a regex to extract the text. In most cases the text in inside compressed binary blobs or encoded. A PDF with the text shown like this is very much the exception.\n", "There's not really enough info for a definite answer--or maybe you're assuming we know more about PDF than you do. Are there always parenthesized chunks inside these BT...ET sections? Is there always only one of them? Is the BT or ET always at the beginning of a line? If so, I would suggest\n(?m)^BT[^()]*\\((.*?)\\)[^()]*?^ET\n\nIf I knew how PDF represented literal parentheses, I could probably come up with something more efficient.\nEDIT: According to the PDF spec, literal parentheses have to be escaped with a backslash, and there are a bunch of other backslash-escape sequences. So try this:\n(?s)\\bBT\\b[^()]*\\(((?:[^()\\\\]*(?:\\\\.[^()\\\\]*)*))\\)\n\nThis part--[^()\\\\]*(?:\\\\.[^()\\\\]*)*--matches a block of text which may contain escaped characters (including parens), but not unescaped parens. I know it looks ugly, but it's the most efficient way, since Python doesn't support atomic groups or possessive quantifiers.\n(?s) allows . to match newlines, and \\bBT\\b makes sure the BT isn't part of a longer \"word\". I'm reasonably confident that this is all I need to match all of the actual text content, so I don't bother matching the stuff after the closing paren.\n", "here's one without regex. simple string parsing using Python internals.\n>>> xtract=\"\"\"\n... BT\n... /F13 12 Tf\n... 288 720 Td\n... (ABC) Tj\n... ET\n...\n... \"\"\"\n>>> for chunk in xtract.split(\"ET\"):\n... if \"BT\" in chunk:\n... for brace in chunk.split(\")\"):\n... if \"(\" in brace:\n... print brace[brace.find(\"(\")+1:]\n...\nABC\n\n", "Since there will be only one bracketed expression between a BT and an ET, you could try the following regular expression for speed:\nr\"(?s)\\bBT\\b[^(]*\\(([^)]*)\\).*?\\bET\\b\"\n\n" ]
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "pdf", "python", "regex" ]
stackoverflow_0002563329_pdf_python_regex.txt
Q: Python class structure ... prep() method? We have a metaclass, a class, and a child class for an alert system: class AlertMeta(type): """ Metaclass for all alerts Reads attrs and organizes AlertMessageType data """ def __new__(cls, base, name, attrs): new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs) # do stuff to new_class return new_class class BaseAlert(object): """ BaseAlert objects should be instantiated in order to create new AlertItems. Alert objects have classmethods for dequeue (to batch AlertItems) and register (for associated a user to an AlertType and AlertMessageType) If the __init__ function recieves 'dequeue=True' as a kwarg, then all other arguments will be ignored and the Alert will check for messages to send """ __metaclass__ = AlertMeta def __init__(self, **kwargs): dequeue = kwargs.pop('dequeue',None) if kwargs: raise ValueError('Unexpected keyword arguments: %s' % kwargs) if dequeue: self.dequeue() else: # Do Normal init stuff def dequeue(self): """ Pop batched AlertItems """ # Dequeue from a custom queue class CustomAlert(BaseAlert): def __init__(self,**kwargs): # prepare custom init data super(BaseAlert, self).__init__(**kwargs) We would like to be able to make child classes of BaseAlert (CustomAlert) that allow us to run dequeue and to be able to run their own __init__ code. We think there are three ways to do this: Add a prep() method that returns True in the BaseAlert and is called by __init__. Child classes could define their own prep() methods. Make dequeue() a class method - however, alot of what dequeue() does requires non-class methods - so we'd have to make those class methods as well. Create a new class for dealing with the queue. Would this class extend BaseAlert? Is there a standard way of handling this type of situation? A: For our particular issue, we're making dequeue() a classmethod.
Python class structure ... prep() method?
We have a metaclass, a class, and a child class for an alert system: class AlertMeta(type): """ Metaclass for all alerts Reads attrs and organizes AlertMessageType data """ def __new__(cls, base, name, attrs): new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs) # do stuff to new_class return new_class class BaseAlert(object): """ BaseAlert objects should be instantiated in order to create new AlertItems. Alert objects have classmethods for dequeue (to batch AlertItems) and register (for associated a user to an AlertType and AlertMessageType) If the __init__ function recieves 'dequeue=True' as a kwarg, then all other arguments will be ignored and the Alert will check for messages to send """ __metaclass__ = AlertMeta def __init__(self, **kwargs): dequeue = kwargs.pop('dequeue',None) if kwargs: raise ValueError('Unexpected keyword arguments: %s' % kwargs) if dequeue: self.dequeue() else: # Do Normal init stuff def dequeue(self): """ Pop batched AlertItems """ # Dequeue from a custom queue class CustomAlert(BaseAlert): def __init__(self,**kwargs): # prepare custom init data super(BaseAlert, self).__init__(**kwargs) We would like to be able to make child classes of BaseAlert (CustomAlert) that allow us to run dequeue and to be able to run their own __init__ code. We think there are three ways to do this: Add a prep() method that returns True in the BaseAlert and is called by __init__. Child classes could define their own prep() methods. Make dequeue() a class method - however, alot of what dequeue() does requires non-class methods - so we'd have to make those class methods as well. Create a new class for dealing with the queue. Would this class extend BaseAlert? Is there a standard way of handling this type of situation?
[ "For our particular issue, we're making dequeue() a classmethod.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002567238_python.txt
Q: Nested generator functions in python Consider a tuple v = (a,b,c) and a generator function generate(x) which receives an item from the tuple and generates several options for each item. What is the pythonic way of generating a set of all the possible combinations of the result of generate(x) on each item in the tuple? I could do this: v = (a,b,c) for d in generate(v[0]): for e in generate(v[1]): for f in generate(v[2]): print d,e,f but that's just ugly, plus I need a generic solution. A: Python 2.6 has the function itertools.product() that does what you want: import itertools v = (a, b, c) for d, e, f in itertools.product(*(generate(x) for x in v)): print d, e, f From the docs: Cartesian product of input iterables. Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
Nested generator functions in python
Consider a tuple v = (a,b,c) and a generator function generate(x) which receives an item from the tuple and generates several options for each item. What is the pythonic way of generating a set of all the possible combinations of the result of generate(x) on each item in the tuple? I could do this: v = (a,b,c) for d in generate(v[0]): for e in generate(v[1]): for f in generate(v[2]): print d,e,f but that's just ugly, plus I need a generic solution.
[ "Python 2.6 has the function itertools.product() that does what you want:\nimport itertools\nv = (a, b, c)\nfor d, e, f in itertools.product(*(generate(x) for x in v)):\n print d, e, f\n\nFrom the docs:\n\nCartesian product of input iterables.\nEquivalent to nested for-loops in a\n generator expression. For example,\n product(A, B) returns the same as\n ((x,y) for x in A for y in B).\n\n" ]
[ 8 ]
[]
[]
[ "generator", "list_comprehension", "python" ]
stackoverflow_0002568396_generator_list_comprehension_python.txt
Q: Avoiding thumbnail name collisions with sorl-thumbnail Understanding that I should probably just dig into the source to come up with a solution, I'm wondering if anyone has come up with a tactic for dealing with this. In my project, I have a lot of images being generated outside of the application. I'm isolating them on the filesystem based on a model's pk. For example, a model instance with a pk of 121 might have the following images: .../src_pics/1/2/1/img.1.jpg .../src_pics/1/2/1/img.2.jpg ... .../src_pics/1/2/1/img.27.jpg Since the image filenames themselves are not guaranteed to be unique, I'm looking for a way to inform sorl (at runtime) that I'd like to prefix thumbs for this model with the instance pk value. Is this even possible without patching sorl? A: Ah hah. Well it looks like the solution was staring me in the face the whole time. http://thumbnail.sorl.net/docs/#this-just-doesn-t-cover-my-cravings Looks like I'm going to subclass sorl.thumbnail.main.DjangoThumbnail and re-implement the _get_relative_thumbnail method to allow me to inject a template driven prefix for the thumbnail filename.
Avoiding thumbnail name collisions with sorl-thumbnail
Understanding that I should probably just dig into the source to come up with a solution, I'm wondering if anyone has come up with a tactic for dealing with this. In my project, I have a lot of images being generated outside of the application. I'm isolating them on the filesystem based on a model's pk. For example, a model instance with a pk of 121 might have the following images: .../src_pics/1/2/1/img.1.jpg .../src_pics/1/2/1/img.2.jpg ... .../src_pics/1/2/1/img.27.jpg Since the image filenames themselves are not guaranteed to be unique, I'm looking for a way to inform sorl (at runtime) that I'd like to prefix thumbs for this model with the instance pk value. Is this even possible without patching sorl?
[ "Ah hah.\nWell it looks like the solution was staring me in the face the whole time.\nhttp://thumbnail.sorl.net/docs/#this-just-doesn-t-cover-my-cravings\nLooks like I'm going to subclass sorl.thumbnail.main.DjangoThumbnail and re-implement the _get_relative_thumbnail method to allow me to inject a template driven prefix for the thumbnail filename.\n" ]
[ 1 ]
[]
[]
[ "django", "python", "sorl_thumbnail" ]
stackoverflow_0002568134_django_python_sorl_thumbnail.txt
Q: Subprocess statement works in python console but not work in Serverdensity plugin? in the python console the following statement works perfectly fine (i guess using eval that way is not really good, but its just for testing purpose in this case and will be replaced with proper parsing) $ python >>> import subprocess >>> r = subprocess.Popen(['/pathto/plugin1.rb'], stdout=subprocess.PIPE, close_fds=True).communicate()[0] >>> data = eval(r) >>> data {'test': 1} when i convert this into a Serverdensity plugin however it keeps crashing the agent.py daemon everytime it executes the plugin. i was able to narrow it down to the subprocess line but could not find out why. exception catching did not seem to work also. here how the plugin looks like: class plugin1: def run(self): r = subprocess.Popen(['/pathto/plugin1.rb'], stdout=subprocess.PIPE, close_fds=True).communicate()[0] data = eval(r) return data I'm quite new to work with python and cant really figure out why this wont work. Thanks a lot for ideas :) A: Do you have subprocess imported in the module? Also what error are you getting could you post the error message ? A: After switching my dev box (maybe because of the different python version?) i finally was able to get some proper error output. Then it was rather simple: I really just needed to import the missing subprocess module. For who is interested in the solution: http://github.com/maxigs/Serverdensity-Wrapper-Plugin/blob/master/ruby_plugin.py Not quite production ready yet, but works already for save input
Subprocess statement works in python console but not work in Serverdensity plugin?
in the python console the following statement works perfectly fine (i guess using eval that way is not really good, but its just for testing purpose in this case and will be replaced with proper parsing) $ python >>> import subprocess >>> r = subprocess.Popen(['/pathto/plugin1.rb'], stdout=subprocess.PIPE, close_fds=True).communicate()[0] >>> data = eval(r) >>> data {'test': 1} when i convert this into a Serverdensity plugin however it keeps crashing the agent.py daemon everytime it executes the plugin. i was able to narrow it down to the subprocess line but could not find out why. exception catching did not seem to work also. here how the plugin looks like: class plugin1: def run(self): r = subprocess.Popen(['/pathto/plugin1.rb'], stdout=subprocess.PIPE, close_fds=True).communicate()[0] data = eval(r) return data I'm quite new to work with python and cant really figure out why this wont work. Thanks a lot for ideas :)
[ "Do you have subprocess imported in the module? Also what error are you getting could you post the error message ?\n", "After switching my dev box (maybe because of the different python version?) i finally was able to get some proper error output.\nThen it was rather simple: I really just needed to import the missing subprocess module.\nFor who is interested in the solution:\nhttp://github.com/maxigs/Serverdensity-Wrapper-Plugin/blob/master/ruby_plugin.py\nNot quite production ready yet, but works already for save input\n" ]
[ 0, 0 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0002560754_popen_python_subprocess.txt
Q: Python: why does `random.randint(a, b)` return a range inclusive of `b`? It has always seemed strange to me that random.randint(a, b) would return an integer in the range [a, b], instead of [a, b-1] like range(...). Is there any reason for this apparent inconsistency? A: I tried to get to the bottom of this by examining some old sources. I suspected that randint was implemented before Python's long integer: meaning that if you wanted a random number that included INT_MAX, you would have needed to call random.randrange(0, INT_MAX + 1) which would have overflowed and resulted in arguments of (0, 0) or (0, INT_MIN) depending. However, looking as far back as even the Python 1.5.2 sources, in Lib/whrandom.py we see: # # Get a random integer in the range [a, b] including both end points. # (Deprecated; use randrange below.) # def randint(self, a, b): return self.randrange(a, b+1) whrandom.randint was continued to be deprecated in 2.0, 2.1, 2.2, and 2.3; but random.randint was marked as deprecated in 2.1, although no longer marked as deprecated in 2.2. Also, random.py from version 2.1 is the first to note in random.randint's docstring: def randrange(self, start, stop=None, step=1, int=int, default=None): """Choose a random item from range(start, stop[, step]). This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. Do not supply the 'int' and 'default' arguments. """ The only available source older than that is the 0.9.1 source, and as far as I can tell, randint was not implemented at that point. Thus, I conclude that the reasoning for randint including the endpoint is known to only Guido himself at this point; given the docstring from Python 2.1, it sounds like the reason may have been a simple mistake. A: I guess random.randint was just the first attempt at implementing this feature. It seems that the Python developers also felt that this was a problem, which is why in v1.5.2 they added another method randrange with more standard parameters: random.randrange([start], stop[, step]) Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object. You can use randrange instead of randint to avoid surprising people. On the other hand, in many situations where the problem is phrased as 'choose a random number between 1 and 6' it might be more natural to use randint(1, 6) instead of writing randrange(1, 7) or randrange(min, max + 1). A: This is speculation, but normal human usage of 'give me a random number from a to b' is inclusive. Implementing it that way sort of makes sense, given Python's general philosophy of being a more human-readable language. A: I don't think there's a reason for that. But at least it's documented.
Python: why does `random.randint(a, b)` return a range inclusive of `b`?
It has always seemed strange to me that random.randint(a, b) would return an integer in the range [a, b], instead of [a, b-1] like range(...). Is there any reason for this apparent inconsistency?
[ "I tried to get to the bottom of this by examining some old sources. I suspected that randint was implemented before Python's long integer: meaning that if you wanted a random number that included INT_MAX, you would have needed to call random.randrange(0, INT_MAX + 1) which would have overflowed and resulted in arguments of (0, 0) or (0, INT_MIN) depending.\nHowever, looking as far back as even the Python 1.5.2 sources, in Lib/whrandom.py we see:\n#\n# Get a random integer in the range [a, b] including both end points.\n# (Deprecated; use randrange below.)\n#\ndef randint(self, a, b):\n return self.randrange(a, b+1)\n\nwhrandom.randint was continued to be deprecated in 2.0, 2.1, 2.2, and 2.3; but random.randint was marked as deprecated in 2.1, although no longer marked as deprecated in 2.2.\nAlso, random.py from version 2.1 is the first to note in random.randint's docstring:\ndef randrange(self, start, stop=None, step=1, int=int, default=None):\n \"\"\"Choose a random item from range(start, stop[, step]).\n\n This fixes the problem with randint() which includes the\n endpoint; in Python this is usually not what you want.\n Do not supply the 'int' and 'default' arguments.\n \"\"\"\n\nThe only available source older than that is the 0.9.1 source, and as far as I can tell, randint was not implemented at that point.\nThus, I conclude that the reasoning for randint including the endpoint is known to only Guido himself at this point; given the docstring from Python 2.1, it sounds like the reason may have been a simple mistake.\n", "I guess random.randint was just the first attempt at implementing this feature. It seems that the Python developers also felt that this was a problem, which is why in v1.5.2 they added another method randrange with more standard parameters:\n\nrandom.randrange([start], stop[, step])\n\nReturn a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.\n\nYou can use randrange instead of randint to avoid surprising people.\nOn the other hand, in many situations where the problem is phrased as 'choose a random number between 1 and 6' it might be more natural to use randint(1, 6) instead of writing randrange(1, 7) or randrange(min, max + 1).\n", "This is speculation, but normal human usage of 'give me a random number from a to b' is inclusive. Implementing it that way sort of makes sense, given Python's general philosophy of being a more human-readable language.\n", "I don't think there's a reason for that. But at least it's documented.\n" ]
[ 92, 16, 9, 3 ]
[]
[]
[ "boundary", "integer", "python", "random" ]
stackoverflow_0002568783_boundary_integer_python_random.txt
Q: urllib2 in Python 2.6.4: Any way to override windows hosts file? I am using the urllib2 module in Python 2.6.4, running in Windows XP, to access a URL. I am making a post request, that does not involve cookies or https or anything too complicated. The domain is redirected in my C:\WINDOWS\system32\drivers\etc\hosts file. However, I would like the request from urllib2 to go to the "real" domain and ignore the entry in the hosts file. Is there any easy and practical way to do this? I would prefer if the request has the domain name in it, for example: GET www.example.com/foo.html rather than GET 123.45.67.89/foo.html Forget about that last part if you want. I don't need to be that specific about what goes in the header. A: Connect to the IP address and pass the Host header manually.
urllib2 in Python 2.6.4: Any way to override windows hosts file?
I am using the urllib2 module in Python 2.6.4, running in Windows XP, to access a URL. I am making a post request, that does not involve cookies or https or anything too complicated. The domain is redirected in my C:\WINDOWS\system32\drivers\etc\hosts file. However, I would like the request from urllib2 to go to the "real" domain and ignore the entry in the hosts file. Is there any easy and practical way to do this? I would prefer if the request has the domain name in it, for example: GET www.example.com/foo.html rather than GET 123.45.67.89/foo.html Forget about that last part if you want. I don't need to be that specific about what goes in the header.
[ "Connect to the IP address and pass the Host header manually.\n" ]
[ 5 ]
[]
[]
[ "hosts", "ip", "python", "urllib2", "windows" ]
stackoverflow_0002569155_hosts_ip_python_urllib2_windows.txt
Q: Using pam_python in a script running with mod_python I would like to develop a web interface to allow users of a Linux system to do certain tasks related to their account. I decided to write the backend of the site using Python and mod_python on Apache. To authenticate the users, I thought I could use python_pam to query the PAM service. I adapted the example bundled with the module and got this: # out is the output stream used to print debug def auth(username, password, out): def pam_conv(aut, query_list, user_data): out.write("Query list: " + str(query_list) + "\n") # List to store the responses to the different queries resp = [] for item in query_list: query, qtype = item # If PAM asks for an input, give the password if qtype == PAM.PAM_PROMPT_ECHO_ON or qtype == PAM.PAM_PROMPT_ECHO_OFF: resp.append((str(password), 0)) elif qtype == PAM.PAM_PROMPT_ERROR_MSG or qtype == PAM.PAM_PROMPT_TEXT_INFO: resp.append(('', 0)) out.write("Our response: " + str(resp) + "\n") return resp # If username of password is undefined, fail if username is None or password is None: return False service = 'login' pam_ = PAM.pam() pam_.start(service) # Set the username pam_.set_item(PAM.PAM_USER, str(username)) # Set the conversation callback pam_.set_item(PAM.PAM_CONV, pam_conv) try: pam_.authenticate() pam_.acct_mgmt() except PAM.error, resp: out.write("Error: " + str(resp) + "\n") return False except: return False # If we get here, the authentication worked return True My problem is that this function does not behave the same whether I use it in a simple script or through mod_python. To illustrate this, I wrote these simple cases: my_username = "markys" my_good_password = "lalala" my_bad_password = "lololo" def handler(req): req.content_type = "text/plain" req.write("1- " + str(auth(my_username,my_good_password,req) + "\n")) req.write("2- " + str(auth(my_username,my_bad_password,req) + "\n")) return apache.OK if __name__ == "__main__": print "1- " + str(auth(my_username,my_good_password,sys.__stdout__)) print "2- " + str(auth(my_username,my_bad_password,sys.__stdout__)) The result from the script is : Query list: [('Password: ', 1)] Our response: [('lalala', 0)] 1- True Query list: [('Password: ', 1)] Our response: [('lololo', 0)] Error: ('Authentication failure', 7) 2- False but the result from mod_python is : Query list: [('Password: ', 1)] Our response: [('lalala', 0)] Error: ('Authentication failure', 7) 1- False Query list: [('Password: ', 1)] Our response: [('lololo', 0)] Error: ('Authentication failure', 7) 2- False I don't understand why the auth function does not return the same value given the same inputs. Any idea where I got this wrong ? Here is the original script, if that could help you. Thanks a lot ! EDIT: All right I found the error. I was running the script as root. mod_python was running the script as the webserver's user. Only root has the right to read shadow. I am not sure how I will circumvent this, but at least now I know what is the problem ! A: It seems like you have to enable Apache to use PAM authentication. Take a look at this site: http://www.debianhelp.co.uk/apachepam.htm You might want to take a look at this site too : http://inming.net/?p=86
Using pam_python in a script running with mod_python
I would like to develop a web interface to allow users of a Linux system to do certain tasks related to their account. I decided to write the backend of the site using Python and mod_python on Apache. To authenticate the users, I thought I could use python_pam to query the PAM service. I adapted the example bundled with the module and got this: # out is the output stream used to print debug def auth(username, password, out): def pam_conv(aut, query_list, user_data): out.write("Query list: " + str(query_list) + "\n") # List to store the responses to the different queries resp = [] for item in query_list: query, qtype = item # If PAM asks for an input, give the password if qtype == PAM.PAM_PROMPT_ECHO_ON or qtype == PAM.PAM_PROMPT_ECHO_OFF: resp.append((str(password), 0)) elif qtype == PAM.PAM_PROMPT_ERROR_MSG or qtype == PAM.PAM_PROMPT_TEXT_INFO: resp.append(('', 0)) out.write("Our response: " + str(resp) + "\n") return resp # If username of password is undefined, fail if username is None or password is None: return False service = 'login' pam_ = PAM.pam() pam_.start(service) # Set the username pam_.set_item(PAM.PAM_USER, str(username)) # Set the conversation callback pam_.set_item(PAM.PAM_CONV, pam_conv) try: pam_.authenticate() pam_.acct_mgmt() except PAM.error, resp: out.write("Error: " + str(resp) + "\n") return False except: return False # If we get here, the authentication worked return True My problem is that this function does not behave the same whether I use it in a simple script or through mod_python. To illustrate this, I wrote these simple cases: my_username = "markys" my_good_password = "lalala" my_bad_password = "lololo" def handler(req): req.content_type = "text/plain" req.write("1- " + str(auth(my_username,my_good_password,req) + "\n")) req.write("2- " + str(auth(my_username,my_bad_password,req) + "\n")) return apache.OK if __name__ == "__main__": print "1- " + str(auth(my_username,my_good_password,sys.__stdout__)) print "2- " + str(auth(my_username,my_bad_password,sys.__stdout__)) The result from the script is : Query list: [('Password: ', 1)] Our response: [('lalala', 0)] 1- True Query list: [('Password: ', 1)] Our response: [('lololo', 0)] Error: ('Authentication failure', 7) 2- False but the result from mod_python is : Query list: [('Password: ', 1)] Our response: [('lalala', 0)] Error: ('Authentication failure', 7) 1- False Query list: [('Password: ', 1)] Our response: [('lololo', 0)] Error: ('Authentication failure', 7) 2- False I don't understand why the auth function does not return the same value given the same inputs. Any idea where I got this wrong ? Here is the original script, if that could help you. Thanks a lot ! EDIT: All right I found the error. I was running the script as root. mod_python was running the script as the webserver's user. Only root has the right to read shadow. I am not sure how I will circumvent this, but at least now I know what is the problem !
[ "It seems like you have to enable Apache to use PAM authentication. Take a look at this site: http://www.debianhelp.co.uk/apachepam.htm\nYou might want to take a look at this site too : http://inming.net/?p=86\n" ]
[ 0 ]
[]
[]
[ "linux", "mod_python", "pam", "python" ]
stackoverflow_0002567705_linux_mod_python_pam_python.txt
Q: wxPython: Load font from file I'm making a wxPython app, and I want to use some non-standard font that I have on file. How do I do this? A: The Win32 API you need is called AddFontResource (you'll also want to use RemoveFontResource when you're done with a font). I haven't been able to find a python wrapper for this function, so you'll need to use ctypes or equivalent to access the API directly. Once the font has been added, it should be accessible in the usual way (note that it will be accessible to all applications). There's an SO thread that suggests using a FreeType library wrapper (ft2) but this seems like overkill (unless you have some other need for it) and the wrapper is marked as beta.
wxPython: Load font from file
I'm making a wxPython app, and I want to use some non-standard font that I have on file. How do I do this?
[ "The Win32 API you need is called AddFontResource (you'll also want to use RemoveFontResource when you're done with a font). I haven't been able to find a python wrapper for this function, so you'll need to use ctypes or equivalent to access the API directly. Once the font has been added, it should be accessible in the usual way (note that it will be accessible to all applications).\nThere's an SO thread that suggests using a FreeType library wrapper (ft2) but this seems like overkill (unless you have some other need for it) and the wrapper is marked as beta.\n" ]
[ 0 ]
[]
[]
[ "fonts", "python", "wxpython" ]
stackoverflow_0002569085_fonts_python_wxpython.txt
Q: Is it possible to use a back reference to specify the number of replications in a regular expression? Is it possible to use a back reference to specify the number of replications in a regular expression? foo= 'ADCKAL+2AG.+2AG.+2AG.+2AGGG+.G+3AGGa.' The substrings that start with '+[0-9]' followed by '[A-z]{n}.' need to be replaced with simply '+' where the variable n is the digit from earlier in the substring. Can that n be back referenced? For example (doesn't work) '+([0-9])[A-z]{/1}.' is the pattern I want replaced with "+" (that last dot can be any character and represents a quality score) so that foo should come out to ADCKAL+++G.G+. import re foo = 'ADCKAL+2AG.+2AG.+2AG.+2AGGG+.+G+3AGGa.' indelpatt = re.compile('\+([0-9])') while indelpatt.search(foo): indelsize=int(indelpatt.search(foo).group(1)) new_regex = '\+%s[ACGTNacgtn]{%s}.' % (indelsize,indelsize) newpatt=re.compile(new_regex) foo = newpatt.sub("+", foo) I'm probably missing an easier way to parse the string. A: No, you cannot use back-references as quantifiers. A workaround is to construct a regular expression that can handle each of the cases in an alternation. import re foo = 'ADCKAL+2AG.+2AG.+2AG.+2AGGG^+.+G+3AGGa4.' pattern = '|'.join('\+%s[ACGTNacgtn]{%s}.' % (i, i) for i in range(1, 10)) regex = re.compile(pattern) foo = regex.sub("+", foo) print foo Result: ADCKAL++++G^+.+G+4. Note also that your code contains an error that causes it to enter an infinite loop on the input you gave.
Is it possible to use a back reference to specify the number of replications in a regular expression?
Is it possible to use a back reference to specify the number of replications in a regular expression? foo= 'ADCKAL+2AG.+2AG.+2AG.+2AGGG+.G+3AGGa.' The substrings that start with '+[0-9]' followed by '[A-z]{n}.' need to be replaced with simply '+' where the variable n is the digit from earlier in the substring. Can that n be back referenced? For example (doesn't work) '+([0-9])[A-z]{/1}.' is the pattern I want replaced with "+" (that last dot can be any character and represents a quality score) so that foo should come out to ADCKAL+++G.G+. import re foo = 'ADCKAL+2AG.+2AG.+2AG.+2AGGG+.+G+3AGGa.' indelpatt = re.compile('\+([0-9])') while indelpatt.search(foo): indelsize=int(indelpatt.search(foo).group(1)) new_regex = '\+%s[ACGTNacgtn]{%s}.' % (indelsize,indelsize) newpatt=re.compile(new_regex) foo = newpatt.sub("+", foo) I'm probably missing an easier way to parse the string.
[ "No, you cannot use back-references as quantifiers. A workaround is to construct a regular expression that can handle each of the cases in an alternation.\nimport re\n\nfoo = 'ADCKAL+2AG.+2AG.+2AG.+2AGGG^+.+G+3AGGa4.'\npattern = '|'.join('\\+%s[ACGTNacgtn]{%s}.' % (i, i) for i in range(1, 10))\nregex = re.compile(pattern)\nfoo = regex.sub(\"+\", foo)\nprint foo\n\nResult:\nADCKAL++++G^+.+G+4.\n\nNote also that your code contains an error that causes it to enter an infinite loop on the input you gave.\n" ]
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002569418_python_regex.txt
Q: How to generate a mixed-case hash in Python? I am having a hard time figuring out a reasonable way to generate a mixed-case hash in Python. I want to generate something like: aZeEe9E Right now I'm using MD5, which doesn't generate case-sensitive hashes. Do any of you know how to generate a hash value consisting of upper- and lower- case characters + numbers? - Okay, GregS's advice worked like a charm (on the first try!): Here is a simple example: >>> import hashlib, base64 >>> s = 'http://gooogle.com' >>> hash = hashlib.md5(s).digest() >>> print hash 46c4f333fae34078a68393213bb9272d >>> print base64.b64encode(hash) NDZjNGYzMzNmYWUzNDA3OGE2ODM5MzIxM2JiOTI3MmQ= A: you can base64 encode the output of the hash. This has a couple of additional characters beyond those you mentioned. A: Maybe you can use base64-encoded hashes?
How to generate a mixed-case hash in Python?
I am having a hard time figuring out a reasonable way to generate a mixed-case hash in Python. I want to generate something like: aZeEe9E Right now I'm using MD5, which doesn't generate case-sensitive hashes. Do any of you know how to generate a hash value consisting of upper- and lower- case characters + numbers? - Okay, GregS's advice worked like a charm (on the first try!): Here is a simple example: >>> import hashlib, base64 >>> s = 'http://gooogle.com' >>> hash = hashlib.md5(s).digest() >>> print hash 46c4f333fae34078a68393213bb9272d >>> print base64.b64encode(hash) NDZjNGYzMzNmYWUzNDA3OGE2ODM5MzIxM2JiOTI3MmQ=
[ "you can base64 encode the output of the hash. This has a couple of additional characters beyond those you mentioned.\n", "Maybe you can use base64-encoded hashes?\n" ]
[ 3, 3 ]
[]
[]
[ "hash", "mixed_case", "python" ]
stackoverflow_0002569503_hash_mixed_case_python.txt
Q: Python and MySQL Is there an easy way (without downloading any plugins) to connect to a MySQL database in Python? Also, what would be the difference from calling a PHP script to retrieve the data from the database and hand it over to Python and importing one of these third-parties plugins that requires some additional software in the server. EDIT: the server has PHP and Python installed by default. A: You just need the MySQL for Python module that is Python DB API 2.0 compliant. I don't know why wouldn't you want to install it. If you are worried about it being too complex to install, there are eggs to make it easy to install. Once installed, you just use it like >>> import MySQLdb >>> db=MySQLdb.connect(host="localhost",user="joebob", passwd="moonpie",db="thangs") >>> c=db.cursor() >>> max_price=5 >>> c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price < %s""", (max_price,)) >>> c.fetchone() (3L, 2L, 0L)
Python and MySQL
Is there an easy way (without downloading any plugins) to connect to a MySQL database in Python? Also, what would be the difference from calling a PHP script to retrieve the data from the database and hand it over to Python and importing one of these third-parties plugins that requires some additional software in the server. EDIT: the server has PHP and Python installed by default.
[ "You just need the MySQL for Python module that is Python DB API 2.0 compliant.\nI don't know why wouldn't you want to install it. If you are worried about it being too complex to install, there are eggs to make it easy to install.\nOnce installed, you just use it like\n>>> import MySQLdb\n>>> db=MySQLdb.connect(host=\"localhost\",user=\"joebob\",\n passwd=\"moonpie\",db=\"thangs\")\n\n>>> c=db.cursor()\n>>> max_price=5\n>>> c.execute(\"\"\"SELECT spam, eggs, sausage FROM breakfast\n WHERE price < %s\"\"\", (max_price,))\n>>> c.fetchone()\n(3L, 2L, 0L)\n\n" ]
[ 2 ]
[ "If you don't want to download the python libraries to connect to MySQL, the effective answer is no, not trivially. \n", "No, there is no way that I've ever heard of or can think of to connect to a MySQL database with vanilla python. Just install the MySqldb python package-\nYou can typically do:\n\nsudo easy_install MySqldb\n\n" ]
[ -1, -1 ]
[ "mysql", "php", "python" ]
stackoverflow_0002569427_mysql_php_python.txt
Q: How do I most efficienty check the unique elements in a list? let's say I have a list li = [{'q':'apple','code':'2B'}, {'q':'orange','code':'2A'}, {'q':'plum','code':'2A'}] What is the most efficient way to return the count of unique "codes" in this list? In this case, the unique codes is 2, because only 2B and 2A are unique. I could put everything in a list and compare, but is this really efficient? A: Probably the most efficient simple way is to create a set of the codes, which will filter out uniques, then get the number of elements in that set: count = len(set(d["code"] for d in li)) As always, I advise to not worry about this kind of efficiency unless you've measured your performance and seen that it's a problem. I usually think only about code clarity when writing this kind of code, and then come back and tighten it only if I've profiled and found that I need to make performance improvements.
How do I most efficienty check the unique elements in a list?
let's say I have a list li = [{'q':'apple','code':'2B'}, {'q':'orange','code':'2A'}, {'q':'plum','code':'2A'}] What is the most efficient way to return the count of unique "codes" in this list? In this case, the unique codes is 2, because only 2B and 2A are unique. I could put everything in a list and compare, but is this really efficient?
[ "Probably the most efficient simple way is to create a set of the codes, which will filter out uniques, then get the number of elements in that set:\ncount = len(set(d[\"code\"] for d in li))\n\nAs always, I advise to not worry about this kind of efficiency unless you've measured your performance and seen that it's a problem. I usually think only about code clarity when writing this kind of code, and then come back and tighten it only if I've profiled and found that I need to make performance improvements.\n" ]
[ 8 ]
[]
[]
[ "dictionary", "list", "performance", "python" ]
stackoverflow_0002569578_dictionary_list_performance_python.txt
Q: I'm doing a lot of lists and dictionary sorting...and this is causing memory errors in Python website I retrieved data from the log table in my database. Then I started finding unique users, comparing/sorting lists, etc. In the end I got down to this. stats = {'2010-03-19': {'date': '2010-03-19', 'unique_users': 312, 'queries': 1465}, '2010-03-18': {'date': '2010-03-18', 'unique_users': 329, 'queries': 1659}, '2010-03-17': {'date': '2010-03-17', 'unique_users': 379, 'queries': 1845}, '2010-03-16': {'date': '2010-03-16', 'unique_users': 434, 'queries': 2336}, '2010-03-15': {'date': '2010-03-15', 'unique_users': 390, 'queries': 2138}, '2010-03-14': {'date': '2010-03-14', 'unique_users': 460, 'queries': 2221}, '2010-03-13': {'date': '2010-03-13', 'unique_users': 507, 'queries': 2242}, '2010-03-12': {'date': '2010-03-12', 'unique_users': 629, 'queries': 3523}, '2010-03-11': {'date': '2010-03-11', 'unique_users': 811, 'queries': 4274}, '2010-03-10': {'date': '2010-03-10', 'unique_users': 171, 'queries': 1297}, '2010-03-26': {'date': '2010-03-26', 'unique_users': 299, 'queries': 1617}, '2010-03-27': {'date': '2010-03-27', 'unique_users': 323, 'queries': 1310}, '2010-03-24': {'date': '2010-03-24', 'unique_users': 352, 'queries': 2112}, '2010-03-25': {'date': '2010-03-25', 'unique_users': 330, 'queries': 1290}, '2010-03-22': {'date': '2010-03-22', 'unique_users': 329, 'queries': 1798}, '2010-03-23': {'date': '2010-03-23', 'unique_users': 329, 'queries': 1857}, '2010-03-20': {'date': '2010-03-20', 'unique_users': 368, 'queries': 1693}, '2010-03-21': {'date': '2010-03-21', 'unique_users': 329, 'queries': 1511}, '2010-03-29': {'date': '2010-03-29', 'unique_users': 325, 'queries': 1718}, '2010-03-28': {'date': '2010-03-28', 'unique_users': 340, 'queries': 1815}, '2010-03-30': {'date': '2010-03-30', 'unique_users': 329, 'queries': 1891}} It's not a big dictionary. But when I try to do one last thing...it craps out on me. for k, v in stats: mylist.append(v) too many values to unpack What the heck does that mean??? TOO MANY VALUES TO UNPACK. A: If you only want the values you could just do: mylist = stats.values() If you need the key - value pair you should iterate the dict's items: mylist = [] for k,v in stats.iteritems(): mylist.append(v) In the code in your question you are just iterating over the dicts keys. Since you assign a single string (the key) to the tuple (k,v) it's characters are instead iterated; it's logical that this complete string cannot be unpacked' into a (k,v) tuple unless in a situation where you would have a string with a length of exactly two. That explains the error message: you're trying to unpack every single character of the string into only two placeholders (k and v). A: The problem is that when you iterate through a dictionary using a for ... in ... loop you only iterate through the keys. You can demonstrate this with: >>> for x in stats: print x ... 2010-03-19 2010-03-18 etc so when you do for k,v in stats: it is trying to assign a string to the tuple (k,v). Since strings are iterable it will try to assign a character at a time, so it would assign '2' to k and '0' to v, but has nowhere to assign the remaining characters to - hence the error. What you want is to either call the dict iteritems method to get a sequence of (key, value) tuples, or to call the itervalues method to get a sequence of the values since you are not using the key. A: The default behavior when iterating a dictionary is equivalent to calling its keys() method. So the following are equivalent: >>> for k in stats: print k >>> for k in stats.keys(): print k If you want to iterate over keys and values in a single run, you must call items().
I'm doing a lot of lists and dictionary sorting...and this is causing memory errors in Python website
I retrieved data from the log table in my database. Then I started finding unique users, comparing/sorting lists, etc. In the end I got down to this. stats = {'2010-03-19': {'date': '2010-03-19', 'unique_users': 312, 'queries': 1465}, '2010-03-18': {'date': '2010-03-18', 'unique_users': 329, 'queries': 1659}, '2010-03-17': {'date': '2010-03-17', 'unique_users': 379, 'queries': 1845}, '2010-03-16': {'date': '2010-03-16', 'unique_users': 434, 'queries': 2336}, '2010-03-15': {'date': '2010-03-15', 'unique_users': 390, 'queries': 2138}, '2010-03-14': {'date': '2010-03-14', 'unique_users': 460, 'queries': 2221}, '2010-03-13': {'date': '2010-03-13', 'unique_users': 507, 'queries': 2242}, '2010-03-12': {'date': '2010-03-12', 'unique_users': 629, 'queries': 3523}, '2010-03-11': {'date': '2010-03-11', 'unique_users': 811, 'queries': 4274}, '2010-03-10': {'date': '2010-03-10', 'unique_users': 171, 'queries': 1297}, '2010-03-26': {'date': '2010-03-26', 'unique_users': 299, 'queries': 1617}, '2010-03-27': {'date': '2010-03-27', 'unique_users': 323, 'queries': 1310}, '2010-03-24': {'date': '2010-03-24', 'unique_users': 352, 'queries': 2112}, '2010-03-25': {'date': '2010-03-25', 'unique_users': 330, 'queries': 1290}, '2010-03-22': {'date': '2010-03-22', 'unique_users': 329, 'queries': 1798}, '2010-03-23': {'date': '2010-03-23', 'unique_users': 329, 'queries': 1857}, '2010-03-20': {'date': '2010-03-20', 'unique_users': 368, 'queries': 1693}, '2010-03-21': {'date': '2010-03-21', 'unique_users': 329, 'queries': 1511}, '2010-03-29': {'date': '2010-03-29', 'unique_users': 325, 'queries': 1718}, '2010-03-28': {'date': '2010-03-28', 'unique_users': 340, 'queries': 1815}, '2010-03-30': {'date': '2010-03-30', 'unique_users': 329, 'queries': 1891}} It's not a big dictionary. But when I try to do one last thing...it craps out on me. for k, v in stats: mylist.append(v) too many values to unpack What the heck does that mean??? TOO MANY VALUES TO UNPACK.
[ "If you only want the values you could just do:\nmylist = stats.values()\n\nIf you need the key - value pair you should iterate the dict's items:\nmylist = []\nfor k,v in stats.iteritems():\n mylist.append(v)\n\nIn the code in your question you are just iterating over the dicts keys. \nSince you assign a single string (the key) to the tuple (k,v) it's characters are instead iterated; it's logical that this complete string cannot be unpacked' into a (k,v) tuple unless in a situation where you would have a string with a length of exactly two. That explains the error message: you're trying to unpack every single character of the string into only two placeholders (k and v).\n", "The problem is that when you iterate through a dictionary using a for ... in ... loop you only iterate through the keys. You can demonstrate this with:\n>>> for x in stats: print x\n... \n2010-03-19\n2010-03-18\netc\n\nso when you do for k,v in stats: it is trying to assign a string to the tuple (k,v). Since strings are iterable it will try to assign a character at a time, so it would assign '2' to k and '0' to v, but has nowhere to assign the remaining characters to - hence the error.\nWhat you want is to either call the dict iteritems method to get a sequence of (key, value) tuples, or to call the itervalues method to get a sequence of the values since you are not using the key.\n", "The default behavior when iterating a dictionary is equivalent to calling its keys() method.\nSo the following are equivalent:\n>>> for k in stats: print k\n>>> for k in stats.keys(): print k\n\nIf you want to iterate over keys and values in a single run, you must call items().\n" ]
[ 7, 5, 1 ]
[]
[]
[ "dictionary", "list", "optimization", "performance", "python" ]
stackoverflow_0002569677_dictionary_list_optimization_performance_python.txt
Q: downloading archives response corrupts files wrapper = FileWrapper(file("C:/pics.zip")) content_type = mimetypes.guess_type(result.files)[0] response = HttpResponse(wrapper, content_type=content_type) response['Content-Length'] = os.path.getsize("C:/pics.zip") response['Content-Disposition'] = "attachment; filename=pics.zip" return response pics.zip is a valid file with 3 pictures inside. server response the download, but when I am going to open the zip, winrar says This archive is either in unknown format or damaged! If I change the file path and the file name to a valid image C:/pic.jpg is downloaded damaged too. What Im missing in this download view? A: The problem is that you're not reading it as a binary file :) This should work: wrapper = FileWrapper(file("C:/pics.zip", 'rb'))
downloading archives response corrupts files
wrapper = FileWrapper(file("C:/pics.zip")) content_type = mimetypes.guess_type(result.files)[0] response = HttpResponse(wrapper, content_type=content_type) response['Content-Length'] = os.path.getsize("C:/pics.zip") response['Content-Disposition'] = "attachment; filename=pics.zip" return response pics.zip is a valid file with 3 pictures inside. server response the download, but when I am going to open the zip, winrar says This archive is either in unknown format or damaged! If I change the file path and the file name to a valid image C:/pic.jpg is downloaded damaged too. What Im missing in this download view?
[ "The problem is that you're not reading it as a binary file :)\nThis should work:\nwrapper = FileWrapper(file(\"C:/pics.zip\", 'rb'))\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002569875_django_python.txt
Q: How come I get a timed-out when I try to download something off my own domain? def download(source_url): socket.setdefaulttimeout(10) agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)'] ree = urllib2.Request(source_url) ree.add_header('User-Agent',random.choice(agents)) resp = urllib2.urlopen(ree) htmlSource = resp.read() return htmlSource url = "http://myIP/details/?id=4" result_html = download(url) It shouldn't time out...even with the 10 second timeout.. A: This will fail if you're running the development server, since it's single-threaded and it's busy serving the original request. Use mod_wsgi or strap on something like CherryPy if you want it to work. A: When you say "your own domain", are you hitting it from inside a NAT firewall? Something like this? 123.1.2.3 (public myIP) <- NAT gateway -> 192.168.1.5 (private IP of server) <--> 192.168.1.10 (you) Many firewalls don't allow an internal address to access an external interface without DNS rewrite. DNS rewrite causes the firewall to intercept your DNS lookup and rewrite the resulting public IP with the private IP.
How come I get a timed-out when I try to download something off my own domain?
def download(source_url): socket.setdefaulttimeout(10) agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)'] ree = urllib2.Request(source_url) ree.add_header('User-Agent',random.choice(agents)) resp = urllib2.urlopen(ree) htmlSource = resp.read() return htmlSource url = "http://myIP/details/?id=4" result_html = download(url) It shouldn't time out...even with the 10 second timeout..
[ "This will fail if you're running the development server, since it's single-threaded and it's busy serving the original request. Use mod_wsgi or strap on something like CherryPy if you want it to work.\n", "When you say \"your own domain\", are you hitting it from inside a NAT firewall?\nSomething like this?\n123.1.2.3 (public myIP) <- NAT gateway -> 192.168.1.5 (private IP of server) <--> 192.168.1.10 (you)\nMany firewalls don't allow an internal address to access an external interface without DNS rewrite. DNS rewrite causes the firewall to intercept your DNS lookup and rewrite the resulting public IP with the private IP.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002569886_django_python.txt
Q: Can I filter a django model with a python list? Say I have a model object 'Person' defined, which has a field called 'Name'. And I have a list of people: l = ['Bob','Dave','Jane'] I would like to return a list of all Person records where the first name is not in the list of names defined in l. What is the most pythonic way of doing this? EDIT: After thinking about it, what I really was trying to do is come up with a sub list of l that wasn't present in the Person table. Is there an efficient way of doing this? I can think of a few ways, not sure how efficient though. A: This should work: Person.objects.exclude(name__in=['Bob','Dave','Jane']) A: Renaming l for readability: names = ['Bob','Dave','Jane'] Person.objects.[exclude][1](Name__[in][2]=names) UPDATE 1: Answer to the second question (in your 'EDIT' paragraph): present = Person.objects.values_list('Name', flat=True) absent = set(names) - set(present) # or, if you prefer named functions to the set operator '-' absent = set(names).difference(present) Yes, the "right hand side" of difference (but not '-') accepts any iterable (I had to look it up to confirm).
Can I filter a django model with a python list?
Say I have a model object 'Person' defined, which has a field called 'Name'. And I have a list of people: l = ['Bob','Dave','Jane'] I would like to return a list of all Person records where the first name is not in the list of names defined in l. What is the most pythonic way of doing this? EDIT: After thinking about it, what I really was trying to do is come up with a sub list of l that wasn't present in the Person table. Is there an efficient way of doing this? I can think of a few ways, not sure how efficient though.
[ "This should work:\nPerson.objects.exclude(name__in=['Bob','Dave','Jane'])\n", "Renaming l for readability:\nnames = ['Bob','Dave','Jane']\n\nPerson.objects.[exclude][1](Name__[in][2]=names)\n\nUPDATE 1: Answer to the second question (in your 'EDIT' paragraph):\npresent = Person.objects.values_list('Name', flat=True)\nabsent = set(names) - set(present) \n# or, if you prefer named functions to the set operator '-'\nabsent = set(names).difference(present) \n\nYes, the \"right hand side\" of difference (but not '-') accepts any iterable (I had to look it up to confirm).\n" ]
[ 4, 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002569982_django_django_models_python.txt
Q: Error in python - don't understand I'm creating a game, and am quite new to Python generally. I created a function 'descriptionGenerator()' which generates a description for characters and objects either randomly or using variables passed to it. It seemed to be working, but every now and then it wouldn't work correctly. So i placed it in a loop, and it never seems to be able to complete the loop without one of the iterations having this problem. The code is as follows: #+------------------------------------------+ #| Name: bitsandpieces.py | #| A module for the 'Europa I' game | #| created for the Game Making Competition | #| | #| Date Created/Modified: | #| 3/4/10 | 3/4/10 | #+------------------------------------------+ # Import the required modules # Import system modules: import time import random # Import 3rd party modules: # Import game modules: # Define the 'descriptionGenerator()' function def descriptionGenerator(descriptionVariables): descriptionVariableSize = len(descriptionVariables) if descriptionVariables[0] == 'char': # If there is only one variable ('char'), create a random description if descriptionVariableSize == 1: # Define choices for descriptionVariables to be generated from gender_choices = ['male', 'female'] hair_choices = ['black', 'red', 'blonde', 'grey', 'brown', 'blue'] hair_choices2 = ['long', 'short', 'cropped', 'curly'] size_choices = ['tubby', 'thin', 'fat', 'almost twig-like'] demeanour_choices = ['glowering', 'bright', 'smiling', 'sombre', 'intelligent'] impression_choices = ['likeable', 'unlikeable', 'dangerous', 'annoying', 'afraid'] # Define description variables gender = random.choice(gender_choices) height = str(float('0.' + str(random.randint(1, 9))) + float(random.randint(1, 2))) if float(height) > 1.8: height_string = 'tall' if float(height) > 2: height_string = 'very tall' elif float(height) < 1.8 and float(height) > 1.5: height_string = 'average' elif float(height) < 1.5: height_string = 'short' if float(height) < 1.3: height_string = 'very short' hair = random.choice(hair_choices2) + ' ' + random.choice(hair_choices) size = random.choice(size_choices) demeanour = random.choice(demeanour_choices) impression = random.choice(impression_choices) # Collect description variables in list 'randomDescriptionVariables' randomDescriptionVariables = ['char', gender, height, height_string, hair, size, demeanour, impression] # Generate description using the 'descriptionGenerator' function descriptionGenerator(randomDescriptionVariables) # Generate the description of a character using the variables passed to the function elif descriptionVariableSize == 8: if descriptionVariables[1] == 'male': if descriptionVariables[7] != 'afraid': print """A %s man, about %s m tall. He has %s hair and is %s. He is %s and you get the impression that he is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) elif descriptionVariables[7] == 'afraid': print """A %s man, about %s m tall. He has %s hair and is %s. He is %s.\nYou feel that you should be %s of him.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) elif descriptionVariables[1] == 'female': if descriptionVariables[7] != 'afraid': print """A %s woman, about %s m tall. She has %s hair and is %s. She is %s and you get the impression that she is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) elif descriptionVariables[7] == 'afraid': print """A %s woman, about %s m tall. She has %s hair and is %s. She is %s.\nYou feel that you should be %s of her.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) else: pass elif descriptionVariables[0] == 'obj': # Insert code here 2 deal with object stuff pass print print myDescriptionVariables = ['char'] i = 0 while i < 30: print print print descriptionGenerator(myDescriptionVariables) i = i + 1 time.sleep(10) When it fails to properly execute it says this: Traceback (most recent call last): File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/Code/Code 2.0/bitsandpieces.py", line 79, in <module> descriptionGenerator(myDescriptionVariables) File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/Code/Code 2.0/bitsandpieces.py", line 50, in descriptionGenerator randomDescriptionVariables = ['char', gender, height, height_string, hair, size, demeanour, impression] UnboundLocalError: local variable 'height_string' referenced before assignment Thanks for any help with this -----EDIT----- Thanks for the help, fixed that problem, but now there is another one! I changed this segment of code 2 take the strings as variables, then 'return' them, and then test them: elif descriptionVariableSize == 8: if descriptionVariables[1] == 'male': if descriptionVariables[7] != 'afraid': descriptionOutput = """A %s man, about %s m tall. He has %s hair and is %s. He is %s and you get the impression that he is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) return descriptionOutput elif descriptionVariables[7] == 'afraid': descriptionOutput = """A %s man, about %s m tall. He has %s hair and is %s. He is %s.\nYou feel that you should be %s of him.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) return descriptionOutput elif descriptionVariables[1] == 'female': if descriptionVariables[7] != 'afraid': descriptionOutput = """A %s woman, about %s m tall. She has %s hair and is %s. She is %s and you get the impression that she is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) return descriptionOutput elif descriptionVariables[7] == 'afraid': descriptionOutput = """A %s woman, about %s m tall. She has %s hair and is %s. She is %s.\nYou feel that you should be %s of her.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) return descriptionOutput else: print 'Incorrect number of variables contained within \'descriptionVariables\'' elif descriptionVariables[0] == 'obj': # Insert code here 2 deal with object stuff pass myDescriptionVariables = ['char'] myOutput = descriptionGenerator(myDescriptionVariables) print myOutput However, when I run this, it gives the following output: None What am I doing wrong? A: You define height_string inside if/else statements: if float(height) > 1.8: height_string = 'tall' if float(height) > 2: height_string = 'very tall' elif float(height) < 1.8 and float(height) > 1.5: height_string = 'average' elif float(height) < 1.5: height_string = 'short' if float(height) < 1.3: height_string = 'very short' However, if height == 1.8 or height == 1.5, all if/elif statements are false, and therefore height_string is never defined. Simply change the second statement to have <= and >= signs instead: elif float(height) <= 1.8 and float(height) >= 1.5: In response to your edit: You call the function with myOutput = descriptionGenerator(["char"]) Notice that you're passing a list of length one. Therefore, your function sees descriptionVariableSize == 1 and creates the random description. So far, so good. But wait! At the end of that if statement, you have an elif: elif descriptionVariableSize == 8: Now you do have descriptionVariableSize == 8. However, you used elif - so you just spent all that time creating a random set of descriptions, but you never get to use it, because the first statement was true and this statement is only executed if the first statement was false. The solution - just change that elif to if. Now, whether you pass in a complete statement or generate one in the function, you'll still reach the second section. Edit the ... fifth ? I didn't notice that you call the function again at the end of the random section. Note that you don't return that call - so anything returned is lost to the void. Simply change it to return descriptionGenerator(randomDescriptionVariables) As an added note - your function is getting a bit unwieldy. The problem is that you're doing two completely different things in the function - one is generating a random list of qualities, and another is generating a description from those quallities. It may be better to move the stuff in the first if block into its own function, generateRandomDescription(), or something, that only gets called in that first if block. A: While you check to see if height is greater than or less than 1.5 or 1.8, you have nothing in place if it is equal to one of those values. Change the comparisons around those points to either >= and <, or to > and <=.
Error in python - don't understand
I'm creating a game, and am quite new to Python generally. I created a function 'descriptionGenerator()' which generates a description for characters and objects either randomly or using variables passed to it. It seemed to be working, but every now and then it wouldn't work correctly. So i placed it in a loop, and it never seems to be able to complete the loop without one of the iterations having this problem. The code is as follows: #+------------------------------------------+ #| Name: bitsandpieces.py | #| A module for the 'Europa I' game | #| created for the Game Making Competition | #| | #| Date Created/Modified: | #| 3/4/10 | 3/4/10 | #+------------------------------------------+ # Import the required modules # Import system modules: import time import random # Import 3rd party modules: # Import game modules: # Define the 'descriptionGenerator()' function def descriptionGenerator(descriptionVariables): descriptionVariableSize = len(descriptionVariables) if descriptionVariables[0] == 'char': # If there is only one variable ('char'), create a random description if descriptionVariableSize == 1: # Define choices for descriptionVariables to be generated from gender_choices = ['male', 'female'] hair_choices = ['black', 'red', 'blonde', 'grey', 'brown', 'blue'] hair_choices2 = ['long', 'short', 'cropped', 'curly'] size_choices = ['tubby', 'thin', 'fat', 'almost twig-like'] demeanour_choices = ['glowering', 'bright', 'smiling', 'sombre', 'intelligent'] impression_choices = ['likeable', 'unlikeable', 'dangerous', 'annoying', 'afraid'] # Define description variables gender = random.choice(gender_choices) height = str(float('0.' + str(random.randint(1, 9))) + float(random.randint(1, 2))) if float(height) > 1.8: height_string = 'tall' if float(height) > 2: height_string = 'very tall' elif float(height) < 1.8 and float(height) > 1.5: height_string = 'average' elif float(height) < 1.5: height_string = 'short' if float(height) < 1.3: height_string = 'very short' hair = random.choice(hair_choices2) + ' ' + random.choice(hair_choices) size = random.choice(size_choices) demeanour = random.choice(demeanour_choices) impression = random.choice(impression_choices) # Collect description variables in list 'randomDescriptionVariables' randomDescriptionVariables = ['char', gender, height, height_string, hair, size, demeanour, impression] # Generate description using the 'descriptionGenerator' function descriptionGenerator(randomDescriptionVariables) # Generate the description of a character using the variables passed to the function elif descriptionVariableSize == 8: if descriptionVariables[1] == 'male': if descriptionVariables[7] != 'afraid': print """A %s man, about %s m tall. He has %s hair and is %s. He is %s and you get the impression that he is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) elif descriptionVariables[7] == 'afraid': print """A %s man, about %s m tall. He has %s hair and is %s. He is %s.\nYou feel that you should be %s of him.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) elif descriptionVariables[1] == 'female': if descriptionVariables[7] != 'afraid': print """A %s woman, about %s m tall. She has %s hair and is %s. She is %s and you get the impression that she is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) elif descriptionVariables[7] == 'afraid': print """A %s woman, about %s m tall. She has %s hair and is %s. She is %s.\nYou feel that you should be %s of her.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) else: pass elif descriptionVariables[0] == 'obj': # Insert code here 2 deal with object stuff pass print print myDescriptionVariables = ['char'] i = 0 while i < 30: print print print descriptionGenerator(myDescriptionVariables) i = i + 1 time.sleep(10) When it fails to properly execute it says this: Traceback (most recent call last): File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/Code/Code 2.0/bitsandpieces.py", line 79, in <module> descriptionGenerator(myDescriptionVariables) File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/Code/Code 2.0/bitsandpieces.py", line 50, in descriptionGenerator randomDescriptionVariables = ['char', gender, height, height_string, hair, size, demeanour, impression] UnboundLocalError: local variable 'height_string' referenced before assignment Thanks for any help with this -----EDIT----- Thanks for the help, fixed that problem, but now there is another one! I changed this segment of code 2 take the strings as variables, then 'return' them, and then test them: elif descriptionVariableSize == 8: if descriptionVariables[1] == 'male': if descriptionVariables[7] != 'afraid': descriptionOutput = """A %s man, about %s m tall. He has %s hair and is %s. He is %s and you get the impression that he is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) return descriptionOutput elif descriptionVariables[7] == 'afraid': descriptionOutput = """A %s man, about %s m tall. He has %s hair and is %s. He is %s.\nYou feel that you should be %s of him.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) return descriptionOutput elif descriptionVariables[1] == 'female': if descriptionVariables[7] != 'afraid': descriptionOutput = """A %s woman, about %s m tall. She has %s hair and is %s. She is %s and you get the impression that she is %s.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) return descriptionOutput elif descriptionVariables[7] == 'afraid': descriptionOutput = """A %s woman, about %s m tall. She has %s hair and is %s. She is %s.\nYou feel that you should be %s of her.""" %(descriptionVariables[3], descriptionVariables[2], descriptionVariables[4], descriptionVariables[5], descriptionVariables[6], descriptionVariables[7]) return descriptionOutput else: print 'Incorrect number of variables contained within \'descriptionVariables\'' elif descriptionVariables[0] == 'obj': # Insert code here 2 deal with object stuff pass myDescriptionVariables = ['char'] myOutput = descriptionGenerator(myDescriptionVariables) print myOutput However, when I run this, it gives the following output: None What am I doing wrong?
[ "You define height_string inside if/else statements:\nif float(height) > 1.8:\n height_string = 'tall'\n if float(height) > 2:\n height_string = 'very tall'\nelif float(height) < 1.8 and float(height) > 1.5:\n height_string = 'average'\nelif float(height) < 1.5:\n height_string = 'short'\n if float(height) < 1.3:\n height_string = 'very short'\n\nHowever, if height == 1.8 or height == 1.5, all if/elif statements are false, and therefore height_string is never defined. Simply change the second statement to have <= and >= signs instead:\nelif float(height) <= 1.8 and float(height) >= 1.5:\n\n\nIn response to your edit:\nYou call the function with \nmyOutput = descriptionGenerator([\"char\"])\n\nNotice that you're passing a list of length one. Therefore, your function sees descriptionVariableSize == 1 and creates the random description.\nSo far, so good.\nBut wait! At the end of that if statement, you have an elif:\nelif descriptionVariableSize == 8:\n\nNow you do have descriptionVariableSize == 8. However, you used elif - so you just spent all that time creating a random set of descriptions, but you never get to use it, because the first statement was true and this statement is only executed if the first statement was false.\nThe solution - just change that elif to if. Now, whether you pass in a complete statement or generate one in the function, you'll still reach the second section.\nEdit the ... fifth ?\nI didn't notice that you call the function again at the end of the random section. Note that you don't return that call - so anything returned is lost to the void. Simply change it to\n return descriptionGenerator(randomDescriptionVariables)\n\n\nAs an added note - your function is getting a bit unwieldy. The problem is that you're doing two completely different things in the function - one is generating a random list of qualities, and another is generating a description from those quallities. It may be better to move the stuff in the first if block into its own function, generateRandomDescription(), or something, that only gets called in that first if block.\n", "While you check to see if height is greater than or less than 1.5 or 1.8, you have nothing in place if it is equal to one of those values. Change the comparisons around those points to either >= and <, or to > and <=.\n" ]
[ 3, 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002570023_macos_python.txt
Q: Should I mix wxpython and pyobjc? I have a wxPython based app which I am porting to Mac OS X, in that I need to show some alerts which should look like native mac alerts, so I am using pyobjc for that e.g. import Cocoa import wx app = wx.PySimpleApp() frame = wx.Frame(None, title="mac alert test") app.SetTopWindow(frame) frame.Show() def onclick(event): Cocoa.CFUserNotificationDisplayAlert(0, 3, 0, 0, 0, "Should i mix wxpython and objc", "hmmm...", "Cool", "Not Cool", "Whatever") frame.Bind(wx.EVT_LEFT_DOWN, onclick) app.MainLoop() Is there any thing wrong in such mixing of wx and objc code, any failure points ? A: One possible question to ask; I believe you must be using wx version for Mac that rests atop Carbon, because I think the Cocoa version hasn't been released yet. Once the cocoa version is released (for wx) then I would think there would have to be "fewer" issues. A mix of carbon and cocoa sounds problematic to me, but I can't point out specific gotchas. A: Any reason you don't just write a custom WX dialog, that inherits from wx.Dialog? The WX demo has a very nice example of that. A little more work, but a cleaner approach. A: I don't think that will work too well, mixing the event loops... [EDIT: I thought this initially, because the dialog is model and the window behind it is not, and there might be two event loops fighting for control. (Because each window has its own, which is why you can have Carbon and Cocoa windows in (an application of mostly the other type). On the other hand, the front window - your dialog box - controls the entire event loop if it's model, so it could work actually.] I'd really suggest you read the Carbon/Cocoa Integration guide. Now, this is more difficult because you're in Python and not C, but it may explain some concepts. I think on a previous project we implemented our own dialog like this, including customizable texts. (Since we were using wxWidgets/C++ we just implemented this using Carbon APIs with a wxWidgets layer and we looked pretty good. (... and we had a pretty heavily modified version of wx...))
Should I mix wxpython and pyobjc?
I have a wxPython based app which I am porting to Mac OS X, in that I need to show some alerts which should look like native mac alerts, so I am using pyobjc for that e.g. import Cocoa import wx app = wx.PySimpleApp() frame = wx.Frame(None, title="mac alert test") app.SetTopWindow(frame) frame.Show() def onclick(event): Cocoa.CFUserNotificationDisplayAlert(0, 3, 0, 0, 0, "Should i mix wxpython and objc", "hmmm...", "Cool", "Not Cool", "Whatever") frame.Bind(wx.EVT_LEFT_DOWN, onclick) app.MainLoop() Is there any thing wrong in such mixing of wx and objc code, any failure points ?
[ "One possible question to ask; I believe you must be using wx version for Mac that rests atop Carbon, because I think the Cocoa version hasn't been released yet. Once the cocoa version is released (for wx) then I would think there would have to be \"fewer\" issues. A mix of carbon and cocoa sounds problematic to me, but I can't point out specific gotchas.\n", "Any reason you don't just write a custom WX dialog, that inherits from wx.Dialog? The WX demo has a very nice example of that. A little more work, but a cleaner approach.\n", "I don't think that will work too well, mixing the event loops...\n[EDIT: I thought this initially, because the dialog is model and the window behind it is not, and there might be two event loops fighting for control. (Because each window has its own, which is why you can have Carbon and Cocoa windows in (an application of mostly the other type). \nOn the other hand, the front window - your dialog box - controls the entire event loop if it's model, so it could work actually.]\nI'd really suggest you read the Carbon/Cocoa Integration guide. Now, this is more difficult because you're in Python and not C, but it may explain some concepts.\nI think on a previous project we implemented our own dialog like this, including customizable texts. (Since we were using wxWidgets/C++ we just implemented this using Carbon APIs with a wxWidgets layer and we looked pretty good. (... and we had a pretty heavily modified version of wx...))\n" ]
[ 0, 0, 0 ]
[]
[]
[ "objective_c", "pyobjc", "python", "wxpython", "wxwidgets" ]
stackoverflow_0002561188_objective_c_pyobjc_python_wxpython_wxwidgets.txt
Q: Calculating Nearest Match to Mean/Stddev Pair With LibSVM I'm new to SVMs, and I'm trying to use the Python interface to libsvm to classify a sample containing a mean and stddev. However, I'm getting nonsensical results. Is this task inappropriate for SVMs or is there an error in my use of libsvm? Below is the simple Python script I'm using to test: #!/usr/bin/env python # Simple classifier test. # Adapted from the svm_test.py file included in the standard libsvm distribution. from collections import defaultdict from svm import * # Define our sparse data formatted training and testing sets. labels = [1,2,3,4] train = [ # key: 0=mean, 1=stddev {0:2.5,1:3.5}, {0:5,1:1.2}, {0:7,1:3.3}, {0:10.3,1:0.3}, ] problem = svm_problem(labels, train) test = [ ({0:3, 1:3.11},1), ({0:7.3,1:3.1},3), ({0:7,1:3.3},3), ({0:9.8,1:0.5},4), ] # Test classifiers. kernels = [LINEAR, POLY, RBF] kname = ['linear','polynomial','rbf'] correct = defaultdict(int) for kn,kt in zip(kname,kernels): print kt param = svm_parameter(kernel_type = kt, C=10, probability = 1) model = svm_model(problem, param) for test_sample,correct_label in test: pred_label, pred_probability = model.predict_probability(test_sample) correct[kn] += pred_label == correct_label # Show results. print '-'*80 print 'Accuracy:' for kn,correct_count in correct.iteritems(): print '\t',kn, '%.6f (%i of %i)' % (correct_count/float(len(test)), correct_count, len(test)) The domain seems fairly simple. I'd expect that if it's trained to know a mean of 2.5 means label 1, then when it sees a mean of 2.4, it should return label 1 as the most likely classification. However, each kernel has an accuracy of 0%. Why is this? A couple of side notes, is there a way to hide all the verbose training output dumped by libsvm in the terminal? I've searched libsvm's docs and code, but I can't find any way to turn this off. Also, I had wanted to use simple strings as the keys in my sparse dataset (e.g. {'mean':2.5,'stddev':3.5}). Unfortunately, libsvm only supports integers. I tried using the long integer representation of the string (e.g. 'mean' == 1109110110971110), but libsvm seems to truncate these to normal 32-bit integers. The only workaround I see is to maintain a separate "key" file that maps each string to an integer ('mean'=0, 'stddev'=1). But obviously that'll be a pain since I'll have to maintain and persist a second file along with the serialized classifier. Does anyone see an easier way? A: The problem seems to be coming from combining multiclass prediction with probability estimates. If you configure your code not to make probability estimates, it actually works, e.g.: <snip> # Test classifiers. kernels = [LINEAR, POLY, RBF] kname = ['linear','polynomial','rbf'] correct = defaultdict(int) for kn,kt in zip(kname,kernels): print kt param = svm_parameter(kernel_type = kt, C=10) # Here -> rm probability = 1 model = svm_model(problem, param) for test_sample,correct_label in test: # Here -> change predict_probability to just predict pred_label = model.predict(test_sample) correct[kn] += pred_label == correct_label </snip> With this change, I get: -------------------------------------------------------------------------------- Accuracy: polynomial 1.000000 (4 of 4) rbf 1.000000 (4 of 4) linear 1.000000 (4 of 4) Prediction with probability estimates does work, if you double up the data in the training set (i.e., include each data point twice). However, I couldn't find anyway to parametrize the model so that multiclass prediction with probabilities would work with just the original four training points. A: If you are interested in a different way of doing this, you could do the following. This way is theoretically more sound, however not as straightforward. By mentioning mean and std, it seems as if you refer to data that you assume to be distributed in some way. E.g., the data you observer is Gaussian distributed. You can then use the Symmetrised Kullback-Leibler_divergence as a distance measure between those distributions. You can then use something like k-nearest neighbour to classify. For two probability densities p and q, you have KL(p, q) = 0 only if p and q are the same. However, KL is not symmetric - so in order to have a proper distance measure, you can use distance(p1, p2) = KL(p1, p2) + KL(p1, p2) For Gaussians, KL(p1, p2) = { (μ1 - μ2)^2 + σ1^2 - σ2^2 } / (2.σ2^2) + ln(σ2/σ1). (I stole that from here, where you can also find a deviation :) Long story short: Given a training set D of (mean, std, class) tuples and a new p = (mean, std) pair, find that q in D for which distance(d, p) is minimal and return that class. To me that feels better as the SVM approach with several kernels, since the way of classifying is not so arbitrary.
Calculating Nearest Match to Mean/Stddev Pair With LibSVM
I'm new to SVMs, and I'm trying to use the Python interface to libsvm to classify a sample containing a mean and stddev. However, I'm getting nonsensical results. Is this task inappropriate for SVMs or is there an error in my use of libsvm? Below is the simple Python script I'm using to test: #!/usr/bin/env python # Simple classifier test. # Adapted from the svm_test.py file included in the standard libsvm distribution. from collections import defaultdict from svm import * # Define our sparse data formatted training and testing sets. labels = [1,2,3,4] train = [ # key: 0=mean, 1=stddev {0:2.5,1:3.5}, {0:5,1:1.2}, {0:7,1:3.3}, {0:10.3,1:0.3}, ] problem = svm_problem(labels, train) test = [ ({0:3, 1:3.11},1), ({0:7.3,1:3.1},3), ({0:7,1:3.3},3), ({0:9.8,1:0.5},4), ] # Test classifiers. kernels = [LINEAR, POLY, RBF] kname = ['linear','polynomial','rbf'] correct = defaultdict(int) for kn,kt in zip(kname,kernels): print kt param = svm_parameter(kernel_type = kt, C=10, probability = 1) model = svm_model(problem, param) for test_sample,correct_label in test: pred_label, pred_probability = model.predict_probability(test_sample) correct[kn] += pred_label == correct_label # Show results. print '-'*80 print 'Accuracy:' for kn,correct_count in correct.iteritems(): print '\t',kn, '%.6f (%i of %i)' % (correct_count/float(len(test)), correct_count, len(test)) The domain seems fairly simple. I'd expect that if it's trained to know a mean of 2.5 means label 1, then when it sees a mean of 2.4, it should return label 1 as the most likely classification. However, each kernel has an accuracy of 0%. Why is this? A couple of side notes, is there a way to hide all the verbose training output dumped by libsvm in the terminal? I've searched libsvm's docs and code, but I can't find any way to turn this off. Also, I had wanted to use simple strings as the keys in my sparse dataset (e.g. {'mean':2.5,'stddev':3.5}). Unfortunately, libsvm only supports integers. I tried using the long integer representation of the string (e.g. 'mean' == 1109110110971110), but libsvm seems to truncate these to normal 32-bit integers. The only workaround I see is to maintain a separate "key" file that maps each string to an integer ('mean'=0, 'stddev'=1). But obviously that'll be a pain since I'll have to maintain and persist a second file along with the serialized classifier. Does anyone see an easier way?
[ "The problem seems to be coming from combining multiclass prediction with probability estimates.\nIf you configure your code not to make probability estimates, it actually works, e.g.:\n<snip>\n# Test classifiers.\nkernels = [LINEAR, POLY, RBF]\nkname = ['linear','polynomial','rbf']\ncorrect = defaultdict(int)\nfor kn,kt in zip(kname,kernels):\n print kt\n param = svm_parameter(kernel_type = kt, C=10) # Here -> rm probability = 1\n model = svm_model(problem, param)\n for test_sample,correct_label in test:\n # Here -> change predict_probability to just predict\n pred_label = model.predict(test_sample)\n correct[kn] += pred_label == correct_label\n</snip>\n\nWith this change, I get:\n--------------------------------------------------------------------------------\nAccuracy:\n polynomial 1.000000 (4 of 4)\n rbf 1.000000 (4 of 4)\n linear 1.000000 (4 of 4)\n\nPrediction with probability estimates does work, if you double up the data in the training set (i.e., include each data point twice). However, I couldn't find anyway to parametrize the model so that multiclass prediction with probabilities would work with just the original four training points.\n", "If you are interested in a different way of doing this, you could do the following. This way is theoretically more sound, however not as straightforward.\nBy mentioning mean and std, it seems as if you refer to data that you assume to be distributed in some way. E.g., the data you observer is Gaussian distributed. You can then use the Symmetrised Kullback-Leibler_divergence as a distance measure between those distributions. You can then use something like k-nearest neighbour to classify.\nFor two probability densities p and q, you have KL(p, q) = 0 only if p and q are the same. However, KL is not symmetric - so in order to have a proper distance measure, you can use \ndistance(p1, p2) = KL(p1, p2) + KL(p1, p2)\nFor Gaussians, KL(p1, p2) = { (μ1 - μ2)^2 + σ1^2 - σ2^2 } / (2.σ2^2) + ln(σ2/σ1). (I stole that from here, where you can also find a deviation :)\nLong story short:\nGiven a training set D of (mean, std, class) tuples and a new p = (mean, std) pair, find that q in D for which distance(d, p) is minimal and return that class.\nTo me that feels better as the SVM approach with several kernels, since the way of classifying is not so arbitrary.\n" ]
[ 5, 3 ]
[]
[]
[ "artificial_intelligence", "libsvm", "machine_learning", "python", "svm" ]
stackoverflow_0002567483_artificial_intelligence_libsvm_machine_learning_python_svm.txt
Q: Searching text for geonames which part of huge package nltk I must study and use, if I need mark geonames in text? A: You'll want to use their named entity recognizer nltk.ne_chunk. Once the text is tagged you'll want to look for phrases labeled LOC (location) and GPE (Geo-political Entity).
Searching text for geonames
which part of huge package nltk I must study and use, if I need mark geonames in text?
[ "You'll want to use their named entity recognizer nltk.ne_chunk. \nOnce the text is tagged you'll want to look for phrases labeled LOC (location) and GPE (Geo-political Entity).\n" ]
[ 2 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0002568963_nlp_nltk_python.txt
Q: SECURITY Flaws in this design for User authentication SECURITY Flaws in this design for User authentication. From: http://wiki.pylonshq.com/display/pylonscookbook/Simple+Homegrown+Authentication Note: a. Project follows the MVC pattern. b. Only a user with a valid username and password is allowed submit something. Design: a. Have a base controller from which all controllers are derived from. b. Before any of the actions in the derived controllers are called the system calls a before action in the base controller. c. In each controller user hardcodes the actions that need to be verified in an array. d. The before action first looks in the array that has the actions that are protected and sees if a user is logged in or not by peaking into the session. If a user is present then user is allowed to submit otherwise user is redirected to login page. What do you think? A: I prefer approach with decorating functions that require authentication because it does not require typing action name 2 times - in the function definition and in requires_auth list. In that case you can mistype action name and it would not be noticed by interpreter. Decorating actions does not have this problem: @authorize(ValidAuthKitUser()) def list(self): pass You also can decorate __before__ function and it will have effect on all controller actions: @authorize(ValidAuthKitUser()) def __before__(self): pass def list(self): # automatically checks if the user is authenticated pass
SECURITY Flaws in this design for User authentication
SECURITY Flaws in this design for User authentication. From: http://wiki.pylonshq.com/display/pylonscookbook/Simple+Homegrown+Authentication Note: a. Project follows the MVC pattern. b. Only a user with a valid username and password is allowed submit something. Design: a. Have a base controller from which all controllers are derived from. b. Before any of the actions in the derived controllers are called the system calls a before action in the base controller. c. In each controller user hardcodes the actions that need to be verified in an array. d. The before action first looks in the array that has the actions that are protected and sees if a user is logged in or not by peaking into the session. If a user is present then user is allowed to submit otherwise user is redirected to login page. What do you think?
[ "I prefer approach with decorating functions that require authentication because it does not require typing action name 2 times - in the function definition and in requires_auth list. In that case you can mistype action name and it would not be noticed by interpreter.\nDecorating actions does not have this problem:\n@authorize(ValidAuthKitUser())\ndef list(self):\n pass\n\nYou also can decorate __before__ function and it will have effect on all controller actions:\n@authorize(ValidAuthKitUser())\ndef __before__(self):\n pass\ndef list(self): # automatically checks if the user is authenticated\n pass\n\n" ]
[ 1 ]
[]
[]
[ "authentication", "pylons", "python" ]
stackoverflow_0002567893_authentication_pylons_python.txt
Q: Counting problem: possible sudoko tables? I'm working on a sudoko solver (python). my method is using a game tree and explore possible permutations for each set of digits by DFS Algorithm. in order to analyzing problem, i want to know what is the count of possible valid and invalid sudoko tables? -> a 9*9 table that have 9 one, 9 two, ... , 9 nine. (this isn't exact duplicate by this question) my solution is: 1- First select 9 cells for 1s: (*) 2- and like (1) for other digits (each time, 9 cells will be deleted from remaining available cells): C(81-9,9) , C(81-9*2,9) .... = 3- finally multiply the result by 9! (permutation of 1s-2s-3s...-9s in (*)) this is not equal to accepted answer of this question but problems are equivalent. what did i do wrong? A: The number of valid Sudoku solution grids for the standard 9×9 grid was calculated by Bertram Felgenhauer and Frazer Jarvis in 2005 to be 6,670,903,752,021,072,936,960. Mathematics of Sudoku | source I think problem with your solution is that deleting 9 cells each time from available cells does not necessarily create a valid grid. What I mean is just deleting 9 cells won't suffice. That is why 81! / (9!)^9 is much bigger number than actual valid solutions. EDIT: Permutations with repeated elements Your solutions is almost correct if you want all the tables not just valid sudoku tables. There is a formula: (a+b+c+...)! / [a! b! c! ....] Suppose there are 5 boys and 3 girls and we have 8 seats then number of different ways in which they can seat is (5+3)! / (5! 3!) Your problem is analogous to this one. There are 9 1s , 9 2s ... 9 9s. and 81 places so answer should be (9+9+...)! / (9!)^9 Now if you multiply again by 9! then this will add duplicate arrangements to the number by shuffling them. A: According to this Wikipedia article (or this OEIS sequence), there are roughly 6.6 * 10^21 different sudoku squares. A: What you did wrong was the last step: you shouldn't multiply the answer by 9!. You have already counted all possible squares. This doesn't help you much when counting the possible Sudoku-tables. One other thing you could do is to count the tables where the "row-condition" holds: that is just (9!)^9, because you just choose one permutation of 1..9 for every row. Still closer to the Sudoku-problem is counting Latin squares. Latin square has to satisfy both the "row-condition" and "column condition". That is already a difficult problem and no closed form formula is known. Sudoku is a Latin square with the additional "subsquare-condition".
Counting problem: possible sudoko tables?
I'm working on a sudoko solver (python). my method is using a game tree and explore possible permutations for each set of digits by DFS Algorithm. in order to analyzing problem, i want to know what is the count of possible valid and invalid sudoko tables? -> a 9*9 table that have 9 one, 9 two, ... , 9 nine. (this isn't exact duplicate by this question) my solution is: 1- First select 9 cells for 1s: (*) 2- and like (1) for other digits (each time, 9 cells will be deleted from remaining available cells): C(81-9,9) , C(81-9*2,9) .... = 3- finally multiply the result by 9! (permutation of 1s-2s-3s...-9s in (*)) this is not equal to accepted answer of this question but problems are equivalent. what did i do wrong?
[ "The number of valid Sudoku solution grids for the standard 9×9 grid was calculated by Bertram Felgenhauer and Frazer Jarvis in 2005 to be 6,670,903,752,021,072,936,960.\nMathematics of Sudoku | \nsource\nI think problem with your solution is that deleting 9 cells each time from available cells does not necessarily create a valid grid. What I mean is just deleting 9 cells won't suffice.\nThat is why 81! / (9!)^9 is much bigger number than actual valid solutions. \nEDIT:\nPermutations with repeated elements\nYour solutions is almost correct if you want all the tables not just valid sudoku tables.\nThere is a formula:\n(a+b+c+...)! / [a! b! c! ....]\nSuppose there are 5 boys and 3 girls and we have 8 seats then number of different ways in which they can seat is\n(5+3)! / (5! 3!)\nYour problem is analogous to this one.\nThere are 9 1s , 9 2s ... 9 9s.\nand 81 places\nso answer should be (9+9+...)! / (9!)^9\nNow if you multiply again by 9! then this will add duplicate arrangements to the number by shuffling them.\n", "According to this Wikipedia article (or this OEIS sequence), there are roughly 6.6 * 10^21 different sudoku squares.\n", "What you did wrong was the last step: you shouldn't multiply the answer by 9!. You have already counted all possible squares.\nThis doesn't help you much when counting the possible Sudoku-tables. One other thing you could do is to count the tables where the \"row-condition\" holds: that is just (9!)^9, because you just choose one permutation of 1..9 for every row.\nStill closer to the Sudoku-problem is counting Latin squares. Latin square has to satisfy both the \"row-condition\" and \"column condition\". That is already a difficult problem and no closed form formula is known. Sudoku is a Latin square with the additional \"subsquare-condition\".\n" ]
[ 2, 1, 1 ]
[]
[]
[ "algorithm", "discrete_mathematics", "math", "python" ]
stackoverflow_0002570799_algorithm_discrete_mathematics_math_python.txt
Q: Text-based game graphics in Python I'm pretty new to programming, and I'm creating a simple text-based game.> I'm wondering if there is a simple way to create my own terminal-type window with which I can place coloured input etc. Is there a graphics module well suited to this? I'm using Mac, but I would like it to work on Windows as well Thanks A: You could use the termcolor library - it that what you're looking for? On Windows things are trickier. See this SO answer - you should resort to win32console and some ctypes. The answer has some code and links to other articles. A: The Tkinter Text Widget will do what you ask. the IDLE main window is implemented as one, if you want to play with an example. A: For game programming with Python, I would always recommend PyGame. It is not very complex and enables you to easily use input, graphics and sound. As a start: http://www.penzilla.net/tutorials/python/pygame/
Text-based game graphics in Python
I'm pretty new to programming, and I'm creating a simple text-based game.> I'm wondering if there is a simple way to create my own terminal-type window with which I can place coloured input etc. Is there a graphics module well suited to this? I'm using Mac, but I would like it to work on Windows as well Thanks
[ "You could use the termcolor library - it that what you're looking for?\nOn Windows things are trickier. See this SO answer - you should resort to win32console and some ctypes. The answer has some code and links to other articles.\n", "The Tkinter Text Widget will do what you ask. the IDLE main window is implemented as one, if you want to play with an example.\n", "For game programming with Python, I would always recommend PyGame. \nIt is not very complex and enables you to easily use input, graphics and sound.\nAs a start:\nhttp://www.penzilla.net/tutorials/python/pygame/\n" ]
[ 2, 2, 1 ]
[]
[]
[ "graphics", "python", "terminal", "textbox" ]
stackoverflow_0002570377_graphics_python_terminal_textbox.txt
Q: Optimising RSS parsing on App Engine to avoid high CPU warnings I'm pulling some RSS feeds into a datastore in App Engine to serve up to an iPhone app. I use cron to schedule updating the RSS every x minutes. Each task only parses one RSS feed (which has 15-20 items). I frequently get warnings about high CPU usage in the App Engine dashboard, so I'm looking for ways to optimise my code. Currently, I use minidom (since it's already there on App Engine), but I suspect it's not very efficient! Here's the code: dom = minidom.parseString(urlfetch.fetch(url).content) if dom: items = [] for node in dom.getElementsByTagName('item'): item = RssItem( key_name = self.getText(node.getElementsByTagName('guid')[0].childNodes), title = self.getText(node.getElementsByTagName('title')[0].childNodes), description = self.getText(node.getElementsByTagName('description')[0].childNodes), modified = datetime.now(), link = self.getText(node.getElementsByTagName('link')[0].childNodes), categories = [self.getText(category.childNodes) for category in node.getElementsByTagName('category')] ); items.append(item); db.put(items); def getText(self, nodelist): rc = '' for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc There isn't much going on, but the scripts often take 2-6 seconds CPU time, which seems a bit excessive for looping through 20ish items and reading a few attributes. What can I do to make this faster? Is there anything particularly bad in the above code, or should I change to another way of parsing? Are there are any libraries (that work on App Engine) that would be better, or would I be better parsing the RSS myself? A: Outsource feed parsing via for example superfeedr You could also look into superfeedr.com. They have a reasonable free quota/paying plans. They will do the polling(within 15 minutes you get updates) for you/etc. If the feeds also support pubsubhubbub, then you will receive the feeds in realtime! This video will explain to you what pubsubhubbub is if you don't know yet. Improved feed parser written by Brett Slatkin I would also advice you to watch this awesome video from Brett Slatkin explaining pubsubhubbub. I also remember that somewhere in the presentation he says that he does not use Universal Feedparser because it's just does to much work for his problem. He wrote his own SAX(14:10 in video presentation he talks about it a little bit) parser which is lightning fast. I guess you should check out the pubsubhubbub code to find out how he accomplished this. A: I'd try ElementTree or the Universal Feed Parser and see if they're any better. ElementTree is in the stdlib as of Python 2.5, so it's available on App Engine. A: If you have a low amount of traffic coming to your site you might be experiencing spin up times for your app. If an app is idle for a as little as a few minutes app engine will spin down your app to save resources. When the next request comes in the app has to be spun up before it can handle the request and this all gets added to your cpu quota. If you search the appengine newsgroup you see that it is full of complaints about this. I use superfeedr for my site www.newsfacet.com and I notice that when superfeedr notifies me most of the time I can handle a few rss articles in a few hundred milliseconds. If its been a while since the last input this time can jump to 10 or 11 seconds as it incurs the spin up cost. A: In regards to using PubSubHubbub to let someone else do the work for you, you may find my blog post on using hubbub on App Engine to be useful. A: You probably should run a profiler to pinpoint where the code is spinning its wheels. It could be waiting on the connections as some RSS feeds are REAL slow. Also, some RDF/RSS/ATOM libraries build in a governor to keep from beating the cr*p out of the host when retrieving multiple feeds from the same site. I've written several aggregators and being considerate to the server is important. Universal Feed Parser is full-featured, at least from what I've seen by looking through the docs. I didn't use it because I wrote my aggregators in Ruby and had different needs but I was aware of it and would consider it for a Python-based solution.
Optimising RSS parsing on App Engine to avoid high CPU warnings
I'm pulling some RSS feeds into a datastore in App Engine to serve up to an iPhone app. I use cron to schedule updating the RSS every x minutes. Each task only parses one RSS feed (which has 15-20 items). I frequently get warnings about high CPU usage in the App Engine dashboard, so I'm looking for ways to optimise my code. Currently, I use minidom (since it's already there on App Engine), but I suspect it's not very efficient! Here's the code: dom = minidom.parseString(urlfetch.fetch(url).content) if dom: items = [] for node in dom.getElementsByTagName('item'): item = RssItem( key_name = self.getText(node.getElementsByTagName('guid')[0].childNodes), title = self.getText(node.getElementsByTagName('title')[0].childNodes), description = self.getText(node.getElementsByTagName('description')[0].childNodes), modified = datetime.now(), link = self.getText(node.getElementsByTagName('link')[0].childNodes), categories = [self.getText(category.childNodes) for category in node.getElementsByTagName('category')] ); items.append(item); db.put(items); def getText(self, nodelist): rc = '' for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc There isn't much going on, but the scripts often take 2-6 seconds CPU time, which seems a bit excessive for looping through 20ish items and reading a few attributes. What can I do to make this faster? Is there anything particularly bad in the above code, or should I change to another way of parsing? Are there are any libraries (that work on App Engine) that would be better, or would I be better parsing the RSS myself?
[ "Outsource feed parsing via for example superfeedr\nYou could also look into superfeedr.com. They have a reasonable free quota/paying plans. They will do the polling(within 15 minutes you get updates) for you/etc. If the feeds also support pubsubhubbub, then you will receive the feeds in realtime! This video will explain to you what pubsubhubbub is if you don't know yet.\nImproved feed parser written by Brett Slatkin\nI would also advice you to watch this awesome video from Brett Slatkin explaining pubsubhubbub. I also remember that somewhere in the presentation he says that he does not use Universal Feedparser because it's just does to much work for his problem. He wrote his own SAX(14:10 in video presentation he talks about it a little bit) parser which is lightning fast. I guess you should check out the pubsubhubbub code to find out how he accomplished this.\n", "I'd try ElementTree or the Universal Feed Parser and see if they're any better. ElementTree is in the stdlib as of Python 2.5, so it's available on App Engine.\n", "If you have a low amount of traffic coming to your site you might be experiencing spin up times for your app. If an app is idle for a as little as a few minutes app engine will spin down your app to save resources. When the next request comes in the app has to be spun up before it can handle the request and this all gets added to your cpu quota. If you search the appengine newsgroup you see that it is full of complaints about this.\nI use superfeedr for my site www.newsfacet.com and I notice that when superfeedr notifies me most of the time I can handle a few rss articles in a few hundred milliseconds. If its been a while since the last input this time can jump to 10 or 11 seconds as it incurs the spin up cost.\n", "In regards to using PubSubHubbub to let someone else do the work for you, you may find my blog post on using hubbub on App Engine to be useful.\n", "You probably should run a profiler to pinpoint where the code is spinning its wheels. It could be waiting on the connections as some RSS feeds are REAL slow. \nAlso, some RDF/RSS/ATOM libraries build in a governor to keep from beating the cr*p out of the host when retrieving multiple feeds from the same site. I've written several aggregators and being considerate to the server is important.\nUniversal Feed Parser is full-featured, at least from what I've seen by looking through the docs. I didn't use it because I wrote my aggregators in Ruby and had different needs but I was aware of it and would consider it for a Python-based solution.\n" ]
[ 4, 1, 1, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002563568_google_app_engine_python.txt
Q: What do the arguments "name__icontains" and "description__icontains" mean in a Django query filter? maps = (maps.filter(name__icontains=search_terms) | maps.filter(description__icontains=search_terms)) I can't find the meaning of these filter arguments. A: It's a case-insensitive containment test. Example: Entry.objects.get(headline__icontains='Lennon') SQL equivalent: SELECT ... WHERE headline ILIKE '%Lennon%'; In your case the code says maps should be True if either the name or the description field contains the value of search_terms. A: xxx_icontains searches the whole xxx field for the argument, case-insensitively. http://docs.djangoproject.com/en/1.1/ref/models/querysets/#icontains
What do the arguments "name__icontains" and "description__icontains" mean in a Django query filter?
maps = (maps.filter(name__icontains=search_terms) | maps.filter(description__icontains=search_terms)) I can't find the meaning of these filter arguments.
[ "It's a case-insensitive containment test.\nExample:\nEntry.objects.get(headline__icontains='Lennon')\n\nSQL equivalent:\nSELECT ... WHERE headline ILIKE '%Lennon%';\n\n\nIn your case the code says maps should be True if either the name or the description field contains the value of search_terms.\n", "xxx_icontains searches the whole xxx field for the argument, case-insensitively. \nhttp://docs.djangoproject.com/en/1.1/ref/models/querysets/#icontains\n" ]
[ 22, 2 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0002571149_django_django_queryset_python.txt
Q: How to convert tag-and-username-like text into proper links in a twitter message? I'm writing a twitter-like note-taking web app. In a page the latest 20 notes of the user will be listed, and when the user scroll to the bottom of the browser window more items will be loaded and rendered. The initial 20 notes are part of the generated html of my django template, but the other dynamically loaded items are in json format. I want to know how do I do the tag-and-username converting consistently. Thanks in advance. A: There's a couple of pieces to consider here. On the server side, you have to be able to maintain what "chunk" of the notes list the user is on. The easiest way to do this is probably the Django paginator. It works basically by taking a QuerySet, setting a count for the number of items, then giving it the "page" number (or "chunk" number) and it returns those items. You could do it with JSON, but it would be just as easy to do it with HTML as well. When we look at the client side part of this you'll see why. So we can have a view "api" to handle a note "chunk" (note all my code samples here are abbreviated just for demonstration. You'd want to have error handling and all that)... def get_notes_chunk(request, *args, **kwargs): # Get our notes, however... all_notes = Notes.objects.all() # Paginate them based on the page we're on... chunk_number = request.GET.get('c') paginator = Paginator(all_notes, 20) # (show 20 at a time) current_chunk = paginator.page(chunk_number) # Render to template all that jazz render_to_template( ... , { 'paginator':paginator, 'current_chunk':current_chunk }, ...) Our template renders <li> tags which we'll stick into a <ul> on the client... {% for note in current_chunk.object_list %} <li>{{ note }}</li> {% endfor %} Now on the client, we need to write some javascript to handle this. It's up to you to determine on what event to fire the update, but as for how, we can use a little jQuery to handle this... <script type="text/javascript"> var chunk_count = 1; var notes_list_id = 'notes-list' function load_next_chunk() { chunk_count += 1; $.get('{% url get_notes_chunk %}?c=' + chunk_count, function(html) { $('#'+notes_list_id).append(html); }); } </script> <body> ... <ul id="notes-list"> <!-- Render chunk #1 here --> </ul> ... </body> Some things that would probably make sense... Refactor the rendering of the notes list into a template tag so that you can re-use it for your API and the main rendering of your page Refactor the querying/paginating of the Notes (or whatever) model so that you can re-use it in both views Figure out on what event the next chunk will be loaded and implement that. A: The question isn't that clear... but for generating the HTML out of a Tweet take a look at twp(based on the official twitter-text-java lib): http://github.com/BonsaiDen/twp A: I'm not sure exactly what you're asking, but what's wrong with something like {{ user.get_absolute_url }}? For the tag detail URLs, it really depends on what you're looking for, but you would have to construct the url and view for that yourself.
How to convert tag-and-username-like text into proper links in a twitter message?
I'm writing a twitter-like note-taking web app. In a page the latest 20 notes of the user will be listed, and when the user scroll to the bottom of the browser window more items will be loaded and rendered. The initial 20 notes are part of the generated html of my django template, but the other dynamically loaded items are in json format. I want to know how do I do the tag-and-username converting consistently. Thanks in advance.
[ "There's a couple of pieces to consider here. On the server side, you have to be able to maintain what \"chunk\" of the notes list the user is on. The easiest way to do this is probably the Django paginator. It works basically by taking a QuerySet, setting a count for the number of items, then giving it the \"page\" number (or \"chunk\" number) and it returns those items.\nYou could do it with JSON, but it would be just as easy to do it with HTML as well. When we look at the client side part of this you'll see why.\nSo we can have a view \"api\" to handle a note \"chunk\" (note all my code samples here are abbreviated just for demonstration. You'd want to have error handling and all that)...\ndef get_notes_chunk(request, *args, **kwargs):\n # Get our notes, however...\n all_notes = Notes.objects.all()\n\n # Paginate them based on the page we're on...\n chunk_number = request.GET.get('c') \n paginator = Paginator(all_notes, 20) # (show 20 at a time)\n current_chunk = paginator.page(chunk_number)\n\n # Render to template all that jazz\n render_to_template( ... , { 'paginator':paginator, 'current_chunk':current_chunk }, ...)\n\nOur template renders <li> tags which we'll stick into a <ul> on the client...\n{% for note in current_chunk.object_list %}\n <li>{{ note }}</li>\n{% endfor %}\n\nNow on the client, we need to write some javascript to handle this. It's up to you to determine on what event to fire the update, but as for how, we can use a little jQuery to handle this...\n<script type=\"text/javascript\"> \n var chunk_count = 1;\n var notes_list_id = 'notes-list'\n\n function load_next_chunk() {\n chunk_count += 1;\n $.get('{% url get_notes_chunk %}?c=' + chunk_count, function(html) {\n $('#'+notes_list_id).append(html);\n }); \n }\n</script>\n\n<body>\n\n ...\n\n <ul id=\"notes-list\">\n <!-- Render chunk #1 here -->\n </ul>\n\n ...\n\n</body>\n\nSome things that would probably make sense...\n\nRefactor the rendering of the notes list into a template tag so that you can re-use it for your API and the main rendering of your page\nRefactor the querying/paginating of the Notes (or whatever) model so that you can re-use it in both views\nFigure out on what event the next chunk will be loaded and implement that.\n\n", "The question isn't that clear... but for generating the HTML out of a Tweet take a look at twp(based on the official twitter-text-java lib):\nhttp://github.com/BonsaiDen/twp \n", "I'm not sure exactly what you're asking, but what's wrong with something like {{ user.get_absolute_url }}? For the tag detail URLs, it really depends on what you're looking for, but you would have to construct the url and view for that yourself.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "django", "python", "twitter" ]
stackoverflow_0002570193_django_python_twitter.txt
Q: Python beautiful soup arguments I have this code that fetches some text from a page using BeautifulSoup soup= BeautifulSoup(html) body = soup.find('div' , {'id':'body'}) print body I would like to make this as a reusable function that takes in some htmltext and the tags to match it like the following def parse(html, atrs): soup= BeautifulSoup(html) body = soup.find(atrs) return body But if i make a call like this parse(htmlpage, ('div' , {'id':'body'}")) or like parse(htmlpage, ['div' , {'id':'body'}"]) I get only the div element, the body attribute seems to get ignored. Is there a way to fix this? A: def parse(html, *atrs): soup= BeautifulSoup(html) body = soup.find(*atrs) return body And then: parse(htmlpage, 'div', {'id':'body'}) A: I think you just need to add an asterisk here: body = soup.find(*atrs) Without the asterisk you are passing a single parameter which is a tuple: body = soup.find(('div' , {'id':'body'})) With the asterisk the tuple is expanded out and the statement becomes equivalent to what you want: body = soup.find('div' , {'id':'body'}) See this article for more information on using the *args notation, and the related **kwargs.
Python beautiful soup arguments
I have this code that fetches some text from a page using BeautifulSoup soup= BeautifulSoup(html) body = soup.find('div' , {'id':'body'}) print body I would like to make this as a reusable function that takes in some htmltext and the tags to match it like the following def parse(html, atrs): soup= BeautifulSoup(html) body = soup.find(atrs) return body But if i make a call like this parse(htmlpage, ('div' , {'id':'body'}")) or like parse(htmlpage, ['div' , {'id':'body'}"]) I get only the div element, the body attribute seems to get ignored. Is there a way to fix this?
[ "def parse(html, *atrs):\n soup= BeautifulSoup(html)\n body = soup.find(*atrs)\n return body\n\nAnd then:\nparse(htmlpage, 'div', {'id':'body'})\n\n", "I think you just need to add an asterisk here:\nbody = soup.find(*atrs)\n\nWithout the asterisk you are passing a single parameter which is a tuple:\nbody = soup.find(('div' , {'id':'body'}))\n\nWith the asterisk the tuple is expanded out and the statement becomes equivalent to what you want:\nbody = soup.find('div' , {'id':'body'})\n\nSee this article for more information on using the *args notation, and the related **kwargs.\n" ]
[ 8, 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002571228_beautifulsoup_python.txt
Q: How to add a separator in a PyGTK combobox? I'm using gtk.combo_box_new_text() to make combobox list, this uses a gtk.ListStore to store only strings, so there are some way to add a separator between items without use a complex gtk.TreeModel? If this is not possible, what is the simplest way to use a gtk.TreeModel to able secuential widget addition? A: I think that you should use ComboBox.set_row_separator_func to set a separator function where you would determine which items of your list will be separators. Since ListStore implements TreeModel interface, you should have no problem simply using it in your case. P.S.: nothing is easy in GTK :)
How to add a separator in a PyGTK combobox?
I'm using gtk.combo_box_new_text() to make combobox list, this uses a gtk.ListStore to store only strings, so there are some way to add a separator between items without use a complex gtk.TreeModel? If this is not possible, what is the simplest way to use a gtk.TreeModel to able secuential widget addition?
[ "I think that you should use ComboBox.set_row_separator_func to set a separator function where you would determine which items of your list will be separators. Since ListStore implements TreeModel interface, you should have no problem simply using it in your case.\nP.S.: nothing is easy in GTK :)\n" ]
[ 4 ]
[]
[]
[ "gnome", "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0002571202_gnome_gtk_pygtk_python_user_interface.txt
Q: Extracting a string between specified characters in python I'm a newbie to regular expressions and I have the following string: sequence = '["{\"First\":\"Belyuen,NT,0801\",\"Second\":\"Belyuen,NT,0801\"}","{\"First\":\"Larrakeyah,NT,0801\",\"Second\":\"Larrakeyah,NT,0801\"}"]' I am trying to extract the text Belyuen,NT,0801 and Larrakeyah,NT,0801 in python. I have the following code which is not working: re.search('\:\\"...\\', ''.join(sequence)) I.e. I want to get the string between characters :\ and \. A: Don't use regex for this. It appears to be a rather strangely split set of JSON strings. Join them back together and use the json module to decode it. import json sequence = '[%s]' % ','.join(sequence) data = json.loads(sequence) print data[0]['First'], data[0]['Second'] (Note the json module is new in Python2.6 - if you have a lower version, download and install simplejson). A: it seems like a proper serialization of the Python dict, you could just do: >>> sequence = ["{\"First\":\"Belyuen,NT,0801\",\"Second\":\"Belyuen,NT,0801\"}","{\"First\":\"Larrakeyah,NT,0801\",\"Second\":\"Larrakeyah,NT,0801\"}"] >>> import json >>> for i in sequence: d = json.loads(i) print(d['First']) Belyuen,NT,0801 Larrakeyah,NT,0801 A: you don't need regex >>> sequence = ["{\"First\":\"Belyuen,NT,0801\",\"Second\":\"Belyuen,NT,0801\"}","{\"First\":\"Larrakeyah,NT,0801\",\"Second\":\"Larrakeyah,NT,0801\"}"] >>> for item in sequence: ... print eval(item).values() ... ['Belyuen,NT,0801', 'Belyuen,NT,0801'] ['Larrakeyah,NT,0801', 'Larrakeyah,NT,0801']
Extracting a string between specified characters in python
I'm a newbie to regular expressions and I have the following string: sequence = '["{\"First\":\"Belyuen,NT,0801\",\"Second\":\"Belyuen,NT,0801\"}","{\"First\":\"Larrakeyah,NT,0801\",\"Second\":\"Larrakeyah,NT,0801\"}"]' I am trying to extract the text Belyuen,NT,0801 and Larrakeyah,NT,0801 in python. I have the following code which is not working: re.search('\:\\"...\\', ''.join(sequence)) I.e. I want to get the string between characters :\ and \.
[ "Don't use regex for this. It appears to be a rather strangely split set of JSON strings. Join them back together and use the json module to decode it.\nimport json\nsequence = '[%s]' % ','.join(sequence)\ndata = json.loads(sequence)\nprint data[0]['First'], data[0]['Second']\n\n(Note the json module is new in Python2.6 - if you have a lower version, download and install simplejson).\n", "it seems like a proper serialization of the Python dict, you could just do:\n>>> sequence = [\"{\\\"First\\\":\\\"Belyuen,NT,0801\\\",\\\"Second\\\":\\\"Belyuen,NT,0801\\\"}\",\"{\\\"First\\\":\\\"Larrakeyah,NT,0801\\\",\\\"Second\\\":\\\"Larrakeyah,NT,0801\\\"}\"]\n>>> import json\n>>> for i in sequence:\n d = json.loads(i)\n print(d['First'])\n\n\nBelyuen,NT,0801\nLarrakeyah,NT,0801\n\n", "you don't need regex\n>>> sequence = [\"{\\\"First\\\":\\\"Belyuen,NT,0801\\\",\\\"Second\\\":\\\"Belyuen,NT,0801\\\"}\",\"{\\\"First\\\":\\\"Larrakeyah,NT,0801\\\",\\\"Second\\\":\\\"Larrakeyah,NT,0801\\\"}\"]\n>>> for item in sequence:\n... print eval(item).values()\n...\n['Belyuen,NT,0801', 'Belyuen,NT,0801']\n['Larrakeyah,NT,0801', 'Larrakeyah,NT,0801']\n\n" ]
[ 3, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002571363_python_regex.txt
Q: What could cause Django to start failing its own tests after an OS and Django reinstall? I had to reinstall my OS, and so, I reinstalled django 1.1. Since reinstalling, when I run tests in my app, I get several failures from django.contrib.auth. Logs: http://dpaste.com/178153/ I asked on #django, and no one is too sure what the cause of the errors are. Some of my own code fails its tests, because it's not fully written yet, but that shouldn't cause django to fail it's core tests... I have included django.contrib.admin, which was mentioned as a possible cause. EDIT: Starting a fresh project, the same django internal tests fail. A: These look like django.contib.auth failures. Are including django.contib.auth in your installed apps? Have you changed either the MIDDLEWARE_CLASSES or TEMPLATE_CONTEXT_PROCESSORS in your settings file? Both of these contain default settings used by the django.contib.auth that might cause these failures. A: Asking on #django again reveals this is a known bug to do with python 2.6.5 which came with the new version of my OS, and Django 1.1.1. It has been patched in the development version.
What could cause Django to start failing its own tests after an OS and Django reinstall?
I had to reinstall my OS, and so, I reinstalled django 1.1. Since reinstalling, when I run tests in my app, I get several failures from django.contrib.auth. Logs: http://dpaste.com/178153/ I asked on #django, and no one is too sure what the cause of the errors are. Some of my own code fails its tests, because it's not fully written yet, but that shouldn't cause django to fail it's core tests... I have included django.contrib.admin, which was mentioned as a possible cause. EDIT: Starting a fresh project, the same django internal tests fail.
[ "These look like django.contib.auth failures. Are including django.contib.auth in your installed apps? Have you changed either the MIDDLEWARE_CLASSES or TEMPLATE_CONTEXT_PROCESSORS\nin your settings file? Both of these contain default settings used by the django.contib.auth that might cause these failures.\n", "Asking on #django again reveals this is a known bug to do with python 2.6.5 which came with the new version of my OS, and Django 1.1.1.\nIt has been patched in the development version.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python", "testing" ]
stackoverflow_0002555629_django_python_testing.txt
Q: One hour difference in Python I have a datetime.datetime property var. I would like to know if it is less than one hour of the current time. Something like var.hour<datetime.datetime.today().hour - 1 Problem with the above syntax is that datetime.datetime.today().hour returns a number such as "10" and it is not really a date comparation but more of a numbers comparation. What is the correct syntax? Thanks! Joel A: Use datetime.timedelta. var < datetime.datetime.today() - datetime.timedelta(hours=1) A: You can use dateutil.relativedelta from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta now = datetime.now() other_time = now + timedelta(hours=8) diff = relativedelta(other_time, now) print diff.hours # 8
One hour difference in Python
I have a datetime.datetime property var. I would like to know if it is less than one hour of the current time. Something like var.hour<datetime.datetime.today().hour - 1 Problem with the above syntax is that datetime.datetime.today().hour returns a number such as "10" and it is not really a date comparation but more of a numbers comparation. What is the correct syntax? Thanks! Joel
[ "Use datetime.timedelta.\nvar < datetime.datetime.today() - datetime.timedelta(hours=1)\n\n", "You can use dateutil.relativedelta\nfrom datetime import datetime, timedelta\nfrom dateutil.relativedelta import relativedelta\n\nnow = datetime.now()\nother_time = now + timedelta(hours=8)\ndiff = relativedelta(other_time, now)\nprint diff.hours # 8\n\n" ]
[ 16, 3 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002571432_datetime_python.txt
Q: detect the most used colour in an image using python I want to find the most used colour in an image using python. for example detect the colour of the object in the following image http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg. how to detect the base colour from the RGB codes(example - red in the above image). A: Since you will most likely not want a histogram of all the million colors that are possible using a 24-bit color space, I suggest transforming the image into HSV space instead. Then you can partition the Hue part of that space into a number of bins that describe the hues you want to find ("dark red", "orange red", or whatever). Then make a histogram of these bins and find which is the dominant hue, which is the "color". The wikipedia article http://en.wikipedia.org/wiki/HSL_and_HSV should get you started. IF you are using an image processing library chances are that a rgb-to-hsv/hsl function exists. Also, if the images are large and speed is an issue, you might consider downsampling the image to a smaller size before histogramming. A: The brute force approach is to loop over all pixels in the image and keep count of R, G, B values. A more refined approach is to use Python Image Library histogram function and calculate the average of all colors. A: I would use the Python Image Library. This is a piece of code that computes the number of white pixels/non-white pixels in an image. import sys from PIL import Image im = Image.open(sys.argv[1]) white = 0 black = 0 for i in im.getdata(): if i == (255,255,255): white += 1 else: # we assume black everything that is not white: black += 1 print im.size[0],im.size[1],white,black In your case, I would do a dictionary to keep every rgb triple against a counter, so I would rework the program like this (not tested) import sys from PIL import Image im = Image.open(sys.argv[1]) count= {} for i in im.getdata(): if not count.has_key(i): count[i] = 0 count[i] += 1 You can now check the one with the highest count and get the most used rgb triple. Of course, if you want to check also vicinal colors, you will have to convert to HSV and check the distances between different HSV points, then decide which distance is too much. Points sufficiently near in HSV space (and in particular the hue component) are most likely the same color and consequently can be summed together. A: If you are really sure that you will always have only one dominant color (no bags in two colors, e.g.), then a crude histogram on the H&S dimensions of HSV should suffice. Otherwise, you can (and should ) use mean shift. It's fairly simple, does exactly what you want, and there are libraries you can use, although I could not find anything in Python. You can either implement it, or call C++ code. The basic idea of the algorithm is this: each pixel looks at nearby pixels of similar color, and changes its color to the weighted mean of all their colors; rinse and repeat. Pretty soon you have all the colors in the image clustered very tightly around a few predominant colors. A: As suggested, it will be handier to convert your image from RGB to HSV. The standard library module colorsys contains the function rgb_to_hsv to that effect. Then, you can map colors on an image, say with H as x and S as y. Select points in that space, and give them names; the more points, the better. Then, for every pixel in your image, find the closest of the points you selected and use its name as the pixel value. Count which name occurs most times. Do you want me to supply code? A: Sort the pixels in-place, then loop through the image and find the longest run.
detect the most used colour in an image using python
I want to find the most used colour in an image using python. for example detect the colour of the object in the following image http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg. how to detect the base colour from the RGB codes(example - red in the above image).
[ "Since you will most likely not want a histogram of all the million colors that are possible using a 24-bit color space, I suggest transforming the image into HSV space instead.\nThen you can partition the Hue part of that space into a number of bins that describe the hues you want to find (\"dark red\", \"orange red\", or whatever). Then make a histogram of these bins and find which is the dominant hue, which is the \"color\".\nThe wikipedia article http://en.wikipedia.org/wiki/HSL_and_HSV should get you started. IF you are using an image processing library chances are that a rgb-to-hsv/hsl function exists.\nAlso, if the images are large and speed is an issue, you might consider downsampling the image to a smaller size before histogramming.\n", "The brute force approach is to loop over all pixels in the image and keep count of R, G, B values. A more refined approach is to use Python Image Library histogram function and calculate the average of all colors.\n", "I would use the Python Image Library. This is a piece of code that computes the number of white pixels/non-white pixels in an image. \nimport sys\n\nfrom PIL import Image\n\nim = Image.open(sys.argv[1])\nwhite = 0\nblack = 0\nfor i in im.getdata():\n if i == (255,255,255):\n white += 1\n else:\n # we assume black everything that is not white:\n black += 1\nprint im.size[0],im.size[1],white,black\n\nIn your case, I would do a dictionary to keep every rgb triple against a counter, so I would rework the program like this (not tested)\nimport sys\n\nfrom PIL import Image\n\nim = Image.open(sys.argv[1])\ncount= {}\nfor i in im.getdata():\n if not count.has_key(i):\n count[i] = 0\n\n count[i] += 1\n\nYou can now check the one with the highest count and get the most used rgb triple. Of course, if you want to check also vicinal colors, you will have to convert to HSV and check the distances between different HSV points, then decide which distance is too much. Points sufficiently near in HSV space (and in particular the hue component) are most likely the same color and consequently can be summed together.\n", "If you are really sure that you will always have only one dominant color (no bags in two colors, e.g.), then a crude histogram on the H&S dimensions of HSV should suffice. \nOtherwise, you can (and should ) use mean shift. It's fairly simple, does exactly what you want, and there are libraries you can use, although I could not find anything in Python. You can either implement it, or call C++ code.\nThe basic idea of the algorithm is this: each pixel looks at nearby pixels of similar color, and changes its color to the weighted mean of all their colors; rinse and repeat. Pretty soon you have all the colors in the image clustered very tightly around a few predominant colors.\n", "As suggested, it will be handier to convert your image from RGB to HSV. The standard library module colorsys contains the function rgb_to_hsv to that effect. Then, you can map colors on an image, say with H as x and S as y. Select points in that space, and give them names; the more points, the better. Then, for every pixel in your image, find the closest of the points you selected and use its name as the pixel value. Count which name occurs most times.\nDo you want me to supply code?\n", "Sort the pixels in-place, then loop through the image and find the longest run.\n" ]
[ 5, 3, 2, 1, 1, 0 ]
[]
[]
[ "colors", "image_processing", "python" ]
stackoverflow_0002423743_colors_image_processing_python.txt
Q: Self-referential ReferenceProperty in Google App Engine I'm having a bit of trouble with ReferencePropertys in App Engine (Python). For a bit of fun, I'm trying to model a folder/file system, but having trouble getting folders to reference folders. My first attempt was this: class Folder(db.Model): id = db.StringProperty() name = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) folder = db.ReferenceProperty(Folder, collection_name="folders") But that fails as "Folder" isn't defined when "folder" is trying to be defined. I've also tried defining "folder" outside of the main declaration for "Folder", like so: class Folder(db.Model): id = db.StringProperty() name = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) Folder.folder = db.ReferenceProperty(Folder, collection_name="folders") But that fails with: AttributeError: 'Folder' object has no attribute 'folders' I'm kind of stumped. Does anyone have experience with this, or a solution to this problem? Thanks in advance. A: That's exactly what SelfReferenceProperty is for. A: You could create a separate model to link the two, named something like FolderChild: class FolderChild(db.Model): parent = db.ReferenceProperty(Folder) child = db.ReferenceProperty(Folder, collection_name="children")
Self-referential ReferenceProperty in Google App Engine
I'm having a bit of trouble with ReferencePropertys in App Engine (Python). For a bit of fun, I'm trying to model a folder/file system, but having trouble getting folders to reference folders. My first attempt was this: class Folder(db.Model): id = db.StringProperty() name = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) folder = db.ReferenceProperty(Folder, collection_name="folders") But that fails as "Folder" isn't defined when "folder" is trying to be defined. I've also tried defining "folder" outside of the main declaration for "Folder", like so: class Folder(db.Model): id = db.StringProperty() name = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) Folder.folder = db.ReferenceProperty(Folder, collection_name="folders") But that fails with: AttributeError: 'Folder' object has no attribute 'folders' I'm kind of stumped. Does anyone have experience with this, or a solution to this problem? Thanks in advance.
[ "That's exactly what SelfReferenceProperty is for.\n", "You could create a separate model to link the two, named something like FolderChild:\nclass FolderChild(db.Model):\n parent = db.ReferenceProperty(Folder)\n child = db.ReferenceProperty(Folder, collection_name=\"children\")\n\n" ]
[ 9, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002571507_google_app_engine_python.txt
Q: Appengine Apps Vs Google bot web crawler i built an appengine web app cricket.hover.in. The web app consists of about 15k url's linked in it, But even after a long time of my launch, no pages are indexed on google. Any base link place on my root site hover.in are being indexed with in minutes. but i placed the same link home page of root site a long back. but its of no use. can any one analyse , if there is any issue with cricket.hover.in or if bots have any issues with Google app engine actually tested the url using labs app of webmaster tools of google there the return is fine and html is clear. but when tested the same (cricket.hover.in) at the following urls its showing different results of failure www.dnsqueries.com/en/googlebot_simulator.php www.smart-it-consulting.com/internet/google/googlebot-spoofer/ but if i test some of my php or word press links at the above url's the results are good and fine. Sorry my mistake in question, excuse me for misleading. the domain is cricket.trak.in/, its referred from the base URL trak.in. made the mistake in half mind of not finding a solution for the issue after a long investigation. please check with this domain. submitted site map 3 days back it almost submitted 22k uri in total, but by the present day indexed count is still 0. secondly cricket.trak.in itself doesn't return 15k uri, what i mean is the site in total if crawled would return about 15k uri. A: Well, from this corner of the cyberspace, there is no such domain cricket.hover.in. $ dig cricket.hover.in. ; <<>> DiG 9.6.1-P2 <<>> cricket.hover.in. ;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 30665 I'd also guess that a URL that returns 15k hrefs is considered utterly useless spam by many spiders which will ignore it even if they can reach it. A: Does your site have proper sitemaps and have you pushed them to Google and other search engines? I can't check because http://cricket.hover.in gives me a 404, so it could be a DNS problem. What happens when you point your browser to that URL?
Appengine Apps Vs Google bot web crawler
i built an appengine web app cricket.hover.in. The web app consists of about 15k url's linked in it, But even after a long time of my launch, no pages are indexed on google. Any base link place on my root site hover.in are being indexed with in minutes. but i placed the same link home page of root site a long back. but its of no use. can any one analyse , if there is any issue with cricket.hover.in or if bots have any issues with Google app engine actually tested the url using labs app of webmaster tools of google there the return is fine and html is clear. but when tested the same (cricket.hover.in) at the following urls its showing different results of failure www.dnsqueries.com/en/googlebot_simulator.php www.smart-it-consulting.com/internet/google/googlebot-spoofer/ but if i test some of my php or word press links at the above url's the results are good and fine. Sorry my mistake in question, excuse me for misleading. the domain is cricket.trak.in/, its referred from the base URL trak.in. made the mistake in half mind of not finding a solution for the issue after a long investigation. please check with this domain. submitted site map 3 days back it almost submitted 22k uri in total, but by the present day indexed count is still 0. secondly cricket.trak.in itself doesn't return 15k uri, what i mean is the site in total if crawled would return about 15k uri.
[ "Well, from this corner of the cyberspace, there is no such domain cricket.hover.in. \n$ dig cricket.hover.in.\n; <<>> DiG 9.6.1-P2 <<>> cricket.hover.in.\n;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 30665\n\nI'd also guess that a URL that returns 15k hrefs is considered utterly useless spam by many spiders which will ignore it even if they can reach it.\n", "Does your site have proper sitemaps and have you pushed them to Google and other search engines? I can't check because http://cricket.hover.in gives me a 404, so it could be a DNS problem. What happens when you point your browser to that URL?\n" ]
[ 2, 1 ]
[]
[]
[ "bots", "google_app_engine", "python", "seo", "web_crawler" ]
stackoverflow_0002571701_bots_google_app_engine_python_seo_web_crawler.txt
Q: Is there a good way of automatically generating javascript client code from server side python I basically want to be able to: Write a few functions in python (with the minimum amount of extra meta data) Turn these functions into a web service (with the minimum of effort / boiler plate) Automatically generate some javascript functions / objects for rpc (this should prevent me from doing as many stupid things as possible like mistyping method names, forgetting the names of methods, passing the wrong number of arguments) Example python: def hello_world(): return "Hello world" javascript: ... <!-- This file is automatically generated (either dynamically or statically) --> <script src="http://myurl.com/webservice/client_side_javascript"> </script> ... <script> $('#button').click(function () { hello_world(function (data){ $('#label').text(data))) } </script> A bit of research has shown me some approaches that come close to this: Automatic generation of json-rpc services from functions with a little boiler plate code in python and then using jquery and json to do the calls (still easy to make mistakes with method names - still need to be aware of urls when calling, very irritating to write these calls yourself in the firebug shell) Using a library like soaplib to generate wsdl from python (by adding copious type information). And then somehow convert this into javascript (not sure if there is even a library to do this) But are there any approaches closer to what I want? A: Yes there is, there is Pyjamas. Some people bill this as the "GWT for Python" A: It looks like using a javascript XML RPC client (there is jquery plugin for this) together with an XML RPC server is a good way to go. The jquery plugin will introspect your rpc service and will populate method names make it impossible to mis type the name of a method call without getting early warning. It will not however test the number of arguments that you pass, or their type. There doesn't seem to be the same support for introspection on json rpc (or rather there doesn't seem to be a consistent standard). This approach can also be used with django. I've put together some example code and uploaded it here (I hope that linking to one's blog posts isn't considered terrible form - a brief search of the internet didn't seem to suggest it was)...
Is there a good way of automatically generating javascript client code from server side python
I basically want to be able to: Write a few functions in python (with the minimum amount of extra meta data) Turn these functions into a web service (with the minimum of effort / boiler plate) Automatically generate some javascript functions / objects for rpc (this should prevent me from doing as many stupid things as possible like mistyping method names, forgetting the names of methods, passing the wrong number of arguments) Example python: def hello_world(): return "Hello world" javascript: ... <!-- This file is automatically generated (either dynamically or statically) --> <script src="http://myurl.com/webservice/client_side_javascript"> </script> ... <script> $('#button').click(function () { hello_world(function (data){ $('#label').text(data))) } </script> A bit of research has shown me some approaches that come close to this: Automatic generation of json-rpc services from functions with a little boiler plate code in python and then using jquery and json to do the calls (still easy to make mistakes with method names - still need to be aware of urls when calling, very irritating to write these calls yourself in the firebug shell) Using a library like soaplib to generate wsdl from python (by adding copious type information). And then somehow convert this into javascript (not sure if there is even a library to do this) But are there any approaches closer to what I want?
[ "Yes there is, there is Pyjamas. Some people bill this as the \"GWT for Python\"\n", "It looks like using a javascript XML RPC client (there is jquery plugin for this) together with an XML RPC server is a good way to go.\nThe jquery plugin will introspect your rpc service and will populate method names make it impossible to mis type the name of a method call without getting early warning. It will not however test the number of arguments that you pass, or their type.\nThere doesn't seem to be the same support for introspection on json rpc (or rather there doesn't seem to be a consistent standard). This approach can also be used with django.\nI've put together some example code and uploaded it here (I hope that linking to one's blog posts isn't considered terrible form - a brief search of the internet didn't seem to suggest it was)...\n" ]
[ 6, 0 ]
[]
[]
[ "javascript", "python", "rpc" ]
stackoverflow_0002541954_javascript_python_rpc.txt
Q: Python2.6 Decimal to Octal How can i convert decimal to Octal in Python2.6, for 1 to 100000? I wanna get this converted result as .txt too. Can someone help me? A: Use the oct function: print oct(9) # prints 011 A: This should do the trick: text = '\n'.join(str(oct(i)) for i in xrange(100000)) f = open('foo.txt', 'w') f.write(text) f.close()
Python2.6 Decimal to Octal
How can i convert decimal to Octal in Python2.6, for 1 to 100000? I wanna get this converted result as .txt too. Can someone help me?
[ "Use the oct function:\nprint oct(9) # prints 011\n\n", "This should do the trick:\ntext = '\\n'.join(str(oct(i)) for i in xrange(100000))\nf = open('foo.txt', 'w')\nf.write(text)\nf.close()\n\n" ]
[ 15, 1 ]
[]
[]
[ "decimal", "octal", "python" ]
stackoverflow_0002571840_decimal_octal_python.txt
Q: How can I configure vim syntax highlighting for mako templates? I'd like to get the HTML elements highlighted as well as the MAKO / Python elements. Thanks. A: This syntax file should (at least) highlight the mako elements.
How can I configure vim syntax highlighting for mako templates?
I'd like to get the HTML elements highlighted as well as the MAKO / Python elements. Thanks.
[ "This syntax file should (at least) highlight the mako elements.\n" ]
[ 4 ]
[]
[]
[ "mako", "python", "vim" ]
stackoverflow_0002571893_mako_python_vim.txt
Q: Referencing other modules in atexit I have a function that is responsible for killing a child process when the program ends: class MySingleton: def __init__(self): import atexit atexit.register(self.stop) def stop(self): os.kill(self.sel_server_pid, signal.SIGTERM) However I get an error message when this function is called: Traceback (most recent call last): File "/usr/lib/python2.5/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/home/commando/Development/Diploma/streaminatr/stream/selenium_tests.py", line 66, in stop os.kill(self.sel_server_pid, signal.SIGTERM) AttributeError: 'NoneType' object has no attribute 'kill' Looks like the os and signal modules get unloaded before atexit is called. Re-importing them solves the problem, but this behaviour seems weird to me - these modules are imported before I register my handler, so why are they unloaded before my own exit handler runs? A: There are no strong guarantees about the order in which things are destroyed at program termination time, so it's best to ensure atexit-registered functions are self contained. E.g., in your case: class MySingleton: def __init__(self): import atexit atexit.register(self.stop) self._dokill = os.kill self._thesig = signal.SIGTERM def stop(self): self._dokill(self.sel_server_pid, self._thesig) This is preferable to re-importing modules (which could conceivably cause slowdown of program termination and even unending loops, though that risk is lesser for "system-supplied" modules such as os).
Referencing other modules in atexit
I have a function that is responsible for killing a child process when the program ends: class MySingleton: def __init__(self): import atexit atexit.register(self.stop) def stop(self): os.kill(self.sel_server_pid, signal.SIGTERM) However I get an error message when this function is called: Traceback (most recent call last): File "/usr/lib/python2.5/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/home/commando/Development/Diploma/streaminatr/stream/selenium_tests.py", line 66, in stop os.kill(self.sel_server_pid, signal.SIGTERM) AttributeError: 'NoneType' object has no attribute 'kill' Looks like the os and signal modules get unloaded before atexit is called. Re-importing them solves the problem, but this behaviour seems weird to me - these modules are imported before I register my handler, so why are they unloaded before my own exit handler runs?
[ "There are no strong guarantees about the order in which things are destroyed at program termination time, so it's best to ensure atexit-registered functions are self contained. E.g., in your case:\nclass MySingleton:\n def __init__(self):\n import atexit\n atexit.register(self.stop)\n self._dokill = os.kill\n self._thesig = signal.SIGTERM\n\n def stop(self):\n self._dokill(self.sel_server_pid, self._thesig)\n\nThis is preferable to re-importing modules (which could conceivably cause slowdown of program termination and even unending loops, though that risk is lesser for \"system-supplied\" modules such as os).\n" ]
[ 9 ]
[]
[]
[ "atexit", "python" ]
stackoverflow_0002572172_atexit_python.txt
Q: Using CookieJar in Python to log in to a website from "Google App Engine". What's wrong here? I've been trying to find a python code that would log in to my mail box on yahoo.com from "Google App Engine" . Here (click here to see that page) I was given this code: import urllib, urllib2, cookielib url = "https://login.yahoo.com/config/login?" form_data = {'login' : 'my-login-here', 'passwd' : 'my-password-here'} jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) form_data = urllib.urlencode(form_data) # data returned from this pages contains redirection resp = opener.open(url, form_data) # yahoo redirects to http://my.yahoo.com, so lets go there instead resp = opener.open('http://mail.yahoo.com') print resp.read() The author of this script looked into HTML script of yahoo log-in form and came up with this script. That log-in form contains two fields, one for users' Yahoo! ID and another one is for users' password. Here is how HTML code of that page for both of those fields looks like: User ID field: <input type="text" maxlength="96" class="yreg_ipt" size="17" value="" id="username" name="login"> Password field: <input type="password" maxlength="64" class="yreg_ipt" size="17" value="" id="passwd" name="passwd"> However, when I uploaded this code to Google App Engine I discovered that this log-in form keeps coming back to me, which, I assume, means that logging-in process didn't succeed. Why is it so? A: You send MD5 hash and not plain password. Also you'd have to play along with all kinds of CSRF protections etc. that they're implementing. Look: <input type="hidden" name=".tries" value="1"> <input type="hidden" name=".src" value="ym"> <input type="hidden" name=".md5" value=""> <input type="hidden" name=".hash" value=""> <input type="hidden" name=".js" value=""> <input type="hidden" name=".last" value=""> <input type="hidden" name="promo" value=""> <input type="hidden" name=".intl" value="us"> <input type="hidden" name=".bypass" value=""> <input type="hidden" name=".partner" value=""> <input type="hidden" name=".u" value="bd5tdpd5rf2pg"> <input type="hidden" name=".v" value="0"> <input type="hidden" name=".challenge" value="5qUiIPGVFzRZ2BHhvtdGXoehfiOj"> <input type="hidden" name=".yplus" value=""> <input type="hidden" name=".emailCode" value=""> <input type="hidden" name="pkg" value=""> <input type="hidden" name="stepid" value=""> <input type="hidden" name=".ev" value=""> <input type="hidden" name="hasMsgr" value="0"> <input type="hidden" name=".chkP" value="Y"> <input type="hidden" name=".done" value="http://mail.yahoo.com"> <input type="hidden" name=".pd" value="ym_ver=0&c=&ivt=&sg="> Launch Wireshark and play with it. Good luck :) However if you intend to use it w/ App Engine keep in my mind that using Google IP will almost surely result w/ Captcha challenge. Also Yahoo might block your User-Agent that is being set permanently by Google.
Using CookieJar in Python to log in to a website from "Google App Engine". What's wrong here?
I've been trying to find a python code that would log in to my mail box on yahoo.com from "Google App Engine" . Here (click here to see that page) I was given this code: import urllib, urllib2, cookielib url = "https://login.yahoo.com/config/login?" form_data = {'login' : 'my-login-here', 'passwd' : 'my-password-here'} jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) form_data = urllib.urlencode(form_data) # data returned from this pages contains redirection resp = opener.open(url, form_data) # yahoo redirects to http://my.yahoo.com, so lets go there instead resp = opener.open('http://mail.yahoo.com') print resp.read() The author of this script looked into HTML script of yahoo log-in form and came up with this script. That log-in form contains two fields, one for users' Yahoo! ID and another one is for users' password. Here is how HTML code of that page for both of those fields looks like: User ID field: <input type="text" maxlength="96" class="yreg_ipt" size="17" value="" id="username" name="login"> Password field: <input type="password" maxlength="64" class="yreg_ipt" size="17" value="" id="passwd" name="passwd"> However, when I uploaded this code to Google App Engine I discovered that this log-in form keeps coming back to me, which, I assume, means that logging-in process didn't succeed. Why is it so?
[ "You send MD5 hash and not plain password. Also you'd have to play along with all kinds of CSRF protections etc. that they're implementing. Look:\n <input type=\"hidden\" name=\".tries\" value=\"1\"> \n <input type=\"hidden\" name=\".src\" value=\"ym\"> \n <input type=\"hidden\" name=\".md5\" value=\"\"> \n <input type=\"hidden\" name=\".hash\" value=\"\"> \n <input type=\"hidden\" name=\".js\" value=\"\"> \n <input type=\"hidden\" name=\".last\" value=\"\"> \n <input type=\"hidden\" name=\"promo\" value=\"\"> \n <input type=\"hidden\" name=\".intl\" value=\"us\"> \n <input type=\"hidden\" name=\".bypass\" value=\"\"> \n <input type=\"hidden\" name=\".partner\" value=\"\"> \n <input type=\"hidden\" name=\".u\" value=\"bd5tdpd5rf2pg\"> \n <input type=\"hidden\" name=\".v\" value=\"0\"> \n <input type=\"hidden\" name=\".challenge\" value=\"5qUiIPGVFzRZ2BHhvtdGXoehfiOj\"> \n <input type=\"hidden\" name=\".yplus\" value=\"\"> \n <input type=\"hidden\" name=\".emailCode\" value=\"\"> \n <input type=\"hidden\" name=\"pkg\" value=\"\"> \n <input type=\"hidden\" name=\"stepid\" value=\"\"> \n <input type=\"hidden\" name=\".ev\" value=\"\"> \n <input type=\"hidden\" name=\"hasMsgr\" value=\"0\"> \n <input type=\"hidden\" name=\".chkP\" value=\"Y\"> \n <input type=\"hidden\" name=\".done\" value=\"http://mail.yahoo.com\"> \n <input type=\"hidden\" name=\".pd\" value=\"ym_ver=0&c=&ivt=&sg=\"> \n\nLaunch Wireshark and play with it. Good luck :)\nHowever if you intend to use it w/ App Engine keep in my mind that using Google IP will almost surely result w/ Captcha challenge. Also Yahoo might block your User-Agent that is being set permanently by Google.\n" ]
[ 3 ]
[]
[]
[ "cookiejar", "google_app_engine", "logging", "python" ]
stackoverflow_0002571450_cookiejar_google_app_engine_logging_python.txt
Q: Python's urllib2 doesn't work on some sites I found that you can't read from some sites using Python's urllib2(or urllib). An example... urllib2.urlopen("http://www.dafont.com/").read() # Returns '' These sites work when you visit the site with a browser. I can even scrape them using PHP(didn't try other languages). I have seen other sites with the same issue - but can't remember the URL at the moment. My questions are... What is the cause of this issue? Any workarounds? A: I believe it gets blocked by the User-Agent. You can change User-Agent using the following sample code: USERAGENT = 'something' HEADERS = {'User-Agent': USERAGENT} req = urllib2.Request(URL_HERE, headers=HEADERS) f = urllib2.urlopen(req) s = f.read() f.close() A: Try setting a different user agent. Check the answers in this link. A: I'm the guy who posted the question. I have some suspicions - but not sure about them - that's why I posted the question here. What is the cause of this issue? I think its due to the host blocking the urllib library using robot.txt or htaccess. But not sure about it. Not even sure if its possible. Any workaround for this issue? If you are in Unix, this will work... contents = commands.getoutput("curl -s '"+url+"'")
Python's urllib2 doesn't work on some sites
I found that you can't read from some sites using Python's urllib2(or urllib). An example... urllib2.urlopen("http://www.dafont.com/").read() # Returns '' These sites work when you visit the site with a browser. I can even scrape them using PHP(didn't try other languages). I have seen other sites with the same issue - but can't remember the URL at the moment. My questions are... What is the cause of this issue? Any workarounds?
[ "I believe it gets blocked by the User-Agent. You can change User-Agent using the following sample code:\nUSERAGENT = 'something'\nHEADERS = {'User-Agent': USERAGENT}\n\nreq = urllib2.Request(URL_HERE, headers=HEADERS)\nf = urllib2.urlopen(req)\ns = f.read()\nf.close()\n\n", "Try setting a different user agent. Check the answers in this link.\n", "I'm the guy who posted the question. I have some suspicions - but not sure about them - that's why I posted the question here.\nWhat is the cause of this issue?\nI think its due to the host blocking the urllib library using robot.txt or htaccess. But not sure about it. Not even sure if its possible.\nAny workaround for this issue?\nIf you are in Unix, this will work...\ncontents = commands.getoutput(\"curl -s '\"+url+\"'\")\n\n" ]
[ 6, 3, 0 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0002572266_python_urllib_urllib2.txt
Q: Returning a list in this recursive coi function in python I'm having trouble getting my list to return in my code. Instead of returning the list, it keeps returning None, but if I replace the return with print in the elif statement, it prints the list just fine. How can I repair this? def makeChange2(amount, coinDenomination, listofcoins = None): #makes a list of coins from an amount given by using a greedy algorithm coinDenomination.sort() #reverse the list to make the largest position 0 at all times coinDenomination.reverse() #assigns list if listofcoins is None: listofcoins = [] if amount >= coinDenomination[0]: listofcoins = listofcoins + [coinDenomination[0]] makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins) elif amount == 0: return listofcoins else: makeChange2(amount, coinDenomination[1:], listofcoins) A: You're not returning the value of the recursive calls to makeChange2. Once control reaches either of those calls to makeChange2 and completes the call, the program continues to the next statement, which is the end of the function; thus, it returns None. If that concept is still giving you trouble, try running this simple factorial program with and without the return keyword in the return n*factorial(n-1) line: def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n-1) print factorial(3) Manually walking through the code should help elucidate what was wrong in your original program.
Returning a list in this recursive coi function in python
I'm having trouble getting my list to return in my code. Instead of returning the list, it keeps returning None, but if I replace the return with print in the elif statement, it prints the list just fine. How can I repair this? def makeChange2(amount, coinDenomination, listofcoins = None): #makes a list of coins from an amount given by using a greedy algorithm coinDenomination.sort() #reverse the list to make the largest position 0 at all times coinDenomination.reverse() #assigns list if listofcoins is None: listofcoins = [] if amount >= coinDenomination[0]: listofcoins = listofcoins + [coinDenomination[0]] makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins) elif amount == 0: return listofcoins else: makeChange2(amount, coinDenomination[1:], listofcoins)
[ "You're not returning the value of the recursive calls to makeChange2.\nOnce control reaches either of those calls to makeChange2 and completes the call, the program continues to the next statement, which is the end of the function; thus, it returns None.\nIf that concept is still giving you trouble, try running this simple factorial program with and without the return keyword in the return n*factorial(n-1) line:\ndef factorial(n):\n if n == 0 or n == 1:\n return 1\n return n * factorial(n-1)\n\nprint factorial(3)\n\nManually walking through the code should help elucidate what was wrong in your original program.\n" ]
[ 3 ]
[]
[]
[ "list", "python", "recursion" ]
stackoverflow_0002572313_list_python_recursion.txt
Q: How do I change my current directory from a python script? I'm trying to implement my own version of the 'cd' command that presents the user with a list of hard-coded directories to choose from, and the user has to enter a number corresponding to an entry in the list. The program, named my_cd.py for now, should then effectively 'cd' the user to the chosen directory. Example of how this should work: /some/directory $ my_cd.py 1) ~ 2) /bin/ 3) /usr Enter menu selection, or q to quit: 2 /bin $ Currently, I'm trying to 'cd' using os.chdir('dir'). However, this doesn't work, probably because my_cd.py is kicked off in its own child process. I tried wrapping the call to my_cd.py in a sourced bash script named my_cd.sh: #! /bin/bash function my_cd() { /path/to/my_cd.py } /some/directory $ . my_cd.sh $ my_cd ... shows list of dirs, but doesn't 'cd' in the interactive shell Any ideas on how I can get this to work? Is it possible to change my interactive shell's current directory from a python script? A: Change your sourced bash code to: #! /bin/bash function my_cd() { cd `/path/to/my_cd.py` } and your Python code to do all of its cosmetic output (messages to the users, menus, etc) on sys.stderr, and, at the end, instead of os.chdir, just print (to sys.stdout) the path to which the directory should be changed. A: my_cd.py: #!/usr/bin/env python import sys dirs = ['/usr/bin', '/bin', '~'] for n, dir in enumerate(dirs): sys.stderr.write('%d) %s\n' % (n+1, dir)) sys.stderr.write('Choice: ') n = int(raw_input()) print dirs[n-1] Usage: nosklo:/tmp$ alias mcd="cd \$(/path/to/my_cd.py)" nosklo:/tmp$ mcd 1) /usr/bin 2) /bin 3) ~ Choice: 1 nosklo:/usr/bin$ A: This can't be done. Changes to the working directory are not visible to parent processes. At best you could have the Python script print the directory to change to, then have the sourced script actually change to that directory. A: For what its worth, since this question is also tagged "bash", here is a simple bash-only solution: $ cat select_cd #!/bin/bash PS3="Number: " dir_choices="/home/klittle /local_home/oracle" select CHOICE in $dir_choices; do break done [[ "$CHOICE" != "" ]] && eval 'cd '$CHOICE Now, this script must be source'd, not executed: $ pwd /home/klittle/bin $ source select_cd 1) /home/klittle 2) /local_home/oracle Number: 2 $ pwd /local_home/oracle So, $ alias mycd='source /home/klittle/bin/select_cd' $ mycd 1) /home/klittle 2) /local_home/oracle Number: To solve your case, you could have the command the user runs be an alias that sources a bash script, which does the dir selection first, then dives into a python program after the cd has been done. A: Contrary to what was said, you can do this by replacing the process image, twice. In bash, replace your my_cd function with: function my_cd() { exec /path/to/my_cd.py "$BASH" "$0" } Then your python script has to finish with: os.execl(sys.argv[1], sys.argv[2]) Remember to import os, sys at the beginning of the script. But note that this is borderline hack. Your shell dies, replacing itself with the python script, running in the same process. The python script makes changes to the environment and replaces itself with the shell, back again, still in the same process. This means that if you have some other local unsaved and unexported data or environment in the previous shell session, it will not persist to the new one. It also means that rc and profile scripts will run again (not usually a problem).
How do I change my current directory from a python script?
I'm trying to implement my own version of the 'cd' command that presents the user with a list of hard-coded directories to choose from, and the user has to enter a number corresponding to an entry in the list. The program, named my_cd.py for now, should then effectively 'cd' the user to the chosen directory. Example of how this should work: /some/directory $ my_cd.py 1) ~ 2) /bin/ 3) /usr Enter menu selection, or q to quit: 2 /bin $ Currently, I'm trying to 'cd' using os.chdir('dir'). However, this doesn't work, probably because my_cd.py is kicked off in its own child process. I tried wrapping the call to my_cd.py in a sourced bash script named my_cd.sh: #! /bin/bash function my_cd() { /path/to/my_cd.py } /some/directory $ . my_cd.sh $ my_cd ... shows list of dirs, but doesn't 'cd' in the interactive shell Any ideas on how I can get this to work? Is it possible to change my interactive shell's current directory from a python script?
[ "Change your sourced bash code to:\n#! /bin/bash\nfunction my_cd() {\n cd `/path/to/my_cd.py`\n}\n\nand your Python code to do all of its cosmetic output (messages to the users, menus, etc) on sys.stderr, and, at the end, instead of os.chdir, just print (to sys.stdout) the path to which the directory should be changed.\n", "my_cd.py:\n#!/usr/bin/env python\nimport sys\n\ndirs = ['/usr/bin', '/bin', '~']\nfor n, dir in enumerate(dirs):\n sys.stderr.write('%d) %s\\n' % (n+1, dir))\nsys.stderr.write('Choice: ')\nn = int(raw_input())\nprint dirs[n-1]\n\nUsage:\nnosklo:/tmp$ alias mcd=\"cd \\$(/path/to/my_cd.py)\"\nnosklo:/tmp$ mcd\n1) /usr/bin\n2) /bin\n3) ~\nChoice: 1\nnosklo:/usr/bin$ \n\n", "This can't be done. Changes to the working directory are not visible to parent processes. At best you could have the Python script print the directory to change to, then have the sourced script actually change to that directory.\n", "For what its worth, since this question is also tagged \"bash\", here is a simple bash-only solution:\n$ cat select_cd\n#!/bin/bash\n\nPS3=\"Number: \"\n\ndir_choices=\"/home/klittle /local_home/oracle\"\n\nselect CHOICE in $dir_choices; do\n break\ndone\n\n[[ \"$CHOICE\" != \"\" ]] && eval 'cd '$CHOICE\n\nNow, this script must be source'd, not executed:\n$ pwd\n/home/klittle/bin\n$ source select_cd\n1) /home/klittle\n2) /local_home/oracle\nNumber: 2\n$ pwd\n/local_home/oracle\n\nSo,\n$ alias mycd='source /home/klittle/bin/select_cd'\n$ mycd\n1) /home/klittle\n2) /local_home/oracle\nNumber:\n\nTo solve your case, you could have the command the user runs be an alias that sources a bash script, which does the dir selection first, then dives into a python program after the cd has been done.\n", "Contrary to what was said, you can do this by replacing the process image, twice.\nIn bash, replace your my_cd function with:\nfunction my_cd() {\n exec /path/to/my_cd.py \"$BASH\" \"$0\"\n}\n\nThen your python script has to finish with:\nos.execl(sys.argv[1], sys.argv[2])\n\nRemember to import os, sys at the beginning of the script.\nBut note that this is borderline hack. Your shell dies, replacing itself with the python script, running in the same process. The python script makes changes to the environment and replaces itself with the shell, back again, still in the same process. This means that if you have some other local unsaved and unexported data or environment in the previous shell session, it will not persist to the new one. It also means that rc and profile scripts will run again (not usually a problem).\n" ]
[ 7, 3, 2, 2, 1 ]
[]
[]
[ "bash", "cd", "directory", "python", "shell" ]
stackoverflow_0002571524_bash_cd_directory_python_shell.txt
Q: Django ORM: Ordering w/ aggregate functions — None special treatment I'm doing this query: SomeObject.objects.annotate(something=Avg('something')).order_by(something).all() I normally have an aggregate field in my model that I use with Django signals to keep in sync, however in this case perfomance isn't an issue so I thought I'd keep it simple and just use subqueries. This approach, however, presented an unexpected issue. It all works great if aggregate function results are like: [5.0, 4.0, 6.0 … (etc, just numbers)] However if you mix in some None's than it is ordered like this: [None, 5.0, 4.0 …] The issue is that None has higher value than any number, while it should have value at most a value of 0. I'm using PostgreSQL and haven't tested w/ other DBs. I haven't actually checked what query is generated etc. I worked it around by just sorting in memory: sorted(…, key=lambda _:_.avg_rating if _.avg_rating is not None else 0) So I'm just curious if there is a way to do it with just the Django ORM? Perhaps .where? Or something else? A: How about just adding a has_something=1,0 via extra() and then order on both has_something and something? with_avg = SomeObject.objects.annotate(avg=Avg('something')) with_avg_and_has = with_avg.extra(select={'has_something': 'something is NULL'}) sorted_result = with_avg_and_has.order_by('-has_something', '-avg').all() Not 100% ORM in the strictest sense but it does push the sorting back into the DB.
Django ORM: Ordering w/ aggregate functions — None special treatment
I'm doing this query: SomeObject.objects.annotate(something=Avg('something')).order_by(something).all() I normally have an aggregate field in my model that I use with Django signals to keep in sync, however in this case perfomance isn't an issue so I thought I'd keep it simple and just use subqueries. This approach, however, presented an unexpected issue. It all works great if aggregate function results are like: [5.0, 4.0, 6.0 … (etc, just numbers)] However if you mix in some None's than it is ordered like this: [None, 5.0, 4.0 …] The issue is that None has higher value than any number, while it should have value at most a value of 0. I'm using PostgreSQL and haven't tested w/ other DBs. I haven't actually checked what query is generated etc. I worked it around by just sorting in memory: sorted(…, key=lambda _:_.avg_rating if _.avg_rating is not None else 0) So I'm just curious if there is a way to do it with just the Django ORM? Perhaps .where? Or something else?
[ "How about just adding a has_something=1,0 via extra() and then order on both has_something and something?\nwith_avg = SomeObject.objects.annotate(avg=Avg('something'))\nwith_avg_and_has = with_avg.extra(select={'has_something': 'something is NULL'})\nsorted_result = with_avg_and_has.order_by('-has_something', '-avg').all() \n\nNot 100% ORM in the strictest sense but it does push the sorting back into the DB.\n" ]
[ 2 ]
[]
[]
[ "aggregate", "django", "orm", "python" ]
stackoverflow_0002572201_aggregate_django_orm_python.txt
Q: Python lambda returning None instead of empty string I have the following lambda function: f = lambda x: x == None and '' or x It should return an empty string if it receives None as the argument, or the argument if it's not None. For example: >>> f(4) 4 >>> f(None) >>> If I call f(None) instead of getting an empty string I get None. I printed the type of what the function returned and I got NoneType. I was expecting string. type('') returns string, so I'd like to know why the lambda doesn't return an empty string when I pass None as an argument. I'm fairly new to lambdas so I might have misunderstood some things about how they work. A: use the if else construct f = lambda x:'' if x is None else x A: The problem in your case that '' is considered as boolean False. bool('') == False. You can use f =lambda x:x if x is not None else '' A: The problem is that Python treats the empty string as False. When you pass None to your function, it evaluates to: None == None and '' or None which (effectively) becomes: True and False or None then: False or None and finally: None One solution would be: lambda x: x if x is not None else '' If you know x will be either a string or None, then you can leverage the fact that None is also a False value in Python: lambda x: x or '' A: Python gives and a higher precedence than or, so the parentheses fall here: lambda x: (x == None and '') or x When passed None, this becomes (True and '') or None. Python’s boolean operators work by returning one argument or another (whence this little trick), so this reduces to '' or None, and finally None. This little trick stems from back before Python 2.5, which didn't have the conditional operator. The caveat, which you just ran into, is that it doesn’t behave as expected when True branch has a False value. Unless you’re concerned with Python ≤ 2.4, just use the conditional operator. A: It's not lambdas that are the problem here. It's the pythonic if/else expressiong you are using there. (condition) and (expression1) or (expression2) most of the times means the (condition) ? (expression1) : (expression2) you'd expect, except when expression1 evaluates to False. This is because the whole thing is evaluated in order. If condition fails, expression1 is evaluated. If it is True, it is returned, due to short circuit evaluation, hence the expected behaviour. If not, expression2 is returned. '' evaluates to False. A: Try short-circuit evaluation: >>> g = lambda x: x or '' >>> g(3) 3 >>> g(None) '' >>> # beware that ... >>> g(0) ''
Python lambda returning None instead of empty string
I have the following lambda function: f = lambda x: x == None and '' or x It should return an empty string if it receives None as the argument, or the argument if it's not None. For example: >>> f(4) 4 >>> f(None) >>> If I call f(None) instead of getting an empty string I get None. I printed the type of what the function returned and I got NoneType. I was expecting string. type('') returns string, so I'd like to know why the lambda doesn't return an empty string when I pass None as an argument. I'm fairly new to lambdas so I might have misunderstood some things about how they work.
[ "use the if else construct\nf = lambda x:'' if x is None else x\n\n", "The problem in your case that '' is considered as boolean False. bool('') == False.\nYou can use\nf =lambda x:x if x is not None else ''\n\n", "The problem is that Python treats the empty string as False. When you pass None to your function, it evaluates to:\nNone == None and '' or None\n\nwhich (effectively) becomes:\nTrue and False or None\n\nthen:\nFalse or None\n\nand finally:\nNone\n\nOne solution would be: \nlambda x: x if x is not None else ''\n\nIf you know x will be either a string or None, then you can leverage the fact that None is also a False value in Python:\nlambda x: x or ''\n\n", "Python gives and a higher precedence than or, so the parentheses fall here:\nlambda x: (x == None and '') or x\n\nWhen passed None, this becomes (True and '') or None. Python’s boolean operators work by returning one argument or another (whence this little trick), so this reduces to '' or None, and finally None.\nThis little trick stems from back before Python 2.5, which didn't have the conditional operator. The caveat, which you just ran into, is that it doesn’t behave as expected when True branch has a False value. Unless you’re concerned with Python ≤ 2.4, just use the conditional operator.\n", "It's not lambdas that are the problem here. It's the pythonic if/else expressiong you are using there.\n(condition) and (expression1) or (expression2) most of the times means the (condition) ? (expression1) : (expression2) you'd expect, except when expression1 evaluates to False.\nThis is because the whole thing is evaluated in order. If condition fails, expression1 is evaluated. If it is True, it is returned, due to short circuit evaluation, hence the expected behaviour. If not, expression2 is returned. '' evaluates to False.\n", "Try short-circuit evaluation:\n >>> g = lambda x: x or ''\n >>> g(3)\n 3\n >>> g(None)\n ''\n >>> # beware that ...\n >>> g(0)\n ''\n\n" ]
[ 27, 8, 4, 3, 2, 2 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0002572564_lambda_python.txt
Q: Using python to play two sine tones at once I'm using python to play a sine tone. The tone is based off the computer's internal time in minutes, but I'd like to simultaneously play one based off the second for a harmonized or dualing sound. This is what I have so far; can someone point me in the right direction? from struct import pack from math import sin, pi import time def au_file(name, freq, dur, vol): fout = open(name, 'wb') # header needs size, encoding=2, sampling_rate=8000, channel=1 fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1)) factor = 2 * pi * freq/8000 # write data for seg in range(8 * dur): # sine wave calculations sin_seg = sin(seg * factor) fout.write(pack('b', vol * 127 * sin_seg)) fout.close() t = time.strftime("%S", time.localtime()) ti = time.strftime("%M", time.localtime()) tis = float(t) tis = tis * 100 tim = float(ti) tim = tim * 100 if __name__ == '__main__': au_file(name='timeSound1.au', freq = tim, dur=1000, vol=1.0) import os os.startfile('timeSound1.au') A: What about the following minimal changes in your code...: from struct import pack from math import sin, pi import time def au_file(name, freq, freq1, dur, vol): fout = open(name, 'wb') # header needs size, encoding=2, sampling_rate=8000, channel=1 fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1)) factor = 2 * pi * freq/8000 factor1 = 2 * pi * freq1/8000 # write data for seg in range(8 * dur): # sine wave calculations sin_seg = sin(seg * factor) + sin(seg * factor1) fout.write(pack('b', vol * 64 * sin_seg)) fout.close() t = time.strftime("%S", time.localtime()) ti = time.strftime("%M", time.localtime()) tis = float(t) tis = tis * 100 tim = float(ti) tim = tim * 100 if __name__ == '__main__': au_file(name='timeSound2.au', freq=tim, freq1=tis, dur=1000, vol=1.0) import os os.startfile('timeSound2.au')
Using python to play two sine tones at once
I'm using python to play a sine tone. The tone is based off the computer's internal time in minutes, but I'd like to simultaneously play one based off the second for a harmonized or dualing sound. This is what I have so far; can someone point me in the right direction? from struct import pack from math import sin, pi import time def au_file(name, freq, dur, vol): fout = open(name, 'wb') # header needs size, encoding=2, sampling_rate=8000, channel=1 fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1)) factor = 2 * pi * freq/8000 # write data for seg in range(8 * dur): # sine wave calculations sin_seg = sin(seg * factor) fout.write(pack('b', vol * 127 * sin_seg)) fout.close() t = time.strftime("%S", time.localtime()) ti = time.strftime("%M", time.localtime()) tis = float(t) tis = tis * 100 tim = float(ti) tim = tim * 100 if __name__ == '__main__': au_file(name='timeSound1.au', freq = tim, dur=1000, vol=1.0) import os os.startfile('timeSound1.au')
[ "What about the following minimal changes in your code...:\nfrom struct import pack\nfrom math import sin, pi\nimport time\n\ndef au_file(name, freq, freq1, dur, vol):\n fout = open(name, 'wb')\n # header needs size, encoding=2, sampling_rate=8000, channel=1\n fout.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))\n factor = 2 * pi * freq/8000\n factor1 = 2 * pi * freq1/8000\n # write data\n for seg in range(8 * dur):\n # sine wave calculations\n sin_seg = sin(seg * factor) + sin(seg * factor1)\n fout.write(pack('b', vol * 64 * sin_seg))\n fout.close()\n\nt = time.strftime(\"%S\", time.localtime())\nti = time.strftime(\"%M\", time.localtime())\ntis = float(t)\ntis = tis * 100\ntim = float(ti)\ntim = tim * 100\n\nif __name__ == '__main__':\n au_file(name='timeSound2.au', freq=tim, freq1=tis, dur=1000, vol=1.0)\n\n import os\n os.startfile('timeSound2.au')\n\n" ]
[ 1 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0002572651_audio_python.txt
Q: Talking with a Bittorrent client listening on a port? I have one of my computers seeding a torrent file on port 45000. I am trying to write a small client in python (or perhaps perl) that helps me to determine the types of messages this client supports for which I need to perhaps do a handshake with the client. In Azureus, this is done using a call like peer.getSupportedMessages(). Is it possible to do this using some library in python or perl? An example of the returned messages would look like this: BT_KEEP_ALIVE BT_PIECE BT_REQUEST BT_UNCHOKE BT_UNINTERESTED BT_SUGGEST_PIECE BT_HAVE_ALL BT_HAVE_NONE BT_REJECT_REQUEST BT_ALLOWED_FAST BT_LT_EXT_MESSAGE BT_DHT_PORT lt_handshake ut_pex A: From what I can tell, the list of supported messages is a part of a custom handshake message supported only by Azureus (and possibly some Azureus-compliant tools) and is not part of the official BitTorrent system. However, you can probably craft a bencoded AZ handshake, send it to your seeder, decode the response, and see what the supported messages are. AZHandshake.java has the details of what the message should look like. Using the Bencode module from CPAN, you could do something like: my $handshake = bencode { identity => '', client => '', ... }; # All fields from AZHandshake.java # send handshake to seeder and get a response my $handshake_response = ... my $dictionary = bdecode $handshake_response; print join "\n", @{$dictionary->{messages}}, "\n"; Of course, the trick will be in setting up a proper handshake that will elicit a valid response from the seeder. Unfortunately, I don't know of anything that will just do it without requiring a little bit of programming work.
Talking with a Bittorrent client listening on a port?
I have one of my computers seeding a torrent file on port 45000. I am trying to write a small client in python (or perhaps perl) that helps me to determine the types of messages this client supports for which I need to perhaps do a handshake with the client. In Azureus, this is done using a call like peer.getSupportedMessages(). Is it possible to do this using some library in python or perl? An example of the returned messages would look like this: BT_KEEP_ALIVE BT_PIECE BT_REQUEST BT_UNCHOKE BT_UNINTERESTED BT_SUGGEST_PIECE BT_HAVE_ALL BT_HAVE_NONE BT_REJECT_REQUEST BT_ALLOWED_FAST BT_LT_EXT_MESSAGE BT_DHT_PORT lt_handshake ut_pex
[ "From what I can tell, the list of supported messages is a part of a custom handshake message supported only by Azureus (and possibly some Azureus-compliant tools) and is not part of the official BitTorrent system. However, you can probably craft a bencoded AZ handshake, send it to your seeder, decode the response, and see what the supported messages are.\nAZHandshake.java has the details of what the message should look like.\nUsing the Bencode module from CPAN, you could do something like:\n my $handshake = bencode { \n identity => '', client => '', ... }; # All fields from AZHandshake.java\n\n # send handshake to seeder and get a response\n my $handshake_response = ...\n\n my $dictionary = bdecode $handshake_response;\n\n print join \"\\n\", @{$dictionary->{messages}}, \"\\n\";\n\nOf course, the trick will be in setting up a proper handshake that will elicit a valid response from the seeder. Unfortunately, I don't know of anything that will just do it without requiring a little bit of programming work.\n" ]
[ 2 ]
[]
[]
[ "bittorrent", "p2p", "perl", "python" ]
stackoverflow_0002572634_bittorrent_p2p_perl_python.txt
Q: Are there Python ORMs out there that support multiple independent databases concurrently in use? I'm writing an application in Python where I wish to use sqlite as the backing store for documents edited by the app, with documents generally living in memory, but being saved to disk-based databases when the application saves. Ideally I'd like to use something like an ORM to make access to the data from my Python application code simple. Unfortunately it seems like the majority of Python ORMs, including SQLAlchemy, SQLObject, Django, and Storm, associate the database connection (or engine or whatever) with the classes representing table data, rather than instances of those classes. This restricts these ORMs to working with a single database connection across all instances. Since I'd like to support having multiple documents open simultaneously, this isn't going to work for me. Are there any ORMs out there that support this usage model in Python? Bazaar seems to support this, but it's quite out of date, and at first glance appears to have some other shortcomings. Thanks for any suggestions! A: The upcoming django 1.2 release supports this. Here's a description of it: http://djangoadvent.com/1.2/multiple-database-support/ A: SQLAlchemy does support multiple database connections per class, as in this example: http://svn.sqlalchemy.org/sqlalchemy/trunk/examples/sharding/attribute_shard.py
Are there Python ORMs out there that support multiple independent databases concurrently in use?
I'm writing an application in Python where I wish to use sqlite as the backing store for documents edited by the app, with documents generally living in memory, but being saved to disk-based databases when the application saves. Ideally I'd like to use something like an ORM to make access to the data from my Python application code simple. Unfortunately it seems like the majority of Python ORMs, including SQLAlchemy, SQLObject, Django, and Storm, associate the database connection (or engine or whatever) with the classes representing table data, rather than instances of those classes. This restricts these ORMs to working with a single database connection across all instances. Since I'd like to support having multiple documents open simultaneously, this isn't going to work for me. Are there any ORMs out there that support this usage model in Python? Bazaar seems to support this, but it's quite out of date, and at first glance appears to have some other shortcomings. Thanks for any suggestions!
[ "The upcoming django 1.2 release supports this.\nHere's a description of it:\nhttp://djangoadvent.com/1.2/multiple-database-support/\n", "SQLAlchemy does support multiple database connections per class, as in this example: http://svn.sqlalchemy.org/sqlalchemy/trunk/examples/sharding/attribute_shard.py\n" ]
[ 3, 3 ]
[]
[]
[ "orm", "python" ]
stackoverflow_0002572686_orm_python.txt
Q: Is frozenset adequate for caching of symmetric input data in a python dict? The title more or less says it all: I have a function which takes symmetric input in two arguments, e.g. something like def f(a1, a2): return heavy_stuff(abs(a1 - a2)) Now, I want to introduce some caching method. Would it be correct / pythonic / reasonably efficient to do something like this: cache = {} def g(a1, a2): fs =frozenset((tuple(a1), tuple(a2))) if fs not in cache: cache[fs] = f(a1, a2) return cache[fs] Or would there be some better way? Edit: a1 and a2 might be the rows of a numpy array; that’s why I wrap them in a tuple each. A: Python always computes all arguments you're passing to a function, and only then does it call the function. In other words, like most other languages, Python is "eager" in its evaluation (the major exception today is probably Haskell, but that doesn't help you;-). So setdefault is a very unsuitable approach for caching! Whenever you do cache.setdefault(akey, f(x, y)) you're first calling f(x, y), with all its computational cost, then maybe dropping the results of that computation on the floor; this makes the caching totally ineffective. Rather, always do it as follows: akey = whatever(x, y) if akey not in cache: cache[akey] = f(x, y) return cache[akey] or the like -- there are a few other possible idioms, especially if e.g. you know that f will never return None: result = cache.get(akey) if result is None: result = cache[akey] = f(x, y) return result As for the secondary issue of what's an appropriate whatever for the key computation, given that you know that f is symmetrical, I think frozenset is probably OK; although (if the components of x and y are comparable, as well as hashable -- i.e. it wouldn't work with complex numbers) you might want to consider ta1 = tuple(a1) ta2 = tuple(a2) if ta1 > ta2: key = ta1, ta2 else: key = ta2, ta1 the relative performance depends on the cost of comparing, vs that of hashing, the items in a1 and a2. Differences are likely to be minor, anyway.
Is frozenset adequate for caching of symmetric input data in a python dict?
The title more or less says it all: I have a function which takes symmetric input in two arguments, e.g. something like def f(a1, a2): return heavy_stuff(abs(a1 - a2)) Now, I want to introduce some caching method. Would it be correct / pythonic / reasonably efficient to do something like this: cache = {} def g(a1, a2): fs =frozenset((tuple(a1), tuple(a2))) if fs not in cache: cache[fs] = f(a1, a2) return cache[fs] Or would there be some better way? Edit: a1 and a2 might be the rows of a numpy array; that’s why I wrap them in a tuple each.
[ "Python always computes all arguments you're passing to a function, and only then does it call the function. In other words, like most other languages, Python is \"eager\" in its evaluation (the major exception today is probably Haskell, but that doesn't help you;-).\nSo setdefault is a very unsuitable approach for caching! Whenever you do\ncache.setdefault(akey, f(x, y))\n\nyou're first calling f(x, y), with all its computational cost, then maybe dropping the results of that computation on the floor; this makes the caching totally ineffective.\nRather, always do it as follows:\nakey = whatever(x, y)\nif akey not in cache:\n cache[akey] = f(x, y)\nreturn cache[akey]\n\nor the like -- there are a few other possible idioms, especially if e.g. you know that f will never return None:\nresult = cache.get(akey)\nif result is None:\n result = cache[akey] = f(x, y)\nreturn result\n\nAs for the secondary issue of what's an appropriate whatever for the key computation, given that you know that f is symmetrical, I think frozenset is probably OK; although (if the components of x and y are comparable, as well as hashable -- i.e. it wouldn't work with complex numbers) you might want to consider\nta1 = tuple(a1)\nta2 = tuple(a2)\nif ta1 > ta2: key = ta1, ta2\nelse: key = ta2, ta1\n\nthe relative performance depends on the cost of comparing, vs that of hashing, the items in a1 and a2. Differences are likely to be minor, anyway.\n" ]
[ 2 ]
[]
[]
[ "caching", "python", "set", "symmetric" ]
stackoverflow_0002572899_caching_python_set_symmetric.txt
Q: What is float('123.987') in Python? It's 123.98699999999999 ! Why is that? A: See Why can't decimal numbers be represented exactly in binary A: The Python FAQ and tutorial address this issue pretty well, I think. More generally, both are excellent resources, well worth your time to browse if you have any interest in Python!-) A: This has changed in/since Python 3.1. See also: issue 1580 To your (already deleted) addition: Use the decimal package.
What is float('123.987') in Python?
It's 123.98699999999999 ! Why is that?
[ "See Why can't decimal numbers be represented exactly in binary\n", "The Python FAQ and tutorial address this issue pretty well, I think. More generally, both are excellent resources, well worth your time to browse if you have any interest in Python!-)\n", "This has changed in/since Python 3.1.\nSee also: issue 1580\n\nTo your (already deleted) addition: Use the decimal package.\n" ]
[ 14, 5, 3 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0002572936_floating_point_python.txt
Q: Creating Instance of Python Extension Type in C I am writing a simple Vector implementation as a Python extension module in C that looks mostly like this: typedef struct { PyObject_HEAD double x; double y; } Vector; static PyTypeObject Vector_Type = { ... }; It is very simple to create instances of Vector while calling from Python, but I need to create a Vector instance in the same extension module. I looked in the documentation but I couldn't find a clear answer. What's the best way to do this? A: Simplest is to call the type object you've created, e.g. with PyObject_CallFunction -- don't let the name fool you, it lets you call any callable, not just a function. If you don't have a reference to your type object conveniently available as a static global to your C module, you can retrieve it in various ways, of course (e.g., from your module object with a PyObject_GetAttrString). But sticking that PyObject* into a static module-level C variable is probably simplest and most convenient.
Creating Instance of Python Extension Type in C
I am writing a simple Vector implementation as a Python extension module in C that looks mostly like this: typedef struct { PyObject_HEAD double x; double y; } Vector; static PyTypeObject Vector_Type = { ... }; It is very simple to create instances of Vector while calling from Python, but I need to create a Vector instance in the same extension module. I looked in the documentation but I couldn't find a clear answer. What's the best way to do this?
[ "Simplest is to call the type object you've created, e.g. with PyObject_CallFunction -- don't let the name fool you, it lets you call any callable, not just a function.\nIf you don't have a reference to your type object conveniently available as a static global to your C module, you can retrieve it in various ways, of course (e.g., from your module object with a PyObject_GetAttrString). But sticking that PyObject* into a static module-level C variable is probably simplest and most convenient.\n" ]
[ 3 ]
[]
[]
[ "extension_modules", "python" ]
stackoverflow_0002573060_extension_modules_python.txt
Q: Changing models in django results in broken database? I have added and removed fields in my models.py file and then run manage.py syncdb. Usually I have to quit out of the shell and restart it before syncdb does anything. And then even after that, I am getting errors when trying to access the admin pages, it seems that certain new fields that I've added still don't show up in the model: Caught an exception while rendering: no such column: mySite_book.Title A: Django does not perform database migration for you, i.e., if you add new fields, Django won't modify your database schema. You can either: Drop the tables that changed and perform syncdb again. This is reasonnable when you are developing your application and you don't have any real data in your database. Use a migration tool like South that performs database migration (like hibernate update script). Edit the database by hand and add/delete the appropriate fields for the previously existing tables. A: For me, (so long as you're doing this with test data, and not doing this in a production environ) it's alot easier to just blow away the test.db and do a new ./manage.py syncdb. Just food for thought... A: Just to expand on @Barthelemy's answer, there are several Django migration tools: South Deseb django-evolution dmigrations (MySQL only) nashvegas yadsel
Changing models in django results in broken database?
I have added and removed fields in my models.py file and then run manage.py syncdb. Usually I have to quit out of the shell and restart it before syncdb does anything. And then even after that, I am getting errors when trying to access the admin pages, it seems that certain new fields that I've added still don't show up in the model: Caught an exception while rendering: no such column: mySite_book.Title
[ "Django does not perform database migration for you, i.e., if you add new fields, Django won't modify your database schema.\nYou can either:\n\nDrop the tables that changed and perform syncdb again. This is reasonnable when you are developing your application and you don't have any real data in your database.\nUse a migration tool like South that performs database migration (like hibernate update script).\nEdit the database by hand and add/delete the appropriate fields for the previously existing tables.\n\n", "For me, (so long as you're doing this with test data, and not doing this in a production environ) it's alot easier to just blow away the test.db and do a new ./manage.py syncdb. Just food for thought...\n", "Just to expand on @Barthelemy's answer, there are several Django migration tools:\n\nSouth\nDeseb\ndjango-evolution\ndmigrations (MySQL only)\nnashvegas\nyadsel\n\n" ]
[ 9, 4, 2 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0002571337_django_django_admin_django_models_python.txt