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: Tetris Timing Problem I am writing a Tetris program with PyGame, and came across a funny problem. Before I ask the question, here is the pseudo-code: while True: # In this part, the human controls the block to go left, right, or speed down if a key is pressed and the block isnt touching the floor: ...
Tetris Timing Problem
I am writing a Tetris program with PyGame, and came across a funny problem. Before I ask the question, here is the pseudo-code: while True: # In this part, the human controls the block to go left, right, or speed down if a key is pressed and the block isnt touching the floor: if the key is K-left: ...
[ "The main problem I see here is that you are limiting your framerate using a wait of 0.4 seconds. \nYou should not limit framerate, but instead, you should limit how fast your block falls.\nIf I remember well, there was a formula you could use to do just that. It was based on the amout of time elapsed since the las...
[ 4, 1, 1, 0 ]
[]
[]
[ "pygame", "python", "tetris", "timing" ]
stackoverflow_0005568654_pygame_python_tetris_timing.txt
Q: Python e-mailing? Easiest way? How can I send an e-mail from Python without any third party programs? A: Use the python email and smtplib modules. Examples: http://docs.python.org/library/email-examples.html A: smtplib You need an SMTP server to send mail with, of course. A: Python comes with an email module...
Python e-mailing? Easiest way?
How can I send an e-mail from Python without any third party programs?
[ "Use the python email and smtplib modules. Examples: http://docs.python.org/library/email-examples.html\n", "smtplib\nYou need an SMTP server to send mail with, of course.\n", "Python comes with an email module:\nhttp://docs.python.org/library/email-examples.html\nNote though that you still need to contend with...
[ 3, 0, 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0005573474_email_python.txt
Q: How to modify query string in python (CGI) I'm experimenting with cgi in Python, and I was wondering how I would modify a query string. For example, if I had a snippit of HTML: <form action="/cgi-bin/text.py" method="get"> <textarea name="stuff"></textarea> <button type="submit">Submit</button> </form> th...
How to modify query string in python (CGI)
I'm experimenting with cgi in Python, and I was wondering how I would modify a query string. For example, if I had a snippit of HTML: <form action="/cgi-bin/text.py" method="get"> <textarea name="stuff"></textarea> <button type="submit">Submit</button> </form> then the query string might be something like http...
[ "Try using urlparse module: http://docs.python.org/library/urlparse.html\n" ]
[ 0 ]
[]
[]
[ "cgi", "html", "python", "query_string" ]
stackoverflow_0005573644_cgi_html_python_query_string.txt
Q: Get Python without (selected) batteries I very like the "battery included" philosophy of Python but now I have to perform a slim installation with only core features and some other which I'd like to choose one by one. Is it possible to download Python with only selected modules? A: Install python as normal. Open...
Get Python without (selected) batteries
I very like the "battery included" philosophy of Python but now I have to perform a slim installation with only core features and some other which I'd like to choose one by one. Is it possible to download Python with only selected modules?
[ "Install python as normal. Open up the python interpreter and import some of the stuff you think you won't want.\nimport io, optparse, tarfile\n\nThen the str representation of the module has its path in it\n>>> tarfile\n<module 'tarfile' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/...
[ 3, 2, 2, 1, 0 ]
[]
[]
[ "distribution", "python" ]
stackoverflow_0005569652_distribution_python.txt
Q: Creating a PDF from XML using XSL FO w/ Python Could someone point me in the right direction of hopefully a library or code examples, any resources on how to take XML and create a PDF using XSL-FO in Python? If I should have to use an XML renderer, then which XML renderer is recommended? A: If you want to run XS...
Creating a PDF from XML using XSL FO w/ Python
Could someone point me in the right direction of hopefully a library or code examples, any resources on how to take XML and create a PDF using XSL-FO in Python? If I should have to use an XML renderer, then which XML renderer is recommended?
[ "If you want to run XSLT programmatically with Python, you want lxml.\nHowever, if you just need to create a .fo file from a defined XSL/XML pair, you might as well just use xsltproc, which is available on any Unix-y system on the command line, including OS X. \nOnce you have the .fo file, use Fop to transform that...
[ 3, 1 ]
[]
[]
[ "python", "xml", "xsl_fo" ]
stackoverflow_0005573215_python_xml_xsl_fo.txt
Q: Is it possible to obtain the IP address from a HTTP Request I am trying to identify users that access my website. I know of assigning a cookie to them & identifying them that way. But is it also possible to use their IP address to identify them? I know of IP subclassing (is that the correct term) so if many users ...
Is it possible to obtain the IP address from a HTTP Request
I am trying to identify users that access my website. I know of assigning a cookie to them & identifying them that way. But is it also possible to use their IP address to identify them? I know of IP subclassing (is that the correct term) so if many users on the same network access my site & have subclassing, they will ...
[ "Sure. Use cgi, and os. The client's IP address is located in the environ variable with a title of REMOTE_ADDR. For example, the following will print out the client's ip address:\nimport cgi\nimport os\n\nprint \"Content-type: text/html\"\nprint \"\"\nprint cgi.escape(os.environ[\"REMOTE_ADDR\"])\n\n" ]
[ 1 ]
[]
[]
[ "http", "python", "tcp" ]
stackoverflow_0005574540_http_python_tcp.txt
Q: How to handle concurrent variable writes with Python workerpool Is there a special way to use Python's workerpool to write to a variable that is outside a particular job. Let's say, for example, you have a job called DownloadJob which downloads some file and increments a counter. What is the best way to handle th...
How to handle concurrent variable writes with Python workerpool
Is there a special way to use Python's workerpool to write to a variable that is outside a particular job. Let's say, for example, you have a job called DownloadJob which downloads some file and increments a counter. What is the best way to handle the incrementing of this counter variable? Do I need to somehow lock t...
[ "You can use threading.Lock for mutual exclusion. The documentation is pretty clear about them: http://docs.python.org/library/threading.html#lock-objects\nCheers!\n" ]
[ 4 ]
[]
[]
[ "multithreading", "python", "worker" ]
stackoverflow_0005574586_multithreading_python_worker.txt
Q: Effectively reading a large, active Python log file When my Python script is writing a large amount of logs to a text file line by line using the Python built-in logging library, in my Delphi-powered Windows program I want to effectively read all newly added logs (lines). When the Python scripting is logging to t...
Effectively reading a large, active Python log file
When my Python script is writing a large amount of logs to a text file line by line using the Python built-in logging library, in my Delphi-powered Windows program I want to effectively read all newly added logs (lines). When the Python scripting is logging to the file, my Windows program will keep a readonly file han...
[ "It depends on the logging handler you use, of course, but as you can see from the source code, logging.FileHandler does not currently create any file locks. By default, it opens files in 'a' (append) mode, so as long as your Windows calls can handle that, you should be fine.\n", "As ʇsәɹoɈ commented, the standa...
[ 1, 0 ]
[]
[]
[ "logging", "python", "text_files", "windows" ]
stackoverflow_0005571035_logging_python_text_files_windows.txt
Q: Transparent axes.axhline in matplotlib? I'm trying to add a horizontal line to my axes to mark an important y value, so I'm using: fig = Figure(figsize=(5, 5)) ax = fig.add_axes((0.2, 0.2, 0.6, 0.6)) ax.plot(...) ax.axhline(100000, xmin=0, xmax=1, linewidth=0.3, color=(0, 0, 0, 0.75)) canvas = FigureCanvasAgg(fig)...
Transparent axes.axhline in matplotlib?
I'm trying to add a horizontal line to my axes to mark an important y value, so I'm using: fig = Figure(figsize=(5, 5)) ax = fig.add_axes((0.2, 0.2, 0.6, 0.6)) ax.plot(...) ax.axhline(100000, xmin=0, xmax=1, linewidth=0.3, color=(0, 0, 0, 0.75)) canvas = FigureCanvasAgg(fig) canvas.print_figure("chart.pdf", dpi=300) H...
[ "Linewidth is in points.\nThe transparency works fine for me using matplotlib 1.0+. Here is the code I used to test:\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nx = np.arange(0,10,.1)\ny = np.sin(x)\nplt.plot(x,y)\nax = plt.gca()\nax.axhline(.4, xmin=0, xmax=1, linewidth=0.3, color=(0, 0, 0, 0.75)...
[ 6 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005574641_matplotlib_python.txt
Q: Why does django jython connection to a MySQL database give a "Communication Link Failure"? I'm trying to convert a django / cPython app to run as a Tomcat WAR using Jython. We are using a mysql database (MySQLdb in cPython / mysql-connector-java-5.1.15-bin.jar in jython). I have changed the DATABASE_ENGINE betwe...
Why does django jython connection to a MySQL database give a "Communication Link Failure"?
I'm trying to convert a django / cPython app to run as a Tomcat WAR using Jython. We are using a mysql database (MySQLdb in cPython / mysql-connector-java-5.1.15-bin.jar in jython). I have changed the DATABASE_ENGINE between the two configurations. The app runs great with cPython (after I disabled SELinux limitation...
[ "I found the mistake. In hindsight, it's obvious. I made a type-o in the IP address of the database server, but only in the configuration file on the jython branch. As a result, the Jython instance hung while the cPython instance didn't. Found the error when I merged the two into a single settings.py (using \"i...
[ 1 ]
[]
[]
[ "django", "jython", "mysql", "python", "tomcat" ]
stackoverflow_0005574482_django_jython_mysql_python_tomcat.txt
Q: Trying to get a session token for Google Calendar using Python. Getting NonAuthSubToken error I'm trying to get a session token to use the Google Calendar API using the Python library. I'm using Django 1.2.1 and Python 2.7. The page basically has a "Login to Google Calendar" (see the auth_url variable below) link ...
Trying to get a session token for Google Calendar using Python. Getting NonAuthSubToken error
I'm trying to get a session token to use the Google Calendar API using the Python library. I'm using Django 1.2.1 and Python 2.7. The page basically has a "Login to Google Calendar" (see the auth_url variable below) link that requests the single use token. From what I can tell the single use token looks exactly as I wo...
[ "the docs says:\n\nNonAuthSubToken : Raised if a method\n to modify an AuthSub token is used\n when\n the user is either not authenticated or is\n authenticated\n through another authentication mechanism.\n\nthe user is authenticated? (second reason is eliminated as yo...
[ 1 ]
[]
[]
[ "django", "google_calendar_api", "python" ]
stackoverflow_0005575009_django_google_calendar_api_python.txt
Q: I need to check if neighboring positions on a board are "paths" The function I'm working in relies on the function mazesol.getBlock(board, x, y). I need to check all of the neighboring positions (up, down, left, right) on the board. Would I write it like this? if mazesol.getBlock(board, ((x+1),(x-1)),((y+1),(y-1))...
I need to check if neighboring positions on a board are "paths"
The function I'm working in relies on the function mazesol.getBlock(board, x, y). I need to check all of the neighboring positions (up, down, left, right) on the board. Would I write it like this? if mazesol.getBlock(board, ((x+1),(x-1)),((y+1),(y-1))) == 'path':
[ "It looks like you want to check each adjacent tile from your current x, y position. Why don't you enumerate all of those possibilities first so its more readable for you :\n//pseudo code...\nup =mazesol.getBlock(board, x, y + 1);\ndown = mazesol.getBlock(x, y - 1);\nleft = mazesol.getBlock(x - 1, y);\nright = maz...
[ 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0005575343_if_statement_python.txt
Q: What's wrong in this code? It keep writing the same value it inserts same value every time. import re import MySQLdb db = MySQLdb.connect("localhost","root","123","tc" ) cursor = db.cursor() for x in range(1,2): file = '/tmp/tc/' file +=`x` file +=".txt" f = open(file, 'r') ...
What's wrong in this code? It keep writing the same value
it inserts same value every time. import re import MySQLdb db = MySQLdb.connect("localhost","root","123","tc" ) cursor = db.cursor() for x in range(1,2): file = '/tmp/tc/' file +=`x` file +=".txt" f = open(file, 'r') print x listTC = re.findall(r'[1-9]{1}[0-9]{10}', f.rea...
[ "2147483647 is 0x7fffffff, so probably you hit max signed int value.\nTake a look on data type on the field at database designers, and probably use Big Integer or something bigger one.\nref: http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html#id603844\n", "It's because of range(1,2):\nfor x in range(1,2):\n...
[ 2, 0 ]
[]
[]
[ "insert", "mysql", "python" ]
stackoverflow_0005575296_insert_mysql_python.txt
Q: NoSQL Solution to Store Arrays? I need a scalable NoSql solution to store data as arrays for many fields & time stamps, where the key is a combination of a field and a timestamp. Data would be stored in the following scheme: KEY --> "FIELD_NAME.YYYYMMDD.HHMMSS" VALUE --> [v1, v2, v3, v4, v5, v6] (...
NoSQL Solution to Store Arrays?
I need a scalable NoSql solution to store data as arrays for many fields & time stamps, where the key is a combination of a field and a timestamp. Data would be stored in the following scheme: KEY --> "FIELD_NAME.YYYYMMDD.HHMMSS" VALUE --> [v1, v2, v3, v4, v5, v6] (v1..v6 are just floats) For instance,...
[ "Sounds like MongoDB would be a good fit. PyMongo is the api.\n", "Your data is highly structured and regular; what benefit do you see in NoSQL vs a more traditional database?\nI think MySQL Cluster sounds tailor-made for your problem.\nEdit:\n@user540009: I agree that there are serious slowdowns on single-machin...
[ 3, 0 ]
[]
[]
[ "linux", "nosql", "python" ]
stackoverflow_0005574649_linux_nosql_python.txt
Q: how to hold 0,1,2 in a list using python the a only Allowed containing 0 1 2 , a=[0,1,2]#a's max size if a=[0,] a += [1] --> [0,1] if a=[0,1] a += [1] --> [0,1] if a=[0,1] a += [2] --> [0,1,2] if a=[0,1,2] a += [1] --> [0,1,2] if a=[0,1,2] a += [4] --> [0,1,2] so what can i do A: You can always create yo...
how to hold 0,1,2 in a list using python
the a only Allowed containing 0 1 2 , a=[0,1,2]#a's max size if a=[0,] a += [1] --> [0,1] if a=[0,1] a += [1] --> [0,1] if a=[0,1] a += [2] --> [0,1,2] if a=[0,1,2] a += [1] --> [0,1,2] if a=[0,1,2] a += [4] --> [0,1,2] so what can i do
[ "You can always create you own class that does what you need:\nEDIT:\nclass LimitedList:\n def __init__(self, inputList=[]):\n self._list = []\n self.append(inputList)\n\n def append(self, inputList):\n for i in inputList:\n if i in [0,1,2] and i not in self._list:\n ...
[ 5, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005575335_list_python.txt
Q: How to get Django Book on Kindle? The Django Book is freely available online. A couple questions: Is it possible to get it for free on the Kindle? If so, how? A: You can use Calibre to convert other formats to Kindle: http://calibre-ebook.com/ A: I'd first search Amazon's store. http://www.amazon.com/s/ref=n...
How to get Django Book on Kindle?
The Django Book is freely available online. A couple questions: Is it possible to get it for free on the Kindle? If so, how?
[ "You can use Calibre to convert other formats to Kindle:\nhttp://calibre-ebook.com/\n", "I'd first search Amazon's store.\nhttp://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Ddigital-text&field-keywords=the+django+book&x=0&y=0\n(This yields no free books entitled \"The Django Book.\")\nThe next step may be ...
[ 2, 1 ]
[]
[]
[ "django", "kindle", "python" ]
stackoverflow_0005575536_django_kindle_python.txt
Q: Parsing a TCL-like text I have a configuration text that looks like this: text=""" key1 value1 key2 { value1 value2 } key3 subkey1 { key1 1 key2 2 key3 { value1 } } BLOBKEY name { dont { # comment parse { me } } } key3 subkey2 { key1 value1 } """ The values a...
Parsing a TCL-like text
I have a configuration text that looks like this: text=""" key1 value1 key2 { value1 value2 } key3 subkey1 { key1 1 key2 2 key3 { value1 } } BLOBKEY name { dont { # comment parse { me } } } key3 subkey2 { key1 value1 } """ The values are plain strings or quoted st...
[ "Here's my progress so far. It doesn't parse raw blobs, but everything else seems right.\nLBRA = Literal(\"{\").suppress()\nRBRA = Literal(\"}\").suppress()\nEOL = lineEnd.suppress()\ntmshString = Word(alphanums + '!#$%&()*+,-./:;<=>?@[\\]^_`|~')\n\ntmshValue = Combine( tmshString | dblQuotedString.setParseAction( ...
[ 3 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0005558276_pyparsing_python.txt
Q: how to loop a dict in a {} using python This is my code : a = {0:'000000',1:'11111',3:'333333',4:'444444'} b = {i:j+'www' for i,j in a.items()} print b and it shows error : File "g.py", line 7 b = {i:j+'www' for i,j in a.items()} ^ SyntaxError: invalid syntax How can I correct this...
how to loop a dict in a {} using python
This is my code : a = {0:'000000',1:'11111',3:'333333',4:'444444'} b = {i:j+'www' for i,j in a.items()} print b and it shows error : File "g.py", line 7 b = {i:j+'www' for i,j in a.items()} ^ SyntaxError: invalid syntax How can I correct this?
[ "{i:j+'www' for i,j in a.items()}\n\nDictionary Comprehension works fine in Python 3.\nAs you can see here: http://ideone.com/tbXLA (note, I am calling print as a function in Python 3).\nIf you have < Python 3, then it will give you this error.\nTo do this type of concept, you must do list/generator expression whi...
[ 4, 3 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0005575670_dictionary_loops_python.txt
Q: How to get field data from model? Say I have a Django application named app. Within it I have a model class defined in models.py named data. Also, I have a html file in the template directory that has several picklists, which should be populated with the fields of the model, such as type, date. What I need to do ...
How to get field data from model?
Say I have a Django application named app. Within it I have a model class defined in models.py named data. Also, I have a html file in the template directory that has several picklists, which should be populated with the fields of the model, such as type, date. What I need to do is to get the lists of the fields in th...
[ "Have a look at Django's Form functionality – specifically ModelChoiceField – it solves this problem.\nIf you want to introspect a model to see what fields it has, have a look at model._meta.fields.\nFor example, the following code prints out the value for each field on a model instance instance:\nfor field in inst...
[ 1, 1 ]
[]
[]
[ "django", "field", "model", "python" ]
stackoverflow_0005575487_django_field_model_python.txt
Q: How to close a pop up window and redirect the url to parent page? I have created a django app. I have implemented a facebook login along with a django login for my app. On clicking the facebook login button, an outh login page pop ups and i able to login bu giving username and password there. But even after signin...
How to close a pop up window and redirect the url to parent page?
I have created a django app. I have implemented a facebook login along with a django login for my app. On clicking the facebook login button, an outh login page pop ups and i able to login bu giving username and password there. But even after signing in, that pop up is not closing, and the new url to be showed after si...
[ "Call this JS in popup page:\nwindow.opener.location.href = \"http://some/new/location\";\nwindow.close();\n\n" ]
[ 5 ]
[]
[]
[ "django", "django_models", "facebook", "javascript", "python" ]
stackoverflow_0005575782_django_django_models_facebook_javascript_python.txt
Q: Problem trying to install PyCurl on Mac Snow Leopard My app needs to use PyCurl, so I tried to install it on my Mac but I found a lot of problems and errors. Requirement: First of all I have to say that the version of Python working on my Mac is 32 bit based, because I need to use WxPython, that needs 32 bit Pytho...
Problem trying to install PyCurl on Mac Snow Leopard
My app needs to use PyCurl, so I tried to install it on my Mac but I found a lot of problems and errors. Requirement: First of all I have to say that the version of Python working on my Mac is 32 bit based, because I need to use WxPython, that needs 32 bit Python. For doing this I used: defaults write com.apple.version...
[ "I ran into the same issue when trying to install from pip and easy_install. I got it installed and working by downloading the pycurl source and compiling for Snow Leopard. In the pycurl source directory, before you run \"python setup.py install\" as the install.txt says, you need to run this:\ngcc-4.2 -fno-stric...
[ 2, 1 ]
[]
[]
[ "importerror", "macos", "osx_snow_leopard", "pycurl", "python" ]
stackoverflow_0002784449_importerror_macos_osx_snow_leopard_pycurl_python.txt
Q: Retrieving token and secret from gdata.gauth.OAuthHmacToken python object I'm following Google's great sample code for three-legged OAuth. Specifically, I'm looking at the python version of the code. I'm stuck between 'Upgrading to an access token' and 'Using an access token'. In 'Upgrading to an access token', th...
Retrieving token and secret from gdata.gauth.OAuthHmacToken python object
I'm following Google's great sample code for three-legged OAuth. Specifically, I'm looking at the python version of the code. I'm stuck between 'Upgrading to an access token' and 'Using an access token'. In 'Upgrading to an access token', there is a line of code as follows: access_token = client.GetAccessToken(request_...
[ "I was able to figure this out.\naccess_token is of type gdata.gauth.OAuthHmacToken. So instead of trying to pass in the individual arguments, I could just do this:\nclient.auth_token = access_token\n\n" ]
[ 1 ]
[]
[]
[ "access_token", "gdata", "oauth", "python" ]
stackoverflow_0005569074_access_token_gdata_oauth_python.txt
Q: Python: Combine several nested lists into a dictionary I have a bunch of lists like the following two: ['a', ['b', ['x', '1'], ['y', '2']]] ['a', ['c', ['xx', '4'], ['gg', ['m', '3']]]] What is the easiest way to combine all of them into a single dictionary that looks like: {'a': { 'b': { 'x':1, ...
Python: Combine several nested lists into a dictionary
I have a bunch of lists like the following two: ['a', ['b', ['x', '1'], ['y', '2']]] ['a', ['c', ['xx', '4'], ['gg', ['m', '3']]]] What is the easiest way to combine all of them into a single dictionary that looks like: {'a': { 'b': { 'x':1, 'y':2 } 'c': { 'xx':4, 'gg': { ...
[ "Here's a very crude implementation, it does not handle weird cases such as lists having less than two elements and it overwrites duplicate keys, but its' something to get you started:\nl1 = ['a', ['b', ['x', '1'], ['y', '2']]]\nl2 = ['a', ['c', ['xx', '4'], ['gg', ['m', '3']]]]\n\ndef combine(d, l):\n if not l[...
[ 2, 1, 1 ]
[]
[]
[ "dictionary", "list", "nested", "python" ]
stackoverflow_0005575124_dictionary_list_nested_python.txt
Q: how can i have the full control on my 3D human model? I'm working on a project that i use a 3D human model made by makehuman and i want to interacting with it ( changing some feature like: height, width, leg long, etc..) i.e. full control. so i want to ask how can i do this in order to make some changes on the mod...
how can i have the full control on my 3D human model?
I'm working on a project that i use a 3D human model made by makehuman and i want to interacting with it ( changing some feature like: height, width, leg long, etc..) i.e. full control. so i want to ask how can i do this in order to make some changes on the model features and then export it automatically(with code not ...
[ "All that can be done by Python scripting\n" ]
[ 0 ]
[]
[]
[ "3d_modelling", "3dsmax", "blender", "python" ]
stackoverflow_0005570727_3d_modelling_3dsmax_blender_python.txt
Q: Python instance to COM Object I'm having a bit of a play with using COM objects with Python and have run into a small problem. The COM object I am using has a method called SetCallback which takes a object, the mothod looks like this: [id(0x60010010)] void SetCallback([in] IDispatch* callbackobject); T...
Python instance to COM Object
I'm having a bit of a play with using COM objects with Python and have run into a small problem. The COM object I am using has a method called SetCallback which takes a object, the mothod looks like this: [id(0x60010010)] void SetCallback([in] IDispatch* callbackobject); Taken from MS OLE/COM Object viewer ...
[ "Worked it out! Just needed to make my own COM server and register it, then create the object via Dispatch:\nclass Callback():\n _public_methods_ = ['SetStatusText']\n _reg_progid_ = \"mycomobject.PythonCallback\"\n _reg_clsid_ = \"{14EF8D30-8B00-4B14-8891-36B8EF6D51FD}\"\n def SetStatusText(self,status...
[ 2, 0 ]
[]
[]
[ "com", "ole", "python" ]
stackoverflow_0005453998_com_ole_python.txt
Q: from php to django for pack('H32',$challenge) and md5("\0" . $word . $challenge) i have the following functions called one after the other in PHP : $chal = pack('H32',$challenge); $word = md5("\0" . $word . $chal); I would like to do the same in Django python. Any tips from your side please ? A: This approach ...
from php to django for pack('H32',$challenge) and md5("\0" . $word . $challenge)
i have the following functions called one after the other in PHP : $chal = pack('H32',$challenge); $word = md5("\0" . $word . $chal); I would like to do the same in Django python. Any tips from your side please ?
[ "This approach produces the same result as the original php (at least on x86_64).\nimport hashlib\nimport struct\n\ncha1 = struct.pack('16B', *[int(c, 16) for c in (challenge[i:i+2]\n for i in xrange(0, len(challenge), 2))])\n\nword = hashlib.md5('\\0%s%s' % (word, cha1)).hexdigest()\n\nPython's struct.pack() me...
[ 1, 0 ]
[]
[]
[ "django", "md5", "pack", "php", "python" ]
stackoverflow_0005576089_django_md5_pack_php_python.txt
Q: convert IP to hostname I want to write a python script to convert IP addresses to hostnames. I am using a Linux box. I don't see this information in whois command. Are there any commands that always give the correct hostnames (as accurately as possible)? A: Socket library has an API to do reverse DNS lookups. i...
convert IP to hostname
I want to write a python script to convert IP addresses to hostnames. I am using a Linux box. I don't see this information in whois command. Are there any commands that always give the correct hostnames (as accurately as possible)?
[ "Socket library has an API to do reverse DNS lookups. \nimport socket\nsocket.gethostbyaddr(\"8.8.8.8\")\n>>> ('google-public-dns-a.google.com', [], ['8.8.8.8'])\n\nKeep in mind that not all IP addresses will have reverse DNS entries, not all aliases might be present in the answer to this query etc.\n", "The clos...
[ 14, 3 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005576744_linux_python.txt
Q: How to go about implementing this calendar feature I'm trying to make a calendar app that when you click through on a date, takes you to all the events for that particular date. I'm writing the app in Python/Django. A good example would be the event calendar in craigslist. I'm not sure how I should go about implem...
How to go about implementing this calendar feature
I'm trying to make a calendar app that when you click through on a date, takes you to all the events for that particular date. I'm writing the app in Python/Django. A good example would be the event calendar in craigslist. I'm not sure how I should go about implementing this. I'm not looking for exact solutions but mor...
[ "I guess your app is using database where you store all available events, right? Then you show calendar with date values. Then when you click some date, you just switch your presentation (view, page... whatever), connect to database and select all events that have same date as date from clicked element. Is this wha...
[ 0, 0 ]
[]
[]
[ "calendar", "django", "python" ]
stackoverflow_0005575856_calendar_django_python.txt
Q: Django in Pydev spawns multiple processes? I have my project setup in PyDev in Eclipse. Whenever I debug my project, things go great, but once I try to restart the Django server, it spawns an additional runserver process, blocking up the port I'm using for the server (8000). Is there a workaround to make sure it r...
Django in Pydev spawns multiple processes?
I have my project setup in PyDev in Eclipse. Whenever I debug my project, things go great, but once I try to restart the Django server, it spawns an additional runserver process, blocking up the port I'm using for the server (8000). Is there a workaround to make sure it really kills the server?
[ "Django reloads the server each time changes are made to any Python code (running another instance of the server and killing the old one). It seems that it's not handled properly when launched from Pydev. You can deactivate this by adding the --noreload argument to the server starting command.\nMore information: --...
[ 4 ]
[]
[]
[ "django", "eclipse", "pydev", "python" ]
stackoverflow_0005576305_django_eclipse_pydev_python.txt
Q: Reading zlib/gzip compressed data from MS SQL Server using Python I'm using Python 2.6 to read data from SQL Server. I'm stuck because a column in my DB is varbinary. I'm using pyodbc, and the data type in the Python program is "buffer". Now, this column in the DB stores gzip compressed text. I'm unable to figure ...
Reading zlib/gzip compressed data from MS SQL Server using Python
I'm using Python 2.6 to read data from SQL Server. I'm stuck because a column in my DB is varbinary. I'm using pyodbc, and the data type in the Python program is "buffer". Now, this column in the DB stores gzip compressed text. I'm unable to figure out how to decompress this from Python, given access to the 'buffer' da...
[ "Do this:\nprint repr(x[:3])\n\nA zlib stream typically starts with the 3 bytes x\\x9cc. A gzip stream always starts with the 2 bytes \\x1f\\x8b. What do you have?\nAccording to your comment, the resul was '+J\\xcd'. This doesn't appear to be zlib or gzip. What documentation do you have? Do you have source code for...
[ 0 ]
[]
[]
[ "pyodbc", "python", "sql_server" ]
stackoverflow_0005576952_pyodbc_python_sql_server.txt
Q: need xhtml2pdf (Pisa 3.0) css syntax for @page and @frame i'm trying stuff out with xhtml2pdf (aka Pisa 3.0) and django and am having trouble with the css http://www.xhtml2pdf.com/doc/pisa-en.html obviously the docs above talk about the css that is available as well as vendor specific tags. If i follow the example...
need xhtml2pdf (Pisa 3.0) css syntax for @page and @frame
i'm trying stuff out with xhtml2pdf (aka Pisa 3.0) and django and am having trouble with the css http://www.xhtml2pdf.com/doc/pisa-en.html obviously the docs above talk about the css that is available as well as vendor specific tags. If i follow the example in the docs for static frames and make css like @page{ ...
[ "@page{ seems to cause an error when there is no whitespace before the { changing to @page { works.\n" ]
[ 6 ]
[]
[]
[ "css", "django", "pdf_generation", "pisa", "python" ]
stackoverflow_0005562019_css_django_pdf_generation_pisa_python.txt
Q: Getting start/end of a python class from source Say I got a file with a few classes defined in it, like so: class A: def somemethod(self): pass ...more methods... class B: def othermethod(self): pass ....even more methods... How can I find out which line in the source Class A starts and ends, whi...
Getting start/end of a python class from source
Say I got a file with a few classes defined in it, like so: class A: def somemethod(self): pass ...more methods... class B: def othermethod(self): pass ....even more methods... How can I find out which line in the source Class A starts and ends, which line of code Class B start and ends? If load the f...
[ "I suggest using the standard library Python class browser (pyclbr) as a starting point.\n", "Think in terms of parsing the Abstract Syntax Tree, not in terms of raw lines. Even Python, with its line- rather than brackets-based syntax, can arrange multiple statements on a line with semicolon, or spread a statemen...
[ 2, 0 ]
[]
[]
[ "ide", "intellisense", "python" ]
stackoverflow_0005577115_ide_intellisense_python.txt
Q: Handling assertion in python I can't understand why this code: x='aaaa' try: self.assertTrue(x==y) except: print (x) generates me this error AssertionError: False is not True It should be handle it by print(x) EDIT original code is: try: self.assertTrue('aaaa'==self.compare_object_name[1]) except:...
Handling assertion in python
I can't understand why this code: x='aaaa' try: self.assertTrue(x==y) except: print (x) generates me this error AssertionError: False is not True It should be handle it by print(x) EDIT original code is: try: self.assertTrue('aaaa'==self.compare_object_name[1]) except: print ('aaa') @Space_C0wb0y ...
[ "You should include the code that defines the assertTrue method. From the output you get, I'd say that it actually does not throw an exception, but deals with it internally (thus the error message being printed, and not your value).\nYou can use the built-in assert statement of Python, which works as expected:\nx =...
[ 4 ]
[]
[]
[ "assert", "exception_handling", "python" ]
stackoverflow_0005577835_assert_exception_handling_python.txt
Q: How perl set the encoding?I want creates a directory with special name If I want do this with python,the code just like : #!usr/bin/python import os import sys reload(sys) sys.setdefaultencoding('utf-8') path = 'H:\\Dolly. - 。.〆bear小熊-葉鏗然-ω·)~☆ぼんじ' print(path) os.mkdir(path) but I try use perl,it does not work. ...
How perl set the encoding?I want creates a directory with special name
If I want do this with python,the code just like : #!usr/bin/python import os import sys reload(sys) sys.setdefaultencoding('utf-8') path = 'H:\\Dolly. - 。.〆bear小熊-葉鏗然-ω·)~☆ぼんじ' print(path) os.mkdir(path) but I try use perl,it does not work. #!/usr/bin/perl use File::Path; use utf8; path = 'H:\\Dolly. - 。.〆bear小熊-葉鏗然...
[ "Unfortunately, Perl is really bad at supporting Windows. In this case, this is partly due to Perl considering file names to be opaque strings of bytes rather than text. As such, the builtins don't use the (W)ide interface calls, so you are limited to your system's \"(A)NSI\" encoding. On most machines, thats's cp1...
[ 3 ]
[]
[]
[ "encoding", "perl", "python", "utf_8" ]
stackoverflow_0005576842_encoding_perl_python_utf_8.txt
Q: python logging to multiple files Does someone has an example of logging in python to 2 or more different logfiles. I want to log for example to '/tmp/foo.log' and '/tmp/bar.log' Thanks in advance T A: Here's an example: import logging logger1 = logging.getLogger('1') logger1.addHandler(logging.FileHandler('/tmp/...
python logging to multiple files
Does someone has an example of logging in python to 2 or more different logfiles. I want to log for example to '/tmp/foo.log' and '/tmp/bar.log' Thanks in advance T
[ "Here's an example:\nimport logging\nlogger1 = logging.getLogger('1')\nlogger1.addHandler(logging.FileHandler('/tmp/logger1'))\nlogger2 = logging.getLogger('2')\nlogger2.addHandler(logging.FileHandler('/tmp/logger2'))\n\nlogger1.error('1')\nlogger2.error('2')\n\nThen,\n $ cat /tmp/logger1\n 1\n $ cat /tmp/logger2\n...
[ 19, 4 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0005577637_django_logging_python.txt
Q: appscript attribute error I'm new to programming, and to python. I'm trying to use appscript in a python script to choose a pdf and a new destination folder, open the pdf in Adobe Acrobat Pro, OCR it, and save it in the new folder. Testing along they way, I'm getting an AttributeError after acrobat opens the pdf, ...
appscript attribute error
I'm new to programming, and to python. I'm trying to use appscript in a python script to choose a pdf and a new destination folder, open the pdf in Adobe Acrobat Pro, OCR it, and save it in the new folder. Testing along they way, I'm getting an AttributeError after acrobat opens the pdf, which trips the program before ...
[ "The activate command does not return an app reference. Try this:\nacrobat = app('Adobe Acrobat Pro')\nacrobat.activate()\nacrobat.open(fileURL)\n\n" ]
[ 1 ]
[]
[]
[ "attributeerror", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0005560082_attributeerror_py_appscript_python_sourceforge_appscript.txt
Q: Strange error in python 3.2 The following code is to find the mean of a given input set of numbers. #!/usr/bin/env python3 print("Enter some integers") count = 0 total = 0 while True: line = input("integer: ") if (line): try: number = int(line) except ValueError as err: ...
Strange error in python 3.2
The following code is to find the mean of a given input set of numbers. #!/usr/bin/env python3 print("Enter some integers") count = 0 total = 0 while True: line = input("integer: ") if (line): try: number = int(line) except ValueError as err: print(err) contin...
[ "Your problem is a question of cut and paste.\nThe line\nnumber = int(line)\n\nGenerates the error\ninvalid literal for int() with base 10: 'integer: 6'\n\nThis means that the line\nline = input(\"integer: \")\n\nMust have recieved the input:\n'integer: 6'\n\nAnd the only way it could have recieved this, is if that...
[ 1 ]
[]
[]
[ "python", "python_3.x", "syntax_error" ]
stackoverflow_0005576548_python_python_3.x_syntax_error.txt
Q: Building reusable components with gtk glade I am writing a simple application and am using glade (gtk) for the UI. I need many windows (~10), of which one will open depending upon the command line flags, other contextual stuff etc. Now, all these windows are pretty much similar, they have 3 top level tabs, the las...
Building reusable components with gtk glade
I am writing a simple application and am using glade (gtk) for the UI. I need many windows (~10), of which one will open depending upon the command line flags, other contextual stuff etc. Now, all these windows are pretty much similar, they have 3 top level tabs, the last tab is the same in all, all have a OK and Quit ...
[ "Design a widget with the common aspects you mention. Wherever you need to implement something different, put a GtkAlignment with an appropriate name. Don't forget to change the alignment and fill values of the GtkAlignment.\nIn PyGTK you can gtk.Builder.get_object(name) to get access to these empty regions and add...
[ 1, 0 ]
[]
[]
[ "glade", "pygtk", "python", "reusability" ]
stackoverflow_0005577339_glade_pygtk_python_reusability.txt
Q: Django packages for cloning Failblog I'm considering making something similar to Failblog using Django. That is, a blog where every post has a main picture or a main video, people can comment and vote on them, people can upload pictures and (YouTube-hosted) videos so they will become posts, there's a page where us...
Django packages for cloning Failblog
I'm considering making something similar to Failblog using Django. That is, a blog where every post has a main picture or a main video, people can comment and vote on them, people can upload pictures and (YouTube-hosted) videos so they will become posts, there's a page where users can vote on those new uploaded items b...
[ "Django basic apps \n" ]
[ 0 ]
[]
[]
[ "blogs", "clone", "django", "python" ]
stackoverflow_0005578579_blogs_clone_django_python.txt
Q: How to layout a queue/worker structure to support large tasks for multiple environments? For a Python/Django/Celery based deployment tool, we have the following setup: We currently use the default Celery setup. (One queue+exchange called "celery".) Each Task on the queue represents a deployment operation. Each ta...
How to layout a queue/worker structure to support large tasks for multiple environments?
For a Python/Django/Celery based deployment tool, we have the following setup: We currently use the default Celery setup. (One queue+exchange called "celery".) Each Task on the queue represents a deployment operation. Each task for an environment ends with a synchronisation phase that potentially takes (very) long. T...
[ "for 1,2 use multiple queues and launch workers with -Q to specify what queue to listen.\nAlso configure CELERYD_PREFETCH_MULTIPLIER = 1, for only one task at a time.\nTo get the queue lenght (tested with rabbitmq), you can use something like this:\nfrom kombu.connection import BrokerConnection\nconnection = Broker...
[ 2, 1 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0002781872_celery_django_python.txt
Q: how to add an empty list to a tuple I need to add an empty list to an existing tuple. example: >>> ([1],[1,2]) + ([]) ([1],[1,2],[]) My problem is that python seems to evaluate ([]) to [] on which i can't use the + operator. I tried tuple([]) but that evaluates to () and nothing is added to the original tup...
how to add an empty list to a tuple
I need to add an empty list to an existing tuple. example: >>> ([1],[1,2]) + ([]) ([1],[1,2],[]) My problem is that python seems to evaluate ([]) to [] on which i can't use the + operator. I tried tuple([]) but that evaluates to () and nothing is added to the original tuple. Thank you.
[ "Use a one-element tuple:\n([], )\n# ^\n\n", "Try \n>>> ([1],[1,2])+([],)\n([1], [1, 2], [])\n\nSimply putting something in between parentheses makes it an expression. Add a comma at the end to mark it as a tuple.\n", "Did you try\n([1],[1,2]) + ([],) \n\n", "tuples are immutable so you need to make a new tu...
[ 15, 7, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005579168_python.txt
Q: all paths between two nodes on the basis of edges My problem is all simple paths problem on hallucinogens. I need to find all the paths between two nodes on the basis of the edges and not nodes I found this as a solution but this approach is way too slow considering the size of my actual graph. I would like to kn...
all paths between two nodes on the basis of edges
My problem is all simple paths problem on hallucinogens. I need to find all the paths between two nodes on the basis of the edges and not nodes I found this as a solution but this approach is way too slow considering the size of my actual graph. I would like to know what are the optimizations that could be done to bet...
[ "Try to build new graph with where current edges are transformed into nodes and there is an edge beetween two nodes if we can use their corresponding edges consequently in a path. After it you can solve your problem with DFS.\n" ]
[ 0 ]
[]
[]
[ "algorithm", "graph", "networkx", "python" ]
stackoverflow_0005576699_algorithm_graph_networkx_python.txt
Q: IPython error: /usr/local/bin/iptest: Permission denied I'm trying to install iPython in Snow Leopard in Terminal. In the terminal window I type: $sudo /usr/bin/easy_install-2.6 ipython I get the following result: Searching for ipython Best match: ipython 0.10.1 Processing ipython-0.10.1-py2.6.egg ipython 0.10.1 ...
IPython error: /usr/local/bin/iptest: Permission denied
I'm trying to install iPython in Snow Leopard in Terminal. In the terminal window I type: $sudo /usr/bin/easy_install-2.6 ipython I get the following result: Searching for ipython Best match: ipython 0.10.1 Processing ipython-0.10.1-py2.6.egg ipython 0.10.1 is already the active version in easy-install.pth Installing ...
[ "I suggest not to mess up with your system python and use virtualenv instead.\nThis would avoid permission problems too.\n" ]
[ 0 ]
[ "Well, check the file permissions using ls -la on the file and if necessary\nuse 'chmod' to give the installed files the right permissions.\n" ]
[ -1 ]
[ "ipython", "macos", "permission_denied", "python", "sudo" ]
stackoverflow_0005530917_ipython_macos_permission_denied_python_sudo.txt
Q: python - inputstreamerror is not defined I'm working on someone else's code, and it's throwing an error that 'InputStreamError' is not defined. I'm new to python and am not sure how to tell where InputStreamError is defined and how to reference it from the code. This is what I've got at the moment: from hachoir_c...
python - inputstreamerror is not defined
I'm working on someone else's code, and it's throwing an error that 'InputStreamError' is not defined. I'm new to python and am not sure how to tell where InputStreamError is defined and how to reference it from the code. This is what I've got at the moment: from hachoir_core.error import HachoirError from hachoir_cor...
[ "Try adding a\nfrom hachoir_core.stream.input import InputStreamError\n\n" ]
[ 2 ]
[]
[]
[ "inputstream", "python" ]
stackoverflow_0005580273_inputstream_python.txt
Q: How can I query the enable status of a plugin in nose? I'm currently trying to see if a nose plugin is enabled from within my test harness. The specific thing I'm trying to do is propagate the enable status of the coverage module to subprocess executions. Essentially when --with-coverage is used, I want to execute...
How can I query the enable status of a plugin in nose?
I'm currently trying to see if a nose plugin is enabled from within my test harness. The specific thing I'm trying to do is propagate the enable status of the coverage module to subprocess executions. Essentially when --with-coverage is used, I want to execute the subprocesses under the coverage tool directly (or propa...
[ "This is one of those cases where you need to work around nose. See Measuring subprocesses in the coverage documentation for ways to ensure that subprocesses automatically invoke coverage.\n" ]
[ 1 ]
[]
[]
[ "coverage.py", "nose", "python" ]
stackoverflow_0005576936_coverage.py_nose_python.txt
Q: Return to the beginning of the table I have a table with numbers inside like this: 2, 3, 4, When I read all the line of the table I would like to start to read the table again. I'm writing in python and for the moment the only solution that I have is to do while loop which copies the table. But this solution isn't...
Return to the beginning of the table
I have a table with numbers inside like this: 2, 3, 4, When I read all the line of the table I would like to start to read the table again. I'm writing in python and for the moment the only solution that I have is to do while loop which copies the table. But this solution isn't very good. Do you know how I can do this?...
[ "Try:\ninfile = open(filename, \"r\")\ntable = []\nfor line in infile:\n table.append(line.split(\",\")\n\nNow you can run over the rows in your table (for row in table) or directly access cells (table[2][0]) as many times as you like.\nIf your data is CSV, you should consider using the csv module to handle it p...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005578574_python.txt
Q: Using regular expressions in python to determine C++ functions and their parameters So I'm doing something wrong in this python script, but it's becoming convoluted and I'm losing sight of what I'm doing wrong. I want a script to go through a file, find all the function definitions, and then pull out the name, ret...
Using regular expressions in python to determine C++ functions and their parameters
So I'm doing something wrong in this python script, but it's becoming convoluted and I'm losing sight of what I'm doing wrong. I want a script to go through a file, find all the function definitions, and then pull out the name, return type, and parameters of the function, and output a "doxygen" style comment like this:...
[ "The grammar of C++ is far too complex to be handled by simple\nregular expressions. You'll need at least a minimal parser.\nI've found that for restricted cases, where I'm not concerned\nwith C++ in general, but only my own style, I can often get away\nwith a flex based tokenizer and a simple state machine. This...
[ 3, 2, 0 ]
[]
[]
[ "c++", "doxygen", "parsing", "python", "regex" ]
stackoverflow_0005577425_c++_doxygen_parsing_python_regex.txt
Q: Seek into a file full of pickled objects I have this huge file with objects pickled in, lets assume: for object in objects: pickle.dump(myfile,object) The objects are of different size although they are the same type. The file gets filled for a long time on different occasions, but from time to time, when the ...
Seek into a file full of pickled objects
I have this huge file with objects pickled in, lets assume: for object in objects: pickle.dump(myfile,object) The objects are of different size although they are the same type. The file gets filled for a long time on different occasions, but from time to time, when the dumping process gets restarted, I would need t...
[ "One way is to do something like this:\nimport os, pickle, struct\n\nmyfile = open('/path/to/my/file', 'w+b')\nmyfile.write(struct.pack('L', 0)) # write a long of zeroes\nindex = []\nfor o in objects:\n index.append(myfile.tell())\n pickle.dump(o, myfile)\nindex_loc = myfile.tell()\npickle.dump(index, myfile)...
[ 3, 0 ]
[]
[]
[ "file", "pickle", "python" ]
stackoverflow_0005580201_file_pickle_python.txt
Q: Double return in python class method When I call the following method, two returns are executed and I can't figure out why. def Build(self, name = None): if self.buildData: try: installData = self.buildData.Build(name) return BuildResult(True, installData) except: ...
Double return in python class method
When I call the following method, two returns are executed and I can't figure out why. def Build(self, name = None): if self.buildData: try: installData = self.buildData.Build(name) return BuildResult(True, installData) except: pass else: Log("Applicat...
[ "Well, I guess that BuildResult() fails, exception is passed and you go into second return. You can easy test it just by adding some debug print in except - never make exceptions silent :)\n", "When return BuildResult(True, installData) is executed BuildResult(True, installData) is evaluated first. My guess is, ...
[ 7, 1 ]
[]
[]
[ "python", "return_value" ]
stackoverflow_0005580676_python_return_value.txt
Q: Python Submodules an easier reference I don't know if this is possible in python but here goes ... I have a folder structure similar to this \webapplication \forms __init__.py model01.py # (defines Model01Form) model02.py # (defines Model02Form) \views __init__.py ...
Python Submodules an easier reference
I don't know if this is possible in python but here goes ... I have a folder structure similar to this \webapplication \forms __init__.py model01.py # (defines Model01Form) model02.py # (defines Model02Form) \views __init__.py admin.py # (this file imports the forms)...
[ "Only if you import the forms into __init__.py in the first place:\nfrom model01 import Model01Form\nfrom model02 import Model02Form\n\nHowever, you should ask yourself if you necessarily need to have two separate model files. Python is not Java: you can have as many classes in a module as you like.\n" ]
[ 6 ]
[]
[]
[ "package", "python" ]
stackoverflow_0005580859_package_python.txt
Q: py2exe has inconsistent behavior with its source .py files My python program has many function which all seem to work fine when run from the .py script. After compiling with py2exe several of the sections of code have very inconsistent behavior. This section seems to be very consistent in its failure. def unzipIt...
py2exe has inconsistent behavior with its source .py files
My python program has many function which all seem to work fine when run from the .py script. After compiling with py2exe several of the sections of code have very inconsistent behavior. This section seems to be very consistent in its failure. def unzipItem(self, fileName, destination): print "--unzipItem--" z...
[ "Not a real answer as to why this occured - but using cx_Freeze instead of py2exe solved this problem.\n" ]
[ 0 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0005580792_py2exe_python.txt
Q: Unable to extract method name in Suds when user is allowed to select a method at run time from suds.client import Client from suds.transport.https import HttpAuthenticated import urllib2 class methodinvokeclass(): def methodinvokemethod(self,*args): method=args[1] c=args[2] ...
Unable to extract method name in Suds when user is allowed to select a method at run time
from suds.client import Client from suds.transport.https import HttpAuthenticated import urllib2 class methodinvokeclass(): def methodinvokemethod(self,*args): method=args[1] c=args[2] #method=LatLonListZipCode in the variable above response=c.service.method("90210")-...
[ "#method constains a string (eg: 'LatLonListZipCode')\nmethod_to_call = getattr(c.service, method)\nresponse = method_to_call(\"90210\")\n\nAlso, you have to do some error checking in case the method can't be found.\n" ]
[ 0 ]
[]
[]
[ "introspection", "methods", "python", "suds" ]
stackoverflow_0005579154_introspection_methods_python_suds.txt
Q: reference issue in python Why is the assignment operator is not making a copy of the rvalue but a reference to that(on a list), and you have to use slices in order to make a real copy which creates an independent object so that changes on one does not affect the other. Is this related to some specific usage relate...
reference issue in python
Why is the assignment operator is not making a copy of the rvalue but a reference to that(on a list), and you have to use slices in order to make a real copy which creates an independent object so that changes on one does not affect the other. Is this related to some specific usage related the language that I missed un...
[ "In python, everything can be considered as a reference. If you want an assignment to be a copy, you always need to put it excplicitely in your expression\na = range(10) # create a list and assign it to \"a\"\nb = a # assign the object referenced by \"a\" to b\na is b # True --> a and b are two references to the s...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005580486_python.txt
Q: Easier way to check conditions? I'm new to python and I need to simplify this checker. How can I change: ... if c == '>' and ( prevTime > currentTime ): c2 = True elif c == '>=' and ( prevTime >= currentTime ): c2 = True ... to something like: if prevTime | condition | currentTime: doSomething() I...
Easier way to check conditions?
I'm new to python and I need to simplify this checker. How can I change: ... if c == '>' and ( prevTime > currentTime ): c2 = True elif c == '>=' and ( prevTime >= currentTime ): c2 = True ... to something like: if prevTime | condition | currentTime: doSomething() I've tried to use either evaluate or c...
[ "You can try making a map of operators, like this:\nimport operator\n\ncompares = {\n '>': operator.gt,\n '>=': operator.ge,\n '<': operator.lt,\n '<=': operator.le,\n '==': operator.eq\n}\n\ndef check(c, prev, current):\n func = compares[c]\n return func(prev, current)\n\nprint check('>', 5, 3...
[ 8, 5, 0, 0 ]
[]
[]
[ "multiple_conditions", "python" ]
stackoverflow_0005581470_multiple_conditions_python.txt
Q: Python to C++ function conversion using Boost.Python I have a bunch of classes and APIs written in C++ and exposed to Python with help of Boost.Python I am currently investigating the possibilities of creating the following architecture. In python: from boostPythonModule import * AddFunction( boostPythonObject.Me...
Python to C++ function conversion using Boost.Python
I have a bunch of classes and APIs written in C++ and exposed to Python with help of Boost.Python I am currently investigating the possibilities of creating the following architecture. In python: from boostPythonModule import * AddFunction( boostPythonObject.Method1, args ) AddFunction( boostPythonObject.Method2, args...
[ "I would think about caching functions and their arguments on python level - save the arguments using the latest form from Keyword arguments section of tutorial and call your C++ functions later unpacking saved arguments unpacking done at python level will isolate you from any boost typesafety complications (all ty...
[ 1 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0003946055_boost_python_c++_python.txt
Q: Python min() apparently not accepting list of ints def minmax (actual, min, max): print 'actual', actual, type(actual) print 'min', min, type(min) print 'max', max, type(max) if actual: if min(actual) < min: min = min(actual1) if max(actual) > max: max = max(...
Python min() apparently not accepting list of ints
def minmax (actual, min, max): print 'actual', actual, type(actual) print 'min', min, type(min) print 'max', max, type(max) if actual: if min(actual) < min: min = min(actual1) if max(actual) > max: max = max(actual1) return min, max I wonder, why does this co...
[ "You are overriding min() function with your min argument of type int, that's why. Rename it to something else.\ndef minmax (actual, min, max):\n print 'actual', actual, type(actual)\n print 'min', min, type(min)\n print 'max', max, type(max)\n if actual:\n if min(actual) < min: #<- min(actu...
[ 12, 11 ]
[]
[]
[ "list", "min", "python" ]
stackoverflow_0005581719_list_min_python.txt
Q: easy_install python What to do after doing all the steps to install easy_install python & the paths are available in the script what shall I do I'm really fed up because I have done all steps several time then open idle & write easy_install tell me invalid! A: i want to install easy_install to be able to import ...
easy_install python
What to do after doing all the steps to install easy_install python & the paths are available in the script what shall I do I'm really fed up because I have done all steps several time then open idle & write easy_install tell me invalid!
[ "\ni want to install easy_install to be able to import packages like geopy\n\nDon't trouble yourself with installing setuptools. ActivePython already includes easy_install, pip, PyPM and virtualenv.\n\nInstall ActivePython (why?) \nOpen Command Prompt and type pypm install geopy\n\n" ]
[ 1 ]
[]
[]
[ "easy_install", "python", "windows_7" ]
stackoverflow_0005581476_easy_install_python_windows_7.txt
Q: Lowest footprint Python? CPython? I'm new in Python. After some searching, I've found that PyPy has great performance but it comes with a price. It use too much memory. What I'm looking for in Python is performance with smallest possible footprint. How about CPython? (CPython benchmark in shootout.alioth.debian.or...
Lowest footprint Python? CPython?
I'm new in Python. After some searching, I've found that PyPy has great performance but it comes with a price. It use too much memory. What I'm looking for in Python is performance with smallest possible footprint. How about CPython? (CPython benchmark in shootout.alioth.debian.org has been removed. Some people say CPy...
[ "When people talk about \"Python\" usually this refers to CPython, PyPy is a Python implementation whose goal is to improve performance and offers a JIT compiler that improves performance.\nIf you are worrying about performance, Cpython is fine tuned very well. Most of the time the slowness you would get would be f...
[ 2, 2 ]
[]
[]
[ "cpython", "jit", "pypy", "python" ]
stackoverflow_0005581743_cpython_jit_pypy_python.txt
Q: Add a debugging page to a Django project? I'm supplying a Django project to a client, who has requested a 'debugging' page that will show useful information. [UPDATE for clarity: We'd like this page so we can use it for debugging in future: the clients are not very technical and I won't have direct access to thei...
Add a debugging page to a Django project?
I'm supplying a Django project to a client, who has requested a 'debugging' page that will show useful information. [UPDATE for clarity: We'd like this page so we can use it for debugging in future: the clients are not very technical and I won't have direct access to their servers. In the event of future issues, it wo...
[ "You can use Django Debug Toolbar and enable it only for choosen IPs\n", "\nGoogling 'standard Django debugging page'\n\nIsn't as effective as reading the Django source itself.\nLook in base.py for code like this\nfrom django.views import debug\n\nThat will provide you some hints as to how they do it.\nThen you c...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005581005_django_python.txt
Q: From PHP to Python accommodation I've been coding php for years, and now i have to finally make my own project, and i want it very optimized and shiny. So, i've been searching around the net about which programming language should i use for my needs (fast, secure, easy-understandable, customizable) and all points ...
From PHP to Python accommodation
I've been coding php for years, and now i have to finally make my own project, and i want it very optimized and shiny. So, i've been searching around the net about which programming language should i use for my needs (fast, secure, easy-understandable, customizable) and all points to -> Python. So I decided to go on, b...
[ "Use what you like and what you know. If you want to try something new that's ok .. but if you want to start a serios project now I would not use a new language for this.\nMaybe better look what you could do better with php. (Maybe use a better template engine or design clever classes or whatever). Many huge webapp...
[ 4, 2, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0005582450_php_python.txt
Q: os.path.getsize() returns negative filesize for large files (for > 3GB file size) I am using python on embedded device which is running linux 2.6.32. Using python to fetch the file size as os.path.getsize() returns me a negative value. I refered to one of the similar questions here on stack overflow and tried reco...
os.path.getsize() returns negative filesize for large files (for > 3GB file size)
I am using python on embedded device which is running linux 2.6.32. Using python to fetch the file size as os.path.getsize() returns me a negative value. I refered to one of the similar questions here on stack overflow and tried recompiling python with CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $...
[ "Clearly, something is wrong with your Linux distribution's build of Python. Rather than fix the actual problem, it might be easier to just work around it:\ndef getsize_workaround( filename ):\n size = os.path.getsize( filename )\n if size < 0:\n import subprocess as s\n size = long( s.Popen(\"l...
[ 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005579407_linux_python.txt
Q: Django settings.py: Separate local and global configuration I was wondering if it was possible to separate the "local" configuration in Django (Local path to static, templates content which have to be absolute, local DB info, etc...) from the "global" configuration (URL, Middleware classes, installed apps, etc...)...
Django settings.py: Separate local and global configuration
I was wondering if it was possible to separate the "local" configuration in Django (Local path to static, templates content which have to be absolute, local DB info, etc...) from the "global" configuration (URL, Middleware classes, installed apps, etc...) so that several people can work on a same project over Git or SV...
[ "Yes, definitely. The settings.py file is just Python, so you can do anything in there - including setting things dynamically, and importing other files to override.\nSo there's two approaches here. The first is not to hard-code any paths, but calculate them dynamically. \nPROJECT_ROOT = os.path.abspath(os.path.dir...
[ 14, 0 ]
[]
[]
[ "configuration", "django", "git", "project_management", "python" ]
stackoverflow_0005583077_configuration_django_git_project_management_python.txt
Q: PyODBC on Snow Leopard - Install Error Has anyone succesffuly installed PyODBC on snow leopard? I'm getting the error below. (I also submitted a bug here too) Any ideas how to fix this and get it installed? Here is the output I'm getting: $ python setup.py install running install running bdist_egg running egg_in...
PyODBC on Snow Leopard - Install Error
Has anyone succesffuly installed PyODBC on snow leopard? I'm getting the error below. (I also submitted a bug here too) Any ideas how to fix this and get it installed? Here is the output I'm getting: $ python setup.py install running install running bdist_egg running egg_info writing pyodbc.egg-info/PKG-INFO writing ...
[ "Your problem is likely the combination of xcode 4 and setuptools. See this error:\n/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/datetime.h:186: warning: ‘PyDateTimeAPI’ defined but not used\n/usr/libexec/gcc/powerpc-apple-darwin10/4.2.1/as: assembler (/usr/bin/../libexec/gcc/darwin/p...
[ 2, 1 ]
[]
[]
[ "gcc", "macos", "osx_snow_leopard", "pyodbc", "python" ]
stackoverflow_0005582567_gcc_macos_osx_snow_leopard_pyodbc_python.txt
Q: exception handling for optparse of python HI, guys. I am using cmd and optparse to develop a CLI.py for a collection of already-functional classes (CDContainer, CD, etc.). The following are some parts of the code. I have a problem here. when there are exceptions(wrong input type or missing values), the optparse w...
exception handling for optparse of python
HI, guys. I am using cmd and optparse to develop a CLI.py for a collection of already-functional classes (CDContainer, CD, etc.). The following are some parts of the code. I have a problem here. when there are exceptions(wrong input type or missing values), the optparse will exit the whole program instead of the speci...
[ "The optparse documentation says this:\n\nIf optparse‘s default error-handling behaviour does not suit your needs, you’ll need to subclass OptionParser and override its exit() and/or error() methods.\n\nIdeally you'd define a new type of exception, subclass optparse, raise the exception in the exit() or error() met...
[ 11, 0, 0 ]
[]
[]
[ "command_line", "exception_handling", "python" ]
stackoverflow_0004014211_command_line_exception_handling_python.txt
Q: Error using simple decorator in Python def simple_decorator(f): def tmp(*args, **kwargs): res = f(*args, **kwargs) return res return tmp @simple_decorator class FirstClass(): pass @simple_decorator class SecondClass(FirstClass): pass I have error: File "1.py", line 16, in <module...
Error using simple decorator in Python
def simple_decorator(f): def tmp(*args, **kwargs): res = f(*args, **kwargs) return res return tmp @simple_decorator class FirstClass(): pass @simple_decorator class SecondClass(FirstClass): pass I have error: File "1.py", line 16, in <module> class SecondClass(FirstClass): TypeError:...
[ "Your decorator returns a function, so FirstClass is a function, not a class; decorators are not required to return an object that is the same type as the input.\n", "Your mistake is that you're trying to decorate a class.\nCheck PEP-3129.\n" ]
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005584002_python.txt
Q: Unable utilize a methodname(from webservice)present in the form of a string.I tried utilizing getattr,but then not unable to extend it for suds from suds.client import Client #@UnresolvedImport from suds.transport.https import HttpAuthenticated #@UnresolvedImport import urllib2 class methodinvokeclass(): def ...
Unable utilize a methodname(from webservice)present in the form of a string.I tried utilizing getattr,but then not unable to extend it for suds
from suds.client import Client #@UnresolvedImport from suds.transport.https import HttpAuthenticated #@UnresolvedImport import urllib2 class methodinvokeclass(): def methodinvokemethod(self,*args): method=args[1] c=args[2] print c response=c.service.method("90210")# I know this won...
[ "You can use getattr to retrieve the SOAP method from the service. Use this instead:\nimpl = getattr(c.service, method)\nresponse = impl('90210')\nprint response\n\nHere is a working example, using a webservicex test SOAP service:\nurl = 'http://www.webservicex.net/stockquote.asmx?WSDL'\nclient = Client(url=url)\nn...
[ 0 ]
[]
[]
[ "getattr", "python", "reflection", "suds" ]
stackoverflow_0005575875_getattr_python_reflection_suds.txt
Q: inputing choices for a flask poll app I have made a database schema for a poll app I am making using Flask as follows: CREATE TABLE questions ( question_id integer primary key autoincrement, questiontext string not null ); CREATE TABLE choices ( choice_id integer primary key autoincrement, choicet...
inputing choices for a flask poll app
I have made a database schema for a poll app I am making using Flask as follows: CREATE TABLE questions ( question_id integer primary key autoincrement, questiontext string not null ); CREATE TABLE choices ( choice_id integer primary key autoincrement, choicetext string not null, question_id intege...
[ "Without the full template or HTML, I am going to assume the HTML <form> is valid. See HTML Forms and Inputs if you suspect a problem there.\nTo verify that form values are reaching your add_poll() function, try using Flask debug mode (i.e. set app.debug = True prior to app.run()). To force invocation of the debu...
[ 2 ]
[]
[]
[ "flask", "html", "jinja2", "python", "sqlite" ]
stackoverflow_0005576005_flask_html_jinja2_python_sqlite.txt
Q: Is the builtin hash method of Python2.6 stable across architectures? I need to compute a hash that needs to be stable across architectures. Is python's hash() stable? To be more specific, the example below shows hash() computing the same value on two different hosts/architectures: # on OSX based laptop >>> hash((...
Is the builtin hash method of Python2.6 stable across architectures?
I need to compute a hash that needs to be stable across architectures. Is python's hash() stable? To be more specific, the example below shows hash() computing the same value on two different hosts/architectures: # on OSX based laptop >>> hash((1,2,3,4)) 485696759010151909 # on x86_64 Linux host >>> hash((1,2,3,4)) 48...
[ "If you need a well defined hash, you can use one out of hashlib.\n", "The hash() function is not what you want; finding a reliable way to serialize the object (eg str() or repr()) and running it through hashlib.md5() would probably be much more preferrable. \nIn detail - hash() is designed to return an integer w...
[ 11, 9, 6, 5 ]
[]
[]
[ "python" ]
stackoverflow_0005583907_python.txt
Q: Text escaped when I want it to show up as html in Flask/jinja2 I pull a feed from rss and store the data in a appengine db. The rss feed content includes the entire html. So I have this python code: @app.route("/rssRead") def pullRss(): feedItem = db.getFeedItemByName(request.args.get('title',None), request....
Text escaped when I want it to show up as html in Flask/jinja2
I pull a feed from rss and store the data in a appengine db. The rss feed content includes the entire html. So I have this python code: @app.route("/rssRead") def pullRss(): feedItem = db.getFeedItemByName(request.args.get('title',None), request.args.get('key',None)) return render_template("rss.html", data= M...
[ "This should work too.\n{% extends \"layout.html\" %}\n{% block body %}\n{{ data|safe }}\n{% endblock %}\n\n", "Instead of data=Markup(feedItem.html).unescape(), you should be using data=Markup(feedItem.html). That will do the right thing and keep your template clean.\nCalling unescape() here is pointless (unless...
[ 111, 16 ]
[]
[]
[ "flask", "jinja2", "python" ]
stackoverflow_0005572225_flask_jinja2_python.txt
Q: How to know name of class in decorator for function-method? I have a simple timemark-decorator for function: def dec_timemark(f): def tmp(*args, **kwargs): sys.stdout.write(strftime("%d.%m.%Y %H:%M:%S") + ' ' + f.__name__ + ' begin' + "\n" ) ...
How to know name of class in decorator for function-method?
I have a simple timemark-decorator for function: def dec_timemark(f): def tmp(*args, **kwargs): sys.stdout.write(strftime("%d.%m.%Y %H:%M:%S") + ' ' + f.__name__ + ' begin' + "\n" ) res = f(*args, **kwargs) sys.stdout.write(strftime("%...
[ "Assuming that the decorated routine is invoked as a method, you can pull the classname out of the self parameter:\ndef dump(f):\n def decorated(self, *args, **kwargs):\n print 'Class: {0}'.format(self.__class__.__name__)\n print 'Args passed to decorated function: {0}'.format(args)\n print ...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005582393_python.txt
Q: Find databasetype ( SQlite, Mysql, PostgreSQL ) from dbapi in python I need to find out what kind of database I am working against based on data from an dbapi cursor instance. Have not found any clues on how to do this in the dbapi docs. Can it be done? A: It isn't part of the dbapi 2.0, at least to my knowledge...
Find databasetype ( SQlite, Mysql, PostgreSQL ) from dbapi in python
I need to find out what kind of database I am working against based on data from an dbapi cursor instance. Have not found any clues on how to do this in the dbapi docs. Can it be done?
[ "It isn't part of the dbapi 2.0, at least to my knowledge. However, you can implement a function to obtain the module name from a given database object (cursor, connection) and map that to a well-known string for your application to use:\n_DBNAME_MAP = {\n 'psycopg2': 'postgres',\n 'MySQLdb': 'mysql',\n '...
[ 2 ]
[]
[]
[ "database", "python", "python_db_api" ]
stackoverflow_0005584530_database_python_python_db_api.txt
Q: Is there a way to wrap a tkinter GUI in a class that can be created and interacted with from another object? (*without* hanging in mainloop) Is there a way to wrap a tkinter GUI in a class that can be created and interacted with from another object? For this to be really useful, the class has to work so mainloop o...
Is there a way to wrap a tkinter GUI in a class that can be created and interacted with from another object? (*without* hanging in mainloop)
Is there a way to wrap a tkinter GUI in a class that can be created and interacted with from another object? For this to be really useful, the class has to work so mainloop or its equivalent doesn't hold the application. If so, can someone point me to a working example? For context, what I'm trying to do is make a Sim...
[ "Is this what you're looking for?\n#The threading module allows you to subclass it's thread class to create\n#and run a thread, in this case we will be starting SimpleUI in a seperate thread\n\nimport threading\nfrom Tkinter import *\n\ndef printfunction():\n print \"ButtonPress\"\n\nclass NewClass:\n def __i...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0005547000_python_tkinter.txt
Q: Initialization of unit-test in PyDev? I am unit-testing my python code in eclipse using PyDev unit-testing. I right click on the appropriate file and select Run As -> Python unit-test. Concerning this plugin I have a few questions: Is there a way to have a setUpClass method that is being executed before any other...
Initialization of unit-test in PyDev?
I am unit-testing my python code in eclipse using PyDev unit-testing. I right click on the appropriate file and select Run As -> Python unit-test. Concerning this plugin I have a few questions: Is there a way to have a setUpClass method that is being executed before any other test within this class? Currently I am onl...
[ "It's a PyDev bug, and has been fixed in 2.0.1.\nsetUpModule(), tearDownModule(), setUpClass(), and tearDownClass() are not run in the 'Python unit-test' run configuration due to the bug in PyDev 2.0.0 and earlier. In 2.0.1 they run correctly in the 'Python unit-test' and 'Python Run' configurations. I tested it my...
[ 7, 5, 2, 0 ]
[]
[]
[ "eclipse", "eclipse_plugin", "pydev", "python", "unit_testing" ]
stackoverflow_0005430707_eclipse_eclipse_plugin_pydev_python_unit_testing.txt
Q: list problem in Python I have 2 lists: first is list that I need to work with and the second is list of -1. First of all I need to find the remainder of the divison of the number (number is len(lst)) and put it to the position (remainder of the divisor) in the list of -1. If there is already element, then to the n...
list problem in Python
I have 2 lists: first is list that I need to work with and the second is list of -1. First of all I need to find the remainder of the divison of the number (number is len(lst)) and put it to the position (remainder of the divisor) in the list of -1. If there is already element, then to the next position in the list (if...
[ "You introduce arv, but you never assigned it a dict. Since it is a dict, assign arv as:\narv = {}\n\nI would also use:\nfor i,elem in enumerate(lst):\n\nYou can now iterate over lst, while also knowing its position.\n", "The line you indicated with a comment refers to a list that does not exist (arv) and I canno...
[ 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005585140_list_python.txt
Q: Threading vs Multiprocess vs Twisted in Python Can I get help converting this code from Threading to Mutliprocess. Then can anyone help convert this code usinf twisted. Would there be a gain from using twisted to upload db within Python vs External tools. import os, pyodbc, sys, threading, Queue class WorkerThr...
Threading vs Multiprocess vs Twisted in Python
Can I get help converting this code from Threading to Mutliprocess. Then can anyone help convert this code usinf twisted. Would there be a gain from using twisted to upload db within Python vs External tools. import os, pyodbc, sys, threading, Queue class WorkerThread(threading.Thread): def __init__(self, queue...
[ "Updated: JP mentioned the txpostgres and txmysql modules, which I wasn't aware of. These allow Twisted to access both databases asynchronously (without using a thread pool).\nNote that if you decide to use Twisted's enterprise adbapi, it will end up using a thread pool to handle database connections, roughly the e...
[ 1 ]
[]
[]
[ "multiprocessing", "multithreading", "mysql", "python", "twisted" ]
stackoverflow_0005585055_multiprocessing_multithreading_mysql_python_twisted.txt
Q: Upgraded Python on Snowleopard Using Homebrew now pip and easy_install don't work I am new to python, I have changed my path to point to the new python 2.7, but pip and easy_install, and mercurial are still looking at the default installed version 2.6. How do I fix this? A: You need to install pip and setuptools...
Upgraded Python on Snowleopard Using Homebrew now pip and easy_install don't work
I am new to python, I have changed my path to point to the new python 2.7, but pip and easy_install, and mercurial are still looking at the default installed version 2.6. How do I fix this?
[ "You need to install pip and setuptools again (which provides the easy_install command) for your new version of Python. pip and setuptools are not globally installed, rather they must be installed specifically for each version of Python on your system.\nTo install pip:\n$ curl -O https://github.com/pypa/pip/raw/mas...
[ 5, 4 ]
[]
[]
[ "easy_install", "pip", "python" ]
stackoverflow_0005585473_easy_install_pip_python.txt
Q: How to concisely represent if/else to specify CSS classes in Django templates In a Django template, I'd like to add CSS classes to a DIV based on certain "conditions", for example: <div class="pkg-buildinfo {% if v.release.version == pkg.b.release.version %}active{% else %}inactive{% endif %} ...
How to concisely represent if/else to specify CSS classes in Django templates
In a Django template, I'd like to add CSS classes to a DIV based on certain "conditions", for example: <div class="pkg-buildinfo {% if v.release.version == pkg.b.release.version %}active{% else %}inactive{% endif %} {% if v.release.version == project.latest.version %}latest{% else %}notlatest{...
[ "You could put that logic into your view instead, and create attributes on the object that are \"active\" or \"inactive\", etc. Then you only have to access the attributes in the template.\n", "A custom filter might be a nice alternative.\n@register.filter\ndef active_class(obj, pkg):\n if obj.release.version...
[ 6, 5, 4 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0005584426_django_django_templates_python.txt
Q: How can locals() be exploited in python code? I stumbled across the following warning when I was reading Code Like a Pythonista: Idiomatic Python by David Goodger. Excerpt from the article ... print('Hello %(name)s, you have %(messages)i messages' % locals()) This is very powerful. With this, you can do all th...
How can locals() be exploited in python code?
I stumbled across the following warning when I was reading Code Like a Pythonista: Idiomatic Python by David Goodger. Excerpt from the article ... print('Hello %(name)s, you have %(messages)i messages' % locals()) This is very powerful. With this, you can do all the string formatting you want without having to wo...
[ "Sample, trivial code:\nscript_name = 'readpw.py'\n...\nentered_pw = raw_input()\nif entered_pw != real_pw:\n print \"%(script_name)s: The password you entered: \"+entered_pw+\" is incorrect.\"%locals()\n\nConsider the case where entered_pw is %(real_pw)s\n", "A simple example: If you have some magic ultra imp...
[ 6, 4 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0005585648_namespaces_python.txt
Q: what's the difference between python objects and json objects? On the surface it appears that python uses json natively. The only exception I can think of is the fact that json can store js functions. Here's my issue: I need to pass json to a python file through the terminal. Why should or shouldn't I just use ev...
what's the difference between python objects and json objects?
On the surface it appears that python uses json natively. The only exception I can think of is the fact that json can store js functions. Here's my issue: I need to pass json to a python file through the terminal. Why should or shouldn't I just use eval()?
[ "No, Python does not use JSON natively. This stuff you think is JSON is, in fact, a dictionary, one of many kinds of objects in Python. The (easy) syntax for building a dictionary in Python is pretty close to JSON but it is incidental. As you can create a dictionary this way:\na = {'a' : 2, 'b' : 3}\n\nyou can crea...
[ 27, 18 ]
[]
[]
[ "django", "javascript", "json", "node.js", "python" ]
stackoverflow_0005584943_django_javascript_json_node.js_python.txt
Q: Imaplib: how to delete an email from Gmail? I am trying to do something as simple as moving an email from inbox to trash using the imaplib of python. However, I am having some problems and I don't know how to solve them. After connect and login into the server, I select the INBOX mailbox and I get the ids list thi...
Imaplib: how to delete an email from Gmail?
I am trying to do something as simple as moving an email from inbox to trash using the imaplib of python. However, I am having some problems and I don't know how to solve them. After connect and login into the server, I select the INBOX mailbox and I get the ids list this way: typ, ids = imap_object.search(None, 'INBOX...
[ "I believe your conversation isn't really deleted: By default, deleting a message per IMAP from the last folder archives the conversation. Have a look at Settings -> Forwarding and POP/IMAP -> When a message is marked as deleted and expunged from the last visible IMAP folder:\n" ]
[ 2 ]
[]
[]
[ "email", "imaplib", "python" ]
stackoverflow_0003013283_email_imaplib_python.txt
Q: How to implement user authentication and sessions with Python Possible Duplicate: Bottle-friendly WSGI authentication library/middleware I'm creating a simple web application with Python and Bottle. What would be some simple way to add user authentication / sessions to this setup? A: See the topic Bottle Frien...
How to implement user authentication and sessions with Python
Possible Duplicate: Bottle-friendly WSGI authentication library/middleware I'm creating a simple web application with Python and Bottle. What would be some simple way to add user authentication / sessions to this setup?
[ "See the topic Bottle Friendly Wsgi Authentication Library Middleware\n" ]
[ 5 ]
[]
[]
[ "authentication", "bottle", "python", "session", "web_applications" ]
stackoverflow_0005586141_authentication_bottle_python_session_web_applications.txt
Q: Where should I define data gathering methods in Django I am working on a simple music website which gathers data from Last.Fm, MusicBrainz, and others. So far when I add an Artist (just by name) it gathers all it's albums and songs and saves them. I decided to put this in a customized save method for the Artist. T...
Where should I define data gathering methods in Django
I am working on a simple music website which gathers data from Last.Fm, MusicBrainz, and others. So far when I add an Artist (just by name) it gathers all it's albums and songs and saves them. I decided to put this in a customized save method for the Artist. This process can last up to 2 or 3 minutes using runserver. I...
[ "You'd be much better off doing this sort of task in a background process – one that doesn't block the request/response cycle of HTTP. There's a couple of decent ways to do, you can write a management command that you would run via python manage.py .... \nHowever, I strongly suggest you have a look at Celery. There...
[ 7 ]
[]
[]
[ "api", "django", "python" ]
stackoverflow_0005586209_api_django_python.txt
Q: Using SlopeOne algorithm to predict if a gamer can complete a level in a Game? I am planning to use SlopeOne algorithm to predict if a gamer can complete a given level in a Game or not? Here is the scenario: Lots of Gamers play and try to complete 100 levels in the game. Each gamer can play a level as many times ...
Using SlopeOne algorithm to predict if a gamer can complete a level in a Game?
I am planning to use SlopeOne algorithm to predict if a gamer can complete a given level in a Game or not? Here is the scenario: Lots of Gamers play and try to complete 100 levels in the game. Each gamer can play a level as many times as they want until they cross the level. The system keeps track of the level and the...
[ "I think it might work, but I would apply log to the number of tries (you can't do log(0) so retries won't work) first. If someone found a level easy they would try it once or twice, whereas people who found it hard would generally have to do it over and over again. The difference between did it in 1 go vs 2 goes i...
[ 2, 0 ]
[]
[]
[ "algorithm", "collaborative", "filtering", "prediction", "python" ]
stackoverflow_0004273169_algorithm_collaborative_filtering_prediction_python.txt
Q: How to manage/host AWS SQS queue consumers in Python? I am currently working on a distributed processing application written in Python that utilises Amazon SQS. What is the most Pythonic way of properly creating and hosting a queue consumer in Python that: is reliable: if there is a problem and the consumer termi...
How to manage/host AWS SQS queue consumers in Python?
I am currently working on a distributed processing application written in Python that utilises Amazon SQS. What is the most Pythonic way of properly creating and hosting a queue consumer in Python that: is reliable: if there is a problem and the consumer terminates, some reactive code should be executed and processing...
[ "Have you looked at Boto? \n\nAn integrated interface to current and\n future infrastructural services\n offered by Amazon Web Services.\n Currently, this includes:\n\nSimple Storage Service (S3)\nSimpleQueue Service (SQS)\nElastic Compute Cloud (EC2) \n\n" ]
[ 0 ]
[]
[]
[ "amazon_sqs", "message_queue", "producer_consumer", "python" ]
stackoverflow_0005560666_amazon_sqs_message_queue_producer_consumer_python.txt
Q: IPython mac terminal strange characters after using os.urandom When using IPython, osx terminal and remoting into an ubuntu server. I noticed that if I try to encode and print the output of os.urandom(1) it will break the terminal and all input will start to look like this: ⎽⎽␤␌±┌▒␌␊@▒⎻⎻.⎻┌▒␌␊⎻┤┼␌␤.␌⎺└ All input...
IPython mac terminal strange characters after using os.urandom
When using IPython, osx terminal and remoting into an ubuntu server. I noticed that if I try to encode and print the output of os.urandom(1) it will break the terminal and all input will start to look like this: ⎽⎽␤␌±┌▒␌␊@▒⎻⎻.⎻┌▒␌␊⎻┤┼␌␤.␌⎺└ All input and output from the terminal continues to be displayed in that way ...
[ "Certain character sequences will send the terminal into alternate character set modes and the like. Run reset to fix this.\n" ]
[ 4 ]
[]
[]
[ "ipython", "macos", "python", "terminal" ]
stackoverflow_0005586497_ipython_macos_python_terminal.txt
Q: Extracting lxml xpath for html table I have a html doc similar to following: <html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml"> <div id="Symbols" class="cb"> <table class="quotes"> <tr><th>Code</th><th>Name</th> <th style="text-align:right;">High</th> <th s...
Extracting lxml xpath for html table
I have a html doc similar to following: <html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml"> <div id="Symbols" class="cb"> <table class="quotes"> <tr><th>Code</th><th>Name</th> <th style="text-align:right;">High</th> <th style="text-align:right;">Low</th> </tr...
[ "You are probably looking at the HTML in Firebug, correct? The browser will insert the implicit tag <tbody> when it is not present in the document. The lxml library will only process the tags present in the raw HTML string.\nOmit the tbody level in your XPath. For example, this works:\ntree = lxml.html.fromstring...
[ 43 ]
[]
[]
[ "html", "html_table", "lxml", "python", "xpath" ]
stackoverflow_0005586296_html_html_table_lxml_python_xpath.txt
Q: Python urllib POST response I am trying to write script that searches an inchikey (ex: OBSSCZVQJAGPOE-KMKNQKDISA-N) to get a chemical structure from this website: http://www.chemspider.com/inchi-resolver/Resolver.aspx From the documentation my code looks like it should work, but instead it just returns the origina...
Python urllib POST response
I am trying to write script that searches an inchikey (ex: OBSSCZVQJAGPOE-KMKNQKDISA-N) to get a chemical structure from this website: http://www.chemspider.com/inchi-resolver/Resolver.aspx From the documentation my code looks like it should work, but instead it just returns the original search page. Thanks for the h...
[ "Your code is performing a GET request and not a POST request. Apart from that: the form contains various hidden fields with some strange values which might be necessary for the processing as well.\n" ]
[ 3 ]
[]
[]
[ "post", "python", "urllib" ]
stackoverflow_0005586617_post_python_urllib.txt
Q: Python to run geopy via ActivePython Trying to get a location using Python and Google Maps, so I tried to use Geopy module by installing activepython using pypm install geopy but i get a problem which is geo required business edition subscription. Can any one help me? Thanks in advance. A: geo required busi...
Python to run geopy via ActivePython
Trying to get a location using Python and Google Maps, so I tried to use Geopy module by installing activepython using pypm install geopy but i get a problem which is geo required business edition subscription. Can any one help me? Thanks in advance.
[ "\ngeo required business edition subscription\n\nNo. You are probably using the Windows 64-bit build, which requires Business Edition to install all packages (as even this page should tell you with the \"lock\" icon). \nTry the 32-bit version instead.\n" ]
[ 1 ]
[]
[]
[ "activepython", "geopy", "google_maps", "pypm", "python" ]
stackoverflow_0005585298_activepython_geopy_google_maps_pypm_python.txt
Q: Change choice in wx.ComboBox() based on TextCtrl() value in another Notebook Tab I'm using wx to make a GUI for running another program. I have two Notebook tabs: the first for the input and the second for the output of my program. I would like to set it up such that the user will indicate a directory for the pr...
Change choice in wx.ComboBox() based on TextCtrl() value in another Notebook Tab
I'm using wx to make a GUI for running another program. I have two Notebook tabs: the first for the input and the second for the output of my program. I would like to set it up such that the user will indicate a directory for the program output in the InputPanel, and the ComboBox in the OutputPanel will update with t...
[ "Well, there's an ugly hack way to do it and the elegant way to do it. Actually, there are probably several hacks. Let's look at one of the most common:\nIn the notebook's page changing event, you can tell the output panel to do something like this: inputPanelRef.dirFile.GetValue() and then update the comboboxe's e...
[ 3, 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0005585883_python_wxpython_wxwidgets.txt
Q: Django template filters, tags, simple_tags, and inclusion_tags This is more of a general question about the distinctions between these four different kinds of django tags. I just read the documentation page on template tags: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ But I'm finding it diffi...
Django template filters, tags, simple_tags, and inclusion_tags
This is more of a general question about the distinctions between these four different kinds of django tags. I just read the documentation page on template tags: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ But I'm finding it difficult to know when I should use one variation over another. For exam...
[ "Template filters can operate on any object (and at most two at once). They're just functions that take one or two arguments. e.g.\n# filter implementation\n@filter\ndef myfilter(arg1, arg2):\n ....\n\n# usage in template\n{{ arg1|myfilter:arg2 }}\n\nThey are limited in that they cannot access the template conte...
[ 67 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005586774_django_python.txt
Q: How can I tile two pixmaps in PyQt 4? Starting with 2 png files on disk (which I can load to 2 pixmaps) with the same dimensions, how can I tile them horizontally with a small vertical (transparent) space between them, like this: aaaaa bbbbb aaaaa bbbbb aaaaa bbbbb and save the result as another pixmap? Environme...
How can I tile two pixmaps in PyQt 4?
Starting with 2 png files on disk (which I can load to 2 pixmaps) with the same dimensions, how can I tile them horizontally with a small vertical (transparent) space between them, like this: aaaaa bbbbb aaaaa bbbbb aaaaa bbbbb and save the result as another pixmap? Environment: PyQt 4.8.3 on Windows
[ "This should be a good starting point (untested):\npainter = QPainter() // the QPainter to the object you want to paint\n\na = QImage(\"file1.png\")\nb = QImage(\"file2.png\")\nspace = 5 // pixels\ntile = QPixmap(QSize(a.width() + b.width(), a.height() + space)\npainter2.setBrush(QBrush(QColor(0, 0, 0, 0)))\npainte...
[ 2 ]
[]
[]
[ "pyqt4", "python", "qt", "qt4", "windows" ]
stackoverflow_0005586759_pyqt4_python_qt_qt4_windows.txt
Q: Problem with Django forms and cache control I'm populating the choices of a form choicefield in django, it's a year select field. I get the years from the database and put them in a list of tuples in the field. My code looks like this def get_years(): choices = [] years = [] for poll in Poll.objects.al...
Problem with Django forms and cache control
I'm populating the choices of a form choicefield in django, it's a year select field. I get the years from the database and put them in a list of tuples in the field. My code looks like this def get_years(): choices = [] years = [] for poll in Poll.objects.all().order_by('created'): years.append(pol...
[ "Update the years when you initialize a form instance.\ndef __init__(self, *args, **kwargs):\n super(MyForm, self).__init__(*args, **kwargs)\n self.fields['year'].choices = self.get_years()\n\n" ]
[ 11 ]
[]
[]
[ "browser_cache", "cache_control", "django", "javascript", "python" ]
stackoverflow_0005586803_browser_cache_cache_control_django_javascript_python.txt
Q: Can the JIRA SOAP api be used to determine whether a given user can view a given record? I'd like to be able to do something like this: #!/usr/bin/python if jira.user_has_permission('jsmith', 'JIRA-123'): print '%s has permission to view %s' % (user, record) else: print '%s does not have permission to view...
Can the JIRA SOAP api be used to determine whether a given user can view a given record?
I'd like to be able to do something like this: #!/usr/bin/python if jira.user_has_permission('jsmith', 'JIRA-123'): print '%s has permission to view %s' % (user, record) else: print '%s does not have permission to view %s' % (user, record) How can I implement jira.user_has_permission()? Note: I'm looking for t...
[ "It's long-winded with the standard API but here you go.\ngetProjectWithSchemesById gives you a RemoteProject object. Probably has to be invoked by a user with jira-admin permissions. Note that getProjectByKey does not set the permission scheme in the value returned but is a handy way to get the project id to use i...
[ 1, 0 ]
[]
[]
[ "api", "jira", "python", "soap" ]
stackoverflow_0005585322_api_jira_python_soap.txt
Q: Scipy interpolation how to resize/resample 3x3 matrix to 5x5? EDIT: Paul has solved this one below. Thanks! I'm trying to resample (upscale) a 3x3 matrix to 5x5, filling in the intermediate points with either interpolate.interp2d or interpolate.RectBivariateSpline (or whatever works). If there's a simple, existing...
Scipy interpolation how to resize/resample 3x3 matrix to 5x5?
EDIT: Paul has solved this one below. Thanks! I'm trying to resample (upscale) a 3x3 matrix to 5x5, filling in the intermediate points with either interpolate.interp2d or interpolate.RectBivariateSpline (or whatever works). If there's a simple, existing function to do this, I'd like to use it, but I haven't found it ye...
[ "Only two small problems:\n1) Your xx,yy is outside the bounds of x,y (you can extrapolate, but I'm guessing you don't want to.)\n2) Your sample size is too small for a kx and ky of 3 (default). Lower it to 2 and get a quadratic fit instead of cubic.\nimport numpy, scipy\nfrom scipy import interpolate\n\nkernelIn ...
[ 10, 9 ]
[]
[]
[ "interpolation", "numpy", "python", "resampling", "scipy" ]
stackoverflow_0005586719_interpolation_numpy_python_resampling_scipy.txt
Q: python sending http response I am trying to write a very simple HTTP server which sends a video being streamed server side. When a client connects, the get_video program (fictional) is started in another process and its stdout is being piped to us (under the assumption get_video sends/streams video to stdout). I...
python sending http response
I am trying to write a very simple HTTP server which sends a video being streamed server side. When a client connects, the get_video program (fictional) is started in another process and its stdout is being piped to us (under the assumption get_video sends/streams video to stdout). I am using subprocess.Popen() for t...
[ "It dawned on me that, because the browser sends a GET followed by a FIN,ACK after the 'save target as...' has been clicked on the link, then that'll be what is causing the broken pipe error. It is when you choose where you want to save the file and hit 'OK' button in the browser that another GET is issued. What ...
[ 0 ]
[]
[]
[ "http", "popen", "python", "sockets" ]
stackoverflow_0005584755_http_popen_python_sockets.txt
Q: Python wrapper amazon product api I was trying to install the following python wrapper for Amazons product api: http://pypi.python.org/pypi/python-amazon-product-api/0.2.5a1 I'm getting an error "File "setup.py", line 3, in from setuptools import setup, find_packages ImportError: No module named setuptools" o...
Python wrapper amazon product api
I was trying to install the following python wrapper for Amazons product api: http://pypi.python.org/pypi/python-amazon-product-api/0.2.5a1 I'm getting an error "File "setup.py", line 3, in from setuptools import setup, find_packages ImportError: No module named setuptools" once I run the setup.py script. I was wo...
[ "You need to install SetupTools first: \nhttp://pypi.python.org/pypi/setuptools#downloads\n" ]
[ 2 ]
[]
[]
[ "amazon_product_api", "python" ]
stackoverflow_0005587560_amazon_product_api_python.txt
Q: python basehttpserver: can i modify the 404 response? Is it possible to modify the 404 response page sent from pythons basehttpserver library? A: To modify the default error document displayed by BaseHTTPRequestHandler, you may customize the error_message_format attribute. It's a string in which you can use the ...
python basehttpserver: can i modify the 404 response?
Is it possible to modify the 404 response page sent from pythons basehttpserver library?
[ "To modify the default error document displayed by BaseHTTPRequestHandler, you may customize the error_message_format attribute. It's a string in which you can use the following tags that will be replaced with their value when rendered:\n\n%(code)d is the numeric error code (eg. 404)\n%(message)s is a string repres...
[ 3 ]
[]
[]
[ "basehttpserver", "python" ]
stackoverflow_0005587525_basehttpserver_python.txt
Q: How to find XML Elements via XPath in Python in a namespace-agnostic way? since I had this annoying issue for the 2nd time, I thought that asking would help. Sometimes I have to get Elements from XML documents, but the ways to do this are awkward. I’d like to know a python library that does what I want, a elegant ...
How to find XML Elements via XPath in Python in a namespace-agnostic way?
since I had this annoying issue for the 2nd time, I thought that asking would help. Sometimes I have to get Elements from XML documents, but the ways to do this are awkward. I’d like to know a python library that does what I want, a elegant way to formulate my XPaths, a way to register the namespaces in prefixes automa...
[ "The *[local-name() = \"elem\"] syntax should work, but to make it easier you can create a function to simplify construction of the partial or full \"wildcard namespace\" XPath expressions. \nI'm using python-lxml 2.2.4 on Ubuntu 10.04 and the script below works for me. You'll need to customize the behavior depend...
[ 14, 2 ]
[]
[]
[ "elementtree", "lxml", "python", "xml", "xpath" ]
stackoverflow_0005572247_elementtree_lxml_python_xml_xpath.txt
Q: Inheritance and inner classes in Python? In the following code class B has inherited yay attribute from class A, I expected this. I'd also expect that inner class B.Foo behaves the same way but it doesn't. How to make B.Foo to inherit alice attribute from class A? I need that the inner subclass Foo in B has both t...
Inheritance and inner classes in Python?
In the following code class B has inherited yay attribute from class A, I expected this. I'd also expect that inner class B.Foo behaves the same way but it doesn't. How to make B.Foo to inherit alice attribute from class A? I need that the inner subclass Foo in B has both the attributes alice and bob. Thanks. >>> class...
[ "The reason why B.Foo.alice gave you an error is because there's no connection between Foo attribute of class A and Foo attribute of class B.\nIn B, attribute Foo has a class object value that completely replaces class object value inherited from A.\nThis should fix it:\nclass B(A):\n nay = False\n class Foo(...
[ 19, 9, 1 ]
[]
[]
[ "class", "inheritance", "inner_classes", "oop", "python" ]
stackoverflow_0005587653_class_inheritance_inner_classes_oop_python.txt
Q: Solving a substitution cipher with python I know similar questions have been asked, but this is kind of a trivial case. Given a text file endcoded with a substitution cipher, I need to decode it using python. I am not given any examples of correctly deciphered words. The relationship is 1-to-1 and case doesn't mak...
Solving a substitution cipher with python
I know similar questions have been asked, but this is kind of a trivial case. Given a text file endcoded with a substitution cipher, I need to decode it using python. I am not given any examples of correctly deciphered words. The relationship is 1-to-1 and case doesn't make a difference. Also, punctuation isn't changed...
[ "I would first get a list of English words for reference. Next construct a list of possible 2 and 3 letter words. Then just start testing those small words in your cipher. Once you guess at a small word, check the larger words against your word list. If some of the words no longer have possible completions in t...
[ 1, 1, 1 ]
[]
[]
[ "encryption", "python", "substitution" ]
stackoverflow_0005587280_encryption_python_substitution.txt