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: How to get the contents of a field instead of `<bound method...` in a CSV output with Python (pytwist) The snippet below is generating "weird" output: for s in servers: vo = ss.getServerVO(s) values = [] for f in voFields: attribValue = getattr(vo, f) values.append(attribValue) cust...
How to get the contents of a field instead of `<bound method...` in a CSV output with Python (pytwist)
The snippet below is generating "weird" output: for s in servers: vo = ss.getServerVO(s) values = [] for f in voFields: attribValue = getattr(vo, f) values.append(attribValue) customValues = ss.getCustomFields(s) for f in customFields: values.append(customValues[f]) # Con...
[ "You could try calling the bound method if it is one:\nfor f, v in customFields.iteritems():\n try:\n v = v()\n except TypeError:\n pass\n values.append(v)\n\nThe problem, of course, is with the design choice (by HP or whoever) to mix \"accessors\" with other kinds of values -- accessors are not a good Pyt...
[ 1 ]
[]
[]
[ "csv", "hpsa", "python" ]
stackoverflow_0002389025_csv_hpsa_python.txt
Q: Declare which signals are subscribed to on DBus? Is there a way to declare which signals are subscribed by a Python application over DBus? In other words, is there a way to advertise through the "Introspectable" interface which signals are subscribed to. I use "D-Feet D-Bus debugger". E.g. Application subscribes ...
Declare which signals are subscribed to on DBus?
Is there a way to declare which signals are subscribed by a Python application over DBus? In other words, is there a way to advertise through the "Introspectable" interface which signals are subscribed to. I use "D-Feet D-Bus debugger". E.g. Application subscribes to signal X (using the add_signal_receiver method on a...
[ "D-Bus clients call AddMatch on the bus daemon to register their interest in messages matching a particular pattern; most bindings add a match rule either for all signals on a particular service and object path, or for signals on a particular interface on that service and object path, when you create a proxy object...
[ 4, 1 ]
[]
[]
[ "dbus", "python" ]
stackoverflow_0002240562_dbus_python.txt
Q: Python string decoding issue I am trying to parse a CSV file containing some data, mostly numeral but with some strings - which I do not know their encoding, but I do know they are in Hebrew. Eventually I need to know the encoding so I can unicode the strings, print them, and perhaps throw them into a database lat...
Python string decoding issue
I am trying to parse a CSV file containing some data, mostly numeral but with some strings - which I do not know their encoding, but I do know they are in Hebrew. Eventually I need to know the encoding so I can unicode the strings, print them, and perhaps throw them into a database later on. I tried using Chardet, whic...
[ "This is what's happening:\n\nsampleString is a byte string (cp1255 encoded)\nsampleString.decode(\"cp1255\") decodes (decode==bytes -> unicode string) the byte string to a unicode string\nprint sampleString.decode(\"cp1255\") attempts to print the unicode string to stdout. Print has to encode the unicode string to...
[ 13, 3, 0, 0 ]
[]
[]
[ "character_encoding", "python", "string", "unicode" ]
stackoverflow_0002389410_character_encoding_python_string_unicode.txt
Q: Python list entries are overridden by last appended entry I've got this code: def __parse(self): for line in self.lines: r = Record(line) self.records[len(self.records):] = [r] print self.records[len(self.records)-1].getValue() # Works fine! print self.record[0].getValue() #...
Python list entries are overridden by last appended entry
I've got this code: def __parse(self): for line in self.lines: r = Record(line) self.records[len(self.records):] = [r] print self.records[len(self.records)-1].getValue() # Works fine! print self.record[0].getValue() # Gives the same as print self.record[1].getValue() # as ...
[ "You aren't appending to self.records; you are always overwriting it.\nUse:\nself.records.append(r) \ninstead.\nEdit: Never mind. See Ignacio Vasquez-Abrams's comment. I would delete this answer if not for that.\n", "Does it still happen if you replace it with the following:\nself.record = [Record(l) for l in s...
[ 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0002389094_append_list_python.txt
Q: python: inheriting or composition Let's say that I have class, that uses some functionality of dict. I used to composite a dict object inside and provide some access from the outside, but recently thought about simply inheriting dict and adding some attributes and methods that I might require. Is it a good way to ...
python: inheriting or composition
Let's say that I have class, that uses some functionality of dict. I used to composite a dict object inside and provide some access from the outside, but recently thought about simply inheriting dict and adding some attributes and methods that I might require. Is it a good way to go, or should I stick to composition?
[ "Inheritance is very often abused. Unless your class is meant to be used as a generic dictionary with extra functionality, I would say composition is the way to go.\nSaving forwarding calls is usually not a good enough reason for choosing inheritance.\nFrom the Design Pattern book:\n\nFavor object composition over ...
[ 14, 3, 3, 3 ]
[]
[]
[ "composition", "dictionary", "inheritance", "python" ]
stackoverflow_0002389816_composition_dictionary_inheritance_python.txt
Q: Logging in worker threads spawned from a pylons application does not seem to work I have a pylons application where, under certain cirumstances I want to spawn multiple worker threads to process items in a queue. Right now we aren't making use of a ThreadPool (would be ideal, but we'll add that in later). The main...
Logging in worker threads spawned from a pylons application does not seem to work
I have a pylons application where, under certain cirumstances I want to spawn multiple worker threads to process items in a queue. Right now we aren't making use of a ThreadPool (would be ideal, but we'll add that in later). The main problem is that the worker threads logging does not get written to the log files. When...
[ "One thing to note about logging is that if an exception occurs while emitting a log event (for whatever reason) the exception is typically swallowed, and not allowed to potentially bring down an application just because of a logging error. (It depends on the handlers used and the value of logging.raiseExceptions)....
[ 1, 0 ]
[]
[]
[ "logging", "multithreading", "pylons", "python" ]
stackoverflow_0002389106_logging_multithreading_pylons_python.txt
Q: PSP class import + MySQL connect Ok so im trying to import a class i made which connects to a MySQL database the class code is shown below: class connection def__init__( self ): self.cnx = MySQLdb.connect(user='xxx',host='xxx',passwd='xxx',db='xxx') All of the parameters for the mysql connection are c...
PSP class import + MySQL connect
Ok so im trying to import a class i made which connects to a MySQL database the class code is shown below: class connection def__init__( self ): self.cnx = MySQLdb.connect(user='xxx',host='xxx',passwd='xxx',db='xxx') All of the parameters for the mysql connection are correct and file containg the class is ...
[ "You are horribly, horribly confused as to how modules and classes work. Please read and work through at least the modules section and the classes section of the Python tutorial.\n", "Try replacing\ncur = cnx.cursor()\n\nwith\ncon=cnx_class.connection()\ncur=con.cnx.cursor()\n\nYou can also replace\nrows = cur.fe...
[ 0, 0 ]
[]
[]
[ "class", "mysql", "python", "python_server_pages" ]
stackoverflow_0002390158_class_mysql_python_python_server_pages.txt
Q: only parse a specific subtree of an XML file I have a massive XML file. However, I'm only interested in a single small subtree of this massive tree. I want to parse this subtree, but I don't want to waste time parsing the entire massive tree when I'm going to only be using a small part of it. Ideally, I'd want to...
only parse a specific subtree of an XML file
I have a massive XML file. However, I'm only interested in a single small subtree of this massive tree. I want to parse this subtree, but I don't want to waste time parsing the entire massive tree when I'm going to only be using a small part of it. Ideally, I'd want to scan through the file until I find the start of t...
[ "I get the impression that iterparse is what you want. Looking at the section \"Selective tag events\" at http://lxml.de/parsing.html it seems like that gives you what you desire:\ncontext = etree.iterparse(xmlfile, tag=\"yourSubTree\")\naction, elem = context.next()\netree.iterwalk(elem, ...)...\n\nSeems like XPat...
[ 1, 0 ]
[]
[]
[ "parsing", "python", "subtree", "xml" ]
stackoverflow_0002390611_parsing_python_subtree_xml.txt
Q: Regex + Python to remove specific trailing and ending characters from value in tab delimited file It's been years (and years) since I've done any regex, so turning to experts on here since it's likely a trivial exercise :) I have a tab delimited file and on each line I have a certain fields that have values such a...
Regex + Python to remove specific trailing and ending characters from value in tab delimited file
It's been years (and years) since I've done any regex, so turning to experts on here since it's likely a trivial exercise :) I have a tab delimited file and on each line I have a certain fields that have values such as: foo bar b"foo's bar" b'bar foo' b'carbar' (A complete line in the file might be something like: 1...
[ "(^|\\t)b[\\\"']\nshould match the leadings, and for the trailing:\n\\\"'\nshould do it\nIn Python, you do:\nimport re\nr1 = re.compile(\"(^|\\t)b[\\\"']\")\nr2 = re.compile(\"[\\\"'](\\t|$)\")\n\nthen just use\nr1.sub(\"\\\\1\", yourString)\nr2.sub(\"\\\\1\", yourString)\n\n", "for each line you can use\nre.sub(...
[ 1, 1, 0 ]
[]
[]
[ "python", "python_3.x", "regex" ]
stackoverflow_0002390501_python_python_3.x_regex.txt
Q: ZODB In Real Life Writing an app in Python, and been playing with various ORM setups and straight SQL. All of which are ugly as sin. I have been looking at ZODB as an object store, and it looks a promising alternative... would you recommend it? What are your experiences, problems, and criticism, particularly regar...
ZODB In Real Life
Writing an app in Python, and been playing with various ORM setups and straight SQL. All of which are ugly as sin. I have been looking at ZODB as an object store, and it looks a promising alternative... would you recommend it? What are your experiences, problems, and criticism, particularly regarding developer's perspe...
[ "I've used ZODB for more than ten years now, in Zope and outside. It's great if your data is hierarchical. The largest data store a customer operates has maybe. I don't know, 100GB in it? Something on that order of magnitude anyway.\nHere is a performance comparison against Postgres.\nIf you're writing a WSGI web ...
[ 27, 15, 5, 2, 0 ]
[]
[]
[ "python", "zodb" ]
stackoverflow_0002388870_python_zodb.txt
Q: Python XML need help with programming error I am having the below code. import xml.dom.minidom def get_a_document(name): return xml.dom.minidom.parse(name) doc = get_a_document("sources.xml") sources = doc.childNodes[1] for e in sources.childNodes: if e.nodeType == e.ELEMENT_NODE and e.localName == "so...
Python XML need help with programming error
I am having the below code. import xml.dom.minidom def get_a_document(name): return xml.dom.minidom.parse(name) doc = get_a_document("sources.xml") sources = doc.childNodes[1] for e in sources.childNodes: if e.nodeType == e.ELEMENT_NODE and e.localName == "source": for source in e.childNodes: ...
[ "What's probably happening is you're running into the nodes containing the whitespace between your tags. It's not clear what you're trying to do, but it might work if you just remove the source.nodeType == source.ELEMENT_NAME part.\n", "[DOM Text node \"u'\\n '\", DOM Element: source at 0x709f80, DOM Text node...
[ 1, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002391037_python_xml.txt
Q: How to identify what function call raise an exception in Python? i need to identify who raise an exception to handle better str error, is there a way ? look at my example: try: os.mkdir('/valid_created_dir') os.listdir('/invalid_path') except OSError, msg: # here i want i way to identify who raise the ex...
How to identify what function call raise an exception in Python?
i need to identify who raise an exception to handle better str error, is there a way ? look at my example: try: os.mkdir('/valid_created_dir') os.listdir('/invalid_path') except OSError, msg: # here i want i way to identify who raise the exception if is_mkdir_who_raise_an_exception: do some things ...
[ "If you have completely separate tasks to execute depending on which function failed, as your code seems to show, then separate try/exec blocks, as the existing answers suggest, may be better (though you may probably need to skip the second part if the first one has failed).\nIf you have many things that you need t...
[ 21, 8, 1, 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0002380073_exception_python.txt
Q: How to perform a signed PUT request with OAuth in Python How is this meant to work? Where are all the oauth_* values meant to go if not in an encoded body like a POST request? In what form do you sign it? All the Python OAuth libraries I can find only support GET and POST. Does anyone know any that support all met...
How to perform a signed PUT request with OAuth in Python
How is this meant to work? Where are all the oauth_* values meant to go if not in an encoded body like a POST request? In what form do you sign it? All the Python OAuth libraries I can find only support GET and POST. Does anyone know any that support all methods?
[ "python-oauth2 supports all HTTP verbs -- as the comment I've linked to says, and I quote,\n\nWe use PUT extensively at SimpleGeo\n (our python-simplegeo package uses\n python-oauth2 and PUT requests).\nThe python-oauth2 package's client\n (oauth2.Client) simply wraps httplib2,\n which supports all of the verbs...
[ 0 ]
[]
[]
[ "oauth", "python" ]
stackoverflow_0002391018_oauth_python.txt
Q: web2py - my application doesn' login i have a web2py application and am using default/user/login to login to my application but sometimes when i login the application redirect to the login page agin and sometimes the system logged fine and there is no problem i dont know why ? so please can anyone tell me ? Thank...
web2py - my application doesn' login
i have a web2py application and am using default/user/login to login to my application but sometimes when i login the application redirect to the login page agin and sometimes the system logged fine and there is no problem i dont know why ? so please can anyone tell me ? Thanks in advance
[ "I have seen something like this happen with cookie based load balancing. The cookie was being set too late, so the user would switch frontends sometimes when they logged it.\nIf you have a load balancer over 2 frontends, you might see this happen 50% of the time.\nCheck the logs and make sure the hits are all goin...
[ 1 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0002126824_python_web2py.txt
Q: telnetlib TypeError I am modifying a python script to make changes en masse to a hand full of switches via telnet: import getpass import sys import telnetlib HOST = "192.168.1.1" user = input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("User Name: ") tn....
telnetlib TypeError
I am modifying a python script to make changes en masse to a hand full of switches via telnet: import getpass import sys import telnetlib HOST = "192.168.1.1" user = input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("User Name: ") tn.write(user + "\n") if pas...
[ "Per the docs, read_until's specs are (quoting, my emphasis):\n\nRead until a given byte string,\n expected, is encountered\n\nYou're not passing a byte string, in Python 3, with e.g.:\ntn.read_until(\"User Name: \")\n\nInstead, you're passing a text string, which in Python 3 means a Unicode string.\nSo, change th...
[ 2 ]
[]
[]
[ "python", "python_3.x", "telnet" ]
stackoverflow_0002388414_python_python_3.x_telnet.txt
Q: Compressed xml on soappy I'm developing an application that uses webservices in python, both sides (server and client) are developed in Python and uses SOAPpy for the webservices, but, you know, the xml is too verbose, I want to compress it, but as far as I have searched in google I can't find something helpful. ...
Compressed xml on soappy
I'm developing an application that uses webservices in python, both sides (server and client) are developed in Python and uses SOAPpy for the webservices, but, you know, the xml is too verbose, I want to compress it, but as far as I have searched in google I can't find something helpful.
[ "You can add HTTP headers to SOAPpy call as shown here (this example sends cookies, but you can generalize it to add different headers) -- to request compression, add header Accept-Encoding: gzip. The web server (not the application server, like your \"SOAPpy server\" in Python, but the actual HTTP server it runs ...
[ 2 ]
[]
[]
[ "compression", "python", "soappy", "web_services" ]
stackoverflow_0002390184_compression_python_soappy_web_services.txt
Q: Models in database speed vs static dictionaries speed I have a need for some kind of information that is in essence static. There is not much of this information, but alot of objects will use that information. Since there is not a lot of that information (few dictionaries and some lists), I thought that I have 2 o...
Models in database speed vs static dictionaries speed
I have a need for some kind of information that is in essence static. There is not much of this information, but alot of objects will use that information. Since there is not a lot of that information (few dictionaries and some lists), I thought that I have 2 options - create models for holding that information in the ...
[ "If they're truly never, ever going to change, then feel free to put them in your settings.py file as you would declare a normal Python dictionary.\nHowever, if you want your information to be modifiable through the normal Django methods, then use the database for persistent storage, and then make the most of Djang...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "django", "python" ]
stackoverflow_0002391788_dictionary_django_python.txt
Q: SQLite or flat text file? I process a lot of text/data that I exchange between Python, R, and sometimes Matlab. My go-to is the flat text file, but also use SQLite occasionally to store the data and access from each program (not Matlab yet though). I don't use GROUPBY, AVG, etc. in SQL as much as I do these operat...
SQLite or flat text file?
I process a lot of text/data that I exchange between Python, R, and sometimes Matlab. My go-to is the flat text file, but also use SQLite occasionally to store the data and access from each program (not Matlab yet though). I don't use GROUPBY, AVG, etc. in SQL as much as I do these operations in R, so I don't necessari...
[ "If all the languages support SQLite - use it. The power of SQL might not be useful to you right now, but it probably will be at some point, and it saves you having to rewrite things later when you decide you want to be able to query your data in more complicated ways.\nSQLite will also probably be substantially fa...
[ 15, 5 ]
[]
[]
[ "database", "file_format", "python", "r", "sql" ]
stackoverflow_0002392017_database_file_format_python_r_sql.txt
Q: Calculating very large exponents in python Currently i am simulating my cryptographic scheme to test it. I have developed the code but i am stuck at one point. I am trying to take: g**x where g = 256 bit number x = 256 bit number Python hangs at this point, i have read alot of forums, threads etcc but only com...
Calculating very large exponents in python
Currently i am simulating my cryptographic scheme to test it. I have developed the code but i am stuck at one point. I am trying to take: g**x where g = 256 bit number x = 256 bit number Python hangs at this point, i have read alot of forums, threads etcc but only come to the conclusion that python hangs, as its ha...
[ "It's not hanging, it's just processing. It will eventually give you the answer, provided it doesn't run out of memory first.\nI haven't heard of the result of such a process being used in cryptography though; usually it's the modulus of said power that matters. If it's the same in your case then you can just use t...
[ 15, 12, 9 ]
[]
[]
[ "python" ]
stackoverflow_0002392235_python.txt
Q: python json loads and unicode I have the following case where I get the result of UTF-8 encoded HTTP response. I want to load the response content(JSON). However I don't know why I have to do 2 json.loads so that I get the final list: result = urllib2.urlopen(req).read() print result, type(result) #=> "[{\"pk\": 6...
python json loads and unicode
I have the following case where I get the result of UTF-8 encoded HTTP response. I want to load the response content(JSON). However I don't know why I have to do 2 json.loads so that I get the final list: result = urllib2.urlopen(req).read() print result, type(result) #=> "[{\"pk\": 66, \"model\": \"core.job\", \"field...
[ "It looks like the repr() of the JSON string is what's being returned instead of the JSON string itself. So, something is broken on the server.\n" ]
[ 3 ]
[]
[]
[ "json", "python", "simplejson", "unicode", "utf_8" ]
stackoverflow_0002392501_json_python_simplejson_unicode_utf_8.txt
Q: Figuring out duration of an event in Python This is a very noobish question, so I apologize in advance! I have two time stamps for start and end of the event. They are stored in as datetime.datetime in UTC. What I need to do is figure out the duration of the event. I tried subtracting one from the other, but recei...
Figuring out duration of an event in Python
This is a very noobish question, so I apologize in advance! I have two time stamps for start and end of the event. They are stored in as datetime.datetime in UTC. What I need to do is figure out the duration of the event. I tried subtracting one from the other, but receive error: Traceback (most recent call last): 02....
[ "Subtracting one datetime from another will give you a timedelta. You can use that to create another datetime if you need to by adding it to or subtracting it from another datetime object.\nHow can you represent a duration with a single datetime object, though?\n", "The difference of two datetime.datetime object...
[ 5, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002388486_google_app_engine_python.txt
Q: Suppose I have this loop in Django...how do I display this? {% for p in profiles %} <div class="result"> {{ p.first_name }} </div> {% endfor %} Suppose I have 1000 of these, in a huge list. How would I make this code appear every 15 times? <div class="menu">abc</div> A: Use the forloop.counter variable wit...
Suppose I have this loop in Django...how do I display this?
{% for p in profiles %} <div class="result"> {{ p.first_name }} </div> {% endfor %} Suppose I have 1000 of these, in a huge list. How would I make this code appear every 15 times? <div class="menu">abc</div>
[ "Use the forloop.counter variable with divisbleby filter.\n{% if forloop.counter|divisbleby:\"15\" %}\n <div class=\"menu\">abc</div>\n{% endif %}\n\n", "You can use the forloop.counter value with a divisibleby filter in an if condition. See the documentation here\n" ]
[ 2, 1 ]
[]
[]
[ "css", "django", "javascript", "python", "templates" ]
stackoverflow_0002392556_css_django_javascript_python_templates.txt
Q: How to detect mouse and keyboard inactivity in linux I am developing an app on python which will check for user inactivity. Is there a way to check for key press and mouse move events in linux? A: You could monitor the /dev/input/* files, when a key is pressed/the mouse is moved it is written to one of those fil...
How to detect mouse and keyboard inactivity in linux
I am developing an app on python which will check for user inactivity. Is there a way to check for key press and mouse move events in linux?
[ "You could monitor the /dev/input/* files, when a key is pressed/the mouse is moved it is written to one of those files.\nTry this for example:\nfh = file('/dev/input/mice')\nwhile True: \n fh.read(3)\n print 'Mouse moved!'\n\nNow that I think of it, it might be better to use something like xi...
[ 8 ]
[]
[]
[ "input", "keyboard", "linux", "mouse", "python" ]
stackoverflow_0002392076_input_keyboard_linux_mouse_python.txt
Q: Python, dynamically invoke script I want to run a python script from within another. By within I mean any state changes from the child script effect the parent's state. So if a variable is set in the child, it gets changed in the parent. Normally you could do something like import module But the issue is here th...
Python, dynamically invoke script
I want to run a python script from within another. By within I mean any state changes from the child script effect the parent's state. So if a variable is set in the child, it gets changed in the parent. Normally you could do something like import module But the issue is here the child script being run is an argument...
[ "You can use the __import__ function which allows you to import a module dynamically:\nmodule = __import__(sys.argv[1])\n\n(You may need to remove the trailing .py or not specify it on the command line.)\nFrom the Python documentation:\n\nDirect use of __import__() is rare, except in cases where you want to import ...
[ 9, 2 ]
[]
[]
[ "command", "python" ]
stackoverflow_0002391099_command_python.txt
Q: Python: Simple Dictionary referencing Problem I have a simple problem that i cannot solve. I have a dictionary: aa = {'ALA':'A'} test = 'ALA' I'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed. I'm assuming i would have to use a for loop? somet...
Python: Simple Dictionary referencing Problem
I have a simple problem that i cannot solve. I have a dictionary: aa = {'ALA':'A'} test = 'ALA' I'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed. I'm assuming i would have to use a for loop? something like... for i in test: if i in aa: ...
[ "\nI'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed.\n\nDo you mean this?\nprint aa[test]\n\n\nIts taking the value from i and using it to reference aa i am having trouble with.\n\nI don’t exactly understand why you’re iterating over the charac...
[ 2, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002392920_dictionary_python.txt
Q: Vim: sort classes in a python source file I have a .py file with lots of classes: class First(Second): #code class Third(Fourth): #code Is it possible to sort the definitions by class name in vim? A: Suggestion for manual sorting. With a reasonable amount of classes, manual sorting is not so tedious. I...
Vim: sort classes in a python source file
I have a .py file with lots of classes: class First(Second): #code class Third(Fourth): #code Is it possible to sort the definitions by class name in vim?
[ "Suggestion for manual sorting.\nWith a reasonable amount of classes, manual sorting is not so tedious. I also propose it since I think it makes much more sense to group superclasses together and make sure superclasses are defined before subclasses -- otherwise your module won't even be importable.\nEnable folding ...
[ 5 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0002393074_python_vim.txt
Q: How do you randomly generate x amount of values and store them? I found a suggestion on a Stack Overflow topic about problems beginners should do to learn a new language. A user posted a very nice list of problems from Beginner to advanced that should help you get to know a language. One of the problems is to crea...
How do you randomly generate x amount of values and store them?
I found a suggestion on a Stack Overflow topic about problems beginners should do to learn a new language. A user posted a very nice list of problems from Beginner to advanced that should help you get to know a language. One of the problems is to create a phone book, with random phone numbers and random people on the p...
[ "You need to define some more parameters before you can tackle this problem.\n\nAre phone numbers unique to each person?\nHow will you store names? First name and last name in different strings? All in one string?\nDo you want to support fuzzy matching?\ndo you want to offer reverse lookup functionality? (I.E. lo...
[ 1, 0 ]
[]
[]
[ "python", "random", "ruby" ]
stackoverflow_0002393238_python_random_ruby.txt
Q: Replace multiple regex string matches in a file I am trying to replace multiple strings in a file. But in the following code, only my last key value gets replaced. How can I replace all the key,value in the file? fp1 = open(final,"w") data = open(initial).read() for key, value in mydict.items(): fp1.write(re.s...
Replace multiple regex string matches in a file
I am trying to replace multiple strings in a file. But in the following code, only my last key value gets replaced. How can I replace all the key,value in the file? fp1 = open(final,"w") data = open(initial).read() for key, value in mydict.items(): fp1.write(re.sub(key,value, data) fp1.close()
[ "This is one task for which regular expressions can really help:\nimport re\n\ndef replacemany(adict, astring):\n pat = '|'.join(re.escape(s) for s in adict)\n there = re.compile(pat)\n def onerepl(mo): return adict[mo.group()]\n return there.sub(onerepl, astring)\n\nif __name__ == '__main__':\n d = {'k1': 'za...
[ 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002392623_python.txt
Q: How do I disable history in python mechanize module? I have a web scraping script that gets new data once every minute, but over the course of a couple of days, the script ends up using 200mb or more of memory, and I found out it's because mechanize is keeping an infinite browser history for the .back() function t...
How do I disable history in python mechanize module?
I have a web scraping script that gets new data once every minute, but over the course of a couple of days, the script ends up using 200mb or more of memory, and I found out it's because mechanize is keeping an infinite browser history for the .back() function to use. I have looked in the docstrings, and I found the cl...
[ "You can pass an argument history=whatever when you instantiate the Browser; the default value is None which means the browser actually instantiates the History class (to allow back and reload). The simplest approach (will give an attribute error exception if you ever do call back or reload):\nclass NoHistory(obje...
[ 19 ]
[]
[]
[ "mechanize", "memory", "python" ]
stackoverflow_0002393299_mechanize_memory_python.txt
Q: Python double iteration What is the pythonic way of iterating simultaneously over two lists? Suppose I want to compare two files line by line (compare each ith line in one file with the ith line of the other file), I would want to do something like this: file1 = csv.reader(open(filename1),...) file2 = csv.reader(o...
Python double iteration
What is the pythonic way of iterating simultaneously over two lists? Suppose I want to compare two files line by line (compare each ith line in one file with the ith line of the other file), I would want to do something like this: file1 = csv.reader(open(filename1),...) file2 = csv.reader(open(filename2),...) for line...
[ "In Python 2, you should import itertools and use its izip:\nwith open(file1) as f1:\n with open(file2) as f2:\n for line1, line2 in itertools.izip(f1, f2):\n if line1 != line2:\n print 'files are different'\n break\n\nwith the built-in zip, both files will be entirely read into memory at onc...
[ 16, 10, 4 ]
[]
[]
[ "python" ]
stackoverflow_0002393444_python.txt
Q: Sending MESSAGE to a person on facebook using python I want to make a script that can be used to send messages to our friends on facebook. How do I proceed? Which is the best module to use? A: You may indeed want pyfacebook as another answer suggested, though the URL I'm giving (on github.com) is where the proj...
Sending MESSAGE to a person on facebook using python
I want to make a script that can be used to send messages to our friends on facebook. How do I proceed? Which is the best module to use?
[ "You may indeed want pyfacebook as another answer suggested, though the URL I'm giving (on github.com) is where the project (esp. its source;-) actually lives.\nA simple survey of Python APIs for facebook is here, and it also points to a possibly-simpler but less complete API, if you want to run in Google App Engin...
[ 7, 0 ]
[]
[]
[ "api", "facebook", "python", "scripting" ]
stackoverflow_0002392111_api_facebook_python_scripting.txt
Q: Python GUI framework for Mac OS X I'm trying to find a good "python GUI framework" for Mac OS X, but I haven't found anything good until now, only wxWidgets which I don't like and it's also unstable. Any suggestions? A: I use pyqt (pyside should be equivalent but with more relaxed license terms) and I find it pl...
Python GUI framework for Mac OS X
I'm trying to find a good "python GUI framework" for Mac OS X, but I haven't found anything good until now, only wxWidgets which I don't like and it's also unstable. Any suggestions?
[ "I use pyqt (pyside should be equivalent but with more relaxed license terms) and I find it pleasing and useful -- I also like the fact that (with no extra effort on my part) it gives me cross-platform apps!-)\npyobjc (comes w/your Mac, works w/Xcode, etc) may be preferable for apps you never want to be cross-platf...
[ 7, 3 ]
[]
[]
[ "macos", "python", "user_interface" ]
stackoverflow_0002393514_macos_python_user_interface.txt
Q: Classname same as file/module name leads to inheritance issue My code worked fine when it was all in one file. Now, I'm splitting up classes into different modules. The modules have been given the same name as the classes. Perhaps this is a problem, because MainPage is failing when it is loaded. Does it think that...
Classname same as file/module name leads to inheritance issue
My code worked fine when it was all in one file. Now, I'm splitting up classes into different modules. The modules have been given the same name as the classes. Perhaps this is a problem, because MainPage is failing when it is loaded. Does it think that I'm trying to inherit from a module? Can module/class namespace co...
[ "Yes, module names share the same namespace as everything else, and, yes, Python thinks you are trying to inherit from a module.\nChange:\nclass MainPage(BaseHandler):\n\nto:\nclass MainPage(BaseHandler.BaseHandler):\n\nand you should be good to go. That way, you're saying \"please inherit from the BaseHandler cla...
[ 18, 18 ]
[]
[]
[ "class", "import", "module", "python" ]
stackoverflow_0002393544_class_import_module_python.txt
Q: Python: Random sequence I have the following code: import string import random d =[random.choice(string.uppercase) for x in xrange(3355)] s = "".join(d) print s At the moment it prints out a random sequence of letters from the alphabet. But, i need it to print out a sequence of letters containing only four lett...
Python: Random sequence
I have the following code: import string import random d =[random.choice(string.uppercase) for x in xrange(3355)] s = "".join(d) print s At the moment it prints out a random sequence of letters from the alphabet. But, i need it to print out a sequence of letters containing only four letters for example 'A', 'C', 'U'...
[ "Change the set you are asking random.choice to pick from:\nimport random\n\nd =[random.choice('ACUG') for x in xrange(3355)]\ns = \"\".join(d)\n\nprint s\n\n\nEdit: As SilentGhost points out, if your ultimate goal is only to make a string, skipping the intermediate list is more memory-efficient:\ns = \"\".join(ran...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002393851_python.txt
Q: Python: File formatting I have a for loop which references a dictionary and prints out the value associated with the key. Code is below: for i in data: if i in dict: print dict[i], How would i format the output so a new line is created every 60 characters? and with the character count along the side f...
Python: File formatting
I have a for loop which references a dictionary and prints out the value associated with the key. Code is below: for i in data: if i in dict: print dict[i], How would i format the output so a new line is created every 60 characters? and with the character count along the side for example: 0001 MRQLLLISD...
[ "It's a finicky formatting problem, but I think the following code:\nimport sys\n\nclass EveryN(object):\n def __init__(self, n, outs):\n self.n = n # chars/line\n self.outs = outs # output stream\n self.numo = 1 # next tag to write\n self.tll = 0 # tot chars on this line\n def write(...
[ 1, 0, 0, 0 ]
[]
[]
[ "file", "formatting", "python" ]
stackoverflow_0002393120_file_formatting_python.txt
Q: Can nginx forward to Pylons, ignore response, return alternate response? One of my URLs is for a tracking cookie. In the basic configuration, the pylons controller parses the query string, does a DB query, and sets the cookie accordingly. I want to move to nginx. I am wondering if this is possible: nginx fetches ...
Can nginx forward to Pylons, ignore response, return alternate response?
One of my URLs is for a tracking cookie. In the basic configuration, the pylons controller parses the query string, does a DB query, and sets the cookie accordingly. I want to move to nginx. I am wondering if this is possible: nginx fetches value of cookie from memcached nginx writes the headers and serves static file...
[ "The scenario you described is hardly possible \"as is\". Problems:\n\nNginx cannot read cookie from memcached, as far as I know. It can pass response body only.\nNginx can indeed call \"post_action\", but this functionality is in beta and you'd better avoid it.\n\nFrankly, I don't completely understand what cookie...
[ 2 ]
[]
[]
[ "nginx", "pylons", "python", "web_applications" ]
stackoverflow_0002383036_nginx_pylons_python_web_applications.txt
Q: how do i stop beautiful soup from skipping rows while parsing? while using beautifulsoup to parse a table in html every other row starts with <tr class="row_k"> instead of a tr tag without a class Sample HTML <tr class="row_k"> <td><img src="some picture url" alt="Item A"></td> <td><a href="some url"> Item A</a...
how do i stop beautiful soup from skipping rows while parsing?
while using beautifulsoup to parse a table in html every other row starts with <tr class="row_k"> instead of a tr tag without a class Sample HTML <tr class="row_k"> <td><img src="some picture url" alt="Item A"></td> <td><a href="some url"> Item A</a></td> <td>14.8k</td> <td><span class="drop">-555</span></td> <td...
[ "I am still learning a lot but I am going to suggest you try lxml. I am going to make a stab at this and I think it will mostly get you there but there may be some niceties I am not certain about.\nassuming this1 is a string\nfrom lxml.html import fromstring\nthis1_tree=fromstring(this1)\nall_cells=[(item[0], item...
[ 2 ]
[]
[]
[ "beautifulsoup", "python", "tags", "urllib2", "xml" ]
stackoverflow_0002394300_beautifulsoup_python_tags_urllib2_xml.txt
Q: pycurl READFUNCTION with a bytestream Is there a way to write a callback function for pycurl's READFUNCTION that does not return a string? I am planning on sending blocks of binary data via pycurl. i tried writing a callback function that does this: def read_callback(self, size): for block in data: yield blo...
pycurl READFUNCTION with a bytestream
Is there a way to write a callback function for pycurl's READFUNCTION that does not return a string? I am planning on sending blocks of binary data via pycurl. i tried writing a callback function that does this: def read_callback(self, size): for block in data: yield block but pycurl exits with an error that say...
[ "The \"read function\" must return a string of bytes -- remember, libcurl is a wrapper on an underlying C library, so of course it's type-picky!-). However, it can perfectly be a binary string of bytes (in Python 2.* at least -- I don't think pycurl works with Python 3 anyway), so of course it can return \"blocks ...
[ 1 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0002394258_pycurl_python.txt
Q: Saving Django xml in a file? I have a function in a view that renders the xml in the browser, but what I want is to save the xml content to a file, to be used in a Flash gallery. def build_xml_menu(request): rubros = Rubro.objects.all() familias = Familia.objects.all() context_data = {'rubros': rub...
Saving Django xml in a file?
I have a function in a view that renders the xml in the browser, but what I want is to save the xml content to a file, to be used in a Flash gallery. def build_xml_menu(request): rubros = Rubro.objects.all() familias = Familia.objects.all() context_data = {'rubros': rubros, 'familias': familias} ret...
[ "You have to use render to string instead of render_to_response :)\n" ]
[ 4 ]
[]
[]
[ "django", "flash", "python", "xml" ]
stackoverflow_0002394437_django_flash_python_xml.txt
Q: Is there a better way to parse html tables than lxml I am working with html documents and ripping out tables to parse them if they turn out to be the correct tables. I am happy with the results - my extraction process successfully maps row labels and column headings in over 95% of the cases and in the cases it do...
Is there a better way to parse html tables than lxml
I am working with html documents and ripping out tables to parse them if they turn out to be the correct tables. I am happy with the results - my extraction process successfully maps row labels and column headings in over 95% of the cases and in the cases it does not we can identify the problems and use other approach...
[ "Actually, browser engines are deliberately stupid in their parsing of HTML, assuming that what they get is only marginally correct. lxml and BeautifulSoup attempt to mimic this level of stupidity, so they are the correct tools to use.\n", "To \"harness the 'engine' of a browser\", your best bet at this time is n...
[ 2, 2 ]
[]
[]
[ "browser", "lxml", "python" ]
stackoverflow_0002393917_browser_lxml_python.txt
Q: How many items in a dictionary share the same value in Python Is there a way to see how many items in a dictionary share the same value in Python? Let's say that I have a dictionary like: {"a": 600, "b": 75, "c": 75, "d": 90} I'd like to get a resulting dictionary like: {600: 1, 75: 2, 90: 1} My first naive atte...
How many items in a dictionary share the same value in Python
Is there a way to see how many items in a dictionary share the same value in Python? Let's say that I have a dictionary like: {"a": 600, "b": 75, "c": 75, "d": 90} I'd like to get a resulting dictionary like: {600: 1, 75: 2, 90: 1} My first naive attempt would be to just use a nested-for loop and for each value then ...
[ "You could use itertools.groupby for this.\nimport itertools\nx = {\"a\": 600, \"b\": 75, \"c\": 75, \"d\": 90}\n[(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]\n\n", "When Python 2.7 comes out you can use its collections.Counter class\notherwise see counter receipe\nUnder Python 2.7a3 \nfro...
[ 7, 2, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002393902_dictionary_python.txt
Q: Best method of connection between automated python XMPP server and interface to django? I have an XMPP server (likely — python, twisted, wokkel), which I prefer not to restart even in the development version, and I have some python module “worker” (which is interface to particular django project), which gets jid a...
Best method of connection between automated python XMPP server and interface to django?
I have an XMPP server (likely — python, twisted, wokkel), which I prefer not to restart even in the development version, and I have some python module “worker” (which is interface to particular django project), which gets jid and message text and returns some response (text or XML, either way). The question is, what wo...
[ "My suggestion is:\n\nUse RabbitMQ with XMPP adaptor.\nUse Python carrot for AMQP since it can be used directly under Django.\n\n", "I can't say that I understand all of your question, but the bit where you're asking how to connect django and twisted and multiple workers: I'd suggest using AMPQ. This gets you rel...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002394284_django_python.txt
Q: How do you NOT automatically dereference a db.ReferenceProperty in Google App Engine? Suppose I have class Foo(db.Model): bar = db.ReferenceProperty(Bar) foo = Foo.all().get() Is there a way for me to do foo.bar without a query being made to Datastore? The docs say that foo.bar will be an instance of Key, so ...
How do you NOT automatically dereference a db.ReferenceProperty in Google App Engine?
Suppose I have class Foo(db.Model): bar = db.ReferenceProperty(Bar) foo = Foo.all().get() Is there a way for me to do foo.bar without a query being made to Datastore? The docs say that foo.bar will be an instance of Key, so I would expect to be able to do foo.bar.id() and be able to get the id of the Bar that's as...
[ "As the docs say,\n\nThe ReferenceProperty value can be\n used as if it were a model instance,\n and the datastore entity will be\n fetched and the model instance created\n when it is first used in this way.\n Untouched reference properties do not\n query for unneeded data.\n\nso you're fine as long as you do...
[ 8 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002395144_google_app_engine_google_cloud_datastore_python.txt
Q: How do I set up QtDesigner for a project that has animated elements? I'm writing a project to simulate creatures moving around a map. These can be represented by simple circles, but I need a map/grid and those circles animated on top of the map. What elements should I use in QtDesigner to set up for this kind o...
How do I set up QtDesigner for a project that has animated elements?
I'm writing a project to simulate creatures moving around a map. These can be represented by simple circles, but I need a map/grid and those circles animated on top of the map. What elements should I use in QtDesigner to set up for this kind of GUI in my project? I've yet to do anything like this before
[ "You probably want a Graphics View to do it right, but if you don't care about performance, you might be able to get by with just setting the pos on a bunch of buttons to move them around on a widget (without a layout).\n" ]
[ 1 ]
[]
[]
[ "animation", "pyqt", "python", "qt", "user_interface" ]
stackoverflow_0002395232_animation_pyqt_python_qt_user_interface.txt
Q: Suppose I have 400 rows of people's names in a database. What's the best way to do a search for their names? They will also search part of their name. Not only words with spaces. If they type "Matt", I expect to retrieve "Matthew" too. A: SELECT * FROM mytable WHERE name LIKE 'matt%' OR name LIKE '[ ,-/]matt%'...
Suppose I have 400 rows of people's names in a database. What's the best way to do a search for their names?
They will also search part of their name. Not only words with spaces. If they type "Matt", I expect to retrieve "Matthew" too.
[ "SELECT * \nFROM mytable \nWHERE name LIKE 'matt%' OR name LIKE '[ ,-/]matt%'\n\nNotes:\n1) Fancy wildcard. The reason for not using the simpler LIKE '%xyz%' form is that depending on the xyz the database could return many non-relevant records. For example \"Jeff Zermatt\" in the case of the \"Matt\" search.\nThe...
[ 12, 10, 1, 0 ]
[]
[]
[ "database", "indexing", "mysql", "python", "search" ]
stackoverflow_0002394870_database_indexing_mysql_python_search.txt
Q: List of evented / asynchronous languages I'm working on a system than has to be pretty scalable from the beginning. I've started looking at / playing around with asynchronous/evented approaches to writing serverside code. I've played around with both ruby's EventMachine and node.js. EventMachine is cool, but doesn...
List of evented / asynchronous languages
I'm working on a system than has to be pretty scalable from the beginning. I've started looking at / playing around with asynchronous/evented approaches to writing serverside code. I've played around with both ruby's EventMachine and node.js. EventMachine is cool, but doesn't have asynchronous file I/O, which I need. T...
[ "Erlang may be the language with the highest intrinsic scalability for server-side code (it manages multiprocessing for you, mostly by doing async, cooperative task switching \"under the covers\") -- if you can stomach its peculiar syntax and (often) peculiar semantics.\nPython has twisted (very general purpose for...
[ 20, 16, 4, 4 ]
[]
[]
[ "asynchronous", "javascript", "lisp", "python", "ruby" ]
stackoverflow_0002384314_asynchronous_javascript_lisp_python_ruby.txt
Q: Detect workstation/System Screen Lock using Python(ubuntu) Is there anyway that we can detect when the system/screen gets locked and notify some event to trigger in Ubuntu ? A: There is a possibility to be notified when the screen becomes locked/unlocked with DBus, this is reference on GnomeScreensaver showing t...
Detect workstation/System Screen Lock using Python(ubuntu)
Is there anyway that we can detect when the system/screen gets locked and notify some event to trigger in Ubuntu ?
[ "There is a possibility to be notified when the screen becomes locked/unlocked with DBus, this is reference on GnomeScreensaver showing the basics of it.\nI am not DBus expert, but there are bindings for python, so you can listen for DBus events in python. Combinig the two, you should be able to get what you want:-...
[ 3 ]
[]
[]
[ "locking", "python", "system", "ubuntu" ]
stackoverflow_0002395579_locking_python_system_ubuntu.txt
Q: Calling an executable from within Python / Django web application running on IIS I have a Python / Django application which is supposed to call an external windows binary and get its output at some point. And it does so when tested via 'python manage.py shell'. But when it is run from within the web browser, which...
Calling an executable from within Python / Django web application running on IIS
I have a Python / Django application which is supposed to call an external windows binary and get its output at some point. And it does so when tested via 'python manage.py shell'. But when it is run from within the web browser, which is served by IIS, the external application is not executed. Is IIS blocking somethin...
[ "Might be a permissions issue. when you run from the shell, you're using the user that run the python manage.py shell command. When serving requests from the IIS you're using its user (IUSR or something like that). Try giving execution permission on the executable file to the Everyone group just to see if it helps....
[ 0 ]
[]
[]
[ "django", "executable", "iis", "python", "windows" ]
stackoverflow_0002394054_django_executable_iis_python_windows.txt
Q: algorithm to find independent sets Folks, I have a problem. I am a writing a script in python which consists of several modules. Some of the modules are dependent on other modules, hence they should be run only after the dependent modules are successfully run. So each modules derives from a base class module and o...
algorithm to find independent sets
Folks, I have a problem. I am a writing a script in python which consists of several modules. Some of the modules are dependent on other modules, hence they should be run only after the dependent modules are successfully run. So each modules derives from a base class module and overrides a list called DEPENDENCIES whic...
[ "I posted a description of topological sorting recently in a question about make -j. Serendipity! From the Wikipedia article:\n\nThe canonical application of topological sorting (topological order) is in scheduling a sequence of jobs or tasks; topological sorting algorithms were first studied in the early 1960s in ...
[ 2, 1 ]
[]
[]
[ "algorithm", "data_structures", "python" ]
stackoverflow_0002395525_algorithm_data_structures_python.txt
Q: Python UTF-16 WAVY DASH encoding question / issue I was doing some work today, and came across an issue where something "looked funny". I had been interpreting some string data as utf-8, and checking the encoded form. The data was coming from ldap (Specifically, Active Directory) via python-ldap. No surprises ther...
Python UTF-16 WAVY DASH encoding question / issue
I was doing some work today, and came across an issue where something "looked funny". I had been interpreting some string data as utf-8, and checking the encoded form. The data was coming from ldap (Specifically, Active Directory) via python-ldap. No surprises there. So I came upon the byte sequence '\xe3\x80\xb0' a fe...
[ "This seems to be the correct behaviour. The character u'\\u3030' when encoded in UTF-16 is the same as the encoding of '00' in UTF-8. It looks strange, but it's correct.\nThe '\\xff\\xfe' you can see is just a Byte Order Mark.\nAre you sure you want a wavy dash, and not some other character? If you were hoping for...
[ 2, 2, 1, 0 ]
[]
[]
[ "encoding", "python", "unicode", "utf_16", "utf_8" ]
stackoverflow_0002269171_encoding_python_unicode_utf_16_utf_8.txt
Q: Elixir create_all() not creating database and tables I'm using Elixir 0.7.1 , Sqlalchemy 0.6beta1 , MySQLdb 1.2.2. My Model file 'model.py' looks like this: from elixir import * from datetime import datetime class Author: first_name = Field(Unicode(64)) last_name = Field(Unicode(64)) class Article: title =...
Elixir create_all() not creating database and tables
I'm using Elixir 0.7.1 , Sqlalchemy 0.6beta1 , MySQLdb 1.2.2. My Model file 'model.py' looks like this: from elixir import * from datetime import datetime class Author: first_name = Field(Unicode(64)) last_name = Field(Unicode(64)) class Article: title = Field(Unicode(64)) class Category: name = Field(Unicod...
[ "Well, you have to inherit from the Entity base class (or from another base class of your choosing that use the EntityMeta metaclass).\nclass Author(Entity):\n first_name = Field(Unicode(64))\n last_name = Field(Unicode(64))\n\nclass Article(Entity):\n title = Field(Unicode(64))\n\nclass Category(Entity):\...
[ 1 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0002394743_python_python_elixir_sqlalchemy.txt
Q: Aggregating across columns in Django I'm trying to figure out if there's a way to do a somewhat-complex aggregation in Django using its ORM, or if I'm going to have to use extra() to stick in some raw SQL. Here are my object models (stripped to show just the essentials): class Submission(Models.model) favorite_o...
Aggregating across columns in Django
I'm trying to figure out if there's a way to do a somewhat-complex aggregation in Django using its ORM, or if I'm going to have to use extra() to stick in some raw SQL. Here are my object models (stripped to show just the essentials): class Submission(Models.model) favorite_of = models.ManyToManyField(User, related_n...
[ "One possibility would be to re-arrange your current query slightly. What if you tried something like the following:\nsubmission_list = Response.objects\\\n .annotate(votes=Count('voted_up_by'))\\\n .filter(votes__gt=0)\\\n .order_by('-votes')[:TOP_NUM]\nsubmission_list.query.group_by = ['submission_id']\...
[ 1, 0 ]
[]
[]
[ "aggregate", "django", "orm", "python" ]
stackoverflow_0002394778_aggregate_django_orm_python.txt
Q: Memory error due to the huge input file size When I using the following code to read file: lines=file("data.txt").read().split("\n") I have the following error MemoryError the file size is ls -l -rw-r--r-- 1 charlie charlie 1258467201 Sep 26 12:57 data.txt A: Obviously the file is too large to be read into mem...
Memory error due to the huge input file size
When I using the following code to read file: lines=file("data.txt").read().split("\n") I have the following error MemoryError the file size is ls -l -rw-r--r-- 1 charlie charlie 1258467201 Sep 26 12:57 data.txt
[ "Obviously the file is too large to be read into memory all at once.\nWhy not just use:\nwith open(\"data.txt\") as myfile:\n for line in myfile:\n do_something(line.rstrip(\"\\n\"))\n\nor, if you're not on Python 2.6 and higher:\nmyfile = open(\"data.txt\")\nfor line in myfile:\n do_something(line.rst...
[ 25, 3 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002396238_file_python.txt
Q: migrating from one framework to another in python I'm having trouble deciding which python framework to use for my website. So I've decided to bite the bullet and use Django. My question is how easy (or difficult) will it be to migrate to a different framework in future if I have issues with Django ? A: Your dat...
migrating from one framework to another in python
I'm having trouble deciding which python framework to use for my website. So I've decided to bite the bullet and use Django. My question is how easy (or difficult) will it be to migrate to a different framework in future if I have issues with Django ?
[ "Your database queries(and object models), url config, and templates to say the least will all be specific to django. That said - if you understand what you're doing, recreating them in another package shouldn't take too long if you really need to at some later time.\nedit: this is all assuming you dont integrate t...
[ 1, 1 ]
[]
[]
[ "django", "frameworks", "migrate", "python" ]
stackoverflow_0002396294_django_frameworks_migrate_python.txt
Q: Load huge data to memory using python I have to load large data to the memory, and the structure is list. How can I get another approach. thanx A: process the data line by line, eg for line in open("file"): print "do processing of line:",line Or if you really really want to load one whole chunk to memory, y...
Load huge data to memory using python
I have to load large data to the memory, and the structure is list. How can I get another approach. thanx
[ "process the data line by line, eg\nfor line in open(\"file\"):\n print \"do processing of line:\",line\n\nOr if you really really want to load one whole chunk to memory, you can try memory mapping.\nimport mmap,os,re\nbigfile = open( \"file2\" )\nlength = os.stat(bigfile.fileno()).st_size\ntry:\n mapping = m...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002396350_python.txt
Q: App Engine, Python: problem updating datastore record I need to update a record in the datastore, but instead of updated record I get always a new record. My model: class PageModel(db.Model): title = db.StringProperty() content = db.TextProperty() reference = db.SelfReferenceProperty() user = db....
App Engine, Python: problem updating datastore record
I need to update a record in the datastore, but instead of updated record I get always a new record. My model: class PageModel(db.Model): title = db.StringProperty() content = db.TextProperty() reference = db.SelfReferenceProperty() user = db.UserProperty(auto_current_user = True) created = db...
[ "Why are you created a new PageModel everytime? instead edit the one you got by id i.e. CP ? e.g.\nedited_page = CP \nedited_page.title = title\nedited_page.content = content\nedited_page.type = type\nedited_page.reference = reference\nedited_page.template = template\n\nedited_page.put()\n\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002396437_google_app_engine_google_cloud_datastore_python.txt
Q: How to split big numbers? I have a big number, which I need to split into smaller numbers in Python. I wrote the following code to swap between the two: def split_number (num, part_size): string = str(num) string_size = len(string) arr = [] pointer = 0 while pointer < string_size: e ...
How to split big numbers?
I have a big number, which I need to split into smaller numbers in Python. I wrote the following code to swap between the two: def split_number (num, part_size): string = str(num) string_size = len(string) arr = [] pointer = 0 while pointer < string_size: e = pointer + part_size a...
[ "Clearly, any leading 0s in the \"parts\" can't be preserved by this operation. Can't join_number also receive the part_size argument, so that it can reconstruct the string formats with all the leading zeros?\nWithout some information such as part_size that's known to both the sender and receiver, or the equivalen...
[ 2, 2, 1, 0 ]
[]
[]
[ "numbers", "python", "string" ]
stackoverflow_0002394698_numbers_python_string.txt
Q: how to document a python package I know what's the standard way to document functions, classes and modules, but how do I document packages - do I put a docstring in __init__.py, or something else? A: Yes, just like for a function or class comment, the first item in the __init__.py file should be a comment string...
how to document a python package
I know what's the standard way to document functions, classes and modules, but how do I document packages - do I put a docstring in __init__.py, or something else?
[ "Yes, just like for a function or class comment, the first item in the __init__.py file should be a comment string:\n\"\"\"\nThis is the xyz package.\n\"\"\"\n\nNow if you import the package, and use help(package), you will see your docstring. See more here: http://www.python.org/dev/peps/pep-0257/\n", "See PEP25...
[ 18, 5 ]
[ "Documenting is a good idea, so long as you don't document something obvious in your code\nTry to understand that most people reading your source will understand python, so commenting or documenting lines like this is pointless:\na = 1 #this assigns 1 to a\n\nBut commenting or documenting a rather complicated f...
[ -3 ]
[ "documentation", "package", "python" ]
stackoverflow_0002396141_documentation_package_python.txt
Q: GTK StatusIcon: Coordinates of left-click? how do I get the x/y-coordinates of a left click in a Gtk StatusIcon? This is my first GTK app and I'm stuck. Is there any way to get details about the last button event that occurred? Or is it possible to pass those details to the handler function when connect()ing the "...
GTK StatusIcon: Coordinates of left-click?
how do I get the x/y-coordinates of a left click in a Gtk StatusIcon? This is my first GTK app and I'm stuck. Is there any way to get details about the last button event that occurred? Or is it possible to pass those details to the handler function when connect()ing the "activate" callback? Greets, Philip
[ "Since the status icon isn't a widget, it's a bit roundabout. You might be able to pass in some kind of widget as part of the user parameter object and get the global mouse position on activate. See here on how you might.\n" ]
[ 1 ]
[]
[]
[ "gtk", "linux", "pygtk", "python" ]
stackoverflow_0002396557_gtk_linux_pygtk_python.txt
Q: How to supress Powershell window when using the -File option I'm calling Powershell like so: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -noninteractive -nologo -file "C:\Users\dummy\Documents\dev\powershell\samples\test.ps1" I'm calling it from a python script, but the same problem can b...
How to supress Powershell window when using the -File option
I'm calling Powershell like so: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -noninteractive -nologo -file "C:\Users\dummy\Documents\dev\powershell\samples\test.ps1" I'm calling it from a python script, but the same problem can be observed if called via a shortcut. I thought the -NonInteractive...
[ "You can pass appropriate arguments to CreateProcess or Process.Start to suppress the console window.\nHowever, PowerShell also has a -WindowStyle parameter which you can set to hidden.\n", "I had no luck with -WindowStyle Hidden, because a console window appeared every time for a while. \nThat's why I use a help...
[ 2, 1, 0 ]
[]
[]
[ "popen", "powershell", "python", "windowless" ]
stackoverflow_0002396271_popen_powershell_python_windowless.txt
Q: Weak reference callback is not called because of circular references I'm trying to write a finalizer for Python classes that have circular references. I found out that weak reference callbacks are the way to go. Unfortunately, it seems the lambda I use as a callback is never called. For example, running this code:...
Weak reference callback is not called because of circular references
I'm trying to write a finalizer for Python classes that have circular references. I found out that weak reference callbacks are the way to go. Unfortunately, it seems the lambda I use as a callback is never called. For example, running this code: def del_A(name): print('An A deleted:' + name) class A(object): ...
[ "When you use \n self._wr = weakref.ref(self, lambda wr, n = self.name: del_A(n)) \n\nthe callback will only be called when self is about to be finalized. \nThe reason why the callback is not getting called is because\na = A('a1')\nb = B()\na.other = b # This gives a another attribute; it does not switch `a` awa...
[ 3, 3, 0 ]
[]
[]
[ "lambda", "python", "weak_references" ]
stackoverflow_0002295993_lambda_python_weak_references.txt
Q: Is the content between anchor tags (a) in html seen as a branch in lxml? I am trying to get some content in html documents. Some of the documents have a table of contents that very nicely indicates where in the document the content I want to strip out is located. That is either the value or text_content of the t...
Is the content between anchor tags (a) in html seen as a branch in lxml?
I am trying to get some content in html documents. Some of the documents have a table of contents that very nicely indicates where in the document the content I want to strip out is located. That is either the value or text_content of the tag are easily identifiable and point to what I need. For example I might have...
[ "No, there is not a single branch between siblings. However, you can just iterate over their parent and extract (can be done in various ways, depending on how you already have handles for the anchor tags). Note the handling of text and tail to avoid losing data. Modifying example_doc to see the results may help ...
[ 1 ]
[]
[]
[ "html", "lxml", "python" ]
stackoverflow_0002397064_html_lxml_python.txt
Q: Python: Connect blender with WinTracker 2 I am trying to develop a project that uses a control model in Blender by using WinTracker machine, but I don't know how to connect it with Blender Game Engine. How can I connect it with Blender Game Engine? A: You must write the plug-in for blender and used the wintrack...
Python: Connect blender with WinTracker 2
I am trying to develop a project that uses a control model in Blender by using WinTracker machine, but I don't know how to connect it with Blender Game Engine. How can I connect it with Blender Game Engine?
[ "You must write the plug-in for blender and used the wintracker driver. It is ready for c Lagrange.\nbut you have \"wintracker2\"?\nI wanted to buy it but the company said \"it's not ready to seal\".\n" ]
[ 0 ]
[]
[]
[ "blender", "python" ]
stackoverflow_0001748482_blender_python.txt
Q: import strategy within django applications I would like to know what is the best import strategy within django reusable applications. Say I have an application called usefulapp. Inside my app, I will need to access, say, the models. Should I use an explicit import as: import usefulapp.models or simply, since I am...
import strategy within django applications
I would like to know what is the best import strategy within django reusable applications. Say I have an application called usefulapp. Inside my app, I will need to access, say, the models. Should I use an explicit import as: import usefulapp.models or simply, since I am inside this very app, I could use: import model...
[ "The second approach assumes that . is in sys.path before any other directories that may contain a models module. There is no requirement that . be in it at all, so importing either via relative imports or via the app is best.\n", "I personally, try to keep the convention of always importing from the app.\nDon't ...
[ 3, 3 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0002397055_django_import_python.txt
Q: Python: web login script, what's the problem? this is the script >> import ClientForm import urllib2 request = urllib2.Request("http://ritaj.birzeit.edu") response = urllib2.urlopen(request) forms = ClientForm.ParseResponse(response, backwards_compat=False) response.close() form = forms[0] print form sooform = s...
Python: web login script, what's the problem?
this is the script >> import ClientForm import urllib2 request = urllib2.Request("http://ritaj.birzeit.edu") response = urllib2.urlopen(request) forms = ClientForm.ParseResponse(response, backwards_compat=False) response.close() form = forms[0] print form sooform = str(raw_input("Form Name: ")) username = str(raw_inp...
[ "The only <form> tag in the HTML served at that URL (save it to a file and look for yourself!) is:\n<form method=\"GET\" action=\"http://www.google.com/u/ritaj\">\n\nwhich does a customized Google search and has nothing to do with logging in (plus, for some reason, ClientForm has some problem identifying that speci...
[ 1, 0 ]
[]
[]
[ "browser", "python" ]
stackoverflow_0002396382_browser_python.txt
Q: Coding style - keep parentheses on the same line or new line? Suppose you are calling a function, where there's clearly a need to break down the statement into few lines, for readability's sake. However there are at least two way to do it: Would you do this: return render(request, template, { ...
Coding style - keep parentheses on the same line or new line?
Suppose you are calling a function, where there's clearly a need to break down the statement into few lines, for readability's sake. However there are at least two way to do it: Would you do this: return render(request, template, { 'var1' : value1, 'var2' : value2, ...
[ "I'd probably do:\nreturn render(\n request, \n template,\n {\n 'var1' : value1,\n 'var2' : value2,\n 'var3' : value3\n }\n)\n\nI would keep the bracket on the same line, so that searches for render( work. And because I find it clearer. But I'd put all the arguments on new lines.\n"...
[ 10, 9, 9, 2 ]
[]
[]
[ "coding_style", "formatting", "python", "readability" ]
stackoverflow_0002395664_coding_style_formatting_python_readability.txt
Q: Re-order list in Python to ensure it starts with check values I'm reading in serial data using Pyserial, to populate a list of 17 values (1byte each) at a sampling rate of 256Hz. The bytes I ultimately want to use are the 5th to 8th in the list. Providing no bytes are dropped, the first two values of the stream a...
Re-order list in Python to ensure it starts with check values
I'm reading in serial data using Pyserial, to populate a list of 17 values (1byte each) at a sampling rate of 256Hz. The bytes I ultimately want to use are the 5th to 8th in the list. Providing no bytes are dropped, the first two values of the stream are always the same ('165','90'). I'm getting quite a few dropped va...
[ "In case I understood you well,\nsuppose you have a list like this:\nl = [67, 126, 165, 90, 11, 1, 3, 5, 151, 99, 23]\n\nyou'd want to obtain:\n useful = [3,5,151,99]\nThen, you could do:\n# obtain places where 165 is followed by 90\nmatch = [x for x in xrange(len(l)-1) if l[x]==165 and l[x+1]==90]\n# obtain ran...
[ 2, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002387068_list_python.txt
Q: using os.path is quite verbose is there a more concise way to manipulate paths for example I have a script that needs to put it's parent directory on the python path, currently I'm using the following sys.path += [os.path.dirname(os.path.dirname(os.path.realpath(__file__)))] this seems a touch ridiculous, surely ...
using os.path is quite verbose is there a more concise way to manipulate paths
for example I have a script that needs to put it's parent directory on the python path, currently I'm using the following sys.path += [os.path.dirname(os.path.dirname(os.path.realpath(__file__)))] this seems a touch ridiculous, surely there is a simpler way?
[ "I've found Jason Orendorff's path module to be very nice. Unfortunately, it seems that his website is no longer on the internet, but you can still download the module from PyPI.\n", "You could do:\nfrom os.path import dirname,realpath\nsys.path.append(dirname(dirname(realpath(__file__))))\n\nBut to be honest, I...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0002395653_path_python.txt
Q: Why time.clock() returns such a large value on Windows Server 2008 X64 I ran following script on different machine and got quite different results. The elapsed time.clock() is so large. Script: #------------------------------------------------------------------------------------ import time start_clock = time.clo...
Why time.clock() returns such a large value on Windows Server 2008 X64
I ran following script on different machine and got quite different results. The elapsed time.clock() is so large. Script: #------------------------------------------------------------------------------------ import time start_clock = time.clock() time.sleep(60) end_clock = time.clock() print "Sleep Clock = ", str(end...
[ "Per the docs on time.clock\n\nOn Windows, this function returns\n wall-clock seconds elapsed since the\n first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter().\n\nso my (blind, i.e., I've never seen Amazon's code for Windows virtualization!-) guess would b...
[ 2 ]
[]
[]
[ "python", "time" ]
stackoverflow_0002395677_python_time.txt
Q: Django: using variables as array indices? I am trying to create a template that will put items in a table. Controller: items = Item.all().order('name').fetch(10) template_values = {'items': items, 'headers': ['Name', 'Price', 'Quantity']} render('Views/table.html', self, template_va...
Django: using variables as array indices?
I am trying to create a template that will put items in a table. Controller: items = Item.all().order('name').fetch(10) template_values = {'items': items, 'headers': ['Name', 'Price', 'Quantity']} render('Views/table.html', self, template_values) Template: <table> <tr> {% for he...
[ "You could tweak the view to do:\nitems = Item.all().order('name').fetch(10)\nheaders = ['Name', 'Price', 'Quantity']\nviewitems = [[getattr(x, h) for h in headers] for x in items]\n\ntemplate_values = {'items': viewitems,\n 'headers': headers}\nrender('Views/table.html', self, template_values)\n\...
[ 2, 1 ]
[]
[]
[ "django", "google_app_engine", "python", "templating" ]
stackoverflow_0002397324_django_google_app_engine_python_templating.txt
Q: How to have multiple python programs append rows to the same file? I've got multiple python processes (typically 1 per core) transforming large volumes of data that they are each reading from dedicated sources, and writing to a single output file that each opened in append mode. Is this a safe way for these progra...
How to have multiple python programs append rows to the same file?
I've got multiple python processes (typically 1 per core) transforming large volumes of data that they are each reading from dedicated sources, and writing to a single output file that each opened in append mode. Is this a safe way for these programs to work? Because of the tight performance requirements and large data...
[ "Have you considered using the multiprocessing module to coordinate between the running programs in a thread-like manner? See in particular the queue interface; you can place each completed work item on a queue when completed, and have a single process reading off the queue and writing to your output file.\nAlterna...
[ 4, 4 ]
[]
[]
[ "concurrency", "python" ]
stackoverflow_0002397576_concurrency_python.txt
Q: Best seed for parallel process I need to run a MonteCarlo simulations in parallel on different machines. The code is in c++, but the program is set up and launched with a python script that set a lot of things, in particular the random seed. The function setseed thake a 4 bytes unsigned integer Using a simple impo...
Best seed for parallel process
I need to run a MonteCarlo simulations in parallel on different machines. The code is in c++, but the program is set up and launched with a python script that set a lot of things, in particular the random seed. The function setseed thake a 4 bytes unsigned integer Using a simple import time setseed(int(time.time())) i...
[ "Reading from /dev/random is a good idea. Just convert the 4 byte string into an Integer:\nf = open(\"/dev/random\",\"rb\")\nrnd_str = f.read(4)\n\nEither using struct:\nimport struct\nrand_int = struct.unpack('I', rnd_string)[0]\n\nUpdate Uppercase I is needed.\nOr multiply and add:\nrand_int = 0\nfor c in rnd_str...
[ 5, 2, 1, 0 ]
[]
[]
[ "montecarlo", "parallel_processing", "python", "random", "seed" ]
stackoverflow_0002396209_montecarlo_parallel_processing_python_random_seed.txt
Q: What's the easiest way to convert a list of hex byte strings to a list of hex integers? I have a list of hex bytes strings like this ['BB', 'A7', 'F6', '9E'] (as read from a text file) How do I convert that list to this format? [0xBB, 0xA7, 0xF6, 0x9E] A: [int(x, 16) for x in L] A: [0xBB, 0xA7, 0xF6, 0x9E] is ...
What's the easiest way to convert a list of hex byte strings to a list of hex integers?
I have a list of hex bytes strings like this ['BB', 'A7', 'F6', '9E'] (as read from a text file) How do I convert that list to this format? [0xBB, 0xA7, 0xF6, 0x9E]
[ "[int(x, 16) for x in L]\n\n", "[0xBB, 0xA7, 0xF6, 0x9E] is the same as [187, 167, 158]. So there's no special 'hex integer' form or the like.\nBut you can convert your hex strings to ints:\n>>> [int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]\n[187, 167, 246, 158]\n\nSee also Convert hex string to int in Python\n"...
[ 9, 4, 4 ]
[]
[]
[ "python" ]
stackoverflow_0002397687_python.txt
Q: Test if value is Decimal In some Python (v3) code I am creating lists of Decimals from user input, like this: input = [] # later populated with strings by user with values like '1.45984000E+001' decimals = [Decimal(c) for c in input] However, sometimes the input list contains strings that cannot be parsed. How ca...
Test if value is Decimal
In some Python (v3) code I am creating lists of Decimals from user input, like this: input = [] # later populated with strings by user with values like '1.45984000E+001' decimals = [Decimal(c) for c in input] However, sometimes the input list contains strings that cannot be parsed. How can I test if c can be represent...
[ "Catch exception\ndecimals = []\nfor s in input:\n try: decimals.append(Decimal(s))\n except InvalidOperation:\n pass\n\nUse helper function\nfrom itertools import imap\n\ndef parse_decimal(s):\n try: return Decimal(s)\n except InvalidOperation:\n return None\n\ndecimals = [d for d in imap...
[ 3, 0 ]
[]
[]
[ "decimal", "python" ]
stackoverflow_0002398141_decimal_python.txt
Q: How to check if datetime is older than 20 seconds This is my first time here so I hope I post this question at the right place. :) I need to build flood control for my script but I'm not good at all this datetime to time conversions with UTC and stuff. I hope you can help me out. I'm using the Google App Engine wi...
How to check if datetime is older than 20 seconds
This is my first time here so I hope I post this question at the right place. :) I need to build flood control for my script but I'm not good at all this datetime to time conversions with UTC and stuff. I hope you can help me out. I'm using the Google App Engine with Python. I've got a datetimeproperty at the DataStore...
[ "You can use the datetime.timedelta datatype, like this:\nimport datetime\nlastplus = q.get()\nif lastplus.date < datetime.datetime.now()-datetime.timedelta(seconds=20):\n print \"Go\"\n\nRead more about it here: http://docs.python.org/library/datetime.html\nCheers,\nPhilip\n", "Try this:\nfrom datetime import...
[ 57, 4 ]
[]
[]
[ "datetime", "google_app_engine", "python", "time" ]
stackoverflow_0002398205_datetime_google_app_engine_python_time.txt
Q: Python - BaseHTTPServer.HTTPServer Concurrency & Threading Is there a way to make BaseHTTPServer.HTTPServer be multi-threaded like SocketServer.ThreadingTCPServer? A: You can simply use the threading mixin using both of those classes to make it multithread :) It won't help you much in performance though, but it'...
Python - BaseHTTPServer.HTTPServer Concurrency & Threading
Is there a way to make BaseHTTPServer.HTTPServer be multi-threaded like SocketServer.ThreadingTCPServer?
[ "You can simply use the threading mixin using both of those classes to make it multithread :)\nIt won't help you much in performance though, but it's atleast multithreaded.\nfrom SocketServer import ThreadingMixIn\nfrom BaseHTTPServer import HTTPServer\n\nclass MultiThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n...
[ 19 ]
[]
[]
[ "basehttpserver", "httpserver", "multithreading", "python", "socketserver" ]
stackoverflow_0002398144_basehttpserver_httpserver_multithreading_python_socketserver.txt
Q: pyqt signal problem I'm working on a plugin for Avogadro (chemistry software) that uses pyqt. I've some problem with connecting a method to the clicked signal of a button. I've my class: class Controller(object): def __init__(self): self.ui = MyDialog() # self.ui.run is a QPushButton self.ui.r...
pyqt signal problem
I'm working on a plugin for Avogadro (chemistry software) that uses pyqt. I've some problem with connecting a method to the clicked signal of a button. I've my class: class Controller(object): def __init__(self): self.ui = MyDialog() # self.ui.run is a QPushButton self.ui.run.clicked.connect(self.o...
[ "Unless they've considerably changed something recently, this doesn't seem like the way to connect signals in PyQt. I'm more used to:\nself.connect(self.ui.run, QtCore.SIGNAL(\"clicked()\"),\n self, QtCore.SLOT(\"on_run_click()\"))\n\n", "The problem is that Avogadro python wrappers don't support the ...
[ 1, 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002392793_pyqt4_python.txt
Q: Rebuilding website from Django 0.96 to Django 1.2 I've got a website done in Django 0.96 (done in 2007), and now we are thinking about rebuilding it (not just migrating) for Django 1.2 . Can anyone point me to the new (and worth the while) widgets, plugins and other stuff for Django 1.2 (released in april 2010). ...
Rebuilding website from Django 0.96 to Django 1.2
I've got a website done in Django 0.96 (done in 2007), and now we are thinking about rebuilding it (not just migrating) for Django 1.2 . Can anyone point me to the new (and worth the while) widgets, plugins and other stuff for Django 1.2 (released in april 2010). I've heard of "South" and of a widget for debugging (ca...
[ "The Django API is amazingly stable so you may not have to rewrite it at all (unless you really want to).\nI have a site I did in 2007 using 0.97-pre -- at least I think that's what they called it, it was trunk 6688. Anyway, I have ported the site twice, once to 1.0 and then to 1.1.1. The only \"major\" thing we ha...
[ 5, 2, 0 ]
[]
[]
[ "django", "python", "web" ]
stackoverflow_0002398299_django_python_web.txt
Q: excluding fields from json serialization in python using jsonpickle I am using jsonpickle to serialize an object to json. The object has certain fields that point to other objects. I'd like to selectively not include those in the serialization, so that the resulting json file is essentially pure human-readable tex...
excluding fields from json serialization in python using jsonpickle
I am using jsonpickle to serialize an object to json. The object has certain fields that point to other objects. I'd like to selectively not include those in the serialization, so that the resulting json file is essentially pure human-readable text without any funny representations of objects. Is there a way to make js...
[ "I think what you might be looking for is the unpicklable argument (see this doc for details). In short, if this argument is set to False, jsonpickle will not output custom python classes to JSON. It should only output JSON native types e.g strings, ints, bools and lists.\n" ]
[ 2 ]
[]
[]
[ "json", "jsonpickle", "python", "serialization" ]
stackoverflow_0002397757_json_jsonpickle_python_serialization.txt
Q: How to encode HTML non-ASCII data to UTF-8 in Python I tried to do that, and I found this errors: >>> import re >>> x = 'Ingl\xeas' >>> x 'Ingl\xeas' >>> print x Ingl�s >>> x.decode('utf8') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/e...
How to encode HTML non-ASCII data to UTF-8 in Python
I tried to do that, and I found this errors: >>> import re >>> x = 'Ingl\xeas' >>> x 'Ingl\xeas' >>> print x Ingl�s >>> x.decode('utf8') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode return co...
[ "You need to know how the input data is encoded before you decode it. In some of you're attempts, you're trying to decode it from UTF-8, but Python throws an exception because the input isn't valid UTF-8. It looks like it might be latin-1. This works for me:\n>>> x = 'Ingl\\xeas'\n>>> print x.decode('latin1')\nI...
[ 7, 0, 0 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0002396925_python_unicode_utf_8.txt
Q: Python: Can subclasses overload inherited methods? I'm making a shopping cart app in Google App Engine. I have many classes that derive from a base handler: class BaseHandler(webapp.RequestHandler): def get(self, CSIN=None): self.body(CSIN) Does this mean that the body() method of every descendant cla...
Python: Can subclasses overload inherited methods?
I'm making a shopping cart app in Google App Engine. I have many classes that derive from a base handler: class BaseHandler(webapp.RequestHandler): def get(self, CSIN=None): self.body(CSIN) Does this mean that the body() method of every descendant class needs to have the same argument? This is cumbersome. ...
[ "Overridden methods don't have to have the same parameters as each other in principle, but they do have to have the same formal parameters they're called with. So since any handler can have body called on it by get, yes they have to be the same. For that matter, kind of the point of overriding is that the caller do...
[ 7, 5 ]
[]
[]
[ "google_app_engine", "oop", "overloading", "python", "refactoring" ]
stackoverflow_0002398666_google_app_engine_oop_overloading_python_refactoring.txt
Q: Saving Python Complex Data Types to Amazon S3 Can Python class data be saved to S3 without marshalling? I am trying to cut down of I/O operations until necessary. A: Amazon S3 stores plain data files. Even if there's a library that makes it look like objects are being saved, it's going to do marshalling in the b...
Saving Python Complex Data Types to Amazon S3
Can Python class data be saved to S3 without marshalling? I am trying to cut down of I/O operations until necessary.
[ "Amazon S3 stores plain data files. Even if there's a library that makes it look like objects are being saved, it's going to do marshalling in the background. Might as well just pickle your objects by yourself.\n" ]
[ 1 ]
[]
[]
[ "amazon", "amazon_s3", "boto", "python" ]
stackoverflow_0002398735_amazon_amazon_s3_boto_python.txt
Q: Python 3.1.1 Class Question I'm a new Python programmer who is having a little trouble using 'self' in classes. For example: class data: def __init__(self): self.table = [] def add(self, file): self.table.append(file) data.add('yes') In this function I want to have table be a variable stor...
Python 3.1.1 Class Question
I'm a new Python programmer who is having a little trouble using 'self' in classes. For example: class data: def __init__(self): self.table = [] def add(self, file): self.table.append(file) data.add('yes') In this function I want to have table be a variable stored in the class data and use add ...
[ "You first need to make an instance of the class:\nmydata = data()\n\nthen you can call the method -- on the instance, of course, not on the class:\nmydata.add('yes')\n\n", "You need to instantiate the class before you can call methods on it:\nmydata = Data()\nmydata.add('yes')\n\n", "you are calling the add me...
[ 7, 1, 1, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002398782_class_python.txt
Q: Why is my implementation of the Sieve of Atkin overlooking numbers close to the specified limit? My implementation of Sieve of Atkin either overlooks primes near the limit or composites near the limit. while some limits work and others don't. I'm am completely confused as to what is wrong. def AtkinSieve (limit): ...
Why is my implementation of the Sieve of Atkin overlooking numbers close to the specified limit?
My implementation of Sieve of Atkin either overlooks primes near the limit or composites near the limit. while some limits work and others don't. I'm am completely confused as to what is wrong. def AtkinSieve (limit): results = [2,3,5] sieve = [False]*limit factor = int(math.sqrt(lim)) for i in range(1,factor): for...
[ "\n Change lim to limit. Of course you must have known that.\n\nSince sieve = [False]*limit,\nthe largest index allowed is limit-1.\nHowever, on this line\nif (n <= limit) and (n % 12 == 1 or n % 12 == 5):\n\nyou are checking if n<=limit. If n==limit then sieve[n] raises an IndexError.\nTry your algorithm with a sm...
[ 6 ]
[]
[]
[ "math", "primes", "python", "sieve_of_atkin" ]
stackoverflow_0002398894_math_primes_python_sieve_of_atkin.txt
Q: How to use py2exe icon_resources in wxPython application? I have a wxPython application I'm bundling into an exe using py2exe. I've defined an icon in the setup.py file using the following: setup( windows=[ { 'script': 'myapp.py', 'icon_resources': [(1, 'myicon.ico')] }...
How to use py2exe icon_resources in wxPython application?
I have a wxPython application I'm bundling into an exe using py2exe. I've defined an icon in the setup.py file using the following: setup( windows=[ { 'script': 'myapp.py', 'icon_resources': [(1, 'myicon.ico')] }, ], ) This works, but I'd like to be able to access that ...
[ "I do this inside the Frame subclass\nif os.path.exists(\"myWxApplication.exe\"):\n self.SetIcon(wx.Icon(\"myWxApplication.exe\",wx.BITMAP_TYPE_ICO))\n\n" ]
[ 4 ]
[]
[]
[ "bundle", "icons", "py2exe", "python", "wxpython" ]
stackoverflow_0002399424_bundle_icons_py2exe_python_wxpython.txt
Q: Python learner needs help spotting an error This piece of code gives a syntax error at the colon of "elif process.loop(i, len(list_i) != 'repeat':" and I can't seem to figure out why. class process: def loop(v1, v2): if v1 < v2 - 1: return 'repeat' def isel(chr_i, list_i): for i...
Python learner needs help spotting an error
This piece of code gives a syntax error at the colon of "elif process.loop(i, len(list_i) != 'repeat':" and I can't seem to figure out why. class process: def loop(v1, v2): if v1 < v2 - 1: return 'repeat' def isel(chr_i, list_i): for i in range(len(list_i)): if chr_i == l...
[ "elif process.loop(i, len(list_i) != 'repeat':\n\nyou forgot a closed-paren, ), just before the !=; so the would-be left-hand side of the comparison opens two parentheses but closes only one -- that's the syntax error: \"unbalanced parentheses\", if you will.\n", "You're missing a parentheses!\nChange\n\nelif pro...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002399438_python.txt
Q: Hexadecimals in python I don't know python and I'm porting a library to C#, I've encountered the following lines of code that is used in some I/O operation but I'm not sure what it is, my guess is that it's a hexadecimal but I don't know why it's inside a string, neither what the backslashes do? sep1 = '\x04H\...
Hexadecimals in python
I don't know python and I'm porting a library to C#, I've encountered the following lines of code that is used in some I/O operation but I'm not sure what it is, my guess is that it's a hexadecimal but I don't know why it's inside a string, neither what the backslashes do? sep1 = '\x04H\xfe\x13' # record separator ...
[ "They're escape sequences. In Python, \\xNN within a (non-raw) string is treated as the character 0xNN.\n", "The backslashes are escape characters. They allow you to insert special characters (IE a quotation mark) inside a string. \\xNN is hexadecimal, like you say.\nIt looks like they're using a string in place ...
[ 5, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002398468_python.txt
Q: Is there a static analysis tool for Python, Ruby, Sql, Cobol, Perl, and PL/SQL? I am looking for a static analysis tool for Python, Ruby, Sql, Cobol, Perl, PL/SQL, SQL similar to find bugs and check style. I am looking for calculating the line count, identify bugs during the development, and enforcing coding stand...
Is there a static analysis tool for Python, Ruby, Sql, Cobol, Perl, and PL/SQL?
I am looking for a static analysis tool for Python, Ruby, Sql, Cobol, Perl, PL/SQL, SQL similar to find bugs and check style. I am looking for calculating the line count, identify bugs during the development, and enforcing coding standard.
[ "Perl has Perl::Critic (and perlcritic.com)\n", "I use PyChecker and pylint as Python code checkers. However it seems that they get buggy when you use some modules (e.g., socket or pygame, IIRC).\n", "For Ruby, you're probably best served looking at this previous SO question:\nhttps://stackoverflow.com/question...
[ 10, 4, 2, 0, 0, 0 ]
[]
[]
[ "cobol", "plsql", "python", "ruby", "static_analysis" ]
stackoverflow_0000956104_cobol_plsql_python_ruby_static_analysis.txt
Q: Kiosk mode in wxpython? Is there a way to create a 'kiosk mode' in wxpython under Windows (98 - 7) where the application disables you from breaking out of the app using Windows keys, alt-tab, alt-f4, and ctrl+alt+delete? A: If an application could do that it would make a great denial-of-service attack on the ma...
Kiosk mode in wxpython?
Is there a way to create a 'kiosk mode' in wxpython under Windows (98 - 7) where the application disables you from breaking out of the app using Windows keys, alt-tab, alt-f4, and ctrl+alt+delete?
[ "If an application could do that it would make a great denial-of-service attack on the machine.\nIn particular Ctrl+Alt+Delete is the Secure Attention Sequence. Microsoft goes to great lengths to insure that when the user hits those keys, they switch to a secure desktop that they can be confident that the logon bo...
[ 2, 0 ]
[]
[]
[ "kiosk", "mode", "python", "wxpython" ]
stackoverflow_0002399812_kiosk_mode_python_wxpython.txt
Q: In python, what does len(list) do? Does len(list) calculate the length of the list every time it is called, or does it return the value of the built-in counter?I have a context where I need to check the length of a list every time through a loop, like: listData = [] for value in ioread(): if len(listData)>=25:...
In python, what does len(list) do?
Does len(list) calculate the length of the list every time it is called, or does it return the value of the built-in counter?I have a context where I need to check the length of a list every time through a loop, like: listData = [] for value in ioread(): if len(listData)>=25: processlistdata() clear...
[ "You should probably be aware, if you're worried about this operation's performance, that \"lists\" in Python are really dynamic arrays. That is, they're not implemented as linked lists, which you generally have to \"walk\" to compute a length for (unless stored in a header).\nSince they already need to store \"boo...
[ 18, 2, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002399835_list_python.txt
Q: __rlshift__, __ror__ in Python I noticed that this recipe seems to use __rlshift__, __ror__ like operators. But, they aren't in the documentation! Can anyone explain these and perhaps point to some docs? A: See the documentation for: object.__rlshift__() object.__ror__() __rlshift__ is the swapped operands ver...
__rlshift__, __ror__ in Python
I noticed that this recipe seems to use __rlshift__, __ror__ like operators. But, they aren't in the documentation! Can anyone explain these and perhaps point to some docs?
[ "See the documentation for:\n\nobject.__rlshift__()\nobject.__ror__()\n\n__rlshift__ is the swapped operands version of __lshift__, used when the right-hand operand supports the operation but the left-hand operand doesn't.\n" ]
[ 10 ]
[]
[]
[ "operators", "python" ]
stackoverflow_0002400171_operators_python.txt
Q: Python 3.1.1 Problem With Tuples This piece of code is supposed to go through a list and preform some formatting to the items, such as removing quotations, and then saving it to another list. class process: def rchr(string_i, asciivalue): string_o = () for i in range(len(string_i)): ...
Python 3.1.1 Problem With Tuples
This piece of code is supposed to go through a list and preform some formatting to the items, such as removing quotations, and then saving it to another list. class process: def rchr(string_i, asciivalue): string_o = () for i in range(len(string_i)): if ord(string_i[i]) != asciivalue: ...
[ "I think you want string_o = \"\" instead of string_o = ()\nYour problem is that you want string_o to be a string so you can append other strings onto it. Setting it equal to () makes it a tuple instead, which is a data type incompatible with string.\n", "In addition to the previous answer, a more pythonic way to...
[ 2, 2, 1 ]
[]
[]
[ "class", "python", "tuples" ]
stackoverflow_0002400188_class_python_tuples.txt
Q: Is closing file descriptor and removing inotify watch really necessary? With python inotifyx, do I have to remove watch and close opened system file descriptor if I need them until program exit? E.g. is there some possible problems if I create one (file descriptor + watch) with each run and don't close it? A: It...
Is closing file descriptor and removing inotify watch really necessary?
With python inotifyx, do I have to remove watch and close opened system file descriptor if I need them until program exit? E.g. is there some possible problems if I create one (file descriptor + watch) with each run and don't close it?
[ "It's always a good idea to release resources (e.g. free memory, close file descriptors, waitpid(2) on child processes, etc) whenever you're done using them. Being lazy and letting the operating system take care of it for you when you exit is a sure way to cause bugs in the future.\n", "The kernel stores watches...
[ 1, 0 ]
[]
[]
[ "inotify", "linux", "python" ]
stackoverflow_0002400276_inotify_linux_python.txt
Q: Implementing __concat__ in Python I tried to implement __concat__, but it didn't work >>> class lHolder(): ... def __init__(self,l): ... self.l=l ... def __concat__(self, l2): ... return self.l+l2 ... def __iter__(self): ... return self.l.__iter__() ... >>> lHolder(...
Implementing __concat__ in Python
I tried to implement __concat__, but it didn't work >>> class lHolder(): ... def __init__(self,l): ... self.l=l ... def __concat__(self, l2): ... return self.l+l2 ... def __iter__(self): ... return self.l.__iter__() ... >>> lHolder([1])+[2] Traceback (most recent call la...
[ "__concat__ is not a special method (http://docs.python.org/glossary.html#term-special-method). It is part of the operator module.\nYou will need to implement __add__ to get the behaviour you want.\n", "You want to implement __add__, not __concat__. There's no __concat__ special method in Python.\n" ]
[ 5, 2 ]
[]
[]
[ "operator_overloading", "python", "sequences" ]
stackoverflow_0002400561_operator_overloading_python_sequences.txt
Q: How can I interact with rather long python scripts? I love the IDLE. However, sometimes I have 100-200 line scripts and I want to sort of interactively debug/play with say, functions defined in foo.py instead of just calling python foo.py. Is there a way I can trigger IDLE in the context of my foo.py? A: Insert ...
How can I interact with rather long python scripts?
I love the IDLE. However, sometimes I have 100-200 line scripts and I want to sort of interactively debug/play with say, functions defined in foo.py instead of just calling python foo.py. Is there a way I can trigger IDLE in the context of my foo.py?
[ "Insert this line into the script:\nimport pdb; pdb.set_trace()\n\nWhich will start the python debugger which lets you step through the script interactively, checking variables and such as you go. \n", "I assume you are asking about how to enable debugging in Idle?\nIn the Python Shell window, choose Debugger fro...
[ 5, 1 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0002400619_python_python_idle.txt
Q: Python urllib proxy I'm trying to fetch some urls via urllib and mechanize through my proxy. With mechanize I try the following: from mechanize import Browser import re br = Browser() br.set_proxies({"http": "MYUSERNAME:*******@itmalsproxy.italy.local:8080"}) br.open("http://www.example.com/") I get the followin...
Python urllib proxy
I'm trying to fetch some urls via urllib and mechanize through my proxy. With mechanize I try the following: from mechanize import Browser import re br = Browser() br.set_proxies({"http": "MYUSERNAME:*******@itmalsproxy.italy.local:8080"}) br.open("http://www.example.com/") I get the following error: httperror_seek_w...
[ "Maybe the proxy is using NTLM authentication?\nIf that is the case, you can try using the NTLM Authorization Proxy Server (see also this answer).\n", "you might get more info from the response headers\nprint br.response().info()\n", "When your web browser uses proxy server to surf the Web from within your loca...
[ 0, 0, 0 ]
[]
[]
[ "mechanize", "proxy", "python" ]
stackoverflow_0001899901_mechanize_proxy_python.txt
Q: How do I execute SQL_CALC_FOUND_ROWS in python MySQLDB cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5") rows = cursor.fetchall() ... total_rows = cursor.execute("SELECT FOUND_ROWS()") #this doesn't work for some reason. Edit: I tried SELECT FOUND_ROWS() FROM my_table...and the numbers are funky...
How do I execute SQL_CALC_FOUND_ROWS in python MySQLDB
cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5") rows = cursor.fetchall() ... total_rows = cursor.execute("SELECT FOUND_ROWS()") #this doesn't work for some reason. Edit: I tried SELECT FOUND_ROWS() FROM my_table...and the numbers are funky.
[ "Seems to work here by fetching the result for the second cursor:\ncursor.execute(\"SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5\")\nrows = cursor.fetchall()\n\ncursor.execute(\"SELECT FOUND_ROWS()\")\n(total_rows,) = cursor.fetchone()\n\n" ]
[ 1 ]
[]
[]
[ "database", "mysql", "python", "select" ]
stackoverflow_0002400492_database_mysql_python_select.txt
Q: Comprehensive guide to Operator Overloading in Python Is there a comprehensive guide to operator overloading anywhere? Preferably online, but a book would be fine too. The description of the operator module leaves a lot out, such as including operators that can't be overloaded and missing the r operators or provid...
Comprehensive guide to Operator Overloading in Python
Is there a comprehensive guide to operator overloading anywhere? Preferably online, but a book would be fine too. The description of the operator module leaves a lot out, such as including operators that can't be overloaded and missing the r operators or providing sensible defaults. (Writing these operators is good pra...
[ "Python's operator overloading is done by redefining certain special methods in any class.\nThis is explained in the Python language reference.\nFor example, to overload the addition operator:\n>>> class MyClass(object):\n... def __add__(self, x):\n... return '%s plus %s' % (self, x)\n... \n>>> obj = My...
[ 50, 24 ]
[]
[]
[ "python" ]
stackoverflow_0002400635_python.txt
Q: Adding a generic image field onto a ModelForm in django I have two models, Room and Image. Image is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, ...
Adding a generic image field onto a ModelForm in django
I have two models, Room and Image. Image is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY. Was hoping someo...
[ "Why don't you just use ImageField? I don't see the need for the Image class.\n# model\nclass Room(models.Model):\n name = models.CharField(max_length=50)\n image = models.ImageField(upload_to=\"uploads/images/\")\n\n# form\nfrom django import forms\n\nclass UploadFileForm(forms.Form):\n name = forms.CharF...
[ 4, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000467985_django_django_forms_python.txt
Q: Netbeans not allowing Python 2.6 as default platform (forcing Jython2.5) I am trying to get Netbeans python to run with the default python platform set to Python 2.6.1 (my system python), so in Netbeans I do the following: Tools -> Python Platform Set Python 2.6.1 to 'default' However, it seems impossible to make ...
Netbeans not allowing Python 2.6 as default platform (forcing Jython2.5)
I am trying to get Netbeans python to run with the default python platform set to Python 2.6.1 (my system python), so in Netbeans I do the following: Tools -> Python Platform Set Python 2.6.1 to 'default' However, it seems impossible to make this stick. Whenever I restart Netbeans it's back to Jython 2.5 again. Moreove...
[ "Looks like http://netbeans.org/bugzilla/show_bug.cgi?id=180693 which provides a clumsy and non persistent workaround. \nThis needs heavy complaining on the netbean bug tracker imo. \n", "Might be worth logging a bug with Netbeans about the first bit of behaviour you described - I can confirm similar (although st...
[ 1, 0 ]
[]
[]
[ "jython", "netbeans", "python" ]
stackoverflow_0002200685_jython_netbeans_python.txt