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: Python2.6 Backtrack/Ubuntu wxPython I wrote a python app and it needs python2.6. I'm trying to get it to run in Backtrack 4 which is a pen-testing linux distro based on debian/ubuntu. I'v managed to install python2.6 along side of python2.5. Now I'm trying to install wxPython for 2.6 from the repos but I can't get...
Python2.6 Backtrack/Ubuntu wxPython
I wrote a python app and it needs python2.6. I'm trying to get it to run in Backtrack 4 which is a pen-testing linux distro based on debian/ubuntu. I'v managed to install python2.6 along side of python2.5. Now I'm trying to install wxPython for 2.6 from the repos but I can't get it to install it for python2.6 rather th...
[ "There is pre-built version of python, wxwidgets, wxpython in ubuntu packages.\nYou don't need to build from the sources(unless you have special reasons), you can install it from the following links.\nhttp://packages.ubuntu.com/jaunty/python2.6\nhttp://packages.ubuntu.com/jaunty/libwxgtk2.8-0\nhttp://packages.ubunt...
[ 1 ]
[]
[]
[ "python", "ubuntu", "wxpython" ]
stackoverflow_0001837558_python_ubuntu_wxpython.txt
Q: Are there any pure Python, BSD-ish open source SVG libraries? I'm looking for a pure Python library to help put together SVG images. It doesn't need to be fast. I know pySVG exists, but I'm not interested in a GPL library (and I can't use GPL libraries for this particular project). Basic SVG elements aren't espec...
Are there any pure Python, BSD-ish open source SVG libraries?
I'm looking for a pure Python library to help put together SVG images. It doesn't need to be fast. I know pySVG exists, but I'm not interested in a GPL library (and I can't use GPL libraries for this particular project). Basic SVG elements aren't especially complicated, so I suppose I could roll my own, but I'd rather...
[ "I wrote a library that I use to generate XHTML and SVG and I posted it here. It's pretty easy, each element has a corresponding all upper case class, the __init__ parameters are child elements and keyword parameters are attributes. The Transformable class, inherited by PATH and RECT, have additional functions fo...
[ 2, 1 ]
[]
[]
[ "python", "svg" ]
stackoverflow_0001837262_python_svg.txt
Q: Invalid Token when using Octal numbers I'm a beginner in python and I'm trying to use a octal number in my script, but when I try it, it returns me that error: >>> a = 010 SyntaxError: invalid token (<pyshell#0>, line 1) >>> 01 SyntaxError: invalid token (<pyshell#1>, line 1) There's something wrong with my code?...
Invalid Token when using Octal numbers
I'm a beginner in python and I'm trying to use a octal number in my script, but when I try it, it returns me that error: >>> a = 010 SyntaxError: invalid token (<pyshell#0>, line 1) >>> 01 SyntaxError: invalid token (<pyshell#1>, line 1) There's something wrong with my code? I'm using Python3 (and reading a python 2.2...
[ "Try 0o10, may be because of python 3, or pyshell itself.\nPEP says, \n\noctal literals must now be specified\n with a leading \"0o\" or \"0O\" instead of\n \"0\";\n\nhttp://www.python.org/dev/peps/pep-3127/\n" ]
[ 83 ]
[]
[]
[ "octal", "python", "python_3.x", "syntax" ]
stackoverflow_0001837874_octal_python_python_3.x_syntax.txt
Q: Pulling HTML from a Webpage in Java I want to pull the entire HTML source code file from a website in Java (or Python or PHP if it is easier in those languages to display). I wish only to view the HTML and scan through it with a few methods- not edit or manipulate it in any way, and I really wish that I do not wri...
Pulling HTML from a Webpage in Java
I want to pull the entire HTML source code file from a website in Java (or Python or PHP if it is easier in those languages to display). I wish only to view the HTML and scan through it with a few methods- not edit or manipulate it in any way, and I really wish that I do not write it to a new file unless there is no ot...
[ "In Java:\nURL url = new URL(\"http://stackoverflow.com\");\nURLConnection connection = new URLConnection(url);\nInputStream stream = url.openConnection();\n// ... read stream like any file stream\n\nThis code, is good for scripting purposes and internal use. I would argue against using it for production use thoug...
[ 5, 2, 0 ]
[]
[]
[ "html", "java", "pull", "python", "webpage" ]
stackoverflow_0001837471_html_java_pull_python_webpage.txt
Q: A Friendship relationship question I am having difficulties with listing this type of data. Scenario is as follows: user1 add's a friend called user2 user2 confirms that user1 is his friend what should happen is user2 and user1 see's each others name in their friends list. What's happening now is I am able to ad...
A Friendship relationship question
I am having difficulties with listing this type of data. Scenario is as follows: user1 add's a friend called user2 user2 confirms that user1 is his friend what should happen is user2 and user1 see's each others name in their friends list. What's happening now is I am able to add user2 to user1 friends list but user1 ...
[ "It's not obvious that your friendship model is associative. Is my friends list the list of all friendships in which I am the from_user? Or is it all friendships in which I am either the from_user or the to_user?\nIf it's the former, then every friend relationship is represented by two friendship objects, one ind...
[ 1, 0 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0001836176_django_models_python.txt
Q: Django-based skill implementation I'm working on a RPG using django and am considering different options for implementing part of the skill system. Say I have a base skill class ie, something like: class Skill (models.Model): name = models.CharField() cost = models.PositiveIntegerField() blah bla...
Django-based skill implementation
I'm working on a RPG using django and am considering different options for implementing part of the skill system. Say I have a base skill class ie, something like: class Skill (models.Model): name = models.CharField() cost = models.PositiveIntegerField() blah blah blah What would be some approaches t...
[ "Perhaps you might consider separating a skill and it's associated effect. More that likely, skills will end up having one or more effect associated with them, and that effect could potentially be used by multiple skills.\nFor example, an effect could be \"Does N frost damage to current target\". That effect coul...
[ 5, 1, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001836881_django_python.txt
Q: mysqldb build error i remember installing Python + Django + MySQL + MySQLdb on my 32-bit Mac with Leopard 10.5.7. I tried the same procedure with Mac Snow Leopard. But have unfortunately ran into a lot of errors... i dont know but something weird is happening. Please look at the error log: Amit-Vermas-MacBook:mysq...
mysqldb build error
i remember installing Python + Django + MySQL + MySQLdb on my 32-bit Mac with Leopard 10.5.7. I tried the same procedure with Mac Snow Leopard. But have unfortunately ran into a lot of errors... i dont know but something weird is happening. Please look at the error log: Amit-Vermas-MacBook:mysql-python-1.2.2 amitverma$...
[ "This is my personal makefile rule for that\nMYSQLDB_VERSION=1.2.3c1\nMYSQLDB_TARGET=$(BUILD_FLAGS_DIR)/mysqldb\nMYSQLDB_PACKAGE=MySQL-python-$(MYSQLDB_VERSION).tar.gz\nMYSQLDB_PACKAGE_URL=http://downloads.sourceforge.net/project/mysql-python/mysql-python-test/$(MYSQLDB_VERSION)/$(MYSQLDB_PACKAGE)\n\n.PHONY: mysqld...
[ 1, 1, 0, 0 ]
[]
[]
[ "django", "macos", "osx_snow_leopard", "python" ]
stackoverflow_0001835658_django_macos_osx_snow_leopard_python.txt
Q: Get new dict from old dict with condition? I am an dictionary (Dictionary of dictionary) old_dict = { '1':{'A':1, 'check': 0, 'AA':2, 'AAA':3 , 'status':0}, '2':{'A':11,'check': 0, 'AA':22, 'AAA':33 ,'status':1}, '3':{'A':111,'check': 0, 'AA':222, 'AAA':333 ,'status':0}, '4':{'A':1111,'check': ...
Get new dict from old dict with condition?
I am an dictionary (Dictionary of dictionary) old_dict = { '1':{'A':1, 'check': 0, 'AA':2, 'AAA':3 , 'status':0}, '2':{'A':11,'check': 0, 'AA':22, 'AAA':33 ,'status':1}, '3':{'A':111,'check': 0, 'AA':222, 'AAA':333 ,'status':0}, '4':{'A':1111,'check': 1, 'AA':2222, 'AAA':3333 ,'status':0}, } I ...
[ "Dropping the [] from yu_sha's answer avoids constructing a dummy list:\nnew_dict = dict( (k,v) for k,v in old_dict.iteritems() \n if v[\"status\"] != 0 and v[\"check\"] != 0 )\n\nor\nnew_dict = dict(item for item in old_dict.iteritems() \n if item[1][\"status\"] != 0...
[ 5, 5, 3, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001838549_dictionary_python.txt
Q: Html Agility Pack for python Is there any module for python similar to Html Agility Pack? If not, can anyone recommend me an alternative. Thanks in advance! A: Try Beautiful Soup.
Html Agility Pack for python
Is there any module for python similar to Html Agility Pack? If not, can anyone recommend me an alternative. Thanks in advance!
[ "Try Beautiful Soup.\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0001838637_python.txt
Q: How to split a string in Python? I have read the documentation but don't fully understand how to do it. I understand that I need to have some kind of identifier in the string so that the functions can find where to split the string (unless I can target the first space in the sentence?). So for example how would I ...
How to split a string in Python?
I have read the documentation but don't fully understand how to do it. I understand that I need to have some kind of identifier in the string so that the functions can find where to split the string (unless I can target the first space in the sentence?). So for example how would I split: "Sico87 is an awful python deve...
[ "Use the split method on strings:\n>>> \"Sico87 is an awful python developer\".split(' ', 1)\n['Sico87', 'is an awful python developer']\n\nHow it works:\n\nEvery string is an object. String objects have certain methods defined on them, such as split in this case. You call them using obj.<methodname>(<arguments>).\...
[ 19, 14 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001838674_python_string.txt
Q: python web app logging through pipe? (performance concerned) I'm writing a web app using python with web.py, and I want to implement my own logging system. I'd like to log detailed information about each request that come to python (static files are handled by web servers). Currently I'm thinking about writing the...
python web app logging through pipe? (performance concerned)
I'm writing a web app using python with web.py, and I want to implement my own logging system. I'd like to log detailed information about each request that come to python (static files are handled by web servers). Currently I'm thinking about writing the logs to a pipe. On the other side, there should be cronolog. My m...
[ "Pipes are one of the fastest I/O mechanisms available. It's just a shared buffer. Nothing more. If the receiving end of your pipe is totally overwhelmed, you may have an issue. But you have no evidence of that right now.\nIf you have 10's of processes started by FastCGI, each can have their own independent lo...
[ 1 ]
[]
[]
[ "logging", "pipe", "python" ]
stackoverflow_0001839348_logging_pipe_python.txt
Q: Compressing UTF-8(or other 8-bit encoding) to 7 or fewer bits I wish to take a file encoded in UTF-8 that doesn't use more than 128 different characters, then move it to a 7-bit encoding to save the 1/8 of space. For example, if I have a 16 MB text file that only uses the first 128(ascii) characters, I would like ...
Compressing UTF-8(or other 8-bit encoding) to 7 or fewer bits
I wish to take a file encoded in UTF-8 that doesn't use more than 128 different characters, then move it to a 7-bit encoding to save the 1/8 of space. For example, if I have a 16 MB text file that only uses the first 128(ascii) characters, I would like to shave off the extra bit to reduce the file to 14MB. How would I ...
[ "Just use gzip compression, and save 60-70% with 0% effort!\n", "Do you understand that files are divided into bytes? Thus, if you did that, you'd have 7 bits of the first letter in bytes 1, plus 1 bit of the second letter, then in byte two, you'd have 6 bits of the second letter, and 2 bits of the third, so on. ...
[ 18, 6, 3, 1, 0 ]
[ "What you need is UTF-7.\nEdit: UTF-7 has the advantage of bloating \"only\" special characters, so if special characters are rare in the input, you get far less bytes than by just converting UTF-8 to 7 bit. That's what UTF-7 is for.\n" ]
[ -2 ]
[ "c", "compression", "python", "utf_8" ]
stackoverflow_0001837686_c_compression_python_utf_8.txt
Q: How to grab live text from a URL? Im trying to grab all data(text) coming from a URL which is constantly sending text, I tried using PHP but that would mean having the script running the whole time which it isn’t really made for (I think). So I ended up using a BASH script. At the moment I use wget (I couldn’t get...
How to grab live text from a URL?
Im trying to grab all data(text) coming from a URL which is constantly sending text, I tried using PHP but that would mean having the script running the whole time which it isn’t really made for (I think). So I ended up using a BASH script. At the moment I use wget (I couldn’t get CURL to output the text to a file) wge...
[ "You can do wget --tries=0 --retry-connrefused $URL -O - >> output.txt.\nExplanation: the parameters -O is short for --output-document, and a dash - means standard output. \nThe line command > file means write \"write output of command to file\", and command >> file means \"append output of command to file\" which ...
[ 4, 1, 0, 0 ]
[]
[]
[ "bash", "keep_alive", "php", "python", "wget" ]
stackoverflow_0001839120_bash_keep_alive_php_python_wget.txt
Q: Calculating point of intersection based on angle and speed I have a vector consisting of a point, speed and direction. We will call this vector R. And another vector that only consists of a point and a speed. No direction. We will call this one T. Now, what I am trying to do is to find the shortest intersection po...
Calculating point of intersection based on angle and speed
I have a vector consisting of a point, speed and direction. We will call this vector R. And another vector that only consists of a point and a speed. No direction. We will call this one T. Now, what I am trying to do is to find the shortest intersection point of these two vectors. Since T has no direction, this is prov...
[ "My math could be a bit rusty, but try this:\np and q are the position vectors, d and e are the direction vectors. After time t, you want them to be at the same place:\n(1) p+t*d = q+t*e \nSince you want the direction vector e, write it like this\n(2) e = (p-q)/t + d\nNow you don't need the time t, which you can ca...
[ 1, 0, 0 ]
[ "OK, if I understand you right, you have\nR = [ xy0, v, r ]\n T = [ xy1, v ]\nIf you are concerned about the shortest intersection point, this will be achieved when your positions are identical, and in an Euclidean space this also forces the direction of the second \"thing\" being perpendicular to the first. You ...
[ -2 ]
[ "intersection", "math", "performance", "python", "vector" ]
stackoverflow_0001839567_intersection_math_performance_python_vector.txt
Q: Python split value of a string I am working on a site in Python built on the back of Django(awesome framework, cant get my head around python), I looking to split a string that is returned from a database and I want it to be split when the first space occurs so I tried something like this, {{product.name.split(' ...
Python split value of a string
I am working on a site in Python built on the back of Django(awesome framework, cant get my head around python), I looking to split a string that is returned from a database and I want it to be split when the first space occurs so I tried something like this, {{product.name.split(' ' ,1)}} This did not work and I get...
[ "You can call methods using the {{ }} -- but the method can't require any attributes. \nWhat I would do in this case is add a method on your model that performs the desired behavior. Example:\nclass Product(models.Model):\n ...\n def get_first_name(self):\n if self.name:\n return self.name.pa...
[ 11 ]
[]
[]
[ "django", "python", "string" ]
stackoverflow_0001840165_django_python_string.txt
Q: Automate interaction with a webpage in python I want to automate interaction with a webpage. I've been using pycurl up til now but eventually the webpage will use javascript so I'm looking for alternatives . A typical interaction is "open the page, search for some text, click on a link (which opens a form), fill o...
Automate interaction with a webpage in python
I want to automate interaction with a webpage. I've been using pycurl up til now but eventually the webpage will use javascript so I'm looking for alternatives . A typical interaction is "open the page, search for some text, click on a link (which opens a form), fill out the form and submit". We're deploying on Google ...
[ "Twill and mechanize don't do Javascript, and Qt and Selenium can't run on App Engine ((1)), which only supports pure Python code. I do not know of any pure-Python Javascript interpreter, which is what you'd need to deploy a JS-supporting scraper on App Engine:-(.\nMaybe there's something in Java, which would at l...
[ 6, 4, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "pycurl", "python" ]
stackoverflow_0001836987_google_app_engine_pycurl_python.txt
Q: How do I call a property setter from __init__ I have the following chunk of python code: import hashlib class User: def _set_password(self, value): self._password = hashlib.sha1(value).hexdigest() def _get_password(self): return self._password password = property( fset = _set...
How do I call a property setter from __init__
I have the following chunk of python code: import hashlib class User: def _set_password(self, value): self._password = hashlib.sha1(value).hexdigest() def _get_password(self): return self._password password = property( fset = _set_password, fget = _get_password) def _...
[ "A property is a descriptor, and descriptors only work on new-style classes. Try:\nclass User(object): ...\n\ninstead of:\nclass User: ...\n\nA good guide to descriptors can be found here.\n" ]
[ 14 ]
[]
[]
[ "init", "new_style_class", "python", "setter" ]
stackoverflow_0001840628_init_new_style_class_python_setter.txt
Q: python X.509 asymmetric encryption I'm trying to understand how certificate and asymmetric encryption works. I'm looking for a python library where i can import public or private ca signed certificates and automatically encrypt or decrypt message in string format, i viewed the crypto library embedded in python sou...
python X.509 asymmetric encryption
I'm trying to understand how certificate and asymmetric encryption works. I'm looking for a python library where i can import public or private ca signed certificates and automatically encrypt or decrypt message in string format, i viewed the crypto library embedded in python source, but i don't know how to use the hex...
[ "MeTooCrypto:\n\nM2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL functionality to implement clients and servers; HTTPS extensions to Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing AuthCookies for web sessi...
[ 3 ]
[]
[]
[ "encryption", "encryption_asymmetric", "python", "x509" ]
stackoverflow_0001840720_encryption_encryption_asymmetric_python_x509.txt
Q: Python3: ssl cert information I have been trying to get information regarding expired ssl certificates using python 3 but it would be nice to be able to get as verbose a workup as possible. any takers? So far i have been trying to use urllib.request to get this info (to no avail), does this strike anyone as fooli...
Python3: ssl cert information
I have been trying to get information regarding expired ssl certificates using python 3 but it would be nice to be able to get as verbose a workup as possible. any takers? So far i have been trying to use urllib.request to get this info (to no avail), does this strike anyone as foolish? I have seen some examples of si...
[ "The 3.1.1 documentation for SSL has an example.\n" ]
[ 1 ]
[]
[]
[ "certificate", "python", "ssl", "urllib" ]
stackoverflow_0001840725_certificate_python_ssl_urllib.txt
Q: Can urllib2 make HTTP/1.1 requests? EDIT: This question is invalid. Turns out a transparent proxy was making an onward HTTP 1.0 request even though urllib/httplib was indeed making a HTTP 1.1 request originally. ORIGINAL QUESTION: By default urllib2.urlopen always makes a HTTP 1.0 request. Is there any way to get...
Can urllib2 make HTTP/1.1 requests?
EDIT: This question is invalid. Turns out a transparent proxy was making an onward HTTP 1.0 request even though urllib/httplib was indeed making a HTTP 1.1 request originally. ORIGINAL QUESTION: By default urllib2.urlopen always makes a HTTP 1.0 request. Is there any way to get it to talk HTTP 1.1 ?
[ "Why do you think it's not already using http 1.1? Have you tried something like...:\n>>> import urllib2\n>>> urllib2._opener.handlers[1].set_http_debuglevel(100)\n>>> urllib2.urlopen('http://mit.edu').read()[:10]\nconnect: (mit.edu, 80)\nsend: 'GET / HTTP/1.1\n\n(etc, etc)? This should show it's sending a 1.1 GE...
[ 12, 3 ]
[]
[]
[ "http", "python", "urllib2" ]
stackoverflow_0001840965_http_python_urllib2.txt
Q: How can urllib2 / httplib talk HTTP 1.1 for HTTPS connections via a Squid proxy? When I use urllib2 to make a HTTP 1.1 connection via a squid proxy, squid makes a new ongoing connection in HTTP 1.0. How can I persuade Squid to talk 1.1 to the destination server? A: After dealing with this problem for an entire a...
How can urllib2 / httplib talk HTTP 1.1 for HTTPS connections via a Squid proxy?
When I use urllib2 to make a HTTP 1.1 connection via a squid proxy, squid makes a new ongoing connection in HTTP 1.0. How can I persuade Squid to talk 1.1 to the destination server?
[ "After dealing with this problem for an entire afternoon, i found the solution. So please excuse me answering my own question, but it would be great if someone else finds this useful and it saves them the pain.\nIn order to get Squid to have a HTTP 1.1 conversation with the destination server, the original request ...
[ 3 ]
[]
[]
[ "https", "proxy", "python", "urllib" ]
stackoverflow_0001841730_https_proxy_python_urllib.txt
Q: Using 'try' vs. 'if' in Python Is there a rationale to decide which one of try or if constructs to use, when testing variable to have a value? For example, there is a function that returns either a list or doesn't return a value. I want to check result before processing it. Which of the following would be more pre...
Using 'try' vs. 'if' in Python
Is there a rationale to decide which one of try or if constructs to use, when testing variable to have a value? For example, there is a function that returns either a list or doesn't return a value. I want to check result before processing it. Which of the following would be more preferable and why? result = function()...
[ "You often hear that Python encourages EAFP style (\"it's easier to ask for forgiveness than permission\") over LBYL style (\"look before you leap\"). To me, it's a matter of efficiency and readability.\nIn your example (say that instead of returning a list or an empty string, the function were to return a list or ...
[ 329, 17, 13, 7, 5, 4, 3, 1 ]
[ "As a general rule of thumb, you should never use try/catch or any exception handling stuff to control flow. Even though behind the scenes iteration is controlled via the raising of StopIteration exceptions, you still should prefer your first code snippet to the second.\n" ]
[ -6 ]
[ "python" ]
stackoverflow_0001835756_python.txt
Q: How can I organize each scraped item into a csv row? What is the best way to organize scraped data into a csv? More specifically each item is in this form url "firstName middleInitial, lastName - level - word1 word2 word3, &amp; wordN practice officeCity." JD, schoolName, date Example: http://www.examplefirm.com/...
How can I organize each scraped item into a csv row?
What is the best way to organize scraped data into a csv? More specifically each item is in this form url "firstName middleInitial, lastName - level - word1 word2 word3, &amp; wordN practice officeCity." JD, schoolName, date Example: http://www.examplefirm.com/jang "Joe E. Ang - partner - privatization mergers, media ...
[ "There's really no short cut on this. Line 1 is easy. Just assign it to url. Line 3 can probably be split on , without any ill effects, but line 2 will have to be manually parsed. What do you know about word1-wordN? Are you sure \"practice\" will never be a \"word\". Are you sure the words are only one word l...
[ 2 ]
[]
[]
[ "csv", "django", "python" ]
stackoverflow_0001841903_csv_django_python.txt
Q: Is there a tuple data structure in Python I want to have an 3 item combination like tag, name, and list of values (array) what is the best possible data structure to store such things. Current I am using dictionary, but it only allows 2 items, but easy traversal using for k, v in dict.iteritems(): can we have som...
Is there a tuple data structure in Python
I want to have an 3 item combination like tag, name, and list of values (array) what is the best possible data structure to store such things. Current I am using dictionary, but it only allows 2 items, but easy traversal using for k, v in dict.iteritems(): can we have something similar like: for k, v, x in tuple.iteri...
[ "Python tutorial on data structutres see section 5.3 \"Tuples and sequences\"\nhowever, if you want to use \"name\" to index the data, you probably want to use a dictionary that has the string name as key and values are tuple of (tag, [list, of, values]) e.g.\n d = \n { \"foo\" : (\"dog\", [1,2,3,4]),\n \"...
[ 8, 4, 4, 2, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0001831218_python_tuples.txt
Q: How do I detect if Python is running as a 64-bit application? Possible Duplicate: How do I determine if my python shell is executing in 32bit or 64bit mode? I'm doing some work with the windows registry. Depending on whether you're running python as 32-bit or 64-bit, the key value will be different. How do I det...
How do I detect if Python is running as a 64-bit application?
Possible Duplicate: How do I determine if my python shell is executing in 32bit or 64bit mode? I'm doing some work with the windows registry. Depending on whether you're running python as 32-bit or 64-bit, the key value will be different. How do I detect if Python is running as a 64-bit application as opposed to a 3...
[ "import platform\nplatform.architecture()\n\nFrom the Python docs:\n\nQueries the given executable (defaults\n to the Python interpreter binary) for\n various architecture information.\nReturns a tuple (bits, linkage) which\n contain information about the bit\n architecture and the linkage format\n used for th...
[ 226, 70 ]
[]
[]
[ "64_bit", "python" ]
stackoverflow_0001842544_64_bit_python.txt
Q: Timer object in Django I'm using Django to create registration/payment application for a limited number of products. I want to create a timer so that when a user chooses to purchase a product, that product will then displayed as "already taken". But, if the user the user does not go through with the purchase a...
Timer object in Django
I'm using Django to create registration/payment application for a limited number of products. I want to create a timer so that when a user chooses to purchase a product, that product will then displayed as "already taken". But, if the user the user does not go through with the purchase and the timer runs out, the p...
[ "I would not use a timer for such situation because it can give some complexity. What will happen to your timers if the process is restarted. That't the case with some internet providers who restart the process on a regular basis. Maybe you are facing a similar situation.\nI would add a 'taken_time' datetimefield t...
[ 6, 1, -2 ]
[]
[]
[ "django", "python", "timer" ]
stackoverflow_0001842593_django_python_timer.txt
Q: How to do PyS60 development on OS X Is it possible to do PyS60 development on Mac OS X? There is an XCode-plugin for Symbian C++ -development, but I don't know whether I can create Python-apps for my Nokia phone with that. I'm talking about a more thorough SDK experience than just editing files with Textmate/Emacs...
How to do PyS60 development on OS X
Is it possible to do PyS60 development on Mac OS X? There is an XCode-plugin for Symbian C++ -development, but I don't know whether I can create Python-apps for my Nokia phone with that. I'm talking about a more thorough SDK experience than just editing files with Textmate/Emacs and copying them over to the device.
[ "I'd recommend you add PuTools to your development environment. It allows you to easily sync files between the phone and the computer, and gives you a remote shell with more functions than the default Bluetooth shell.\nThe \"official\" PuTools instructions are written for Windows machines, but the tools definitely ...
[ 3, 1, 1, 0 ]
[]
[]
[ "nokia", "pys60", "python", "s60" ]
stackoverflow_0000790915_nokia_pys60_python_s60.txt
Q: Python's string.maketrans works at home but fails on Google App Engine I have this code in Google AppEngine (Python SDK): from string import maketrans intab = u"ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ".encode('latin1') outtab = u"aaaaaaaaaaaaooooooooooooeeeeeeeecciiiiiiiiuuuuuuuuynn".encode('lati...
Python's string.maketrans works at home but fails on Google App Engine
I have this code in Google AppEngine (Python SDK): from string import maketrans intab = u"ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ".encode('latin1') outtab = u"aaaaaaaaaaaaooooooooooooeeeeeeeecciiiiiiiiuuuuuuuuynn".encode('latin1') logging.info(len(intab)) logging.info(len(outtab)) trantab = maketrans...
[ "string.maketrans and string.translate do not work for Unicode strings. Your call to string.maketrans will implictly convert the Unicode you gave it to an encoding like utf-8. In utf-8 å takes up more space than ASCII a. string.maketrans sees len(str(argument)) which is different for your two strings.\nThere is a U...
[ 15, 1 ]
[]
[]
[ "google_app_engine", "internationalization", "python", "translation" ]
stackoverflow_0001842692_google_app_engine_internationalization_python_translation.txt
Q: parsing large compressed xml files, python file = BZ2File(SOME_FILE_PATH) p = xml.parsers.expat.ParserCreate() p.Parse(file) Here's code that tries to parse xml file compressed with bz2. Unfortunately it fails with a message: TypeError: Parse() argument 1 must be string or read-only buffer, not bz2.BZ2File Is th...
parsing large compressed xml files, python
file = BZ2File(SOME_FILE_PATH) p = xml.parsers.expat.ParserCreate() p.Parse(file) Here's code that tries to parse xml file compressed with bz2. Unfortunately it fails with a message: TypeError: Parse() argument 1 must be string or read-only buffer, not bz2.BZ2File Is there a way to parse on the fly compressed bz2 xml...
[ "Just use p.ParseFile(file) instead of p.Parse(file).\nParse() takes a string, ParseFile() takes a file handle, and reads the data in as required.\nRef: http://docs.python.org/library/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile\n", "Use .read() on the file object to read in the entire file as a string, and...
[ 5, 1, 0 ]
[]
[]
[ "bzip", "compression", "python" ]
stackoverflow_0001843009_bzip_compression_python.txt
Q: Hadoop MapReduce job on file containing HTML tags I have a bunch of large HTML files and I want to run a Hadoop MapReduce job on them to find the most frequently used words. I wrote both my mapper and reducer in Python and used Hadoop streaming to run them. Here is my mapper: #!/usr/bin/env python import sys im...
Hadoop MapReduce job on file containing HTML tags
I have a bunch of large HTML files and I want to run a Hadoop MapReduce job on them to find the most frequently used words. I wrote both my mapper and reducer in Python and used Hadoop streaming to run them. Here is my mapper: #!/usr/bin/env python import sys import re import string def remove_html_tags(in_text): '...
[ "You can reproduce the bug even with just:\necho \"hello - world\" | ./mapper.py | sort | ./reducer.py\n\nThe issue is here:\nif word =='': continue\nfor c in string.punctuation:\n word= word.replace(c,'')\n\nIf word is a single punctuation mark, as would be the case for the above input (after it is spli...
[ 1 ]
[]
[]
[ "hadoop", "mapreduce", "python" ]
stackoverflow_0001842747_hadoop_mapreduce_python.txt
Q: Django ManyToMany relation add() error I've got a model that looks like this, class PL(models.Model): locid = models.AutoField(primary_key=True) mentionedby = models.ManyToManyField(PRT) class PRT(models.Model): tid = .. The resulting many to many table in mysql is formed as, +------------------+----...
Django ManyToMany relation add() error
I've got a model that looks like this, class PL(models.Model): locid = models.AutoField(primary_key=True) mentionedby = models.ManyToManyField(PRT) class PRT(models.Model): tid = .. The resulting many to many table in mysql is formed as, +------------------+------------+------+-----+---------+------------...
[ "Adding prt directly should work on first try. How are you retrieving pl and prt? Assuming you have some data in your database, try those commands from the Django shell and see if it works. There seems to be some missing information from the question. After running python manage.py shell:\nfrom yourapp.models i...
[ 6, 0 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0001226290_django_django_models_many_to_many_python.txt
Q: Check whether a connection exists to a remote host using paramiko I'm using single object of paramiko.SSHClient() for executing a command on a remote machine. When I use ssh.exec_command(cmd), and the connection to remote host is lost, ssh.exec_command hangs up. Is there a way to check for connection existence bef...
Check whether a connection exists to a remote host using paramiko
I'm using single object of paramiko.SSHClient() for executing a command on a remote machine. When I use ssh.exec_command(cmd), and the connection to remote host is lost, ssh.exec_command hangs up. Is there a way to check for connection existence before ssh.exec_command()?
[ "If you have a long running SSH connection, you may want to use the Keep Alive parameter via Transport.set_keepalive.\n", "As an alternate possibility, maybe execnet would work. It wraps the command line ssh command instead, so it's definitely not the paramiko approach... just a though.\n" ]
[ 2, 0 ]
[]
[]
[ "paramiko", "python", "ssh" ]
stackoverflow_0001796106_paramiko_python_ssh.txt
Q: how to fix or make an exception for this error I'm creating a code that gets image's urls from any web pages, the code are in python and use BeutifulSoup and httplib2. When I run the code, I get the next error: Look me http://movies.nytimes.com (this line is printed by the code) Traceback (most recent cal...
how to fix or make an exception for this error
I'm creating a code that gets image's urls from any web pages, the code are in python and use BeutifulSoup and httplib2. When I run the code, I get the next error: Look me http://movies.nytimes.com (this line is printed by the code) Traceback (most recent call last): File "main.py", line 103, in <module> visit...
[ "Are you using latest version of BeautifulSoup?\nThis seems a known issue of version 3.1.x, because it started using a new parser (HTMLParser, instead of SGMLParser) that is much worse at processing malformed HTML. You can find more information about this on BeautifulSoup website.\nAs a quick solution, you can simp...
[ 4, 2, 0 ]
[]
[]
[ "beautifulsoup", "httplib2", "python" ]
stackoverflow_0001100029_beautifulsoup_httplib2_python.txt
Q: starting my own threads within python paste I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on. If I start a thread to do this work, is that OK? I al...
starting my own threads within python paste
I'm writing a web application using pylons and paste. I have some work I want to do after an HTTP request is finished (send some emails, write some stuff to the db, etc) that I don't want to block the HTTP request on. If I start a thread to do this work, is that OK? I always see this stuff about paste killing off hung ...
[ "You could use a thread approach (maybe setting the Thead.daemon property would help--but I'm not sure). \nHowever, I would suggest looking into a task queuing system. You can place a task on a queue (which is very fast), then a listener can handle the tasks asynchronously, allowing the HTTP request to return quic...
[ 0, 0, 0, 0 ]
[]
[]
[ "paste", "pylons", "python" ]
stackoverflow_0001604079_paste_pylons_python.txt
Q: Any python "compiler" that can statically link the python2x.dll dependency? It's my understanding that py2exe can only dynamically link a python2x.dll file. Are there any Python "compilers" out there that can package it all into one standalone .exe file for easier portability? If so or if not, which is the best c...
Any python "compiler" that can statically link the python2x.dll dependency?
It's my understanding that py2exe can only dynamically link a python2x.dll file. Are there any Python "compilers" out there that can package it all into one standalone .exe file for easier portability? If so or if not, which is the best compiler z0mg!
[ "If you check the bottom of the py2exe SingleFileExecutable wiki page you'll see that it can create one-file executables. They do include the DLL inside, but you shouldn't notice that. I believe it works with a freakish hack that intercepts the LoadLibrary calls to allow them to read from elsewhere in the .exe fi...
[ 2, 1, 0, 0 ]
[]
[]
[ "compilation", "dll", "py2exe", "python" ]
stackoverflow_0001720893_compilation_dll_py2exe_python.txt
Q: several lexers for one parser with PLY? I'm trying to implement a python parser using PLY for the Kconfig language used to generate the configuration options for the linux kernel. There's a keyword called source which performs an inclusion, so what i do is that when the lexer encounters this keyword, I change the ...
several lexers for one parser with PLY?
I'm trying to implement a python parser using PLY for the Kconfig language used to generate the configuration options for the linux kernel. There's a keyword called source which performs an inclusion, so what i do is that when the lexer encounters this keyword, I change the lexer state to create a new lexer which is go...
[ "I don't know about the details of PLY, but in other systems like this that I've built, it made the most sense to have a single lexer which managed the stack of include files. So the lexer would return a unified stream of tokens, opening and closing include files as they were encountered.\n", "By an interesting ...
[ 2, 2, 0 ]
[]
[]
[ "lexer", "ply", "python" ]
stackoverflow_0001718067_lexer_ply_python.txt
Q: Sending movie stream from client to server. The python server should play the stream on the fly I would like to simulate some kind of camera on a UAV. The camera should provide a live stream, and send the stream over a network connection to a server. The server should be able to play the stream on the fly for me t...
Sending movie stream from client to server. The python server should play the stream on the fly
I would like to simulate some kind of camera on a UAV. The camera should provide a live stream, and send the stream over a network connection to a server. The server should be able to play the stream on the fly for me to see. I was thinking the client(UAV) just read a moviefile and sent it to the server. But how can th...
[ "try 'webcam'\nsudo apt-get install webcam\n\non debian.\nIt will grab images from a USB camera and put them in a jpg file in /var/www/ then you make an html page that auto-refreshes as fast as possible that points to the image file.\nI know its not a very elegant solution but its the only one I know of.\nIf you re...
[ 0 ]
[]
[]
[ "movie", "network_programming", "python", "streaming" ]
stackoverflow_0001842583_movie_network_programming_python_streaming.txt
Q: Strings are wrapped in b'...' import urllib.request #name = input("What is your screenname? "); name = "zezima" page = urllib.request.urlopen('http://hiscore.runescape.com/index_lite.ws?player=' + name) page = page.readlines() skills = [] for line in page: skills += [line] print(skills) Outputs: [[b'478,2372...
Strings are wrapped in b'...'
import urllib.request #name = input("What is your screenname? "); name = "zezima" page = urllib.request.urlopen('http://hiscore.runescape.com/index_lite.ws?player=' + name) page = page.readlines() skills = [] for line in page: skills += [line] print(skills) Outputs: [[b'478,2372,1224928266\n'], [b'458,99,595021...
[ "\"b\" means byte array.\nYou can refer to this question for a solution.\n" ]
[ 6 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001844034_python_python_3.x.txt
Q: User authentication in Django I learned how to authenticate users in Django months ago, but I've since upgraded and am having some problems so it occurred to me this morning that I may not have been doing it correctly from the start so I decided to ask. In my project's urls.py file I've got ^accounts/login/$ and ^...
User authentication in Django
I learned how to authenticate users in Django months ago, but I've since upgraded and am having some problems so it occurred to me this morning that I may not have been doing it correctly from the start so I decided to ask. In my project's urls.py file I've got ^accounts/login/$ and ^accounts/logout/$ both wired up to ...
[ "This answer is tangential, but Jim's suggestion to use RequestContext is so good I want to explicitly explain how to do it.\nYou can reduce your start_here function to \nfrom django.template import RequestContext\n\ndef start_here(request):\n return render_to_response(\"profile.html\", {},\n context_inst...
[ 6, 1, 1 ]
[]
[]
[ "authentication", "django", "django_templates", "python" ]
stackoverflow_0001843535_authentication_django_django_templates_python.txt
Q: How to get back to the for loop after exception handling I am ready to run this code but before I want to fix the exception handling: for l in bios: OpenThisLink = url + l try: response = urllib2.urlopen(OpenThisLink) except urllib2.HTTPError: pass bio = response.read() item = r...
How to get back to the for loop after exception handling
I am ready to run this code but before I want to fix the exception handling: for l in bios: OpenThisLink = url + l try: response = urllib2.urlopen(OpenThisLink) except urllib2.HTTPError: pass bio = response.read() item = re.search('(JD)(.*?)(\d+)', bio) .... As suggested here, I...
[ "Use continue instead of break.\nThe statement pass is a no-op (meaning that it doesn't do anything). The program just continues to the next statement, which is why you get an error.\nbreak exits the loops and continues running from the next statement immediately after the loop. In this case, there are no more stat...
[ 53, 19, 1 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0001843659_exception_handling_python.txt
Q: Facebook login without opening another window/popup Is it possible for web application that is created by the same owner as facebook application to have access to facebook application without going through a explicit session opening exercise? Most of the work is done on server side and I need to access facebook ap...
Facebook login without opening another window/popup
Is it possible for web application that is created by the same owner as facebook application to have access to facebook application without going through a explicit session opening exercise? Most of the work is done on server side and I need to access facebook application directly from backend server. Each time the web...
[ "The opening of a window for facebook auth is the way facebook set up their authentication for facebook connect.\nI don't think they offer another way of authenticating users, and I doubt you'd be able to work-around/circumvent this method without breaking their terms of use\nSorry I don't have better news for you ...
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0001842360_facebook_python.txt
Q: How do I get urllib2 to log ALL transferred bytes I'm writing a web-app that uses several 3rd party web APIs, and I want to keep track of the low level request and responses for ad-hock analysis. So I'm looking for a recipe that will get Python's urllib2 to log all bytes transferred via HTTP. Maybe a sub-classed H...
How do I get urllib2 to log ALL transferred bytes
I'm writing a web-app that uses several 3rd party web APIs, and I want to keep track of the low level request and responses for ad-hock analysis. So I'm looking for a recipe that will get Python's urllib2 to log all bytes transferred via HTTP. Maybe a sub-classed Handler?
[ "Well, I've found how to setup the built-in debugging mechanism of the library:\nimport logging, urllib2, sys\n\nhh = urllib2.HTTPHandler()\nhsh = urllib2.HTTPSHandler()\nhh.set_http_debuglevel(1)\nhsh.set_http_debuglevel(1)\nopener = urllib2.build_opener(hh, hsh)\nlogger = logging.getLogger()\nlogger.addHandler(lo...
[ 12, 2 ]
[]
[]
[ "http", "logging", "python", "urllib2" ]
stackoverflow_0001170744_http_logging_python_urllib2.txt
Q: Remove a sublayout in qt? In PyQt 4.5, I have a layout inside another layout. I'd like to remove the sublayout from its parent, and hide it. I can say parent_layout.removeItem(child_layout) to remove the layout from its parent, but it still shows on the widget. I can't find any way to hide it in one step, as QL...
Remove a sublayout in qt?
In PyQt 4.5, I have a layout inside another layout. I'd like to remove the sublayout from its parent, and hide it. I can say parent_layout.removeItem(child_layout) to remove the layout from its parent, but it still shows on the widget. I can't find any way to hide it in one step, as QLayout doesn't have a hide() met...
[ "The easy solution would be to have an interior widget, not an interior layout. You could assign the layout you desire to the widget, then just remove/hide the widget when you want to do so. A good rule of thumb is if you just want to arrange how widgets appear, then use a layout; if you want to hide/show them as...
[ 4, 1 ]
[]
[]
[ "pyqt", "python", "qt4" ]
stackoverflow_0001844630_pyqt_python_qt4.txt
Q: Windows impersonation for WMI calls via python? I'm using PyWin32 to make WMI calls to the system in python from my django web application. My goal is to allow users to add printers to the system via a web interface. To do this, I'm using win32print.AddPrinterConnection. This works well running the development ser...
Windows impersonation for WMI calls via python?
I'm using PyWin32 to make WMI calls to the system in python from my django web application. My goal is to allow users to add printers to the system via a web interface. To do this, I'm using win32print.AddPrinterConnection. This works well running the development server under my user account. I can add all the printers...
[ "I can't help with the specific problem, but I do know that if I had to work with WMI stuff on Windows, with Python, I would definitely reach for Tim Golden's Python WMI module instead of pywin32. Perhaps in the documentation/cookbook or Google searches using that module you can find a solution.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "pywin32", "wmi" ]
stackoverflow_0001464894_django_python_pywin32_wmi.txt
Q: AJAX upload in Python (WSGI) without Flash/Silverlight, with progress bar I am looking for a pure Javascript/Python upload example, that uses server polling instead of client-side SWF to display upload progress (like the one on rapidshare.com for example) Currently, website is running on the standalone wsgi server...
AJAX upload in Python (WSGI) without Flash/Silverlight, with progress bar
I am looking for a pure Javascript/Python upload example, that uses server polling instead of client-side SWF to display upload progress (like the one on rapidshare.com for example) Currently, website is running on the standalone wsgi server included with Werkzeug framework, but may be moved to mod_wsgi if the load inc...
[ "If you don't have support on the web side to track the size of the temporary file (or in-memory buffer) of the uploading data as it arrives, I don't know how you'll do this. Some of the popular web servers have special support for this, mostly experimental, but it's not widely supported and what you're trying to ...
[ 0 ]
[]
[]
[ "ajax", "progress", "python", "upload", "werkzeug" ]
stackoverflow_0001284922_ajax_progress_python_upload_werkzeug.txt
Q: Regular expression to replace with XML node I'm using Python to write a regular expression for replacing parts of the string with a XML node. The source string looks like: Hello REPLACE(str1) this is to replace REPLACE(str2) this is to replace And the result string should be like: Hello <replace name="str1"> th...
Regular expression to replace with XML node
I'm using Python to write a regular expression for replacing parts of the string with a XML node. The source string looks like: Hello REPLACE(str1) this is to replace REPLACE(str2) this is to replace And the result string should be like: Hello <replace name="str1"> this is to replace </replace> <replace name="str2">...
[ "What makes your problem a little bit tricky is that you want to match inside of a multiline string. You need to use the re.MULTILINE flag to make that work.\nThen, you need to match some groups inside your source string, and use those groups in the final output. Here is code that works to solve your problem:\nim...
[ 5, 4, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001842608_python_regex.txt
Q: exec() bytecode with arbitrary locals? Suppose I want to execute code, for example value += 5 inside a namespace of my own (so the result is essentially mydict['value'] += 5). There's a function exec(), but I have to pass a string there: exec('value += 5', mydict) and passing statements as strings seems...
exec() bytecode with arbitrary locals?
Suppose I want to execute code, for example value += 5 inside a namespace of my own (so the result is essentially mydict['value'] += 5). There's a function exec(), but I have to pass a string there: exec('value += 5', mydict) and passing statements as strings seems strange (e.g. it's not colorized that way)....
[ "You can pass bytecode instead of a string to exec, you just need to make the right bytecode for the purpose:\n>>> bytecode = compile('value += 5', '<string>', 'exec')\n>>> mydict = {'value': 23}\n>>> exec(bytecode, mydict)\n>>> mydict['value']\n28\n\nSpecifically, ...:\n>>> import dis\n>>> dis.dis(bytecode)\n 1 ...
[ 7, 3, 3, 0 ]
[]
[]
[ "bytecode", "codeblocks", "python", "python_3.x" ]
stackoverflow_0001280100_bytecode_codeblocks_python_python_3.x.txt
Q: Problem with the size of the arrows on a vector field plot I would like to know how can I make it so the arrows have a length of sqrt(2) (as their x and y coordinates have length 1). As you can see for the picture shown bellow, they seem quite small. Thanks! from pylab import * from numpy import ma X = (0,...
Problem with the size of the arrows on a vector field plot
I would like to know how can I make it so the arrows have a length of sqrt(2) (as their x and y coordinates have length 1). As you can see for the picture shown bellow, they seem quite small. Thanks! from pylab import * from numpy import ma X = (0, 0, 0) Y = (0, 1, 2) quiver(X, Y, (1, 1, 1), (1, 1, 1)) #axis([...
[ "This will produce arrows sqrt(2) in proportion to the y axis.\npylab.quiver(X,Y,(1,1,1),(1,1,1), scale=2**.5, units='y')\n\nIt was in the documentation.\nHere is an example.\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0001844467_matplotlib_python.txt
Q: What modules ought I to consider in Python if I wish to use CGI sessions? Given that I know no web frameworks in Python and would like to keep it Very Simple at the moment (as I am Very Stupid), for what is a prototype of sketchy longevity, are there any streamlined, simple, "batteries-included" modules for this? ...
What modules ought I to consider in Python if I wish to use CGI sessions?
Given that I know no web frameworks in Python and would like to keep it Very Simple at the moment (as I am Very Stupid), for what is a prototype of sketchy longevity, are there any streamlined, simple, "batteries-included" modules for this? (It is also too early in my Python career to evaluate frameworks, select one, ...
[ "I think the web2py (web framework) is easy enough for you. I think it is the simplest approach of making a website or webservice. It will be also easier, than to understand Cookie or the other modules of python related to web-things.\nYou can start a session, by just typing:\nsession.your_session_name = \"blabla\"...
[ 3, 0, 0 ]
[]
[]
[ "python", "session" ]
stackoverflow_0001843022_python_session.txt
Q: Programmatically pass unknown number of parameters in Python I'd like an easy way to plug in a function and arguments to be executed later so I can have a kind of wrapper around it. In this case, I'd like to use it to benchmark, example: def timefunc(fn, *args): start = time.clock() fn(args) stop = time.c...
Programmatically pass unknown number of parameters in Python
I'd like an easy way to plug in a function and arguments to be executed later so I can have a kind of wrapper around it. In this case, I'd like to use it to benchmark, example: def timefunc(fn, *args): start = time.clock() fn(args) stop = time.clock() return stop - start How do I pass arguments where the n...
[ "Just call the function like this:\nfn(*args)\n\n", "MatrixFrog's answer is the correct one, but just to complete the picture. For finding out the number of arguments simply call len, because args is a tuple:\nimport time\n\ndef timefunc(fn, *args):\n start = time.clock()\n print len(args), type(args)\n fn(...
[ 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001844705_python.txt
Q: 'setup.py test' egg install location? I have all the eggs my project requires pre-downloaded in a directory, and I would like setuptools to only install packages from that directory. In my setup.cfg I have: [easy_install] allow_hosts = None find_links = ../../setup I run python setup.py develop and it finds and i...
'setup.py test' egg install location?
I have all the eggs my project requires pre-downloaded in a directory, and I would like setuptools to only install packages from that directory. In my setup.cfg I have: [easy_install] allow_hosts = None find_links = ../../setup I run python setup.py develop and it finds and installs all the packages correctly. For tes...
[ "Just looking at the source code (setuptools/command/tests.py), it doesn't look like setup.py test is not supposed to install anything by design (it is testing, so why put anything in site-packages?). It uses fetch_build_egg (setuptools/dist.py) to get the eggs, which actually does a local easy_install. I suspect...
[ 3 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0001843424_python_setuptools.txt
Q: How to set shell variables in subprocess.Popen (in a less ugly way...) NOTE: This is not the same question as Python: Persistent shell variables in subprocess, as that question is actually about environment variables, not shell variables. I'm trying to automate a basic benchmark that I'm doing in csh using the she...
How to set shell variables in subprocess.Popen (in a less ugly way...)
NOTE: This is not the same question as Python: Persistent shell variables in subprocess, as that question is actually about environment variables, not shell variables. I'm trying to automate a basic benchmark that I'm doing in csh using the shell built-in time command. You can tweak the output of time by setting the v...
[ "You have a limited number of options to communicate to a child process (invocation arguments, environment, and streams). Since setting a shell variable is in a more general sense modifying a child process's internal state, what you call a \"kludge\" is actually quite reasonable. I don't know of any csh variants ...
[ 1 ]
[]
[]
[ "freebsd", "python", "shell", "subprocess", "unix" ]
stackoverflow_0001845435_freebsd_python_shell_subprocess_unix.txt
Q: Can I CREATE TEMPORARY TABLE in SQLAlchemy without appending to Table._prefixes? I'd like to create a temporary table in SQLAlchemy. I can build a CREATE TABLE statement with a TEMPORARY clause by calling table._prefixes.append('TEMPORARY') against a Table object, but that's less elegant than table.select().prefix...
Can I CREATE TEMPORARY TABLE in SQLAlchemy without appending to Table._prefixes?
I'd like to create a temporary table in SQLAlchemy. I can build a CREATE TABLE statement with a TEMPORARY clause by calling table._prefixes.append('TEMPORARY') against a Table object, but that's less elegant than table.select().prefix_with() used to add a prefix to data manipulation language expressions. Is there an eq...
[ "No, prefix_with() is defined for SELECT and INSERT only. But convenient way to add prefix to CREATE TABLE statement is passing it into table definition:\nt = Table(\n 't', metadata,\n Column('id', Integer, primary_key=True),\n # ...\n prefixes=['TEMPORARY'],\n)\n\n" ]
[ 11 ]
[]
[]
[ "python", "sqlalchemy", "temp_tables" ]
stackoverflow_0001842902_python_sqlalchemy_temp_tables.txt
Q: Bignum implementation that has efficient addition of small integers I have been using python's native bignums for an algorithm and decided to try and speed it up by converting it to C++. When I used long longs, the C++ was about 100x faster than the python, but when I used GMP bindings in C++, it was only 10x fast...
Bignum implementation that has efficient addition of small integers
I have been using python's native bignums for an algorithm and decided to try and speed it up by converting it to C++. When I used long longs, the C++ was about 100x faster than the python, but when I used GMP bindings in C++, it was only 10x faster than the python (for the same cases that fit in long longs). Is there ...
[ "The GMP library itself has a fast short integer add to MPZ routine\nvoid mpz_add_ui (mpz_t rop, mpz_t op1, unsigned long int op2)\n\nI don't know whether gmpy uses that, but if it does try adding a normal python int to an mpz vs adding an mpz to mpz and see if it is quicker.\nEdit\nI tried a bit of benchmarking an...
[ 2, 0, 0 ]
[]
[]
[ "arbitrary_precision", "bignum", "c++", "gmp", "python" ]
stackoverflow_0001831212_arbitrary_precision_bignum_c++_gmp_python.txt
Q: Matrices and inverse Matrices in Python For a project that I am doing, I decompose a graph that I created using NetworkX into an adjacency matrix using the NetworkX adj_matrix() function. However, one of the problems that I have come across is that every single graph that I decompose gives me the following error w...
Matrices and inverse Matrices in Python
For a project that I am doing, I decompose a graph that I created using NetworkX into an adjacency matrix using the NetworkX adj_matrix() function. However, one of the problems that I have come across is that every single graph that I decompose gives me the following error when I try to find the inverse of the matrix. ...
[ "Adjacency matrices are not always invertible. There are papers on this subject; I'm not sure whether there is any simple characterization of the corresponding graphs. A pragmatic approach would be to catch the LinAlgError exception in your code (try… except…), and warn when the adjacency matrix is not invertible...
[ 4, 2, 1 ]
[]
[]
[ "matrix", "matrix_inverse", "networkx", "python" ]
stackoverflow_0001845209_matrix_matrix_inverse_networkx_python.txt
Q: Patterns for dealing with memcache Caching in Django I have a big Django project with several interrelated projects and a lot of caching in use. It currently has a file which stores cache helper functions. So for example, get_object_x(id) would check cache for this object and if it wasn't there, go to the DB and p...
Patterns for dealing with memcache Caching in Django
I have a big Django project with several interrelated projects and a lot of caching in use. It currently has a file which stores cache helper functions. So for example, get_object_x(id) would check cache for this object and if it wasn't there, go to the DB and pull it from there and return it, caching it along the way....
[ "A general Python pattern for avoiding circular imports is to put one set of the imports inside the dependent functions:\n# module_a.py\nimport module_b\n\ndef foo():\n return \"bar\"\n\ndef bar():\n return module_b.baz()\n\n# module_b.py\ndef baz():\n import module_a\n return module_a.foo()\n\nAs for c...
[ 7, 3 ]
[]
[]
[ "django", "memcached", "python" ]
stackoverflow_0001844432_django_memcached_python.txt
Q: Python long multiplication I'm in need of an algorithm faster than the current normal Python long multiplication. I tried to find a decent Karatsuba implementation, but I can't. def main(): a=long(raw_input()) if(a<0): a=a*-1 a=((a*(a+1)/2)-1) print(-a) else: a=(a*(a+1))...
Python long multiplication
I'm in need of an algorithm faster than the current normal Python long multiplication. I tried to find a decent Karatsuba implementation, but I can't. def main(): a=long(raw_input()) if(a<0): a=a*-1 a=((a*(a+1)/2)-1) print(-a) else: a=(a*(a+1))/2 print(a) main() As y...
[ "I'm the author of the DecInt (Decimal Integer) library so I'll make a few comments.\nThe DecInt library was specifically designed to work with very large integers that needed to be converted to decimal format. The problem with converting to decimal format is that most arbitrary-precision libraries store values in ...
[ 27, 9, 2, 2 ]
[]
[]
[ "biginteger", "multiplication", "python" ]
stackoverflow_0001835857_biginteger_multiplication_python.txt
Q: Submenu items in Nautilus right-click menu I am trying to write an extension for nautilus, which add an item to the menu that appears when you right-click a file (as shown in image) However, I would like to add a submenu to my custom menu item. I downloaded a 'nautilus-python' package which includes examples of h...
Submenu items in Nautilus right-click menu
I am trying to write an extension for nautilus, which add an item to the menu that appears when you right-click a file (as shown in image) However, I would like to add a submenu to my custom menu item. I downloaded a 'nautilus-python' package which includes examples of how to write extensions for Nautilus (and so far ...
[ "I found the solution.\n\nyou need a init function declared.\nhad to make some variable name change to the example above\nimport nautilus\n\nclass ExampleMenuProvider(nautilus.MenuProvider):\n def __init__(self):\n pass\n\n def get_file_items(self, window, files):\n submenu = nautilus.Menu()\n\n...
[ 4 ]
[]
[]
[ "gnome", "gtk", "nautilus", "python" ]
stackoverflow_0001845681_gnome_gtk_nautilus_python.txt
Q: Howto Embed , load .swf into Pygame? How can I load a .swf(flash) file in Pygame? A: As far as I know, Pygame does not have a browser widget that supports playing flash. To get this working, you'll have to embed a window from a web browser that does (i.e. FireFox, IE, Safari, etc). Alternatively, you can use Pyt...
Howto Embed , load .swf into Pygame?
How can I load a .swf(flash) file in Pygame?
[ "As far as I know, Pygame does not have a browser widget that supports playing flash. To get this working, you'll have to embed a window from a web browser that does (i.e. FireFox, IE, Safari, etc).\nAlternatively, you can use Python's C/C++ interface integrate the GNU Gnash project (an open source flash player) in...
[ 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0001844535_pygame_python.txt
Q: game design - handling bonuses / duck typing - python I am currently faced with a design problem in my game design, not terrible but it bothers me enough so I want to ask others opinions :-) I am currently experimenting with pygame, I have developed a little space shooter and now I would like to handle some bonuse...
game design - handling bonuses / duck typing - python
I am currently faced with a design problem in my game design, not terrible but it bothers me enough so I want to ask others opinions :-) I am currently experimenting with pygame, I have developed a little space shooter and now I would like to handle some bonuses. Right now I have an abstract class Bonus from which deri...
[ "If you don't want a certain col to go in player.bonuses but elsewhere, make a toplayer method in the abstract class Bonus with the default implementation:\ndef toplayer(self, player):\n player.bonuses.append(self)\n\nand override it in the bomb bonus class. (You don't have to inherit, as you mention, but there...
[ 1, 1, 0, 0 ]
[]
[]
[ "duck_typing", "pygame", "python" ]
stackoverflow_0001085532_duck_typing_pygame_python.txt
Q: Django makes strange multiple GET calls on admin-site My Django-Project is making some strange faned-out GET calls when opening on model from the admin-site and i have no idea where this comes from. I will try to provide as much information possible. Imagine this model called 'Rating', which holds a reference i.e....
Django makes strange multiple GET calls on admin-site
My Django-Project is making some strange faned-out GET calls when opening on model from the admin-site and i have no idea where this comes from. I will try to provide as much information possible. Imagine this model called 'Rating', which holds a reference i.e. foreign key to 'Item', 'Usecase' and 'Rater'. So the Item ...
[ "I'd be interested to see the admin.py for that app. I'd guess there's something wrong in the media definitions for the form - the clue is the 'js' at the end of the list. You're probably using a string somewhere Django is expecting a tuple.\n" ]
[ 2 ]
[]
[]
[ "django", "get", "python" ]
stackoverflow_0001846571_django_get_python.txt
Q: Python mechanize loses attributes on second open This is a really specialized case and I feel awkward asking it; however I'm at wits end working on it. I need to follow a tracking number through a form and to a results page so I've been using mechanize in python, the link after form submission is embedded in java...
Python mechanize loses attributes on second open
This is a really specialized case and I feel awkward asking it; however I'm at wits end working on it. I need to follow a tracking number through a form and to a results page so I've been using mechanize in python, the link after form submission is embedded in javascript so I can't simply follow_link. What I want to d...
[ "You never make first .read method call on Browser instance. That's because it doesn't have such method. The Browswer.response has read method, so if you want to get the body of response you'd need to do:\nresponse = br.response()\nresponse.read()\n\nFor the future, you could use dir(obj) to see the content of the ...
[ 7 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0001846476_mechanize_python.txt
Q: Getting python.exe path at run time On Windows, how do I find the path to python.exe from within a script at runtime? A: >>> import sys >>> sys.executable 'C:\\Program Files\\Python31\\pythonw.exe'
Getting python.exe path at run time
On Windows, how do I find the path to python.exe from within a script at runtime?
[ ">>> import sys\n>>> sys.executable\n'C:\\\\Program Files\\\\Python31\\\\pythonw.exe'\n\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0001846888_python.txt
Q: Pivoting SQLite table, setwise like SQL should be I have some data. 224,000 rows of it, in a SQLite database. I want to extract time series information from it to feed a data visualisation tool. Essentially, each row in the db is an event that has (among other things not strictly relevant) a time-date group in sec...
Pivoting SQLite table, setwise like SQL should be
I have some data. 224,000 rows of it, in a SQLite database. I want to extract time series information from it to feed a data visualisation tool. Essentially, each row in the db is an event that has (among other things not strictly relevant) a time-date group in seconds since the epoch and a name responsible for it. I w...
[ "A good approach in cases like this is not to push SQL to the point where it becomes convoluted and hard to understand and maintain. Let SQL do what it conveniently can and post-process the query results in Python.\nHere's a cut-down version of a simple crosstab generator that I wrote. The full version delivers row...
[ 4, 1 ]
[]
[]
[ "python", "sql", "sqlite", "visualization" ]
stackoverflow_0001835391_python_sql_sqlite_visualization.txt
Q: how to find list of modules which depend upon a specific module in python In order to reduce development time of my Python based web application, I am trying to use reload() for the modules I have recently modified. The reload() happens through a dedicated web page (part of the development version of the web app) ...
how to find list of modules which depend upon a specific module in python
In order to reduce development time of my Python based web application, I am trying to use reload() for the modules I have recently modified. The reload() happens through a dedicated web page (part of the development version of the web app) which lists the modules which have been recently modified (and the modified tim...
[ "So - this answers \"Find a list of modules which depend on a given one\" - instead of how the question was initally phrased - which I answered above.\nAs it turns out, this is a bit more complex: One have to find the dependency tree for all loaded modules, and invert it for each module, while preserving a loading ...
[ 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001827629_python.txt
Q: I'm looking for a cross-platform Python library that can play MP3 and OGG and support ALSA or similar There are several different audio libraries, however, none of them meet my exact needs: - It needs to be cross-platform. - It needs to be able to use the ALSA, PulseAudio or any other common default mixer under Li...
I'm looking for a cross-platform Python library that can play MP3 and OGG and support ALSA or similar
There are several different audio libraries, however, none of them meet my exact needs: - It needs to be cross-platform. - It needs to be able to use the ALSA, PulseAudio or any other common default mixer under Linux. - It needs to be able to autodetect the sample frequency. - It needs to be (fairly) simple in usage, i...
[ "Use gstreamer.\n\n\n\nIt needs to be cross-platform.\nIt needs to be able to use the ALSA, PulseAudio or any other common default mixer under Linux.\n\n\nCheck - From gstreamer website:\n\nGStreamer has been ported to a wide\n range of operating systems, processors\n and compilers. This include but are\n not li...
[ 4 ]
[]
[]
[ "alsa", "audio", "cross_platform", "python" ]
stackoverflow_0001847022_alsa_audio_cross_platform_python.txt
Q: Print function calls with a variable delay / Python The question is, how can I configure the Python debugger to show me in the console what functions are being called? In order not to see everything flash by, a delay between the function calls would be needed. A: If you want to monitor when a few particular func...
Print function calls with a variable delay / Python
The question is, how can I configure the Python debugger to show me in the console what functions are being called? In order not to see everything flash by, a delay between the function calls would be needed.
[ "If you want to monitor when a few particular functions are being called, \nyou could use this decorator:\nimport functools\ndef trace(f):\n @functools.wraps(f)\n def wrapper(*arg,**kw):\n '''This decorator shows how the function was called'''\n arg_str=','.join(['%r'%a for a in arg]+['%s=%s'%(k...
[ 2, 1 ]
[]
[]
[ "console", "debugging", "python" ]
stackoverflow_0001847177_console_debugging_python.txt
Q: From a coder's perspective, what kind of project should I choose python over php for where both could do the job? I've never used python before. I've used php for about 5 years now. I plan to learn python, but I'm not sure what for yet. If I can think of a project that might be better to do in python, I'll use tha...
From a coder's perspective, what kind of project should I choose python over php for where both could do the job?
I've never used python before. I've used php for about 5 years now. I plan to learn python, but I'm not sure what for yet. If I can think of a project that might be better to do in python, I'll use that to learn it. Edit: just to add this as an important note, I do mean strictly for linux, not multi-platform. Edit 2: I...
[ "Python is better suited for practically anything that doesn't fall within PHP's specialty domain, which is building websites.\nIf you want a list of programming projects that you could work on, see this thread:\nhttps://stackoverflow.com/questions/1022738/i-need-a-good-programming-project\n", "PHP for websites. ...
[ 16, 5, 4, 3, 2, 1, 1, 1 ]
[]
[]
[ "linux", "php", "python", "theory" ]
stackoverflow_0001842208_linux_php_python_theory.txt
Q: Popularity of path hooks (PEP 302 custom import) My project has the ability to run python functions remotely. Doing so requires transmitting modules a given function utilizes. Determining what to send is conducted via a modified modulefinder. As I modify the modulefinder to support arbitrary path_hooks, I've sta...
Popularity of path hooks (PEP 302 custom import)
My project has the ability to run python functions remotely. Doing so requires transmitting modules a given function utilizes. Determining what to send is conducted via a modified modulefinder. As I modify the modulefinder to support arbitrary path_hooks, I've started to get the impression that path_hooks are not al...
[ "Yes, I've coded some path hooks (for one of the obvious purposes: access modules living in other forms of storage besides the filesystem and zipfiles), but never on an open-source project (and actually never needed to support modulefinder in them). What difficulties are you encountering? While I can't share my ori...
[ 2 ]
[]
[]
[ "path", "python" ]
stackoverflow_0001845251_path_python.txt
Q: Speeding up computations with numpy matrices I have two matrices. Both are filled with zeros and ones. One is a big one (3000 x 2000 elements), and the other is smaller ( 20 x 20 ) elements. I am doing something like: newMatrix = (size of bigMatrix), filled with zeros l = (a constant) for y in xrange(0, len(bigMa...
Speeding up computations with numpy matrices
I have two matrices. Both are filled with zeros and ones. One is a big one (3000 x 2000 elements), and the other is smaller ( 20 x 20 ) elements. I am doing something like: newMatrix = (size of bigMatrix), filled with zeros l = (a constant) for y in xrange(0, len(bigMatrix[0])): for x in xrange(0, len(bigMatrix)):...
[ "I can think of a couple of optimisations there - \nAs you are using 4 nested python \"for\" statements, you are about as slow as you can be.\nI can't figure out exactly what you are looking for - \nbut for one thing, if your big matrix \"1\"s density is low, you can certainly use python's \"any\" function on bigMt...
[ 1, 1, 0 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0001803054_matrix_numpy_python.txt
Q: Django filename from database with non-ascii characters I'm trying to create a file dynamically in Django: response = HttpResponse(mimetype='text/txt') response['Content-Disposition'] = 'attachment; filename=%s' % filename # UnicodeEncodeError response.write('text') return response If I hardcode the filename it...
Django filename from database with non-ascii characters
I'm trying to create a file dynamically in Django: response = HttpResponse(mimetype='text/txt') response['Content-Disposition'] = 'attachment; filename=%s' % filename # UnicodeEncodeError response.write('text') return response If I hardcode the filename it works properly, but if I try to create the filename from DB ...
[ "from django.utils.encoding import smart_str\n...\n\n response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename)\n\n", "You can fix the problem on the Django side but there is no guarantee it will work in all browsers.\nSee the testcases at http://greenbytes.de/tech/tc2231/.\nFor more detai...
[ 4, 3 ]
[]
[]
[ "django", "python", "utf_8" ]
stackoverflow_0001846497_django_python_utf_8.txt
Q: Catching a drag exit in Qt? I've got a custom widget descended from QWidget that I want to be able to drop onto, and while the drag is hovering over the widget I'd like to highlight it to provide a little visual feedback to the user. Seems to me the simplest way to do this would be to highlight when dragEnterEve...
Catching a drag exit in Qt?
I've got a custom widget descended from QWidget that I want to be able to drop onto, and while the drag is hovering over the widget I'd like to highlight it to provide a little visual feedback to the user. Seems to me the simplest way to do this would be to highlight when dragEnterEvent is called and unhighlight when...
[ "Open Assistant on the Index tab, type \"drag*event\" and you will find dragLeaveEvent. :)\n" ]
[ 6 ]
[]
[]
[ "drag_and_drop", "pyqt", "python", "qt" ]
stackoverflow_0001848430_drag_and_drop_pyqt_python_qt.txt
Q: Can Unittest in Python run a list made of strings? I am using Selenium to run tests on a website. I have many individual test I need to run, and want to create a script that will run all of the python files in a certain folder. I can get the names, and import the modules, but once I do this I can't get the unitt...
Can Unittest in Python run a list made of strings?
I am using Selenium to run tests on a website. I have many individual test I need to run, and want to create a script that will run all of the python files in a certain folder. I can get the names, and import the modules, but once I do this I can't get the unittest to run the files. Here is some of the test code I h...
[ "Although I wouldn't exactly recommend this approach (nor probably what you're trying to do), here's a simple approach that appears to accomplish roughly what you want.\nIn file \"runner.py\" (for example, similar to your above):\n import glob\n import unittest\ntestfiles = glob.glob('subdir/*.py')\nfor name ...
[ 0, 0 ]
[]
[]
[ "python", "selenium_rc" ]
stackoverflow_0001446317_python_selenium_rc.txt
Q: lxml Changing Unicode Characters I am using lxml to read through an xml file and change a few details. However, when running it I find that even if I just use lxml to read the file and then write it out again, as below: fil='iTunes Music Library.XML' tre=etree.parse(fil) tre.write('temp.xml') I find Queensrÿche c...
lxml Changing Unicode Characters
I am using lxml to read through an xml file and change a few details. However, when running it I find that even if I just use lxml to read the file and then write it out again, as below: fil='iTunes Music Library.XML' tre=etree.parse(fil) tre.write('temp.xml') I find Queensrÿche converted to Queensr&#255;che. Anyone k...
[ "Change your last line to:\ntre.write('temp.xml', encoding='utf-8')\n\nOtherwise lxml writes XML in ASCII encoding, so it have to escape all non-ASCII characters.\n" ]
[ 7 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0001848371_lxml_python_xml.txt
Q: How can I prevent a Python module from importing itself? For instance, I want to make a sql alchemy plugin for another project. And I want to name that module sqlalchemy.py. The problem with this is that it prevents me from importing sqlalchemy: #sqlalchemy.py import sqlalchemy This will make the module import...
How can I prevent a Python module from importing itself?
For instance, I want to make a sql alchemy plugin for another project. And I want to name that module sqlalchemy.py. The problem with this is that it prevents me from importing sqlalchemy: #sqlalchemy.py import sqlalchemy This will make the module import itself. I've tried this, but it doesn't seem to work: import...
[ "Edit: as the OP has now mentioned that the issue is one of relative import being preferred to absolute, the simplest solution for the OP's specific problem is to add at the start of the module from __future__ import absolute_import which changes that \"preference\"/ordering.\nThe following still applies to the tic...
[ 14, 2, 2 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0001848268_import_module_python.txt
Q: Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)? I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration p...
Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)?
I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration package. In order to get a feel for it, i decided to try integrating sin(x) and observed this behavior- >>> from math import ...
[ "The quad function is a function from an old Fortran library. It works by judging by the flatness and slope of the function it is integrating how to treat the step size it uses for numerical integration in order to maximize efficiency. What this means is that you may get slightly different answers from one region t...
[ 10, 6, 6, 4, 3, 2 ]
[]
[]
[ "integration", "numerical_methods", "python", "scipy" ]
stackoverflow_0000581186_integration_numerical_methods_python_scipy.txt
Q: matching stored keywords/phrases in text I have a database table with around 1000 keywords/phrases (one to four words long) - This table changes rarely, so I could extract the data into something more useful (like a regular expression?) - So this is not finding / guessing at keywords based on natural language proc...
matching stored keywords/phrases in text
I have a database table with around 1000 keywords/phrases (one to four words long) - This table changes rarely, so I could extract the data into something more useful (like a regular expression?) - So this is not finding / guessing at keywords based on natural language processing.. I then have a user inputting some tex...
[ "The algorithm for this job is Aho-Corasick ... see the link at the bottom whch points to a C-extension for Python.\n", "If I understand you correctly, you have a unique set of strings, that you want to compare an input strings against. In this case you could use set to store both processing results and db values...
[ 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "django", "mysql", "python", "regex" ]
stackoverflow_0001846833_django_mysql_python_regex.txt
Q: What is the difference between M2Crypto's set_client_CA_list_from_file() and load_verify_info() and when would you use each? The M2Crypto library has a few CA-related functions on its SSL.Context object, but the documentation is very unclear as to when you would use certain functions and why. In fact, the docs fo...
What is the difference between M2Crypto's set_client_CA_list_from_file() and load_verify_info() and when would you use each?
The M2Crypto library has a few CA-related functions on its SSL.Context object, but the documentation is very unclear as to when you would use certain functions and why. In fact, the docs for almost all of them are, "Load CA certs into the context," so it seems possible that they all do the same thing. There are severa...
[ "If your server requires the client to present a certificate, it can restrict who are the valid issuers of the client certificates by specifying the issuers calling set_client_CA_list_from_file. This is actually pretty rare.\nThe client specifies who are the valid server certificate issuers by calling load_verify_l...
[ 2 ]
[]
[]
[ "m2crypto", "python" ]
stackoverflow_0001848160_m2crypto_python.txt
Q: Decorators on Django Template Filters? I have a template filter that performs a very simple task and works well, but I would like to use a decorator on it. Unfortunately the decorator causes a nasty django error that doesn't make any sense... Code that works: @register.filter(name="has_network") def has_network(pr...
Decorators on Django Template Filters?
I have a template filter that performs a very simple task and works well, but I would like to use a decorator on it. Unfortunately the decorator causes a nasty django error that doesn't make any sense... Code that works: @register.filter(name="has_network") def has_network(profile, network): hasnetworkfunc = getatt...
[ "Final Answer: Add an extra argument to the decorator indicating what is being decorated\nThere may be something more elegant, but this works.\nfrom django.core.cache import cache\nfrom django.db.models.query import QuerySet\ntry:\n from cPickle import dumps\nexcept:\n from pickle import dumps\nfrom hashlib i...
[ 0 ]
[]
[]
[ "django", "django_templates", "filter", "python", "templatetags" ]
stackoverflow_0001849243_django_django_templates_filter_python_templatetags.txt
Q: How to do conditional character replacement within a string I have a unicode string in Python and basically need to go through, character by character and replace certain ones based on a list of rules. One such rule is that a is changed to ö if a is after n. Also, if there are two vowel characters in a row, they g...
How to do conditional character replacement within a string
I have a unicode string in Python and basically need to go through, character by character and replace certain ones based on a list of rules. One such rule is that a is changed to ö if a is after n. Also, if there are two vowel characters in a row, they get replaced by one vowel character and :. So if I have the string...
[ "# -*- coding: utf-8 -*-\n\ndef subpairs(s, prefix, suffix):\n def sub(i, sentinal=object()):\n r = prefix.get(s[i:i+2], sentinal)\n if r is not sentinal: return r\n\n r = suffix.get(s[i-1:i+1], sentinal)\n if r is not sentinal: return r\n return s[i]\n\n s = '\\0'+s+'\\0'\n...
[ 7, 2, 2, 1, 1 ]
[]
[]
[ "conditional", "python", "replace", "string" ]
stackoverflow_0001849185_conditional_python_replace_string.txt
Q: How can you detect if two regular expressions overlap in the strings they can match? I have a container of regular expressions. I'd like to analyze them to determine if it's possible to generate a string that matches more than 1 of them. Short of writing my own regex engine with this use case in mind, is there an ...
How can you detect if two regular expressions overlap in the strings they can match?
I have a container of regular expressions. I'd like to analyze them to determine if it's possible to generate a string that matches more than 1 of them. Short of writing my own regex engine with this use case in mind, is there an easy way in C++ or Python to solve this problem?
[ "There's no easy way.\nAs long as your regular expressions use only standard features (Perl lets you embed arbitrary code in matching, I think), you can produce from each one a nondeterministic finite-state automaton (NFA) that compactly encodes all the strings that the RE matches.\nGiven any pair of NFA, it's deci...
[ 37, 2 ]
[ "In theory, the problem you describe is impossible.\nIn practice, if you have a manageable number of regular expressions that use a limited subset or of regexp syntax, and/or a limited selection of strings that can be used to match against the container of regular expressions, you might be able to solve it.\nAssumi...
[ -1 ]
[ "algorithm", "c++", "overlap", "python", "regex" ]
stackoverflow_0001849447_algorithm_c++_overlap_python_regex.txt
Q: how to make import conditionally in Python? I want to do something like this in C: #ifdef SOMETHING do_this(); #endif But in Python this doesn't jive: if something: import module What am I doing wrong? Is this possible in the first place? A: It should work fine: >>> if False: ... import sys ... >>> sy...
how to make import conditionally in Python?
I want to do something like this in C: #ifdef SOMETHING do_this(); #endif But in Python this doesn't jive: if something: import module What am I doing wrong? Is this possible in the first place?
[ "It should work fine:\n>>> if False:\n... import sys\n... \n>>> sys\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'sys' is not defined\n>>> if True:\n... import sys\n... \n>>> sys\n<module 'sys' (built-in)>\n\n", "In Python there's a built-in feature called ...
[ 18, 1, 1, 1 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0001846158_python_python_import.txt
Q: Pyjamas import statements I'm starting to use Pyjamas and I'm running into some annoyances. I have to import a lot of stuff to make a script work well. For example, to make a button I need to first from pyjamas.ui.Button import Button and then I can use Button. Note that import pyjamas.ui.Button and then usin...
Pyjamas import statements
I'm starting to use Pyjamas and I'm running into some annoyances. I have to import a lot of stuff to make a script work well. For example, to make a button I need to first from pyjamas.ui.Button import Button and then I can use Button. Note that import pyjamas.ui.Button and then using Button.Button doesn't work (r...
[ "If you want to be able to say Button.Button, then instead of\nimport pyjamas.ui.Button\n\nyou should write\nfrom pyjamas.ui import Button\n\nOtherwise you need to use pyjamas.ui.Button.Button. What ends up in your namespace is what you have after the import keyword.\n" ]
[ 5 ]
[]
[]
[ "coding_style", "import", "pyjamas", "python" ]
stackoverflow_0001849909_coding_style_import_pyjamas_python.txt
Q: Do dicts preserve iteration order if they are not modified? If I have a dictionary in Python, and I iterate through it once, and then again later, is the iteration order guaranteed to be preserved given that I didn't insert, delete, or update any items in the dictionary? (But I might have done look-ups). A: Here...
Do dicts preserve iteration order if they are not modified?
If I have a dictionary in Python, and I iterate through it once, and then again later, is the iteration order guaranteed to be preserved given that I didn't insert, delete, or update any items in the dictionary? (But I might have done look-ups).
[ "Here is what dict.items() documentation says:\n\ndict.items() return a copy of the dictionary’s list of (key, value) pairs.\nIf items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.\n\nI think it's re...
[ 31, 12, 5, 4, 3, 2, 1 ]
[]
[]
[ "algorithm", "dictionary", "hash", "python" ]
stackoverflow_0001849324_algorithm_dictionary_hash_python.txt
Q: Python bash pipe I want to pipe a python script's output to a bash script. What i did so far was i tried to use os.popen(), sys.subprocess(), and tried to give a pipe for an example os.popen('echo "P 1 1 591336 4927369 1 321 " | v.in.ascii -zn out=abcx format=standard --overwrite') but this didn't work, the value...
Python bash pipe
I want to pipe a python script's output to a bash script. What i did so far was i tried to use os.popen(), sys.subprocess(), and tried to give a pipe for an example os.popen('echo "P 1 1 591336 4927369 1 321 " | v.in.ascii -zn out=abcx format=standard --overwrite') but this didn't work, the values "591336" and "492736...
[ "You can just use print to output to stdout and pipe the Python process to the next process, e.g.\npython myprogram.py | ...\n\nWhere myprogram.py might look like:\nfor x in something:\n print dosomething(x)\n\n", "This works for me:\n>>> stdin, stdout = os.popen2(\"echo %s | grep 'test'\" % 'some test param')...
[ 6, 1, 1, 0 ]
[]
[]
[ "bash", "pipe", "python" ]
stackoverflow_0001847195_bash_pipe_python.txt
Q: Python: TypeError: 'float' object is not callable I am trying to join 2 strings using this code: def __get_temp(self): return float(self.ask('RS')) def __set_temp(self, temp): set = ('SS' + repr(temp)) stat = self.ask(set) return self.check(stat) temp = property(__get_temp, __set_temp) Once toge...
Python: TypeError: 'float' object is not callable
I am trying to join 2 strings using this code: def __get_temp(self): return float(self.ask('RS')) def __set_temp(self, temp): set = ('SS' + repr(temp)) stat = self.ask(set) return self.check(stat) temp = property(__get_temp, __set_temp) Once together, I then send a signal over a serial bus using PyVi...
[ "It looks like you are trying to set the property temp, but what you're actually doing is getting the property and then trying to call it as function with the parameter 13. The syntax for setting is:\nchil.temp = 13\n\n" ]
[ 7 ]
[]
[]
[ "python", "types" ]
stackoverflow_0001850633_python_types.txt
Q: What's the best python idiom for grouping a list of items into groups of a specific max size? I want to write a function that takes items from a list and groups them into groups of size n. Ie, for n = 5, [1, 2, 3, 4, 5, 6, 7] would become [[1, 2, 3, 4, 5], [6, 7]]. What's the best python idiomatic way to do this? ...
What's the best python idiom for grouping a list of items into groups of a specific max size?
I want to write a function that takes items from a list and groups them into groups of size n. Ie, for n = 5, [1, 2, 3, 4, 5, 6, 7] would become [[1, 2, 3, 4, 5], [6, 7]]. What's the best python idiomatic way to do this?
[ "You could do this:\n[a[x:x+n] for x in range(0, len(a), n)]\n\n(In Python 2, use xrange for efficiency; in Python 3 use range as above.)\n", "I don't know of a good command to do this, but here's a way to do it with a list comprehension:\nl = [1,2,3,4,5,6,7]\nn = 5\nnewlist = [l[i:i+n] for i in range(0,len(l),n)...
[ 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001849741_python.txt
Q: Pylucene eclipse plugin Is there a Pylucene eclipse plugin? or am I missing something? I want it for Auto complete. Is the import structure same as java lucene A: Assuming you're using PyDev, you need to add PyLucene to your import path. This can be done in the preferences pane somewhere under the PyDev sectio...
Pylucene eclipse plugin
Is there a Pylucene eclipse plugin? or am I missing something? I want it for Auto complete. Is the import structure same as java lucene
[ "Assuming you're using PyDev, you need to add PyLucene to your import path. This can be done in the preferences pane somewhere under the PyDev section. (Sorry, I don't have PyDev installed on this computer so I can't be more specific.) Not having used PyLucene I can't tell you exactly which path you need to add, bu...
[ 1 ]
[]
[]
[ "java", "lucene", "pylucene", "python" ]
stackoverflow_0001850717_java_lucene_pylucene_python.txt
Q: Is pickle file of python cross-platform? I have created a small python script of mine. I saved the pickle file on Linux and then used it on windows and then again used it back on Linux but now that file is not working on Linux but it is working perfectly on windows. Is is so that python is coss-platform but the p...
Is pickle file of python cross-platform?
I have created a small python script of mine. I saved the pickle file on Linux and then used it on windows and then again used it back on Linux but now that file is not working on Linux but it is working perfectly on windows. Is is so that python is coss-platform but the pickle file is not. Is there any solution to th...
[ "Python's pickle is perfectly cross-platform.\nThis is likely due to EOL (End-Of-Line) differences between Windows and Linux. Make sure to open your pickle files in binary mode both when writing them and when reading them, using open()'s \"wb\" and \"rb\" modes respectively.\nNote: Passing pickles between different...
[ 36, 12, 4, 4, 1, 0 ]
[]
[]
[ "file_io", "pickle", "python" ]
stackoverflow_0001849523_file_io_pickle_python.txt
Q: Python: Change class type name How would you change a class type name to something other than classobj? class bob(): pass foo = bob print "%s" % type(foo).__name__ which gets me 'classobj'. A: In your example, you've defined foo as a reference to the class definition of bob, not to an instance of bob. The ...
Python: Change class type name
How would you change a class type name to something other than classobj? class bob(): pass foo = bob print "%s" % type(foo).__name__ which gets me 'classobj'.
[ "In your example, you've defined foo as a reference to the class definition of bob, not to an instance of bob. The type of an (old-style) class is indeed classobj.\nIf you instantiate bob, on the other hand, the result will be different:\n# example using new-style classes, which are recommended over old-style\nclas...
[ 14, 12 ]
[]
[]
[ "python" ]
stackoverflow_0001850289_python.txt
Q: PDF Parsing Using Python - extracting formatted and plain texts I'm looking for a PDF library which will allow me to extract the text from a PDF document. I've looked at PyPDF, and this can extract the text from a PDF document very nicely. The problem with this is that if there are tables in the document, the text...
PDF Parsing Using Python - extracting formatted and plain texts
I'm looking for a PDF library which will allow me to extract the text from a PDF document. I've looked at PyPDF, and this can extract the text from a PDF document very nicely. The problem with this is that if there are tables in the document, the text in the tables is extracted in-line with the rest of the document tex...
[ "You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).\nA particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking t...
[ 63, 2 ]
[]
[]
[ "information_extraction", "parsing", "pdf", "python", "text_extraction" ]
stackoverflow_0001848464_information_extraction_parsing_pdf_python_text_extraction.txt
Q: python web crawler with thread support these day im making some web crawler script, but one of problem is my internet is very slow. so i was thought whether is it possible webcrawler with multithreading by use mechanize or urllib or so. if anyone have experience ,share info much appreciate. i was look for in goog...
python web crawler with thread support
these day im making some web crawler script, but one of problem is my internet is very slow. so i was thought whether is it possible webcrawler with multithreading by use mechanize or urllib or so. if anyone have experience ,share info much appreciate. i was look for in google ,but not found much useful info. Thanks i...
[ "There's a good, simple example on this Stack Overflow thread.\n", "Practical threaded programming with Python is worth reading.\n", "Making multiple requests to many websites at the same time will certainly improve your results, since you don't have to wait for a result to arrive before sending new requests.\n...
[ 4, 3, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0001848413_multithreading_python.txt
Q: Troubles installing PyQt4 I'm following this guide. Python is at C:\Python31 PyQt4 is at C:\Python31\pyqt sip is at C:\Python31\sip Qt is at C:\Qt\4.6.0 I followed the instructions on that guide, but when I tried to test it (from PyQt4.Qt install *), it said the module didn't exist. I checked all the files that ...
Troubles installing PyQt4
I'm following this guide. Python is at C:\Python31 PyQt4 is at C:\Python31\pyqt sip is at C:\Python31\sip Qt is at C:\Qt\4.6.0 I followed the instructions on that guide, but when I tried to test it (from PyQt4.Qt install *), it said the module didn't exist. I checked all the files that guide said should exist, and no...
[ "There is pre-built version already, why you still need to build yourself?\nhttp://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py3.1-gpl-4.6.2-2.exe\n" ]
[ 5 ]
[]
[]
[ "pyqt4", "python", "python_sip" ]
stackoverflow_0001851321_pyqt4_python_python_sip.txt
Q: Numpy - show decimal values in array results how do I calculate that an array of python numpy or me of all the calculate decimals and not skip like. >> A = numpy.array ([[1,2,3], [4,5,6], [7,8,9]]). >> C = numpy.array ([[7,8,9], [1,2,3], [4,5,6]]). >> A / C array ([[0, 0, 0], [4, 2, 2], [1, 1, 1]]...
Numpy - show decimal values in array results
how do I calculate that an array of python numpy or me of all the calculate decimals and not skip like. >> A = numpy.array ([[1,2,3], [4,5,6], [7,8,9]]). >> C = numpy.array ([[7,8,9], [1,2,3], [4,5,6]]). >> A / C array ([[0, 0, 0], [4, 2, 2], [1, 1, 1]]) but in the first vector would not have to be gi...
[ "To avoid integer division, use numpy.true_divide(A,C). You can also put from __future__ import division at the top of the file to default to this behavior.\n", "Try converting one of the arrays A or C into an array of floats. For instance:\nA = A * 1.0\n\nThen the division will be floating point division.\n", ...
[ 6, 4, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001799527_numpy_python.txt
Q: Why is pdb displaying "*** Blank or comment" when I try to set a Break? I'm working with my Django app. For some reason an element of a list is being assigned incorrectly. I'm trying to set a break where I think the error is occurring. ( line 20 ) I'm invoking pdb with this line of code: import pdb; pdb.set_trac...
Why is pdb displaying "*** Blank or comment" when I try to set a Break?
I'm working with my Django app. For some reason an element of a list is being assigned incorrectly. I'm trying to set a break where I think the error is occurring. ( line 20 ) I'm invoking pdb with this line of code: import pdb; pdb.set_trace() However, inside the code, I can't seem to set a Break. (Pdb) b 20 **...
[ "pdb is telling you that line 20 of the file you're in doesn't contain code; it's either blank or just contains a comment. Such a line will never actually be executed, so a breakpoint can't be set on it.\nUse the 'list' command to see the code of the file you're currently in ('help list' for details on this command...
[ 9 ]
[]
[]
[ "django", "pdb", "python" ]
stackoverflow_0001852427_django_pdb_python.txt
Q: Ruby Quiz for Python Is there a blog/forum/listserv that is equivalent to RubyQuiz.com for the Python language? A: How about the Python Challenge? It isn't a weekly challenge, more a fixed set of challenges of increasing difficulty but it is fun and educational none-the-less. A great way to get to know python a...
Ruby Quiz for Python
Is there a blog/forum/listserv that is equivalent to RubyQuiz.com for the Python language?
[ "How about the Python Challenge?\nIt isn't a weekly challenge, more a fixed set of challenges of increasing difficulty but it is fun and educational none-the-less. A great way to get to know python and have fun solving puzzles. Try to do them yourself without cheating to get the most out of it!\n", "At the risk...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001851396_python.txt
Q: Python values with units I need to keep track of units on float and int values in Python, but I don't want to use an external package like magnitude or others, because I don't need to perform operations on the values. Instead, all I want is to be able to define floats and ints that have a unit attribute (and I don...
Python values with units
I need to keep track of units on float and int values in Python, but I don't want to use an external package like magnitude or others, because I don't need to perform operations on the values. Instead, all I want is to be able to define floats and ints that have a unit attribute (and I don't want to add a new dependenc...
[ "You might be looking for something like this:\nclass UnitFloat(float):\n\n def __new__(self, value, unit=None):\n return float.__new__(self, value)\n\n def __init__(self, value, unit=None):\n self.unit = unit\n\n\nx = UnitFloat(35.5, \"cm\")\ny = UnitFloat(42.5)\n\nprint x\nprint x.unit\n\nprint...
[ 11, 7, 1, 0 ]
[ "It looks like you need to check if kwargs is not None before you try to see if there is a label 'unit'.\nChange your code to\n if kwargs and 'unit' in kwargs:\n\nUpdated answer:\ndon't pass kwargs to __oldinit__\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0001852720_python.txt
Q: Django application deployment help I'm using Capistrano to deploy a Django application (it uses Nginx as the web server), using instructions I found at http://akashxav.com/2009/07/11/getting-django-running-on-nginx-and-fastcgi-on-prgmr/ (I had to look at a cached version earlier today) and was wondering about the ...
Django application deployment help
I'm using Capistrano to deploy a Django application (it uses Nginx as the web server), using instructions I found at http://akashxav.com/2009/07/11/getting-django-running-on-nginx-and-fastcgi-on-prgmr/ (I had to look at a cached version earlier today) and was wondering about the last command in there, which is python ...
[ "There is a section in the django docs about this\nBasically use the pidfile option to manage.py and then write a small shell script to use that pid to kill the existing cgi process if it exists before starting the new one.\nSomething like this\n#!/bin/bash\nif [ -f \"pidfile\" ]; then\n kill `cat -- pidfile`\n ...
[ 1 ]
[]
[]
[ "deployment", "django", "python" ]
stackoverflow_0001852693_deployment_django_python.txt
Q: Looking for feedback on my program design I'm aware that SO is for questions but overall the aim is to help people learn so I figured I'd try my hand at sharing some code and asking for feedback on it. I'm looking to create a program that will rely on random numbers, specifically dice. These will be presented in ...
Looking for feedback on my program design
I'm aware that SO is for questions but overall the aim is to help people learn so I figured I'd try my hand at sharing some code and asking for feedback on it. I'm looking to create a program that will rely on random numbers, specifically dice. These will be presented in the form of "2D6", "4D10+3", "2D2 + 3D3" and so...
[ "I think your approach makes for a lot of complexity: you're trying to solve the hard problem (parsing the input) at the same time you're solving the less-hard problem (doing the dice-rolling). It's easier if you separate the problems.\nA class to roll dice is relatively easy to write. Two things I'm doing that ...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001849924_python.txt
Q: why Ghost Process appears after kill -9 In my Python script, I first launch a subprocess by subprocess.Popen(). Then later on, I want to kill that subprocess by kill -9 Pid. What I found is that after the kill is executed, the subprocess is "stopped" because the GUI window of that process disappeared immediately. ...
why Ghost Process appears after kill -9
In my Python script, I first launch a subprocess by subprocess.Popen(). Then later on, I want to kill that subprocess by kill -9 Pid. What I found is that after the kill is executed, the subprocess is "stopped" because the GUI window of that process disappeared immediately. But when I perform a "ps aux" right after the...
[ "From the manual page of ps:\n\nZ Defunct (\"zombie\") process,\n terminated but not reaped by its\n parent.\n\nThat means that the parent didn't do a waitpid() for the child that died.\nApart from waitpid(), you can avoid that by using a double fork when executing the child.\n", "I think -9 sign...
[ 4, 0, 0 ]
[]
[]
[ "kill", "process", "python" ]
stackoverflow_0001830370_kill_process_python.txt