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:
IPython in Emacs. Quick code evaluation
Update: The question still lacks a satisfactory answer.
I would like to "send" code snippets to a IPython interpreter in Emacs 23.2 (Linux). Assuming that I have already started an IPython shell in a buffer in Emacs (e.g. using Python-mode.el and IPython.el), is there a way... | IPython in Emacs. Quick code evaluation | Update: The question still lacks a satisfactory answer.
I would like to "send" code snippets to a IPython interpreter in Emacs 23.2 (Linux). Assuming that I have already started an IPython shell in a buffer in Emacs (e.g. using Python-mode.el and IPython.el), is there a way of selecting a region in a different buffer ... | [
"Are you using ipython.el?\nIt should work okay with Emacs 23.\nIf not, have a look at EmacsWiki: iPython Emacs 23.\nThere is also a section in the IPython Cookbook on Emacs (search for IPythonEmacs23; sorry am not allowed to post more than one link :(\nOnce you've started an ipython-shell (C-c !) you can execute c... | [
1,
0
] | [] | [] | [
"emacs",
"ipython",
"python",
"shell"
] | stackoverflow_0004542718_emacs_ipython_python_shell.txt |
Q:
Is there a way to do runtime inspection for django apps? (Any IDE that does this?)
I want to do runtime inspection for django apps, meaning, I want to run an app and be able to break/step through/inspect runtime variables.
Is there any IDE that support this or anyway to commandline run django to do this?
I know th... | Is there a way to do runtime inspection for django apps? (Any IDE that does this?) | I want to do runtime inspection for django apps, meaning, I want to run an app and be able to break/step through/inspect runtime variables.
Is there any IDE that support this or anyway to commandline run django to do this?
I know that the Django shell exists, however, that just sets up an environment and doesn't provid... | [
"You can do that with PyCharm from JetBrains.\n",
"Wingware's WingIDE supports live inspecting and debugging:\nhttp://wingware.com/ -> http://wingware.com/doc/howtos/django\nEdit: It seems that PyScripter has some support for debugging Django too -> http://code.google.com/p/pyscripter/\nIf you're into Eclipse, Py... | [
1,
1
] | [] | [] | [
"django",
"ide",
"python"
] | stackoverflow_0004556847_django_ide_python.txt |
Q:
Plotting graph in python
I'm new to Python am trying to plot a graph based on the pyODE tutorial found here. I'm using pylab for the plotting.
Below is the main part of the code and #added represents the code I've added in order to try and display the graph. When looking at the values themselves, y and v are the o... | Plotting graph in python | I'm new to Python am trying to plot a graph based on the pyODE tutorial found here. I'm using pylab for the plotting.
Below is the main part of the code and #added represents the code I've added in order to try and display the graph. When looking at the values themselves, y and v are the ones that change and x,z,u,w re... | [
"The trick is to accumulate all the values you want to plot first, and then just call plot once. \nyplot = 0 #added\n\n#do the simulation\ntotal_time = 0.0\ndt = 0.04\ntimes=[]\nyvals=[]\nwhile total_time<2.0:\n x,y,z = body.getPosition()\n u,v,w = body.getLinearVel()\n print \"%1.2fsec: pos=(%6.3f,%6.3f,%... | [
2
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0004555948_matplotlib_plot_python.txt |
Q:
Multiple commands within Supervisor - Python/Linux
I'm using the amazing utility supervisord
I'm happily running a few apps editing the config file as follows:
[program: Django Dev Server]
command=python /path/to/project/manage.py runserver 127.0.0.1:8000
[program: MongoDB]
command=sudo /path/to/mongod
Now prob... | Multiple commands within Supervisor - Python/Linux | I'm using the amazing utility supervisord
I'm happily running a few apps editing the config file as follows:
[program: Django Dev Server]
command=python /path/to/project/manage.py runserver 127.0.0.1:8000
[program: MongoDB]
command=sudo /path/to/mongod
Now problem is that some apps need a few commands before they s... | [
"Instead of calling manage.py, write a script (call it, say, start_manage.py) which verifies conditions, cleans folders, etc, and then calls manage.py (using subprocess.Popen). Or, of course, start_manage could be a shell script if that fits your needs better.\nThen change the config file to run\ncommand=python sta... | [
8
] | [] | [] | [
"django",
"linux",
"python",
"supervisord",
"ubuntu"
] | stackoverflow_0004556984_django_linux_python_supervisord_ubuntu.txt |
Q:
How to parse xml in Python on Google App Engine
For this following xml, how do I fetch the xml and then parse it to get out the value for <age>?
<boardgames>
<boardgame objectid="13">
<yearpublished>1995</yearpublished>
<minplayers>3</minplayers>
<maxplayers>4</maxplayers>
<playingtime>90</playingtime>
... | How to parse xml in Python on Google App Engine | For this following xml, how do I fetch the xml and then parse it to get out the value for <age>?
<boardgames>
<boardgame objectid="13">
<yearpublished>1995</yearpublished>
<minplayers>3</minplayers>
<maxplayers>4</maxplayers>
<playingtime>90</playingtime>
<age>10</age>
<name sortindex="1">Catan</name>
.... | [
"xml.findtext('age') or xml.findtext('boardgames/age') would normally get you the 10 inside <age>10</age>, but the parsing appears to fail due to invalid xml. ElementTree does a rather poor job of parsing invalid xml in my experience.\nInstead use BeautifulSoup, which handles invalid xml well.\ncontent = urllib2.ur... | [
7,
2
] | [] | [] | [
"beautifulsoup",
"elementtree",
"google_app_engine",
"python",
"xml"
] | stackoverflow_0004556924_beautifulsoup_elementtree_google_app_engine_python_xml.txt |
Q:
good idea to modify Python to accept continue statement in interactive mode?
as an alternative to using pdb, I would have a use for the Python continue statement in interactive mode, after control-C during a script invocation with python -i. that way, say at a raw_input('continue->') prompt in my script, I could b... | good idea to modify Python to accept continue statement in interactive mode? | as an alternative to using pdb, I would have a use for the Python continue statement in interactive mode, after control-C during a script invocation with python -i. that way, say at a raw_input('continue->') prompt in my script, I could break out, inspect/modify things, and go right back to the raw_input prompt (or wha... | [
"ctrl-C raised a KeyboardInterrupt exception in your script. Since you didn't catch that exception, the program terminated. Only then the interactive prompt appears.\nYou can't continue because your program is already over. The fact that you pressed Ctrl-C just raised an exception, the program didn't pause at that ... | [
3
] | [] | [] | [
"pdb",
"python"
] | stackoverflow_0004557551_pdb_python.txt |
Q:
In Python, how do I make a datetime that is 15 minutes from now? 1 hour from now?
Possible Duplicates:
Python - easy way to add N seconds to a datetime.time?
How to create a DateTime equal to 15 minutes ago?
what's the best way to do this?
A:
d1 = datetime.datetime.now() + datetime.timedelta(minutes=15)
d2 = d... | In Python, how do I make a datetime that is 15 minutes from now? 1 hour from now? |
Possible Duplicates:
Python - easy way to add N seconds to a datetime.time?
How to create a DateTime equal to 15 minutes ago?
what's the best way to do this?
| [
"d1 = datetime.datetime.now() + datetime.timedelta(minutes=15)\nd2 = datetime.datetime.now() + datetime.timedelta(hours=1)\n\n"
] | [
54
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0004557577_datetime_python.txt |
Q:
Django custom template tag which accepts a boolean parameter
According to this thread on the django-developers list, I can't pass the constant False as a parameter to a Django template tag because it will be treated as a variable name not a builtin constant.
But if I want to create a template tag takes needs a tr... | Django custom template tag which accepts a boolean parameter | According to this thread on the django-developers list, I can't pass the constant False as a parameter to a Django template tag because it will be treated as a variable name not a builtin constant.
But if I want to create a template tag takes needs a true/false parameter, what's the the recommended way to create (in P... | [
"I came up against this problem a while ago, and arrived at the conclusion that using 1 and 0 was the simplest solution.\nHowever an idea might be to add a context processor which adds True and False to the template context using respective names:\n# projectname/appname/context_processors.py\n\ndef booleans():\n ... | [
17
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004557114_django_django_templates_python.txt |
Q:
Python random sequence with seed
I'm doing this for a school project (so I can't use any advanced features) and I'm using Python 2.6.6.
I have a list of numbers from 1 to 1000 and my seed will be, lets say, 448.
How can I generate a random sequence with that seed so that the numbers in my list will be in a differe... | Python random sequence with seed | I'm doing this for a school project (so I can't use any advanced features) and I'm using Python 2.6.6.
I have a list of numbers from 1 to 1000 and my seed will be, lets say, 448.
How can I generate a random sequence with that seed so that the numbers in my list will be in a different index?
And is it possible, knowing ... | [
"import random\nSEED = 448\n\nmyList = [ 'list', 'elements', 'go', 'here' ]\nrandom.seed(SEED)\nrandom.shuffle(myList)\n\nprint myList\n\nresults in\n['here', 'go', 'list', 'elements']\n\nYour list is now pseudorandomized.\n'Pseudo' is important, because all lists having the same seed and number of items will retur... | [
49,
3
] | [] | [] | [
"python",
"random"
] | stackoverflow_0004557444_python_random.txt |
Q:
Static content from my local django server loads incredibly slowly when using an domain aliased to localhost, vs. localhost itself
I've added the domain to my /etc/hosts/ file, and my site resolves, however static content is loading painfully slow. I'm talking 30 seconds for a page that normally takes 0.8s from lo... | Static content from my local django server loads incredibly slowly when using an domain aliased to localhost, vs. localhost itself | I've added the domain to my /etc/hosts/ file, and my site resolves, however static content is loading painfully slow. I'm talking 30 seconds for a page that normally takes 0.8s from localhost. I have no idea why this is, and it's killing my workflow. I actually formatted my machine to see if that would resolve but stil... | [
"I'd test with the SimpleHTTPServer to see if the problem is related to Django or not:\npython -m SimpleHTTPServer\n\n"
] | [
1
] | [] | [] | [
"django",
"django_views",
"macos",
"python"
] | stackoverflow_0004557743_django_django_views_macos_python.txt |
Q:
How to restart a simple coin tossing game
I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice([... | How to restart a simple coin tossing game | I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" head... | [
"Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.\nNot based on your question, but how to use continue:\nwhile True: \n choice = raw_input('What do you want? ')\n if choice ... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004557308_python.txt |
Q:
Best practices in Python for handling external exceptions (do I use raise?)
I'm writing a procedure in Python which at it's fundamental level communicates with a motor controller. It is possible for the controller to throw flags indicating that an error has occurred. I'm trying to figure how to best handle these e... | Best practices in Python for handling external exceptions (do I use raise?) | I'm writing a procedure in Python which at it's fundamental level communicates with a motor controller. It is possible for the controller to throw flags indicating that an error has occurred. I'm trying to figure how to best handle these errors.
In the example below, there are three possible errors, a temperature fault... | [
"My approach, for what it's worth, would be to define a small hierarchy of exceptions, say:\nclass MotorFaultError(Exception) # top level exception\nclass MotorTempFault(MotorFaultError)\nclass MotorVoltageFault(MotorFaultError)\n# etc\n\nThen, on any error, make sure your API throws one of those. If your API, itse... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"robotics"
] | stackoverflow_0004557970_python_robotics.txt |
Q:
Having trouble running a mechanize script on Linux when it runs fine on windows
Well here is the thing, I have written a Python script that connects to my works webpage and downloads my most recent paycheck. It works great in windows but when I move this script to my server that is running Debian it fails to redir... | Having trouble running a mechanize script on Linux when it runs fine on windows | Well here is the thing, I have written a Python script that connects to my works webpage and downloads my most recent paycheck. It works great in windows but when I move this script to my server that is running Debian it fails to redirect past the initial page. Is there a difference between the platforms? Searching for... | [
"I'd suggest that before you go after the deep suspects, try clearing the obvious differences: download Python 2.7 (no need to install it) and see if the behavior matches Windows.\nHere's a 'build and run 2.7' copy-n-paste:\nwget http://python.org/ftp/python/2.7.1/Python-2.7.1.tgz\ntar -xzf Python-2.7.1.tgz\ncd Pyt... | [
0,
0
] | [] | [] | [
"authentication",
"https",
"mechanize",
"python"
] | stackoverflow_0004556781_authentication_https_mechanize_python.txt |
Q:
Python eval(compile(...), sandbox), globals go in sandbox unless in def, why?
Consider the following:
def test(s):
globals()['a'] = s
sandbox = {'test': test}
py_str = 'test("Setting A")\nglobals()["b"] = "Setting B"'
eval(compile(py_str, '<string>', 'exec'), sandbox)
'a' in sandbox # returns False, !What I ... | Python eval(compile(...), sandbox), globals go in sandbox unless in def, why? | Consider the following:
def test(s):
globals()['a'] = s
sandbox = {'test': test}
py_str = 'test("Setting A")\nglobals()["b"] = "Setting B"'
eval(compile(py_str, '<string>', 'exec'), sandbox)
'a' in sandbox # returns False, !What I dont want!
'b' in sandbox # returns True, What I want
'a' in globals() # returns Tr... | [
"When you call a function in Python, the global variables it sees are always the globals of the module it was defined in. (If this wasn't true, the function might not work -- it might actually need some global values, and you don't necessarily know which those are.) Specifying a dictionary of globals with exec or e... | [
6,
3,
2
] | [] | [] | [
"eval",
"python",
"sandbox",
"scope"
] | stackoverflow_0004558104_eval_python_sandbox_scope.txt |
Q:
How to make my python script easy portable? or how to compile into binary with all module dependencies?
Is there any way to compile python script into binary?
I have one file python script which uses a lot of modules.
What I would like is to have its copy on other machines (freebsd) but without installing all need... | How to make my python script easy portable? or how to compile into binary with all module dependencies? | Is there any way to compile python script into binary?
I have one file python script which uses a lot of modules.
What I would like is to have its copy on other machines (freebsd) but without installing all needed modules on every host.
What are possible solutions in such cases?
| [
"Programs that can do what you ask for are:\n\nPyInstaller: http://www.pyinstaller.org/ [Windows, Linux, OS X]\ncx_freeze: http://cx-freeze.sourceforge.net/ [Windows, Linux]\npy2exe: http://www.py2exe.org/ [Windows]\npy2app: http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html [os x]\n\nBut as mentioned you ... | [
19,
3,
2,
2
] | [] | [] | [
"binary",
"freebsd",
"python"
] | stackoverflow_0004556424_binary_freebsd_python.txt |
Q:
Does sleep() in python prevent access to an object's variables?
I have an object that is to perform an action, and then sleep for 1 second before performing the action again. However, the object has variables that need to be accessible at all times regardless if it is in its one second sleep period. Is when the ... | Does sleep() in python prevent access to an object's variables? | I have an object that is to perform an action, and then sleep for 1 second before performing the action again. However, the object has variables that need to be accessible at all times regardless if it is in its one second sleep period. Is when the object's execution is suspended, are its variables inaccessible?
This... | [
"time.sleep() does release the GIL, so other threads will be allowed to run.\nThe reason I give this answer instead of answering the question you've asked is that the question you've asked makes no sense. No access is ever prevented other than the ability for other threads to run.\n",
"Never touched much on pytho... | [
11,
1
] | [] | [] | [
"python",
"sleep"
] | stackoverflow_0004558856_python_sleep.txt |
Q:
which Forms libaray to use with Flask and SQLAlchemy
I am working on a web app based on Flask and SQLAlchemy. Most of forms/models are related and therefore need to use a library that's flexible enough to handle multiple forms and allows easy overriding [or creation] of default widgets.
Can someone recommend a goo... | which Forms libaray to use with Flask and SQLAlchemy | I am working on a web app based on Flask and SQLAlchemy. Most of forms/models are related and therefore need to use a library that's flexible enough to handle multiple forms and allows easy overriding [or creation] of default widgets.
Can someone recommend a good forms library (other than formalchemy). I really liked d... | [
"WTForms should suit your taste, with Flask and SQLAlchemy.\n",
"You can also use \"deform\" which currently powers repoze.BFG aka Pylons2.\nIt has some nice \"magical\" methods for creating collection of forms and adding more forms on the fly.\nIf you liked django then deform may be a good choice.\n"
] | [
12,
1
] | [] | [] | [
"flask",
"forms",
"python",
"sqlalchemy"
] | stackoverflow_0004555188_flask_forms_python_sqlalchemy.txt |
Q:
need help with moving from curl to pycurl
I'm trying to figure out how to send a pycurl "POST" to a REST interface (in this case, Neo4j).
I can do it via CURL with:
curl -HContent-Type:application/json -X POST -d '"http://localhost:7474/db/data/node/123"' http://localhost:7474/db/data/index/node/persons/name/peter... | need help with moving from curl to pycurl | I'm trying to figure out how to send a pycurl "POST" to a REST interface (in this case, Neo4j).
I can do it via CURL with:
curl -HContent-Type:application/json -X POST -d '"http://localhost:7474/db/data/node/123"' http://localhost:7474/db/data/index/node/persons/name/peter
... but I cannot figure out how to translate ... | [
"Appending these statements may help:\nc.setopt(pycurl.POST, 1)\nc.setopt(pycurl.POSTFIELDS, data)\n\nCheck out the \"HTTP POSTing\" section of the libcurl tutorial for more info.\nNote 1: If the data string must be enclosed by double quotes, then you should do: c.setopt(pycurl.POSTFIELDS, '\"%s\"' % data).\nNote 2... | [
3
] | [] | [] | [
"curl",
"pycurl",
"python"
] | stackoverflow_0004558484_curl_pycurl_python.txt |
Q:
Python: Prevent argument array being globally modified
I have a problem with python here. If I pass an array through a recursive function that adds something to the array each time it is called, the array is modified in each instance
Code:
def test(n,myList):
if n>0:
myList.append("Test")
prin... | Python: Prevent argument array being globally modified | I have a problem with python here. If I pass an array through a recursive function that adds something to the array each time it is called, the array is modified in each instance
Code:
def test(n,myList):
if n>0:
myList.append("Test")
print ( "BEFORE CALL Instance ", n, myList )
test(n-1,my... | [
"Your attempted solution does not actually copy the array. It assigns a new name to the same array. If you want to create a new array, try this:\nmy_new_list = my_list[:]\n\nThat creates a list containing a slice of the old list, where the slice starts at the beginning, and ends at the end. In other words, a per... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0002141739_python.txt |
Q:
How can I convert a float to a string, but to the sixth decimal - Python
I need to convert a float to a string, but to the sixth decimal. How would I preform a task like that without converting it into a string with an E notation?
A:
>>> "{0:.6f}".format(123455.12345678)
'123455.123457'
Note the rounding as wel... | How can I convert a float to a string, but to the sixth decimal - Python | I need to convert a float to a string, but to the sixth decimal. How would I preform a task like that without converting it into a string with an E notation?
| [
">>> \"{0:.6f}\".format(123455.12345678)\n'123455.123457'\n\nNote the rounding as well.\nSee the python docs on format string syntax and format specification mini-language.\n",
"If you're on an older version of python:\nprint \"%.6f\" % 1.23456789\n\nIf you want the \"e notation\" you can try\nprint \"%.6e\" % 1.... | [
7,
1
] | [] | [] | [
"floating_point",
"python",
"string_formatting"
] | stackoverflow_0004559475_floating_point_python_string_formatting.txt |
Q:
Python sched scheduler and reboots
I have read about python sched (task scheduler), it works like a cron.
but I have a question :
lets say if I schedule a function to run after every 2 hours and in the mean time my system gets shut down, then I again restart the system...
Does the scheduler automatically star... | Python sched scheduler and reboots | I have read about python sched (task scheduler), it works like a cron.
but I have a question :
lets say if I schedule a function to run after every 2 hours and in the mean time my system gets shut down, then I again restart the system...
Does the scheduler automatically start and run the function after 2 hours? Or... | [
"Answer to all three questions is No.\nsched is different from cron. It takes a generic timer or counter function and a delay function and lets you to schedule a function call after a particular time (an event as defined by your generic timer function).\nIt won't run after you close your program, unless you maintai... | [
1,
0
] | [] | [] | [
"python",
"scheduled_tasks"
] | stackoverflow_0004559758_python_scheduled_tasks.txt |
Q:
Why is my multithreaded python script that uses Queue , threading.Thread and subprocess so flaky
I have three shell scripts P1 , P2 and P3 which I am trying to chain. These three shell scripts need to be run in series , but at any given time multiple P1s and P2s and P3s can be running.
I need to run these on tens... | Why is my multithreaded python script that uses Queue , threading.Thread and subprocess so flaky | I have three shell scripts P1 , P2 and P3 which I am trying to chain. These three shell scripts need to be run in series , but at any given time multiple P1s and P2s and P3s can be running.
I need to run these on tens of files and quickly and hence the desire to use Threads and do things in parallel.
I am using the py... | [
"Well this is really bad:\nrunner.run()\n\nYou shouldn't ever call a thread's run method manually. You start a thread with .start(). Your code is a HUGE mess and no one here is going to wade through it to find your error.\n",
"The thread's exit condition makes them commit suicide when another thread empties their... | [
2,
1
] | [] | [] | [
"multithreading",
"python",
"subprocess"
] | stackoverflow_0004549889_multithreading_python_subprocess.txt |
Q:
How to select a MenuItem programatically
I am trying to add a global shortcut to a gtk.MenuItem which has a sub menu.
Here is my code:
import pygtk, gtk
import keybinder
dlg = gtk.Dialog('menu test')
dlg.set_size_request(200, 40)
menubar = gtk.MenuBar()
menubar.show()
menuitem = gtk.MenuItem('foo')
menuitem.show... | How to select a MenuItem programatically | I am trying to add a global shortcut to a gtk.MenuItem which has a sub menu.
Here is my code:
import pygtk, gtk
import keybinder
dlg = gtk.Dialog('menu test')
dlg.set_size_request(200, 40)
menubar = gtk.MenuBar()
menubar.show()
menuitem = gtk.MenuItem('foo')
menuitem.show()
menubar.append(menuitem)
mitem = gtk.MenuI... | [
"I figured this out. MenuShell.select_item will make the specified menuitem grab the focus, but after the selection inside the menuitem is done, it's necessary to explicitly ungrab the keyboard and mouse focus. So the code looks like:\ndef on_done(w, *args):\n gtk.gdk.keyboard_ungrab()\n gtk.gdk.pointer_ungra... | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003975225_gtk_pygtk_python.txt |
Q:
IronPython/C# Float data comparison
We have WPF based application using Prism Framework. We have embedded IronPython and using Python Unit Test framework to automate our application GUI testing.
It works very well. We have difficulties in comparing two float numbers.
Example C#
class MyClass
{
public object Va... | IronPython/C# Float data comparison | We have WPF based application using Prism Framework. We have embedded IronPython and using Python Unit Test framework to automate our application GUI testing.
It works very well. We have difficulties in comparing two float numbers.
Example C#
class MyClass
{
public object Value { get; set;}
public MyClass()
{... | [
"12.345 in C# is a double, unless you explicitly use 12.345f\n",
"IronPython float is actually a .NET double. Besides, you shouldn't be comparing floating point values for equality anyway.\n",
"I'm not familiar with Python but I'm taking a stab at an answer based on what I know about the CLR and C#.\nIn your ex... | [
3,
3,
0
] | [] | [] | [
"c#",
"ironpython",
"python",
"types"
] | stackoverflow_0004560066_c#_ironpython_python_types.txt |
Q:
Resizing gtk widgets by user
I am working on a project in python using gtk and in it the is a gtk notebook on top of a vte console. I am having trouble getting it to be resizable by the user (i.e. I want the user to be able to drag the border of the 2 up and down and resize both accordingly). Could anyone point me... | Resizing gtk widgets by user | I am working on a project in python using gtk and in it the is a gtk notebook on top of a vte console. I am having trouble getting it to be resizable by the user (i.e. I want the user to be able to drag the border of the 2 up and down and resize both accordingly). Could anyone point me in the right direction on how to ... | [
"Try this:\nvpan = gtk.VPaned()\nvpan.show()\nvpan.pack1(box1, shrink=False)\nvpan.pack2(box2, shrink=False)\n\n"
] | [
3
] | [] | [] | [
"gtk",
"pygtk",
"python",
"resize"
] | stackoverflow_0004560048_gtk_pygtk_python_resize.txt |
Q:
How can C++ object lifetimes be correctly managed in Cython?
When writing a Cython wrapper for a C++ library, I've encountered a case where it's not clear how to correctly decide when to delete certain C++ instances.
The C++ library looks something like this:
#include <stdio.h>
#include <string.h>
class Widget {
... | How can C++ object lifetimes be correctly managed in Cython? | When writing a Cython wrapper for a C++ library, I've encountered a case where it's not clear how to correctly decide when to delete certain C++ instances.
The C++ library looks something like this:
#include <stdio.h>
#include <string.h>
class Widget {
char *name;
public:
Widget() : name(strdup("a widg... | [
"cdef extern from \"somelib.h\":\n cdef cppclass Widget:\n pass\n\n cdef cppclass Sprocket:\n Sprocket(Widget*)\n\n\ncdef class PyWidget:\n cdef Widget *thisptr\n cdef set sprockets\n\n def __init__(self):\n self.thisptr = new Widget()\n self.sprockets = set()\n\n de... | [
6
] | [] | [] | [
"c++",
"cython",
"memory",
"python"
] | stackoverflow_0004501938_c++_cython_memory_python.txt |
Q:
problem with python xgoogle library. How to increase the limit of 10 results?
I use http://www.catonmat.net/blog/python-library-for-google-search/ to make
queries at Google search engine but the number of results I get is limited to
10. I used the results_per_page property and I set it to 50, 100 etc. but the
numb... | problem with python xgoogle library. How to increase the limit of 10 results? | I use http://www.catonmat.net/blog/python-library-for-google-search/ to make
queries at Google search engine but the number of results I get is limited to
10. I used the results_per_page property and I set it to 50, 100 etc. but the
number of results didn't changed. Is there a way to get more results?
Is there another ... | [
"You will need to loop through the pages: listed below is an example; remember to place a thread sleep between each call to Google: otherwise your IP will be blocked if your search is large (getting it unblocked is a real hassle and your ISP may get on your case).\nfrom xgoogle.search import GoogleSearch, SearchErr... | [
1
] | [] | [] | [
"limit",
"python",
"search_engine"
] | stackoverflow_0003830943_limit_python_search_engine.txt |
Q:
Unicode problem with pygtk
I have the following problem:
I am programming a questions/answers game for XO (OLPC machines) in python using pygame, pygtk and pgu.
When the user (a kid) writes something, the textarea (from pgu) doesn't take special characters like ñ, ó, á, etc.
I have tried a smaller program only wit... | Unicode problem with pygtk | I have the following problem:
I am programming a questions/answers game for XO (OLPC machines) in python using pygame, pygtk and pgu.
When the user (a kid) writes something, the textarea (from pgu) doesn't take special characters like ñ, ó, á, etc.
I have tried a smaller program only with pygame and pgu and it works we... | [
"when you import gtk, the default encoding will be set to utf-8.\nimport gtk, sys\nprint sys.getdefaultencoding()\n\nsince it works fine without gtk, I guess it might have something to do with the encoding.\n"
] | [
0
] | [] | [] | [
"pygame",
"pygtk",
"python",
"unicode"
] | stackoverflow_0004475682_pygame_pygtk_python_unicode.txt |
Q:
Python basic data references, list of same reference
Say I have two lists:
>>> l1=[1,2,3,4]
>>> l2=[11,12,13,14]
I can put those lists in a tuple, or dictionary, and it appears that they are all references back to the original list:
>>> t=(l1,l2)
>>> d={'l1':l1, 'l2':l2}
>>> id(l1)==id(d['l1'])==id(t[0])
True
>>>... | Python basic data references, list of same reference | Say I have two lists:
>>> l1=[1,2,3,4]
>>> l2=[11,12,13,14]
I can put those lists in a tuple, or dictionary, and it appears that they are all references back to the original list:
>>> t=(l1,l2)
>>> d={'l1':l1, 'l2':l2}
>>> id(l1)==id(d['l1'])==id(t[0])
True
>>> l1 is d['l1'] is t[0]
True
Since they are references, I ... | [
"1) Modifying a mutable object through a reference will always modify the \"original\". Honestly, this is betraying a misunderstanding of references. The newer reference is just as much the \"original\" as is any other reference. So long as both names point to the same object, modifying the object through either na... | [
6,
3,
0,
0,
0,
0
] | [] | [] | [
"data_structures",
"python",
"reference"
] | stackoverflow_0004557223_data_structures_python_reference.txt |
Q:
Slightly different execution times between python2 and python3
Lastly I wrote a simple generator of permutations in python (implementation of "plain changes" algorithm described by Knuth in "The Art... 4").
I was curious about the differences in execution time of it between python2 and python3.
Here is my function... | Slightly different execution times between python2 and python3 | Lastly I wrote a simple generator of permutations in python (implementation of "plain changes" algorithm described by Knuth in "The Art... 4").
I was curious about the differences in execution time of it between python2 and python3.
Here is my function:
def perms(s):
s = tuple(s)
N = len(s)
if N <= 1:
... | [
"Quoting:\n\nThe net result of the 3.0\n generalizations is that Python 3.0\n runs the pystone benchmark around 10%\n slower than Python 2.5. Most likely\n the biggest cause is the removal of\n special-casing for small integers.\n There’s room for improvement, but it\n will happen after 3.0 is released!\n\n>... | [
4,
2,
0
] | [] | [] | [
"execution",
"python",
"python_3.x",
"testing",
"time"
] | stackoverflow_0004558183_execution_python_python_3.x_testing_time.txt |
Q:
Could not run pexect with cygwin
Getting following errors while executing the pexpect example file at a Cygwin prompt.
Can anyone help?
Administrator@INDSQA2253 /cygdrive/c/Python26/Tools/pexpect-2.1/examples
$ python ssh_session.py
Traceback (most recent call last):
File "ssh_session.py", line 7, in <module>
... | Could not run pexect with cygwin | Getting following errors while executing the pexpect example file at a Cygwin prompt.
Can anyone help?
Administrator@INDSQA2253 /cygdrive/c/Python26/Tools/pexpect-2.1/examples
$ python ssh_session.py
Traceback (most recent call last):
File "ssh_session.py", line 7, in <module>
from pexpect import *
File "c:\Pyt... | [
"Try to install Python from cygwin. I mean cygwin's Python, that can be installed \n"
] | [
1
] | [] | [] | [
"cygwin",
"pexpect",
"python",
"windows"
] | stackoverflow_0002736137_cygwin_pexpect_python_windows.txt |
Q:
Unique names in INSTALLED_APPS Django limitation
Django docs says:
the final dotted part of the path to the module defined in INSTALLED_APPS must be unique
I'm developing a CMS based on Django. And here comes the problem: the moment will come when two 3rd-party developers create two different apps with the same ... | Unique names in INSTALLED_APPS Django limitation | Django docs says:
the final dotted part of the path to the module defined in INSTALLED_APPS must be unique
I'm developing a CMS based on Django. And here comes the problem: the moment will come when two 3rd-party developers create two different apps with the same name.
Why is it so? Is there any possibility to overco... | [
"For the time being, the only solution is to use unique application names. This is a known limitation which is currently being worked on.\nFor reference, it was one of the accepted projects during the 2010 Google Summer of Code by Arthur Koziel, and you can see some of the background and design considerations on Dj... | [
3,
2,
0
] | [] | [] | [
"django",
"django_apps",
"python"
] | stackoverflow_0004559204_django_django_apps_python.txt |
Q:
How come there is a TypeError in my Python code?
from celery.task import Task
class Decayer(Task):
def calc_decay_value(self, x):
y = (1.0/(2^x))
return y
def calc_decay_time(self, x):
y = 2^x
return y
def run(self, d, **kwargs):
#do stuff.
return 0... | How come there is a TypeError in my Python code? | from celery.task import Task
class Decayer(Task):
def calc_decay_value(self, x):
y = (1.0/(2^x))
return y
def calc_decay_time(self, x):
y = 2^x
return y
def run(self, d, **kwargs):
#do stuff.
return 0
>>> decayer = tasks.Decayer(r)
Traceback (most r... | [
"Two errors\n1) Your class doesn't have an __init__ function. Either add one, or use this instead:\ndecayer = tasks.Decayer()\n\n2) You are trying to raise an integer to the power of a float, but ^ means xor and cannot be used on floats. Use ** instead of ^:\ny = 2 ** x\n\n",
"The problem seems due to decayer = t... | [
7,
2
] | [] | [] | [
"oop",
"python",
"traceback"
] | stackoverflow_0004561726_oop_python_traceback.txt |
Q:
how to let the parser print help message rather than error and exit
I am using argparse to handle cmd args, I wanna if there is no args specified, then print the help message, but now the parse will output a error, and then exit.
my code is:
def main():
print "in abing/start/main"
parser = argparse.Argumen... | how to let the parser print help message rather than error and exit | I am using argparse to handle cmd args, I wanna if there is no args specified, then print the help message, but now the parse will output a error, and then exit.
my code is:
def main():
print "in abing/start/main"
parser = argparse.ArgumentParser(prog="abing")#, usage="%(prog)s <command> [args] [--help]")
p... | [
"A solution consists in subclassing argparse.ArgumentParser and redefining its error() method. In fact, upon error, ArgumentParser calls its error() method. The custom argument parsing can then be performed through the subclass instead of argparse.ArgumentParser. A model error() function is found in the source f... | [
3
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0004561580_argparse_python.txt |
Q:
Python, unittest.main() won't test my program
I am trying to create a very basic unittest.TestCase class, just to check I know how to do it. However, when I try to run tests, it won't do them. I wrote a very basic piece of code that should in theory run 1 test, but it keeps saying that it ran none. Here is what I ... | Python, unittest.main() won't test my program | I am trying to create a very basic unittest.TestCase class, just to check I know how to do it. However, when I try to run tests, it won't do them. I wrote a very basic piece of code that should in theory run 1 test, but it keeps saying that it ran none. Here is what I wrote:
import unittest
class c(unittest.TestCase):
... | [
"the name of your test function should start with \"test\".\nimport unittest\nclass c(unittest.TestCase): \n kv = ((1, 2), (3, 4)) \n def test_cc(self): \n for k, v in self.kv: \n res = tothis(k) \n self.assertEqual(v, res)\n\n"
] | [
6
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0004562035_python_unit_testing.txt |
Q:
Python - what's your conventions to declare your attributes in a class?
In Python, I can declare attributes all over the class. For example :
class Foo:
def __init__(self):
self.a = 0
def foo(self):
self.b = 0
It's difficult to retrieve all attributes in my class when I have a big class with a lot of att... | Python - what's your conventions to declare your attributes in a class? | In Python, I can declare attributes all over the class. For example :
class Foo:
def __init__(self):
self.a = 0
def foo(self):
self.b = 0
It's difficult to retrieve all attributes in my class when I have a big class with a lot of attributes.
Is it better to have the following code (a) or the next following co... | [
"Ideally, your constructor should not call methods: a constructor should not do real work. \nIf the number of attributes grows out of proportion, you should refactor your class, for example using Extract Class to break your class into several classes, thereby respecting the single responsibility principle.\n",
"... | [
5,
4,
0,
0
] | [] | [] | [
"coding_style",
"convention",
"python"
] | stackoverflow_0004561913_coding_style_convention_python.txt |
Q:
what framework to use for python card game?
my question is quite simple, but I can't move on until I solve it. I want to develop a card game, something like Magic the Gathering. I suppose there will be just a little of animation, but much work with images, image transformation and special rendering - some kind of ... | what framework to use for python card game? | my question is quite simple, but I can't move on until I solve it. I want to develop a card game, something like Magic the Gathering. I suppose there will be just a little of animation, but much work with images, image transformation and special rendering - some kind of things, that every unit has now attack plus 2 so ... | [
"if you want just a simple animation and want to finish your game fast. use the pyqt's scene view. refer to (Rapid GUI programming using python and pyqt) book if you want to learn more about scene view. \n",
"PySolitaire is a collection of more than 300 solitaire and Mahjongg games. So maybe if you browse around,... | [
3,
1,
0
] | [] | [] | [
"pygame",
"pyqt",
"python"
] | stackoverflow_0004530901_pygame_pyqt_python.txt |
Q:
Voodoo Code In Python
I was going through Zed Shaw's Learn Python The Hard Way and something in Chapter 15 struck me. In the extra credit exercises he asks us to delete the latter part of the code [everything after print txt.read() ] and then execute it, but the interpreter behaves as if nothing has happened. Yes,... | Voodoo Code In Python | I was going through Zed Shaw's Learn Python The Hard Way and something in Chapter 15 struck me. In the extra credit exercises he asks us to delete the latter part of the code [everything after print txt.read() ] and then execute it, but the interpreter behaves as if nothing has happened. Yes, I saved the file and when ... | [
"You are probably executing a different file then the one you are editing.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004498280_python.txt |
Q:
Django - How to deal with the paths in settings.py on collaborative projects
I have just started a feasibility study on Django for my company and I have noticed the need for absolute paths on settings.py:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
#... | Django - How to deal with the paths in settings.py on collaborative projects | I have just started a feasibility study on Django for my company and I have noticed the need for absolute paths on settings.py:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute p... | [
"import os.path\n\n#Get the absolute path of the settings.py file's directory\nPWD = os.path.dirname(os.path.realpath(__file__ )) \n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \n # \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don... | [
30,
3,
3,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004562252_django_python.txt |
Q:
does Python support constants that are enforced by the interpreter?
Possible Duplicate:
Creating constant in Python
Does Python support constants that are enforced by the interpreter? For example: integer constants. How about a programmer defined enumerated type?
A:
No. If you want something to be constant t... | does Python support constants that are enforced by the interpreter? |
Possible Duplicate:
Creating constant in Python
Does Python support constants that are enforced by the interpreter? For example: integer constants. How about a programmer defined enumerated type?
| [
"No. If you want something to be constant then just refrain from modifying it.\n"
] | [
6
] | [] | [] | [
"constants",
"python"
] | stackoverflow_0004563098_constants_python.txt |
Q:
How to retrieve information from curl using python subprocess
I'm using curl.exe on windows. But unfortunately I can't get back data from console.
python code looks like this:
tid = subprocess.Popen("C:/users/zero/Desktop/lm/curl.exe -i -H \"Cookie: login=" + userhash + "\" -F \"type=" + caid + "\" -F \"descriptio... | How to retrieve information from curl using python subprocess | I'm using curl.exe on windows. But unfortunately I can't get back data from console.
python code looks like this:
tid = subprocess.Popen("C:/users/zero/Desktop/lm/curl.exe -i -H \"Cookie: login=" + userhash + "\" -F \"type=" + caid + "\" -F \"description=\" -F \"descr=" + cleaned + "\" -F \"filetype=2\" -F \"name=" + p... | [
"Using curl via subprocess is the hard way. Spare yourself the trouble and use urllib or pycurl.\n[update]\nCurrently, the requests library is the best option for this kind of thing.\n",
"p = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]\n\nWhere command is your command. \n"
] | [
7,
1
] | [] | [] | [
"curl",
"python"
] | stackoverflow_0004563315_curl_python.txt |
Q:
django: 360 panoramic photos
I'm searching for django 360 panorama app. any suggestions? sample: http://www.0-360.com/ (on the right side).
UPDATE: Related questions
flash/JavaScript: non 360 (partial) panorama viewer
https://stackoverflow.com/questions/4850958/django-flash-with-scrollwheel-fail
A:
I am not awa... | django: 360 panoramic photos | I'm searching for django 360 panorama app. any suggestions? sample: http://www.0-360.com/ (on the right side).
UPDATE: Related questions
flash/JavaScript: non 360 (partial) panorama viewer
https://stackoverflow.com/questions/4850958/django-flash-with-scrollwheel-fail
| [
"I am not aware of existing Django plugins for viewing 360 pano images.\nThe page you link to uses the PTViewer java app by Helmut Dersch (see http://www.all-in-one.ee/~dersch/) There are a variety of other viewers available; see http://wiki.panotools.org/Panorama_Viewers#Flash_or_Shockwave_based_Viewers ; you can ... | [
5
] | [] | [] | [
"django",
"photo",
"python"
] | stackoverflow_0004562060_django_photo_python.txt |
Q:
gmail imap: get recently updated messages
is it any way (with IMAP) to retrieve only updated messages for some period of time? (or, perhaps, only their flags).
what i mean, with example:
i've checked my mbox with imaplib.IMAP4_SSL(...) at 4.00pm;
at 4.15pm i've gone to gmail web interface and marked one of my mai... | gmail imap: get recently updated messages | is it any way (with IMAP) to retrieve only updated messages for some period of time? (or, perhaps, only their flags).
what i mean, with example:
i've checked my mbox with imaplib.IMAP4_SSL(...) at 4.00pm;
at 4.15pm i've gone to gmail web interface and marked one of my mails as "read";
at 4.30pm i want to check all upd... | [
"For vanilla IMAP, you're out of luck. But if the IMAP server supports the CONDSTORE extension, you can do this. See RFC 4551 section 3.3.1 for the details. Generally, it involves keeping track of the folder's HIGHESTMODSEQ value and issuing a command like\nA001 UID FETCH 1:* (FLAGS) (CHANGEDSINCE 12345)\n\n",
... | [
3,
0
] | [] | [] | [
"imap",
"python"
] | stackoverflow_0004148349_imap_python.txt |
Q:
How do I delete an instance of a class in python (by force)?
I'm using a script to test if a website runs smoothly, basically I open the site every 20 minutes or so and check the response time and so on. Like this:
while True:
MechBrowser = mechanize.Browser()
Response = MechBrowser.open("http://example.c... | How do I delete an instance of a class in python (by force)? | I'm using a script to test if a website runs smoothly, basically I open the site every 20 minutes or so and check the response time and so on. Like this:
while True:
MechBrowser = mechanize.Browser()
Response = MechBrowser.open("http://example.com")
time.sleep(1000)
I know python will do garbage collectio... | [
"Try also closing your response object.\n",
"delthe object manually, notice that this will not delete the object but will just decrement the reference count of the object. When the reference countof an object reaches zero the garbage collector removes it from the memory.\n",
"You can also use multiprocessing to... | [
10,
6,
0
] | [] | [] | [
"mechanize",
"mechanize_python",
"python"
] | stackoverflow_0004562153_mechanize_mechanize_python_python.txt |
Q:
Cannot run any multiprocessing script in PythonWin
I have updated this question to show my problem in a multiprocessing script that doesn't run from PythonWin (by pressing F5), but runs from command prompt.
My script:-
"""
File Name: simple multiprocess example.py
Description:
A very basic multiprocessing script t... | Cannot run any multiprocessing script in PythonWin | I have updated this question to show my problem in a multiprocessing script that doesn't run from PythonWin (by pressing F5), but runs from command prompt.
My script:-
"""
File Name: simple multiprocess example.py
Description:
A very basic multiprocessing script to show the use of daemon.
There are two processes:-
p1 -... | [
"You need to save the code you want to run in a .py file. multiprocessing does not support execution of code that was merely entered in the interactive mode.\n"
] | [
4
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0004563757_multiprocessing_python.txt |
Q:
bsddb and reprepro (berkeley) database
I'm trying to read the database files created by reprepro. I don't have that much experience with bdb, so I might be confused here, but it looks like the database is layered in some way.
If I simply do btopen('path/to/packages.db', 'r'), I get the database object with content... | bsddb and reprepro (berkeley) database | I'm trying to read the database files created by reprepro. I don't have that much experience with bdb, so I might be confused here, but it looks like the database is layered in some way.
If I simply do btopen('path/to/packages.db', 'r'), I get the database object with contents like:
In [4]: packages.items()
Out[4]:
[(... | [
"And the answer seems to be that the \"nice\" version of the bsddb interface doesn't support multi btree tables inside one file. You can open such table explicitly via bsddb.db, using:\nenv = db.DBEnv()\nenv.open(None, db.DB_CREATE | db.DB_INIT_MPOOL)\ninternal_db = db.DB(env)\ninternal_db.open(\"the filename\", \"... | [
2
] | [] | [] | [
"b_tree",
"berkeley_db",
"bsddb",
"database",
"python"
] | stackoverflow_0004563284_b_tree_berkeley_db_bsddb_database_python.txt |
Q:
grouping objects to achieve a similar mean property for all groups
I have a collection of objects, each of which has a numerical 'weight'. I would like to create groups of these objects such that each group has approximately the same arithmetic mean of object weights.
The groups won't necessarily have the same num... | grouping objects to achieve a similar mean property for all groups | I have a collection of objects, each of which has a numerical 'weight'. I would like to create groups of these objects such that each group has approximately the same arithmetic mean of object weights.
The groups won't necessarily have the same number of members, but the size of groups will be within one of each other.... | [
"The program that follows is a low-cost heuristic. What it does is distribute the values among \"buckets\" placing large values along with small ones by choosing the values from one end of a sorted list on one round, and from the other end on the next. Doing the distribution in round-robin guarantees that the rules... | [
2,
1,
1
] | [] | [] | [
"combinations",
"grouping",
"mean",
"python"
] | stackoverflow_0004462531_combinations_grouping_mean_python.txt |
Q:
Django: how to publish an app
I have developed an app using Django 1.1.1 and python 2.7.1. I want to publish it on a commercial website, but not sure which one.
the app works fine on the apache server running on my local machine, however, before investing on a host, I want to be sure that I have the necessary requ... | Django: how to publish an app | I have developed an app using Django 1.1.1 and python 2.7.1. I want to publish it on a commercial website, but not sure which one.
the app works fine on the apache server running on my local machine, however, before investing on a host, I want to be sure that I have the necessary requirements, so if it matters, what ar... | [
"You can follow the docs on linode just fine, it doesn't matter that you're a Windows user, the app will be deployed on a linux box.\nYou can also try a shared hosting solution, that will run django right way, without any need to configure and setup a new machine. My personal recommendation is http://www.webfaction... | [
3
] | [] | [] | [
"apache",
"django",
"linode",
"production",
"python"
] | stackoverflow_0004564509_apache_django_linode_production_python.txt |
Q:
How come my Python code doesn't work?
from celery.decorators import task
from celery.decorators import task
@task()
def add(x, y):
r = open("./abc.txt","w")
r.write("sdf")
r.close()
return x + y
That's my tasks.py file.
>>> import tasks
>>> r = tasks.add.delay(3,5)
>>> r.result
8
As you can see, ... | How come my Python code doesn't work? | from celery.decorators import task
from celery.decorators import task
@task()
def add(x, y):
r = open("./abc.txt","w")
r.write("sdf")
r.close()
return x + y
That's my tasks.py file.
>>> import tasks
>>> r = tasks.add.delay(3,5)
>>> r.result
8
As you can see, the function works. However, the file does ... | [
"If the file was not being written, you would get an exception, so the function cannot possibly complete.\nSince the function is returning 8, it follows that the file is being written somewhere.\nPerhaps the file is written in a different directory to the one you are expecting\nThe only other possibility I can thin... | [
2,
1,
1
] | [] | [] | [
"celery",
"django",
"file",
"python",
"rabbitmq"
] | stackoverflow_0004551370_celery_django_file_python_rabbitmq.txt |
Q:
Decode base64 data as array in Python
I'm using this handy Javascript function to decode a base64 string and get an array in return.
This is the string:
base64_decode_array('6gAAAOsAAADsAAAACAEAAAkBAAAKAQAAJgEAACcBAAAoAQAA')
This is what's returned:
234,0,0,0,235,0,0,0,236,0,0,0,8,1,0,0,9,1,0,0,10,1,0,0,38,1,0,0,... | Decode base64 data as array in Python | I'm using this handy Javascript function to decode a base64 string and get an array in return.
This is the string:
base64_decode_array('6gAAAOsAAADsAAAACAEAAAkBAAAKAQAAJgEAACcBAAAoAQAA')
This is what's returned:
234,0,0,0,235,0,0,0,236,0,0,0,8,1,0,0,9,1,0,0,10,1,0,0,38,1,0,0,39,1,0,0,40,1,0,0
The problem is I don't r... | [
"Who cares. Python has easier ways of doing the same.\n[ord(c) for c in '6gAAAOsAAADsAAAACAEAAAkBAAAKAQAAJgEAACcBAAAoAQAA'.decode('base64')]\n\n",
"In Python I expected you'd just use the base64 module...\n... but in response to your question about << and >>>:\n\n<< is the left-shift operator; the result is the f... | [
11,
5,
3,
2
] | [] | [] | [
"arrays",
"base64",
"decode",
"javascript",
"python"
] | stackoverflow_0004563508_arrays_base64_decode_javascript_python.txt |
Q:
Erratic behavior with email attachments using python smtplib
My email script is based on this script at Fine Frog. I'm using this script to send HTML log files from a number of remote machines using a variety of ISPs.
The attachment isn't being sent consistently, however. It does work 80% of the time, but I'm gett... | Erratic behavior with email attachments using python smtplib | My email script is based on this script at Fine Frog. I'm using this script to send HTML log files from a number of remote machines using a variety of ISPs.
The attachment isn't being sent consistently, however. It does work 80% of the time, but I'm getting two types of weird behavior. The first is where the email isn'... | [
"I had a problem before using smtplib.SMTP, and figured out the email server required using an SSL connection. You could try using smtplib.SMTP_SSL if the regular call fails.\n",
"The first problem which raised one of the two following errors: \nsmtplib.SMTPServerDisconnected: Server not connected \n\nor \nsocke... | [
1,
1
] | [] | [] | [
"email",
"email_attachments",
"python",
"smtplib"
] | stackoverflow_0004559295_email_email_attachments_python_smtplib.txt |
Q:
Terminating subprocess in python
Completely rewritten based on my own investigation
I have a master script that runs a number of other python scripts.
The scripts are created as
from subprocess import STDOUT, Popen
from signal import SIGINT
import shlex
p = Popen(shlex.split("python somescript.py arg1 arg2"), cwd=... | Terminating subprocess in python | Completely rewritten based on my own investigation
I have a master script that runs a number of other python scripts.
The scripts are created as
from subprocess import STDOUT, Popen
from signal import SIGINT
import shlex
p = Popen(shlex.split("python somescript.py arg1 arg2"), cwd="../src/somedir", stderr=STDOUT)
And ... | [
"You can use psutil to find out about child processes, e.g. in pseudo-code:\np = Popen(...)\npp = psutil.Process(p.pid)\nfor child in pp.get_children():\n child.send_signal(signal.SIGINT)\n\nNote the difference in processes when running without --reload, obtained using ps -ef | grep manage.py | grep -v grep:\nvi... | [
0
] | [] | [] | [
"django",
"python",
"subprocess"
] | stackoverflow_0004554767_django_python_subprocess.txt |
Q:
in pyodbc how do you get a single table from database as an object
I've struggled through documentation and I don't really know how to get a single table from Database via pyodbc.
I know how to access table and all the values, but is there way to get a table as an object?
I tried this, but it doesn't seem nice (al... | in pyodbc how do you get a single table from database as an object | I've struggled through documentation and I don't really know how to get a single table from Database via pyodbc.
I know how to access table and all the values, but is there way to get a table as an object?
I tried this, but it doesn't seem nice (although it works):
conn=pyodbc.connect('DRIVER={Microsoft Access Driver (... | [
"you can always use cursor.tables(table=tablename, catalog=, schema=, tableType=)\nyou should read through the wiki: http://code.google.com/p/pyodbc/wiki/Cursor\n"
] | [
1
] | [] | [] | [
"pyodbc",
"python",
"sql"
] | stackoverflow_0004461000_pyodbc_python_sql.txt |
Q:
ListCtrl Hack: Set a ListItems Text in a ListCtrl
I am attempting to set an item's text contents in a ListCtrl. The problem is it doesn't work.
I use this function: _listItem.SetText( "Blah" ) but the text does not change? I have also tried the function SetItemText() but that doesn't work either.
Some important in... | ListCtrl Hack: Set a ListItems Text in a ListCtrl | I am attempting to set an item's text contents in a ListCtrl. The problem is it doesn't work.
I use this function: _listItem.SetText( "Blah" ) but the text does not change? I have also tried the function SetItemText() but that doesn't work either.
Some important information (that maybe helpful):
The ListCtrl has the L... | [
"When you use _listItem.SetText(\"Blah\") you also need to put the item back into the listctrl with something like self.SetItem(_listItem). Or you can use the listctrl's SetItemText method and not have to deal with the wx.ListItem object at all.\n"
] | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004532602_python_wxpython.txt |
Q:
How do I use python wx:Config to access the Windows registry?
I've read http://wxpython.org/docs/api/wx.ConfigBase-class.html
I've done some basic things like the appended. What I can see is that
Config.Create() returns me some sort of configuration object, which has
information about python in it. But clearly... | How do I use python wx:Config to access the Windows registry? | I've read http://wxpython.org/docs/api/wx.ConfigBase-class.html
I've done some basic things like the appended. What I can see is that
Config.Create() returns me some sort of configuration object, which has
information about python in it. But clearly that's not what I'm looking for:
I seem to be missing the magic to... | [
"I usually use Python builtin _winreg module for all my Registry work. Tim Golden's WMI module is also useful and you can use PyWin32 as well, but I think _winreg is the easiest unless you need to do a recursive delete.\n",
"The Config classes are not intended to be used as a general purpose access path to the re... | [
1,
1
] | [] | [] | [
"python",
"registry",
"wxpython"
] | stackoverflow_0004544708_python_registry_wxpython.txt |
Q:
Best method of extracting text from multiple html files into one CSV file
After reading this forum I am not sure which method is best to extract sections of data into a CSV file I.e. Python/Beautiful Soup/html2text. Because of the large number of files, I want to try and write a script I can run within the Termina... | Best method of extracting text from multiple html files into one CSV file | After reading this forum I am not sure which method is best to extract sections of data into a CSV file I.e. Python/Beautiful Soup/html2text. Because of the large number of files, I want to try and write a script I can run within the Terminal.
Output: One CSV file, with lines of text and five columns of data. e.g. firs... | [
"I would recommend using BeautifulSoup. Something like this will do (completely untested). Read the documentation for more.\ncsvfile = open('dump.csv', 'w')\nfor file in glob.glob('*.html'):\n print 'Processing', file\n soup = BeautifulSoup(open(file).read())\n for tr in soup.findAll('tr'):\n print ... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004528915_python.txt |
Q:
What was the first version of Python that included SQLite?
What was the first version of Python that included SQLite?
What version of SQLite was included?
I thought Python 2.5 was the first version to include SQLite, but I was hoping someone could confirm that and the version of SQLite that was first included.
A... | What was the first version of Python that included SQLite? |
What was the first version of Python that included SQLite?
What version of SQLite was included?
I thought Python 2.5 was the first version to include SQLite, but I was hoping someone could confirm that and the version of SQLite that was first included.
| [
"From the docs:\n\n11.13. sqlite3 — DB-API 2.0 interface for SQLite databases\nNew in version 2.5.\n\n",
"As others have noted, a snapshot of the pysqlite2 was merged into the Python standard library and released as the sqlite3 module in Python 2.5. There has been subsequent independent development on pysqlite2 ... | [
8,
6,
5,
3
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004563415_python_sqlite.txt |
Q:
Got Django and Buildout working, but what about PIL and Postgres?
I'm on Mac OSX 10.5.8. I have followed Jacob Kaplan-Moss's article on setting up Django with Buildout: http://jacobian.org/writing/django-apps-with-buildout/
Finally, I have got this Buildout to work! ...but I'm now needing PIL and Postgres for a co... | Got Django and Buildout working, but what about PIL and Postgres? | I'm on Mac OSX 10.5.8. I have followed Jacob Kaplan-Moss's article on setting up Django with Buildout: http://jacobian.org/writing/django-apps-with-buildout/
Finally, I have got this Buildout to work! ...but I'm now needing PIL and Postgres for a complete isolated Django development area. I've tried to modify my buildo... | [
"In theory, you should just be able to add PIL and psycopg2 to your eggs directive:\neggs = myproject\n PIL\n psycopg2\n\nThis works on some systems and in some situations.\nHowever, there are two problems that can prevent it from working everywhere, and especially on OSX:\n\nPIL's packaging is... weird... | [
8,
0
] | [] | [] | [
"buildout",
"postgresql",
"python",
"python_imaging_library"
] | stackoverflow_0002013789_buildout_postgresql_python_python_imaging_library.txt |
Q:
Forwarding an email with python smtplib
I'm trying to put together a script that automatically forwards certain emails that match a specific criteria to another email.
I've got the downloading and parsing of messages using imaplib and email working, but I can't figure out how to forward an entire email to another ... | Forwarding an email with python smtplib | I'm trying to put together a script that automatically forwards certain emails that match a specific criteria to another email.
I've got the downloading and parsing of messages using imaplib and email working, but I can't figure out how to forward an entire email to another address. Do I need to build a new message fro... | [
"I think the part you had wrong was how to replace the headers in the message, and the fact that you don't need to make a copy of the message, you can just operate directly on it after creating it from the raw data you fetched from the IMAP server.\nYou did omit some detail so here's my complete solution with all d... | [
25
] | [] | [] | [
"email",
"imap",
"python",
"smtp",
"smtplib"
] | stackoverflow_0002717196_email_imap_python_smtp_smtplib.txt |
Q:
Python Logger logging things twice to console
I'm trying to put together a logger using Python. I'm working in 2.6 so I can't use the new dictionary style method and instead am going with the good old fashioned config file. The problem is, stuff outputs twice to the console and I can't understand why. Here's my te... | Python Logger logging things twice to console | I'm trying to put together a logger using Python. I'm working in 2.6 so I can't use the new dictionary style method and instead am going with the good old fashioned config file. The problem is, stuff outputs twice to the console and I can't understand why. Here's my test script:
import logging
import logging.config
if... | [
"Change your non-root loggers to set propagate to 0, to prevent messages from being propagated up to the root logger:\n[logger_sloggerMain]\nhandlers=consoleHandler,infoFileHandler,debugFileHandler\nlevel=DEBUG\nqualname=sloggerMain\npropagate=0\n\nThe logging module's docs say:\n\nChild loggers propagate messages ... | [
42
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0004566327_logging_python.txt |
Q:
Paypal integration with Google application engine-python
I have to integrate paypal with my application which is built on app engine patch with python.
I searched over the web and found some issues reported in paypal integration with google application engine like here:
http://groups.google.com/group/google-appen... | Paypal integration with Google application engine-python | I have to integrate paypal with my application which is built on app engine patch with python.
I searched over the web and found some issues reported in paypal integration with google application engine like here:
http://groups.google.com/group/google-appengine/browse_thread/thread/9059b0750c45703b/b1d0611dd4b04273
Th... | [
"We have no problem accessing the paypal URL's FWIW...\nThe thread you are referencing is from 2008...\n",
"The official toolkit for Python wasn't released yet, so a promising library seems to be \npaypal-python. It is actively developed at least. One problem is that it requires Python 2.6 or 2.7, but maybe it wo... | [
3,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"paypal",
"python"
] | stackoverflow_0003634791_google_app_engine_paypal_python.txt |
Q:
Location of Beaker's @beaker_cache cache in Pylons
I've already asked this on pylons-discuss but got no answers.
I can't find where the cache of the @beaker_cache decorator is stored. I thought it should be in the data directory but it's not. It's also not in /tmp. I tried setting beaker.cache.data_dir = %(here)s/... | Location of Beaker's @beaker_cache cache in Pylons | I've already asked this on pylons-discuss but got no answers.
I can't find where the cache of the @beaker_cache decorator is stored. I thought it should be in the data directory but it's not. It's also not in /tmp. I tried setting beaker.cache.data_dir = %(here)s/data/cache and creating the directory manually but it's ... | [
"Depending on how you are using the decorator, it could be storing the data in memory. \n@cache.cache('mycache', type=\"file\", expire=15)\ndef my_action(self):\n stuff\n\ntype can be 'file', 'memory', or 'database'. The default is memory.\n"
] | [
2
] | [] | [] | [
"beaker",
"caching",
"pylons",
"python"
] | stackoverflow_0004532212_beaker_caching_pylons_python.txt |
Q:
Trying to Launch Google App Engine, given error related to python
I have installed python and don't really know what this means. Any ideas?
A:
Try opening launcher preferences (what it refers to in the last line), and tell it where you installed Python. There should be a "Python path" setting that you can set.
... | Trying to Launch Google App Engine, given error related to python |
I have installed python and don't really know what this means. Any ideas?
| [
"Try opening launcher preferences (what it refers to in the last line), and tell it where you installed Python. There should be a \"Python path\" setting that you can set.\n",
"\nSet the python.exe in your PATH. \nOR When you open and run cmd.exe, go to your python installation, which will be C:\\Python26\\ and f... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004567190_google_app_engine_python.txt |
Q:
Weird django admin importerror
I am getting a weird import error when I try to access admin: http://dpaste.com/292489/ It doesn't seem to be related to my code and I have setup all the proper admin settings and urls, since admin has worked properly before.
A:
The only thing I think to do is to double check your ... | Weird django admin importerror | I am getting a weird import error when I try to access admin: http://dpaste.com/292489/ It doesn't seem to be related to my code and I have setup all the proper admin settings and urls, since admin has worked properly before.
| [
"The only thing I think to do is to double check your PYTHONPATH and triple check that your ROOT_URLCONF is pointing to the right spot.\n"
] | [
1
] | [] | [] | [
"django",
"exception",
"importerror",
"python"
] | stackoverflow_0004567458_django_exception_importerror_python.txt |
Q:
Encrypting string based on X509 .cer in Python on Google App Engine
As the title says, I have the .cer file and I want to encrypt a string. I've tried quite a few libs out there, w/o success. Does anyone have any experience with this?
A:
I don't have an experience with this, but did you try Keyczar package by bu... | Encrypting string based on X509 .cer in Python on Google App Engine | As the title says, I have the .cer file and I want to encrypt a string. I've tried quite a few libs out there, w/o success. Does anyone have any experience with this?
| [
"I don't have an experience with this, but did you try Keyczar package by bundling it and trying to use that for your purposes. It has an Encrypter class for what you are trying to. It has a dependency on PyCrypto, but that seems already included in the GAE infrastructure.\n"
] | [
2
] | [] | [] | [
"certificate",
"google_app_engine",
"python",
"x509"
] | stackoverflow_0004567372_certificate_google_app_engine_python_x509.txt |
Q:
Handling Python program arguments in a json file
I am a Python re-newbie. I would like advice on handling program parameters which are in a file in json format. Currently, I am doing something like what is shown below, however, it seems too wordy, and the idea of typing the same literal string multiple times (some... | Handling Python program arguments in a json file | I am a Python re-newbie. I would like advice on handling program parameters which are in a file in json format. Currently, I am doing something like what is shown below, however, it seems too wordy, and the idea of typing the same literal string multiple times (sometimes with dashes and sometimes with underscores) seem... | [
"Usually, we do things like this.\ndef get_parameters( some_file_name ):\n source= json.loads( some_file_name )\n return dict(\n mpi_nodes= source.get('mpi-nodes',1),\n cluster_size= source['cluster-size'],\n initial_cutoff = source['initial-cutoff'],\n )\n\n controlsFileName= sys.argv... | [
2,
1,
1,
1
] | [] | [] | [
"json",
"parameters",
"python",
"validation"
] | stackoverflow_0004566313_json_parameters_python_validation.txt |
Q:
What should i do for accommodating large scale data storage and retrieval?
There's two columns in the table inside mysql database. First column contains the fingerprint while the second one contains the list of documents which have that fingerprint. It's much like an inverted index built by search engines. An inst... | What should i do for accommodating large scale data storage and retrieval? | There's two columns in the table inside mysql database. First column contains the fingerprint while the second one contains the list of documents which have that fingerprint. It's much like an inverted index built by search engines. An instance of a record inside the table is shown below;
34 "doc1, doc2, doc45"
The nu... | [
"Get a high end database. Oracle has some offers. SQL Server also.\nTRILLIONS of entries is well beyond the scope of a normal database. THis is very high end very special stuff, especially if you want decent performance. Also get the hardware for it - this means a decent mid range server, 128+gb memory for caching,... | [
2,
1,
0
] | [] | [] | [
"distributed_computing",
"large_data_volumes",
"mysql",
"nosql",
"python"
] | stackoverflow_0004560252_distributed_computing_large_data_volumes_mysql_nosql_python.txt |
Q:
Easiest non-Java way to write HBase MapReduce on CDH3?
I've been working on this for a long time, and I feel very worn out; I'm hoping for an [obvious?] insight from SO community that might get my pet project back on the move, so I can stop kicking myself. I'm using Cloudera CDH3, HBase .89 and Hadoop .20.
I have ... | Easiest non-Java way to write HBase MapReduce on CDH3? | I've been working on this for a long time, and I feel very worn out; I'm hoping for an [obvious?] insight from SO community that might get my pet project back on the move, so I can stop kicking myself. I'm using Cloudera CDH3, HBase .89 and Hadoop .20.
I have a Python/Django app that writes data to a single HBase table... | [
"It's not precisely an answer, but it's the closest I got --\nI asked in #hbase on irc.freenode.net yesterday, and one of the Cloudera employees responded.\nThe \"Input Splits\" problem I'm having with Pig is specific to Pig 0.7, and Pig 0.8 will be bundled with Cloudera CDH3 Beta 4 (no ETA on that). Therefore, wha... | [
0
] | [] | [] | [
"hadoop",
"hbase",
"mapreduce",
"python"
] | stackoverflow_0004557045_hadoop_hbase_mapreduce_python.txt |
Q:
How to efficiently add sparse matrices in Python
I want to know how to efficiently add sparse matrices in Python.
I have a program that breaks a big task into subtasks and distributes them across several CPUs. Each subtask yields a result (a scipy sparse matrix formatted as: lil_matrix).
The sparse matrix dimensio... | How to efficiently add sparse matrices in Python | I want to know how to efficiently add sparse matrices in Python.
I have a program that breaks a big task into subtasks and distributes them across several CPUs. Each subtask yields a result (a scipy sparse matrix formatted as: lil_matrix).
The sparse matrix dimensions are: 100000x500000 , which is quite huge, so I real... | [
"Have you tried timing the simplest method?\nmatrix_result = matrix_a + matrix_b\n\nThe documentation warns this may be slow for LIL matrices, suggesting the following may be faster:\nmatrix_result = (matrix_a.tocsr() + matrix_b.tocsr()).tolil()\n\n"
] | [
11
] | [] | [] | [
"add",
"numpy",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0004565685_add_numpy_python_scipy_sparse_matrix.txt |
Q:
Python and the self parameter
I'm having some issues with the self parameter, and some seemingly inconsistent behavior in Python is annoying me, so I figure I better ask some people in the know. I have a class, Foo. This class will have a bunch of methods, m1, through mN. For some of these, I will use a standard d... | Python and the self parameter | I'm having some issues with the self parameter, and some seemingly inconsistent behavior in Python is annoying me, so I figure I better ask some people in the know. I have a class, Foo. This class will have a bunch of methods, m1, through mN. For some of these, I will use a standard definition, like in the case of m1 b... | [
"os.access() is a built-in function, in the sense that it's part of an extension module written in C. When the class is defined, Python doesn't recognize m2 as a method because it's the wrong type — methods are Python functions, not C functions. m3, however, is a Python function, so it's recognized as a method and ... | [
4,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004567590_python.txt |
Q:
Python User Interface Print Statements
I'm writing a CLI helper program for managing a video library. Is it better to keep any kind of print statements in a single module, passing data via return statements, or simply print my output when I need to, where I need to?
A:
Use return statements properly for returnin... | Python User Interface Print Statements | I'm writing a CLI helper program for managing a video library. Is it better to keep any kind of print statements in a single module, passing data via return statements, or simply print my output when I need to, where I need to?
| [
"Use return statements properly for returning Outputs from function calls so that your I/O interfaces between functions are clear and meaningful. If you want debugging, use logging module and when your program is development phases, you can use print statements in between too.\n"
] | [
6
] | [] | [] | [
"command_line_interface",
"python"
] | stackoverflow_0004567801_command_line_interface_python.txt |
Q:
Multiple inheritance in Python; how to do so in Java?
I'm porting some Python code to Java, and I am having trouble dealing with the following problem:
I have some classes which need to have abilities A, B, or C. Class 1 needs ability A, class 2 needs A, B and C, and class 3 needs B and C. Most importantly, I want... | Multiple inheritance in Python; how to do so in Java? | I'm porting some Python code to Java, and I am having trouble dealing with the following problem:
I have some classes which need to have abilities A, B, or C. Class 1 needs ability A, class 2 needs A, B and C, and class 3 needs B and C. Most importantly, I want to easily be able to change what class can have what abili... | [
"Multiple-inheritance ain't frowned upon. What is frowned upon is \"implementation inheritance\" (also known as \"code reuse\"), because it leads to the unsolvable \"diamond problem\". And because, well, code-reuse really hasn't much to do with OO.\nWhat you want to do can be solved using multiple inheritance (an... | [
3,
3,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"java",
"multiple_inheritance",
"python"
] | stackoverflow_0004567692_java_multiple_inheritance_python.txt |
Q:
Are there benefits to running X86-64 Python on a 64-bit CPU in a 64-bit OS?
What kind of benefits are there to running the amd64 builds of Python and extensions? (Lots of extensions compiled for amd64 here.) I have an i5 processor and Win7 64-bit, so it seems like it would be appropriate. But it also sounds lik... | Are there benefits to running X86-64 Python on a 64-bit CPU in a 64-bit OS? | What kind of benefits are there to running the amd64 builds of Python and extensions? (Lots of extensions compiled for amd64 here.) I have an i5 processor and Win7 64-bit, so it seems like it would be appropriate. But it also sounds like it is buggy, beta, unsupported, etc.
Does it actually provide a performance ben... | [
"The primary rationale to use a 64-bit Python is that you can access more than 2GB of main memory, e.g. if you have large dicts, lists, or long strings. This requires that you actually have that much memory in your system to be practical.\nA secondary effect is that in AMD64 mode, the CPU has more registers, so the... | [
27,
7,
6,
5,
2
] | [] | [] | [
"64_bit",
"python",
"windows_7",
"x86_64"
] | stackoverflow_0004567856_64_bit_python_windows_7_x86_64.txt |
Q:
Looping through a text file, readline() construction fails on large files
In Python 2.6 and 2.7 I would have thought that these two constructs would be identical:
Method A
i=0
f=open('fred.txt','r')
for line in f.readline():
i+=1
print i
Method B
i=0
f=open('fred.txt','r')
for line in f:
i+=1
print i
How... | Looping through a text file, readline() construction fails on large files | In Python 2.6 and 2.7 I would have thought that these two constructs would be identical:
Method A
i=0
f=open('fred.txt','r')
for line in f.readline():
i+=1
print i
Method B
i=0
f=open('fred.txt','r')
for line in f:
i+=1
print i
However, when fred.txt grew to be 74,000 lines, with each line 2,684 characters in... | [
"There’s a typo, it should be f.readlines(). You’re reading one line and looping through each character in the line.\nBoth methods (readlines vs iterating over the file directly) ought to give the same results, but readlines will store the entire contents in memory.\n"
] | [
18
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0004568171_file_io_python.txt |
Q:
What tool can run in Linux, create an installer for a Python program, and install it on Windows?
I have a Python program that runs in Linux.
My customers may want to run the Python program on Windows.
Assume that they do not want to install Python, PyGTK, or Linux.
Is there a tool, preferably free ("open-source")... | What tool can run in Linux, create an installer for a Python program, and install it on Windows? | I have a Python program that runs in Linux.
My customers may want to run the Python program on Windows.
Assume that they do not want to install Python, PyGTK, or Linux.
Is there a tool, preferably free ("open-source") software, that can run in Linux, take my Python program, and create an installer that will install it... | [
"py2exe will get you a win32 exe file, along with a few pyd files and a zip archive. You can zip the entire dist folder and deploy it that way. However, if you need a GUI simple user installer you'll have to build that in a separate step.\nOptions: \n\ncreate Zip archive, manually extract \nDOS style BAT file ... | [
1,
0,
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0004543176_pygtk_python.txt |
Q:
Placement of config file reading
I'm developing a CLI python program and I'm using ConfigParser. I know this is probably more to preference than anything else, but currently my configuration reading script is in config.py in a package. Would I be better off placing my configuration reading information in __init__.... | Placement of config file reading | I'm developing a CLI python program and I'm using ConfigParser. I know this is probably more to preference than anything else, but currently my configuration reading script is in config.py in a package. Would I be better off placing my configuration reading information in __init__.py?
| [
"My preference would to put it in config.py too, because __init__.py should be minimal, separate classes should be in separate files to lower maintainance overhead. So I would go ahead and create a Configuration class like this;\nclass Configuration:\n\n def getVersion():\n ....\n\n def getFoo()\n ... | [
3
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0004568565_configparser_python.txt |
Q:
python socket programming error
i got this error while running my function.
"socket.error: [Errno 98] Address already in use"
how can i close the address already in use and start new connection with port in python?
A:
These scenarios will raise error "[Errno 98] Address already in use" when you create a soc... | python socket programming error | i got this error while running my function.
"socket.error: [Errno 98] Address already in use"
how can i close the address already in use and start new connection with port in python?
| [
"These scenarios will raise error \"[Errno 98] Address already in use\" when you create a socket at certain port:\n\nThe port was't closed. When you created a socket, but forgot to close it, or annother program hold that.\nYou have close the socket(or kill the process), but the port stay at TIME_WAIT status in 2 MS... | [
3,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0004568040_python_sockets.txt |
Q:
Python Memory Size
If I have a list of numbers and if I implement the same thing using dictionary, will they both occupy the same memory space?
Eg.
list = [[0,1],[1,0]]
dict = {'0,0' = 0 , '0,1' = 1, '1,0' = 1, '1,1' = 0 }
will the memory size of list and dict be the same? which will take up more space?
A:
If ... | Python Memory Size | If I have a list of numbers and if I implement the same thing using dictionary, will they both occupy the same memory space?
Eg.
list = [[0,1],[1,0]]
dict = {'0,0' = 0 , '0,1' = 1, '1,0' = 1, '1,1' = 0 }
will the memory size of list and dict be the same? which will take up more space?
| [
"If you're using Python 2.6 or higher, you can use sys.getsizeof() to do a test\n>>> import sys\n>>> aList = [[0,1],[1,0]]\n>>> aDict = {'0,0' : 0 , '0,1' : 1, '1,0' : 1, '1,1' : 0 }\n>>> sys.getsizeof(aList)\n44\n>>> sys.getsizeof(aDict)\n140\n\nWith the example you provided, we see that aDict takes up more space ... | [
3,
1,
1,
1
] | [] | [] | [
"memory",
"memory_management",
"python"
] | stackoverflow_0004568587_memory_memory_management_python.txt |
Q:
I am trying to debug Python which I am using to manipulate HTML for the Google App Engine
I am trying to debug Python which I am using to manipulate HTML for the Google App Engine. I am new to programming and looking for an easy way to debug my code. Thanks in advance!
A:
Normally, when you run your application ... | I am trying to debug Python which I am using to manipulate HTML for the Google App Engine | I am trying to debug Python which I am using to manipulate HTML for the Google App Engine. I am new to programming and looking for an easy way to debug my code. Thanks in advance!
| [
"Normally, when you run your application in the command line mode:\npython dev_appserver.py yourappname\n\nLots of debugging information is presented in the console for your app. You might also run\npython dev_server.py --debug-imports yourappname \n\nTo get the logging while imports happing and the paths. ( I have... | [
0,
0
] | [] | [] | [
"google_app_engine",
"html",
"python"
] | stackoverflow_0004568879_google_app_engine_html_python.txt |
Q:
Slicing a 2D numpy array into a 1D array
I have a 2D numpy array, FilteredOutput, that has 2 columns and 10001 rows, though the number of rows is a variable.
I am trying to take the 2nd column of FilteredOutput and use it to populate a new 1D numpy array called timeSeriesArray using some code I found):
timeSeriesA... | Slicing a 2D numpy array into a 1D array | I have a 2D numpy array, FilteredOutput, that has 2 columns and 10001 rows, though the number of rows is a variable.
I am trying to take the 2nd column of FilteredOutput and use it to populate a new 1D numpy array called timeSeriesArray using some code I found):
timeSeriesArray = np.array(FilteredOutput[:,0])
But I am... | [
"This is solved now. The problem was that I had not explicitly declared FilteredOutput to be a numpy array inside the function. I thought it had been declared as a numpy array outside the function, but the problem was solved when I added\nFilteredOutput = np.array(FilteredOutput)\n\nbefore\ntimeSeriesArray = np.a... | [
1
] | [] | [] | [
"arrays",
"numpy",
"python",
"slice"
] | stackoverflow_0004568959_arrays_numpy_python_slice.txt |
Q:
How to create a personalized Django admin model?
I am writing a Django application and I need to create a personalized admin model, in order to show only determined items in the administration interface when you create a new object.
I wrote this code for admin.py:
from django import forms
from myapp.models import ... | How to create a personalized Django admin model? | I am writing a Django application and I need to create a personalized admin model, in order to show only determined items in the administration interface when you create a new object.
I wrote this code for admin.py:
from django import forms
from myapp.models import *
from django.contrib import admin
class SimAdmin(adm... | [
"this is incorrect:\nclass SimAdmin(admin.ModelAdmin):\n phone = forms.ModelChoiceField(queryset=Item.objects.filter(name='phone'))\n\nyou're trying to attach forms.Field to admin.ModelAdmin. It doesn't work this way. \nTake a look at how can it be implemented: http://docs.djangoproject.com/en/1.2/ref/contrib/ad... | [
3
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004569101_django_django_admin_python.txt |
Q:
Why python IDLE and Console produce different results
I write a simple Python script to translate Chinese Punctuation to English.
import codecs, sys
def trcn():
tr = lambda x: x.translate(str.maketrans(""",。!?;:、()【】『』「」﹁﹂“”‘’《》~¥…—×""", """,.!?;:,()[][][][]""''<>~$^-*"""))
out = codecs.getwriter('utf-8')... | Why python IDLE and Console produce different results | I write a simple Python script to translate Chinese Punctuation to English.
import codecs, sys
def trcn():
tr = lambda x: x.translate(str.maketrans(""",。!?;:、()【】『』「」﹁﹂“”‘’《》~¥…—×""", """,.!?;:,()[][][][]""''<>~$^-*"""))
out = codecs.getwriter('utf-8')(sys.stdout)
for line in sys.stdin:
out.write(t... | [
"Your encoded output is coming out of the encoder as bytes, and therefore must be passed to sys.stdout.buffer:\nout = codecs.getwriter('utf-8')(sys.stdout.buffer)\n\nI'm not entirely sure why your code acts differently in IDLE versus the console, but the above may help. Perhaps IDLE's sys.stdout actually expects by... | [
6,
1
] | [
"It is very well obvious that the console's encoding is not utf-8. there is a way to specify the encoding as optional parameter when invoking python in console. just look for it in python docs.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0004568203_python.txt |
Q:
Emacs: methods for debugging python
I posted this on programmers.stackexchange.com, but I figured it may be more appropriate on SO.
I use emacs for all my code edit needs. Typically, I will use M-x compile to run my test runner which I would say gets me about 70% of what I need to do to keep the code on track how... | Emacs: methods for debugging python | I posted this on programmers.stackexchange.com, but I figured it may be more appropriate on SO.
I use emacs for all my code edit needs. Typically, I will use M-x compile to run my test runner which I would say gets me about 70% of what I need to do to keep the code on track however lately I've been wondering how it mi... | [
"A specific problem with GAE is that it redirects STDOUT to the browser, including debugger output.\nAs outlined in the pdb documentation, the usual workflow is to set a breakpoint in code at the point you need it. Normally you'd do import pdb; pdb.set_trace(), but in the case of GAE, you'll also want to grab your... | [
4,
1
] | [] | [] | [
"emacs",
"google_app_engine",
"python"
] | stackoverflow_0004542504_emacs_google_app_engine_python.txt |
Q:
RuntimeError: maximum recursion depth exceeded while calling a Python object
this error arises when i try to run the following test case which is written in models.py of my django app named 'administration' :
from django.test import Client, TestCase
from django.core import mail
class ClientTest( TestCase ):
... | RuntimeError: maximum recursion depth exceeded while calling a Python object | this error arises when i try to run the following test case which is written in models.py of my django app named 'administration' :
from django.test import Client, TestCase
from django.core import mail
class ClientTest( TestCase ):
fixtures = [ 'testdata.json' ]
def test_get_register( self ):
respon... | [
"django test client uses default base url:\nhttp://testserver/\nwhich makes your test url /accounts/register/ into:\nhttp://testserver/accounts/register/\nso you should add 'testserver' in django sites.site model as a base url.\nmaximum recursion depth exceed because django client did'nt find 'testserver' as a doma... | [
1
] | [] | [] | [
"django",
"python",
"satchmo"
] | stackoverflow_0004546711_django_python_satchmo.txt |
Q:
Vim: Good AutoCompletion Plugin for Python and PHP
I use Vim with ctags for development. I found ctags to be very useful in going to definitions, but I don't know a good plugin to make use of ctags for clever auto completion. It seems that the default Vim auto completion is not good. When I write set omnifunc? in ... | Vim: Good AutoCompletion Plugin for Python and PHP | I use Vim with ctags for development. I found ctags to be very useful in going to definitions, but I don't know a good plugin to make use of ctags for clever auto completion. It seems that the default Vim auto completion is not good. When I write set omnifunc? in Vim, I get this:
omnifunction=pythoncomplete#Complete
I... | [
"For Python, you can use the .vimrc file specified here:\nUltimate Vim Python setup.\nI think you will like it :)\nHappy vimming and Happy New Year!\n",
"You can use following:\nFor Python: http://www.vim.org/scripts/script.php?script_id=30\nFor PHP: http://www.vim.org/scripts/script.php?script_id=1571\n"
] | [
3,
2
] | [] | [] | [
"autocomplete",
"ctags",
"php",
"python",
"vim"
] | stackoverflow_0004568833_autocomplete_ctags_php_python_vim.txt |
Q:
Python replace not working with list
My code reads a directory and stores the filename with extention into a list. What I am trying to do is get rid of the extention with replace. However, it is not saving into the list.
print projectFilenames
for f in projectFilenames:
print f
f = f.replace('.txt','')
... | Python replace not working with list | My code reads a directory and stores the filename with extention into a list. What I am trying to do is get rid of the extention with replace. However, it is not saving into the list.
print projectFilenames
for f in projectFilenames:
print f
f = f.replace('.txt','')
f = f.replace('.mdown','')
f = f.replace... | [
"The list doesn't change, because you aren't updating it. You aren't touching the projectFilenames list in any way (nor the strings in the list. Python variables are not pointers) Here is one way to do it:\nnewlist = []\nfor f in projectFilenames:\n f = f.replace('.txt','')\n f = f.replace('.mdown','')\n f... | [
7,
4,
4,
2,
1
] | [] | [] | [
"python",
"replace",
"string"
] | stackoverflow_0004569186_python_replace_string.txt |
Q:
Emacs and Python
I recently started learning Emacs. I went through the tutorial, read some introductory articles, so far so good.
Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, w... | Emacs and Python | I recently started learning Emacs. I went through the tutorial, read some introductory articles, so far so good.
Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs ... | [
"If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain th... | [
20,
8,
7
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0000157018_emacs_python.txt |
Q:
Making windows not appear over each other
Is there a way to check if part or an entire window is over/under another window in python?
I have two windows and I'd like to make them not appear over each other. This is in Windows, using Tkinter.
A:
You can use the methods winfo_rootx and winfo_rooty to get the x/y ... | Making windows not appear over each other | Is there a way to check if part or an entire window is over/under another window in python?
I have two windows and I'd like to make them not appear over each other. This is in Windows, using Tkinter.
| [
"You can use the methods winfo_rootx and winfo_rooty to get the x/y in the upper left corner. You can use winfo_width and winfo_height to get the width and height of the window. From that it's just a little math to figure out if two windows overlap. You can then use the geometry method to position the windows anyw... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004566330_python_tkinter.txt |
Q:
Is there a commandline flag to set PYTHONHOME?
I'm attempting to run python on a system that doesn't allow me to set environment variables. Is there a commandline flag to python that will set PYTHONHOME? I looked here: http://docs.python.org/release/2.3.5/inst/search-path.html but didn't see anything.
So, hopefu... | Is there a commandline flag to set PYTHONHOME? | I'm attempting to run python on a system that doesn't allow me to set environment variables. Is there a commandline flag to python that will set PYTHONHOME? I looked here: http://docs.python.org/release/2.3.5/inst/search-path.html but didn't see anything.
So, hopefully something like this:
python -magical_path_flag /... | [
"You could simply set it in your script -- sys.path is a regular, modifiable list. Something like:\nimport sys\nsys.path.append(\"/path/to/libraries\")\n\nshould do the trick\n",
"In UNIXy shells, you can set an environment variable just for the duration of one command by prepending the command with the environme... | [
5,
2,
0
] | [] | [] | [
"android",
"python"
] | stackoverflow_0004568588_android_python.txt |
Q:
(python) os.path.exists os.path.isfile lies?
os.path.exists is giving me incorrect answers.
it's not the same problem discussed at below link since I'm at windows.
Are there other reasons for it to fail?
os.path.exists() lies
The test returns ok when I test it against a file at the same directory as the *.py scri... | (python) os.path.exists os.path.isfile lies? | os.path.exists is giving me incorrect answers.
it's not the same problem discussed at below link since I'm at windows.
Are there other reasons for it to fail?
os.path.exists() lies
The test returns ok when I test it against a file at the same directory as the *.py script runs, but none of its sub directories..
-EDIT-... | [
"os.path.exists and os.path.isfile is not case sensitive in Windows machines.\nHere's what I get in Windows 7 (Python 2.7)\n>>> os.path.exists('C:/.rnd')\nTrue\n>>> os.path.exists('C:/.RND')\nTrue\n>>> os.path.isfile('C:/.rnd')\nTrue\n>>> os.path.isfile('C:/.RND')\nTrue\n\n",
"Turned out, os.path.exists and os.pa... | [
3,
1
] | [] | [] | [
"path",
"python",
"windows"
] | stackoverflow_0004565619_path_python_windows.txt |
Q:
Take up Python 3.x or 2.x?
I started learning Python a few months back - and was immediately faced w/ this question. At that point I made the conscious decision to continue w/ 2.x [2.7.1 to be precise], because I was going to be involved in a project which was based on that version.
Over time I've come across num... | Take up Python 3.x or 2.x? | I started learning Python a few months back - and was immediately faced w/ this question. At that point I made the conscious decision to continue w/ 2.x [2.7.1 to be precise], because I was going to be involved in a project which was based on that version.
Over time I've come across numerous occurrences of lines like ... | [
"Use python 2.7 and start python with -3 parameter so it'll warn you when you use stuff thats not in python3 (or will be deprecated there), more details about this warnings here.\n",
"It's a common question and you can find a great answer on the \"official wiki\" : http://wiki.python.org/moin/Python2orPython3\n",... | [
5,
3,
3,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004570006_python_python_3.x.txt |
Q:
Python fetch data 403
I am trying to fetch data from a webpage using urllib2. The page is visible on the browser but through the script I keep getting HTTPError: HTTP Error 403: Forbidden
I also tried mimicking a browser request by changing the user-agent string but no success.
Any ideas on this?
A:
I tried wit... | Python fetch data 403 | I am trying to fetch data from a webpage using urllib2. The page is visible on the browser but through the script I keep getting HTTPError: HTTP Error 403: Forbidden
I also tried mimicking a browser request by changing the user-agent string but no success.
Any ideas on this?
| [
"I tried with tamper data and firefox to send only user agent, and I get 403.\nTry to add other headers:\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nAccept-Language: en-us,en;q=0.5\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\nKeep-Alive: 115\nConnection: keep-alive\n\nI tried, and ... | [
2,
1,
0
] | [] | [] | [
"fetch",
"http_status_code_403",
"httplib2",
"python",
"urllib2"
] | stackoverflow_0004546086_fetch_http_status_code_403_httplib2_python_urllib2.txt |
Q:
Django signals, implementing on save listner
am having difficulties understanding how signals works, I went through some pages but none of them helped me get the picture.
I have two models, I would like to create a signal that will save in the child model when a record is saved in the parent. Actually, I want the... | Django signals, implementing on save listner | am having difficulties understanding how signals works, I went through some pages but none of them helped me get the picture.
I have two models, I would like to create a signal that will save in the child model when a record is saved in the parent. Actually, I want the child to be listening across my application for a... | [
"With the code below you can connect the save of an Instance object, with the after_save_instance_handler method. In this method you create the relation to the Audit. Please also see the generic relations doc\nI usually add the signals in the models.py where the sender has been defined. Not sure if this is needed.\... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004569844_django_python.txt |
Q:
Good tools for animated maps on a webpage
I want to present regions on a map inside a webpage. The region should be clickable and highlighted when hovered. I'am using django so I tend to orient towords matplotlib and other python tools.
There are interesting projects on the web:
thematic mapping
polymaps
geodjang... | Good tools for animated maps on a webpage | I want to present regions on a map inside a webpage. The region should be clickable and highlighted when hovered. I'am using django so I tend to orient towords matplotlib and other python tools.
There are interesting projects on the web:
thematic mapping
polymaps
geodjango seems complicated
this blog shows a marvelous... | [
"I'd definitely go with openlayers if it's just presentation.\nGeodjango is handy for allowing admins to edit spatial data in the django admin, but by itself doesn't have much in the way of map presentation templates - you have to build them yourself (using openlayers) or try the olwidget django addon.\n",
"I sug... | [
2,
1
] | [] | [] | [
"django",
"geodjango",
"map",
"python"
] | stackoverflow_0004570666_django_geodjango_map_python.txt |
Q:
Emacs: methods for debugging python
I use emacs for all my code edit needs. Typically, I will use M-x compile to run my test runner which I would say gets me about 70% of what I need to do to keep the code on track however lately I've been wondering how it might be possible to use M-x pdb on occasions where it wou... | Emacs: methods for debugging python | I use emacs for all my code edit needs. Typically, I will use M-x compile to run my test runner which I would say gets me about 70% of what I need to do to keep the code on track however lately I've been wondering how it might be possible to use M-x pdb on occasions where it would be nice to hit a breakpoint and inspec... | [
"Hmm. You're doing this a little differently than I do. I haven't experimented with your method. I use the pdb library module directly, with no wrapper script, just using the \"-m\" python command-line option to tell python to run the module as a script.\nTo be excessively thorough, here's my sequence of operati... | [
4
] | [] | [] | [
"emacs",
"google_app_engine",
"python"
] | stackoverflow_0004570826_emacs_google_app_engine_python.txt |
Q:
How to generate an alternating range?
I need to search for an item in a list around a given index with in a given radius. Currently I use this function to generate alternating offsets for the search:
def generateSearchIndizes(radius):
for i in range(1, radius + 1):
yield i
yield -i
The code th... | How to generate an alternating range? | I need to search for an item in a list around a given index with in a given radius. Currently I use this function to generate alternating offsets for the search:
def generateSearchIndizes(radius):
for i in range(1, radius + 1):
yield i
yield -i
The code that does the search looks something like thi... | [
"\nis there a more elegant way to generate the search indices\n\nI don't think there's a more elegant way. Your code is very simple and clear.\n\nmaybe without defining a special function?\n\nYes, that's definitely possible.\n>>> [b for a in ((x,-x) for x in range(1, 10 + 1)) for b in a]\n[1, -1, 2, -2, 3, -3, 4, -... | [
4,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004570106_python.txt |
Q:
Count letters in a word in python debug
I am trying to count the number of times 'e' appears in a word.
def has_no_e(word): #counts 'e's in a word
letters = len(word)
count = 0
while letters >= 0:
if word[letters-1] == 'e':
count = count + 1
letters = letters - 1
pri... | Count letters in a word in python debug | I am trying to count the number of times 'e' appears in a word.
def has_no_e(word): #counts 'e's in a word
letters = len(word)
count = 0
while letters >= 0:
if word[letters-1] == 'e':
count = count + 1
letters = letters - 1
print count
It seems to work fine except when t... | [
">>> word = 'eeeooooohoooooeee'\n>>> word.count('e')\n6\n\nWhy not this?\n",
"As others mention, you can implement the test with a simple word.count('e'). Unless you're doing this as a simple exercise, this is far better than trying to reinvent the wheel.\nThe problem with your code is that it counts the last cha... | [
14,
12,
1,
1,
1,
1,
1,
1,
1
] | [] | [] | [
"count",
"letter",
"python"
] | stackoverflow_0004563552_count_letter_python.txt |
Q:
Class from variable
I have a class, trying to instantiate another class, based off of a variable name passed to it. It is complaining that 'str' object is not callable. What is the proper way to do this?
def MyClass:
def __init__(self, otherName):
self.other = otherName()
EDIT: Here is the entirety of... | Class from variable | I have a class, trying to instantiate another class, based off of a variable name passed to it. It is complaining that 'str' object is not callable. What is the proper way to do this?
def MyClass:
def __init__(self, otherName):
self.other = otherName()
EDIT: Here is the entirety of my code, is there anythi... | [
"You can do this without using strings at all. You can refer to classes in Python by name, and pass them around just like any other object. So, using your definition of MyClass above, instead of doing:\nc = Controller(\"Blog\")\n\nyou can use simply:\nc = Controller(Blog)\n\nUsing eval() for something like this is ... | [
9,
0
] | [
"If you really would like to pass the parameter as a string, you could use eval().\nclass MyClass: \n def __init(self, otherName): \n self.other = eval(otherName)()\n\n"
] | [
-1
] | [
"class",
"new_operator",
"object",
"python"
] | stackoverflow_0004566655_class_new_operator_object_python.txt |
Q:
Which is quicker? Memcache or file query? (using maxmind geoip.dat file)
I'm using Python on Appengine and am looking up the geolocation of an IP address like this:
import pygeoip
gi = pygeoip.GeoIP('GeoIP.dat')
Location = gi.country_code_by_addr(self.request.remote_addr)
(pygeoip can be found here: http://code.g... | Which is quicker? Memcache or file query? (using maxmind geoip.dat file) | I'm using Python on Appengine and am looking up the geolocation of an IP address like this:
import pygeoip
gi = pygeoip.GeoIP('GeoIP.dat')
Location = gi.country_code_by_addr(self.request.remote_addr)
(pygeoip can be found here: http://code.google.com/p/pygeoip/)
I want to geolocate each page of my app for a user so cu... | [
"What takes time there is rather loading the database from the dat file. Once you have that in memory, the lookup time is not significant. So if you can keep the gi variable in memory that seems the best solution. \nIf you can't you probably can't use memcached either.\n",
"If you need to do lookups across multip... | [
3,
3,
1
] | [] | [] | [
"google_app_engine",
"memcached",
"optimization",
"python"
] | stackoverflow_0004569780_google_app_engine_memcached_optimization_python.txt |
Q:
Problem with re.findall (duplicates)
I tried to fetch source of 4chan site, and get links to threads.
I have problem with regexp (isn't working). Source:
import urllib2, re
req = urllib2.Request('http://boards.4chan.org/wg/')
resp = urllib2.urlopen(req)
html = resp.read()
print re.findall("res/[0-9]+", html)
#pr... | Problem with re.findall (duplicates) | I tried to fetch source of 4chan site, and get links to threads.
I have problem with regexp (isn't working). Source:
import urllib2, re
req = urllib2.Request('http://boards.4chan.org/wg/')
resp = urllib2.urlopen(req)
html = resp.read()
print re.findall("res/[0-9]+", html)
#print re.findall("^res/[0-9]+$", html)
The ... | [
"That's because there are multiple copies of the link in the source.\nYou can easily make them unique by putting them in a set.\n>>> print set(re.findall(\"res/[0-9]+\", html))\nset(['res/3833795', 'res/3837945', 'res/3835377', 'res/3837941', 'res/3837942',\n'res/3837950', 'res/3100203', 'res/3836997', 'res/3837643... | [
11
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0004571468_html_python_regex.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.