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: Inheritance in Python We just started learning about class inheritance and attribute lookup in python. I have a question about the following code: class a : n = 1 class b : n = 2 class c : n = 3 class d (a,b) : pass class e (d,c) : pass I know that e.n would equal 1 due to the nature of attribute lookup procedure...
Inheritance in Python
We just started learning about class inheritance and attribute lookup in python. I have a question about the following code: class a : n = 1 class b : n = 2 class c : n = 3 class d (a,b) : pass class e (d,c) : pass I know that e.n would equal 1 due to the nature of attribute lookup procedure (depth first search). Howe...
[ "You can't get there from here. Class attributes are replaced. Use the class reference directly (c.n).\n", ">>> e.__bases__[1].n\n3\n\n" ]
[ 1, 1 ]
[]
[]
[ "attributes", "inheritance", "python" ]
stackoverflow_0002278955_attributes_inheritance_python.txt
Q: Python UUID represented as special characters When creating a UUID in Python, likeso: >>> uuid.uuid1() UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') How could one map that UUID into a string made up of the capitalized alphabet A-Z minus the characters D, F, I, O, Q, and U, plus the numerical digits, plus the chara...
Python UUID represented as special characters
When creating a UUID in Python, likeso: >>> uuid.uuid1() UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') How could one map that UUID into a string made up of the capitalized alphabet A-Z minus the characters D, F, I, O, Q, and U, plus the numerical digits, plus the characters "+" and "=". i.e. the from an integer or stri...
[ "How important is it to you to \"squeeze\" the representation by 18.75%, i.e., from 32 to 26 characters? Because, if saving this small percentage of bytes isn't absolutely crucial, something like uid.hex.upper().replace('D','Z') will do what you ask (not using the whole alphabet you make available, but the only c...
[ 2, 1, 1 ]
[]
[]
[ "algorithm", "isomorphism", "python", "transpose", "uuid" ]
stackoverflow_0002278239_algorithm_isomorphism_python_transpose_uuid.txt
Q: Error in downloading and saving image using python I written a code for downloading and saving images from a site .It worked nicely,but for some urls it is being showing an error.I have paste code below import urllib2 import webbrowser imageurl='http://www.example.com/'+image[s] opener1 = urllib2.build_opener() p...
Error in downloading and saving image using python
I written a code for downloading and saving images from a site .It worked nicely,but for some urls it is being showing an error.I have paste code below import urllib2 import webbrowser imageurl='http://www.example.com/'+image[s] opener1 = urllib2.build_opener() page1=opener1.open(imageurl) my_picture=page1.read() imag...
[ "You should fix the link. Try this:\n>>> import urllib\n>>> urllib.quote(\"images/PG013001 GROUP 2.jpg\")\n'images/PG013001%20GROUP%202.jpg'\n\n", "Urls can't include spaces directly; it's simply not allowed. What you want to do is to quote, or encode the spaces in the filename, so that the url becomes legal. ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002278982_python.txt
Q: Python function composition I've tried to implement function composition with nice syntax and here is what I've got: from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) return _compfunc(f) def __rshift...
Python function composition
I've tried to implement function composition with nice syntax and here is what I've got: from functools import partial class _compfunc(partial): def __lshift__(self, y): f = lambda *args, **kwargs: self.func(y(*args, **kwargs)) return _compfunc(f) def __rshift__(self, y): f = lambda *...
[ "append does in-place addition, as Ignacio Vazquez-Abrams said (well, implied) -- so, while you could fix that by just adding a return to your function, it would have the side-effect of changing the argument it was passed, too:\n@composable\ndef f4(a):\n a.append(0)\n return a\n\nIt would be best to use the f...
[ 9 ]
[]
[]
[ "function_composition", "python" ]
stackoverflow_0002279423_function_composition_python.txt
Q: Multiple consumers & producers connected to a message queue, Is that possible in AMQP? I'd like to create a farm of processes that are able to OCR text. I've thought about using a single queue of messages which is read by multiple OCR processes. I would like to ensure that: each message in queue is eventually pro...
Multiple consumers & producers connected to a message queue, Is that possible in AMQP?
I'd like to create a farm of processes that are able to OCR text. I've thought about using a single queue of messages which is read by multiple OCR processes. I would like to ensure that: each message in queue is eventually processed the work is more or less equally distributed an image will be parsed only by one OCR ...
[ "Yes, as @nailxx points out. The AMQP programming model is slightly different from JMS in that you only have queues, which can be shared between workers, or used privately by a single worker. You can also easily set up RabbitMQ to do PubSub use cases or what in JMS are called topics. Please go to our Getting Start...
[ 5, 3 ]
[]
[]
[ "amqp", "message_queue", "py_amqplib", "python", "rabbitmq" ]
stackoverflow_0002161206_amqp_message_queue_py_amqplib_python_rabbitmq.txt
Q: PyScripter Rpyc maybe somebody could give me a couple guidelines how to install Rpyc to PyScripter. I use PyScripter 1.9.9.7 with Python 2.6. I have tried to google it and found some instructions, but still have not succeeded... Thanks! A: Grab the file rpyc-2.60-py24.zip from here: http://code.google.com/p/pysc...
PyScripter Rpyc
maybe somebody could give me a couple guidelines how to install Rpyc to PyScripter. I use PyScripter 1.9.9.7 with Python 2.6. I have tried to google it and found some instructions, but still have not succeeded... Thanks!
[ "Grab the file rpyc-2.60-py24.zip from here:\nhttp://code.google.com/p/pyscripter/downloads/list\nUnder your python2.6 install directory go to the following subdirectory\n\\Lib\\site-packages\\\ncheck if you already have an rpyc subdirectory,\n\\Lib\\site-packages\\Rpyc\\\nif you do, delete it or delete its content...
[ 4 ]
[]
[]
[ "pyscripter", "python", "rpyc" ]
stackoverflow_0002276323_pyscripter_python_rpyc.txt
Q: Question regarding UDP communication in twisted framework I would like to find out if Twisted imposes restriction on maximum size of UDP packets. The allowable limit on linux platforms is upto 64k (although I intend to send packets of about 10k bytes consisting of JPEG images) but I am not able to send more than a...
Question regarding UDP communication in twisted framework
I would like to find out if Twisted imposes restriction on maximum size of UDP packets. The allowable limit on linux platforms is upto 64k (although I intend to send packets of about 10k bytes consisting of JPEG images) but I am not able to send more than approx. 2500 bytes
[ "It's very unlikely that Twisted is imposing any limit but there's no reason some other part of the network wouldn't drop the packets if they're too large. It's very rare for people to send UDP packets of such a large size for precisely that sort of reason. Most game applications for example try to keep them below ...
[ 1 ]
[ "Are you sure that it is not a receive problem?\nThere is no indication that your packets won't be fragmented en route to the destination\n" ]
[ -1 ]
[ "python", "twisted", "udp" ]
stackoverflow_0002278665_python_twisted_udp.txt
Q: Unit testing functions that access files I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions: def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): ...
Unit testing functions that access files
I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions: def pass_file_name(self): self.log_files= [] file_name = self.path+"\\access_"+self.appliacation+".log" if os.path.isfile(file_name): self.log_files.append(file_name) fo...
[ "You have two units here:\n\nOne that generate file paths\nSecond that reads them\n\nThus there should be two unit-test-cases (i.e. classes with tests). First would test only file paths generation. Second would test reading from predefined set of files you prepared in special subdirectory of tests directory, it sho...
[ 8, 3, 2, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002279835_python_unit_testing.txt
Q: Formatting data from a python array I'm learning python for the first time. I have an aim which is to take data from an API and output it as xml. The output is stored in an array ("projectData"), here is an example of the output: [{'code': 'demo', 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19, tzinfo=<ap...
Formatting data from a python array
I'm learning python for the first time. I have an aim which is to take data from an API and output it as xml. The output is stored in an array ("projectData"), here is an example of the output: [{'code': 'demo', 'created_at': datetime.datetime(2008, 6, 11, 7, 35, 19, tzinfo=<api.LocalTimezone object at 0x10072ab10>), ...
[ "Consider using something like genshi or etree instead of building the XML by hand.\n", "Here's an example using lxml.etree, incomplete.. and probably a bit naive. Really you should define a schema and make sure your output is consistent with it.\nEdit, said it was incomplete, added None type and assumed a create...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002280190_python.txt
Q: Pearson Similarity Score, how can I optimise this further? I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise. Even the slightest ...
Pearson Similarity Score, how can I optimise this further?
I have an implemented of Pearson's Similarity score for comparing two dictionaries of values. More time is spent in this method than anywhere else (potentially many millions of calls), so this is clearly the critical method to optimise. Even the slightest optimisation could have a big impact on my code, so I'm keen to ...
[ "The real speed increase would be gained by moving to numpy or scipy. Short of that, there are microoptimizations: e.g. x*x is faster than pow(x,2); you could extract the values at the same time as the keys by doing, instead of:\nsi = [val for val in v1 if val in v2]\n\nsomething like\nvs = [ (v1[val],v2[val]) for ...
[ 4, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "optimization", "pearson", "python", "similarity" ]
stackoverflow_0001307016_optimization_pearson_python_similarity.txt
Q: Emacs defadvice on python-mode function In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing...
Emacs defadvice on python-mode function
In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising functio...
[ "In this case the solution appears to be\n(custom-set-variables\n '(py-shell-switch-buffers-on-execute nil))\n\n", "Use around-advice to wrap the function in a call to\nsave-window-excursion, which will restore the previous window\nconfiguration after the command completes.\n(defadvice py-execute-region\n (arou...
[ 9, 2, 1, 1 ]
[]
[]
[ "advising_functions", "defadvice", "elisp", "emacs", "python" ]
stackoverflow_0001416882_advising_functions_defadvice_elisp_emacs_python.txt
Q: Discovering referers to SQLAlchemy object I have a lot of model classes with ralations between them with a CRUD interface to edit. The problem is that some objects can't be deleted since there are other objects refering to them. Sometimes I can setup ON DELETE rule to handle this case, but in most cases I don't wa...
Discovering referers to SQLAlchemy object
I have a lot of model classes with ralations between them with a CRUD interface to edit. The problem is that some objects can't be deleted since there are other objects refering to them. Sometimes I can setup ON DELETE rule to handle this case, but in most cases I don't want automatic deletion of related objects till t...
[ "SQL: I have to absolutely disagree with S.Lott' answer.\nI am not aware of out-of-the-box solution, but it is definitely possible to discover all the tables that have ForeignKey constraints to a given table. One needs to use properly the INFORMATION_SCHEMA views such as REFERENTIAL_CONSTRAINTS, KEY_COLUMN_USAGE, T...
[ 6, 1, 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0002279919_orm_python_sqlalchemy.txt
Q: How to run server script indefinitely I would like to run an asynchronous program on a remote linux server indefinitely. This script doesn't output anything to the server itself(other than occasionally writing information to a mysql database). So far the only option I have been able to find is the nohup command: n...
How to run server script indefinitely
I would like to run an asynchronous program on a remote linux server indefinitely. This script doesn't output anything to the server itself(other than occasionally writing information to a mysql database). So far the only option I have been able to find is the nohup command: nohup script_name & From what I understand,...
[ "What you are basically asking is \"How do I create a daemon process?\" What you want to do is \"daemonize\", there are many examples of this floating around on the web. The process is basically that you fork(), the child creates a new session, the parent exits, the child duplicates and then closes open file hand...
[ 3, 2, 1, 0 ]
[]
[]
[ "linux", "nohup", "python" ]
stackoverflow_0001927144_linux_nohup_python.txt
Q: Python imports with different directory structures I'm working on a project where all the code in the source tree is separated into module directories, e.g.: modules/check/lib/check.py modules/edit/lib/edit.py During installation, the Python files are put in the same directory program_name under Python's site-pac...
Python imports with different directory structures
I'm working on a project where all the code in the source tree is separated into module directories, e.g.: modules/check/lib/check.py modules/edit/lib/edit.py During installation, the Python files are put in the same directory program_name under Python's site-packages. All the modules therefore use the syntax import p...
[ "You can just add the /modules/ directories to your PYTHONPATH in your dev environment. Once installed in site-packages, calling import edit inside check.py will import the correct module since they are in the same directory. Calling import edit from your dev environ will import the one you added to your PYTHONPAT...
[ 2, 0 ]
[]
[]
[ "directory_structure", "import", "python" ]
stackoverflow_0002280761_directory_structure_import_python.txt
Q: Using SQLite3 in Python I am trying to store some parsed feed contents values in Sqlite database table in python.But facing error.Could anybody help me out of this issue.Infact it is so trivial question to ask!I am newbie!..Anyway thanks in advance! from sqlite3 import * import feedparser data = feedparser.parse...
Using SQLite3 in Python
I am trying to store some parsed feed contents values in Sqlite database table in python.But facing error.Could anybody help me out of this issue.Infact it is so trivial question to ask!I am newbie!..Anyway thanks in advance! from sqlite3 import * import feedparser data = feedparser.parse("some url") conn = connect(...
[ "Try\ncurs.execute(\"insert into location_tr values\\\n (NULL, '%s', '%s')\" % (data.entries[i].title, data.feed.updated))\n\n", "the error should be this line\n curs.execute(\"insert into location_tr values\\\n (NULL, data.entries[i].title,data.feed.updated)\")\n\ndata.entries[i].title comes f...
[ 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002280882_python_sqlite.txt
Q: Django ORM and Unicode data I'm using following model to store info about pages: class Page(models.Model): title = models.TextField(blank = False, null = False) New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query: page = Page.objects.filter(id = 1)...
Django ORM and Unicode data
I'm using following model to store info about pages: class Page(models.Model): title = models.TextField(blank = False, null = False) New data saves correctly, I'm saving Unicode data there (lots of non-ASCII titles). But when I'm performing query: page = Page.objects.filter(id = 1) page.title looks odd: u'\u042e\...
[ "You're doing nothing wrong. Have you tried printing it (or outputting it in a web page)?\nIn [1]: l = u'\\u042e\\u0449\\u0435\\u043d\\u043a\\u043e'\n\nIn [2]: print l\nЮщенко\n\n", "That's perfectly fine. It's \"Ющенко\" unicode-escaped.\n", "Might just be your shell not being able to display unicode character...
[ 3, 2, 1, 1, 1 ]
[]
[]
[ "django", "django_models", "orm", "python", "unicode" ]
stackoverflow_0002280855_django_django_models_orm_python_unicode.txt
Q: Python: Do (explicit) string parameters hurt performance? Suppose some function that always gets some parameter s that it does not use. def someFunc(s): # do something _not_ using s, for example a=1 now consider this call someFunc("the unused string") which gives a string as a parameter that is not built dur...
Python: Do (explicit) string parameters hurt performance?
Suppose some function that always gets some parameter s that it does not use. def someFunc(s): # do something _not_ using s, for example a=1 now consider this call someFunc("the unused string") which gives a string as a parameter that is not built during runtime but compiled straight into the binary (hope thats r...
[ "The string is passed (by reference) each time, but the overhead is way too tiny to really affect performance unless it's in a super-tight loop.\n", "this is an implementation detail of CPython, and may not apply to other pythons but yes, in many cases in a compiled module, a constant string will reference the sa...
[ 2, 1 ]
[]
[]
[ "compile_time", "function", "parameters", "performance", "python" ]
stackoverflow_0002281019_compile_time_function_parameters_performance_python.txt
Q: XMPPPY have function to manage invitation in client side? I'm coding by python about Gtalk I use XMPPPY. But I can chat with GTalk client but the problem is I can't accept invitation. Is XMPPY can do ? A: Looks like you want to "authorize" the request. I'm assuming you've received the request at the client. In ...
XMPPPY have function to manage invitation in client side?
I'm coding by python about Gtalk I use XMPPPY. But I can chat with GTalk client but the problem is I can't accept invitation. Is XMPPY can do ?
[ "Looks like you want to \"authorize\" the request. I'm assuming you've received the request at the client. In the roster class (xmpp.roster) there is an \"Authorize\" method. It sends the \"subscribed\" packet to accept the roster request. This is what the method looks like:\ndef Authorize(self,jid):\n \"\"\" A...
[ 0 ]
[]
[]
[ "chat", "google_talk", "python", "xmpp" ]
stackoverflow_0002266040_chat_google_talk_python_xmpp.txt
Q: Removing empty items from a list (Python) I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those? This is my current code: import re f = open('myfile.txt','r') for line in f.rea...
Removing empty items from a list (Python)
I'm reading a file in Python that isn't well formatted, values are separated by multiple spaces and some tabs too so the lists returned has a lot of empty items, how do I remove/avoid those? This is my current code: import re f = open('myfile.txt','r') for line in f.readlines(): if re.search(r'\bDeposit', line)...
[ "Don't explicitly specify ' ' as the delimiter. line.split() will split on all whitespace. It's equivalent to using re.split:\n>>> line = ' a b c \\n\\tg '\n>>> line.split()\n['a', 'b', 'c', 'g']\n>>> import re\n>>> re.split('\\s+', line)\n['', 'a', 'b', 'c', 'g', '']\n>>> re.split('\\s+', line.strip())\n['a', ...
[ 11, 2, 1, 0 ]
[]
[]
[ "list", "python", "regex", "split" ]
stackoverflow_0002281263_list_python_regex_split.txt
Q: Are there more ways to define a tuple with only one item? I know this is one way, by placing a comma: >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) Source: http://docs.python.org/tutorial/datastructures.html Are there more ways ...
Are there more ways to define a tuple with only one item?
I know this is one way, by placing a comma: >>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) Source: http://docs.python.org/tutorial/datastructures.html Are there more ways to define a tuple with only 1 item?
[ ">>> tuple(['hello'])\n('hello',)\n\nBut the built-in syntax is there for a reason.\n", "Even though you can define a tuple as 'hello', I think it would be easy for someone to possibly miss the trailing comma if they were reading your code. I definitely prefer \n('hello',) from a readability stand-point.\n", "...
[ 11, 5, 2, 2 ]
[]
[]
[ "python", "singleton", "tuples" ]
stackoverflow_0002281409_python_singleton_tuples.txt
Q: Trouble importing modules in Python IDEs Right I'm getting a bit tired of this so hopefully you can help me sort it out once and for all. I'm really confused about what's going on with Python on my MacBook. I'm running OS X 10.6.2 and have installed python from the website (the package that includes IDLE). This wo...
Trouble importing modules in Python IDEs
Right I'm getting a bit tired of this so hopefully you can help me sort it out once and for all. I'm really confused about what's going on with Python on my MacBook. I'm running OS X 10.6.2 and have installed python from the website (the package that includes IDLE). This works absolutely fine, and in fact IDLE will run...
[ "I deal with this by sticking to the macports Python installation. For compatibility reasons, I'm very wary of mixing modules for different python versions. \nUsing python_select, port installed modules and the macports version of easy_install should ensure that everything is found. In rare cases, you might have t...
[ 0 ]
[]
[]
[ "macos", "matplotlib", "python" ]
stackoverflow_0002282239_macos_matplotlib_python.txt
Q: Adding an entry to a python tuple I have a list of tuples representing x,y points. I also have a list of values for each of these points. How do I combine them into a list of lists (i.e one entry for each point [x,y,val]) or a list of tuples? Thanks A: You can't add entries to tuples, since tuples are immutable....
Adding an entry to a python tuple
I have a list of tuples representing x,y points. I also have a list of values for each of these points. How do I combine them into a list of lists (i.e one entry for each point [x,y,val]) or a list of tuples? Thanks
[ "You can't add entries to tuples, since tuples are immutable. But you can create a new list of lists:\nnew = [[x, y, val] for (x, y), val in zip(points, vals)]\n\n", "Tuples are immutable, they can't be modified. Convert it to a list, then convert it back if you want to (list((a, b))).\n" ]
[ 10, 1 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0002282300_list_python_tuples.txt
Q: How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation? In python 2.5, I have the following code in a module called modtest.py: def print_method_module(method): def printer(self): print self.__module__ return method(self) retur...
How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation?
In python 2.5, I have the following code in a module called modtest.py: def print_method_module(method): def printer(self): print self.__module__ return method(self) return printer class ModTest(): @print_method_module def testmethod(self): pass if __name__ == "__main__": ...
[ "When you execute a python source file directly, the module name of that file is __main__, even if it is known by another name when you execute some other file and import it. \nYou probably want to do like you did in modtest2, and import the module containing the class definition instead of executing that file dire...
[ 18 ]
[ "I'm guessing you could use sys._getframe() hackery to get at what you want.\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0002282369_python.txt
Q: Suds + JIRA = SAXException I'm using Python 2.6 and suds 0.3.7 to interact with JIRA 4.0. When I connect to the JIRA server, I get information on all the issues just fine. However, when I want to update an issue, I get a SAXException from suds (presumably): WebFault: Server raised fault: org.xml.sax.SAXExcepti...
Suds + JIRA = SAXException
I'm using Python 2.6 and suds 0.3.7 to interact with JIRA 4.0. When I connect to the JIRA server, I get information on all the issues just fine. However, when I want to update an issue, I get a SAXException from suds (presumably): WebFault: Server raised fault: org.xml.sax.SAXException: Found character data inside ...
[ "How about increasing the verbosity to see what is being sent? Or use wireshark. You could also do the same with SOAPpy and compare exactly what is sent. Debugging soap errors is usually like this for me :-/ \n~Matt\n", "Actually, by just changing the library from suds to SOAPpy, everything started working with n...
[ 1, 1, 1 ]
[]
[]
[ "jira", "python", "soap", "suds" ]
stackoverflow_0001609666_jira_python_soap_suds.txt
Q: Why/When in Python does `x==y` call `y.__eq__(x)`? The Python docs clearly state that x==y calls x.__eq__(y). However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's __cmp__ or __eq__ methods are go...
Why/When in Python does `x==y` call `y.__eq__(x)`?
The Python docs clearly state that x==y calls x.__eq__(y). However it seems that under many circumstances, the opposite is true. Where is it documented when or why this happens, and how can I work out for sure whether my object's __cmp__ or __eq__ methods are going to get called. Edit: Just to clarify, I know that __...
[ "You're missing a key exception to the usual behaviour: when the right-hand operand is an instance of a subclass of the class of the left-hand operand, the special method for the right-hand operand is called first.\nSee the documentation at:\nhttp://docs.python.org/reference/datamodel.html#coercion-rules\nand in p...
[ 33, 6, 1, 1 ]
[]
[]
[ "comparison", "operator_overloading", "python" ]
stackoverflow_0002281222_comparison_operator_overloading_python.txt
Q: Python, trying to run a program from the command prompt I am trying to run a program from the command prompt in windows. I am having some issues. The code is below: commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'" os.system(commandStr...
Python, trying to run a program from the command prompt
I am trying to run a program from the command prompt in windows. I am having some issues. The code is below: commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'" os.system(commandString) time.sleep(10) So with the single quotes I get "The fil...
[ "\nWindows requires double quotes in this situation, and you used single quotes.\nUse the subprocess module rather than os.system, which is more robust and avoids calling the shell directly, making you not have to worry about confusing escaping issues.\nDont use + to put together long strings. Use string formatting...
[ 2, 1 ]
[]
[]
[ "command_line", "command_prompt", "os.system", "python", "windows" ]
stackoverflow_0002282544_command_line_command_prompt_os.system_python_windows.txt
Q: How to see if code is backwards compatible for Python? I have some code that I am trying to make it play nicely with ESRI's geoprocessor. However, ESRI's geoprocessor runs on Python 2.2, 2.3, 2.4, 2.5. We need to make our tools work on any version. So I've spent a lot of time working and coding workarounds for dif...
How to see if code is backwards compatible for Python?
I have some code that I am trying to make it play nicely with ESRI's geoprocessor. However, ESRI's geoprocessor runs on Python 2.2, 2.3, 2.4, 2.5. We need to make our tools work on any version. So I've spent a lot of time working and coding workarounds for different versions, such that the wrapper geoprocessor has iden...
[ "If you are actively developing a commercial product, and you -really- want to support all these versions properly, I would suggest:\n\nWriting an automated test suite that can be run and tests functionality for your entire library/application/whatever.\nSetting up a machine, or ideally virtual machine for each tes...
[ 11, 10 ]
[]
[]
[ "backwards_compatibility", "python" ]
stackoverflow_0002282882_backwards_compatibility_python.txt
Q: Is there a cleaner or more efficient to do this Python assignment? Here's the code I have now: lang = window.get_active_document().get_language() if lang != None: lang = lang.get_name() Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equal...
Is there a cleaner or more efficient to do this Python assignment?
Here's the code I have now: lang = window.get_active_document().get_language() if lang != None: lang = lang.get_name() Is there a better way to do that? I'm new to Pythonic and was wondering if there's a more Python way to say "something equals this if x is true, else it equals that." Thanks.
[ "You could do lang = lang and lang.get_name() instead of the 'if' statement.\nIf lang is None it will stay None. If not, it will be set to lang.get_name().\nI'm not sure if that syntax makes things much clearer, though.\nP.S. Instead of lang != None you should use not lang is None.\n", "Try\nlang = lang.get_name(...
[ 7, 2, 2, 1 ]
[]
[]
[ "python", "variable_assignment" ]
stackoverflow_0002282526_python_variable_assignment.txt
Q: Help for novice choosing between Java and Python for app with sql db I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highe...
Help for novice choosing between Java and Python for app with sql db
I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical user a...
[ "The largest issue I can think of is the need to install an interpreter.\nWith Java, a lot of people will already have that interpreter installed, although you won't necessarily know which version. It may be wise to include the installer for Java with the program.\nWith Python, you're going to have to install the ...
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002282360_java_python.txt
Q: Python trouble importing modules I am building a web app with this directory structure: app/ __init__.py config/ __init__.py db_config.py models/ __init__.py model.py datasources/ __init__.py database.py ... ... Every __init__.py ...
Python trouble importing modules
I am building a web app with this directory structure: app/ __init__.py config/ __init__.py db_config.py models/ __init__.py model.py datasources/ __init__.py database.py ... ... Every __init__.py file has __all__ = ['', '', ...] in ...
[ "import app.config.db_config is the best way (avoid non-absolute imports and never ever use import *), and for this to work the app directory should be in sys.path. If it is not, add the directory to you PYTHONPATH or move the project to somewhere this is the case.\n" ]
[ 2 ]
[]
[]
[ "filesystems", "module", "python" ]
stackoverflow_0002283394_filesystems_module_python.txt
Q: simple twisted server (twistd .tap)with a pexpect instance error I have been creating an async server socket that sends and recives xml using twisted. The application works great! but because my main objective was to embed it in an init.d script and make it run in the background i decided to transform it in a "twi...
simple twisted server (twistd .tap)with a pexpect instance error
I have been creating an async server socket that sends and recives xml using twisted. The application works great! but because my main objective was to embed it in an init.d script and make it run in the background i decided to transform it in a "twisted application" in order to run it using twistd # from twisted.inter...
[ "You're spawning a child process before daemonizing. After daemonizing that child is now a child of init, and not a child of your daemon.\nYou need to subclass from twisted.application.service import Service and spawn the child process in startService, which will be called after daemonizing.\nÁ La: Twisted network ...
[ 3 ]
[]
[]
[ "daemon", "pexpect", "python", "twisted" ]
stackoverflow_0002283408_daemon_pexpect_python_twisted.txt
Q: Setting the cursor position in PyGTK (for a Gedit plugin) I'm developing a Gedit plugin which is built on PyGTK. I'm trying to figure out how to programatically tell the cursor where to go. For example, I'd like to have the cursor automatically go to right before the first "|" (pipe) in the current line. Any ideas...
Setting the cursor position in PyGTK (for a Gedit plugin)
I'm developing a Gedit plugin which is built on PyGTK. I'm trying to figure out how to programatically tell the cursor where to go. For example, I'd like to have the cursor automatically go to right before the first "|" (pipe) in the current line. Any ideas or starting points? I've been using the Gedit API up until now...
[ "Looking at the gedit plugin API, it looks like gedit.Document is a subclass of GtkSourceBuffer which itself subclasses GtkTextBuffer, the last of which has the cursor manipulation API you want. In particular, get_insert() and place_cursor(where) give the basics of moving the cursor around. For other operations (e....
[ 2 ]
[]
[]
[ "gedit", "plugins", "pygtk", "python" ]
stackoverflow_0002283933_gedit_plugins_pygtk_python.txt
Q: OpenGl with Python I am currently in a course that is using OpenGL and I have been using C for all the programs so far. I have Python installed on Fedora as well as OpenGL, however the minute I call an OpenGL command in my Python code, I get a segmentation fault. I have no idea why this is. Just to avoid the "just...
OpenGl with Python
I am currently in a course that is using OpenGL and I have been using C for all the programs so far. I have Python installed on Fedora as well as OpenGL, however the minute I call an OpenGL command in my Python code, I get a segmentation fault. I have no idea why this is. Just to avoid the "just use C" comments, here i...
[ "You may also want to consider using Pyglet instead of PyOpenGL. It's a ctypes-wrapper around the native OpenGL libs on the local platform, along with windowing support (should handle most of the stuff you want to use GLUT for.) The pyglet-users list is pretty active and very helpful.\n", "Well, I don't know if t...
[ 16, 2, 1, 0, 0, 0 ]
[]
[]
[ "fedora", "opengl", "python" ]
stackoverflow_0000242059_fedora_opengl_python.txt
Q: Django extends/include - bug? I'm trying to use both extends and include tags in one template, just like: {% extends "layout.html" %} {% block content %} <div id="content"> <nav class="mainMenu"> {% include "list.html" %} </nav> </div> {% endblock %} Unfortunately what is displayed is only list.html wit...
Django extends/include - bug?
I'm trying to use both extends and include tags in one template, just like: {% extends "layout.html" %} {% block content %} <div id="content"> <nav class="mainMenu"> {% include "list.html" %} </nav> </div> {% endblock %} Unfortunately what is displayed is only list.html without contents from layout.html and ...
[ "You are most probably only rendering list.html in your view, check for that.\n" ]
[ 2 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0002284495_django_python_templates.txt
Q: How can I add consistent whitespace to existing HTML using Python? I just started working on a website that is full of pages with all their HTML on a single line, which is a real pain to read and work with. I'm looking for a tool (preferably a Python library) that will take HTML input and return the same HTML unc...
How can I add consistent whitespace to existing HTML using Python?
I just started working on a website that is full of pages with all their HTML on a single line, which is a real pain to read and work with. I'm looking for a tool (preferably a Python library) that will take HTML input and return the same HTML unchanged, except for adding linebreaks and appropriate indentation. (All ...
[ "Algorithm\n\nParse html into some representation\nSerialize the representation back to html\n\nExample html5lib parser with BeautifulSoup tree builder\n#!/usr/bin/env python\nfrom html5lib import HTMLParser, treebuilders\n\nparser = HTMLParser(tree=treebuilders.getTreeBuilder(\"beautifulsoup\"))\n\nc = \"\"\"<HTML...
[ 2, 2, 1 ]
[]
[]
[ "html", "html5lib", "python", "whitespace" ]
stackoverflow_0002279404_html_html5lib_python_whitespace.txt
Q: How to install html5lib-0.90 library for Python on Windows? I'm using Windows, and trying to install html5lib-0.90 library on python C:\>python C:\Users\Junior\Downloads\Python\html5lib-0.90\setup.py install Traceback (most recent call last): File "C:\Users\Junior\Downloads\Python\html5lib-0.90\setup.py", line 36...
How to install html5lib-0.90 library for Python on Windows?
I'm using Windows, and trying to install html5lib-0.90 library on python C:\>python C:\Users\Junior\Downloads\Python\html5lib-0.90\setup.py install Traceback (most recent call last): File "C:\Users\Junior\Downloads\Python\html5lib-0.90\setup.py", line 36, in <module> for name in os.listdir(os.path.join('src','html5lib...
[ "Try:\nC:\\>cd \\Users\\Junior\\Downloads\\Python\\html5lib-0.90\\\nC:\\Users\\Junior\\Downloads\\Python\\html5lib-0.90>python setup.py install\n\n" ]
[ 6 ]
[]
[]
[ "html5lib", "python" ]
stackoverflow_0002285086_html5lib_python.txt
Q: Room for improvement on my Python code? I'm working on a Gedit plugin using Python (and PyGTK) and I really havent' worked with Python much so I have no idea if I'm writing Pythonic code. All of my own code is contained in __init__.py. There are a few other files, but they're from an outside library that I'm hooki...
Room for improvement on my Python code?
I'm working on a Gedit plugin using Python (and PyGTK) and I really havent' worked with Python much so I have no idea if I'm writing Pythonic code. All of my own code is contained in __init__.py. There are a few other files, but they're from an outside library that I'm hooking into. My __init__.py is as follows: # # @f...
[ "I've never done a GEdit plugin, so i can't comment on the __init__.py issue, but general notes:\n\nIsn't calling parent's __init__ with no new args redundant -- can't you just take out those 2 lines?\nYou create more local variables than I would have. I had to keep looking around to see where a value came from, o...
[ 3, 2, 1, 1 ]
[ "It's gui code and is always verbose, my best advice is: does it work? good. Next Task !\n" ]
[ -3 ]
[ "gedit", "pygtk", "python" ]
stackoverflow_0002284809_gedit_pygtk_python.txt
Q: Python basics: How to read N ints until '\n' is found in stdin How can I read N ints from the input, and stop reading when I find \n? Also, how can I add them to an array that I can work with? I'm looking for something like this from C but in python while(scanf("%d%c",&somearray[i],&c)!=EOF){ i++; if (c ==...
Python basics: How to read N ints until '\n' is found in stdin
How can I read N ints from the input, and stop reading when I find \n? Also, how can I add them to an array that I can work with? I'm looking for something like this from C but in python while(scanf("%d%c",&somearray[i],&c)!=EOF){ i++; if (c == '\n'){ break; } }
[ "In Python 2:\nlst = map(int, raw_input().split())\n\nraw_input() reads a whole line from the input (stopping at the \\n) as a string.\n.split() creates a list of strings by splitting the input into words.\nmap(int, ...) creates integers from those words.\nIn Python 3 raw_input has been renamed to input and map ret...
[ 19, 13 ]
[]
[]
[ "python", "stdin" ]
stackoverflow_0002285284_python_stdin.txt
Q: Pylons: response renaming? Is there a better way? I've got a Pylons controller with an action called serialize returning content_type=text/csv. I'd like the response of the action to be named based on the input patameter, i.e. for the following route, produced csv file should be named {id}.csv : /app/PROD/serializ...
Pylons: response renaming? Is there a better way?
I've got a Pylons controller with an action called serialize returning content_type=text/csv. I'd like the response of the action to be named based on the input patameter, i.e. for the following route, produced csv file should be named {id}.csv : /app/PROD/serialize => PROD.csv (so a user can open the file in Excel wit...
[ "You should be able to set the content-disposition header on a response object.\nIf you have already tried that, it may not have worked because the http standard says that the quotes should be done by double-quote marks.\n" ]
[ 2 ]
[]
[]
[ "pylons", "python", "response", "webob", "wsgi" ]
stackoverflow_0002285247_pylons_python_response_webob_wsgi.txt
Q: Adding text to p tag in Beautiful Soup I was wondering if anyone knew how to add text to a tag (p, b -- any tag where you might want to include character data). The documentation mentions no where how you might do this. A: I'm not sure exactly if this is what you want, but maybe it's a start... from BeautifulSo...
Adding text to p tag in Beautiful Soup
I was wondering if anyone knew how to add text to a tag (p, b -- any tag where you might want to include character data). The documentation mentions no where how you might do this.
[ "I'm not sure exactly if this is what you want, but maybe it's a start...\nfrom BeautifulSoup import BeautifulSoup, NavigableString\n\nhtml = \"<p></p>\"\nsoup = BeautifulSoup(html)\nptag = soup.find('p')\nptag.insert(0, NavigableString(\"new\"))\nprint ptag\n\nOutputs\n<p>new</p>\n\nThe documentations shows a few ...
[ 8, 1 ]
[]
[]
[ "beautifulsoup", "html", "python", "xml" ]
stackoverflow_0002285389_beautifulsoup_html_python_xml.txt
Q: Do all dynamic languages have the circular import issue? For the following Python code: first.py # first.py from second import Second class First: def __init__(self): print 'Second' second.py # second.py from first import First class Second: def __init__(self): print 'Second' After crea...
Do all dynamic languages have the circular import issue?
For the following Python code: first.py # first.py from second import Second class First: def __init__(self): print 'Second' second.py # second.py from first import First class Second: def __init__(self): print 'Second' After creating the files and running the following from the shell: pytho...
[ "Python can handle circular imports to some extent. In cases where no sense can be made, the solution would probably still not make sense in another language. Most of the problems can be cleared up by using import first and later referring to first.First instead of from first import First. \nIt would be better if y...
[ 12, 3, 2, 1, 1 ]
[]
[]
[ "dynamic_languages", "python", "ruby" ]
stackoverflow_0002284968_dynamic_languages_python_ruby.txt
Q: What resources/references are available for multithreaded programming in Python? I'm evaluating the use of Python for a new project and ran through some basic tutorials but am looking for some recommendations and resources for multithreaded development in Python? How does it compare to other languages? A: I'd r...
What resources/references are available for multithreaded programming in Python?
I'm evaluating the use of Python for a new project and ran through some basic tutorials but am looking for some recommendations and resources for multithreaded development in Python? How does it compare to other languages?
[ "I'd recommend http://herbsutter.wordpress.com/ (scroll down to the efficient concurrency columns) for a really great overview of what multiprocessing is all about. Yes, that guy talks about concurrency in a C++ context, but most of it is applicable for any language.\nIf you mention concurrency and Python, a lot of...
[ 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002283610_multithreading_python.txt
Q: splitting one program into several smaller and their binding in python? i want to make from one big program 5 smaller programs:main and program1,program2,program3 and program4.programs1,2,3,4 should use variables from main program and return some new variables,and main program should use(or call) programs1,2,3,4....
splitting one program into several smaller and their binding in python?
i want to make from one big program 5 smaller programs:main and program1,program2,program3 and program4.programs1,2,3,4 should use variables from main program and return some new variables,and main program should use(or call) programs1,2,3,4... can i bind these programs using functions,modules or something else and ho...
[ "You can simply use functions to do this:\ndef function1(a):\n print a\n\ndef function2(b):\n print b\n\ndef function3(c):\n print c\n\ndef function4():\n return \"hello!\"\n\ndef main():\n a, b, c = (1, 2, 3)\n function1(a)\n function2(b)\n function3(c)\n d = function4()\n print d\n\n...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002285746_python.txt
Q: Python dictionary that maps strings to a set of strings? I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: { "crackers" : ["crunchy", "salty"] } It must be a set, not a list. However, when I try the following: word_dict = dict() word_dict["foo"] =...
Python dictionary that maps strings to a set of strings?
I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: { "crackers" : ["crunchy", "salty"] } It must be a set, not a list. However, when I try the following: word_dict = dict() word_dict["foo"] = set() word_dict["foo"] = word_dict["foo"].add("baz") ...
[ "set.add() does not return a new set, it modifies the set it is called on. Use it this way:\nword_dict = dict()\nword_dict[\"foo\"] = set()\nword_dict[\"foo\"].add(\"baz\") \nword_dict[\"foo\"].add(\"bang\")\n\nAlso, if you use a for loop to iterate over a dict, you are iterating ...
[ 32, 31, 7, 1, 1 ]
[]
[]
[ "dictionary", "python", "set" ]
stackoverflow_0002285874_dictionary_python_set.txt
Q: Endless Recursion in Python Full disclosure, this is part of a homework assignment (though a small snippet, the project itself is a game playing AI). I have this function built into a tree node class: def recursive_score_calc(self): current_score = self.board for c in self.children: ...
Endless Recursion in Python
Full disclosure, this is part of a homework assignment (though a small snippet, the project itself is a game playing AI). I have this function built into a tree node class: def recursive_score_calc(self): current_score = self.board for c in self.children: child_score = c.recursive_score_...
[ "This bit of your code:\nclass TreeNode:\n children = []\n\nmeans that every instance of the class shares the same children list. So, in this bit:\ndef add_child(self, child):\n self.children.append(child)\n\nyou're appending to the \"class-global\" list. So, of course, every node is a child of every other ...
[ 7, 3 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0002286019_python_recursion.txt
Q: how does stackoverflow get the user-info when people login site use openid i want to get the userid and somethins other about user. but i don't get this i used pinax what should i do ?? thanks ex:facebook Javascript (from therunaround demo): FB.Facebook.get_sessionState().waitUntilReady(function() { ...
how does stackoverflow get the user-info when people login site use openid
i want to get the userid and somethins other about user. but i don't get this i used pinax what should i do ?? thanks ex:facebook Javascript (from therunaround demo): FB.Facebook.get_sessionState().waitUntilReady(function() { var user = FB.Facebook.apiClient.get_session() ? FB.Facebook.apiClien...
[ "You can read about the open-id implementation details on their site, where: http://openid.net/add-openid/add-getting-started/.\nIn a nutshell, you redirect the client to the openid provider who fills out the appropriate information, then the provider sends the client back to your site. You then make a (HTTP) reque...
[ 1, 0 ]
[]
[]
[ "django", "openid", "python" ]
stackoverflow_0002285976_django_openid_python.txt
Q: detection of communication failure when "put" in queue I am using the multiprocessing python module with Queue for communication between processes. Some processes only send (i.e. queue.put) and I can't seem to find a way to detect when the receiving end gets terminated abruptly. Is there a way to detect if the pr...
detection of communication failure when "put" in queue
I am using the multiprocessing python module with Queue for communication between processes. Some processes only send (i.e. queue.put) and I can't seem to find a way to detect when the receiving end gets terminated abruptly. Is there a way to detect if the process at the other end of the Queue gets terminated without ...
[ "I don't believe multiprocessing sets up a \"watch-dog\" process for you to take care of crashes or kills of some of your processes. It may be worth your while to set one up (pretty hard to do cross-platform, but if, say, you're only worried about Linux, it's not that terrible).\n" ]
[ 0 ]
[]
[]
[ "multiprocessing", "python", "queue" ]
stackoverflow_0002285922_multiprocessing_python_queue.txt
Q: Python URL Characters I really new to Python and coding in general, but I have been making some good strides. I am able to pull some data off of the web through an API, and the result should be a string. What I am seeing though, are some instances such as "& amp;"" and " &quot". (I modified the character sets so ...
Python URL Characters
I really new to Python and coding in general, but I have been making some good strides. I am able to pull some data off of the web through an API, and the result should be a string. What I am seeing though, are some instances such as "& amp;"" and " &quot". (I modified the character sets so it would print properly to ...
[ "xml.sax.saxutils.unescape(data[, entities]): Unescape '&amp', '&lt', and '&gt' in a string of data.\nYou can unescape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. '&amp', '&lt', and...
[ 2 ]
[]
[]
[ "html", "html_entities", "python" ]
stackoverflow_0002286188_html_html_entities_python.txt
Q: The origin of using # as a comment in Python? So I just had like this mental explosion dude! I was looking at my Python source code and was reading some comments and then I looked a the comments again. When I came across this: #!/usr/bin/env python # A regular comment Which made me wonder, was # chosen as the sym...
The origin of using # as a comment in Python?
So I just had like this mental explosion dude! I was looking at my Python source code and was reading some comments and then I looked a the comments again. When I came across this: #!/usr/bin/env python # A regular comment Which made me wonder, was # chosen as the symbol to start a comment because it would allow the p...
[ "Yes.\nUsing # to start a comment is a convention followed by every major interpreted language designed to work on POSIX systems (i.e. not Windows).\nIt also dovetails nicely with the fact that the sequence \"#!\" at the beginning of a file is recognized by the OS to mean \"run the command on this line\" when you t...
[ 13, 6, 1, 0 ]
[]
[]
[ "linux", "python", "shell" ]
stackoverflow_0002286120_linux_python_shell.txt
Q: Syntax error after uploading GAE Python app I have created a GAE app that parses RSS feeds using cElementTree. Testing on my local installation of GAE works fine. When I uploaded this app and tried to test it, I get a SyntaxError. The error is : Traceback (most recent call last): File "/base/python_lib/versions/...
Syntax error after uploading GAE Python app
I have created a GAE app that parses RSS feeds using cElementTree. Testing on my local installation of GAE works fine. When I uploaded this app and tried to test it, I get a SyntaxError. The error is : Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line ...
[ "You may have run into one of the mysterious limits placed on GAE.\nUrlopen has been overridden by google to it's urlfetch method, so there shouldn't be any difference in it. (though it might be worth trying, there are a lot of hidden things in GAE)\nnewline characters shouldn't effect cElementTree.\nAre there any ...
[ 0 ]
[]
[]
[ "feed", "python", "rss" ]
stackoverflow_0002269941_feed_python_rss.txt
Q: Putting a message in the same line import pythoncom, pyHook, logging, string LOG_FILENAME = 'logfile.txt' def OnKeyboardEvent(event): print 'MessageName:',event.MessageName print 'Time:',event.Time print 'WindowName:',event.WindowName print 'Ascii:', event.Ascii, chr(event.Ascii) print 'Key:'...
Putting a message in the same line
import pythoncom, pyHook, logging, string LOG_FILENAME = 'logfile.txt' def OnKeyboardEvent(event): print 'MessageName:',event.MessageName print 'Time:',event.Time print 'WindowName:',event.WindowName print 'Ascii:', event.Ascii, chr(event.Ascii) print 'Key:', event.Key print '---' k = even...
[ "There doesn't seem to be any way to make Logger.debug() append messages to the same line. Since your log file format is so simple, why not just use a plain file object?\n\nlogger = open(LOG_FILENAME, 'a')\nlogger.write(k)\nlogger.close()\n\n" ]
[ 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002286287_logging_python.txt
Q: Positional Comparisons in Python (Here's a sort of hypothetical situation for everybody. I'm more looking for directions rather than straight processes, but if you can provide them, awesome!) So let's say we have a list of athletes, I'm going to use figure skaters since I'm knee deep in the Winter Olympics right n...
Positional Comparisons in Python
(Here's a sort of hypothetical situation for everybody. I'm more looking for directions rather than straight processes, but if you can provide them, awesome!) So let's say we have a list of athletes, I'm going to use figure skaters since I'm knee deep in the Winter Olympics right now. (I'm throwing it in a dictionary s...
[ "I would use the athlet name as key in your dicts. Then you can look for their position more easily. Something like:\ndiff = {}\nfor (a, pos2) in after_free_skate.items():\n pos1 = after_short_program[a]\n diff[a] = pos2 - pos1\n\nI hope it helps\n", "This solution prints the results in the same order as ...
[ 7, 3, 1, 1, 0 ]
[]
[]
[ "comparison", "python" ]
stackoverflow_0002286557_comparison_python.txt
Q: How to execute a VS2008 command from Python and grab its output? I wish to run tf changeset 12345 Using the Visual Studio 2008 Command tool. It is located in: "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\" and the command that gets launched is: %comspec% /k ""c:\Program Files (x86)\Microsoft Visual Stu...
How to execute a VS2008 command from Python and grab its output?
I wish to run tf changeset 12345 Using the Visual Studio 2008 Command tool. It is located in: "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\" and the command that gets launched is: %comspec% /k ""c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86 I would like to append the "tf changese...
[ "process = subprocess.Popen(['tf', 'changeset', '12345'], cwd='c:/somedir', env={'SOMEENVVAR': 'SOMEVALUE', ...}, stdout=subprocess.PIPE)\n\nfor line in process.stdout:\n print line\n\nprocess.terminate()\n\n", "Have a look at this code I used here to do the job that you're looking for. This is written in C#, an...
[ 3, 2 ]
[]
[]
[ "python", "shellexecute", "visual_studio_2008" ]
stackoverflow_0002258094_python_shellexecute_visual_studio_2008.txt
Q: How do I start GWT devmode on a particular port from the console? So, within the directory containing my GWT application, I can type in the console ant devmode And it will start up my GWT application as per usual. So far so good. However, what if wish to specify the port as a dynamic argument when starting devm...
How do I start GWT devmode on a particular port from the console?
So, within the directory containing my GWT application, I can type in the console ant devmode And it will start up my GWT application as per usual. So far so good. However, what if wish to specify the port as a dynamic argument when starting devmode. Something conceptually like: ant devmode port=8821 Or am I suppo...
[ "Passing an argument via ant can be done via the ant properties. The call would be:\nant devmode -Dport=8821\n\nIn your ant file specify a property port. The default value will be overridden when you pass the argument via the command line:\n<property name=\"port\" value=\"8080\" /> //replace 8080 with the default ...
[ 2 ]
[]
[]
[ "ant", "gwt", "python" ]
stackoverflow_0002286468_ant_gwt_python.txt
Q: Python : updating values in a dictionary I have the following dictionary -> key : (time,edge_list) Now I want to increment all time values by 1. How do I do that? dict_list = dict(key:(time+1,edge_list) for key:(time,edge_list) in dict_list) A: >>> d={"key" : (100,"edge_list")} >>> for i,(time,edge_list) in d.i...
Python : updating values in a dictionary
I have the following dictionary -> key : (time,edge_list) Now I want to increment all time values by 1. How do I do that? dict_list = dict(key:(time+1,edge_list) for key:(time,edge_list) in dict_list)
[ ">>> d={\"key\" : (100,\"edge_list\")}\n>>> for i,(time,edge_list) in d.items():\n... d[i] = time+1, edge_list\n... \n>>> d\n{'key': (101, 'edge_list')}\n\n", "dict((key, (time + 1, edge_list)) for (key, (time, edge_list)) in somedict.iteritems())\n\n" ]
[ 9, 7 ]
[]
[]
[ "python" ]
stackoverflow_0002287061_python.txt
Q: Pylons: free module-level variables? Not even sure if module-level is correct here, but... I have a Pylons project and within the model component I have a global variable, doc, in __init__.py that I want to use from different Query objects. (doc is a Document handle on an XML file that I am using as a fake DB.) My...
Pylons: free module-level variables?
Not even sure if module-level is correct here, but... I have a Pylons project and within the model component I have a global variable, doc, in __init__.py that I want to use from different Query objects. (doc is a Document handle on an XML file that I am using as a fake DB.) My question is, when does __init__.py's scop...
[ "Objects only stop existing when 1) no references to them exist, or 2) the interpreter ends. A module/package keeps a reference to all module-level names in its private dict; deleting all references to the module in all other modules as well as in sys.modules, and all references to any objects within it will releas...
[ 0, 0 ]
[]
[]
[ "object", "pylons", "python", "scope", "singleton" ]
stackoverflow_0002129164_object_pylons_python_scope_singleton.txt
Q: How to do I integrate a 304 in Django? When a user requests the same page, with the same data...I'd like Django to return a 304, so that the browser doesn't have to load the page all over again. I'm new to this. How can this be done? Thanks. A: There's extensive description in Django documentation: Conditional v...
How to do I integrate a 304 in Django?
When a user requests the same page, with the same data...I'd like Django to return a 304, so that the browser doesn't have to load the page all over again. I'm new to this. How can this be done? Thanks.
[ "There's extensive description in Django documentation: Conditional view processing\nFollowing tools are particularly useful:\n\n@last_modified and @etag view decorators. You supply them with a function to compute the value from request and everything else is done automatically.\ndjango.middleware.http.Conditional...
[ 13, 6 ]
[]
[]
[ "django", "header", "http_status_code_304", "python" ]
stackoverflow_0002287387_django_header_http_status_code_304_python.txt
Q: Only connect to database when necessary I'm using Pylons + Python and am trying to figure how how to connect to our central database server only when necessary. I created a class called Central() which I would like to instantiate whenever a connection to the central database server is necessary, e.g.: class Cent...
Only connect to database when necessary
I'm using Pylons + Python and am trying to figure how how to connect to our central database server only when necessary. I created a class called Central() which I would like to instantiate whenever a connection to the central database server is necessary, e.g.: class Central(): def __init__(self): engine = eng...
[ "Since I can't tell what's the layout of your code, I can only assume that you've got engine and central_db defined somewhere in the global context. Is that correct? If so you could try something like this:\ndef __init__(self):\n global engine\n global central_db\n engine = engine_from_config(config, 'sqla...
[ 1, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0002210646_pylons_python_sqlalchemy.txt
Q: Python MySQL query not completing I am having problems with a Python script which is basically just analysing a CSV file line-by-line and then inserting each line into a MySQL table using a FOR loop: f = csv.reader(open(filePath, "r")) i = 1 for line in f: if (i > skipLines): vals = nullify(line) ...
Python MySQL query not completing
I am having problems with a Python script which is basically just analysing a CSV file line-by-line and then inserting each line into a MySQL table using a FOR loop: f = csv.reader(open(filePath, "r")) i = 1 for line in f: if (i > skipLines): vals = nullify(line) try: cursor.execute(quer...
[ "Have you tried LOAD MySQL function?\nquery = \"LOAD DATA INFILE '/path/to/file' INTO TABLE atable FIELDS TERMINATED BY ',' ENCLOSED BY '\\\"' ESCAPED BY '\\\\\\\\'\"\ncursor.execute( query )\n\nYou can always pre-process the CSV file (at least that's what I do :)\nAnother thing worth trying would be bulk inserts. ...
[ 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002285620_mysql_python.txt
Q: how do I filter values from XML file in python I have a basic grasp of XML and python and have been using minidom with some success. I have run into a situation where I am unable to get the values I want from an XML file. Here is the basic structure of the pre-existing file. <localization> <b n="Stats"> ...
how do I filter values from XML file in python
I have a basic grasp of XML and python and have been using minidom with some success. I have run into a situation where I am unable to get the values I want from an XML file. Here is the basic structure of the pre-existing file. <localization> <b n="Stats"> <l k="SomeStat1"> <v>10</v> </...
[ "You might consider using XPATH, a language for addressing parts of an xml document.\nHere's the answer using lxml.etree and it's support for xpath.\n>>> data = \"\"\"\n... <localization>\n... <b n=\"Stats\">\n... <l k=\"SomeStat1\">\n... <v>10</v>\n... </l>\n... <l k=\"SomeS...
[ 4, 2, 2, 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002286633_python_xml.txt
Q: Python & parsing IRC messages What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example: :test!~test@test.com PRIVMSG #channel :Hi! becomes this: { "sender" : "test!~test@test.com", "target" : "#channel", "message" : "...
Python & parsing IRC messages
What's the best way to parse messages received from an IRC server with Python according to the RFC? I simply want some kind of list/whatever, for example: :test!~test@test.com PRIVMSG #channel :Hi! becomes this: { "sender" : "test!~test@test.com", "target" : "#channel", "message" : "Hi!" } And so on? (Edit: I want to...
[ "Look at Twisted's implementation http://twistedmatrix.com/\nUnfortunately I'm out of time, maybe someone else can paste it here for you.\nEdit\nWell I'm back, and strangely no one has pasted it yet so here it is:\nhttp://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/irc.py#54\ndef parsemsg(s):\n ...
[ 22, 1, 0, 0, 0 ]
[]
[]
[ "irc", "parsing", "python" ]
stackoverflow_0000930700_irc_parsing_python.txt
Q: What are some good ways to do connection management in C? In C, when making a networking client / server setup, I usually have to do some standard BSD socket setup. Then on the server side, I'll have to manage multiple threads, usually a main thread, an a io thread. Each connection is managed by a connection manag...
What are some good ways to do connection management in C?
In C, when making a networking client / server setup, I usually have to do some standard BSD socket setup. Then on the server side, I'll have to manage multiple threads, usually a main thread, an a io thread. Each connection is managed by a connection manager so that you can have connections being processed while new r...
[ "Personally, I am not a huge fan of the one-thread-per-connection model with synchronous IO. I prefer X threads with a pool of Y connections with asynchronous IO. You can spawn threads as needed, or round robin the connections as they come in to a pre-allocated pool.\nIf you want to be really tricky, spawn threads ...
[ 2 ]
[]
[]
[ "c", "connection_pooling", "python", "service", "sockets" ]
stackoverflow_0002288131_c_connection_pooling_python_service_sockets.txt
Q: Enumerate CD-Drives using Python (Windows) How can I find out the drive letters of available CD/DVD drives? I am using Python 2.5.4 on Windows. A: Using win32api you can get list of drives and using GetDriveType you can check what type of drive it is, you can access win32api either by 'Python for Windows Extensi...
Enumerate CD-Drives using Python (Windows)
How can I find out the drive letters of available CD/DVD drives? I am using Python 2.5.4 on Windows.
[ "Using win32api you can get list of drives and using GetDriveType\nyou can check what type of drive it is, you can access win32api either by 'Python for Windows Extensions' or ctypes module\nHere is an example using ctypes:\nimport string\nfrom ctypes import windll\n\ndriveTypes = ['DRIVE_UNKNOWN', 'DRIVE_NO_ROOT_D...
[ 10, 2, 2, 2, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002288065_python_windows.txt
Q: python: two way partial credit card storing encrytion For my ecommece site, I want to store partial credit card numbers as string, for this I need to encrypt the information to store at the database and decrypt when users want to reuse the already entered credit card info from earlier purchases without typing it a...
python: two way partial credit card storing encrytion
For my ecommece site, I want to store partial credit card numbers as string, for this I need to encrypt the information to store at the database and decrypt when users want to reuse the already entered credit card info from earlier purchases without typing it all over again. I am using Django thus I need to solve this ...
[ "Before you go much further you should take a look at PCI-DSS, which governs exactly what processes you need to have in place to even consider storing encrypted card numbers. In short, you should seriously consider outsourcing to a 3rd party payment gateway.\nIf once you've understood the consequences you do want t...
[ 16, 2 ]
[]
[]
[ "credit_card", "django", "encryption", "python" ]
stackoverflow_0002288448_credit_card_django_encryption_python.txt
Q: Install python egg in buildout environment including data files This question assumes that the python package I want to install is a django app that includes templates and media files. But the question is valid for any python package that does not only contain .py files. I'm using buildout to create a re-buildable...
Install python egg in buildout environment including data files
This question assumes that the python package I want to install is a django app that includes templates and media files. But the question is valid for any python package that does not only contain .py files. I'm using buildout to create a re-buildable environment in which I'm developing a django project. My buildout.cf...
[ "It sounds like you need to make use of the package_data keyword argument in your setup.py file, so distutils knows those files should be installed with your package.\n" ]
[ 3 ]
[]
[]
[ "buildout", "django", "egg", "python" ]
stackoverflow_0002288533_buildout_django_egg_python.txt
Q: What's wrong in this caching function in Django? I've created the model for counting the number of views of my page: class RequestCounter(models.Model): count = models.IntegerField(default=0) def __unicode__(self): return str(self.count) For incrementing the counter I use: def inc_counter(): c...
What's wrong in this caching function in Django?
I've created the model for counting the number of views of my page: class RequestCounter(models.Model): count = models.IntegerField(default=0) def __unicode__(self): return str(self.count) For incrementing the counter I use: def inc_counter(): counter = RequestCounter.objects.get_or_create(id =1)[0...
[ "What CACHE_BACKEND are you using? If it's locmem:// and you're running Apache, you'll have a different cache active for each Apache child, which would explain the differing results. I had this a while ago and it was a subtle one to work out. I'd recommend switching to memcache if you're not already on it, as this ...
[ 4 ]
[]
[]
[ "caching", "django", "python" ]
stackoverflow_0002288720_caching_django_python.txt
Q: Problem with running Django 1.1.1 on Google App Engine Developement Server I've downloaded google_appengine version 1.3.1. Using some web tutorials, I've created basic django 1.1.1 application. Using appcfg I managed to deploy it on GAE and it works. The problem is, that application doesn't want to work on dev_app...
Problem with running Django 1.1.1 on Google App Engine Developement Server
I've downloaded google_appengine version 1.3.1. Using some web tutorials, I've created basic django 1.1.1 application. Using appcfg I managed to deploy it on GAE and it works. The problem is, that application doesn't want to work on dev_appengine.py developement server. Whenever I run the app GAE local server is return...
[ "I had module nammed same way as the default GAE launcher (main/ and main.py). After renaming the launcher everything works great.\n" ]
[ 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002288725_django_google_app_engine_python.txt
Q: Wrong results with Python multiply() and prod() Can anyone explain the following? I'm using Python 2.5 Consider 1*3*5*7*9*11 ... *49. If you type all that from within IPython(x,y) interactive console, you'll get 58435841445947272053455474390625L, which is correct. (why odd numbers: just the way I did it originall...
Wrong results with Python multiply() and prod()
Can anyone explain the following? I'm using Python 2.5 Consider 1*3*5*7*9*11 ... *49. If you type all that from within IPython(x,y) interactive console, you'll get 58435841445947272053455474390625L, which is correct. (why odd numbers: just the way I did it originally) Python multiply.reduce() or prod() should yield th...
[ "This is because numpy.multiply.reduce() converts the range list to an array of type numpy.int32, and the reduce operation overflows what can be stored in 32 bits at some point:\n>>> type(numpy.multiply.reduce(range(1, 50, 2)))\n<type 'numpy.int32'>\n\nAs Mike Graham says, you can use the dtype parameter to use Pyt...
[ 6, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002288952_numpy_python.txt
Q: displaying a large amount of formatted text in Python I have two large identical-sized files. One is ASCII plain text, and the other is a colour-coded overlay, one byte per text character in the corresponding file. These files can be large - upto 2.5 MB; possibly substantially more, perhaps over 100MB later. I wa...
displaying a large amount of formatted text in Python
I have two large identical-sized files. One is ASCII plain text, and the other is a colour-coded overlay, one byte per text character in the corresponding file. These files can be large - upto 2.5 MB; possibly substantially more, perhaps over 100MB later. I want to display the text is a scrollable text viewer, using t...
[ "How about using a scrollable canvas instead, and only ever drawing the text/heatmap that is exposed by the user? That should give you a quick initial draw and a quick redraw when things move around, regardless of the size of the file.\nIf you want more speed and more control, then you would need some sort of virtu...
[ 4 ]
[]
[]
[ "performance", "python", "richtextbox", "tkinter" ]
stackoverflow_0002279063_performance_python_richtextbox_tkinter.txt
Q: Effective ways to implement Every-to-Every interaction? Given a list of elements, how to process all elements if every element requires knowledge about states of every other element of this list? For example, direct way to implement it in Python could be: S = [1,2,3,4] for e in S: for j in S: if e!=j: ...
Effective ways to implement Every-to-Every interaction?
Given a list of elements, how to process all elements if every element requires knowledge about states of every other element of this list? For example, direct way to implement it in Python could be: S = [1,2,3,4] for e in S: for j in S: if e!=j: process_it(e,j) but it is very slow O(n²) if number of elem...
[ "If you need to process every pair of items, there are O(n2) pairs, so you will have to make that many calls!\nIf you only need the combinations (ab, ac, bc), not all the permutations (ab,ba,ac,ca,bc,cb), then you can do this, to halve the number of calls (and skip the if):\nfor idA,val in enumerate(items):\n fo...
[ 2, 1, 0 ]
[]
[]
[ "algorithm", "c", "parallel_processing", "python" ]
stackoverflow_0002288849_algorithm_c_parallel_processing_python.txt
Q: Python, mongo + spider monkey Ok, so this isn't exactly a question that I expect a full answer for but here goes... I am currently using a python driver to fire data at a mongo instance and all it well in the world. Now I want to be able to pull data from mongo and evaluate each record in the collection. Now I nee...
Python, mongo + spider monkey
Ok, so this isn't exactly a question that I expect a full answer for but here goes... I am currently using a python driver to fire data at a mongo instance and all it well in the world. Now I want to be able to pull data from mongo and evaluate each record in the collection. Now I need to pass in to this evaluation a s...
[ "Have you looked at $where clauses in MongoDB? Seems like those would pretty much give you exactly what you're looking for. In PyMongo it would look something like:\ndb.foo.find().where(\"some javascript function that will get applied to each document matched by the find\")\n\n" ]
[ 3 ]
[]
[]
[ "mongodb", "python", "spidermonkey" ]
stackoverflow_0002285083_mongodb_python_spidermonkey.txt
Q: Fast way to get N Min or Max elements from a list in Python I currently have a long list which is being sorted using a lambda function f. I then choose a random element from the first five elements. Something like: f = lambda x: some_function_of(x, local_variable) my_list.sort(key=f) foo = choice(my_list[:4]) Thi...
Fast way to get N Min or Max elements from a list in Python
I currently have a long list which is being sorted using a lambda function f. I then choose a random element from the first five elements. Something like: f = lambda x: some_function_of(x, local_variable) my_list.sort(key=f) foo = choice(my_list[:4]) This is a bottleneck in my program, according to the profiler. How c...
[ "Use heapq.nlargest or heapq.nsmallest.\nFor example:\nimport heapq\n\nelements = heapq.nsmallest(4, my_list, key=f)\nfoo = choice(elements)\n\nThis will take O(N+KlogN) time (where K is the number of elements returned, and N is the list size), which is faster than O(NlogN) for normal sort when K is small relative ...
[ 11, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002289053_python_sorting.txt
Q: How can I work with base 5 numbers in Python? Possible Duplicate: convert integer to a string in a given numeric base in python I want to work with base 5 numbers, or any other non standard base for that matter. I found out int('123', 5) works, but I need to go the other way around. Should I write my own number...
How can I work with base 5 numbers in Python?
Possible Duplicate: convert integer to a string in a given numeric base in python I want to work with base 5 numbers, or any other non standard base for that matter. I found out int('123', 5) works, but I need to go the other way around. Should I write my own number class to accomplish this? Maybe I'm just thinking...
[ "def to_base_5(n):\n s = \"\"\n while n:\n s = str(n % 5) + s\n n /= 5\n return s\n\n", "I had fun with this a while ago for a python-dev thread. The original post can be found at \nhttp://mail.python.org/pipermail/python-dev/2006-January/059925.html This particular algorithm can perform ...
[ 5, 3 ]
[]
[]
[ "math", "python" ]
stackoverflow_0002288482_math_python.txt
Q: Disable class instance methods How can I quickly disable all methods in a class instance based on a condition? My naive solution is to override using the __getattr__ but this is not called when the function name exists already. class my(): def method1(self): print 'method1' def method2(self): ...
Disable class instance methods
How can I quickly disable all methods in a class instance based on a condition? My naive solution is to override using the __getattr__ but this is not called when the function name exists already. class my(): def method1(self): print 'method1' def method2(self): print 'method2' def __getattr...
[ "The equivalent of what you want to do is actually to override __getattribute__, which is going to be called for every attribute access. Besides it being very slow, take care: by definition of every, that includes e.g. the call to self.isValid within __getattribute__'s own body, so you'll have to use some circuito...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0002289797_python.txt
Q: Python and urllib I'm trying to download a zip file ("tl_2008_01001_edges.zip") from an ftp census site using urllib. What form is the zip file in when I get it and how do I save it? I'm fairly new to Python and don't understand how urllib works. This is my attempt: import urllib, sys zip_file = urllib.urlretriev...
Python and urllib
I'm trying to download a zip file ("tl_2008_01001_edges.zip") from an ftp census site using urllib. What form is the zip file in when I get it and how do I save it? I'm fairly new to Python and don't understand how urllib works. This is my attempt: import urllib, sys zip_file = urllib.urlretrieve("ftp://ftp2.census.go...
[ "Use urllib2.urlopen() for the zip file data and directory listing.\nTo process zip files with the zipfile module, you can write them to a disk file which is then passed to the zipfile.ZipFile constructor.\nRetrieving the data is straightforward using read() on the file-like object returned\nby urllib2.urlopen().\n...
[ 8, 5, 3 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0002289768_python_urllib_urllib2.txt
Q: Sort strings by the first N characters I have a text file with lines like this: 2010-02-18 11:46:46.1287 bla 2010-02-18 11:46:46.1333 foo 2010-02-18 11:46:46.1333 bar 2010-02-18 11:46:46.1467 bla A simple sort would swap lines 2 and 3 (bar comes before foo), but I would like to keep lines (that have the same date...
Sort strings by the first N characters
I have a text file with lines like this: 2010-02-18 11:46:46.1287 bla 2010-02-18 11:46:46.1333 foo 2010-02-18 11:46:46.1333 bar 2010-02-18 11:46:46.1467 bla A simple sort would swap lines 2 and 3 (bar comes before foo), but I would like to keep lines (that have the same date/time) in their original order. How can I do...
[ "sorted(array, key=lambda x:x[:24])\n\nExample:\n>>> a = [\"wxyz\", \"abce\", \"abcd\", \"bcde\"]\n>>> sorted(a)\n['abcd', 'abce', 'bcde', 'wxyz']\n>>> sorted(a, key=lambda x:x[:3])\n['abce', 'abcd', 'bcde', 'wxyz']\n\n", "The built-in sort is stable, so you the effectively-equal values stay in order by default.\...
[ 26, 5 ]
[]
[]
[ "python", "sorting", "string" ]
stackoverflow_0002289870_python_sorting_string.txt
Q: what this python code trying to do The following python code is to traverse a 2D grid of (c, g) in some special order, which is stored in "jobs" and "job_queue". But I am not sure which kind of order it is after trying to understand the code. Is someone able to tell about the order and give some explanation for th...
what this python code trying to do
The following python code is to traverse a 2D grid of (c, g) in some special order, which is stored in "jobs" and "job_queue". But I am not sure which kind of order it is after trying to understand the code. Is someone able to tell about the order and give some explanation for the purpose of each function? Thanks and r...
[ "permute_sequence reorders a list of values so that the middle value is first, then the midpoint of each half, then the midpoints of the four remaining quarters, and so on. So permute_sequence(range(1000)) starts out like this:\n [500, 250, 750, 125, 625, 375, ...]\n\ncalculate_jobs alternately fills in rows and...
[ 2, 1 ]
[]
[]
[ "algorithm", "libsvm", "machine_learning", "python", "search" ]
stackoverflow_0002286438_algorithm_libsvm_machine_learning_python_search.txt
Q: Accessing a Variable from Within a Doubly Nested Function in Python The following code: x = 0 print "Initialization: ", x def f1(): x = 1 print "In f1 before f2:", x def f2(): global x x = 2 print "In f2: ", x f2() print "In f1 after f2: ", x f1() print "Final: ...
Accessing a Variable from Within a Doubly Nested Function in Python
The following code: x = 0 print "Initialization: ", x def f1(): x = 1 print "In f1 before f2:", x def f2(): global x x = 2 print "In f2: ", x f2() print "In f1 after f2: ", x f1() print "Final: ", x prints: Initialization: 0 In f1 before f2: 1 In f2: ...
[ "In Python 3, you can define x as nonlocal in f2.\nIn Python 2, you can't assign directly to f1's x in f2. However, you can read its value and access its members. So this could be a workaround:\ndef f1():\n x = [1]\n def f2():\n x[0] = 2\n f2()\n print x[0]\nf1()\n\n", "You can access the varia...
[ 6, 6, 0 ]
[]
[]
[ "global_variables", "nested_function", "python" ]
stackoverflow_0002290654_global_variables_nested_function_python.txt
Q: python more trouble importing modules I asked a similar question yesterday, but have acquired a really odd problem since then. With this directory structure: app/ models/ __init__.py user.py other.py pages/ __init__.py pages.py The models/__init__.py file has this ...
python more trouble importing modules
I asked a similar question yesterday, but have acquired a really odd problem since then. With this directory structure: app/ models/ __init__.py user.py other.py pages/ __init__.py pages.py The models/__init__.py file has this line: __all__ = ['user', 'other'] and the ...
[ "import models.user\n\n", "There are two options, depending on where you want to be explicit and how much you want available \"by default\" (which also means forced).\nIn those __init__ files you could use:\n# models/__init__.py shown:\nimport user, other # ambiguous relative import\nfrom . import...
[ 1, 1, 1 ]
[]
[]
[ "python", "python_import", "python_module" ]
stackoverflow_0002290595_python_python_import_python_module.txt
Q: Any utility function in python which returns value when passed object and attribute to it? Like we have in Java Beans util where you pass object and the property name it gives you the value do we have anything similar in python: def attr(obj, attr) return obj.attr A: You can use getattr for this purpose. Fro...
Any utility function in python which returns value when passed object and attribute to it?
Like we have in Java Beans util where you pass object and the property name it gives you the value do we have anything similar in python: def attr(obj, attr) return obj.attr
[ "You can use getattr for this purpose. From the built-in function documentation:\n\nFor example, getattr(x, 'foobar') is\n equivalent to x.foobar.\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0002290805_python.txt
Q: Python for a Perl programmer I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediatel...
Python for a Perl programmer
I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediately, related to Google App Engine). ...
[ "I've recently had to make a similar transition for work reasons, and it's been pretty painful. For better or worse, Python has a very different philosophy and way of working than Perl, and getting used to that can be frustrating. The things I've found most useful have been\n\nSpend a few hours going through all th...
[ 71, 16, 9, 4, 3, 2 ]
[ "I wouldn't try to compare Perl and Python too much in order to learn Python, especially since you have working knowledge of other languages. If you are unfamiliar with OOP/Functional programming aspects and just looking to work procedurally like in Perl, start learning the Python language constructs / syntax and t...
[ -4 ]
[ "perl", "python" ]
stackoverflow_0002283034_perl_python.txt
Q: Interrupt method execution after arbitrary time in Python I have some method doA() that occasionally hangs for a while. Are there any common modules in Python that can control time of doA() execution and interrupt it? Of course, it may be implemented via threads, so simple wrapper around threading module may be go...
Interrupt method execution after arbitrary time in Python
I have some method doA() that occasionally hangs for a while. Are there any common modules in Python that can control time of doA() execution and interrupt it? Of course, it may be implemented via threads, so simple wrapper around threading module may be good solution. In other words i'd like to have code like: import ...
[ "You can use a threading.Timer to call thread.interrupt_main, as long as you're running doA in the main thread. Note that the syntax you desire is impossible because Python (like most languages, excepting e.g. Haskell) is \"eager\" -- arguments are entirely computed before a call is performed, so the self.doA() wo...
[ 6 ]
[]
[]
[ "asynchronous", "multithreading", "python" ]
stackoverflow_0002291129_asynchronous_multithreading_python.txt
Q: sqlalchemy 0.6 legacy database access? I feel like this should be simple, but i cant find a single example of it being done. As an example I have the following existing tables: CREATE TABLE `source` ( `source_id` tinyint(3) unsigned NOT NULL auto_increment, `name` varchar(40) default NULL, PRIMARY KEY (`sou...
sqlalchemy 0.6 legacy database access?
I feel like this should be simple, but i cant find a single example of it being done. As an example I have the following existing tables: CREATE TABLE `source` ( `source_id` tinyint(3) unsigned NOT NULL auto_increment, `name` varchar(40) default NULL, PRIMARY KEY (`source_id`), UNIQUE KEY `source_name` (`name`...
[ "You can use a predefined/autoloaded table with declarative_base by assigning it to the __table__ attribute. The columns are picked up from the table, but you'll still have declare any relations you want to use.\nclass Source(Base):\n __table__ = source\n\nclass Event(Base):\n __table__ = event\n source = ...
[ 2 ]
[]
[]
[ "legacy_database", "python", "sqlalchemy" ]
stackoverflow_0002285062_legacy_database_python_sqlalchemy.txt
Q: SQLAlchemy.declarative and deferred column loading is it possible to specify some columns in the SQLAlchemy to be deferred-loading? I am using the sqlalchemy.ext.declarative module to define my mapping, example: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SomeClass(Bas...
SQLAlchemy.declarative and deferred column loading
is it possible to specify some columns in the SQLAlchemy to be deferred-loading? I am using the sqlalchemy.ext.declarative module to define my mapping, example: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class SomeClass(Base): __tablename__ = 'some_table' id = Column(Int...
[ "Just add deferred() around the column declaration:\nclass SomeClass(Base):\n __tablename__ = 'some_table'\n id = Column(Integer, primary_key=True)\n name = deferred(Column(String(50)))\n\n", "Do not define the mapping for the columns which you want to load on demand. Then configure those as described i...
[ 12, 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002289401_python_sqlalchemy.txt
Q: Django. Retrieving and opening a zip file from HDD I have a path to a zip file. I don't know how to retrieve the file from the hard drive or open that zip file. Does anyone know? The zip file is a zip file, but it's really a .epub file. A: http://docs.python.org/library/zipfile.html >>> import zipfile >>> path...
Django. Retrieving and opening a zip file from HDD
I have a path to a zip file. I don't know how to retrieve the file from the hard drive or open that zip file. Does anyone know? The zip file is a zip file, but it's really a .epub file.
[ "http://docs.python.org/library/zipfile.html\n>>> import zipfile\n>>> path = \"example/path.epub\"\n>>> epub = zipfile.ZipFile(open(path))\n>>> epub.namelist()\n ['some_file.txt']\n>>> file = epub.open('some_file.txt')\n>>> file.read()\n\n", "You don't need anything Django specific, just use the Python standard l...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002291913_django_python.txt
Q: python timer mystery Well, at least a mystery to me. Consider the following: import time import signal def catcher(signum, _): print "beat!" signal.signal(signal.SIGALRM, catcher) signal.setitimer(signal.ITIMER_REAL, 2, 2) while True: time.sleep(5) Works as expected i.e. delivers a "beat!" message eve...
python timer mystery
Well, at least a mystery to me. Consider the following: import time import signal def catcher(signum, _): print "beat!" signal.signal(signal.SIGALRM, catcher) signal.setitimer(signal.ITIMER_REAL, 2, 2) while True: time.sleep(5) Works as expected i.e. delivers a "beat!" message every 2 seconds. Next, no out...
[ "From my system's man setitimer (emphasis mine):\n\nThe system provides each process with three interval timers, each decrementing in a distinct time domain. When any timer expires, a signal is sent to the process, and the timer (potentially) restarts.\nITIMER_REAL decrements in real time, and delivers SIGALR...
[ 16, 4 ]
[]
[]
[ "python", "signals", "timer" ]
stackoverflow_0002292054_python_signals_timer.txt
Q: uncompressing tar.Z file with python? I need to write a python script that retrieves tar.Z files from an FTP server, and uncompress them on a windows machine. tar.Z, if I understood correctly is the result of a compress command in Unix. Python doesn't seem to know how to handle these, it's not gz, nor bz2 or zip. ...
uncompressing tar.Z file with python?
I need to write a python script that retrieves tar.Z files from an FTP server, and uncompress them on a windows machine. tar.Z, if I understood correctly is the result of a compress command in Unix. Python doesn't seem to know how to handle these, it's not gz, nor bz2 or zip. Does anyone know a library that would handl...
[ "If GZIP -- the application -- can handle it, you have two choices.\n\nTry the Python gzip library. It may work.\nUse subprocess Popen to run gzip for you.\n\nIt may be an InstallShield .Z file. You may want to use InstallShield to unpack it and extract the .TAR file. Again, you may be able to use subprocess Pope...
[ 1, 0, 0 ]
[]
[]
[ "compression", "python", "tar" ]
stackoverflow_0002272199_compression_python_tar.txt
Q: IntelliJ Python plug-in I've been using IntelliJ IDEA at the day job for Java development for a few weeks now. I'm really impressed with it and I'm looking to extend it for other programming languages that I tinker with, starting with Python. I found this plug-in, pythonid. I figured I would look for some input o...
IntelliJ Python plug-in
I've been using IntelliJ IDEA at the day job for Java development for a few weeks now. I'm really impressed with it and I'm looking to extend it for other programming languages that I tinker with, starting with Python. I found this plug-in, pythonid. I figured I would look for some input on the Stack before proceeding...
[ "There is currently an EAP for the Intellij Python IDE (PyCharm): here\n", "I've tried Pythonid before and found it very limited. There's a new Python plugin from JetBrains, the people that make IDEA, which looks pretty nice, though it's still very unfinished.\n" ]
[ 5, 4 ]
[]
[]
[ "ide", "java", "python" ]
stackoverflow_0000376765_ide_java_python.txt
Q: ID3 Decision Tree with Numeric Values I'm looking for a ID3 decision tree implementation in Python or any languages which takes a validation and a testing file as an input and returns predictions. I found this and this but I couldn't adapt them to numeric values, e.g. to Iris dataset. Do you know any ID3 tree impl...
ID3 Decision Tree with Numeric Values
I'm looking for a ID3 decision tree implementation in Python or any languages which takes a validation and a testing file as an input and returns predictions. I found this and this but I couldn't adapt them to numeric values, e.g. to Iris dataset. Do you know any ID3 tree implementation that works from console or any w...
[ "I have a similar algorithm C4.5 written in python. It work from console. If you are interested I put it here. \nSorry for a post if you need not this.\nBTW, I have tested it on Iris data set :)\nUpdate:\nI have uploaded both: code and data:\n\nc4.5 - http://pastebin.ca/1802066\niris.data - http://pastebin.ca/18020...
[ 2 ]
[]
[]
[ "decision_tree", "id3", "python" ]
stackoverflow_0002292540_decision_tree_id3_python.txt
Q: What Python/IronPython web development framework work on the Microsoft technology stack? I started learning Python using the IronPython implementation. I'd like to do some web development now. I'm looking for a python web development framework that works on the Microsoft technology stack (IIS + MS SQL Server). Dja...
What Python/IronPython web development framework work on the Microsoft technology stack?
I started learning Python using the IronPython implementation. I'd like to do some web development now. I'm looking for a python web development framework that works on the Microsoft technology stack (IIS + MS SQL Server). Django looks like an interesting framework but based on what I have read, getting it to work on t...
[ "Working with the full MS stack will be hard as not many FLOSS frameworks aim there. You'll have better luck with a WAMP (Windows/Apache/MySQL-PostgreSQL/Python) approach.\nThat being said, Django works on Windows, and even can be made to work under IIS by using PyISAPIe and MS SQL Server support.\nTurboGears can a...
[ 7, 3, 1 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0002292775_ironpython_python.txt
Q: Is windows's setsockopt broken? I want to be able to reuse some ports, and that's why I'm using setsockopt on my sockets, with the following code: sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) However, this doesn't really work. I'm not getting a bind error either, but the server socket just isn't respo...
Is windows's setsockopt broken?
I want to be able to reuse some ports, and that's why I'm using setsockopt on my sockets, with the following code: sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) However, this doesn't really work. I'm not getting a bind error either, but the server socket just isn't responding (it seems to start , but if I t...
[ "It appears that SO_REUSEADDR has different semantics on Windows vs Unix.\nSee this msdn article (particularly the chart below \"Using SO_EXCLUSIVEADDRUSE\") and this unix faq.\nAlso, see this python bug discussion, this twisted bug discussion, and this list of differences between Windows and Unix sockets.\n", "s...
[ 3, 1 ]
[]
[]
[ "python", "setsockopt", "sockets", "windows" ]
stackoverflow_0000796957_python_setsockopt_sockets_windows.txt
Q: Content of file to tree format using python I have a file containing a file "dir.txt" with the below data: /home/abc/a.txt /home/abc/b.txt /home/xyz/test /home/xyz/test/d.txt /home/xyz/test/e.txt /home/xyz/test/f.txt /home/xyz /home/xyz/g.txt I want to parse the file and get the output like /home/abc/a.txt ...
Content of file to tree format using python
I have a file containing a file "dir.txt" with the below data: /home/abc/a.txt /home/abc/b.txt /home/xyz/test /home/xyz/test/d.txt /home/xyz/test/e.txt /home/xyz/test/f.txt /home/xyz /home/xyz/g.txt I want to parse the file and get the output like /home/abc/a.txt b.txt /home/xyz/test/d.txt e.t...
[ "you need to use os.path.split on every path, find the first dirname and print path as it is. find it length and print so many spaces before next basename, on change of the dirname repeat as before.\n>>> import os.path \n>>> olddir = None\n>>> for name in open('input.txt'):\n dirname, fname = os.path.split(na...
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "python", "treeview" ]
stackoverflow_0002288570_python_treeview.txt
Q: Django decorator getting a WSGIRequest and not the expected function argument I'm creating a decorator for Django views that will check permissions in a non-Django-managed database. Here is the decorator: def check_ownership(failure_redirect_url='/', *args, **kwargs): def _check_ownership(view): def _w...
Django decorator getting a WSGIRequest and not the expected function argument
I'm creating a decorator for Django views that will check permissions in a non-Django-managed database. Here is the decorator: def check_ownership(failure_redirect_url='/', *args, **kwargs): def _check_ownership(view): def _wrapper(request, csi=None): try: opb_id=request.user.get...
[ "@check_ownership\ndef my_view(request, csi=None):\n ...\n\nTranslates into:\ndef my_view(request, csi=None):\n ...\nmy_view = check_ownership(my_view)\n\nbut check_ownership does not accept a function, but _check_ownership does. This might be where your problem lies.\n", "So the issue has to do with how th...
[ 1, 0 ]
[]
[]
[ "decorator", "django", "python" ]
stackoverflow_0002291616_decorator_django_python.txt
Q: Overloading embedded Python functions using PyArg_ParseTuple If I'm trying to overload an embedded Python function so that the second argument can be a long or an Object, is there a standard way to do it? Is this it? What I'm trying now (names changed to protect the innocent): bool UseLongVar2 = true; if (!PyA...
Overloading embedded Python functions using PyArg_ParseTuple
If I'm trying to overload an embedded Python function so that the second argument can be a long or an Object, is there a standard way to do it? Is this it? What I'm trying now (names changed to protect the innocent): bool UseLongVar2 = true; if (!PyArg_ParseTuple(args, "ll:foo", &LongVar1, &LongVar2)) { PyE...
[ "What I normally do is have two C functions that take the different arguments. The \"python-facing\" function's job is to parse out the arguments, call the appropriate C function, and build the return value if any.\nThis is pretty common when, for example, you want to allow both byte and Unicode strings.\nHere is a...
[ 3 ]
[]
[]
[ "embedded_language", "overloading", "python" ]
stackoverflow_0002291740_embedded_language_overloading_python.txt
Q: Why dictionaries appear to be reversed? Why dictionaries in python appears reversed? >>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'} >>> a {'four': '4', 'three': '3', 'two': '2', 'one': '1'} How can I fix this? A: Dictionaries in python (and hash tables in general) are unordered. In python you can u...
Why dictionaries appear to be reversed?
Why dictionaries in python appears reversed? >>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'} >>> a {'four': '4', 'three': '3', 'two': '2', 'one': '1'} How can I fix this?
[ "Dictionaries in python (and hash tables in general) are unordered. In python you can use the sort() method on the keys to sort them.\n", "Dictionaries have no intrinsic order. You'll have to either roll your own ordered dict implementation, use an ordered list of tuples or use an existing ordered dict implementa...
[ 16, 5, 5, 2, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002291637_dictionary_python.txt
Q: How to generate code objects from modules in Python? I have a .pyc file with no corresponding Python source code. I want to see the disassembly of the module using dis. I can import my module just fine with import dis import foo But to call dis.dis on it, I can't use the module object. I need the corresponding co...
How to generate code objects from modules in Python?
I have a .pyc file with no corresponding Python source code. I want to see the disassembly of the module using dis. I can import my module just fine with import dis import foo But to call dis.dis on it, I can't use the module object. I need the corresponding code object which backs foo. How do I create it? It seems th...
[ "See http://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html\n" ]
[ 4 ]
[]
[]
[ "bytecode", "bytecode_manipulation", "cpython", "python" ]
stackoverflow_0002293322_bytecode_bytecode_manipulation_cpython_python.txt
Q: How to solve this using regex? Given that string: \n \n text1\n \ttext2\n Message: 1st message\n some more text\n \n \n Message: 2dn message\n\n \t\t Message: 3rd message\n text3\n I want to extract messages from a multiline string (token is 'Message: '). What regex expression should I use to capture those 3...
How to solve this using regex?
Given that string: \n \n text1\n \ttext2\n Message: 1st message\n some more text\n \n \n Message: 2dn message\n\n \t\t Message: 3rd message\n text3\n I want to extract messages from a multiline string (token is 'Message: '). What regex expression should I use to capture those 3 groups: group 1 : '1st message' gr...
[ ">>> re.findall('Message: (.+?)$', s, re.M)\n['1st message', '2dn message', '3rd message']\n\nre.M flag gives special meaning to ^ and $:\n\nWhen specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern charac...
[ 9, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002290859_python_regex.txt
Q: the number of images, using "len()" I need to count the number of images (in this case 1 image). Apparently using "len()"? Here is HTML: <div class="detail-headline"> Fotogal&#233;ria </div> <div class="detail-indent"> <table id="ctl00_ctl00_ctl00_containerHolder_mainContentHolder_innnerContentHold...
the number of images, using "len()"
I need to count the number of images (in this case 1 image). Apparently using "len()"? Here is HTML: <div class="detail-headline"> Fotogal&#233;ria </div> <div class="detail-indent"> <table id="ctl00_ctl00_ctl00_containerHolder_mainContentHolder_innnerContentHolder_ZakazkaControl_ZakazkaObrazky1_Obrazky...
[ "Your job will be easier if you use BeautifulSoup\nPerhaps something like this\nfrom BeautifulSoup import BeaufitulSoup\ndef count_images(htmltext)\n soup=BeautifulSoup(htmltext)\n return len(soup.findAll('div',{'class':'detail-indent'}))\n\nOr using lxml\nfrom lxml.html.soupparser import fromstring\ndef coun...
[ 3, 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0002292982_parsing_python.txt
Q: django error when i signup my site . why? This is the signup view: def signup(request, form_class=SignupForm, template_name="account/signup.html", success_url=None): if success_url is None: success_url = get_default_redirect(request) if request.method == "POST": form = form_class(re...
django error when i signup my site . why?
This is the signup view: def signup(request, form_class=SignupForm, template_name="account/signup.html", success_url=None): if success_url is None: success_url = get_default_redirect(request) if request.method == "POST": form = form_class(request.POST) if form.is_valid(): ...
[ "it is ok now \ni used mysql insteadof squite3\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002293500_django_python.txt
Q: How can I show a widget and all its parent containers? In my program, there is a point where all widgets are hidden. Is there a simple way to show a widget and all of its parent containers? I am not able to use show_all(), because that would show other widgets that I don't want shown. I could go down the container...
How can I show a widget and all its parent containers?
In my program, there is a point where all widgets are hidden. Is there a simple way to show a widget and all of its parent containers? I am not able to use show_all(), because that would show other widgets that I don't want shown. I could go down the containers and show them all, but I would prefer not to if there is a...
[ "Other than iterating through Widget.get_parent and showing them all, you can also set the no-show-all property on the widgets you don't want shown, and call show_all on the ancestor.\n" ]
[ 1 ]
[]
[]
[ "containers", "gtk", "pygtk", "python", "widget" ]
stackoverflow_0002293672_containers_gtk_pygtk_python_widget.txt