content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to retrieve result of calling a script from within a Python function? I would like to call an external script from within a function, for instance: import subprocess def call_script(script): subprocess.call(script) return answer #retrieving the result is the part I'm struggling with call_script("/user/...
How to retrieve result of calling a script from within a Python function?
I would like to call an external script from within a function, for instance: import subprocess def call_script(script): subprocess.call(script) return answer #retrieving the result is the part I'm struggling with call_script("/user/bin/calc_delta.py") The script calc_delta.py simply prints the result when it ...
[ "Instead of using subprocess.call you should use Popen and call communicate on it.\nThat will allow you to read stdout and stderr. You can also input data with stdin.\nExample from the docs http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote:\noutput = Popen([\"mycmd\", \"myarg\"], stdou...
[ 3, 2, 2 ]
[]
[]
[ "function", "python" ]
stackoverflow_0003302202_function_python.txt
Q: Create a reference to a variable (similar to PHP's "=&")? In PHP one can create a reference variable, so that two named variables can look at the same value: $a = 1; $b =& $a; echo $a; // 1 echo $b; // 1 $b = 2; echo $a; // 2 I'm looking to achieve something similar in Python. Specifically, I want to create a ref...
Create a reference to a variable (similar to PHP's "=&")?
In PHP one can create a reference variable, so that two named variables can look at the same value: $a = 1; $b =& $a; echo $a; // 1 echo $b; // 1 $b = 2; echo $a; // 2 I'm looking to achieve something similar in Python. Specifically, I want to create a reference to an object's property, eg: class Foo(object): @prope...
[ "There is some more magic that can be done in Python (not that I would recommend it and it will require digging on your part ;-), but using a closure may be sufficient for your needs:\nget_x = lambda: foo_instance.bar\nget_x() # yahoo!\n\nEdit, for those wanting \"update support\", it's all about the closures:\ndef...
[ 5, 1, 1 ]
[]
[]
[ "python", "reference" ]
stackoverflow_0003301805_python_reference.txt
Q: Locality Sensitive Hashing - finding probabilities and values for R Thanks to those who've answered my previous questions and gotten me this far. I have a table of about 25,000 vectors, each with 48 dimensions, with values ranging from 0-255. I am attempting to develop a Locality Sensitive Hash (http://en.wikipedi...
Locality Sensitive Hashing - finding probabilities and values for R
Thanks to those who've answered my previous questions and gotten me this far. I have a table of about 25,000 vectors, each with 48 dimensions, with values ranging from 0-255. I am attempting to develop a Locality Sensitive Hash (http://en.wikipedia.org/wiki/Locality-sensitive_hashing) algorithm for finding a near neigh...
[ "To those interested. I've found this document (http://web.mit.edu/andoni/www/papers/cSquared.pdf which has a very detailed, albeit complicated explanation of how to use LSH for high dimensional spaces.\n", "You might want to check out \"MetaOptimize\" -- like Stack Overflow for machine learning.\nhttp://metaopt...
[ 2, 2 ]
[]
[]
[ "nearest_neighbor", "python" ]
stackoverflow_0003267166_nearest_neighbor_python.txt
Q: What this line doing? Django-template Explain me please what this line doing: <a href="{% url video.media.views.channel_browse slug=slug%}">Archie Channel</a> Actually this: {% url video.media.views.channel_browse slug=slug%} I know that it give me URL, but what from, or how it is making this URL? does this url ...
What this line doing? Django-template
Explain me please what this line doing: <a href="{% url video.media.views.channel_browse slug=slug%}">Archie Channel</a> Actually this: {% url video.media.views.channel_browse slug=slug%} I know that it give me URL, but what from, or how it is making this URL? does this url depend from context? if it depend from cont...
[ "The url template tag uses the reverse() function to look up which url dispatch line has a name=channel_browse, including if it needs to fill in slug=whatever because that particular url dispatch line has a (?P<slug>.*) argument in it that needs to be filled in order to recreate the actual url.\nHere's a complete e...
[ 4 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003302307_django_django_templates_python.txt
Q: Splicing NumPy arrays I am having a problem splicing together two arrays. Let's assume I have two arrays: a = array([1,2,3]) b = array([4,5,6]) When I do vstack((a,b)) I get [[1,2,3],[4,5,6]] and if I do hstack((a,b)) I get: [1,2,3,4,5,6] But what I really want is: [[1,4],[2,5],[3,6]] How do I accomplish this ...
Splicing NumPy arrays
I am having a problem splicing together two arrays. Let's assume I have two arrays: a = array([1,2,3]) b = array([4,5,6]) When I do vstack((a,b)) I get [[1,2,3],[4,5,6]] and if I do hstack((a,b)) I get: [1,2,3,4,5,6] But what I really want is: [[1,4],[2,5],[3,6]] How do I accomplish this without using for loops (it...
[ "Try column_stack()?\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html\nAlternatively,\nvstack((a,b)).T\n\n", "column_stack.\n", "I forgot how to transpose NumPy arrays, but you could do:\nat = transpose(a)\nbt = transpose(b)\n\nresult = vstack((a,b))\n\n", ">>> c = [list(x) for x i...
[ 7, 4, 0, 0, 0 ]
[ "You are probably looking for shape manipulation of the array. You can look in the \"Tentative NumPy Tutorial, Array Creation\".\n" ]
[ -1 ]
[ "numpy", "python" ]
stackoverflow_0003302459_numpy_python.txt
Q: Python parsing: lxml to get just part of a tag's text I'm working in Python with HTML that looks like this. I'm parsing with lxml, but could equally happily use pyquery: <p><span class="Title">Name</span>Dave Davies</p> <p><span class="Title">Address</span>123 Greyfriars Road, London</p> Pulling out 'Name' and 'A...
Python parsing: lxml to get just part of a tag's text
I'm working in Python with HTML that looks like this. I'm parsing with lxml, but could equally happily use pyquery: <p><span class="Title">Name</span>Dave Davies</p> <p><span class="Title">Address</span>123 Greyfriars Road, London</p> Pulling out 'Name' and 'Address' is dead easy, whatever library I use, but how do I ...
[ "Another method -- using xpath:\n>>> from lxml import html\n>>> doc = html.parse( file )\n>>> doc.xpath( '//span[@class=\"Title\"][text()=\"Name\"]/../self::p/text()' )\n['Dave Davies']\n>>> doc.xpath( '//span[@class=\"Title\"][text()=\"Address\"]/../self::p/text()' )\n['123 Greyfriars Road, London']\n\n", "Each ...
[ 2, 1, 0 ]
[]
[]
[ "lxml", "python", "screen_scraping" ]
stackoverflow_0003302248_lxml_python_screen_scraping.txt
Q: Matplotlib legend help I am writing a script that plot's several points. I am also trying to create a legend from these points. To sum up my script, I am plotting several 'types' of points (call them 'a', 'b', 'c'). These points have different colors and shapes: 'a'-'go' 'b'-'rh' 'c'-'k^'. This is a shortened vers...
Matplotlib legend help
I am writing a script that plot's several points. I am also trying to create a legend from these points. To sum up my script, I am plotting several 'types' of points (call them 'a', 'b', 'c'). These points have different colors and shapes: 'a'-'go' 'b'-'rh' 'c'-'k^'. This is a shortened version of the relevant parts of...
[ "Group x and y according to the type of point.\nPlot all the points of the same type with one call to plot:\nimport pylab\nimport numpy as np\n\nlbl=np.array(('a','b','c','c','b','a','b','c','a','c'))\nx=np.random.random(10)\ny=np.random.random(10)\nfor t,color in zip(('a','b','c'),('go','rh','k^')):\n pylab.plo...
[ 2 ]
[]
[]
[ "legend", "matplotlib", "python" ]
stackoverflow_0003302586_legend_matplotlib_python.txt
Q: Python - Using cPickle to load a previously saved pickle uses too much memory? Python - Using cPickle to load a previously saved pickle uses too much memory? My pickle file is about 340MB but takes up 29% of 6gb of memory when loaded. This seems a bit too much. The pickle file is a dictionary of dictionaries. I...
Python - Using cPickle to load a previously saved pickle uses too much memory?
Python - Using cPickle to load a previously saved pickle uses too much memory? My pickle file is about 340MB but takes up 29% of 6gb of memory when loaded. This seems a bit too much. The pickle file is a dictionary of dictionaries. Is this appropriate? Code used: import cPickle as pickle file = pickle.load( file_ha...
[ "I always had memory problems with big pickels and sub dicts. So i ended up writing my objects via pprint into files and later i import that files via a a custom module loader to get the data back in the process scope. Works fine and doesn't waste memory.\n", "About 1.7GB seems a bit much, but not impossible. How...
[ 1, 0 ]
[]
[]
[ "memory_management", "pickle", "python" ]
stackoverflow_0003302632_memory_management_pickle_python.txt
Q: Adding server certificate validation to httplib.HTTPSConnection I've found that httplib.HTTPSConnection doesn't perform an automatic server certificate check. As far as I've understood the problem, I need to add that functionality manually, e.g. by subclassing this class as described here. As I'm using Python2.4.5...
Adding server certificate validation to httplib.HTTPSConnection
I've found that httplib.HTTPSConnection doesn't perform an automatic server certificate check. As far as I've understood the problem, I need to add that functionality manually, e.g. by subclassing this class as described here. As I'm using Python2.4.5 and an upgrade is not possible under the given circumstances, I cann...
[ "Try this site maybe: http://www.cs.technion.ac.il/~danken/xmlrpc-ssl.html\nIt requires SSL but doesn't require the Python SSL module. It only requires Open SSL library.\n" ]
[ 2 ]
[]
[]
[ "certificate", "httplib", "m2crypto", "python", "validation" ]
stackoverflow_0003280603_certificate_httplib_m2crypto_python_validation.txt
Q: how to loop through httprequest post variables in python How can you loop through the HttpRequest post variables in Django? I have for k,v in request.POST: print k,v which is not working properly. Thanks! A: request.POST is a dictionary-like object containing all given HTTP POST parameters. When you loop ...
how to loop through httprequest post variables in python
How can you loop through the HttpRequest post variables in Django? I have for k,v in request.POST: print k,v which is not working properly. Thanks!
[ "request.POST is a dictionary-like object containing all given HTTP POST parameters.\nWhen you loop through request.POST, you only get the keys.\nfor key in request.POST:\n print(key)\n value = request.POST[key]\n print(value)\n\nTo retrieve the keys and values together, use the items method.\nfor key, val...
[ 107 ]
[]
[]
[ "django", "httprequest", "post", "python" ]
stackoverflow_0003303336_django_httprequest_post_python.txt
Q: Pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values? I have a list of strings parsed from somewhere, in the following format: [key1, value1, key2, value2, key3, value3, ...] I'd like to create a dictionary based on this list, like so: {key1...
Pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values?
I have a list of strings parsed from somewhere, in the following format: [key1, value1, key2, value2, key3, value3, ...] I'd like to create a dictionary based on this list, like so: {key1:value1, key2:value2, key3:value3, ...} An ordinary for loop with index offsets would probably do the trick, but I wonder if there'...
[ "You can try:\ndict(zip(l[::2], l[1::2]))\n\nExplanation: we split the list into two lists, one of the even and one of the odd elements, by taking them by steps of two starting from either the first or the second element (that's the l[::2] and l[1::2]). Then we use the zip builtin to the two lists into one list of ...
[ 16, 5, 3, 2, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003303213_list_comprehension_python.txt
Q: Best way to schedule a task to run in next iteration of a Twisted reactor loop I want to schedule a task to run in the next iteration of the reactor loop. What's the best way to do it? reactor.callLater(0, ...)? A: You are correct: reactor.callLater(0, ...) A: From the docs, the correct way seems to be as you ...
Best way to schedule a task to run in next iteration of a Twisted reactor loop
I want to schedule a task to run in the next iteration of the reactor loop. What's the best way to do it? reactor.callLater(0, ...)?
[ "You are correct:\nreactor.callLater(0, ...)\n\n", "From the docs, the correct way seems to be as you said, reactor.callLater(0, ...).\n" ]
[ 1, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002321453_python_twisted.txt
Q: How do I set a default page in Pylons? I've created a new Pylons application and added a controller ("main.py") with a template ("index.mako"). Now the URL http://myserver/main/index works. How do I make this the default page, ie. the one returned when I browse to http://myserver/ ? I've already added a default ro...
How do I set a default page in Pylons?
I've created a new Pylons application and added a controller ("main.py") with a template ("index.mako"). Now the URL http://myserver/main/index works. How do I make this the default page, ie. the one returned when I browse to http://myserver/ ? I've already added a default route in routing.py: def make_map(): """Cr...
[ "Try this: map.connect('/', controller='main', action='index')\n", "You need to remove public/index.html file to make / routing rule work. Otherwise it is served directly.\n" ]
[ 3, 2 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0002406630_pylons_python_routes.txt
Q: Help with Python code I need some help understanding what's happening here. This code is from a models/log.py module in web2py, and is meant to allow for global logging. def _init_log(): logger=logging.getLogger(request.application) ... return logger logging=cache.ram('mylog',lambda:_init_log(),ti...
Help with Python code
I need some help understanding what's happening here. This code is from a models/log.py module in web2py, and is meant to allow for global logging. def _init_log(): logger=logging.getLogger(request.application) ... return logger logging=cache.ram('mylog',lambda:_init_log(),time_expire=99999999) Can so...
[ "This is not a standard web2py file. Sombody wrote it but I can see what it does:\nIn web2py a single installation can run multiple apps. Some users want different app running under the same web2py to have separate logs, therefore they need different logger objects. In web2py there are not global settings and all u...
[ 2, 1 ]
[]
[]
[ "logging", "python", "web2py" ]
stackoverflow_0003303026_logging_python_web2py.txt
Q: Writing a CherryPy Decorator for Authorization I have a cherrypy application and on some of the views I want to start only allowing certain users to view them, and sending anyone else to an authorization required page. Is there a way I can do this with a custom decorator? I think that would be the most elegant op...
Writing a CherryPy Decorator for Authorization
I have a cherrypy application and on some of the views I want to start only allowing certain users to view them, and sending anyone else to an authorization required page. Is there a way I can do this with a custom decorator? I think that would be the most elegant option. Here's a basic example of what I want to do: c...
[ "You really don't want to be writing custom decorators for CherryPy. Instead, you want to write a new Tool:\ndef myauth(allowed_groups=None, debug=False):\n # Do your auth here...\n authlib.auth(...)\ncherrypy.tools.myauth = cherrypy.Tool(\"on_start_resource\", myauth)\n\nSee http://docs.cherrypy.org/en/lates...
[ 15, 4 ]
[]
[]
[ "authorization", "cherrypy", "decorator", "permissions", "python" ]
stackoverflow_0003302844_authorization_cherrypy_decorator_permissions_python.txt
Q: Terminating android ASE shell from within the script I'm using android scripting environment with python (ASE), and I'd like to terminate the shell executing the script when the script terminates. Is there a good way to do this? I have tried executing on the last line: os.system( 'kill %d' % os.getppid() ) but to ...
Terminating android ASE shell from within the script
I'm using android scripting environment with python (ASE), and I'd like to terminate the shell executing the script when the script terminates. Is there a good way to do this? I have tried executing on the last line: os.system( 'kill %d' % os.getppid() ) but to no avail.
[ "You should use android.exit().\n", "My guess is that the above answer ought to be android.Android().exit()\n" ]
[ 1, 0 ]
[]
[]
[ "android", "ase", "python" ]
stackoverflow_0003125325_android_ase_python.txt
Q: Git "failed to push some refs to..." with custom Git bridge I have been working on setting up a git server by using Paramiko to act as an SSH bridge for Git. I am able to clone my repository without issue, and even push changes up, however I get an annoying error message. Pushing to git@localhost:/pckprojects/heyw...
Git "failed to push some refs to..." with custom Git bridge
I have been working on setting up a git server by using Paramiko to act as an SSH bridge for Git. I am able to clone my repository without issue, and even push changes up, however I get an annoying error message. Pushing to git@localhost:/pckprojects/heyworld Counting objects: 5, done. Delta compression using up to 2 t...
[ "As you probably know, this could be a bunch of issues!\n\nMy initial guess is that some permissions are not correct on the server and thus could not update some non-critical information\nCould also some other issues as well...\n\nCouple quick questions/suggestions:\n\nCan you run the command manually successfully?...
[ 0, 0 ]
[]
[]
[ "git", "paramiko", "python" ]
stackoverflow_0003262161_git_paramiko_python.txt
Q: django application configuration I'm dying to get started Django but I'm really struggling with the initial setup. I have Python/MySql/Apache2.2/mod_python installed. Now I'm trying to create a proper directory structure and then update Django and Apache settings.py/httpd docs respectively. Specifically the locati...
django application configuration
I'm dying to get started Django but I'm really struggling with the initial setup. I have Python/MySql/Apache2.2/mod_python installed. Now I'm trying to create a proper directory structure and then update Django and Apache settings.py/httpd docs respectively. Specifically the location tag in the latter. Django and Pytho...
[ "Don't use Apache for development, that'll make you tear your hair out restarting Apache every fifteen seconds (EDIT: or you could just use PythonDebug On).\nThis technique is how to get your media (stylesheets, etc) loading via the development server. If you used that exact snippet, you'd need to set MEDIA_URL to...
[ 1, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000464010_django_python.txt
Q: How to stop a python subprocess which is running unit tests right away? Terminate and kill not working I have a Tkinter GUI running two threads, the main tread for the GUI and a worker thread. The worker thread creates a subprocess using the following code: myProcess = subprocess.Popen(['python', '-u', 'runTests.p...
How to stop a python subprocess which is running unit tests right away? Terminate and kill not working
I have a Tkinter GUI running two threads, the main tread for the GUI and a worker thread. The worker thread creates a subprocess using the following code: myProcess = subprocess.Popen(['python', '-u', 'runTests.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ...
[ "The Python documentation [ http://docs.python.org/library/signal.html ] says:\n\n\nAlthough Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the “atomic” instructions of the Python interpreter. This means that signals arriving during long calculat...
[ 2 ]
[]
[]
[ "execfile", "python", "subprocess", "terminate" ]
stackoverflow_0003302910_execfile_python_subprocess_terminate.txt
Q: how do I run a python script that requires pyparsing? I got a python file which using something called pyparsing but when I run it It showed an error that pyparsing is required can any one pls tel me what to do not that I am a dump in that thing called pything I need to run that script only :)thanks A: If pypar...
how do I run a python script that requires pyparsing?
I got a python file which using something called pyparsing but when I run it It showed an error that pyparsing is required can any one pls tel me what to do not that I am a dump in that thing called pything I need to run that script only :)thanks
[ "If pyparsing is required, and you haven't got it, you need to install it. See https://pypi.org/project/pyparsing/ and/or https://github.com/pyparsing/pyparsing for instructions.\n" ]
[ 3 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0003304855_pyparsing_python.txt
Q: XML parsing gives me empty values Having trouble getting this to work. What's strange is that I have 10 bookmarks in Delicious and it prints out 10 blank strings so it must be close to working. import urllib from xml.dom.minidom import parse FEED = 'http://feeds.delicious.com/v2/rss/migrantgeek' dom = parse(urll...
XML parsing gives me empty values
Having trouble getting this to work. What's strange is that I have 10 bookmarks in Delicious and it prints out 10 blank strings so it must be close to working. import urllib from xml.dom.minidom import parse FEED = 'http://feeds.delicious.com/v2/rss/migrantgeek' dom = parse(urllib.urlopen(FEED)) for item in dom.getE...
[ "Title isn't an attribute, it's another tag within item.\n" ]
[ 3 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0003305323_minidom_python_xml.txt
Q: How to link as .so instead of .dylib on OSX 10.6 using qmake I am trying to use SWIG to wrap some C++ code for the use with Python. As described here it seems to be necessary to link my C++ code against an .so file, not a .dylib file. The thread suggests to use libtool in combination with the -module flag to link,...
How to link as .so instead of .dylib on OSX 10.6 using qmake
I am trying to use SWIG to wrap some C++ code for the use with Python. As described here it seems to be necessary to link my C++ code against an .so file, not a .dylib file. The thread suggests to use libtool in combination with the -module flag to link, but I am using qmake and need more precise instructions on how I ...
[ "I think you might have two issues. \nTo get the output file to be a .so file, I set the compile option -o mylib.so and that forced gcc to name the file correctly.\nThe other issue I think you might have is that on the Mac, linking against the python lib is not the same as on a Linux machine. What I found that was ...
[ 0 ]
[]
[]
[ "dylib", "python", "qmake", "shared_libraries", "swig" ]
stackoverflow_0002601965_dylib_python_qmake_shared_libraries_swig.txt
Q: Cannot make cProfile work in IPython I'm missing something very basic. class C: def __init__(self): self.N = 100 pass def f(self, param): print 'C.f -- param' for k in xrange(param): for i in xrange(self.N): for j in xrange(self.N): ...
Cannot make cProfile work in IPython
I'm missing something very basic. class C: def __init__(self): self.N = 100 pass def f(self, param): print 'C.f -- param' for k in xrange(param): for i in xrange(self.N): for j in xrange(self.N): a = float(i)/(1+float(j)) + float(...
[ "While inside IPython, you can use the %prun magic function:\nIn [9]: %prun c.f(3)\nC.f -- param\n 3 function calls in 0.066 CPU seconds\n\n Ordered by: internal time\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.066 0.066 0.066 0.066 <string>:6(f)\n ...
[ 26, 16, 3 ]
[]
[]
[ "ipython", "profiler", "profiling", "python" ]
stackoverflow_0001819448_ipython_profiler_profiling_python.txt
Q: How do I get Python's Mechanize to POST an ajax request? The site I'm trying to spider is using the javascript: request.open("POST", url, true); To pull in extra information over ajax that I need to spider. I've tried various permutations of: r = mechanize.urlopen("https://site.tld/dir/" + url, urllib.urlencode({...
How do I get Python's Mechanize to POST an ajax request?
The site I'm trying to spider is using the javascript: request.open("POST", url, true); To pull in extra information over ajax that I need to spider. I've tried various permutations of: r = mechanize.urlopen("https://site.tld/dir/" + url, urllib.urlencode({'none' : 'none'})) to get Mechanize to get the page but it al...
[ "This was what I came up with:\nreq = mechanize.Request(\"https://www.site.com/path/\" + url, \" \")\nreq.add_header(\"User-Agent\", \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.7) Gecko/20100713 Firefox/3.6.7\")\nreq.add_header(\"Referer\", \"https://www.site.com/path\")\ncj.add_cookie_header(req)\nr...
[ 8 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003225569_mechanize_python.txt
Q: Static memory in python: do loops create new instances of variables in memory? I've been running Python scripts that make several calls to some functions, say F1(x) and F2(x), that look a bit like this: x = LoadData() for j in range(N): y = F1(x[j]) z[j] = F2(y) del y SaveData(z) Performance is a l...
Static memory in python: do loops create new instances of variables in memory?
I've been running Python scripts that make several calls to some functions, say F1(x) and F2(x), that look a bit like this: x = LoadData() for j in range(N): y = F1(x[j]) z[j] = F2(y) del y SaveData(z) Performance is a lot faster if I keep the "del y" line. But I don't understand why this is true. If I ...
[ "Without the del y you might need twice as much memory. This is because for each pass through the loop, y is bound to the previous value of F1 while the next one is calculated.\nonce F1 returns y is rebound to that new value and the old F1 result can be released.\nThis would mean that the object returned by F1 occu...
[ 17, 2, 0 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0003305870_memory_python.txt
Q: Google App engine(python) Updating a db.StringListProperty contention/concurrency issues Ive been looking at the principles of fan out of messages as described in the google IO "building scalable complex apps" In it it suggests that using a list property for say a list of receivers is a scalable solution. In this ...
Google App engine(python) Updating a db.StringListProperty contention/concurrency issues
Ive been looking at the principles of fan out of messages as described in the google IO "building scalable complex apps" In it it suggests that using a list property for say a list of receivers is a scalable solution. In this scenario how does one update the list property so that contention issues don't step in, If the...
[ "I have now found the solution for this using a fork-join-queue. Their is a post on google IO 2010 - regarding how this is done:\nlink text\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003184411_google_app_engine_python.txt
Q: How can I map non-English Windows timezone names to Olsen names in Python? If I call win32timezone.TimeZoneInfo.local().timeZoneName, it gives me the time zone name in the current locale (for example, on a Japanese machine, it returns u"東京 (標準時)"). I would like to map this name to an Olsen database timezone name f...
How can I map non-English Windows timezone names to Olsen names in Python?
If I call win32timezone.TimeZoneInfo.local().timeZoneName, it gives me the time zone name in the current locale (for example, on a Japanese machine, it returns u"東京 (標準時)"). I would like to map this name to an Olsen database timezone name for use with pytz. CLDR windowZones.xml helps me to map English names, but can't ...
[ "dict(win32timezone.TimeZoneInfo._get_indexed_time_zone_keys()) returns exactly the mapping I need from the current locale's name to the English name. The following code solves it:\n import win32timezone\n win32tz_name = win32timezone.TimeZoneInfo.local().timeZoneName\n win32timezone_to_en = dict(win32timezone.T...
[ 3 ]
[]
[]
[ "locale", "python", "pywin32", "timezone", "winapi" ]
stackoverflow_0003306787_locale_python_pywin32_timezone_winapi.txt
Q: amara and django I am trying to do webservice calls with django views using Amara library. However anytime I do import amara (by simply importing it!) and call a django view with it imported, I get such errors: Environment: Request Method: GET Request URL: http://127.0.0.1:4444/test Django Version: 1.2.1 Python V...
amara and django
I am trying to do webservice calls with django views using Amara library. However anytime I do import amara (by simply importing it!) and call a django view with it imported, I get such errors: Environment: Request Method: GET Request URL: http://127.0.0.1:4444/test Django Version: 1.2.1 Python Version: 2.6.5 Installe...
[ "Putting \"WSGIRestrictStdout Off\" to my apache fixed the issue as said in here.\n" ]
[ 2 ]
[]
[]
[ "amara", "django", "python" ]
stackoverflow_0003306760_amara_django_python.txt
Q: If x is list, why does x += "ha" work, while x = x + "ha" throws an exception? From what little I know, + op for lists only requires the 2nd operand to be iterable, which "ha" clearly is. In code: >>> x = [] >>> x += "ha" >>> x ['h', 'a'] >>> x = x + "ha" Traceback (most recent call last): File "<stdin>", line 1, ...
If x is list, why does x += "ha" work, while x = x + "ha" throws an exception?
From what little I know, + op for lists only requires the 2nd operand to be iterable, which "ha" clearly is. In code: >>> x = [] >>> x += "ha" >>> x ['h', 'a'] >>> x = x + "ha" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "str") to list
[ "Using += with a list is like calling extend, not +.\n\nYou can call extend with an iterable.\nYou can only use + with another list.\n\nI can only guess why this decision was made, but I imagine it is for performance reasons. Calling + results in a new object being created and all items being copied, whereas extend...
[ 31, 7, 5 ]
[]
[]
[ "list", "operators", "python" ]
stackoverflow_0003216706_list_operators_python.txt
Q: Django manage.py doesn't work with IPython I am on MacOSX Snow Leopard and I'm using python 2.6.5 installed with macports. I'm inside a virtualenv. I can't run python manage.py shell after installing IPython but I can run IPython standalone. I figured out that the following line is what causes the issue: (status, ...
Django manage.py doesn't work with IPython
I am on MacOSX Snow Leopard and I'm using python 2.6.5 installed with macports. I'm inside a virtualenv. I can't run python manage.py shell after installing IPython but I can run IPython standalone. I figured out that the following line is what causes the issue: (status, result) = commands.getstatusoutput("otool -L %s ...
[ "Are they the same commands? Try print commands.__file__ in each. You may find that your project has a module called \"commands\" which shadows the stdlib module.\n" ]
[ 0 ]
[]
[]
[ "django", "ipython", "python" ]
stackoverflow_0003307431_django_ipython_python.txt
Q: how to send a post request and get the response in ruby how to send a post request and get the response in ruby request is, name=$name_val URL is http://example.com/a/2 how do i do this in python or ruby? A: To do this in python: import urllib data = urllib.urlencode({ "fieldName1" : "Val1", "fieldName2" ...
how to send a post request and get the response in ruby
how to send a post request and get the response in ruby request is, name=$name_val URL is http://example.com/a/2 how do i do this in python or ruby?
[ "To do this in python:\nimport urllib\ndata = urllib.urlencode({\n \"fieldName1\" : \"Val1\", \n \"fieldName2\" : \"Val2\", \n \"fieldName3\" : \"Val3\"\n})\nf = urllib.urlopen(\"http://example.com/a/2\", data)\nhtml = f.read() # this is the response\n\n" ]
[ 1 ]
[]
[]
[ "http", "python", "ruby" ]
stackoverflow_0003307601_http_python_ruby.txt
Q: On the google app engine, how do I get rid of the 'Only ancestor queries are allowed inside transactions' error? I am having trouble with one specific query. It needs to run in a transaction, and it does, but whenever the app engine executes my query I get the following error: Only ancestor queries are allowed ...
On the google app engine, how do I get rid of the 'Only ancestor queries are allowed inside transactions' error?
I am having trouble with one specific query. It needs to run in a transaction, and it does, but whenever the app engine executes my query I get the following error: Only ancestor queries are allowed inside transactions You'll see that my query DOES have an ancestor. So what is the app engine really complaining abou...
[ "This line:\nq.ancestor = db.Key.from_path(aggrRootKind, aggrRootKeyName)\n\nshould read:\nq.ancestor(db.Key.from_path(aggrRootKind, aggrRootKeyName))\n\nancestor() is a method, and in the first snippet, you're replacing it, rather than calling it.\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "pydev", "python" ]
stackoverflow_0003305821_google_app_engine_pydev_python.txt
Q: Python converting - [] to London Excuse my total newbie question but how do I convert: [<Location: London>] or [<Location: Edinburgh>, <Location: London>] etc into: 'London' or 'Edinburgh, london' Some background info to put it in context: Models.py: class Location(models.Model): place = models.CharField(max_...
Python converting - [] to London
Excuse my total newbie question but how do I convert: [<Location: London>] or [<Location: Edinburgh>, <Location: London>] etc into: 'London' or 'Edinburgh, london' Some background info to put it in context: Models.py: class Location(models.Model): place = models.CharField(max_length=100) def __unicode__(self)...
[ "You're printing the QueryList instead of the individual elements.\nu', '.join(x.place for x in Q)\n\n", "Override the __repr__ method if you want to change the way a Django model is printed in the shell.\n", "If it's a result from a query you're printing there, try \n[x.name for x in result]\n\nif name is the ...
[ 7, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003307646_django_python.txt
Q: Improve fetch time and this function's performance I am searching the Final model (defined below) with a query which filters on its name property. This query is taking about 2200ms to execute on the development server. How can I speed it up? Here is an AppStats screenshot. I was filtering on the created field t...
Improve fetch time and this function's performance
I am searching the Final model (defined below) with a query which filters on its name property. This query is taking about 2200ms to execute on the development server. How can I speed it up? Here is an AppStats screenshot. I was filtering on the created field too, but this was taking in excess of 10000ms so I've rem...
[ "While David's suggestions are good ones, optimizing for speed on the development server is probably a bad idea. The development server's performance does not reflect that of the production server, and optimizations based on development server runtime may not fare well in production.\nIn general, you can assume tha...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "performance", "python" ]
stackoverflow_0003301607_google_app_engine_performance_python.txt
Q: Question on python xlrd How to know the total number of columns used in an excel sheet in the following link http://scienceoss.com/read-excel-files-from-python/ Thanks.. A: The Sheet class has a ncols member which indicates the number of columns A: Here are the first 6 lines in the "Quick Start" section of xlr...
Question on python xlrd
How to know the total number of columns used in an excel sheet in the following link http://scienceoss.com/read-excel-files-from-python/ Thanks..
[ "The Sheet class has a ncols member which indicates the number of columns\n", "Here are the first 6 lines in the \"Quick Start\" section of xlrd's README.html:\nimport xlrd\nbook = xlrd.open_workbook(\"myfile.xls\")\nprint \"The number of worksheets is\", book.nsheets\nprint \"Worksheet name(s):\", book.sheet_nam...
[ 8, 8 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0003307912_python_xlrd.txt
Q: Python access to object as a function (not __call__) I want to do the following: I have a container-class Container, it has attribute attr, which refers to another class OtherClass. class OtherClass: def __init__(self, value): self._value = value def default(self): retirn self._value ...
Python access to object as a function (not __call__)
I want to do the following: I have a container-class Container, it has attribute attr, which refers to another class OtherClass. class OtherClass: def __init__(self, value): self._value = value def default(self): retirn self._value def another(self): return self._value ** 2 ...
[ "Not sure if this is what you need. Seems like an odd design to me\n>>> class OtherClass(int):\n... def __init__(self, value): \n... self._value = value \n... def another(self): \n... return self._value ** 2 \n... \n>>> class Container: \n... def __init__(self, attr): \n... self....
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003308579_python.txt
Q: I need help with messaging and queuing middleware systems for extjs I developed a system that consists of software and hardware interaction. Basically its a transaction system where the transaction details are encrypted on a PCI device then returned back to my web based system where it is stored in a DB then displ...
I need help with messaging and queuing middleware systems for extjs
I developed a system that consists of software and hardware interaction. Basically its a transaction system where the transaction details are encrypted on a PCI device then returned back to my web based system where it is stored in a DB then displayed using javascript/extjs in the browser. How I do this now is the foll...
[ "I would change it this way:\n\nmake PHP block and wait until Python daemon finishes processing the transaction\nincrease the timeout in the Ext.data.Connection() so it would wait until PHP responds\nremove the Ext.MessageBox and handle possible errors in the callback handler in Ext.data.Connection()\n\nI.e. instea...
[ 0 ]
[]
[]
[ "ajax", "extjs", "javascript", "php", "python" ]
stackoverflow_0003297110_ajax_extjs_javascript_php_python.txt
Q: django: Nonelogout in admin urls After upgrading to Django 1.2 I have strange urls in my administration panel. They look like this: http://example.com/admin/Nonelogout/ or http://example.com/admin/Nonepassword_change/ What might have gone wrong during the migration and what I need to fix? I have found in django ...
django: Nonelogout in admin urls
After upgrading to Django 1.2 I have strange urls in my administration panel. They look like this: http://example.com/admin/Nonelogout/ or http://example.com/admin/Nonepassword_change/ What might have gone wrong during the migration and what I need to fix? I have found in django source, that it is caused by root_path...
[ "If you haven't found an answer for this, here is what I did... (and it is a hack, but it is the only thing that made it work).\nIn urls.py:\nadmin.site.root_path = ''\n\nBut I would be happy to see someone come out with a better solution.\n" ]
[ 1 ]
[]
[]
[ "admin", "django", "python", "url" ]
stackoverflow_0003102817_admin_django_python_url.txt
Q: calling class from an external module causes NameError, in IDLE it works fine i have the following code in a module called code_database.py class Entry(): def enter_data(self): self.title = input('enter a title: ') print('enter the code, press ctrl-d to end: ') self.code = sys.stdin.rea...
calling class from an external module causes NameError, in IDLE it works fine
i have the following code in a module called code_database.py class Entry(): def enter_data(self): self.title = input('enter a title: ') print('enter the code, press ctrl-d to end: ') self.code = sys.stdin.readlines() self.tags = input('enter tags: ') def save_data(self): ...
[ "You're using python-2.x when running your testclass.py file. Your code, however, seems to be written for python-3.x version. In python-2.x you need to use raw_input functions for the same purpose you would use input in python-3.x. You could run\n$ python --version\n\nTo find out what exactly version you're using b...
[ 3 ]
[]
[]
[ "call", "class", "nameerror", "python" ]
stackoverflow_0003309843_call_class_nameerror_python.txt
Q: Facebook Style Wall / Activity log - General design help I'm building a face-book style activity stream/wall. Using python/app engine. I have build the activity classes based on the current activity standard being used by face-book, yahoo and the likes. i have a Chanel/api system built that will create the various...
Facebook Style Wall / Activity log - General design help
I'm building a face-book style activity stream/wall. Using python/app engine. I have build the activity classes based on the current activity standard being used by face-book, yahoo and the likes. i have a Chanel/api system built that will create the various object messages that live on the wall/activity stream. Where...
[ "This is pretty much exactly what Brett Slatkin was talking about in his 2009 I/O talk. I'd highly recommend watching it for inspiration, and to see how a member of the App Engine team solves this problem.\n", "Also you can check Opensocial API for design and maybe http://github.com/sahid/gosnippets.\n" ]
[ 1, 0 ]
[]
[]
[ "facebook", "feed", "google_app_engine", "python" ]
stackoverflow_0003306545_facebook_feed_google_app_engine_python.txt
Q: Change texture on 3D object and export 2D image I would like to generate 2D images of 3D books with custom covers on demand. Ideally, I'd like to import a 3D model of a book (created by an artist), change the cover texture to the custom one, and export a bitmap image (jpeg, png, etc...). I'm fairly ignorant about ...
Change texture on 3D object and export 2D image
I would like to generate 2D images of 3D books with custom covers on demand. Ideally, I'd like to import a 3D model of a book (created by an artist), change the cover texture to the custom one, and export a bitmap image (jpeg, png, etc...). I'm fairly ignorant about 3D graphics, so I'm not sure if that's possible or fe...
[ "Sure it's possible.\nBlender would probably be overkill, but you can script blender with python, so that's one solution.\nThe latter solution is (I'm pretty sure) what most of those e-book cover generators do, which is why they always look a little off.\nThe PIL is an excellent tool for manipulating images and pix...
[ 1 ]
[]
[]
[ "3d", "python" ]
stackoverflow_0003310017_3d_python.txt
Q: python execute remote program I'm re-writing a legacy Windows application using Python and running on Linux. Initially, the new application needs to call the legacy application so that we have consistent results between customers still using the legacy application and customers using the new application. So I ha...
python execute remote program
I'm re-writing a legacy Windows application using Python and running on Linux. Initially, the new application needs to call the legacy application so that we have consistent results between customers still using the legacy application and customers using the new application. So I have a Linux box, sitting right next ...
[ "I ended up going with SSH + Twisted. On the windows machine I setup freeSSHd as a Windows service. After hacking away trying to get paramiko to work and running into tons of problems getting my public/private keys to work, I decided to try Twisted, and it only took a few minutes to get it working. So, I wrote/st...
[ 5, 4, 1, 1, 0 ]
[]
[]
[ "linux", "python", "twisted", "windows" ]
stackoverflow_0003237558_linux_python_twisted_windows.txt
Q: Using Python with WAMP I use WAMP for my PHP and MySQL development. I want to start learning Python for use in web development. Is there a way for me to use Python within WAMP? A: Short answer: yes, use MOD_WSGI (not MOD_PYTHON). Long answer: yes, what do you want to use it for? Server-side scripting? Code gener...
Using Python with WAMP
I use WAMP for my PHP and MySQL development. I want to start learning Python for use in web development. Is there a way for me to use Python within WAMP?
[ "Short answer: yes, use MOD_WSGI (not MOD_PYTHON).\nLong answer: yes, what do you want to use it for? Server-side scripting? Code generation?\n" ]
[ 4 ]
[]
[]
[ "apache", "python", "wamp" ]
stackoverflow_0003310309_apache_python_wamp.txt
Q: What is best way for interactive debug in python? I want to utilize introspection capability of python for debugging/development, but cannot find appropriate tool for this. I need to enter into shell (IPython for example) at specific position or at specific event (like exception), with locals and globals of shell ...
What is best way for interactive debug in python?
I want to utilize introspection capability of python for debugging/development, but cannot find appropriate tool for this. I need to enter into shell (IPython for example) at specific position or at specific event (like exception), with locals and globals of shell being set to the frame's ones. My own quick hack to ill...
[ "Similar to what you're already doing, there's ipdb. Effectively, it's pdb with ipython's shell (i.e. tab completion, all the various magic functions, etc).\nIt's actually doing exactly what the little code snipped you posted in your question does, but wraps it into a simple \"ipdb.set_trace()\" call.\n", "For p...
[ 3, 2, 0 ]
[]
[]
[ "debugging", "pdb", "python" ]
stackoverflow_0003309878_debugging_pdb_python.txt
Q: How do you use pip, virtualenv and Fabric to handle deployment? What are your settings, your tricks, and above all, your workflow? These tools are great but there are still no best practices attached to their usage, so I don't know what is the most efficient way to use them. Do you use pip bundles or always downl...
How do you use pip, virtualenv and Fabric to handle deployment?
What are your settings, your tricks, and above all, your workflow? These tools are great but there are still no best practices attached to their usage, so I don't know what is the most efficient way to use them. Do you use pip bundles or always download? Do you set up Apache/Cherokee/MySQL by hand or do you have a sc...
[ "\"Best practices\" are very context-dependent, so I won't claim my practices are best, just that they work for me. I work on mostly small sites, so no multiple-server deployments, CDNs etc. I do need to support Webfaction shared hosting deployment, as some clients need the cheapest hosting they can find. I do ofte...
[ 79, 9 ]
[]
[]
[ "deployment", "fabric", "pip", "python", "virtualenv" ]
stackoverflow_0002441704_deployment_fabric_pip_python_virtualenv.txt
Q: pysqlite - how to save images I need to save an image file into sqlite database in python. I could not find a solution. How can I do it? Thanks in advance. A: write - cursor.execute('insert into File (id, name, bin) values (?,?,?)', (id, name, sqlite3.Binary(file.read()))) read - file = cursor.execute('select b...
pysqlite - how to save images
I need to save an image file into sqlite database in python. I could not find a solution. How can I do it? Thanks in advance.
[ "write - cursor.execute('insert into File \n(id, name, bin) values (?,?,?)', (id, name, sqlite3.Binary(file.read())))\nread - file = cursor.execute('select bin from File where id=?', (id,)).fetchone()\nif you need to return bin data in web app - return cStringIO.StringIO(file['bin'])\n", "Do you have to store the...
[ 11, 3, 2, 0 ]
[]
[]
[ "blob", "image", "pysqlite", "python", "sqlite" ]
stackoverflow_0003309957_blob_image_pysqlite_python_sqlite.txt
Q: Where and how do I set an environmental variable using mod-wsgi and django? I'm trying to use this env variable to specify the path for my templates and it will probably be easier to do this using git or svn. A: In you app.wsgi file do: import os os.environ['MY_ENV_VARIABLE'] = 'value' # e.g. os.environ['MPLCONF...
Where and how do I set an environmental variable using mod-wsgi and django?
I'm trying to use this env variable to specify the path for my templates and it will probably be easier to do this using git or svn.
[ "In you app.wsgi file do:\nimport os\nos.environ['MY_ENV_VARIABLE'] = 'value'\n# e.g. os.environ['MPLCONFIGDIR'] = '/path/to/config/dir'\n\n", "The reference material is here. But the operative line for your project path (in case that's what you mean) is:\nsys.path.append('/path/to/project')\n\nHowever, your temp...
[ 2, 0 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0003310419_django_mod_wsgi_python.txt
Q: How to add a comma to the end of a list efficiently? I have a list of horizontal names that is too long to open in excel. It's 90,000 names long. I need to add a comma after each name to put into my program. I tried find/replace but it freezes up my computer and crashes. Is there a clever way I can get a comma at ...
How to add a comma to the end of a list efficiently?
I have a list of horizontal names that is too long to open in excel. It's 90,000 names long. I need to add a comma after each name to put into my program. I tried find/replace but it freezes up my computer and crashes. Is there a clever way I can get a comma at the end of each name? My options to work with are python a...
[ "If you actually had a Python list, say names, then ','.join(names) would make into a string with a comma between each name and the following one (if you need one at the end as well, just use + ',' to append one more comma to the result).\nEven though you say you have \"a list\" I suspect you actually have a string...
[ 5 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0003311124_excel_python.txt
Q: How to make Django work with MySQL Connector/Python? Has anyone made Django work with myconnpy? I've checked out http://github.com/rtyler/connector-django-mysql but the author said it's very outdated and not supported. If you've managed to make Django work with myconnpy, please share your experience. Thanks. A: ...
How to make Django work with MySQL Connector/Python?
Has anyone made Django work with myconnpy? I've checked out http://github.com/rtyler/connector-django-mysql but the author said it's very outdated and not supported. If you've managed to make Django work with myconnpy, please share your experience. Thanks.
[ "I needed something similar, so I forked the project you linked to and updated it to work (for small values of) with Django 1.2's newer database backend API.\nIt should be noted that my use case is very simple (read access to a single table on a single database) and I have not tested it with anything more than that...
[ 1 ]
[]
[]
[ "django", "django_database", "mysql", "mysql_connector", "python" ]
stackoverflow_0002814450_django_django_database_mysql_mysql_connector_python.txt
Q: Installing a python + django open source project on my server and making it work? I'm trying to install an open source python + django project: http://github.com/coulix/Massive-Coupon---Open-source-groupon-clone on a server to play with. I'm using mediatemple.net grid-server hosting. I uploaded the files in my htm...
Installing a python + django open source project on my server and making it work?
I'm trying to install an open source python + django project: http://github.com/coulix/Massive-Coupon---Open-source-groupon-clone on a server to play with. I'm using mediatemple.net grid-server hosting. I uploaded the files in my html folder but I can't seem to run the program. I'd love to talk this out with someone an...
[ "Did you check out/follow the directions on deploying Django?\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003311197_django_python.txt
Q: Python generator that returns the same thing forever I'm looking for a standard function that does this: def Forever(v): while True: yield v It seems so trivial I can't believe there isn't a standard version. For that matter anyone know of a good link to a list of all the standard generator functions? A: ...
Python generator that returns the same thing forever
I'm looking for a standard function that does this: def Forever(v): while True: yield v It seems so trivial I can't believe there isn't a standard version. For that matter anyone know of a good link to a list of all the standard generator functions?
[ "itertools.repeat(x[, count]) repeats x a finite number of times if told how many times, otherwise repeats forever.\nFor a general list of all of the itertools generator functions, see here:\nhttp://docs.python.org/library/itertools.html\n", "Your are looking for itertools.repeat(object[, times]):\n\nMake an iter...
[ 14, 9 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0003311266_generator_python.txt
Q: How to protect text when doing INSERT using MySQLdb This query is easy, but when the text contains some quotes it doesn't work. cursor.execute ("INSERT INTO text (text_key, language_id, text) VALUES ('%s', '%s', '%s')" % (key, language_id, text)) What is the best way to protect my text variable ? A: What you ar...
How to protect text when doing INSERT using MySQLdb
This query is easy, but when the text contains some quotes it doesn't work. cursor.execute ("INSERT INTO text (text_key, language_id, text) VALUES ('%s', '%s', '%s')" % (key, language_id, text)) What is the best way to protect my text variable ?
[ "What you are doing will lead to a SQL injection vulnerability. Pass the parametrized query as the first argument, and the sequence of values as the second argument.\n", "Always pass the parameters separately from the query:\ncursor.execute (\n \"INSERT INTO text (text_key, language_id, text) VALUES (%s, %s, %...
[ 2, 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003311417_mysql_python.txt
Q: programing pseudocode I'm trying to make the game KenKen in Python. I need some help with the pseudocode. What data types required to store and process the game information as it progresses and completes? A: By the sound of your question, babikar, you assumedly have very little knowledge of game programming in ...
programing pseudocode
I'm trying to make the game KenKen in Python. I need some help with the pseudocode. What data types required to store and process the game information as it progresses and completes?
[ "By the sound of your question, babikar, you assumedly have very little knowledge of game programming in any language? If so, I advise that you start by looking for tutorials and books to read about both game programming in Python, and in general - the theory is usually language independent. You cannot expect peopl...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003311457_python.txt
Q: Make a line into a string I got a bot from this website, and I've been having a lot of fun with it. However I wanted to add an away command. The way it's gonna work is that when someone write away [reason] then it saves the reason, and when someone else types his name, the bot sais "He is not available, he left...
Make a line into a string
I got a bot from this website, and I've been having a lot of fun with it. However I wanted to add an away command. The way it's gonna work is that when someone write away [reason] then it saves the reason, and when someone else types his name, the bot sais "He is not available, he left a note '[reason]'" or somethin...
[ "You can do what you want like this:\nline = [\n ':NickName!email@gtanet-GTMJLJRI83.nextgentel.com',\n 'PRIVMSG #mychat :away Im going',\n 'fishing.'\n]\n\naway = '\\n'.join(line[1:])\nneedle = ':away '\naway = away[away.index(needle) + len(needle):]\nprint away\n\nResult:\n\nIm going\nfishing.\n\nIf you w...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003311520_python.txt
Q: Python function based on Scrapy to crawl entirely a web site I recently discovered Scrapy which i find very efficient. However, I really don't see how to embed it in a larger project written in python. I would like to create a spider in the normal way but be able to launch it on a given url with a function start_c...
Python function based on Scrapy to crawl entirely a web site
I recently discovered Scrapy which i find very efficient. However, I really don't see how to embed it in a larger project written in python. I would like to create a spider in the normal way but be able to launch it on a given url with a function start_crawl(url) which would launch the crawling process on a given doma...
[ "Scrapy is much more complicated. It runs several processes and use multi-threating. So in fact there are no way to use it as normal python function. Of course you can import function that starts crawler and invoke it, but what then? You will have normal scrappy process, that has taken control of your program.\nPro...
[ 3 ]
[]
[]
[ "python", "scrapy", "web_crawler" ]
stackoverflow_0003302220_python_scrapy_web_crawler.txt
Q: Creating a python priority Queue I would like to build a priority queue in python in which the queue contains different dictionaries with their priority numbers. So when a "get function" is called, the dictionary with the highest priority(lowest number) will be pulled out of the queue and when "add function" is ca...
Creating a python priority Queue
I would like to build a priority queue in python in which the queue contains different dictionaries with their priority numbers. So when a "get function" is called, the dictionary with the highest priority(lowest number) will be pulled out of the queue and when "add function" is called, the new dictionary will be added...
[ "Use the heapq module in the standard library.\nYou don't specify how you wanted to associate priorities with dictionaries, but here's a simple implementation:\nimport heapq\n\nclass MyPriQueue(object):\n def __init__(self):\n self.heap = []\n\n def add(self, d, pri):\n heapq.heappush(self.heap,...
[ 6, 2, 0 ]
[]
[]
[ "priority_queue", "python", "task_queue" ]
stackoverflow_0003311480_priority_queue_python_task_queue.txt
Q: How to default to CLoader in PyYaml.load Is there any way to have the default loader for PyYaml be CLoader. So instead of having to do yaml.load(f, Loader=yaml.CLoader) It would just default to CLoader, so I could do: yaml.load(f) A: I think what you are looking for is functools.partial: import functools myloa...
How to default to CLoader in PyYaml.load
Is there any way to have the default loader for PyYaml be CLoader. So instead of having to do yaml.load(f, Loader=yaml.CLoader) It would just default to CLoader, so I could do: yaml.load(f)
[ "I think what you are looking for is functools.partial:\nimport functools\n\nmyload=functools.partial(yaml.load,Loader=yaml.CLoader)\nmyload(f)\n\n" ]
[ 1 ]
[]
[]
[ "python", "pyyaml", "yaml" ]
stackoverflow_0003311682_python_pyyaml_yaml.txt
Q: Calling method from a class in a different class in python Let's say I have this code: class class1(object): def __init__(self): #don't worry about this def parse(self, array): # do something with array class class2(object): def __init__(self): #don't worry about this d...
Calling method from a class in a different class in python
Let's say I have this code: class class1(object): def __init__(self): #don't worry about this def parse(self, array): # do something with array class class2(object): def __init__(self): #don't worry about this def parse(self, array): # do something else with array ...
[ "It sounds like you want a static method:\nclass class1(object):\n @staticmethod\n def parse(array):\n ...\n\nNote that in such cases you leave off the usually-required self parameter, because parse is not a function called on a particular instance of class1.\nOn the other hand, if you want a method wh...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0003311987_python.txt
Q: django URL reverse: When URL reversig a username it fails when username has a '.' literal in it I didn't expect this to occur [since I didn't know when django changed to allow _ and . in usernames], but when I attempt {% url feed_user entry.username %} I will get a 500 error when the username contains a '.' In thi...
django URL reverse: When URL reversig a username it fails when username has a '.' literal in it
I didn't expect this to occur [since I didn't know when django changed to allow _ and . in usernames], but when I attempt {% url feed_user entry.username %} I will get a 500 error when the username contains a '.' In this case rob.e as a username will fail. Any ideas how to deal with this?
[ "The problem will be in whatever regex you are using in your urls.py to match feed_user. Presumably you are using something like r'(?P<username>\\w+)/$', which only matches on alphanumeric characters and doesn't match on punctuation.\nInstead, use this: r'(?P<username>[\\w.]+)/$'\n" ]
[ 4 ]
[]
[]
[ "django", "python", "reverse", "url" ]
stackoverflow_0003311973_django_python_reverse_url.txt
Q: algorithms issue in uniform cost solution I am doing the unifrom cost search algorithm. I am getting my solution slightly larger than actual. The number of expanded nodes are coming larger than actual. I used this algorithm: Get the initial node and put it into the priority queue.The P.queue will itself arranges t...
algorithms issue in uniform cost solution
I am doing the unifrom cost search algorithm. I am getting my solution slightly larger than actual. The number of expanded nodes are coming larger than actual. I used this algorithm: Get the initial node and put it into the priority queue.The P.queue will itself arranges the nodes in it according to the cost. Lower cos...
[ "It seems that you're implementing a Dijkstra with priority queue. But since the costs are uniform, BFS would be enough. \n" ]
[ 2 ]
[]
[]
[ "algorithm", "python", "search", "uniform" ]
stackoverflow_0003305713_algorithm_python_search_uniform.txt
Q: Python and Zope: Module will import in python but not in zope I have installed the Image module http://www.pythonware.com/products/pil/. I then try and import it in the python interpreter and successfully so: >>> import Image >>> But when I try to import the module in Zope via DTML page: DTML page looks like: <d...
Python and Zope: Module will import in python but not in zope
I have installed the Image module http://www.pythonware.com/products/pil/. I then try and import it in the python interpreter and successfully so: >>> import Image >>> But when I try to import the module in Zope via DTML page: DTML page looks like: <dtml-var import_image> Which calls this script: def import_image(se...
[ "Try:\nimport PIL.Image\n\nrather than:\nimport Image\n\nZope has an Image module and you could be encountering a namespace clash.\n", "You can’t just import any module in zope python script. Zope has some security restrictions. In your case you need create external method in %zope-instance%/Extensions\n\nOR mayb...
[ 2, 1 ]
[]
[]
[ "python", "zope" ]
stackoverflow_0003303333_python_zope.txt
Q: Why does an apostrophe in a python docstring break emacs syntax highlighting? Running GNU Emacs 22.2.1 on Ubuntu 9.04. When editing python code in emacs, if a docstring contains an apostrophe, emacs highlights all following code as a comment, until another apostrophe is used. Really annoying! In other words, if I ...
Why does an apostrophe in a python docstring break emacs syntax highlighting?
Running GNU Emacs 22.2.1 on Ubuntu 9.04. When editing python code in emacs, if a docstring contains an apostrophe, emacs highlights all following code as a comment, until another apostrophe is used. Really annoying! In other words, if I have a docstring like this: ''' This docstring has an apostrophe ' ''' Then all fo...
[ "This appears to work correctly in GNU Emacs 23.2.1. If it's not practical to upgrade, you might be able to copy python.el out of the Emacs 23 source code, or perhaps just the relevant pieces of it (python-quote-syntax, python-font-lock-syntactic-keywords, and the code that uses the latter, I think - I'm not much ...
[ 7, 2 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0003312436_emacs_python.txt
Q: Python: Amazon AWS interface? Googling reveals several Python interfaces to Amazon Web Services (AWS). Which are the most popular, feature-complete, etc? A: I suggest boto - It's an active project, and boto's new home is now on GitHub, so you can fork it and add/patch it as desired (not that you need to - it see...
Python: Amazon AWS interface?
Googling reveals several Python interfaces to Amazon Web Services (AWS). Which are the most popular, feature-complete, etc?
[ "I suggest boto - It's an active project, and boto's new home is now on GitHub, so you can fork it and add/patch it as desired (not that you need to - it seems very stable).\nThe author recently got a job that lets him hack on this part time for work, see And Now For Something Completely Different...\nUpdate: Meanw...
[ 20, 0 ]
[]
[]
[ "amazon_web_services", "python" ]
stackoverflow_0003216791_amazon_web_services_python.txt
Q: Creating a spider using Scrapy, Spider generation error I just downloaded Scrapy (web crawler) on Windows 32 and have just created a new project folder using the "scrapy-ctl.py startproject dmoz" command in dos. I then proceeded to created the first spider using the command: scrapy-ctl.py genspider myspider myspdi...
Creating a spider using Scrapy, Spider generation error
I just downloaded Scrapy (web crawler) on Windows 32 and have just created a new project folder using the "scrapy-ctl.py startproject dmoz" command in dos. I then proceeded to created the first spider using the command: scrapy-ctl.py genspider myspider myspdier-domain.com but it did not work and returns the error: Erro...
[ "There is a difference between PATH and PYTHON_PATH. Is your PYTHON_PATH set correctly? This path is where python looks to include packages / modules.\n", "use the scrapy-ctl.py in the project's dir. that script will know about that project's settings. the main scrapy-ctl.py doesn't have a clue about that specifi...
[ 2, 1, 0 ]
[]
[]
[ "python", "scrapy", "web_crawler" ]
stackoverflow_0002842629_python_scrapy_web_crawler.txt
Q: Django, PIP, and Virtualenv Got this django project that I assume would run on virtualenv. I installed virtualenv through pip install and created the env but when I try to feed the pip requirements file, I got this: Directory 'tagging' is not installable. File 'setup.py' not found. Storing complete log in /Users/X...
Django, PIP, and Virtualenv
Got this django project that I assume would run on virtualenv. I installed virtualenv through pip install and created the env but when I try to feed the pip requirements file, I got this: Directory 'tagging' is not installable. File 'setup.py' not found. Storing complete log in /Users/XXXX/.pip/pip.log Here's the entr...
[ "Sounds like you have a tagging/ directory in the directory from which you are running pip, and pip thinks this directory (rather than the django-tagging project on PyPI) is what you want it to install. But there's no setup.py in that directory, so pip doesn't know how to install it.\nIf the name of the project you...
[ 3, 1 ]
[]
[]
[ "django", "pip", "python", "setup_project", "virtualenv" ]
stackoverflow_0003295322_django_pip_python_setup_project_virtualenv.txt
Q: Finding blank regions in image This question is somewhat language-agnostic, but my tool of choice happens to be a numpy array. What I am doing is taking the difference of two images via PIL: img = ImageChops.difference(img1, img2) And I want to find the rectangular regions that contain changes from one picture to...
Finding blank regions in image
This question is somewhat language-agnostic, but my tool of choice happens to be a numpy array. What I am doing is taking the difference of two images via PIL: img = ImageChops.difference(img1, img2) And I want to find the rectangular regions that contain changes from one picture to another. Of course there's the buil...
[ "I believe scipy's ndimage module has everything you need... \nHere's a quick example\nimport numpy as np\nimport scipy as sp\nimport scipy.ndimage.morphology\n\n# The array you gave above\ndata = np.array( \n [\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0], \n [0, 0, 0, ...
[ 20, 1, 1 ]
[]
[]
[ "image_processing", "language_agnostic", "numpy", "python", "python_imaging_library" ]
stackoverflow_0003310681_image_processing_language_agnostic_numpy_python_python_imaging_library.txt
Q: How to Convert Extended ASCII to HTML Entity Names in Python? I'm currently doing this to replace extended-ascii characters with their HTML-entity-number equivalents: s.encode('ascii', 'xmlcharrefreplace') What I would like to do is convert to the HTML-entity-name equivalent (i.e. &copy; instead of &#169;). This...
How to Convert Extended ASCII to HTML Entity Names in Python?
I'm currently doing this to replace extended-ascii characters with their HTML-entity-number equivalents: s.encode('ascii', 'xmlcharrefreplace') What I would like to do is convert to the HTML-entity-name equivalent (i.e. &copy; instead of &#169;). This small program below shows what I'm trying to do that is failing. I...
[ "edit\nOthers have mentioned the htmlentitydefs that I never knew about. It would work with my code this way:\nfrom htmlentitydefs import entitydefs as symbols\n\nfor tag, val in symbols.iteritems():\n mystr = mystr.replace(\"&{0};\".format(tag), val)\n\nAnd that should work.\n", "Is htmlentitydefs what you wan...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "ascii", "encoding", "html", "python" ]
stackoverflow_0003312810_ascii_encoding_html_python.txt
Q: In Python, are single character strings guaranteed to be identical? I read somewhere (an SO post, I think, and probably somewhere else, too), that Python automatically references single character strings, so not only does 'a' == 'a', but 'a' is 'a'. However, I can't remember reading if this is guaranteed behavior ...
In Python, are single character strings guaranteed to be identical?
I read somewhere (an SO post, I think, and probably somewhere else, too), that Python automatically references single character strings, so not only does 'a' == 'a', but 'a' is 'a'. However, I can't remember reading if this is guaranteed behavior in Python, or is it just implementation specific? Bonus points for offici...
[ "It's implementation specific. It's difficult to tell, because (as the reference says):\n\n... for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed.\n\nThe interpreter's pretty good...
[ 14, 6 ]
[]
[]
[ "identity", "python", "string" ]
stackoverflow_0003313135_identity_python_string.txt
Q: PIL: Composite / merge two images as "Dodge" How do I use PIL to implement the equivalent of merging a layer in "dodge" mode with another layer (as done in Gimp/Photoshop)? I have my original image as well as the image I'd like to use as the layer to merge with, but I don't how to do the dodge merge/composite: fro...
PIL: Composite / merge two images as "Dodge"
How do I use PIL to implement the equivalent of merging a layer in "dodge" mode with another layer (as done in Gimp/Photoshop)? I have my original image as well as the image I'd like to use as the layer to merge with, but I don't how to do the dodge merge/composite: from PIL import Image, ImageFilter, ImageOps img = I...
[ "There might be a pure-PIL way to do this; I don't know. However, if not, here is a way you could do it with numpy:\nimport numpy as np\nimport Image\nimport ImageFilter\n\ndef dodge(front,back):\n # The formula comes from http://www.adobe.com/devnet/pdf/pdfs/blend_modes.pdf\n result=back*256.0/(256.0-front) ...
[ 7 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0003312606_image_processing_python_python_imaging_library.txt
Q: Why does my setup.py script give this error? So I have a C++ class that I made python wrappers for, and I made a setup.py file to compile it in order to use it in python. When I try to run python setup.py install I get the following error: lipo: can't create output file: build/temp.macosx-10.5-fat3-2.7/../tools/tr...
Why does my setup.py script give this error?
So I have a C++ class that I made python wrappers for, and I made a setup.py file to compile it in order to use it in python. When I try to run python setup.py install I get the following error: lipo: can't create output file: build/temp.macosx-10.5-fat3-2.7/../tools/transport-stream/TransportStreamPacket_py.o (No such...
[ "Your problem is the leading '..' in the source definitions. Distutils uses the names of the source files to generate names of temporary and output files, but doesn't normalize them. Reorganize your source tree (or move the setup.py file) so you don't need to reference '../tools/...'\n" ]
[ 3 ]
[]
[]
[ "c++", "python", "setup.py", "wrapper" ]
stackoverflow_0003313625_c++_python_setup.py_wrapper.txt
Q: twisted, unblock a threads.blockingCallFromThread when the reactor stops it seems threads.blockingCallFromThread keeps blocking even when the reactor stops. is there any way to un-block it? the deferred that it is blocking on relies on an RPC coming from the other end, and that definitely won't come in with the re...
twisted, unblock a threads.blockingCallFromThread when the reactor stops
it seems threads.blockingCallFromThread keeps blocking even when the reactor stops. is there any way to un-block it? the deferred that it is blocking on relies on an RPC coming from the other end, and that definitely won't come in with the reactor stopped.
[ "It blocks until the Deferred fires. If you want it to unblock, fire the Deferred. If you're stopping your application and stopping the reactor, then you might want to fire the Deferred before you do that. You probably want to fire it with a Failure since presumably you haven't been able to come up with a succes...
[ 1 ]
[]
[]
[ "deferred", "python", "twisted" ]
stackoverflow_0003311622_deferred_python_twisted.txt
Q: how to get final redirected url i am using google app engine for fetching the feed url bur few of the urls are 301 redirect i want to get the final url which returns me the result i am usign the universal feed reader for parsing the url is there any way or any function which can give me the final url. A: It is n...
how to get final redirected url
i am using google app engine for fetching the feed url bur few of the urls are 301 redirect i want to get the final url which returns me the result i am usign the universal feed reader for parsing the url is there any way or any function which can give me the final url.
[ "It is not possible to get the 'final' URL by parsing, in order to resolve it, you would need to at least perform an HTTP HEAD operation\n", "If you're using the urlfetch API, you can just access the final_url attribute of the response object you get from urlfetch.fetch(), assuming you set follow_redirects to Tru...
[ 3, 3, 0 ]
[]
[]
[ "feedparser", "google_app_engine", "python" ]
stackoverflow_0003309695_feedparser_google_app_engine_python.txt
Q: Class design: Last Modified My class: class ManagementReview: """Class describing ManagementReview Object. """ # Class attributes id = 0 Title = 'New Management Review Object' fiscal_year = '' region = '' review_date = '' date_completed = '' prepared_by = '' __goals = ...
Class design: Last Modified
My class: class ManagementReview: """Class describing ManagementReview Object. """ # Class attributes id = 0 Title = 'New Management Review Object' fiscal_year = '' region = '' review_date = '' date_completed = '' prepared_by = '' __goals = [] # List of <ManagementReviewGoa...
[ "To update __modified when instance attributes are modified (as in your example of self.__objectives), you could override __setattr__.\nFor example, you could add this to your class:\ndef __setattr__(self, name, value):\n # set the value like usual and then update the modified attribute too\n self.__dict__[na...
[ 5, 0, 0 ]
[]
[]
[ "class_design", "python" ]
stackoverflow_0003313978_class_design_python.txt
Q: In Python, how do I find the date of the first Monday of a given week? If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week? Many thanks A: >>> import time >>> time.asctime(time.strptime('2008 50 1', '%Y %W %w')) 'Mon Dec 15 00:00:00 200...
In Python, how do I find the date of the first Monday of a given week?
If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week? Many thanks
[ ">>> import time\n>>> time.asctime(time.strptime('2008 50 1', '%Y %W %w'))\n'Mon Dec 15 00:00:00 2008'\n\nAssuming the first day of your week is Monday, use %U instead of %W if the first day of your week is Sunday. See the documentation for strptime for details.\nUpdate: Fixed week number. The %W directive is 0-b...
[ 34, 33, 17, 8, 4, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0000396913_datetime_python.txt
Q: twisted.protocols.ftp.FTPClient and Deferreds Like most it's taking me a while to get used to using Deferreds but I'm slowly getting there. However, it's not clear to me how I can process a response and then call another FTP command using the processed response when using Twisted's FTP module. I'm using the the ex...
twisted.protocols.ftp.FTPClient and Deferreds
Like most it's taking me a while to get used to using Deferreds but I'm slowly getting there. However, it's not clear to me how I can process a response and then call another FTP command using the processed response when using Twisted's FTP module. I'm using the the example FTP code as my jumping off point. I want to c...
[ "\nShould I be passing ftpClient to\n enterDirs like fileList is passed to\n getSortedDirectories and then make my\n download requests? ... Is this the\n best approach?\n\nI do think that passing the client object explicitly as an argument is indeed the best approach -- mostly, it's spare and elegant. The main...
[ 1 ]
[]
[]
[ "deferred", "ftp", "python", "twisted" ]
stackoverflow_0003313663_deferred_ftp_python_twisted.txt
Q: Creating an instance of a class, before class is defined? Here's an example of my problem : class bar() : spam = foo() def test(self) : print self.spam.eggs pass class foo() : eggs = 50 The issue (I assume) is that I'm trying to create an instance of a class before the class is define...
Creating an instance of a class, before class is defined?
Here's an example of my problem : class bar() : spam = foo() def test(self) : print self.spam.eggs pass class foo() : eggs = 50 The issue (I assume) is that I'm trying to create an instance of a class before the class is defined. The obvious solution is to re-order my classes, but I like t...
[ "Alphabetical order is a silly idea indeed;-). Nevertheless, various possibilities include:\nclass aardvark(object):\n eggs = 50\n\nclass bar(object):\n spam = aardvark()\n def test(self) :\n print self.spam.eggs\n\nfoo = aardvark\n\nand\nclass bar(object):\n spam = None # optional!-)\n def t...
[ 7 ]
[]
[]
[ "class", "python" ]
stackoverflow_0003314528_class_python.txt
Q: How do I do this replace regex in python? Given a string of text, in Python: s = "(((((hi abc )))))))" s = "***(((((hi abc ***&&&&" How do I replace all non-alphabetic symbols that occur more than 3 times...as blank string For all the above, the result should be: hi abc A: This should work: \W{3,}: matching non...
How do I do this replace regex in python?
Given a string of text, in Python: s = "(((((hi abc )))))))" s = "***(((((hi abc ***&&&&" How do I replace all non-alphabetic symbols that occur more than 3 times...as blank string For all the above, the result should be: hi abc
[ "This should work: \\W{3,}: matching non-alphanumerics that occur 3 or more times:\n>>> s = \"***(((((hi abc ***&&&&\"\n>>> re.sub(\"\\W{3,}\", \"\", s) \n'hi abc'\n>>> s = \"(((((hi abc )))))))\"\n>>> re.sub(\"\\W{3,}\", \"\", s) \n'hi abc'\n\n", "If you want to replace any sequence of non-space non-alphamerics ...
[ 8, 4, 0 ]
[]
[]
[ "python", "regex", "string", "text" ]
stackoverflow_0003314517_python_regex_string_text.txt
Q: Destroy session in Pylons or Python I can't find information on how to destroy / kill a session within Pylons or Python on the interwebs. Thought it would be a good idea just to ask it here so that when I need to do it again a year from now I'll find this question :) So I'm looking for a PHP session_destroy() equ...
Destroy session in Pylons or Python
I can't find information on how to destroy / kill a session within Pylons or Python on the interwebs. Thought it would be a good idea just to ask it here so that when I need to do it again a year from now I'll find this question :) So I'm looking for a PHP session_destroy() equivalent for Pylons or Python. Thanks, Mag...
[ "session.delete() or session.invalidate(), depending on what you want.\nhttp://beaker.readthedocs.org/en/latest/sessions.html#deleting\n" ]
[ 4 ]
[]
[]
[ "pylons", "python", "session" ]
stackoverflow_0003308510_pylons_python_session.txt
Q: GIMP get layer position relative to the image i'm coding in python-fu and i need to get the layer position relative to the image (eg. the layer starts at x=35, y=50) Is this possible? I haven't found anything in the gimp pdb docs A: Nevermind, got it. It's layer.offsets (property) for future reference. :)
GIMP get layer position relative to the image
i'm coding in python-fu and i need to get the layer position relative to the image (eg. the layer starts at x=35, y=50) Is this possible? I haven't found anything in the gimp pdb docs
[ "Nevermind, got it. \nIt's layer.offsets (property) for future reference.\n:)\n" ]
[ 5 ]
[]
[]
[ "gimp", "python" ]
stackoverflow_0003314598_gimp_python.txt
Q: How to display choices in my form using django forms? I have a model that looks like this in my application: class Member(models.Model): name = models.CharField(max_length=200) telephone_number = models.CharField(max_length=200) email_address = models.CharField(max_length=200) membership_type = mod...
How to display choices in my form using django forms?
I have a model that looks like this in my application: class Member(models.Model): name = models.CharField(max_length=200) telephone_number = models.CharField(max_length=200) email_address = models.CharField(max_length=200) membership_type = models.CharField(max_length=1, choices=MEMBERSHIP_TYPES) m...
[ "Hmmm... You might want to read on ModelForms. \n", "Using the multiple choice field in the forms class. \n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003313919_django_django_models_python.txt
Q: How do I detect the currently focused application? I'd like to be able to track which application is currently focused on my X11 display from Python. The intent is to tie it into a timetracking tool so that I can keep track of how much time I spend being unproductive. I already found this code at http://thpinfo.co...
How do I detect the currently focused application?
I'd like to be able to track which application is currently focused on my X11 display from Python. The intent is to tie it into a timetracking tool so that I can keep track of how much time I spend being unproductive. I already found this code at http://thpinfo.com/2007/09/x11-idle-time-and-focused-window-in.html: impo...
[ "Whoo! I figured it out myself:\nimport Xlib.display\ndisplay = Xlib.display.Display()\nwindow = display.get_input_focus().focus\nwmname = window.get_wm_name()\nwmclass = window.get_wm_class()\nif wmclass is None and wmname is None:\n window = window.query_tree().parent\n wmname = window.get_wm_name()\nprint ...
[ 13, 0 ]
[]
[]
[ "python", "x11", "xlib" ]
stackoverflow_0003130912_python_x11_xlib.txt
Q: Django form don't show specific inputs Say, I've got a model like this: class Fleet(models.Model): user = models.ForeignKey(User) [...] ship1 = models.IntegerField(default=0) ship2 = models.IntegerField(default=0) ship3 = models.IntegerField(default=0) ship4 = models.IntegerField(default=0)...
Django form don't show specific inputs
Say, I've got a model like this: class Fleet(models.Model): user = models.ForeignKey(User) [...] ship1 = models.IntegerField(default=0) ship2 = models.IntegerField(default=0) ship3 = models.IntegerField(default=0) ship4 = models.IntegerField(default=0) And a form: class sendFleet(forms.Form): ...
[ "You can override the visible_fields (or hidden_fields if you really want a hidden field) methods in your form to flag them as \"invisible\" (or hidden inputs). See the docs for details.\nEDIT: Something like this should work ...\nclass sendFleet(forms.Form):\n [...]\n ship1 = forms.IntegerField(initial=0)\n...
[ 2, 1 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0003314569_django_forms_python.txt
Q: Is it possible to cut away transparent areas of Gtk-pixbuf? I am currently using rsvg in Python to separate Svggroups. I got it working so that rsvg loads a single group ... alas all the transparent space around that still remains. Is there a gtk functionallity to cut away all this space? Thanks for all the answer...
Is it possible to cut away transparent areas of Gtk-pixbuf?
I am currently using rsvg in Python to separate Svggroups. I got it working so that rsvg loads a single group ... alas all the transparent space around that still remains. Is there a gtk functionallity to cut away all this space? Thanks for all the answers!
[ "There's nothing built-in but it's fairly simple to code it (walk over pixels, find the transparent ones). Unfortunately walking over pixels in python is probably slow.\n" ]
[ 0 ]
[]
[]
[ "gtk", "python", "rsvg" ]
stackoverflow_0003270704_gtk_python_rsvg.txt
Q: Dump Contents of Python Module loaded in memory I ran the Python REPL tool and imported a Python Module. Can I can dump the contents of that Module into a file? Is this possible? Thanks in advance. A: In what format do you want to write the file? If you want exactly the same format that got imported, that's n...
Dump Contents of Python Module loaded in memory
I ran the Python REPL tool and imported a Python Module. Can I can dump the contents of that Module into a file? Is this possible? Thanks in advance.
[ "In what format do you want to write the file? If you want exactly the same format that got imported, that's not hard -- but basically it's done with a file-to-file copy. For example, if the module in question is called blah, you can do:\n>>> import shutil\n>>> shutil.copy(blah.__file__, '/tmp/blahblah.pyc')\n\n"...
[ 1, 0, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0003314259_module_python.txt
Q: Handling large dense matrices in python Basically, what is the best way to go about storing and using dense matrices in python? I have a project that generates similarity metrics between every item in an array. Each item is a custom class, and stores a pointer to the other class and a number representing it's "clo...
Handling large dense matrices in python
Basically, what is the best way to go about storing and using dense matrices in python? I have a project that generates similarity metrics between every item in an array. Each item is a custom class, and stores a pointer to the other class and a number representing it's "closeness" to that class. Right now, it works br...
[ "Well, I've found my solution:\nh5py\nIt's a library that basically presents a numpy-like interface, but uses compressed memmapped files to store arrays of arbitrary size (It's basically a wrapper for HDF5).\nPyTables is built on it, and PyTables actually led me to it. However, I do not need any of the SQL function...
[ 11, 3, 1, 0, 0 ]
[ "You can reduce the memory use by using uint8, but be careful to avoid overflow errors. A uint16 requires two bytes, so the minimal memory requirement in your example is 8000*8000*30*2 bytes = 3.84 Gb.\nIf the second example fails then you need a new machine. The memory requirement is 20000*20000*2*bytes =800 Mb. ...
[ -1 ]
[ "32_bit", "matrix", "python", "python_2.6", "windows_xp" ]
stackoverflow_0003218645_32_bit_matrix_python_python_2.6_windows_xp.txt
Q: How do I create a unix timestamp that doesn't adjust for localtime? So I have datetime objects in UTC time and I want to convert them to UTC timestamps. The problem is, time.mktime makes adjustments for localtime. So here is some code: import os import pytz import time import datetime epoch = pytz.utc.localize...
How do I create a unix timestamp that doesn't adjust for localtime?
So I have datetime objects in UTC time and I want to convert them to UTC timestamps. The problem is, time.mktime makes adjustments for localtime. So here is some code: import os import pytz import time import datetime epoch = pytz.utc.localize(datetime.datetime(1970, 1, 1)) print time.mktime(epoch.timetuple()) os....
[ "The calendar module contains calendar.timegm which solves this problem.\ncalendar.timegm(tuple)\n\n\nAn unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX enc...
[ 6 ]
[]
[]
[ "python", "pytz", "timezone" ]
stackoverflow_0003315092_python_pytz_timezone.txt
Q: Django LocaleMiddleware determines the language for me. How do I know what language it determined? I need to know what language it returns, so that I can perform my own actions. A: from django.utils import translation def myview(...): ... lang = translation.get_language() ... This will return the l...
Django LocaleMiddleware determines the language for me. How do I know what language it determined?
I need to know what language it returns, so that I can perform my own actions.
[ "from django.utils import translation\n\ndef myview(...):\n ...\n lang = translation.get_language()\n ...\n\nThis will return the language code used in the current thread, so in your case, that set by the middleware.\n", "templates with RequestContext have {{ LANGUAGE_CODE }} by default. http://docs.djan...
[ 6, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002900969_django_python.txt
Q: Problems with django deployment Im trying to deploy my django and I always get one of these erros: (they alternate as I refresh the page) The model Page has already been registered ( its from feincms, but i dont get this on my computer ) unable to open database file (the database is sqlite3 and was successfully c...
Problems with django deployment
Im trying to deploy my django and I always get one of these erros: (they alternate as I refresh the page) The model Page has already been registered ( its from feincms, but i dont get this on my computer ) unable to open database file (the database is sqlite3 and was successfully created with syncdb on the server ) A...
[ "First one is probably because on your local computer you run Django as CGI, or some other \"new request - different process\" way. So if you registering Page model in every request, it's works because you have single request. But on web server your app is loaded as FCGI or some other way like this, so only first r...
[ 2 ]
[]
[]
[ "deployment", "django", "django_database", "python" ]
stackoverflow_0003315314_deployment_django_django_database_python.txt
Q: Consecutive, conflicting regex substitutions I've tried this for the italics: r = re.compile(r"(\*[^ ]+\*)") r.sub(r'<i>"\1"</i>', foo) but it doesn't work, as I am sure anyone in the regex know will see right away. A: It would easily work, if you switch the order of substitutions. Handling the bold case first ...
Consecutive, conflicting regex substitutions
I've tried this for the italics: r = re.compile(r"(\*[^ ]+\*)") r.sub(r'<i>"\1"</i>', foo) but it doesn't work, as I am sure anyone in the regex know will see right away.
[ "It would easily work, if you switch the order of substitutions. Handling the bold case first would prevent italics taking over.\n", "Your regex and substitution need a few tweaks.\nr = re.compile(r\"(\\*[^ ]+\\*)\")\n\nYou are capturing a bit too much here -- the asterisks are preserved in \\1.\nr.sub(r'<i>\"\\1...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003314682_python_regex.txt
Q: how can I call view method in different files If I have one view which called myview1.py and I want to call a view which is located in myview2.py, how can I do that? should I import myview2.py somehow? A: I think you need to read about modules, but here's the cheat sheet: $ cat gilliam.py def spam(): print '...
how can I call view method in different files
If I have one view which called myview1.py and I want to call a view which is located in myview2.py, how can I do that? should I import myview2.py somehow?
[ "I think you need to read about modules, but here's the cheat sheet:\n$ cat gilliam.py\ndef spam():\n print 'eggs'\n$ cat jones.py\nimport gilliam\ngilliam.spam()\n$ python jones.py\neggs\n\n", "just import it\nfrom myview2 import viewname1, viewname2\n\nvalue = viewname1(params)\n\n", "You should be able to...
[ 3, 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003315362_django_python.txt
Q: Python - Referencing class name from inside class body In Python, I want to have a class attribute, a dictionary, with initialized values. I wrote this code: class MetaDataElement: (MD_INVALID, MD_CATEGORY, MD_TAG) = range(3) mapInitiator2Type = {'!':MetaDataElement.MD_CATEGORY, '...
Python - Referencing class name from inside class body
In Python, I want to have a class attribute, a dictionary, with initialized values. I wrote this code: class MetaDataElement: (MD_INVALID, MD_CATEGORY, MD_TAG) = range(3) mapInitiator2Type = {'!':MetaDataElement.MD_CATEGORY, '#':MetaDataElement.MD_TAG} But when I try to run this code,...
[ "You cannot refer to MetaDataElement while it is being constructed, since it does not yet exist. Thus,\nclass MetaDataElement:\n (MD_INVALID, MD_CATEGORY, MD_TAG) = range(3)\n mapInitiator2Type = {'!':MetaDataElement.MD_CATEGORY, \n '#':MetaDataElement.MD_TAG}\n\nfails because the ver...
[ 3, 1 ]
[]
[]
[ "class_attributes", "python", "static" ]
stackoverflow_0003315510_class_attributes_python_static.txt
Q: Optimal extraction of columns from numpy matrix Say I have a numpy matrix like so: [[ x1, x2, x3, ... ], [ y1, y2, y3, ... ], [ z1, z2, z3, ... ], [ 1, 1, 1, ... ]] From which I want to extract a list of lists like so: [[x1, y1, z1], [x2, y2, z2], [x3, y3, z3], ... ] What is the most optimal way of doing t...
Optimal extraction of columns from numpy matrix
Say I have a numpy matrix like so: [[ x1, x2, x3, ... ], [ y1, y2, y3, ... ], [ z1, z2, z3, ... ], [ 1, 1, 1, ... ]] From which I want to extract a list of lists like so: [[x1, y1, z1], [x2, y2, z2], [x3, y3, z3], ... ] What is the most optimal way of doing this? At the moment I have: tpoints = [pt[:3].tolist()...
[ "Why not remove the last row before the transpose?\nm[:3].T.tolist()\n# ^^^^^^^^^ optional\n\nMicro-benchmark shows this method is faster than yours by 61%, and if you don't convert it into a list of list it is 45 times faster, for a 100×4 matrix.\n$ python2.5 -m timeit -s 'import numpy; m = numpy.matrix([[5]*...
[ 3, 1 ]
[]
[]
[ "numpy", "optimization", "python" ]
stackoverflow_0003315894_numpy_optimization_python.txt
Q: Python Command Line "characters" returns 'characters' Thanks in advance for your help. When entering "example" at the command line, Python returns 'example'. I can not find anything on the web to explain this. All reference materials speaks to strings in the context of the print command, and I get all of the mate...
Python Command Line "characters" returns 'characters'
Thanks in advance for your help. When entering "example" at the command line, Python returns 'example'. I can not find anything on the web to explain this. All reference materials speaks to strings in the context of the print command, and I get all of the material about using double quotes, singles quotes, triple quot...
[ "In Python both 'string' and \"string\" are used to represent string literals. It's not like Java where single and double quotes represent different data types to the compiler. \nThe interpreter evaluates each line you enter and displays this value to you. In both cases the interpreter is evaluating what you ent...
[ 6, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003315346_python.txt
Q: Why would you use lambda instead of def? Is there any reason that will make you use: add2 = lambda n: n+2 instead of : def add2(n): return n+2 I tend to prefer the def way but every now and then I see the lambda way being used. EDIT : The question is not about lambda as unnamed function, but about lambda as a ...
Why would you use lambda instead of def?
Is there any reason that will make you use: add2 = lambda n: n+2 instead of : def add2(n): return n+2 I tend to prefer the def way but every now and then I see the lambda way being used. EDIT : The question is not about lambda as unnamed function, but about lambda as a named function. There is a good answer to the ...
[ "lambda is nice for small, unnamed functions but in this case it would serve no purpose other than make functionalists happy.\n", "I usually use a lambda for throwaway functions I'm going to use only in one place, for example as an argument to a function. This keeps the logic together and avoids filling the name...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0003288421_lambda_python.txt
Q: Executing a function every 1 second Possible Duplicate: Python timer countdown Hi guys, I want to know about timer in Python. Suppose i have a code snippet something like: def abc() print 'Hi' print 'Hello' print 'Hai' And i want to print it every 1 second. Max three times;ie; 1st second i need to ch...
Executing a function every 1 second
Possible Duplicate: Python timer countdown Hi guys, I want to know about timer in Python. Suppose i have a code snippet something like: def abc() print 'Hi' print 'Hello' print 'Hai' And i want to print it every 1 second. Max three times;ie; 1st second i need to check the printf, 2nd second I need to che...
[ "You can use a while loop, and the time module, with time.sleep to wait one second, and time.clock to know at what time you print your variables.\n", "You can see, if you can utilize the sched module from the standard library:\n\nThe sched module defines a class which implements a general purpose event scheduler....
[ 3, 2 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0003316240_python_timer.txt
Q: Unable to get correct link in BeautifulSoup I'm trying to parse a bit of HTML and I'd like to extract the link that matches a particular pattern. I'm using the find method with a regular expression but it doesn't get me the correct link. Here's my snippet. Could someone tell me what I'm doing wrong? from Beautiful...
Unable to get correct link in BeautifulSoup
I'm trying to parse a bit of HTML and I'd like to extract the link that matches a particular pattern. I'm using the find method with a regular expression but it doesn't get me the correct link. Here's my snippet. Could someone tell me what I'm doing wrong? from BeautifulSoup import BeautifulSoup import re html = """ <...
[ "find only returns the first <a> tag. You want findAll.\n", "Can't answer your question, but anyway your (originally) posted code has an import typo. Change\nimport BeautifulSoup\n\nto \nfrom BeautifulSoup import BeautifulSoup\n\nThen, your output (using beautifulsoup version 3.1.0.1) will be:\nhttp://www.imdb.co...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003316415_beautifulsoup_python.txt
Q: Python and/or django solution for reading log files on linux? I would like my Django application to be able to display local syslog etc files. I would like to avoid writing the logic for managing .1,.2 etc rotated files, and get an object for each log that I can retrieve a set of rows from. Is there any such pyth...
Python and/or django solution for reading log files on linux?
I would like my Django application to be able to display local syslog etc files. I would like to avoid writing the logic for managing .1,.2 etc rotated files, and get an object for each log that I can retrieve a set of rows from. Is there any such python library, or even better, any such django app? Clarification: I d...
[]
[]
[ "Python has a syslog module. You can also use SysLogHandler.\n" ]
[ -1 ]
[ "django", "logging", "logrotate", "python", "syslog" ]
stackoverflow_0003316736_django_logging_logrotate_python_syslog.txt
Q: XML Question relating to Java and Python I am trying to write an application using Python 2.7 that will allow the user to open a dialog box, pick a file, have it read into a structure of some sort (ArrayList, List etc...) open to suggestions here and then to find basic statistical measures from the data (things li...
XML Question relating to Java and Python
I am trying to write an application using Python 2.7 that will allow the user to open a dialog box, pick a file, have it read into a structure of some sort (ArrayList, List etc...) open to suggestions here and then to find basic statistical measures from the data (things like mean, standard deviation etc...) and to out...
[ "Well, you could do this in either Python or Java without too much difficulty, but I would make up your mind as to which one you want! I'll talk about Python because I much prefer it to Java, but I'm sure you can find people who will help you with Java.\nSo first, you want a file selection box with Tkinter. Well, t...
[ 1 ]
[]
[]
[ "java", "parsing", "python", "xml" ]
stackoverflow_0003316835_java_parsing_python_xml.txt
Q: Hiding a django website while development I developed a django website on my local machine and now is the time to upload it on a server. I would like that during the time i work on it, only logged in users can see it. I thought about a {% if is_logged_in %} {% else %} {% endif %} structure in my base.py template...
Hiding a django website while development
I developed a django website on my local machine and now is the time to upload it on a server. I would like that during the time i work on it, only logged in users can see it. I thought about a {% if is_logged_in %} {% else %} {% endif %} structure in my base.py template but not all my views return a Context so it do...
[ "Use django.contrib.auth.decorators.login_required. It is a decorator, that will prevent users from viewing anything, if they are not logged in. Or you can find middleware for this: http://djangosnippets.org/snippets/1179/.\nMiddleware will be better, becuase it is unobtrusive and you can remove it later.\n", "Th...
[ 4, 4, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003308379_django_python.txt
Q: Python Create Byte Array for Web Service Expecting Byte[] I'm using a SOAP based web service that expects an image element in the form of a 'ByteArray' described in their docs as being of type 'byte[]' - the client I am using is the Python based suds library. Problem is that I am not exactly sure how to represent ...
Python Create Byte Array for Web Service Expecting Byte[]
I'm using a SOAP based web service that expects an image element in the form of a 'ByteArray' described in their docs as being of type 'byte[]' - the client I am using is the Python based suds library. Problem is that I am not exactly sure how to represent the ByteArray in for this service - I presume that it should lo...
[ "I got it figured in the end - what the web service meant by a ByteArray (byte[]) looked something like:\n/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB...\n\n... aha, base 64 (not anywhere in their docs, I hasten to add)...\nso I managed to get it working by using this:\nencoded_data = base64.b64encode(open(file...
[ 2, 0 ]
[]
[]
[ "bytearray", "python" ]
stackoverflow_0003309868_bytearray_python.txt