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: Analyze logfile from GAE Hi My app had visitors and I like to analyze the log file. Can I run a log analyzer program on the log file that google app engine allows us to download? Are third-party programs such as webalizer and visitors compatible? Thank you A: You can get a lot of meaningful and derived data out...
Analyze logfile from GAE
Hi My app had visitors and I like to analyze the log file. Can I run a log analyzer program on the log file that google app engine allows us to download? Are third-party programs such as webalizer and visitors compatible? Thank you
[ "You can get a lot of meaningful and derived data out of Appstats instead of downloading and analyzing your log file. You may want to try with those server side stats and see if those fit your bill. \n", "I suggest you use Google Analytics on your web app. If you want to do some sort of server-side visitor anala...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005699092_google_app_engine_python.txt
Q: What is the difference between % and , in a string? I am using a String in Python and need to update it line = '' byte_data = 0 What is the difference between these two syntaxes (what they do): line += "%c" % byte_data line += "%c", byte_data A: The former adds \x00 to the string, and the latter results in a ...
What is the difference between % and , in a string?
I am using a String in Python and need to update it line = '' byte_data = 0 What is the difference between these two syntaxes (what they do): line += "%c" % byte_data line += "%c", byte_data
[ "The former adds \\x00 to the string, and the latter results in a TypeError.\n", "The difference is that one works and one does not.\n>>> line = ''\n>>> byte_data = 0\n>>> line += \"%c\" % byte_data\n>>> line\n'\\x00'\n>>> line += \"%c\", byte_data\n\nTraceback (most recent call last):\n File \"<pyshell#4>\", li...
[ 6, 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005699325_python_python_3.x.txt
Q: Python Reflection suppose we have many objects in memory. Each one has a distinct id. How can I iterate the memory to find a specific object that is compared to some id ? In order to grab it and use it through getattr ? A: You should maintain a collection of these objects as they are created in a class attribute...
Python Reflection
suppose we have many objects in memory. Each one has a distinct id. How can I iterate the memory to find a specific object that is compared to some id ? In order to grab it and use it through getattr ?
[ "You should maintain a collection of these objects as they are created in a class attribute, then provide a class method for retrieving them.\nSomething along the lines of:\nclass Thing(object):\n all = {}\n\n def __init__(self, id, also, etc):\n self.id = id\n self.all[id] = self\n\n @classm...
[ 10, 2, 0, 0 ]
[]
[]
[ "python", "reflection" ]
stackoverflow_0005686723_python_reflection.txt
Q: Python - how to write this in vector form def compute(c, r): s = 0; l = len(c); for i in range(l): s = s + c[i]*f(r[i]); return s A: I don't know what you mean by vector form (unless you are using numpy?), but I would write your function like this: def compute(c, r): return sum(x*f(y) f...
Python - how to write this in vector form
def compute(c, r): s = 0; l = len(c); for i in range(l): s = s + c[i]*f(r[i]); return s
[ "I don't know what you mean by vector form (unless you are using numpy?), but I would write your function like this:\ndef compute(c, r):\n return sum(x*f(y) for x,y in zip(c,r))\n\nIf you are using numpy you can use whole-array expressions instead of generator expressions, but in that case c and r must be numpy a...
[ 3 ]
[]
[]
[ "python", "vectorization" ]
stackoverflow_0005699512_python_vectorization.txt
Q: How to change a .png output from Python to an OpenGL window output? I have a Python code whose output is a .png file. What should I do to get the output in an OpenGL window? I searched a few places and the closest I got to converting an Image was StringIO() but that didn't seem very helpful. A: First of all, you...
How to change a .png output from Python to an OpenGL window output?
I have a Python code whose output is a .png file. What should I do to get the output in an OpenGL window? I searched a few places and the closest I got to converting an Image was StringIO() but that didn't seem very helpful.
[ "First of all, you need the OpenGL bindings to create an OpenGL window. Try PyOpenGL\nThe next step is to look at the code. My guess is that some kind of image object is created, then something is drawn onto it and lastly, the image is saved as PNG.\nAt that point, you need to convert the image data (see the docs f...
[ 0, 0 ]
[]
[]
[ "image", "python" ]
stackoverflow_0005699508_image_python.txt
Q: Is passing ORM entities into templates acceptable in MVC pattern frameworks? Is passing ORM entities directly into templates acceptable? In a hypothetical python framework is this worse def fetch_widgets: widgets = widget.fetch("price < 50") render_template('widget.html', widgets=widgets) than this? def ...
Is passing ORM entities into templates acceptable in MVC pattern frameworks?
Is passing ORM entities directly into templates acceptable? In a hypothetical python framework is this worse def fetch_widgets: widgets = widget.fetch("price < 50") render_template('widget.html', widgets=widgets) than this? def fetch_widgets: widgets = [(w.name, w.price) for w in widget.fetch("price < 50"...
[ "If the template engine is only capable of retrieving models, then sure. It's when templates are used to manipulate models that the walls break down.\n" ]
[ 1 ]
[]
[]
[ "model_view_controller", "orm", "python", "separation_of_concerns" ]
stackoverflow_0005699727_model_view_controller_orm_python_separation_of_concerns.txt
Q: python, dynamically implement a class onthefly Flocks, we have a framework that allows our researchers to change methods(operations) in a class to suite thier needs while saving those changes. E.g Consider definition of the class foo below. (with version 1 & version 2) class foo: #class version 1 def operat...
python, dynamically implement a class onthefly
Flocks, we have a framework that allows our researchers to change methods(operations) in a class to suite thier needs while saving those changes. E.g Consider definition of the class foo below. (with version 1 & version 2) class foo: #class version 1 def operation_1(self): # version 1 pass def ...
[ "type is the metaclass you want.\nklass = type('klass', (foo,), {'operation_1': foo.operation_1,\n 'operation_2': foo.operation_2})\n\n" ]
[ 2 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0005699746_methods_python.txt
Q: Why matplotlib has no attribute 'pylab'? I imported matplotlib in the way like this: import matplotlib as mpl A error saying 'module' object has no attribute 'pylab' was thrown out when i run the following code: x = np.arange(0,10,0.01) # import numpy as np y = np.sin(x) mpl.pylab.plot(x,y) mpl.pylab.show() An...
Why matplotlib has no attribute 'pylab'?
I imported matplotlib in the way like this: import matplotlib as mpl A error saying 'module' object has no attribute 'pylab' was thrown out when i run the following code: x = np.arange(0,10,0.01) # import numpy as np y = np.sin(x) mpl.pylab.plot(x,y) mpl.pylab.show() And there was no error appears when i imported ...
[ "To plot in non-interactive mode, you should use the module pyplot, not pylab.\nfrom matplotlib import pyplot\nimport numpy\n\npyplot.plot(range(1,100), numpy.sin(range(1,100)))\npyplot.show()\n\nThe module pylab is not typically used as a submodule of matplotlib, but as a top-level module instead. Typically, it is...
[ 10, 5 ]
[ "You normally get this error if the module you are trying to import does not have a __init__.py file. I also get this error on my installation. I think you just have to accept that you must import matplotlib.pylab separately from matplotlib.\n" ]
[ -1 ]
[ "matplotlib", "python" ]
stackoverflow_0005698442_matplotlib_python.txt
Q: Add a space in string How can I add a blank space in Python? Ex. print "How many times did " + name + "go here?"; will print: How many times didnamego here?" How can I add that space in? A: print "How many times did " + name + " go here?" or print "How many times did", name, "go here?" or print "How many ti...
Add a space in string
How can I add a blank space in Python? Ex. print "How many times did " + name + "go here?"; will print: How many times didnamego here?" How can I add that space in?
[ "print \"How many times did \" + name + \" go here?\"\n\nor\nprint \"How many times did\", name, \"go here?\"\n\nor \nprint \"How many times did %s go here?\" % name\n\nThe preferred form in this simple case is the second one. The first uses concatenation (which is useful if you want more or less than one space bet...
[ 12, 6, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005697378_python_string.txt
Q: Python string split decimals from end of string I use nlst on a ftp server which returns directories in the form of lists. The format of the returned list is as follows: [xyz123,abcde345,pqrst678]. I have to separate each element of the list into two parts such that part1 = xyz and part2 = 123 i.e split the stri...
Python string split decimals from end of string
I use nlst on a ftp server which returns directories in the form of lists. The format of the returned list is as follows: [xyz123,abcde345,pqrst678]. I have to separate each element of the list into two parts such that part1 = xyz and part2 = 123 i.e split the string at the beginning of the integer part. Any help on ...
[ ">>> re.findall(r'\\d+|[a-z]+', 'xyz123')\n['xyz', '123']\n\n", "For example, using the re module:\n>>> import re\n>>> a = ['xyz123','ABCDE345','pqRst678']\n>>> regex = '(\\D+)(\\d+)'\n>>> for item in a:\n... m = re.match(regex, item)\n... (a, b) = m.groups()\n... print a, b\n\nxyz 123\nABCDE 345\npqRst ...
[ 2, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "ftp", "python", "split", "string" ]
stackoverflow_0005699417_ftp_python_split_string.txt
Q: How to save the email and name fields in the Django deafult User table I want to save the email and name fields in django default table called UserSignup my models.py is: from django.db import models class UserSignup(models.Model): mailid = models.CharField(max_length=100) name = models.CharFie...
How to save the email and name fields in the Django deafult User table
I want to save the email and name fields in django default table called UserSignup my models.py is: from django.db import models class UserSignup(models.Model): mailid = models.CharField(max_length=100) name = models.CharField(max_length=100) my views.py is: from django import views from django.sho...
[ "Check the Django documentation properly http://docs.djangoproject.com/en/dev/topics/forms/\nJust change your code in views.py.\ndef usersignup(request,form_class=signup):\n\n if request.method == 'POST': #If its a form submission, the method is POST\n form = form_class(request.POST)\n if form.is_v...
[ 0, 0 ]
[]
[]
[ "django", "forms", "python", "save" ]
stackoverflow_0005528215_django_forms_python_save.txt
Q: Draw a block of colour on top of a figure to create trails in python I have a set of data which I am plotting using pylab which changes over time. I can store each frame as a .png and put them together using iMovie, but I want to add trails to the plots to illustrate the position at previous time points. One way...
Draw a block of colour on top of a figure to create trails in python
I have a set of data which I am plotting using pylab which changes over time. I can store each frame as a .png and put them together using iMovie, but I want to add trails to the plots to illustrate the position at previous time points. One way I thought this could be done is to set plt.hold(True) on the figure, then...
[ "An alternative way to achieve fading trails on a sequence of plots would be to change the alpha values of the plotted items using the .set_alpha() method, if it’s available for the particular plotting method that you’re using.\nYou can do this by appending the output of the particular plotting function you’re usin...
[ 2 ]
[]
[]
[ "alpha", "patch", "python" ]
stackoverflow_0005082109_alpha_patch_python.txt
Q: Add file name as last column of CSV file I have a Python script which modifies a CSV file to add the filename as the last column: import sys import glob for filename in glob.glob(sys.argv[1]): file = open(filename) data = [line.rstrip() + "," + filename for line in file] file.close() file = open(...
Add file name as last column of CSV file
I have a Python script which modifies a CSV file to add the filename as the last column: import sys import glob for filename in glob.glob(sys.argv[1]): file = open(filename) data = [line.rstrip() + "," + filename for line in file] file.close() file = open(filename, "w") file.write("\n".join(data))...
[ "Have a look at the official csv module.\n", "Here are a few minor notes on your current code:\n\nIt's a bad idea to use file as a variable name, since that shadows the built-in type.\nYou can close the file objects automatically by using the with syntax.\nDon't you want to add an extra column in the header line,...
[ 6, 5, 1, 1, 1, 1 ]
[]
[]
[ "csv", "linux", "python" ]
stackoverflow_0005700300_csv_linux_python.txt
Q: Django-CMS plugin isn't showing up in available plugins I've been attempting to write a Django CMS plugin, but it's not showing up in the "Available plugins" on the page edits and I'm very unsure why as I've read the source of another few plugins trying to see what I've done wrong. It's as if Django-CMS hasn't reg...
Django-CMS plugin isn't showing up in available plugins
I've been attempting to write a Django CMS plugin, but it's not showing up in the "Available plugins" on the page edits and I'm very unsure why as I've read the source of another few plugins trying to see what I've done wrong. It's as if Django-CMS hasn't registered the plugin. Directory structure: /linkrotator __ini...
[ "The problem is an import error in your cms_plugins.py. You do from linkrator.models import LinksPlugin as LinkListPluginModel, it should be from linkrotator.models import LinkListPluginModel. You should also set a name on LinkListPlugin, or the name will be blank when it shows up under available plugins. Giving us...
[ 8, 0 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0005696287_django_django_cms_python.txt
Q: Python script for URL split I'm new to python,learning the basics. My Query : I have multiple pages accessed as a request from a log file like the below, "GET /img/home/search-user-ico.jpg HTTP/1.1" "GET /SpellCheck/am.tlx HTTP/1.1" "GET /img/plan-comp-nav.jpg HTTP/1.1" "GET /ie6.css HTTP/1.1" "GET /img/portlet...
Python script for URL split
I'm new to python,learning the basics. My Query : I have multiple pages accessed as a request from a log file like the below, "GET /img/home/search-user-ico.jpg HTTP/1.1" "GET /SpellCheck/am.tlx HTTP/1.1" "GET /img/plan-comp-nav.jpg HTTP/1.1" "GET /ie6.css HTTP/1.1" "GET /img/portlet/portlet-content-bg.jpg HTTP/1.1"...
[ "Assuming that you don't have spaces in the filenames and that you don't want \"HTTP\" at the end.\nYou can split the line by space.\nparts = line.split(\" \")\n\nand then use the os module to get the filename from the path.\nfilename = os.path.basename(parts[1])\n\nFor example.\n>>> line = \"GET /img/home/search-u...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005700552_python_regex.txt
Q: Driving Distance Between GIS Points I have a large number of GIS (latitude, longitude) coordinates, and I'd like to get the distance between them. Is there a service that will calculate the shortest path for me? I know about google maps, but I'd like something I can use from Python, and that can handle a large bat...
Driving Distance Between GIS Points
I have a large number of GIS (latitude, longitude) coordinates, and I'd like to get the distance between them. Is there a service that will calculate the shortest path for me? I know about google maps, but I'd like something I can use from Python, and that can handle a large batch of requests at once. I'm looking for t...
[ "So I take it based on your question and the answers posted that you are asking what program to use? If you can find a way to get a copy for free or cheap (like through work, school, etc) I'd recommend ArcGIS 9.x. It has its quirks, but it's highly supported by the user community and there are a lot of forums and h...
[ 2, 1, 1, 0 ]
[]
[]
[ "gis", "maps", "python" ]
stackoverflow_0002445806_gis_maps_python.txt
Q: Construct the entire tree from a SQLAlchemy adjacency list relationship I have a class Node with a self referential mapping 'children' (backref 'parent') representing a tree in SQLAlchemy and I want to select the entire tree. If I do session.query(Node).all() then every access to node.children triggers a select. ...
Construct the entire tree from a SQLAlchemy adjacency list relationship
I have a class Node with a self referential mapping 'children' (backref 'parent') representing a tree in SQLAlchemy and I want to select the entire tree. If I do session.query(Node).all() then every access to node.children triggers a select. If I do a joined load session.query(Node).options(joinedload_all('children'))...
[ "There is no problem with parent property, since all information needed is already loaded in the object. SQLAlchemy just have to look for parent object in the session and issue query only when it's missing. But this doesn't work for children: the library can't be sure all children objects are already in the session...
[ 13 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0005680459_python_sqlalchemy.txt
Q: Skip stdin and stderr of child with pexpect I'm controlling a child process using pexpect (because subprocess doesn't support pty's and I run into a deadlock with two pipes). The process creates a lot of output on stderr, in which I'm not interested, and apparantly pexpect also echoes back anything I write to its ...
Skip stdin and stderr of child with pexpect
I'm controlling a child process using pexpect (because subprocess doesn't support pty's and I run into a deadlock with two pipes). The process creates a lot of output on stderr, in which I'm not interested, and apparantly pexpect also echoes back anything I write to its stdin: >>> import pexpect >>> p = pexpect.spawn('...
[ "Using pty's is not quite the same as a pipe. If you don't put in in raw mode the tty driver will echo back the characters and perform other line editing. So to get a clean data path you need to also put the pty/tty in raw mode. \nSince you are now dealing with a pseudo device you have only a single I/O stream. The...
[ 3 ]
[]
[]
[ "ipc", "pexpect", "pty", "python" ]
stackoverflow_0005699418_ipc_pexpect_pty_python.txt
Q: Assigning values to a new user from a view I have an application fileman with models.py like so: from django.db import models from django.contrib.auth.models import User from fileman.fields import AutoForeignKey from django.utils.translation import ugettext as _ class Setting(models.Model): owner = AutoForei...
Assigning values to a new user from a view
I have an application fileman with models.py like so: from django.db import models from django.contrib.auth.models import User from fileman.fields import AutoForeignKey from django.utils.translation import ugettext as _ class Setting(models.Model): owner = AutoForeignKey(User, unique=True, related_name='fileman_S...
[ "You need to save newuser.fileman_Setting too, because django won't save changes to models automatically.\n", "I've no idea what AutoForeignKey does, but assuming it's similar to a standard ForeignKey, the reverse fileman_Setting refers to a QuerySet. \nA ForeignKey is a one-to-many relationship, where the one is...
[ 0, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "django_views", "python" ]
stackoverflow_0005701721_django_django_admin_django_models_django_views_python.txt
Q: How do I set up gaeunit 2.0a with my Django app? I am trying to set up Google App Engine unit testing for my web application. I downloaded the file from here. I followed the instructions in the readmen by copying the directory gaeunit into the directory with the rest of my apps and registering 'gaeunit' in settin...
How do I set up gaeunit 2.0a with my Django app?
I am trying to set up Google App Engine unit testing for my web application. I downloaded the file from here. I followed the instructions in the readmen by copying the directory gaeunit into the directory with the rest of my apps and registering 'gaeunit' in settings.py. This didn't seem sufficient to actually get th...
[ "According to the instructions on the main page you should add the URL to app.yaml, not urls.py.\n- url: /test.*\n script: gaeunit.py\n\n", "You can copy url but in your urls.py include \n(r'^test', include('gaeunit.urls')), \n\nAlso you will have to change test path in gaeunit.py \n_LOCAL_DJANGO_TEST_DIR = 'tes...
[ 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python", "unit_testing" ]
stackoverflow_0003056461_django_google_app_engine_python_unit_testing.txt
Q: print formatting in python 3 I am trying to print in Python 3 and am having trouble. I have a for loop in my code that looks like this: seq = input("enter DNA sequence to search: ") pat = re.compile('(.{10})(ATC.{3,6}CAG)') li = [] output_lines = [] for mat in pat.finditer(seq): x = mat.end() li.append(ma...
print formatting in python 3
I am trying to print in Python 3 and am having trouble. I have a for loop in my code that looks like this: seq = input("enter DNA sequence to search: ") pat = re.compile('(.{10})(ATC.{3,6}CAG)') li = [] output_lines = [] for mat in pat.finditer(seq): x = mat.end() li.append(mat.groups()+(seq[x:x+10],)) for u i...
[ "You can try this:\noutput_lines = []\nfor u in li: \n z = u[1] \n A = z.count('A') \n C = z.count('C') \n G = z.count('G') \n T = z.count('T')\n sumbases = \"A,C,G,T\" # I suppose you format it here differently\n y = sumbases.replace(\"\\n\",\" \") # not sure why you need this\n\n #...
[ 2 ]
[]
[]
[ "printing", "python", "python_3.x" ]
stackoverflow_0005701890_printing_python_python_3.x.txt
Q: Selecting from multidimensional numpy array I have a multidimensional array a with shape (nt, nz, ny, nx). The dimensions are time, z, y, x. For each time, x and y, I've selected the appropriate z in a new index array J with shape (nt, ny, nx). J contains the indices along the height dimension that I'd like to sel...
Selecting from multidimensional numpy array
I have a multidimensional array a with shape (nt, nz, ny, nx). The dimensions are time, z, y, x. For each time, x and y, I've selected the appropriate z in a new index array J with shape (nt, ny, nx). J contains the indices along the height dimension that I'd like to select. Using Python, I could do this in a loop: b=J...
[ "You can use numpy.indices() together with advanced indexing:\nt, y, x = numpy.indices(J.shape)\nb = a[t, J, y, x]\n\n" ]
[ 8 ]
[]
[]
[ "arrays", "matrix", "multidimensional_array", "numpy", "python" ]
stackoverflow_0005701811_arrays_matrix_multidimensional_array_numpy_python.txt
Q: What caused this traceback? Possible Duplicate: UnicodeDecodeError when passing GET data in Python/AppEngine I get the following traceback locally and on production when trying to submit a form. Can you explain where I should look or should I start making debugging statements to see where in the code the excepti...
What caused this traceback?
Possible Duplicate: UnicodeDecodeError when passing GET data in Python/AppEngine I get the following traceback locally and on production when trying to submit a form. Can you explain where I should look or should I start making debugging statements to see where in the code the exception occurs? --> --> --> Traceb...
[ "The error manifested itself in /usr/lib/python2.6/StringIO.py i.e. the Python StringIO module. We don't need to read too far into that source file (line 49) to find this warning:\n\nThe StringIO object can accept either Unicode or 8-bit strings, but\nmixing the two may take some care. If both are used, 8-bit strin...
[ 5 ]
[]
[]
[ "django", "django_forms", "google_app_engine", "python" ]
stackoverflow_0005701372_django_django_forms_google_app_engine_python.txt
Q: App works on Local host but not on appspot I'm working on having a user authenticate on my webpage using Foursquare, once they are redirected back to my webpage the information recieved back is parsed out of the URL. This works perfect on localhost but when I deploy it I get the following error Traceback (most...
App works on Local host but not on appspot
I'm working on having a user authenticate on my webpage using Foursquare, once they are redirected back to my webpage the information recieved back is parsed out of the URL. This works perfect on localhost but when I deploy it I get the following error Traceback (most recent call last): File "/base/python_runtime...
[ "Do you have an '/_ah/login_required' handler setup in your app.yaml file? \nI'm assuming you've turned on Federated Login to allow Foursquare credentials. If so you need to define your own login handler in order for it to work on appspot (localhost uses different login handling).\nex:\nhandlers:\n- url: /_ah/log...
[ 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005688216_django_google_app_engine_python.txt
Q: Output python into python-readable format We're using a python based application which reads a configuration file containing a couple of arrays: Example layout of config file: array1 = [ 'bob', 'sue', 'jayne' ] Currently changes to the configuration are done by hand, but I've written a little interface to streaml...
Output python into python-readable format
We're using a python based application which reads a configuration file containing a couple of arrays: Example layout of config file: array1 = [ 'bob', 'sue', 'jayne' ] Currently changes to the configuration are done by hand, but I've written a little interface to streamline the process (mainly to avoid errors). It cu...
[ "I'd suggest JSON or YAML (Less verbose than JSON) for configuration files. That way, the configuration file becomes more readable for the less pythonate ;) It's also easier to throw adequate errors, e.g. if the configuration is incomplete.\nTo save python objects you can always use pickle.\n", "Generally using r...
[ 3, 2, 1 ]
[]
[]
[ "arrays", "file", "python" ]
stackoverflow_0005702002_arrays_file_python.txt
Q: using unbound methods in another python class I have an unbound method as <unbound method foo.ops>, i would like to use the same method with another class. take an example class foo2(object): pass foo2.ops = foo.ops however obj = foo2() obj.ops() raises TypeError: unbound method ops() must be called with f...
using unbound methods in another python class
I have an unbound method as <unbound method foo.ops>, i would like to use the same method with another class. take an example class foo2(object): pass foo2.ops = foo.ops however obj = foo2() obj.ops() raises TypeError: unbound method ops() must be called with foo instance as first argument (got nothing instead)...
[ "If you want to add the same method to several unrelated classes (e.g. doing AOP), don't copy an unbound method from one of them. Instead, define a plain function and assign it as a method to every class.\nUsually a better way to do it is a mixin (using plain inheritance) or a metaclass (class decorator syntax is n...
[ 11, 0 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0005701201_methods_python.txt
Q: enable temporary file creation and usage in Apache/PHP by Python/R/any external program - best options I have a python/R script, that uses both Python and R to compute a figure. The actual figure is generated by R and it can be stored as a PNG image. This works fine when tested on the machine, in a folder with cor...
enable temporary file creation and usage in Apache/PHP by Python/R/any external program - best options
I have a python/R script, that uses both Python and R to compute a figure. The actual figure is generated by R and it can be stored as a PNG image. This works fine when tested on the machine, in a folder with correct permissions, but I have to do it online now. I have an Apache/PHP interface that sends the user data to...
[ "With R, you can tempfile generates filenames for temp files. You could also use file.remove to delete the file later, but it sounds like this would be done best from PHP code (if it to be removed when the PHP session finishes).\nplot_file <- paste(tempfile(tmpdir = \"some_dir_with_write_permission\"), \"png\", se...
[ 1 ]
[]
[]
[ "apache", "php", "python", "r" ]
stackoverflow_0005702157_apache_php_python_r.txt
Q: Creating big Excel sheets programmatically We are using OpenPyxl to export MySQL content to Microsoft Excel in XSLX format https://bitbucket.org/ericgazoni/openpyxl/overview However, the amount of data we are dealing with is big. We are running to out of memory situation. Tables may contain up to 400 columns in 50...
Creating big Excel sheets programmatically
We are using OpenPyxl to export MySQL content to Microsoft Excel in XSLX format https://bitbucket.org/ericgazoni/openpyxl/overview However, the amount of data we are dealing with is big. We are running to out of memory situation. Tables may contain up to 400 columns in 50000+ rows. Even the files are big, they are not ...
[ "If you're going to use Java, you will want to use Apache POI, but likely not the regular UserModel as you're wanting to keep your memory footprint down.\nInstead, take a look at BigGridDemo, which shows you how to write a very large xlsx file using POI, with most of the work not happening in memory.\nYou might als...
[ 4, 4 ]
[]
[]
[ "excel", "lxml", "mysql", "openpyxl", "python" ]
stackoverflow_0005700896_excel_lxml_mysql_openpyxl_python.txt
Q: __init__.py usage for directories in Python I use __init__.py in my project with the following structure : project\ project.py cfg.py __init__.py database\ data.py __init__.py test\ test_project.py __init__.py All is OK when I need to see database\ modules in proj...
__init__.py usage for directories in Python
I use __init__.py in my project with the following structure : project\ project.py cfg.py __init__.py database\ data.py __init__.py test\ test_project.py __init__.py All is OK when I need to see database\ modules in project.py with from database.data import * But if ...
[ "You have 3 options:\n\nuse relative imports (from .. import database.data). I wouldn't recommend that one.\nappend paths to sys.path in your code.\nuse addsitedir() and .pth files. Here is how.\n\n", "Relative imports.\nfrom .. import database.data\n\n", "If you run a script from the directory that contains pr...
[ 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005702469_python.txt
Q: >>> operator in python ActionScript and javascript supports '>>>' operator. I am converting an actionscript of base64 encoding/decoding using python. I know base64 is available and this is for learning purpose. python doesn't have "..." operator. base64 action script in decode function you have two lines o1 = bit...
>>> operator in python
ActionScript and javascript supports '>>>' operator. I am converting an actionscript of base64 encoding/decoding using python. I know base64 is available and this is for learning purpose. python doesn't have "..." operator. base64 action script in decode function you have two lines o1 = bits >>> 16 & 0xff; o2 = bits >...
[ "IINM, >>> is a right shift that preserves the value of the leftmost bit. This has the effect of keeping the sign of the number intact (i.e. negative numbers get a 1 inserted as their MSB instead of a 0).\nIn Python, integers can be arbitrarily big. There is no meaningful concept of a most significant bit since the...
[ 3, 0 ]
[]
[]
[ "operator_keyword", "python" ]
stackoverflow_0005702560_operator_keyword_python.txt
Q: How to comment out an XML Element (using minidom DOM implementation) I would like to comment out a specific XML element in an xml file. I could just remove the element, but I would prefer to leave it commented out, in case it's needed later. The code I use at the moment that removes the element looks like this: fr...
How to comment out an XML Element (using minidom DOM implementation)
I would like to comment out a specific XML element in an xml file. I could just remove the element, but I would prefer to leave it commented out, in case it's needed later. The code I use at the moment that removes the element looks like this: from xml.dom import minidom doc = minidom.parse(myXmlFile) for element in d...
[ "The following solution does exactly what I want.\nfrom xml.dom import minidom\n\ndoc = minidom.parse(myXmlFile)\nfor element in doc.getElementsByTagName('MyElementName'):\n if element.getAttribute('name') in ['AttrName1', 'AttrName2']:\n parentNode = element.parentNode\n parentNode.insertBefore(do...
[ 5, 0 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0005699745_minidom_python_xml.txt
Q: Is there something like PyFlakes for PHP? Pretty straight forward question. I'm quite happy with my simple text editor but sometimes it'd be nice to run something like PyFlakes on my code before running to check for any obvious errors like undeclared variables or syntax errors. A: The previous answer is wrong - ...
Is there something like PyFlakes for PHP?
Pretty straight forward question. I'm quite happy with my simple text editor but sometimes it'd be nice to run something like PyFlakes on my code before running to check for any obvious errors like undeclared variables or syntax errors.
[ "The previous answer is wrong - the question is neither a duplicated nor does the given command do what \"pyflakes\" does.\n\"pyflakes\" is a python project that integrates with Vim, and allows you to check for interpreter errors in your python code live (as you are coding).\nHowever, i am not aware of any existing...
[ 4, 2 ]
[]
[]
[ "php", "pyflakes", "python" ]
stackoverflow_0004008538_php_pyflakes_python.txt
Q: How to serve an mp3 file with built-in python http server I am currently trying to serve MP3 Files using Python. The problem is that I can only play the MP3 once. Afterwards media controls stop responding and I need to reload entirely the page to be able to listen again to the MP3. (tested in Chrome) Problem: runn...
How to serve an mp3 file with built-in python http server
I am currently trying to serve MP3 Files using Python. The problem is that I can only play the MP3 once. Afterwards media controls stop responding and I need to reload entirely the page to be able to listen again to the MP3. (tested in Chrome) Problem: running the script below, and entering http://127.0.0.1/test.mp3 on...
[ "BaseServer is single-threaded, you should use either ForkingMixIn or ThreadingMixIn to support multiple connections. \nFor example replace line:\nserver = HTTPServer(('', 80), MyHandler)\n\nwith \nfrom SocketServer import ThreadingMixIn\n\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n pass\n\nserver =...
[ 3, 2 ]
[]
[]
[ "http", "mp3", "python", "wsgi" ]
stackoverflow_0005666048_http_mp3_python_wsgi.txt
Q: Markers not showing on Google Map in Google App Engine I have created a Google App Engine project in Python it runs on my localhost but when I upload it onto geo-event-maps.appspot.com the markers are not displaying. I have a cron which runs to call on /place. I have no log errors My datastore is empty! The txt fi...
Markers not showing on Google Map in Google App Engine
I have created a Google App Engine project in Python it runs on my localhost but when I upload it onto geo-event-maps.appspot.com the markers are not displaying. I have a cron which runs to call on /place. I have no log errors My datastore is empty! The txt files are being uploaded with: file_path = os.path.dirname...
[ "You need to be sure your files are being uploaded with your application code, they can not be marked as static files or they won't be accessible to your code. Run appcfg.py with the --verbose flag and make sure they get uploaded.\nSecond issue, in your place class you define path as path = '/storing/txtFiles'. T...
[ 2, 1 ]
[]
[]
[ "cron", "google_app_engine", "google_maps", "google_maps_markers", "python" ]
stackoverflow_0005702013_cron_google_app_engine_google_maps_google_maps_markers_python.txt
Q: Summing 3D array elements with 1D arrays I'm using OpenCV for a computer vision project, however, I need to do a pixel by pixel operation on the image which means accessing every pixel in a 640x480 image and changing it's HSV values. The image is made up of a 3D array X, Y and HSV Values, so a pixel at 130, 230 ma...
Summing 3D array elements with 1D arrays
I'm using OpenCV for a computer vision project, however, I need to do a pixel by pixel operation on the image which means accessing every pixel in a 640x480 image and changing it's HSV values. The image is made up of a 3D array X, Y and HSV Values, so a pixel at 130, 230 may have a HSV value of [12, 26, 18] or represe...
[ "The first and easiest thing you should do is to check to see if OpenCV can take numpy arrays as arguments. Numpy is built on fast C algorithms that can handle large loops over data structures in what are called \"vectorized\" operations. Each loop in Python incurs a very large overhead.\nAnother alternative might ...
[ 1, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0005703096_opencv_python.txt
Q: MySQL&django hangs on huge session delete I'm running django site with MySQL as DB back-end. Finally i've got 3 millions rows in django_session table. Most of them are expired, thus i want to remove them. But if i manually run delete from django_session where expire_date < "2011-04-18" whole site seems to be hang...
MySQL&django hangs on huge session delete
I'm running django site with MySQL as DB back-end. Finally i've got 3 millions rows in django_session table. Most of them are expired, thus i want to remove them. But if i manually run delete from django_session where expire_date < "2011-04-18" whole site seems to be hanged - it cannot be accessed via browser. Why suc...
[ "If your table is MyISAM, DELETE operations lock the table and it is not accessible by the concurrent queries.\nIf there are many records to delete, the table is locked for too long.\nSplit your DELETE statement into several shorter batches.\n", "I am not MySQL expert, but I guess MySQL locks the table for the de...
[ 5, 1, 0, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0005703308_django_mysql_python.txt
Q: php/python date conversion Guys, I have a python script which builds up a MySQL table with timestamps that look like: 2011-04-18 09:54:45 To interface with this MySQL table, I need a php script to match updates. If I run this in PHP: $todaysdate = date(DATE_RFC822); print $todaysdate; returns: Mon, 18 Apr 11 0...
php/python date conversion
Guys, I have a python script which builds up a MySQL table with timestamps that look like: 2011-04-18 09:54:45 To interface with this MySQL table, I need a php script to match updates. If I run this in PHP: $todaysdate = date(DATE_RFC822); print $todaysdate; returns: Mon, 18 Apr 11 09:57:57 -0400 How do I get php ...
[ "just ask the documentation.\n$todaysdate = date(\"Y-m-d H:i:s\");\n\n", "Using date like this should do the trick\n$todaysdate = date(\"Y-m-j H:i:s\");\nprint $todaysdate;\n\nHere is a list of the options you can use.\nhttp://php.net/manual/en/function.date.php \n" ]
[ 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0005704028_php_python.txt
Q: PyGTK Curve memory error i need to draw a graph. and i use gtk.Curve widget for this. and when i add him a long vector it gives me this error: GLib-ERROR **: /build/buildd/glib2.0-2.26.1/glib/gmem.c:170: failed to allocate 4294967276 bytes aborting... the code is simple: w = gtk.Window() c = gtk.Curve() c.set...
PyGTK Curve memory error
i need to draw a graph. and i use gtk.Curve widget for this. and when i add him a long vector it gives me this error: GLib-ERROR **: /build/buildd/glib2.0-2.26.1/glib/gmem.c:170: failed to allocate 4294967276 bytes aborting... the code is simple: w = gtk.Window() c = gtk.Curve() c.set_vector(v) c.set_curve_type(gt...
[ "I do not know why but gtk.Curve does not seem to be able to manipulate data outside of the main loop. Try something like this to add the data after the main call.\nimport random, gtk, gobject\n\ndef createCurve(c):\n v = [random.random() for i in range(800)]\n c.set_vector(v)\n c.set_curve_type(gtk.CURV...
[ 1 ]
[]
[]
[ "memory", "pygtk", "python" ]
stackoverflow_0005703300_memory_pygtk_python.txt
Q: python httplib timeout to localhost I have a local server running on port 6868. Technically it's node.js-driven micro-site built with express. It actually has a single '/push' constroller reading some data and writing to console (+ some specific not question-related operatons). When using curl h100:~ eugenemiroti...
python httplib timeout to localhost
I have a local server running on port 6868. Technically it's node.js-driven micro-site built with express. It actually has a single '/push' constroller reading some data and writing to console (+ some specific not question-related operatons). When using curl h100:~ eugenemirotin$ curl -i http://127.0.0.1:6868/push -d ...
[ "Remove http:// from the address.\nThis:\nconn = httplib.HTTPConnection('http://127.0.0.1:6868')\n\nShould be:\nconn = httplib.HTTPConnection('127.0.0.1:6868')\n\n", "You can simplify your code a lot:\nimport urllib, urllib2\nparams = {'password': 'pwd', 'type': 'msg', 'channel': 'chat', 'client_id': '', 'body': ...
[ 4, 3 ]
[]
[]
[ "httplib", "node.js", "python", "timeout" ]
stackoverflow_0005704097_httplib_node.js_python_timeout.txt
Q: "+=" causing SyntaxError in Python n = 1 p = 4 print n += p gives me: File "p7.py", line 17 print n += p SyntaxError: invalid syntax How can this problem be fixed? A: n += p is a statement in Python, not an expression that returns a value you could print. This is different from a couple of other languages, f...
"+=" causing SyntaxError in Python
n = 1 p = 4 print n += p gives me: File "p7.py", line 17 print n += p SyntaxError: invalid syntax How can this problem be fixed?
[ "n += p is a statement in Python, not an expression that returns a value you could print. This is different from a couple of other languages, for example Ruby, where everything is an expression.\nYou need to do\nn += p\nprint n\n\n", "Assignment, including \"augmented\" assignment (x op= expr as shorcut for x = x...
[ 24, 7, 5, 4, 1, 0 ]
[]
[]
[ "augmented_assignment", "python", "syntax_error" ]
stackoverflow_0005704292_augmented_assignment_python_syntax_error.txt
Q: JIRA - how to get reports programmatically? I use JIRA as a bug tracker and I built a Python tool that converts JIRA tasks report (got as XML from the 'Views' menu) into MS Access records that are user by another tool. Ok, that's done, Python's the greatest ! Now I'd like to know how I can automate the 1st part, i...
JIRA - how to get reports programmatically?
I use JIRA as a bug tracker and I built a Python tool that converts JIRA tasks report (got as XML from the 'Views' menu) into MS Access records that are user by another tool. Ok, that's done, Python's the greatest ! Now I'd like to know how I can automate the 1st part, i.e. creating the report programmatically, ideally...
[ "You can expose JIRA through:\n\nSOAP (currently the preferred way)\nXML-RPC\nREST API (still under development)\n\nAll of which can be easily consumed in Python client. \nSee: http://confluence.atlassian.com/display/JIRA/JIRA+RPC+Services\n" ]
[ 3 ]
[]
[]
[ "jira", "python" ]
stackoverflow_0005704437_jira_python.txt
Q: Python .csv writer I use a .writer() method in a loop, as shown in the Python documentation. I want to write the results of the variable u, row by row (or better line by line). Actually it works perfectly in the interpreter but the module writerow() doesn't seem to work. Why? from urlparse import urlparse import c...
Python .csv writer
I use a .writer() method in a loop, as shown in the Python documentation. I want to write the results of the variable u, row by row (or better line by line). Actually it works perfectly in the interpreter but the module writerow() doesn't seem to work. Why? from urlparse import urlparse import csv import re ifile =ope...
[ "Guessing at you really mean, I would rewrite your code as follows:\nfrom urlparse import urlparse\nimport csv\nimport re\n\nifile =open(ipath,'r')\nofile = open(opath, 'wb')\nwriter = csv.writer(ofile, dialect='excel')\n\nurl =[urlparse(u).netloc for u in ifile]\nsitesource = set([re.sub(\"www.\", \"\", e) for e ...
[ 5, 2, 0, 0 ]
[]
[]
[ "csv", "python", "writer" ]
stackoverflow_0005701962_csv_python_writer.txt
Q: Cast R objects into Python ones with rpy2 The question: how to cast R objects to python ones My case: I need to use the result of cor.test() into a python routine. correlation = robjects.r('function(x, y) cor.test(x, y)') corr= correlation(robjects.IntVector(goodtotemp), robjects.IntVector(goodGDPs)) print corr ...
Cast R objects into Python ones with rpy2
The question: how to cast R objects to python ones My case: I need to use the result of cor.test() into a python routine. correlation = robjects.r('function(x, y) cor.test(x, y)') corr= correlation(robjects.IntVector(goodtotemp), robjects.IntVector(goodGDPs)) print corr print corr[3] print 'coef:',type(corr[3]) outp...
[ "The segmentation fault is a something that should be reported as an rpy2 bug. Otherwise, try either:\nc.ro * 3\n\nor:\nc[0] * 3\n\n", "Python really does not support the concept of casting. It's true that in some limited circumstances it does do something like casting with built-in types.\nBut beyond that it is ...
[ 1, 0 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0005652855_python_r_rpy2.txt
Q: Python networking client, trying to respond to server responses The application is a WxPython client/server setup that has multiple clients connect to the server and engaging in duplex networking protocol. I've had Twisted hooked up with AMP in the past, but it did not fully cut it for the architecture in the appl...
Python networking client, trying to respond to server responses
The application is a WxPython client/server setup that has multiple clients connect to the server and engaging in duplex networking protocol. I've had Twisted hooked up with AMP in the past, but it did not fully cut it for the architecture in the application without overly complicating things in the end. So for the ser...
[ "I think you're mistaken about whether a single-threaded or multi-threaded approach will complicate your application more or less. The problem you're wrestling with now is one of the many that (for example) Twisted solves for you out of the box.\nThe most common complaint people have about Twisted is that it makes...
[ 1, 0 ]
[]
[]
[ "networking", "python", "tcp" ]
stackoverflow_0005702120_networking_python_tcp.txt
Q: Python generator vs callback function I have a class that solves an exact cover problem using a recursive, backtracking algorithm. Originally, I implemented the class with a callback function I passed to the object during initialization. This callback is invoked whenever a solution is found. In looking at someone ...
Python generator vs callback function
I have a class that solves an exact cover problem using a recursive, backtracking algorithm. Originally, I implemented the class with a callback function I passed to the object during initialization. This callback is invoked whenever a solution is found. In looking at someone else's implementation of the same problem, ...
[ "What i meant in my comment, (\"yielding from a recursive function sounds like it requires extra for loops to pass the results down to the caller\") is this line:\n for tf in self.solve():\n yield tf\n\nThese lines recursively loop over the results from the deeper recursion stages. That means t...
[ 2 ]
[]
[]
[ "generator", "profiling", "python" ]
stackoverflow_0005704220_generator_profiling_python.txt
Q: Python Commandline script: file/directory autocompletion on user input I'm writing a Python program which is running inside a Bash Terminal (and it already depends on Bash as its environment). There I have a little setup routine, which asks the user for a directory which is located on his filesystem. This is how I...
Python Commandline script: file/directory autocompletion on user input
I'm writing a Python program which is running inside a Bash Terminal (and it already depends on Bash as its environment). There I have a little setup routine, which asks the user for a directory which is located on his filesystem. This is how I read the input: print "Input:", input = sys.stdin.readline().strip() Now I...
[ "You want to checkout the readline module. I answered a similar question here, which shows how to do filename/dirname auto-completion of paths. Let me know if you need more detail.\n" ]
[ 5 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0005705066_command_line_python.txt
Q: Django: want to improve speed of query I have a django app which displays the list of items for each client. it displays an item id, an alternative id, title and more other information. Because I have a lot of I items (Each client could have thousand of items), it can take very long to load up all of the items. Is...
Django: want to improve speed of query
I have a django app which displays the list of items for each client. it displays an item id, an alternative id, title and more other information. Because I have a lot of I items (Each client could have thousand of items), it can take very long to load up all of the items. Is there a way to improve this speed? def clie...
[ "\"Pagination\"\n", "Paginate results into something more manageable than thousands of item. Without pagination it not only slow, but also gives bad user experience. \n", "Make sure that the items are loaded with a constant number of database queries. For most views, you should be able to load all your data wit...
[ 2, 0, 0 ]
[]
[]
[ "django", "mysql", "python", "views" ]
stackoverflow_0005700939_django_mysql_python_views.txt
Q: How can I get the width of a wx.ListCtrl and its column name? I'm working in wx.Python and I want to get the columns of my wx.ListCtrl to auto-resize i.e. to be at minimum the width of the column name and otherwise as wide as the widest element or its column name. At first I thought the ListCtrlAutoWidthMixin mig...
How can I get the width of a wx.ListCtrl and its column name?
I'm working in wx.Python and I want to get the columns of my wx.ListCtrl to auto-resize i.e. to be at minimum the width of the column name and otherwise as wide as the widest element or its column name. At first I thought the ListCtrlAutoWidthMixin might do this but it doesn't so it looks like I might have to do it my...
[ "In Addition to jakepars answer: this should check, whether the header is bigger, or the item which takes the most space in the column. Not to elegant but working...\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self, *args, **kw):\n wx.Frame.__init__(self, *args, **kw)\n\n self.list = wx.Lis...
[ 4, 3, 2, 1 ]
[]
[]
[ "listctrl", "python", "width", "wxpython", "wxwidgets" ]
stackoverflow_0000722298_listctrl_python_width_wxpython_wxwidgets.txt
Q: Python Website Full-Site Search I'm wondering if anyone has any recommendations for a Python full-text search engine similar to mnogosearch. I'm trying to get it to function like Mnogosearch, but not sure how that compares to other options (if there are better options out there). Haystack, for example, seems ...
Python Website Full-Site Search
I'm wondering if anyone has any recommendations for a Python full-text search engine similar to mnogosearch. I'm trying to get it to function like Mnogosearch, but not sure how that compares to other options (if there are better options out there). Haystack, for example, seems like it does a great job at indexing ...
[ "IMHO Solr is probably the best option, performance-wise and feature-wise and it's based on heavily tested technology. And if you're looking for a pure Python solution Whoosh looks good - I haven't used it in production, just checked it out and looked at the code. It may be slower, but I doubt that it's noticeable ...
[ 2 ]
[]
[]
[ "lucene", "python", "search", "solr", "whoosh" ]
stackoverflow_0005705122_lucene_python_search_solr_whoosh.txt
Q: How to run command from within eclipse(Pydev) Is it possible to run python command from within eclipse(Pydev)? I want to create a procedure which will create database. Currently I create database by writing the command in command prompt, But I want the same from my code within eclipse. Something like: def createD...
How to run command from within eclipse(Pydev)
Is it possible to run python command from within eclipse(Pydev)? I want to create a procedure which will create database. Currently I create database by writing the command in command prompt, But I want the same from my code within eclipse. Something like: def createDatabase() createdb -U myUser -T template0
[ "Try popen2 module. It allows you to spawn processes. Then you can call your function from PyDev console\n", "You can also execute a program from Run>External Tools>External Tools Configurations. Once you set it up, you can re-run it from the toolbar.\n" ]
[ 1, 0 ]
[]
[]
[ "eclipse", "postgresql", "python" ]
stackoverflow_0005699894_eclipse_postgresql_python.txt
Q: How to choose python version run when typing only "python" at prompt? I have just installed Python2.6 on a Red Hat linux server which was supplied with python2.4 preinstaleld. When I type python, python2.4 is launched, typing python2.6 launches python 2.6 correctly. What is the correct way to make 2.6 the default?...
How to choose python version run when typing only "python" at prompt?
I have just installed Python2.6 on a Red Hat linux server which was supplied with python2.4 preinstaleld. When I type python, python2.4 is launched, typing python2.6 launches python 2.6 correctly. What is the correct way to make 2.6 the default? Also how can this result be possible: $ python -V && which python && pwd &...
[ "It's a symlink actually.\n$ ls -al `which python`\nlrwxrwxrwx 1 root root 9 2010-04-21 12:08 /usr/bin/python -> python2.6\n\nSo changing the default version from 2.4 to 2.6 would be just:\ncd /usr/bin\nsudo ln -sf `which python2.6` python\n\n", "The easiest and quickest way, is to prepend the path to the 2.6.6 v...
[ 5, 3 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005705627_linux_python.txt
Q: Django upgrade succeeds, then reverts back My django version is 1.1 rgross@fun:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> print django.VERSION (1, 1, 1, 'final', 0) >>> quit() rgross@...
Django upgrade succeeds, then reverts back
My django version is 1.1 rgross@fun:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> print django.VERSION (1, 1, 1, 'final', 0) >>> quit() rgross@fun:~$ So, I upgrade to the latest version. gr...
[ "The problem was caused because I had also installed django by apt-get.\nTo resolve:\nsudo apt-get remove python-django\n\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005705640_django_python.txt
Q: Accessing function as attribute in a Python class I'm in a situation where it would be extremely useful (though not strictly necessary) to access a class' instancemethod as an attribute. (it's for an API that uses getattr to set some return values for a dictionary and I don't want to mess the neat little thing up)...
Accessing function as attribute in a Python class
I'm in a situation where it would be extremely useful (though not strictly necessary) to access a class' instancemethod as an attribute. (it's for an API that uses getattr to set some return values for a dictionary and I don't want to mess the neat little thing up) I remember reading something about an @attribute decor...
[ "You can use the @property decorator.\nclass foo(object):\n bar = \"bar\"\n @property\n def baz(self):\n return \"baz\"\n\n", "Take a look at the decorator form of property.\n@property\ndef baz(self):\n return \"baz\"\n\n" ]
[ 79, 17 ]
[]
[]
[ "django", "metaprogramming", "python" ]
stackoverflow_0005705618_django_metaprogramming_python.txt
Q: Are Python global variables thread-safe? edit: im asking if global variables are safe in a single-threaded web framework like tornado im using the mongoengine orm, which gets a database connection from a global variable: _get_db() # gets the db connection im also using tornado, a single-threaded python web fram...
Are Python global variables thread-safe?
edit: im asking if global variables are safe in a single-threaded web framework like tornado im using the mongoengine orm, which gets a database connection from a global variable: _get_db() # gets the db connection im also using tornado, a single-threaded python web framework. in one particular view, i need to grab ...
[ "Threads are always required to hold the GIL when interacting with Python objects. The namespace holding the variables is a Python object (either a frameobject or a dict, depending on what kind of variable it is.) It's always safe to get or set variables in multiple threads. You will never get garbage data.\nHowev...
[ 3, 2, 1, 0 ]
[]
[]
[ "mongodb", "python", "tornado" ]
stackoverflow_0002248434_mongodb_python_tornado.txt
Q: How does BLAS sgemm/dgemm work? I am trying to make use of the function sgemm in BLAS using ctypes in python. Trying to solve C = A x B the following code works just fine: no_trans = c_char("n") m = c_int(number_of_rows_of_A) n = c_int(number_of_columns_of_B) k = c_int(number_of_columns_of_A) one = c_float(1.0) ze...
How does BLAS sgemm/dgemm work?
I am trying to make use of the function sgemm in BLAS using ctypes in python. Trying to solve C = A x B the following code works just fine: no_trans = c_char("n") m = c_int(number_of_rows_of_A) n = c_int(number_of_columns_of_B) k = c_int(number_of_columns_of_A) one = c_float(1.0) zero = c_float(0.0) blaslib.sgemm_(byr...
[ "Blas typically uses column-major matrices (like Fortran), hence A = [1 2; 3 4] means \n |1 3| \nA = | |\n |2 4|\n\nand the result is correct (assuming that your Python library does the same). See this read-me\n", "The result you have indicates sgemm had computed A*A' rather than A'*A as you wanted. The...
[ 7, 1 ]
[]
[]
[ "blas", "ctypes", "linear_algebra", "python" ]
stackoverflow_0005705506_blas_ctypes_linear_algebra_python.txt
Q: How can I install my project from source with Buildout? I want to use Buildout to install my Distribute-based project and its dependencies to an isolated environment. My project should be installed directly from the source tree (a local Git repository), and is not registered with PyPI. How do I accomplish this? Ed...
How can I install my project from source with Buildout?
I want to use Buildout to install my Distribute-based project and its dependencies to an isolated environment. My project should be installed directly from the source tree (a local Git repository), and is not registered with PyPI. How do I accomplish this? Edit: Thanks to M. Pieters I was able to suss out what to do. I...
[ "You have 3 options, depending on where you want your buildout configuration to live and what options you have to check out your git repository.\nNote that as far as Python is concerned, the resulting egg is exactly the same. The only difference between a development egg and a \"normal\" egg is that a development e...
[ 12, 3 ]
[]
[]
[ "buildout", "deployment", "python" ]
stackoverflow_0005703456_buildout_deployment_python.txt
Q: How to Detect in Sub Process When Parent Process Has Died? In python, I have a parent process that spawns a handful of child processes. I've run into a situation where, due to an unhandled exception, the parent process was dieing and the child processes where left orphaned. How do I get the child processes to reco...
How to Detect in Sub Process When Parent Process Has Died?
In python, I have a parent process that spawns a handful of child processes. I've run into a situation where, due to an unhandled exception, the parent process was dieing and the child processes where left orphaned. How do I get the child processes to recognize that they've lost their parent? I tried some code that hoo...
[ "on UNIX (including Linux):\ndef is_parent_running():\n try:\n os.kill(os.getppid(), 0)\n return True\n except OSError:\n return False\n\nNote, that on UNIX, signal 0 is not a real signal. It is used just to test if given process exists. See manual for kill command.\n", "You can use soc...
[ 8, 5 ]
[]
[]
[ "orphan", "python", "subprocess" ]
stackoverflow_0005705659_orphan_python_subprocess.txt
Q: Java vs. Python specific code-fragment performance improvement I have a question regarding performance of a specific piece of code in Java and Python. Algorithm: I am generating random N-dimensional points and then for all points under a certain distance threshold of each other I do some processing. The processi...
Java vs. Python specific code-fragment performance improvement
I have a question regarding performance of a specific piece of code in Java and Python. Algorithm: I am generating random N-dimensional points and then for all points under a certain distance threshold of each other I do some processing. The processing itself is not important here as it does not impact total executio...
[ "You might want to consider using numpy.\nI've just tried the following:\nimport numpy\nfrom scipy.spatial.distance import pdist\nD=2\nN=3000\np=numpy.random.uniform(size=(N,D))\ndist=pdist(p, 'euclidean')\n\nThe last line computes the distance matrix (this is equivalent to computing distance in your code for every...
[ 5, 2, 1 ]
[]
[]
[ "algorithm", "java", "performance", "python" ]
stackoverflow_0005705378_algorithm_java_performance_python.txt
Q: PyCUDA kernel timing errors Simple enough start=cuda.Event() func(args,block=blockdims) cuda.memcpy_dtoh(d,h) end=cuda.Event() dur=start.time_till(end) print dur But I'm getting this error File "gpu.py", line 161, in gpu_test dur=start.time_till(end) pycuda._driver.LogicError: cuEventElapsedTime failed: inva...
PyCUDA kernel timing errors
Simple enough start=cuda.Event() func(args,block=blockdims) cuda.memcpy_dtoh(d,h) end=cuda.Event() dur=start.time_till(end) print dur But I'm getting this error File "gpu.py", line 161, in gpu_test dur=start.time_till(end) pycuda._driver.LogicError: cuEventElapsedTime failed: invalid handle This is as far as I c...
[ "Take a look at SimpleSpeedTest.py:\nstart=cuda.Event()\nend=cuda.Event()\n\nstart.record() # start timing\nfunc(args,block=blockdims)\ncuda.memcpy_dtoh(d,h)\nend.record() # end timing\n# calculate the run length\nend.synchronize()\nmillis = start.time_till(end)\nprint millis\n\n" ]
[ 1 ]
[]
[]
[ "cuda", "gpu", "pycuda", "python" ]
stackoverflow_0005706192_cuda_gpu_pycuda_python.txt
Q: Monitoring vi usage I have a file in which I have stored information about users: username, full name, group, etc. I have to write a "monitoring" shell script, that saves in a file called log.txt all the users (username, full name, group) that execute a vi command more than once per minute. The log file should a...
Monitoring vi usage
I have a file in which I have stored information about users: username, full name, group, etc. I have to write a "monitoring" shell script, that saves in a file called log.txt all the users (username, full name, group) that execute a vi command more than once per minute. The log file should also contain the time when...
[ "Rename /usr/bin/vi. Put a wrapper script that does your logging and then executes the original vi.\nWithout more work, users could still run the original vi, but this might help and will certainly have a lower impact than running 'ps' constantly.\n" ]
[ 1 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0005541971_python_shell.txt
Q: two bytes swapped in packet received from Python raw socket My Python program is receiving ICMP destination unreachable messages from a raw socket. The socket is created with the following code: socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) ICMP destination unreachable messages include a co...
two bytes swapped in packet received from Python raw socket
My Python program is receiving ICMP destination unreachable messages from a raw socket. The socket is created with the following code: socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) ICMP destination unreachable messages include a copy of a portion of the original packet. The problem I am experienc...
[ "Those fields are likely in network byte-order (i.e. big-endian), and you are using a little-endian machine. So, byte-swapping is needed. The struct library built into Python should help you with deserialization of these messages. Please refer to section 7.3.2.1. Byte Order, Size, and Alignment.\nI'd recommend refe...
[ 3 ]
[]
[]
[ "icmp", "ip", "ipv4", "network_programming", "python" ]
stackoverflow_0005682990_icmp_ip_ipv4_network_programming_python.txt
Q: Clicking a link based on partial text match I'm using Selenium 2/Webdriver with python and I want to click on the first link that starts with a string. Here's the code I came up with: def click_link_partial(div_id, partial): linkdiv = driver.find_element_by_id(div_id) z = (a.click() for a in linkdiv.find_eleme...
Clicking a link based on partial text match
I'm using Selenium 2/Webdriver with python and I want to click on the first link that starts with a string. Here's the code I came up with: def click_link_partial(div_id, partial): linkdiv = driver.find_element_by_id(div_id) z = (a.click() for a in linkdiv.find_elements_by_tag_name('a') if a.text.startswith(partial...
[ "First and foremost, please, familiarize yourself with Python's generators, they are a very powerful tool in your Python arsenal. A great explanation by Thomas Wouters can be found by reading another question: What can you use Python generator functions for?\nOnce you're finished reading, you'll realize that a gene...
[ 2 ]
[]
[]
[ "python", "selenium_webdriver" ]
stackoverflow_0005705534_python_selenium_webdriver.txt
Q: Python summation style question Which is more pythonic? T = 0 for a in G: T += a.f() or T = sum(a.f() for a in G) A: The latter. The name is only bound once, as opposed to happening n+1 times. A: The latter. It is just one line and you quickly see what it's doing. Besides that, there's onl...
Python summation style question
Which is more pythonic? T = 0 for a in G: T += a.f() or T = sum(a.f() for a in G)
[ "The latter. The name is only bound once, as opposed to happening n+1 times.\n", "The latter. It is just one line and you quickly see what it's doing. Besides that, there's only one access to T which might be a little bit faster.\n", "ncoghlan is right: in the more rigorous sense, an augmented assignement alway...
[ 8, 6, 2, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0005683476_coding_style_python.txt
Q: ZODB not able to commit I am using ZODB first time. Just trying to commit the data with FileStorage. But when I do the same script second time I am not able to commit the new object. Here is my script from ZODB import FileStorage,DB import transaction storage = FileStorage.FileStorage('/tmp/test.fs') db = DB(...
ZODB not able to commit
I am using ZODB first time. Just trying to commit the data with FileStorage. But when I do the same script second time I am not able to commit the new object. Here is my script from ZODB import FileStorage,DB import transaction storage = FileStorage.FileStorage('/tmp/test.fs') db = DB(storage) conn = db.open() roo...
[ "The ZODB persistence layer detects changes by hooking into the python __setattr__ hook, marking the persistent object as changed every time you set an attribute.\nBut if you use a primitive mutable object like a python dictionary, then there is no way for the persistence machinery to detect the changes, as there i...
[ 5, 0 ]
[]
[]
[ "python", "zodb" ]
stackoverflow_0005704589_python_zodb.txt
Q: python creating a class at runtime containing another class I wanted to generate a class at runtime like the following: from google.appengine.ext.db import djangoforms class TestForm(ConsumerForm): class Meta: model = Consumer I can use form_model = type("TestForm", (djangoforms.ModelForm,), {}) to creat...
python creating a class at runtime containing another class
I wanted to generate a class at runtime like the following: from google.appengine.ext.db import djangoforms class TestForm(ConsumerForm): class Meta: model = Consumer I can use form_model = type("TestForm", (djangoforms.ModelForm,), {}) to create the TestForm class but I'm not sure how to create the Meta clas...
[ "Create it in the same manner as TestForm and put it into TesForm's dictionary:\nMeta = type(\"Meta\", (), {\"model\": Consumer})\nTestForm = type(\"TestForm\", (djangoforms.ModelForm,), {\"Meta\": Meta})\n\n(Disclaimer: I'd usually avoid dynamically creating classes.)\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "python", "types" ]
stackoverflow_0005706603_google_app_engine_python_types.txt
Q: Floating point precision while using Python's max() Why so? >>> max(2, 2.01) 2.0099999999999998 A: The number 2.01 represented in binary is: b10.00000010100011111100001010001111110000101000111111000010100011111100... The computer uses only a finite number of digits to store floating-point values, but the binary...
Floating point precision while using Python's max()
Why so? >>> max(2, 2.01) 2.0099999999999998
[ "The number 2.01 represented in binary is:\nb10.00000010100011111100001010001111110000101000111111000010100011111100...\n\nThe computer uses only a finite number of digits to store floating-point values, but the binary representation of 2.01 requires infinitely many digits; as a result, it is rounded to the closest...
[ 5, 3, 2, 0 ]
[]
[]
[ "floating_accuracy", "floating_point", "precision", "python" ]
stackoverflow_0005701317_floating_accuracy_floating_point_precision_python.txt
Q: pythonic way to split string into two lists I have a lot of files with string pairs looking like: first_string~second_string The first part is what to change and the second, to what change the first part. These are regular expressions and I run my app with these collections to apply all modifications to dirty ...
pythonic way to split string into two lists
I have a lot of files with string pairs looking like: first_string~second_string The first part is what to change and the second, to what change the first part. These are regular expressions and I run my app with these collections to apply all modifications to dirty tv schedule listings for more than a hundred chan...
[ "x = [\"c~d\", \"e~f\", \"g~h\"]\na, b = zip(*(s.split(\"~\") for s in x))\nprint a\nprint b\n\nprints\n('c', 'e', 'g')\n('d', 'f', 'h')\n\n" ]
[ 12 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005706735_python_string.txt
Q: Changing password, python, linux How can i change password of ubuntu root user by python script? Thanks. A: There are two main ways to go about this - One is calling the passwd command line tool from python (such as via stdlib's subprocess module). If your script isn't running as root, you'll need to wrap using...
Changing password, python, linux
How can i change password of ubuntu root user by python script? Thanks.
[ "There are two main ways to go about this - \nOne is calling the passwd command line tool from python (such as via stdlib's subprocess module). If your script isn't running as root, you'll need to wrap using the \"su\" or \"sudo\" commands in order to elevate to root privledge. Writing the expected data to stdin sh...
[ 5, 2, 0 ]
[]
[]
[ "change_password", "linux", "python" ]
stackoverflow_0005706597_change_password_linux_python.txt
Q: Refresh PyDev import paths in Eclipse I'm using Eclipse Helios under Ubuntu. Whenever I install a new library under /usr/local/lib/python2.6/dist-packages/ using pip, Eclipse doesn't see it and complains about invalid imports. I double checked the library is in place. Importing it works from the interpreter. Refre...
Refresh PyDev import paths in Eclipse
I'm using Eclipse Helios under Ubuntu. Whenever I install a new library under /usr/local/lib/python2.6/dist-packages/ using pip, Eclipse doesn't see it and complains about invalid imports. I double checked the library is in place. Importing it works from the interpreter. Refreshing the PyDev configuration or restarting...
[ "The problem was that I installed the library from an egg. Egg folders need to be added manually or otherwise PyDev won't see them. Another thing that confused me a little was that I had another version of the same library installed as a regular folder. That folder however didn't have __init__.py in it.\n" ]
[ 4 ]
[]
[]
[ "eclipse", "import", "path", "pydev", "python" ]
stackoverflow_0005705336_eclipse_import_path_pydev_python.txt
Q: Python : Using abc in Python < 2.6 Do someone know an implementation of abc for older versions of Python (older than 2.6) ? EDIT : I am for example looking for a snippet that would do the same thing as ABCMeta and abstractmethod, with same interface, I actually need to make a piece of code backward compatible A: ...
Python : Using abc in Python < 2.6
Do someone know an implementation of abc for older versions of Python (older than 2.6) ? EDIT : I am for example looking for a snippet that would do the same thing as ABCMeta and abstractmethod, with same interface, I actually need to make a piece of code backward compatible
[ "The abc module itself happens to be backwards compatible. Just copy abc.py from 2.6 to somewhere on the pythonpath.\n" ]
[ 1 ]
[ "There is nothing like that. But metaclasses are a core concept of Python since a long time.\n" ]
[ -2 ]
[ "abc", "backport", "python" ]
stackoverflow_0005700424_abc_backport_python.txt
Q: execute code block on two separate dicts at the same time Say I have this piece of code, and I want to execute it on two separate dictionaries. How can I do this easily without writing the code twice? I guess i could def a small function and then pass each dict to it. Are there any better ways? for key, val...
execute code block on two separate dicts at the same time
Say I have this piece of code, and I want to execute it on two separate dictionaries. How can I do this easily without writing the code twice? I guess i could def a small function and then pass each dict to it. Are there any better ways? for key, value in self.mfiles.iteritems(): if key not in self.INPUT...
[ "You can do this:\nfor data in (self.mfiles, self.nmfiles):\n for key, value in data.iteritems():\n if key not in self.INPUT['extras']:\n data[key] = self.dirs['confdir'] + '/' + value\n\nHowever, I think writing a small function is probably clearer.\n", "Make a method which uses the dictiona...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005707118_dictionary_python.txt
Q: using several xmlrpc commands on twisted I have a simple client code using xmlrpclib. try: Server.func1 Server.func2 ..... Server.funcN except: pass , where Server - ServerProxy from xmlrpclib. How to do this on twisted ? I see this example: from twisted.web.xmlrpc import Proxy fr...
using several xmlrpc commands on twisted
I have a simple client code using xmlrpclib. try: Server.func1 Server.func2 ..... Server.funcN except: pass , where Server - ServerProxy from xmlrpclib. How to do this on twisted ? I see this example: from twisted.web.xmlrpc import Proxy from twisted.internet import reactor def printV...
[ "You have code in the sample you pasted which takes an action when an XML-RPC call completes. printValue prints the result of a call and printError print an error which occurs during a call.\nIf you want to make another call after one finishes, then maybe instead of just printing something in printValue, you could...
[ 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0005705420_python_twisted.txt
Q: How to open a list from python module depending upon user input I have a bunch of lists in a module (say student_data) which I import in my file. All the list are of type student[1-100]. Now depending on user input I wish to iterate through the corresponding list. Lets say the user inputs 10 then I want to print t...
How to open a list from python module depending upon user input
I have a bunch of lists in a module (say student_data) which I import in my file. All the list are of type student[1-100]. Now depending on user input I wish to iterate through the corresponding list. Lets say the user inputs 10 then I want to print the contents of list student10. How do I go about doing this? Input in...
[ "You should put all of the lists into a big list of lists.\nThen you use can the standard student_data.student_lists[index] to get an individual list.\n", "Winston Ewert is definitely correct in what the right way to do this would be.\nHowever, if you're locked into your existing data structure, what you want is ...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005707097_python.txt
Q: Python, use the lists in the list, or objects in the list? I have a list and in each list element, I need some details. What will be more efficient to use the list in the list [['brown', 'wood', 2], ['red', 'box', 3 ],...] Or create a new class for the parameters(details) of color, type, etc.. and creating objec...
Python, use the lists in the list, or objects in the list?
I have a list and in each list element, I need some details. What will be more efficient to use the list in the list [['brown', 'wood', 2], ['red', 'box', 3 ],...] Or create a new class for the parameters(details) of color, type, etc.. and creating objects from this class in every element of the list. [object1,objec...
[ "List of lists will be more efficient(as in less overhead for function calls, object creation, object destruction etc and take up less space in memory), however creating a new class might be better for readability, writability, and maintainability. \nMy opinion is that you shouldn't worry about these micro optimiza...
[ 3, 2 ]
[]
[]
[ "list", "object", "performance", "python" ]
stackoverflow_0005707549_list_object_performance_python.txt
Q: Python web framework Is there a Python web framework where the Python code and the HTML code are in the same file? Django uses templates with a special language to generate HTML. Pylons uses a kind of language whose name is Mako. I prefer to output HTML using calls like: echo(''' HTML string ''') or print '''...
Python web framework
Is there a Python web framework where the Python code and the HTML code are in the same file? Django uses templates with a special language to generate HTML. Pylons uses a kind of language whose name is Mako. I prefer to output HTML using calls like: echo(''' HTML string ''') or print ''' HTML string ''' inst...
[ "This might be what you prefer, but it's really against every best practice ever. That being said, you can do this with django.\nfrom django.http import HttpResponse\ndev some_view(request):\n return HttpResponse(\"This is foolish short term gain\")\n\n", "If you want to use print itself you may want to rely ...
[ 2, 2, 1, 0 ]
[]
[]
[ "python", "web_frameworks" ]
stackoverflow_0005683748_python_web_frameworks.txt
Q: Custom urllib opener that uses client certificates I have got an API that I have to work with. The API is secured by HTTPS and uses mutual authentication/client certificates. I have a PEM file and a CRT file. When I connect to the server regularly, using PyOpenSSL I have no problem, here is the code: import setti...
Custom urllib opener that uses client certificates
I have got an API that I have to work with. The API is secured by HTTPS and uses mutual authentication/client certificates. I have a PEM file and a CRT file. When I connect to the server regularly, using PyOpenSSL I have no problem, here is the code: import settings from OpenSSL import SSL import socket def verify(co...
[ "It looks like you're adding a lot of complexity here that you don't really need. If you're just doing simple client certificate authentication, you could probably get away from the following snippet (source):\nimport httplib\nimport urllib2\n\n# HTTPS Client Auth solution for urllib2, inspired by\n# http://bugs.py...
[ 3, 1 ]
[]
[]
[ "https", "mutual_authentication", "pyopenssl", "python", "ssl" ]
stackoverflow_0005700289_https_mutual_authentication_pyopenssl_python_ssl.txt
Q: PyQt Signals and slots I've just started programming in PyQt and I'm following "Rapid GUI programming in Python and Qt" by Mark Summerfield. Before this I did some programming in C++ and Qt and the author of the book which I followed recommended the use of signals and slots, and I too like the use of signals and s...
PyQt Signals and slots
I've just started programming in PyQt and I'm following "Rapid GUI programming in Python and Qt" by Mark Summerfield. Before this I did some programming in C++ and Qt and the author of the book which I followed recommended the use of signals and slots, and I too like the use of signals and slots over "on_widgetName_sig...
[ "Basicly when you use on_widget_signal() it auto connects \"widget\"'s signals to that function (applies to C++)\nCheck QMetaObject::connectSlotsByName\n" ]
[ 1 ]
[]
[]
[ "pyqt", "python", "signals_slots" ]
stackoverflow_0005707966_pyqt_python_signals_slots.txt
Q: Recurrence sequence in Java / Python / Mathematica How can you write the following statement in the given languages? a(0) = 1 a_(n+1) = 1 - 1 / ( a_n + 3) I need to find the smallest value of n when a_n -> 0.732050.... My attempt in Mathematica a[(x+1)_] = 1 - 1/(a[x_] + 3) The problem is apparently in this a[(x...
Recurrence sequence in Java / Python / Mathematica
How can you write the following statement in the given languages? a(0) = 1 a_(n+1) = 1 - 1 / ( a_n + 3) I need to find the smallest value of n when a_n -> 0.732050.... My attempt in Mathematica a[(x+1)_] = 1 - 1/(a[x_] + 3) The problem is apparently in this a[(x+1)_]. However, I do not know how to do it iteratively i...
[ "Mathematica\na[0] = 1;\na[n_] := a[n] = 1 - 1/(a[n-1] + 3)\n\n(Note the memoization trick.)\nAlso, a[n] converges (very quickly) to sqrt(3)-1:\nSolve[x == 1 - 1/(x+3), x]\n\n", "Python, simplest:\ndef a(n):\n if n == 0: return 1\n return 1 - 1 / float(a(n-1) + 3)\n\n# limit is sqrt(3) - 1\nlimit = 3.0 ** 0.5 -...
[ 8, 4, 3, 3, 2, 1 ]
[]
[]
[ "java", "python", "sequence", "wolfram_mathematica" ]
stackoverflow_0001540519_java_python_sequence_wolfram_mathematica.txt
Q: Script always gets a 302 response when pulling random pages from Wikipedia I can pull a any page from wikipedia with import httplib conn = httplib.HTTPConnection("en.wikipedia.org") conn.debuglevel = 1 conn.request("GET","/wiki/Normal_Distribution",headers={'User-Agent':'Python httplib'}) r1 = conn.getresponse() ...
Script always gets a 302 response when pulling random pages from Wikipedia
I can pull a any page from wikipedia with import httplib conn = httplib.HTTPConnection("en.wikipedia.org") conn.debuglevel = 1 conn.request("GET","/wiki/Normal_Distribution",headers={'User-Agent':'Python httplib'}) r1 = conn.getresponse() r1.read() The normal response will be reply: 'HTTP/1.0 200 OK\r\n' header: Date...
[ "The 302 is a redirect. It's telling you where to go in the following line:\nheader: Location: http://en.wikipedia.org/wiki/tuticorin_port_trust \n\nYou just need to follow the redirect.\n", "When you're redirected the response object is going to have a code of 302 and the geturl() method will report the redirec...
[ 5, 3, 2, 2 ]
[]
[]
[ "http", "python", "wikipedia" ]
stackoverflow_0005707984_http_python_wikipedia.txt
Q: Trying to read quicktime file chapter metadata Does anyone know of a way using php, perl, or python I can read the chapter name and chapter start time from a quicktime video file in a .mov container on a linux system? I'd appreciate any help. Thanks! A: I'd use the unix commandline extract tool which supports hu...
Trying to read quicktime file chapter metadata
Does anyone know of a way using php, perl, or python I can read the chapter name and chapter start time from a quicktime video file in a .mov container on a linux system? I'd appreciate any help. Thanks!
[ "I'd use the unix commandline extract tool which supports hundreds of file formats - .mov included.\n" ]
[ 0 ]
[]
[]
[ "linux", "perl", "php", "python", "quicktime" ]
stackoverflow_0005708151_linux_perl_php_python_quicktime.txt
Q: Displaying HTML Source rather than rendering the code in GAE I am trying to display the source code of the site using Google App Engine. Here is the snippets of the code that I have tried out. def post(self): s = 'http://www.bing.com' fp = urllib.urlopen(s) src = fp.read() self.response.out.write(...
Displaying HTML Source rather than rendering the code in GAE
I am trying to display the source code of the site using Google App Engine. Here is the snippets of the code that I have tried out. def post(self): s = 'http://www.bing.com' fp = urllib.urlopen(s) src = fp.read() self.response.out.write(template.render('main.html',{'temp1':src})) And the template I ha...
[ "If you want to see the html and not the page you gonna need to escape the html entities.\nTry: src = cgi.escape(src)\nAnd maybe put it inside <pre></pre> tags for distinctive displaying.\n", "(assuming that you're using the Django templates that come with Appengine,) you can use the built-in escape filter, like:...
[ 5, 2, 1 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0005706034_django_templates_google_app_engine_python.txt
Q: Getting the checkboxes toggling in a GtkTreeView I am using a treeview with checkboxes. I want the user to be able to click a checkbox and it will add that item to a favourites list. But currently I cannot get the boxes to toggle at all. Here's my code: def draw_columns(self,treeview): self.ren = gtk.CellRende...
Getting the checkboxes toggling in a GtkTreeView
I am using a treeview with checkboxes. I want the user to be able to click a checkbox and it will add that item to a favourites list. But currently I cannot get the boxes to toggle at all. Here's my code: def draw_columns(self,treeview): self.ren = gtk.CellRendererToggle() self.ren.connect('toggled',self.on_tog...
[ "Disclaimer: I am confident this is not total bs, but can't test it at the moment.\nFirst, a CellRendererToggle wouldn't take a text property. second, if you would set it anyway, you wouldn't set it to column index 7 because you only have 7 column on the liststore (and index 7 would be the eigth column).\nYou can s...
[ 4 ]
[]
[]
[ "gtktreeview", "pygtk", "python" ]
stackoverflow_0005707495_gtktreeview_pygtk_python.txt
Q: How can I elegantly implement version checking in Python without throwing off indentation? I'd like to very elegantly integrate version checking in Python. I don't want a version checking routine to throw off the indentation of all of my code, however. I.e. if old_version: print 'hey, upgrade.' else: # main b...
How can I elegantly implement version checking in Python without throwing off indentation?
I'd like to very elegantly integrate version checking in Python. I don't want a version checking routine to throw off the indentation of all of my code, however. I.e. if old_version: print 'hey, upgrade.' else: # main body of whole script In the above implementation, the main body of the whole script would need t...
[ "You can do\nimport sys\n\nif old_version:\n print 'hey, upgrade.'\n sys.exit(1) # A non-zero code indicates failure, on Unix (sys.exit() exits too, but it returns a 0 [=success] exit code)\n\n# main body of whole script\n\nThis exits the interpreter if the code needs to be upgraded.\nThe reason for returnin...
[ 7, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005708634_python.txt
Q: Is there a function that can calculate a score for aligned sequences given the alignment parameters? I try to score the already-aligned sequences. Let say seq1 = 'PAVKDLGAEG-ASDKGT--SHVVY----------TI-QLASTFE' seq2 = 'PAVEDLGATG-ANDKGT--LYNIYARNTEGHPRSTV-QLGSTFE' with given parameters substitution matrix : blosum6...
Is there a function that can calculate a score for aligned sequences given the alignment parameters?
I try to score the already-aligned sequences. Let say seq1 = 'PAVKDLGAEG-ASDKGT--SHVVY----------TI-QLASTFE' seq2 = 'PAVEDLGATG-ANDKGT--LYNIYARNTEGHPRSTV-QLGSTFE' with given parameters substitution matrix : blosum62 gap open penalty : -5 gap extension penalty : -1 I did look through the biopython cookbook but all i ca...
[ "Jessada, \nThe Blosum62 matrix (note the spelling ;) is in Bio.SubsMat.MatrixInfo and is a dictionary with tuples resolving to scores (so ('A', 'A') is worth 4 pts). It doesn't have the gaps, and it's only one triangle of the matrix (so it might ahve ('T', 'A') but not ('A', 'T'). There are some helper functions i...
[ 12, 10 ]
[]
[]
[ "bioinformatics", "biopython", "python" ]
stackoverflow_0005686211_bioinformatics_biopython_python.txt
Q: Python xlrd read as string I'm having difficulties in reading a particular cell value from Excel in xlrd. Whatever value I'm reading (date value) is getting converted to a number. I know there are solutions to convert it into a python date format, but can I read directly the string value in xlrd? A: xlrd does NO...
Python xlrd read as string
I'm having difficulties in reading a particular cell value from Excel in xlrd. Whatever value I'm reading (date value) is getting converted to a number. I know there are solutions to convert it into a python date format, but can I read directly the string value in xlrd?
[ "xlrd does NOT convert dates to float. Excel stores dates as floats.\nQuoting from the xlrd documentation (scroll down a page):\n\nDates in Excel spreadsheets\nIn reality, there are no such things.\n What you have are floating point\n numbers and pious hope. There are\n several problems with Excel dates:\n(1) Da...
[ 10, 7, 4 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0005707812_python_xlrd.txt
Q: Linking error Boost.Python with stlport as stdlib I'm trying to create C++ extensions for python. My C++ code relies on STLPort 5.1.0. I've compiled boost.python with stdlib=stlport. This occurs in my compiler which is Microsoft Visual Studio 2005. But I keep getting the following linking error when I attempt t...
Linking error Boost.Python with stlport as stdlib
I'm trying to create C++ extensions for python. My C++ code relies on STLPort 5.1.0. I've compiled boost.python with stdlib=stlport. This occurs in my compiler which is Microsoft Visual Studio 2005. But I keep getting the following linking error when I attempt to compile my test project. stdafx.h contains: // STL #i...
[ "If I remember correctly, the Boost Python library requires you to build it ahead of time so that your projects that use it can link against it. Have you done this already?\n" ]
[ 0 ]
[]
[]
[ "boost", "boost_python", "c++", "python", "stlport" ]
stackoverflow_0005704260_boost_boost_python_c++_python_stlport.txt
Q: Jinja2 vs. Smarty I always thought that jinja was better because of template extending.. but them I've found this: http://www.smarty.net/docs/en/advanced.features.template.inheritance.tpl Is there's any difference of smarty extendings and jinja2 extendings? A: Smarty is an overkill, in my opinion. I prefer Twig...
Jinja2 vs. Smarty
I always thought that jinja was better because of template extending.. but them I've found this: http://www.smarty.net/docs/en/advanced.features.template.inheritance.tpl Is there's any difference of smarty extendings and jinja2 extendings?
[ "Smarty is an overkill, in my opinion. I prefer Twig:\nhttp://www.twig-project.org/\nYou should give it a try if you're stuck with php. It's almost the same as jinja2. \n" ]
[ 12 ]
[]
[]
[ "jinja2", "php", "python", "smarty" ]
stackoverflow_0005708094_jinja2_php_python_smarty.txt
Q: Painless way to get C++ extensions in Python in Visual Studio 2005 I'm having some very serious compatibility issues with STLPort 5.1.0 and Boot.Python 1.46.1 in Visual Studio 2005, I was wondering if there was any other way to have Python calling C++ code. Just in case someone can help: The following code compiel...
Painless way to get C++ extensions in Python in Visual Studio 2005
I'm having some very serious compatibility issues with STLPort 5.1.0 and Boot.Python 1.46.1 in Visual Studio 2005, I was wondering if there was any other way to have Python calling C++ code. Just in case someone can help: The following code compiels and runs without issue: char const* greet() { return "h...
[ "Try using SWIG. I remember it being straight forward.\n" ]
[ 0 ]
[]
[]
[ "c++", "python", "stlport" ]
stackoverflow_0005600970_c++_python_stlport.txt
Q: Python library to display a web page on Mac Is there a Python library that will easily display a web page in a small window on Mac? I just want to display a web page when the user clicks a button, but without the user having to leave my app. A: PyQt has an integrated web browser in it. So any app you make with ...
Python library to display a web page on Mac
Is there a Python library that will easily display a web page in a small window on Mac? I just want to display a web page when the user clicks a button, but without the user having to leave my app.
[ "PyQt has an integrated web browser in it. So any app you make with PyQt can also include a browser window. PyQt is cross-platfrom so it should work on a mac as well.\n" ]
[ 3 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0005709090_macos_python.txt
Q: Python: Not finding value in list that should be there I am trying to find entries with specific zip codes in a mailing list (CSV format). I thought this should work but it never finds anything despite my knowing that the sought after zip codes are there. text = open("during1.txt","r") a = list(range(93201,93399...
Python: Not finding value in list that should be there
I am trying to find entries with specific zip codes in a mailing list (CSV format). I thought this should work but it never finds anything despite my knowing that the sought after zip codes are there. text = open("during1.txt","r") a = list(range(93201,93399)) b = list(range(93529,93535)) c = list(range(93601,93899))...
[ "Because array[6][0:5] is the string. You should convert it to the integer before looking at the KFCFzip list.\nfor line in text:\n array= line.strip().split(\",\")\n print(array[6][0:5])\n if int(array[6][0:5]) in KFCFzip:\n print(\"yes\")\n\nAnother problem with this solution is the performance. r...
[ 7, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005707875_python.txt
Q: Improving python code I am facing the following scenario : I set DEBUG=True/False and based on this I do the logging. Traditional way of doing this is if DEBUG: logger.log(whatever) Is there a better way to write this code? Using closures/lambda functions etc.. ? A: Look at the logging library's manual: htt...
Improving python code
I am facing the following scenario : I set DEBUG=True/False and based on this I do the logging. Traditional way of doing this is if DEBUG: logger.log(whatever) Is there a better way to write this code? Using closures/lambda functions etc.. ?
[ "Look at the logging library's manual: http://docs.python.org/library/logging.html\nyou can configure directly in code, or in a config file ...\ne.g. \nimport logging\nlogging.basicConfig(filename='example.log',level=logging.INFO)\nlogging.debug('This message should go to the log file')\nlogging.info('So should thi...
[ 7, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005709256_python.txt
Q: Python datetime in reverse y=(datetime.datetime.now() ).strftime("%y%m%d") gives '110418' I have data that reads '110315' and '110512', not trying to create it. How do I change '110418' into date time so I can subtract from '2011-07-15' (str) import datetime t = datetime.datetime.today() print type(t) tdate ...
Python datetime in reverse
y=(datetime.datetime.now() ).strftime("%y%m%d") gives '110418' I have data that reads '110315' and '110512', not trying to create it. How do I change '110418' into date time so I can subtract from '2011-07-15' (str) import datetime t = datetime.datetime.today() print type(t) tdate =datetime.datetime.strptime('110...
[ "You can convert any string representation into a datetime object using the strptime method.\nHere's an example converting your string above into a datetime object:\nimport datetime\n\nmy_date = datetime.datetime.strptime('2011-07-15', '%Y-%m-%d')\n\nNow you'll have a datetime object which can be subtracted against...
[ 6, 4 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0005709474_datetime_python.txt
Q: What's the difference between python shebangs with /usr/bin/env rather than hard-path? I used to use the shebang #!/usr/bin/env python When is it better to use #!/usr/bin/python What is the exact difference between them? A: #!/usr/bin/python is hardcoded to always run /usr/bin/python, while #!/usr/bin/env pyt...
What's the difference between python shebangs with /usr/bin/env rather than hard-path?
I used to use the shebang #!/usr/bin/env python When is it better to use #!/usr/bin/python What is the exact difference between them?
[ "#!/usr/bin/python is hardcoded to always run /usr/bin/python, while #!/usr/bin/env python will run whichever python would be default in your current environment (it will take in account for example $PATH, you can check which python interpreter will be used with which python). \nThe second way ( #!/usr/bin/env pyth...
[ 92 ]
[]
[]
[ "environment", "path", "python", "shebang" ]
stackoverflow_0005709616_environment_path_python_shebang.txt
Q: stepping in python-bitstring 2.2.0 Update: in python-bitstring 3.0.0 step has the conventional meaning I am using python bitstring, I have a ConstBitArray loaded from file and I would like to get a slice with a step different from 1. In a normal list I just would do: s = mylist[start:stop:step] however bitstring ...
stepping in python-bitstring 2.2.0
Update: in python-bitstring 3.0.0 step has the conventional meaning I am using python bitstring, I have a ConstBitArray loaded from file and I would like to get a slice with a step different from 1. In a normal list I just would do: s = mylist[start:stop:step] however bitstring has a strange definition for stepping, s...
[ "It's quite clear in the link you provided that they have chosen to make mylist[start:stop:step] syntactic sugar for mylist[start*step:stop*step] which unfortunately means you won't be able to use the step in the usual way\nYou could try something list this as a replacement\n[mylist[i] for i in range(start,stop,ste...
[ 1, 1 ]
[]
[]
[ "bitstring", "python", "slice" ]
stackoverflow_0005709118_bitstring_python_slice.txt
Q: Python Code Shortening I was trying to solve this problem here :- https://www.spoj.pl/problems/PHIVAL/ The questions asks you to output as many decimal digits of the golden ratio (1+sqrt(5))/2 as possible and also try to minimise the code length. This is what I have right now. Can this code be made any shorter ? ...
Python Code Shortening
I was trying to solve this problem here :- https://www.spoj.pl/problems/PHIVAL/ The questions asks you to output as many decimal digits of the golden ratio (1+sqrt(5))/2 as possible and also try to minimise the code length. This is what I have right now. Can this code be made any shorter ? from decimal import * getcon...
[ "You can take out the space before the asterisk.\nUpdate:\nYou added the part about insignificant whitespace, so I started thinking about a different approach. If whitespace isn't counted, you may be able to do something like this\nprint\"1.\"+`map(len,\"\"\" \n\n\n\n\n\n\n\n\n \"\"\".split(\"\\n\"))`[1...
[ 3, 1, 0, 0 ]
[]
[]
[ "code_golf", "code_snippets", "python" ]
stackoverflow_0005705419_code_golf_code_snippets_python.txt
Q: Why did I need to specify a specific class to import in python? I just upgraded to Python 2.7.1 (on Mac) so I could use OrderedDicts. After trying to run the following script: import collections test = OrderedDict() I got: NameError: name 'OrderedDict' is not defined I fixed it with: from collections import Ord...
Why did I need to specify a specific class to import in python?
I just upgraded to Python 2.7.1 (on Mac) so I could use OrderedDicts. After trying to run the following script: import collections test = OrderedDict() I got: NameError: name 'OrderedDict' is not defined I fixed it with: from collections import OrderedDict ...but I want to know why I needed to do that? Why didn't t...
[ "import collections\n\nimports the collections module into the current namespace, so you could work with this import like this:\nimport collections\norderedDict = collections.OrderedDict()\n\nHowever, if you only need a specific function (and not the entire library), you could do this:\nfrom collections import Orde...
[ 29, 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005710029_python.txt
Q: sales tax python They question is, Using a function give one instruction below that adds the sales tax of three items, item1, item2 and item3, and assigns the result to variable total_sales_tax so far I have: item1 = input(‘Enter price of the first item:’) item2 = input(‘Enter price of the second item:’) item3 = i...
sales tax python
They question is, Using a function give one instruction below that adds the sales tax of three items, item1, item2 and item3, and assigns the result to variable total_sales_tax so far I have: item1 = input(‘Enter price of the first item:’) item2 = input(‘Enter price of the second item:’) item3 = input(‘Enter price of t...
[ "It looks like you're using smart quotes (‘’) - are you writing your code in Word? Try this:\nitem1 = input('Enter price of the first item:')\nitem2 = input('Enter price of the second item:')\nitem3 = input('Enter price of the third item:')\nreturn total_sales_tax = (item1 * .06) + (item2 * .06) + (item3 * .06)\n\n...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005710042_python.txt
Q: Is there a python data structure that is: keyed, ordered, and addressable via key and order? I'm looking for a data structure that's a mix of OrderedDict but also addressable via an integer, depending on when the element was added. i.e. config_key = OrderedDict([('Version_Number', 'a'), ('Hardware_...
Is there a python data structure that is: keyed, ordered, and addressable via key and order?
I'm looking for a data structure that's a mix of OrderedDict but also addressable via an integer, depending on when the element was added. i.e. config_key = OrderedDict([('Version_Number', 'a'), ('Hardware_Config', 'b'), ('Size_Of_Data', 'c'), ('Checksum', 'd')]) That wi...
[ "If you're using Python 2.7+ then there's one built in.\nhttp://docs.python.org/library/collections.html#collections.OrderedDict\nedit: So it looks like the order of items is supported via pop operations, but you could do the equivalent of what you want via list(my_ordered_dict)[i] where i is an integer.\n# Make yo...
[ 7 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0005710266_data_structures_python.txt
Q: How to use Python slice to extract a list of positions in a string I have two strings: a='1234512345' b='abcdefghik' I would like to search string "a" for occurrences of '1' and then print the positions of "b" that correspond to that index, i.e. 'af' I can use import re starts=[match.start() for match in re.f...
How to use Python slice to extract a list of positions in a string
I have two strings: a='1234512345' b='abcdefghik' I would like to search string "a" for occurrences of '1' and then print the positions of "b" that correspond to that index, i.e. 'af' I can use import re starts=[match.start() for match in re.finditer(re.escape('1'), a)] to find that '1' occurs in positions [0,5]....
[ "You could do something like this: \n''.join(b[x] for x in starts)\n\nBut I would recommend this instead:\na='1234512345'\nb='abcdefghik'\n\n''.join(y for (x, y) in zip(a, b) if x == '1')\n\n", ">>> a='1234512345'\n>>> b='abcdefghik'\n>>> [ j for i,j in zip(a,b) if i==\"1\" ]\n['a', 'f']\n\n", "In [11]: a='1234...
[ 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "indexing", "python", "string" ]
stackoverflow_0005710142_indexing_python_string.txt
Q: Graceful Handling of Segfault I'm writing a program in Python that uses a closed source API in Linux. The API sometimes works, and sometimes segfaults - crashing my program also. However, if the program runs for 10 seconds, its past the point where it has a chance of segfaulting and runs forever (errors only happ...
Graceful Handling of Segfault
I'm writing a program in Python that uses a closed source API in Linux. The API sometimes works, and sometimes segfaults - crashing my program also. However, if the program runs for 10 seconds, its past the point where it has a chance of segfaulting and runs forever (errors only happen in the beginning). I think I nee...
[ "Yes, such a program is perfectly possible. You just have to run these two programs in separate processes - SEGFAULT only kills the process in which it has occured.\nIf you are under Linux, you can use either bash or python if you want. Just start the script that is failling in separate process. Code in python coul...
[ 2, 1 ]
[]
[]
[ "linux", "python", "scripting", "segmentation_fault" ]
stackoverflow_0005710354_linux_python_scripting_segmentation_fault.txt