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:
Use value of variable in lambda expression
a = [] a.append(lambda x:x**0)
a.append(lambda x:x**1)
a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ...
b=[]
for i in range(4)
b.append(lambda x:x**i)
b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ...
In the for loop, the i is being passed to lambda as a var... | Use value of variable in lambda expression | a = [] a.append(lambda x:x**0)
a.append(lambda x:x**1)
a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ...
b=[]
for i in range(4)
b.append(lambda x:x**i)
b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ...
In the for loop, the i is being passed to lambda as a variable, so when I call it, the last value of i is... | [
"Ugly, but one way:\nfor i in range(4)\n b.append(lambda x, copy=i: x**copy)\n\nYou might prefer\ndef raiser(power):\n return lambda x: x**power\n\nfor i in range(4)\n b.append(raiser(i))\n\n(All code untested.)\n",
"Define a factory\ndef power_function_factory(value):\n def new_power_function(base):\... | [
8,
4,
2
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0000760688_lambda_python.txt |
Q:
Is there a fini routine for a python module written in C?
I have a python module written in C, and I would like to add a function that is called when the module is unloaded. I obviously have an initfoo function to initialize the module -- is there a way to tell python to call a finifoo function when it's uninitial... | Is there a fini routine for a python module written in C? | I have a python module written in C, and I would like to add a function that is called when the module is unloaded. I obviously have an initfoo function to initialize the module -- is there a way to tell python to call a finifoo function when it's uninitializing the module?
Is atexit my only option?
| [
"Not in Python 2, but Python 3 seems to. If you need to manage some resource, I would advise putting it in a module-level object -- I'm pretty sure those will be garbage-collected when the module is unloaded.\n\nFrom the link:\n\nCurrently, extension modules are\n initialized usually once and then\n \"live\" fore... | [
4
] | [] | [] | [
"c",
"python",
"python_module"
] | stackoverflow_0000760937_c_python_python_module.txt |
Q:
sys.getrefcount continuation
link text
I got the concept of reference count
So when i do a "del astrd" ,reference count drops to zero and astrd gets collected by gc ?
This is the sample codes.These codes I developed after my yesterday's question:link text
one.py:
def abc():
print "Hello"
print "123"
print '345'
t... | sys.getrefcount continuation | link text
I got the concept of reference count
So when i do a "del astrd" ,reference count drops to zero and astrd gets collected by gc ?
This is the sample codes.These codes I developed after my yesterday's question:link text
one.py:
def abc():
print "Hello"
print "123"
print '345'
two.py:
import one
#reload(one)
#d... | [
"I believe that memory is automatically freed the moment the refcount reaches zero. The GC is not involved.\nThe python GC is optional, and is only used when there are unreachable objects that has reference cycles. In fact, you can call gc.disable() if you are sure your program does not create reference cycles.\nAs... | [
8,
1,
1
] | [] | [] | [
"del",
"python"
] | stackoverflow_0000759906_del_python.txt |
Q:
Why csv.reader is not pythonic?
I started to use the csv.reader in Python 2.6 but you can't use len on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.
Or is this just an abandoned module in later versions?
A:
I'm pretty sure you can't use len or slice because it is an itera... | Why csv.reader is not pythonic? | I started to use the csv.reader in Python 2.6 but you can't use len on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.
Or is this just an abandoned module in later versions?
| [
"I'm pretty sure you can't use len or slice because it is an iterator. Try this instead.\nimport csv\nr = csv.reader(...)\nlines = [line for line in r]\nprint len(lines) #number of lines\nfor odd in lines[1::2]: print odd # print odd lines\n\n"
] | [
14
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0000761430_csv_python.txt |
Q:
Overriding 'to boolean' operator in python?
I'm using a class that is inherited from list as a data structure:
class CItem( list ) :
pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
All is perfect, but if I use my object of my class inside of an 'if', python evaluates it to False if underlying t... | Overriding 'to boolean' operator in python? | I'm using a class that is inherited from list as a data structure:
class CItem( list ) :
pass
oItem = CItem()
oItem.m_something = 10
oItem += [ 1, 2, 3 ]
All is perfect, but if I use my object of my class inside of an 'if', python evaluates it to False if underlying the list has no elements. Since my class is not j... | [
"In 2.x: override __nonzero__(). In 3.x, override __bool__().\n"
] | [
45
] | [] | [] | [
"python"
] | stackoverflow_0000761586_python.txt |
Q:
Program Control-Flow in Python
I have some data that I have stored in a list and if I print out the list I see the following:
.
.
.
007 A000000 Y
007 B000000 5
007 C010100 1
007 C020100 ACORN FUND
007 C030100 N
007 C010200 2
007 C020200 ACORN INTERNATIONAL
007 C030200 N
007 C010300 3
007 C020300 ACORN USA
007 ... | Program Control-Flow in Python | I have some data that I have stored in a list and if I print out the list I see the following:
.
.
.
007 A000000 Y
007 B000000 5
007 C010100 1
007 C020100 ACORN FUND
007 C030100 N
007 C010200 2
007 C020200 ACORN INTERNATIONAL
007 C030200 N
007 C010300 3
007 C020300 ACORN USA
007 C030300 N
007 C010400 4
.
.
.
The ... | [
"You can use itertools.groupby() to segment your sequence into multiple sub-sequences. \nimport itertools\n\nfor key, subseq in itertools.groupby(tempans, lambda s: s.partition(' ')[0]):\n if key == '007':\n for dataLine in subseq:\n if dataLine.startswith('007 B'):\n numberOfSeries = int(dataL... | [
3,
2,
2,
0,
0
] | [] | [] | [
"enumerate",
"list",
"python"
] | stackoverflow_0000758465_enumerate_list_python.txt |
Q:
Send headers along in python
I have the following python script and I would like to send "fake" header information along so that my application acts as if it is firefox. How could I do that?
import urllib, urllib2, cookielib
username = '****'
password = '****'
login_user = urllib.urlencode({'password' : passwo... | Send headers along in python | I have the following python script and I would like to send "fake" header information along so that my application acts as if it is firefox. How could I do that?
import urllib, urllib2, cookielib
username = '****'
password = '****'
login_user = urllib.urlencode({'password' : password, 'username' : username})
jar =... | [
"Use the addheaders() function on your opener object. \nJust add this one line after you create your opener, before you start opening pages:\nopener.addheaders = [('User-agent', 'Mozilla/5.0')]\n\nhttp://docs.python.org/library/urllib2.html (it's at the bottom of this document)\n",
"You have to get a bit more low... | [
6,
5,
1
] | [] | [] | [
"http_headers",
"post",
"python"
] | stackoverflow_0000761978_http_headers_post_python.txt |
Q:
Python Regexp problem
I'm trying to regexp a line from a webpage. The line is as follows:
<tr><td width=60 bgcolor='#ffffcc'><b>random Value</b></td><td align=center width=80>
This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contains the html page and no, I did not forget to i... | Python Regexp problem | I'm trying to regexp a line from a webpage. The line is as follows:
<tr><td width=60 bgcolor='#ffffcc'><b>random Value</b></td><td align=center width=80>
This is what I tried, but it doesn't seem to work, can anyone help me out? 'htmlbody' contains the html page and no, I did not forget to import 're'.
reg = re.compil... | [
"There is no surefire way to do this with a regex. See Can you provide some examples of why it is hard to parse XML and HTML with a regex? for why. What you need is an HTML parser like HTMLParser:\n#!/usr/bin/python\n\nfrom HTMLParser import HTMLParser\n\nclass FindTDs(HTMLParser):\n def __init__(self):\n ... | [
4,
1,
1
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0000762482_html_python_regex.txt |
Q:
How can I get useful information from flash swf files?
I'm doing some crawling with Python, and would like to be able to identify (however imperfectly) the flash I come across - is it a video, an ad, a game, or whatever.
I assume I would have to decompile the swf, which seems doable. But what sort of processing wo... | How can I get useful information from flash swf files? | I'm doing some crawling with Python, and would like to be able to identify (however imperfectly) the flash I come across - is it a video, an ad, a game, or whatever.
I assume I would have to decompile the swf, which seems doable. But what sort of processing would I do with the decompiled Actionscript to figure out what... | [
"I think your best bet would be to check the context where you see the swf file\nusually they're embedded within web pages so if that page has 100 occurences of the word \"game\", then it might be a game, as an example\nTo detect an ad it might be trickier but i think that checking the domainname where the swf is h... | [
4,
2,
0
] | [] | [] | [
"actionscript",
"flash",
"python"
] | stackoverflow_0000731016_actionscript_flash_python.txt |
Q:
pyQT QNetworkManager and ProgressBars
I'm trying to code something that downloads a file from a webserver and saves it, showing the download progress in a QProgressBar.
Now, there are ways to do this in regular Python and it's easy. Problem is that it locks the refresh of the progressBar. Solution is to use PyQT'... | pyQT QNetworkManager and ProgressBars | I'm trying to code something that downloads a file from a webserver and saves it, showing the download progress in a QProgressBar.
Now, there are ways to do this in regular Python and it's easy. Problem is that it locks the refresh of the progressBar. Solution is to use PyQT's QNetworkManager class. I can download stu... | [
"Well you haven't connected any of the signals to your updateBar() method.\nchange\ndef replyFinished(self, reply):\n self.connect(reply,SIGNAL(\"downloadProgress(int,int)\"),self.progressBar, SLOT(\"setValue(int)\"))\n\nto \ndef replyFinished(self, reply):\n self.connect(reply,SIGNAL(\"downloadProgre... | [
4
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0000761286_pyqt_python.txt |
Q:
How do i convert WMD markdown syntax to HTML on my site?
Am using django and am implementing WMD on my site, am just wondering how do i convert the markdown syntax to HTML for display purposes, is there some sort of function i should call to do this conversion?
What is the best way to handle markdown ie. do i save... | How do i convert WMD markdown syntax to HTML on my site? | Am using django and am implementing WMD on my site, am just wondering how do i convert the markdown syntax to HTML for display purposes, is there some sort of function i should call to do this conversion?
What is the best way to handle markdown ie. do i save the markdown as is to the database then parse it when display... | [
"Check out the markup add-on which comes with Django. That is what you are looking for.\n\nTo activate these filters, add 'django.contrib.markup' to your INSTALLED_APPS setting. Once you’ve done that, use {% load markup %} in a template, and you’ll have access to these filters. For more documentation, read the sour... | [
6
] | [] | [] | [
"django",
"html",
"markdown",
"python",
"wmd"
] | stackoverflow_0000763087_django_html_markdown_python_wmd.txt |
Q:
If you were to clone Monopoly Tycoon in Python, what libraries would you use?
Ever played the game Monopoly Tycoon? I think it's great.
I would love to remake it. Unfortunately, I have no experience when it comes to 3D programming. I imagine there's a relatively steep learning curve when it comes to openGL stuff... | If you were to clone Monopoly Tycoon in Python, what libraries would you use? | Ever played the game Monopoly Tycoon? I think it's great.
I would love to remake it. Unfortunately, I have no experience when it comes to 3D programming. I imagine there's a relatively steep learning curve when it comes to openGL stuff, figuring out what is being clicked on and so on...
If you were to undertake this ... | [
"pyGame seems quite mature and builds on top of the proven SDL library. \n",
"I'd use pyglet. It's all opengl from the start, doesn't build on top of ugly SDL library and has better interfaces than what I've seen on other python's multimedia libraries.\nimport pyglet\nfrom pyglet.gl import *\n\nclass Application(... | [
6,
4
] | [] | [] | [
"opengl",
"python"
] | stackoverflow_0000761652_opengl_python.txt |
Q:
Auto GET to argument of view
some_view?param1=10¶m2=20
def some_view(request, param1, param2):
Is such possible in Django?
A:
You could always write a decorator. Eg. something like (untested):
def map_params(func):
def decorated(request):
return func(request, **request.GET)
return decorate... | Auto GET to argument of view | some_view?param1=10¶m2=20
def some_view(request, param1, param2):
Is such possible in Django?
| [
"You could always write a decorator. Eg. something like (untested):\ndef map_params(func):\n def decorated(request):\n return func(request, **request.GET)\n return decorated\n\n@map_params\ndef some_view(request, param1, param2):\n ...\n\n",
"I'm not sure it's possible to get it to pass them as a... | [
3,
1,
1,
1
] | [] | [] | [
"django",
"django_urls",
"django_views",
"python"
] | stackoverflow_0000763103_django_django_urls_django_views_python.txt |
Q:
Python Beginner: How to Prevent 'finally' from executing?
The function code:
# Connect to the DB
try:
dbi = MySQLdb.connect(host='localhost', \
user='user', \
passwd='pass', \
db='dbname', \
port=3309)
... | Python Beginner: How to Prevent 'finally' from executing? | The function code:
# Connect to the DB
try:
dbi = MySQLdb.connect(host='localhost', \
user='user', \
passwd='pass', \
db='dbname', \
port=3309)
print "Connected to DB ..."
except MySQLdb.Error, e:
apiEr... | [
"Use else: instead of finally:. See the Exception Handling part of the docs:\n\nThe try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.\n\nfor arg in sys.argv[1:]:\n t... | [
6,
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0000763480_python.txt |
Q:
Importing In Python
Is it possible to import modules based on location?
(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)
I'd like to import a module that's local to the current script.
A:
You can extend the path at runtime like this:
sys.path.extend(map(os.path.abspath, ['othe... | Importing In Python | Is it possible to import modules based on location?
(eg. do all modules i import have to be in /usr/lib64/python2.5/ or a similar dir?)
I'd like to import a module that's local to the current script.
| [
"You can extend the path at runtime like this:\nsys.path.extend(map(os.path.abspath, ['other1/', 'other2/', 'yourlib/']))\n\n",
"You can edit your PYTHONPATH to add or remove locations that python will search whenever you attempt an import.\n",
"\npython will import from the current directory by default.\nsys.p... | [
9,
3,
3,
0,
0,
0,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0000762111_import_python.txt |
Q:
Active Directory - Django/Rails
I'm thinking about re-writing a web app in Django or Rails and wondering about authenticating against AD. Is one ecosystem better suited for this (libraries, etc) or is it a toss-up?
(The app will be hosted on Linux)
I have lots of reasons for the re-write, one them is to make myse... | Active Directory - Django/Rails | I'm thinking about re-writing a web app in Django or Rails and wondering about authenticating against AD. Is one ecosystem better suited for this (libraries, etc) or is it a toss-up?
(The app will be hosted on Linux)
I have lots of reasons for the re-write, one them is to make myself more marketable. Anyone care to co... | [
"A quick google to give you some pointers on using Active Directory in these environments.\n\nhttp://www.djangosnippets.org/snippets/501/\nhttp://www.zorched.net/2007/06/04/active-directory-authentication-for-ruby-on-rails/\n\n",
"I did Active Directory auth in Rails about a year ago. I did it similarly to the ar... | [
3,
0
] | [] | [] | [
"active_directory",
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0000761820_active_directory_django_python_ruby_ruby_on_rails.txt |
Q:
How to interact through vim?
I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rath... | How to interact through vim? | I am writing an editor which has lot of parameters that could be easily interacted with through text. I find it inconvenient to implement a separate text-editor or lots of UI code for every little parameter. Usual buttons, boxes and gadgets would be burdensome and clumsy. I'd much rather let user interact with those pa... | [
"Write your intermediate results (what you want the user to edit) to a temp file. Then use the $EDITOR environment variable in a system call to make the user edit the temp file, and read the results when the process finishes.\nThis lets users configure which editor they want to use in a pseudo-standard fashion.\n"... | [
6,
2,
1
] | [] | [] | [
"linux",
"python",
"vim"
] | stackoverflow_0000763372_linux_python_vim.txt |
Q:
Determine if a function is available in a Python module
I am working on some Python socket code that's using the socket.fromfd() function.
However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined.
What's the best way to determine if a met... | Determine if a function is available in a Python module | I am working on some Python socket code that's using the socket.fromfd() function.
However, this method is not available on all platforms, so I am writing some fallback code in the case that the method is not defined.
What's the best way to determine if a method is defined at runtime? Is the following sufficient or is ... | [
"hasattr() is the best choice. Go with that. :)\nif hasattr(socket, 'fromfd'):\n pass\nelse:\n pass\n\nEDIT: Actually, according to the docs all hasattr is doing is calling getattr and catching the exception. So if you want to cut out the middle man you should go with marcog's answer.\nEDIT: I also just real... | [
60,
26,
3
] | [] | [] | [
"python"
] | stackoverflow_0000763971_python.txt |
Q:
Trying to get enum style choices= working for django but the whole tuplets are appearing in the drop down
Im using appengine and the appenginepatch (so my issue could be related to that)
I have set up a model with a property that has several choices but when trying to display on a form or via admin interface I am ... | Trying to get enum style choices= working for django but the whole tuplets are appearing in the drop down | Im using appengine and the appenginepatch (so my issue could be related to that)
I have set up a model with a property that has several choices but when trying to display on a form or via admin interface I am getting an error:
Property mode is 'o'; must be one of (('s', 'Single'), ('m', 'Multi'), ('o', 'Ordered'))
T... | [
"It looks like this is an issue in Django/appengine support. It's documented here on the google-app-engine-django bug tracker, but it's closed as \"wontfix\" there. It is also documented here on the googleappengine bug tracker and is closed as invalid.\nAccording to the docs, the appengine choices parameter works... | [
2
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0000764177_django_google_app_engine_python.txt |
Q:
Pythonic macro syntax
I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.
My problem is that I can't come up with a ... | Pythonic macro syntax | I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.
My problem is that I can't come up with a pythonic macro definition s... | [
"After thinking about it a while a few days ago, and coming up with nothing worth posting, I came back to it now and came up with some syntax I rather like, because it nearly looks like python:\nmacro PrintMacro:\n syntax:\n \"print\", OneOrMore(Var(), name='vars')\n\n return Printnl(vars, None)\n\n\nMake all ... | [
11,
3,
3,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"macros",
"python",
"syntax"
] | stackoverflow_0000454648_macros_python_syntax.txt |
Q:
How do I modify sys.path from .htaccess to allow mod_python to see Django?
The host I'm considering for hosting a Django site has mod_python installed, but does not have Django. Django's INSTALL file indicates that I can simply copy the django directory to Python's site-packages directory to install Django, so I s... | How do I modify sys.path from .htaccess to allow mod_python to see Django? | The host I'm considering for hosting a Django site has mod_python installed, but does not have Django. Django's INSTALL file indicates that I can simply copy the django directory to Python's site-packages directory to install Django, so I suspect that it might be possible to configure Python / mod_python to look for it... | [
"According to ticket #2255 for Django, you need admin access to httpd.conf in order to use Django with mod_python, and this is not going to change, so you may be dead in the water. To answer the basic question of how to modify sys.path from .htaccess, you can use the PythonPath directive in .htaccess.\n",
"Is th... | [
3,
1,
1
] | [] | [] | [
".htaccess",
"apache",
"django",
"mod_python",
"python"
] | stackoverflow_0000764312_.htaccess_apache_django_mod_python_python.txt |
Q:
Is there a Python library that allows to build user interfaces without writing much code?
I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.
Is there a technology that allows me to, say, specify the relation... | Is there a Python library that allows to build user interfaces without writing much code? | I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.
Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to d... | [
"Besides the ones already mentioned I can add:\n\nKiwi\nuxpython\npygtk\ntreethon\n\nI've never used any of them so have no recommendations but, for what it's worth, I have used at least 2 complex programs built directly on pygtk that worked in both Windows and Linux.\nI think Kiwi is the only one of these with bak... | [
5,
4,
4,
1,
1,
1,
0,
0
] | [] | [] | [
"glade",
"gtk",
"python",
"sqlite",
"user_interface"
] | stackoverflow_0000671741_glade_gtk_python_sqlite_user_interface.txt |
Q:
How's Python Multiprocessing Implemented on Windows?
Given the absence of a Windows fork() call, how's the multiprocessing package in Python 2.6 implemented under Windows? On top of Win32 threads or some sort of fake fork or just compatibility on top of the existing multithreading?
A:
It's done using a subproce... | How's Python Multiprocessing Implemented on Windows? | Given the absence of a Windows fork() call, how's the multiprocessing package in Python 2.6 implemented under Windows? On top of Win32 threads or some sort of fake fork or just compatibility on top of the existing multithreading?
| [
"It's done using a subprocess call to sys.executable (i.e. start a new Python process) followed by serializing all of the globals, and sending those over the pipe. A poor man's cloning of the current process. This is the cause of the extra restrictions found when using multiprocessing on Windows plaform.\nYou may a... | [
30
] | [] | [] | [
"fork",
"multithreading",
"python"
] | stackoverflow_0000765129_fork_multithreading_python.txt |
Q:
How do I store a string with a `"` in it?
I want to have a JSON object with the value of an attribute as a string with the character ".
For example:
{
"Dimensions" : " 12.0" x 9.6" "
}
Obviously this is not possible. How do I do this?
With Python.
A:
Isaac is correct.
As for how to do it in python, you need to... | How do I store a string with a `"` in it? | I want to have a JSON object with the value of an attribute as a string with the character ".
For example:
{
"Dimensions" : " 12.0" x 9.6" "
}
Obviously this is not possible. How do I do this?
With Python.
| [
"Isaac is correct.\nAs for how to do it in python, you need to provide a more detailed explanation of how you are building your JSON object. For example, let's say you're using no external libraries and are doing it manually (ridiculous, I know), you would do this:\n>>> string = \"{ \\\"Dimensions\\\" : \\\" 12.0\... | [
7,
3,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0000763654_json_python.txt |
Q:
Standard Django way for letting users edit rich content
I have a Django website in which I want site administrators to be able to edit rich content.
Suppose we're talking about an organizational info page, which might include some pictures, and some links, where the page is not as structured as a news page (which ... | Standard Django way for letting users edit rich content | I have a Django website in which I want site administrators to be able to edit rich content.
Suppose we're talking about an organizational info page, which might include some pictures, and some links, where the page is not as structured as a news page (which updates with news pieces every few days), but still needs the... | [
"Use one of the existing rich-text editors\nThe lightest weight would be to use something at the js level like DojoEditor: \nhttp://code.djangoproject.com/wiki/AddDojoEditor\nSee also this thread: \nReplace textarea with rich text editor in Django Admin?\n",
"For what you're describing I'd use flatpages, which is... | [
4,
1
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0000765066_django_django_admin_django_models_python.txt |
Q:
Is this Python code thread safe?
import time
import threading
class test(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.doSkip = False
self.count = 0
def run(self):
while self.count<9:
self.work()
def skip(self):
self.doSkip = True... | Is this Python code thread safe? | import time
import threading
class test(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.doSkip = False
self.count = 0
def run(self):
while self.count<9:
self.work()
def skip(self):
self.doSkip = True
def work(self):
self.count... | [
"Thread-safe in which way? I don't see any part you might want to protect here.\nskip may reset the doSkip at any time, so there's not much point in locking it. You don't have any resources that are accessed at the same time - so IMHO nothing can be corrupted / unsafe in this code.\nThe only part that might run dif... | [
2,
1,
0,
0,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0000762448_multithreading_python.txt |
Q:
mod_wsgi/python sys.path.exend problems
I'm working on a mod_wsgi script.. at the beginning is:
sys.path.extend(map(os.path.abspath, ['/media/server/www/webroot/']))
But I've noticed, that every time I update the script the sys.path var keeps growing with duplicates of this extension:
['/usr/lib64/python25.zip'
'... | mod_wsgi/python sys.path.exend problems | I'm working on a mod_wsgi script.. at the beginning is:
sys.path.extend(map(os.path.abspath, ['/media/server/www/webroot/']))
But I've noticed, that every time I update the script the sys.path var keeps growing with duplicates of this extension:
['/usr/lib64/python25.zip'
'/usr/lib64/python2.5'
'/usr/lib64/python2.5/p... | [
"No need to worry about checking or using abspath yourself. Use the ‘site’ module's built-in addsitedir function. It will take care of these issues and others (eg. pth files) automatically:\nimport site\nsite.addsitedir('/media/server/www/webroot/')\n\n(This function is only documented in Python 2.6, but it has pre... | [
7,
3,
2
] | [] | [] | [
"apache",
"mod_wsgi",
"python"
] | stackoverflow_0000764081_apache_mod_wsgi_python.txt |
Q:
Python Collections.DefaultDict Sort + Output Top X Custom Class Object
Problem: I need to output the TOP X Contributors determined by the amount of messages posted.
Data: I have a collection of the messages posted. This is not a Database/SQL question by the sample query below just give an overview of the code.
twe... | Python Collections.DefaultDict Sort + Output Top X Custom Class Object | Problem: I need to output the TOP X Contributors determined by the amount of messages posted.
Data: I have a collection of the messages posted. This is not a Database/SQL question by the sample query below just give an overview of the code.
tweetsSQL = db.GqlQuery("SELECT * FROM TweetModel ORDER BY date_created DESC")
... | [
"Use heapq.nlargest() instead of sorted(), for efficiency; it's what it's for. I don't know the answer about the DB part of your question.\n",
"I think your job would be a lot easier if you change the SQL query to something like: \nSELECT top 100 userId FROM TweetModel GROUP BY userId ORDER BY count(*)\n\nI would... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000766546_python.txt |
Q:
Attributes not available when overwriting __init__?
I'm trying to overwrite a __init__ method, but when I call the super method the attributes created in that method are not available.
I can see that it's not an inheritance problem since class B still has the attributes available.
I think the code sample will expl... | Attributes not available when overwriting __init__? | I'm trying to overwrite a __init__ method, but when I call the super method the attributes created in that method are not available.
I can see that it's not an inheritance problem since class B still has the attributes available.
I think the code sample will explain it better :-)
Python 2.5.2 (r252:60911, Oct 5 2008, ... | [
"Your call to the superclass needs to use its own type\nsuper(D, self).__init__(*args,**kwargs)\n\nrather than \nsuper(A...\n\nI believe calling super(A, self).__init__ will call the superclass of A, which is object. Rather, you want to call the superclass of D, which is A.\n",
"You're using super() incorrectly. ... | [
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0000767241_python.txt |
Q:
Some internals of Django auth middleware
In the django.contrib.auth middleware
I see the code:
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "requires session middleware"
request.__class__.user = LazyUser()
return None
P... | Some internals of Django auth middleware | In the django.contrib.auth middleware
I see the code:
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "requires session middleware"
request.__class__.user = LazyUser()
return None
Please avdise me why such a form
request._... | [
"LazyUser is descriptor-class. According to documentation it can be only class attribute not instance one:\n\nFor instance, a.x has a lookup chain starting with a.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses.\n\n"
] | [
9
] | [
"This is going to affect how requests are created. All such instances will have their user attribute as that particular LazuUser without the need to make that change after each individual request is instantiated.\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0000766733_django_python.txt |
Q:
Current working directory no longer inherited from calling process from python 2.5 onwards?
I updated my python version on windows 2003 server from 2.4 to 2.5.
In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this:
import sub1
as long as the calling script main.py that lives ... | Current working directory no longer inherited from calling process from python 2.5 onwards? | I updated my python version on windows 2003 server from 2.4 to 2.5.
In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this:
import sub1
as long as the calling script main.py that lives in c:\application was started like this:
c:\application\subdir>python ..\main.py
But in 2.5 it n... | [
"to import sub.py you need to:\nimport sub # not sub1\n\n",
"You can check where python searches for modules. A list of locations is contained in variable sys.path.\nYou can create a simple script (or execute it interactively) that shows this:\nimport sys\n\nfor x in sys.path:\n print x\n\nBy default, pytho... | [
4,
2,
1,
1,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0000767531_import_python.txt |
Q:
Estimating zip size/creation time
I need to create ZIP archives on demand, using either Python zipfile module or unix command line utilities.
Resources to be zipped are often > 1GB and not necessarily compression-friendly.
How do I efficiently estimate its creation time / size?
A:
Extract a bunch of small parts... | Estimating zip size/creation time | I need to create ZIP archives on demand, using either Python zipfile module or unix command line utilities.
Resources to be zipped are often > 1GB and not necessarily compression-friendly.
How do I efficiently estimate its creation time / size?
| [
"Extract a bunch of small parts from the big file. Maybe 64 chunks of 64k each. Randomly selected.\nConcatenate the data, compress it, measure the time and the compression ratio. Since you've randomly selected parts of the file chances are that you have compressed a representative subset of the data.\nNow all you h... | [
16,
3,
1,
0
] | [] | [] | [
"python",
"time_estimation",
"zip"
] | stackoverflow_0000767684_python_time_estimation_zip.txt |
Q:
how to send mail in python ssmtp vs smtplib
I need to send email in delbian linux. How to send? I run my server on 256 MB linux box and I heard postfix and sendmail is overkill.
Recently I came across the ssmtp, that seems to be an executable, needs to be executed as a process and called through python using os mo... | how to send mail in python ssmtp vs smtplib | I need to send email in delbian linux. How to send? I run my server on 256 MB linux box and I heard postfix and sendmail is overkill.
Recently I came across the ssmtp, that seems to be an executable, needs to be executed as a process and called through python using os modules.
alternatively, python already provides smt... | [
"In a Python program, there is no advantage.\nThe only purpose of ssmtp is to wrap the SMTP protocol in the sendmail API. That is, it provides a program /usr/sbin/sendmail that accepts the same options, arguments, and inputs as the full-blown sendmail (though most of the options do nothing); but behind the scenes, ... | [
5,
2,
1
] | [] | [] | [
"python",
"smtplib",
"ssmtp"
] | stackoverflow_0000764778_python_smtplib_ssmtp.txt |
Q:
Blocks of code in Python
Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python?
What are the language constructs that exist in Python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does Python lack such constructs?
I have so far understood the lambda th... | Blocks of code in Python | Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python?
What are the language constructs that exist in Python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does Python lack such constructs?
I have so far understood the lambda thing; it is only one-line, but ... | [
"Functions are the first-class members in Python:\ndef add(x, y):\n return x + y\n\na = add # Bind\nb = a(34, 1) # Call\n\nSo you can pass functions around all you want. You can do the same with any callable object in Python.\n",
"lambda is the closest equivalent to a Ruby block, and the restricti... | [
10,
3,
3,
0
] | [] | [] | [
"lambda",
"python",
"ruby"
] | stackoverflow_0000767519_lambda_python_ruby.txt |
Q:
Markup-based GUI for python
I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them.
I think GUI design should be d... | Markup-based GUI for python | I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them.
I think GUI design should be done in a separate text-based file... | [
"You can try Mozilla's XUL. It supports Python via XPCOM.\nSee this project: pyxpcomext\nXUL isn't compiled, it is packaged and loaded at runtime. Firefox and many other great applications use it, but most of them use Javascript for scripting instead of Python. There are one or 2 using Python though.\n",
"You sho... | [
7,
2,
2,
2,
1
] | [
"It's XML, not Python, but look at Open Laszlo\n",
"windows?\nyou can use the WinForms editor in Visual Studio and then talk to the assembly from IronPython.\n"
] | [
-1,
-2
] | [
"markup",
"python",
"user_interface"
] | stackoverflow_0000364327_markup_python_user_interface.txt |
Q:
How do I prevent execution of arbitrary commands from a Django app making system calls?
I have a Django application I'm developing that must make a system call to an external program on the server. In creating the command for the system call, the application takes values from a form and uses them as parameters for... | How do I prevent execution of arbitrary commands from a Django app making system calls? | I have a Django application I'm developing that must make a system call to an external program on the server. In creating the command for the system call, the application takes values from a form and uses them as parameters for the call. I suppose this means that one can essentially use bogus parameters and write arbit... | [
"Based on my understanding of the question, I'm assuming you aren't letting the users specify commands to run on the shell, but just arguments to those commands. In this case, you can avoid shell injection attacks by using the subprocess module and not using the shell (i.e. specify use the default shell=False para... | [
11,
6,
4,
3,
0
] | [] | [] | [
"django",
"python",
"security"
] | stackoverflow_0000768677_django_python_security.txt |
Q:
Overriding class member variables in Python (Django/Satchmo)
I'm using Satchmo and Django and am trying to extend Satchmo's Product model. I'd like to make one of the fields in Satchmo's Product model have a default value in the admin without changing Satchmo's source code. Here is an abbreviated version of Satc... | Overriding class member variables in Python (Django/Satchmo) | I'm using Satchmo and Django and am trying to extend Satchmo's Product model. I'd like to make one of the fields in Satchmo's Product model have a default value in the admin without changing Satchmo's source code. Here is an abbreviated version of Satchmo's Product model:
class Product(models.Model):
site = model... | [
"For two reasons, firstly the way you are trying to override a class variable just isn't how it works in Python. You just define it in the class as normal, the same way that def __init__(self): is overriding the super-class initializer. But, Django model inheritance simply doesn't support this. If you want to add c... | [
1,
1
] | [
"You can't change the superclass from a subclass. \nYou have the source. Use subversion. Make the change. When Satchmo is updated merge the updates around your change. \n"
] | [
-2
] | [
"django",
"python",
"satchmo"
] | stackoverflow_0000762165_django_python_satchmo.txt |
Q:
What is the most Pythonic way to provide a fall-back value in an assignment?
In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:
my $x = undef;
my $y = 2;
my $a = $x || $y;
After this,
$a == 2
Is there a concise ... | What is the most Pythonic way to provide a fall-back value in an assignment? | In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:
my $x = undef;
my $y = 2;
my $a = $x || $y;
After this,
$a == 2
Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...
if x ... | [
"Since 2.5:\nIf you want to fall back only on None:\na = x if x is not None else y \n\nIf you want to fall back also on empty string, false, 0 etc.: \na = x if x else y \n\nor\na = x or y \n\n\nAs for undefined (as never defined, a.k.a. not bound):\ntry:\n a = x \nexcept NameError:\n a = y\n\nor a bit more hackis... | [
57,
6,
4,
3,
1,
1,
0,
0
] | [
"If it's an argument to a function you can do this:\ndef MyFunc( a=2 ):\n print \"a is %d\"%a\n\n>>> MyFunc()\n...a is 2\n>>> MyFunc(5)\n...a is 5\n\n[Edit] For the downvoters.. the if/else bit is unnecessary for the solution - just added to make the results clear. Edited it to remove the if statement if that ma... | [
-1
] | [
"python"
] | stackoverflow_0000768175_python.txt |
Q:
How to find all built in libraries in Python
I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.
What's included, and where can I get ... | How to find all built in libraries in Python | I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.
What's included, and where can I get other good quality libraries from?
| [
"Firstly, the python libary reference gives a blow by blow of what's actually included. And the global module index contains a neat, alphabetized summary of those same modules. If you have dependencies on a library, you can trivially test for the presence with a construct like:\ntry:\n import foobar\nexcept:\n... | [
17,
12,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000329498_python.txt |
Q:
How do I use AND in a Django filter?
How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.
For example the following SQL query does exactly that when I run it on mysql database:
select * from myapp_question
where ((... | How do I use AND in a Django filter? | How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.
For example the following SQL query does exactly that when I run it on mysql database:
select * from myapp_question
where ((question like '%software%') and (question ... | [
"For thoroughness sake, let's just mention the Q object method:\nfrom django.db.models import Q\ncriterion1 = Q(question__contains=\"software\")\ncriterion2 = Q(question__contains=\"java\")\nq = Question.objects.filter(criterion1 & criterion2)\n\nNote the other answers here are simpler and better adapted for your u... | [
165,
112,
16
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000769843_django_python.txt |
Q:
Multiple projects from one setup.py?
My current setup.py (using setuptools) installs two things, one is tvdb_api (an API wrapper), the other is tvnamer (a command line script)
I wish to make the two available separately, so a user can do..
easy_install tvdb_api
..to only get the API wrapper, or..
easy_install tvn... | Multiple projects from one setup.py? | My current setup.py (using setuptools) installs two things, one is tvdb_api (an API wrapper), the other is tvnamer (a command line script)
I wish to make the two available separately, so a user can do..
easy_install tvdb_api
..to only get the API wrapper, or..
easy_install tvnamer
..to install tvnamer (and tvdb_api, ... | [
"setup.py is just a regular Python file, which by convention sets up packages. By convention, setup.py contains a call to the setuptools or distutils setup() function. If you want to use one setup.py for two packages, you can call a different setup() function based on a command-line argument:\nimport sys\nif len(s... | [
11
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0000769793_python_setuptools.txt |
Q:
The lines that stand out in a file, but aren't exact duplicates
I'm combing a webapp's log file for statements that stand out.
Most of the lines are similar and uninteresting. I'd pass them through Unix uniq, however that filters nothing, as all the lines are slightly different: they all have a different timestamp... | The lines that stand out in a file, but aren't exact duplicates | I'm combing a webapp's log file for statements that stand out.
Most of the lines are similar and uninteresting. I'd pass them through Unix uniq, however that filters nothing, as all the lines are slightly different: they all have a different timestamp, similar statements might print a different user ID, etc.
What's a w... | [
"Define \"notably different\". Then have a look at \"edit distance\" measures.\n",
"You could try a bit of code that counts words, and then sorts lines by those having the least common words. \nIf that doesn't do the trick, you can add in some smarts to filter out time stamps and numbers. \nYour problem is simil... | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"algorithm",
"grep",
"nlp",
"python",
"unix"
] | stackoverflow_0000769775_algorithm_grep_nlp_python_unix.txt |
Q:
Installing Django on Shared Server: No module named MySQLdb?
I'm getting this error
Traceback (most recent call last):
File "/home/<username>/flup/server/fcgi_base.py", line 558, in run
File "/home/<username>/flup/server/fcgi_base.py", line 1116, in handler
File "/home/<username>/python/django/django/core/ha... | Installing Django on Shared Server: No module named MySQLdb? | I'm getting this error
Traceback (most recent call last):
File "/home/<username>/flup/server/fcgi_base.py", line 558, in run
File "/home/<username>/flup/server/fcgi_base.py", line 1116, in handler
File "/home/<username>/python/django/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_res... | [
"You are missing the python-mysql db driver on your python path.\nsee if you can figure out the pythonpath WSGI is seeing... which can be different from what you are experiencing in shell\n",
"Is it possible that you have the wrong DATABASE_ENGINE setting in your settings.py? It should be mysql and not mysqldb th... | [
2,
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0000770904_django_mysql_python.txt |
Q:
What is the best secure way to allow a user to delete a model instance that they added to the db?
I would like to give users access to delete a model instance that they added to the db. In the django docs it says allowing someone to delete from the template is not a good practice. Is there a secure way to let a us... | What is the best secure way to allow a user to delete a model instance that they added to the db? | I would like to give users access to delete a model instance that they added to the db. In the django docs it says allowing someone to delete from the template is not a good practice. Is there a secure way to let a user click a "delete this" link from the template and remove that model instance? How should I go about d... | [
"Check out this question for discussion related to what you are asking about.\nEssentially, when you normally click on a link on the page the browser makes a GET request to the server to get the next page's contents. Just like there is a lot of pushing towards semantically relevant CSS layouts, it is also important... | [
7,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000770427_django_python.txt |
Q:
importing gaeutilities or any other module by dev_appserver
I'm developing a gae application on a windows machine. to have session handling I downloaded gaeutilities and added its path (C:\Python25\Lib\site-packages\gaeutilities-1.2.1) to the registry ("PythonPath" item under python25).
in my code this is how I im... | importing gaeutilities or any other module by dev_appserver | I'm developing a gae application on a windows machine. to have session handling I downloaded gaeutilities and added its path (C:\Python25\Lib\site-packages\gaeutilities-1.2.1) to the registry ("PythonPath" item under python25).
in my code this is how I import the gaeutilities Session class:
from appengine_utilities.ses... | [
"Strange.\nI would start troubleshooting by making 100% sure that the sys.path that dev_appserver.py uses does include C:\\Python25\\Lib\\site-packages\\gaeutilities-1.2.1.\nI suggest you display sys.path in a HTML view served by dev_appserver.py.\nCheck permissions on gaeutilities-1.2.1 directory and subdirectorie... | [
1
] | [] | [] | [
"google_app_engine",
"import",
"python"
] | stackoverflow_0000770385_google_app_engine_import_python.txt |
Q:
GStrings in Python
Groovy has a concept of GStrings. I can write code like this:
def greeting = 'Hello World'
println """This is my first program ${greeting}"""
I can access the value of a variable from within the String.
How can I do this in Python?
--
Thanks
A:
In Python, you have to explicitely pass a dicti... | GStrings in Python | Groovy has a concept of GStrings. I can write code like this:
def greeting = 'Hello World'
println """This is my first program ${greeting}"""
I can access the value of a variable from within the String.
How can I do this in Python?
--
Thanks
| [
"In Python, you have to explicitely pass a dictionary of possible variables, you cannot access arbitrary \"outside\" variables from within a string. But, you can use the locals() function that returns a dictionary with all variables of the local scope.\nFor the actual replacement, there are many ways to do it (how ... | [
5,
3,
1,
1,
1
] | [] | [] | [
"gstring",
"python"
] | stackoverflow_0000771312_gstring_python.txt |
Q:
Python + PHP + Lighttpd?
I've set up a few web servers in my day, but I'm not sure how they work internally. I'm setting up a new environment for myself and I'm interested in configuring my lighttpd server to support both PHP and Python. Is this possible?
A:
Yes, this is possible. Here you can find a sample conf... | Python + PHP + Lighttpd? | I've set up a few web servers in my day, but I'm not sure how they work internally. I'm setting up a new environment for myself and I'm interested in configuring my lighttpd server to support both PHP and Python. Is this possible?
| [
"Yes, this is possible. Here you can find a sample configuration.\nfastcgi.server = (\n\".php\" => ((\n\"bin-path\" => \"/usr/bin/php5-cgi\",\n\"socket\" => \"/tmp/php.socket\"\n)),\n\"django.fcgi\" => (\n\"main\" => (\n\"host\" => \"127.0.0.1\",\n\"port\" => 9090, #set the port numbers to what-eva you want\n),\n),... | [
3,
1
] | [] | [] | [
"configure",
"lighttpd",
"php",
"python"
] | stackoverflow_0000771341_configure_lighttpd_php_python.txt |
Q:
pyqt4 and pyserial
I want to do an app constantly watching the serial port and changing the user interface according to the input received from the port. I've managed to read lines from the port with pyserial under Linux, but I'm not sure how to do this in a regular fashion: create a separate thread and check for ... | pyqt4 and pyserial | I want to do an app constantly watching the serial port and changing the user interface according to the input received from the port. I've managed to read lines from the port with pyserial under Linux, but I'm not sure how to do this in a regular fashion: create a separate thread and check for input on a timer event? ... | [
"You won't miss any bytes, any pending input is buffered.\nYou have several options:\n\nuse a thread that polls the serial port with PySerial/inWaiting() \nUse a timer in the main thread that polls the serial port with PySerial/inWaiting.\nfind the handle of the port and pass it to QSocketNotifier. This works only ... | [
4
] | [] | [] | [
"linux",
"pyserial",
"python",
"qt",
"serial_port"
] | stackoverflow_0000771988_linux_pyserial_python_qt_serial_port.txt |
Q:
How to add a second bouncing ball to the window?
I have coded an animation (in python) for a beach ball to bounce around a screen. I now wish to add a second ball to the window, and when the two collide for them to bounce off each other.
So far, my attempts at this have been unsuccessful. Any ideas how to do thi... | How to add a second bouncing ball to the window? | I have coded an animation (in python) for a beach ball to bounce around a screen. I now wish to add a second ball to the window, and when the two collide for them to bounce off each other.
So far, my attempts at this have been unsuccessful. Any ideas how to do this? The code I have so far is below.
import pygame
imp... | [
"Here's a very basic restructure of your code. It could still be tidied up a lot, but it should show you how you can use instances of the class.\nimport pygame\nimport random\nimport sys\n\nclass Ball:\n def __init__(self,X,Y):\n self.velocity = [1,1]\n self.ball_image = pygame.image.load ('Beachba... | [
7,
3
] | [] | [] | [
"animation",
"pygame",
"python"
] | stackoverflow_0000771992_animation_pygame_python.txt |
Q:
Running python code from standard Cocoa application
I have an XCode project built as a Cocoa single document application (it's not a Python-Cocoa application, that is not what I want).
All the documentation I found assumes I want to create a Cocoa application with code written in Python and this is not the case - ... | Running python code from standard Cocoa application | I have an XCode project built as a Cocoa single document application (it's not a Python-Cocoa application, that is not what I want).
All the documentation I found assumes I want to create a Cocoa application with code written in Python and this is not the case - I want a standard Cocoa application that calls a method o... | [
"A google search for embed python objective C, returns a few links that might be of interest, in particular:\n\nhttp://blog.alienoverlord.com/?p=14\nhttp://blog.tlensing.org/2008/11/04/embedding-python-in-a-cocoa-application/\n\n"
] | [
7
] | [] | [] | [
"cocoa",
"macos",
"pyobjc",
"python"
] | stackoverflow_0000772112_cocoa_macos_pyobjc_python.txt |
Q:
Oracle / Python Converting to string -> HEX (for RAW column) -> varchar2
I have a table with a RAW column for holding an encrypted string.
I have the PL/SQL code for encrypting from plain text into this field.
I wish to create a trigger containg the encryption code.
I wish to 'misuse' the RAW field to pass the pla... | Oracle / Python Converting to string -> HEX (for RAW column) -> varchar2 | I have a table with a RAW column for holding an encrypted string.
I have the PL/SQL code for encrypting from plain text into this field.
I wish to create a trigger containg the encryption code.
I wish to 'misuse' the RAW field to pass the plain text into the trigger. (I can't modify the schema, for example to add anoth... | [
"Do you have to encode to hex?\nI think there is a package (utl_encode) available for PL/SQL to decode Base64 for instance, you could use that? \n"
] | [
2
] | [] | [] | [
"oracle",
"python"
] | stackoverflow_0000772518_oracle_python.txt |
Q:
What does the 'shell' argument in subprocess mean on Windows?
The docs for the subprocess module state that 'If shell is True, the specified command will be executed through the shell'. What does this mean in practice, on a Windows OS?
A:
It means that the command will be executed using the program specified in ... | What does the 'shell' argument in subprocess mean on Windows? | The docs for the subprocess module state that 'If shell is True, the specified command will be executed through the shell'. What does this mean in practice, on a Windows OS?
| [
"It means that the command will be executed using the program specified in the COMSPEC environment variable. Usually cmd.exe.\nTo be exact, subprocess calls the CreateProcess windows api function, passing \"cmd.exe /c \" + args as the lpCommandLine argument. \nIf shell==False, the lpCommandLine argument to CreatePr... | [
3,
1,
0,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0000771816_python_subprocess.txt |
Q:
How to create a password protected zipfile with python?
Since python2.6, it's now easier to extract data from a password protected zip. But how to create a password protected zipfile in pure python ?
A:
I've looked for this in the past and been unsuccessful. (I'd love to see a solution get posted!)
One option i... | How to create a password protected zipfile with python? | Since python2.6, it's now easier to extract data from a password protected zip. But how to create a password protected zipfile in pure python ?
| [
"I've looked for this in the past and been unsuccessful. (I'd love to see a solution get posted!)\nOne option is a commercial package from chilkatsoft that will do this, but at $150. Makes sense if you are doing a commercial app, but tough to swallow otherwise.\nI wound up calling out to the system for my solutio... | [
3
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0000772814_python_zip.txt |
Q:
Python +sockets
i have to create connecting server<=>client. I use this code:
Server:
import socket
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
... | Python +sockets | i have to create connecting server<=>client. I use this code:
Server:
import socket
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
... | [
"The question is a little confusing, but I will try to help out. Basically, if the port (50007) is blocked on the server machine by a firewall, you will NOT be able to make a tcp connection to it from the client. That is the purpose of the firewall. A lot of protocols (SIP and bittorrent for example) do use firewal... | [
7,
2
] | [] | [] | [
"ports",
"python",
"sockets"
] | stackoverflow_0000773869_ports_python_sockets.txt |
Q:
classmethod for Tkinter-Monitor-Window
I would like to realise a monitor window that reports the user about ongoing computations. To do so I wrote a little class. But as I would like to use it accross different modules in an easy fashion I thought to implement it with classmethods. This allows to use it in the fol... | classmethod for Tkinter-Monitor-Window | I would like to realise a monitor window that reports the user about ongoing computations. To do so I wrote a little class. But as I would like to use it accross different modules in an easy fashion I thought to implement it with classmethods. This allows to use it in the following way without instances:
from MonitorMo... | [
"You don't need lots of classmethods just to make it easy to use an object across multiple modules.\nInstead consider making an instance at module import time as shown here:\nimport Tkinter\n\nclass Monitor(object):\n\n def __init__(self):\n self.mw = Tkinter.Tk()\n self.mw.title(\"Messages by NeuronSimulati... | [
3
] | [] | [] | [
"class_method",
"python",
"tkinter"
] | stackoverflow_0000768474_class_method_python_tkinter.txt |
Q:
Good python library for generating audio files?
Can anyone recommend a good library for generating an audio file, such as mp3, wav, or even midi, from python?
I've seen recommendations for working with the id tags (song name, artist, etc) in mp3 files, but this is not my goal.
A:
See http://wiki.python.org/moin/... | Good python library for generating audio files? | Can anyone recommend a good library for generating an audio file, such as mp3, wav, or even midi, from python?
I've seen recommendations for working with the id tags (song name, artist, etc) in mp3 files, but this is not my goal.
| [
"See http://wiki.python.org/moin/Audio/ and http://wiki.python.org/moin/PythonInMusic, maybe some of the projects listed there can be of help.\nAlso, Google is your friend.\n",
"I've never used it, but check out ounk.\n"
] | [
9,
0
] | [] | [] | [
"audio",
"mp3",
"python"
] | stackoverflow_0000045385_audio_mp3_python.txt |
Q:
(Python) socket.gaierror: [Errno 11001] getaddrinfo failed
I'm not sure whats wrong with this code I keep getting that socket.gaierror error ;\ .
import sys
import socket
import random
filename = "whoiservers.txt"
server_name = random.choice(list(open(filename)))
print "connecting to %s..." % server_name
s = s... | (Python) socket.gaierror: [Errno 11001] getaddrinfo failed | I'm not sure whats wrong with this code I keep getting that socket.gaierror error ;\ .
import sys
import socket
import random
filename = "whoiservers.txt"
server_name = random.choice(list(open(filename)))
print "connecting to %s..." % server_name
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((serv... | [
"I think the problem is a newline at the end of server_name.\nIf the format of your file whoiservers.txt is one hostname on each line then you need to strip the newline at the end of the hostname before passing it to s.connect()\nSo, for example, change the open line to:\nserver_name = random.choice(list(open(filen... | [
7,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0000771247_python_sockets.txt |
Q:
SFTP listing directory
I'm trying to make a connection to a secure sftp site, however I'm not able to list the directory,however, it's possible to connect using python "expect" or php"ssh2_connect" but it gives me the following mesg: Received disconnect from xx.xx.xx.
If I use a GUI appliction like winscp I'm able... | SFTP listing directory | I'm trying to make a connection to a secure sftp site, however I'm not able to list the directory,however, it's possible to connect using python "expect" or php"ssh2_connect" but it gives me the following mesg: Received disconnect from xx.xx.xx.
If I use a GUI appliction like winscp I'm able to go to the sftp server an... | [
"You can do this easily with paramiko, checkout SFTP with Python\n"
] | [
3
] | [] | [] | [
"php",
"python",
"sftp"
] | stackoverflow_0000774039_php_python_sftp.txt |
Q:
Business rules for calculating prices
The business I work for is an on-line retailer, I'm currently working on a project that among other things involves calculating the customer prices for products. We will probably create a service that looks something like...
public interface IPriceService
{
decimal Calculate... | Business rules for calculating prices | The business I work for is an on-line retailer, I'm currently working on a project that among other things involves calculating the customer prices for products. We will probably create a service that looks something like...
public interface IPriceService
{
decimal CalculateCustomerPrice(ISupplierPriceProvider produc... | [
"It definitely sounds like a sane idea to me. You can trivially access CLR internals (objects and return values) from IronPython, I don't know about IronRuby. Chapters 1 and 7 of IronPython in Action are available online and would probably be helpful. There is also a \"hello world\" style tutorial available at t... | [
1
] | [] | [] | [
"dynamic_language_runtime",
"python",
"ruby",
"rules",
"scripting"
] | stackoverflow_0000774245_dynamic_language_runtime_python_ruby_rules_scripting.txt |
Q:
Python scripted mp3 database, with a php front end
So, here's the deal. I am attempting to write a quick python script that reads the basic id3 tags from an mp3 (artist, album, songname, genre, etc). The python script will use most likely the mutagen library (unless you know of a better one). I'm not sure how t... | Python scripted mp3 database, with a php front end | So, here's the deal. I am attempting to write a quick python script that reads the basic id3 tags from an mp3 (artist, album, songname, genre, etc). The python script will use most likely the mutagen library (unless you know of a better one). I'm not sure how to recursively scan through a directory to get each mp3's... | [
"To get started with extracting ID3 tags in Python, there's a module for that.\nfrom ID3 import ID3\n\nmp3_filepath = r'/music/song.mp3'\nid3_data = ID3(mp3_filepath)\nprint 'Artist:', id3_data['ARTIST']\nprint 'Title:', id3_data['TITLE']\n\nMore info on ID3 module.\nIf you want to recursively search a directory fo... | [
4
] | [] | [] | [
"database",
"id3",
"mp3",
"php",
"python"
] | stackoverflow_0000774502_database_id3_mp3_php_python.txt |
Q:
Programmatically taking screenshots in windows without the application noticing
There are various ways to take screenshots of a running application in Windows. However, I hear that an application can be tailored such that it can notice when a screenshot is being taken of it, through some windows event handlers per... | Programmatically taking screenshots in windows without the application noticing | There are various ways to take screenshots of a running application in Windows. However, I hear that an application can be tailored such that it can notice when a screenshot is being taken of it, through some windows event handlers perhaps? Is there any way of taking a screenshot such that it is impossible for the appl... | [
"There will certainly be no protection against a screenshot taken with a digital camera.\n",
"> I hear that an application can be tailored such that it can notice when a screenshot is being taken of it\nComplete nonsense.\nDon't repeat what kids say...\nRead MSDN about screenshots.\n",
"Do you have a particular... | [
6,
3,
2,
0
] | [] | [] | [
"events",
"operating_system",
"python",
"screenshot",
"windows"
] | stackoverflow_0000767212_events_operating_system_python_screenshot_windows.txt |
Q:
how can I decode the REG_BINARY value HKLM\Software\Microsoft\Ole\DefaultLaunchPermission to see which users have permission?
I am trying to find a way to decode the REG_BINARY value for "HKLM\Software\Microsoft\Ole\DefaultLaunchPermission" to see which users have permissions by default, and if possible, a method ... | how can I decode the REG_BINARY value HKLM\Software\Microsoft\Ole\DefaultLaunchPermission to see which users have permission? | I am trying to find a way to decode the REG_BINARY value for "HKLM\Software\Microsoft\Ole\DefaultLaunchPermission" to see which users have permissions by default, and if possible, a method in which I can also append other users by their username.
At work we make use of DCOM and for the most part we always give the sam... | [
"We came across similar issues when installing a COM server that was hosted by our .NET service, i.e. we wanted to programmatically alter the the COM ACLs in our install logic. I think you'll find that it's just a binary ACL format that you can manipulate in .NET using the class:\nSystem.Security.AccessControl.Comm... | [
3,
0
] | [] | [] | [
"binary",
"decode",
"python",
"registry",
"wmi"
] | stackoverflow_0000775365_binary_decode_python_registry_wmi.txt |
Q:
How do you transfer binary data with Python?
I'm working on a client-server program for the first time, and I'm feeling woefully inadequate on where to begin for what I'm doing.
I'm going to use Google Protocol Buffers to transfer binary data between my client and my server. I'm going to be using the Python varia... | How do you transfer binary data with Python? | I'm working on a client-server program for the first time, and I'm feeling woefully inadequate on where to begin for what I'm doing.
I'm going to use Google Protocol Buffers to transfer binary data between my client and my server. I'm going to be using the Python variant. The basic idea, as I understand, is that the ... | [
"Any time you're going to move binary data from one system to another there a couple of things to keep in mind.\nDifferent machines store the same information differently. This has implication both in memory and on the network. More info here (http://en.wikipedia.org/wiki/Endianness)\nBecause you're using python yo... | [
4,
3,
1,
0
] | [] | [] | [
"client_server",
"file",
"http",
"protocol_buffers",
"python"
] | stackoverflow_0000775482_client_server_file_http_protocol_buffers_python.txt |
Q:
Sorted collections: How do i get (extended) slices right?
How can I resolve this?
>>> class unslice:
... def __getitem__(self, item): print type(item), ":", item
...
>>> u = unslice()
>>> u[1,2] # using an extended slice
<type 'tuple'> : (1, 2)
>>> t = (1, 2)
>>> u[t] # or passing a plain tuple
<type 'tupl... | Sorted collections: How do i get (extended) slices right? | How can I resolve this?
>>> class unslice:
... def __getitem__(self, item): print type(item), ":", item
...
>>> u = unslice()
>>> u[1,2] # using an extended slice
<type 'tuple'> : (1, 2)
>>> t = (1, 2)
>>> u[t] # or passing a plain tuple
<type 'tuple'> : (1, 2)
Rational:
I'm currently overengineering a sorted... | [
"Since there is no way to differentiate between the calls u[x,y] and u[(x,y)], you should shift one of the two operations you are trying to define off to an actual method. You know, something named u.slice() or u.range() or u.getslice() or u.getrange() or something like that.\nActually, when writing my own program... | [
5,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000775490_python.txt |
Q:
How to catch POST using WSGIREF
I am trying to catch POST data from a simple form.
This is the first time I am playing around with WSGIREF and I can't seem to find the correct way to do this.
This is the form:
<form action="test" method="POST">
<input type="text" name="name">
<input type="submit"></form>
And the ... | How to catch POST using WSGIREF | I am trying to catch POST data from a simple form.
This is the first time I am playing around with WSGIREF and I can't seem to find the correct way to do this.
This is the form:
<form action="test" method="POST">
<input type="text" name="name">
<input type="submit"></form>
And the function that is obviously missing th... | [
"You should be reading responses from the server.\nFrom nosklo's answer to a similar problem: \"PEP 333 says you must read environ['wsgi.input'].\"\nTested code (adapted from this answer):\n\n Caveat: This code is for demonstrative purposes only. \n\n Warning: Try to avoid hard-coding paths or filenames.\nde... | [
5
] | [] | [] | [
"python",
"wsgi",
"wsgiref"
] | stackoverflow_0000775396_python_wsgi_wsgiref.txt |
Q:
Filetype information
I'm in the process of writing a python script, and I want to find out information about a file, such as for example a mime-type (or any useful depiction of what a file contains).
I've heard about python-magic, but I'm really looking for the solution that will allow me to find this information,... | Filetype information | I'm in the process of writing a python script, and I want to find out information about a file, such as for example a mime-type (or any useful depiction of what a file contains).
I've heard about python-magic, but I'm really looking for the solution that will allow me to find this information, without requiring the ins... | [
"I am not sure if you want to infer something from file content but if you want to know mime type from file extension mimetypes module will be sufficient\n>>> import mimetypes\n>>> mimetypes.init()\n>>> mimetypes.knownfiles\n['/etc/mime.types', '/etc/httpd/mime.types', ... ]\n>>> mimetypes.suffix_map['.tgz']\n'.tar... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0000775674_python.txt |
Q:
What is "generator object" in django?
Am using Django voting package and when I use the method get_top() in the shell, it returns something like "generator object at 0x022f7AD0, I've never seen anything like this before, how do you access it and what is it?
my code:
v=Vote.objects.get_top(myModel, limit=10, revers... | What is "generator object" in django? | Am using Django voting package and when I use the method get_top() in the shell, it returns something like "generator object at 0x022f7AD0, I've never seen anything like this before, how do you access it and what is it?
my code:
v=Vote.objects.get_top(myModel, limit=10, reversed=False)
print v
<generator object at 0x02... | [
"If you want a list, just call list() on your generator object.\nA generator object in python is something like a lazy list. The elements are only evaluated as soon as you iterate over them. (Thus calling list on it evaluates all of them.)\nFor example you can do:\n>>> def f(x):\n... print \"yay!\"\n... return 2 ... | [
21,
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0000776060_python.txt |
Q:
access eggs in python?
Is there any way to call an installed python egg from python code? I need to cal a sphinx documentation
generator from within a python code, and currently i'm doing it like this:
os.system( "sphinx-build.exe -b html c:\\src c:\\dst" )
This works, but requires some additional configuration: '... | access eggs in python? | Is there any way to call an installed python egg from python code? I need to cal a sphinx documentation
generator from within a python code, and currently i'm doing it like this:
os.system( "sphinx-build.exe -b html c:\\src c:\\dst" )
This works, but requires some additional configuration: 'scripts' folder
inside a pyt... | [
"So basically, you want to use Sphinx as a library?\nHere is what sphinx-build does:\nfrom pkg_resources import load_entry_point\n\nload_entry_point('Sphinx==0.5.1', 'console_scripts', 'sphinx-build')()\n\nLooking at entry-points.txt in the EGG-INFO directory, notice that the sphinx-build entry point is the sphinx.... | [
3,
1
] | [] | [] | [
"egg",
"python"
] | stackoverflow_0000775880_egg_python.txt |
Q:
fastest way to store comment data python
Hi I have a small comment shoutbox type cgi process running on a server and currently when someone leaves a comment I simply format that comment into html i.e
<p class="title">$title</p>
<p class="comment">$comment</p>
and store in a flat file.
Would it be faster and accept... | fastest way to store comment data python | Hi I have a small comment shoutbox type cgi process running on a server and currently when someone leaves a comment I simply format that comment into html i.e
<p class="title">$title</p>
<p class="comment">$comment</p>
and store in a flat file.
Would it be faster and acceptably low in LOC to reimplement the storage in ... | [
"If a flat file is fast enough, then go with that, since it's very simple and accessible. Storing as XML and JSON but still using a flat file probably is very comparable in performance.\nYou might want to consider (ignore this if you just left it out of your question) sanitizing/filtering the text, so that users ca... | [
3,
1,
1
] | [] | [] | [
"json",
"python",
"xml"
] | stackoverflow_0000777090_json_python_xml.txt |
Q:
Efficiently determining if a business is open or not based on store hours
Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses.
I have the open and close times for every business for every day of the week
Let's assume a bu... | Efficiently determining if a business is open or not based on store hours | Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses.
I have the open and close times for every business for every day of the week
Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour
I'm assu... | [
"If you are willing to just look at single week at a time, you can canonicalize all opening/closing times to be set numbers of minutes since the start of the week, say Sunday 0 hrs. For each store, you create a number of tuples of the form [startTime, endTime, storeId]. (For hours that spanned Sunday midnight, you'... | [
8,
5,
4,
3,
1,
0,
0
] | [] | [] | [
"mysql",
"performance",
"python",
"solr"
] | stackoverflow_0000775161_mysql_performance_python_solr.txt |
Q:
Django Form values without HTML escape
I need to set the Django forms.ChoiceField to display the currency symbols. Since django forms escape all the HTML ASCII characters, I can't get the $ ( € ) or the £ ( £ ) to display the currency symbol.
<select id="id_currency" name="currency">
<option value="... | Django Form values without HTML escape | I need to set the Django forms.ChoiceField to display the currency symbols. Since django forms escape all the HTML ASCII characters, I can't get the $ ( € ) or the £ ( £ ) to display the currency symbol.
<select id="id_currency" name="currency">
<option value="&#36;">$</option>
<option value=... | [
"You can use \"safe\" in the template or \"mark_safe\" in the view,\nturn off autoescaping in the template, \nor use Unicode characters instead of HTML entities in your form.\nUsing mark_safe\nfrom django.utils.safestring import mark_safe\n\ncurrencies = ((mark_safe('$'), mark_safe('$')), \n (m... | [
9
] | [] | [] | [
"currency",
"django_forms",
"python",
"symbols"
] | stackoverflow_0000777458_currency_django_forms_python_symbols.txt |
Q:
Qt-style documentation using Doxygen?
How do I produce Qt-style documentation (Trolltech's C++ Qt or Riverbank's PyQt docs) with Doxygen? I am documenting Python, and I would like to be able to improve the default function brief that it produces.
In particular, I would like to be able to see the return type (which... | Qt-style documentation using Doxygen? | How do I produce Qt-style documentation (Trolltech's C++ Qt or Riverbank's PyQt docs) with Doxygen? I am documenting Python, and I would like to be able to improve the default function brief that it produces.
In particular, I would like to be able to see the return type (which can be user specified) and the parameters ... | [
"Then just use Doxygen? This will get you started:\n\nThis is a guide for automatically\n generating documentation off of Python\n source code using Doxygen.\n\nObviously, since Python is not strongly typed, specifying the return type and the expected type of the parameters will be up to you, the documentation wr... | [
2,
1,
0,
0
] | [] | [] | [
"documentation",
"doxygen",
"python"
] | stackoverflow_0000776388_documentation_doxygen_python.txt |
Q:
How do I set up a model to use an AutoField with a legacy database in Python?
I have a legacy database with an integer set as a primary key. It was initially managed manually, but since we are wanting to move to django, the admin tool seemed to be the right place to start. I created the model and am trying to set ... | How do I set up a model to use an AutoField with a legacy database in Python? | I have a legacy database with an integer set as a primary key. It was initially managed manually, but since we are wanting to move to django, the admin tool seemed to be the right place to start. I created the model and am trying to set the primary key to be an autofield. It doesn't seem to be remembering the old id in... | [
"The DB is responsible for managing the value of the ID. If you want to use AutoField, you have to change the column in the DB to use that. Django is not responsible for managing the generated ID\n"
] | [
2
] | [] | [] | [
"autofield",
"django",
"oracle",
"python"
] | stackoverflow_0000777778_autofield_django_oracle_python.txt |
Q:
Directory Walker for Python
I am currently using the directory walker from Here
import os
class DirectoryWalker:
# a forward iterator that traverses a directory tree
def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
... | Directory Walker for Python | I am currently using the directory walker from Here
import os
class DirectoryWalker:
# a forward iterator that traverses a directory tree
def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
try:
file = self.f... | [
"Why do you want to do such boring thing yourself?\nfor path, directories, files in os.walk('.'):\n print 'ls %r' % path\n for directory in directories:\n print ' d%r' % directory\n for filename in files:\n print ' -%r' % filename\n\nOutput:\n'.'\n d'finction'\n d'.hg'\n -'setu... | [
14,
6,
1,
0
] | [] | [] | [
"directory_listing",
"python"
] | stackoverflow_0000775231_directory_listing_python.txt |
Q:
Python subprocess "object has no attribute 'fileno'" error
This code generates "AttributeError: 'Popen' object has no attribute 'fileno'" when run with Python 2.5.1
Code:
def get_blame(filename):
proc = []
proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE))
proc.append(Popen(['tr'... | Python subprocess "object has no attribute 'fileno'" error | This code generates "AttributeError: 'Popen' object has no attribute 'fileno'" when run with Python 2.5.1
Code:
def get_blame(filename):
proc = []
proc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE))
proc.append(Popen(['tr', '-s', r"'\040'"], stdin=proc[-1]), stdout=PIPE)
proc.appen... | [
"Three things\nFirst, your ()'s are wrong.\nSecond, the result of subprocess.Popen() is a process object, not a file.\nproc = []\nproc.append(Popen(['svn', 'blame', shellquote(filename)], stdout=PIPE))\nproc.append(Popen(['tr', '-s', r\"'\\040'\"], stdin=proc[-1]), stdout=PIPE)\n\nThe value of proc[-1] isn't the fi... | [
10,
3,
1
] | [
"looks like syntax error. except first append the rest are erroneous (review brackets).\n",
"Like S.Lott said, processing the text in Python is better.\nBut if you want to use the cmdline utilities, you can keep it readable by using shell=True:\ncmdline = r\"svn blame %s | tr -s '\\040' | tr '\\040' ';' | cut -d ... | [
-1,
-2
] | [
"pipe",
"python",
"subprocess"
] | stackoverflow_0000777996_pipe_python_subprocess.txt |
Q:
What's the difference between scgi and wsgi?
What's the difference between these two?
Which is better/faster/reliable?
A:
SCGI is a language-neutral means of connecting a front-end web server and a web application. WSGI is a Python-specific interface standard for web applications.
Though they both have roots in ... | What's the difference between scgi and wsgi? | What's the difference between these two?
Which is better/faster/reliable?
| [
"SCGI is a language-neutral means of connecting a front-end web server and a web application. WSGI is a Python-specific interface standard for web applications.\nThough they both have roots in CGI, they're rather different in scope and you could indeed quite reasonably use both at once, for example having a mod_scg... | [
27,
12,
11
] | [] | [] | [
"python",
"scgi",
"wsgi"
] | stackoverflow_0000257481_python_scgi_wsgi.txt |
Q:
How to query any constraint's target list without knowing the constraint type?
In Maya, I have a list of constraints gathered by the following code. I want to iterate the constraints and query the targets for each of them:
cons = ls(type='constraint')
for con in cons:
targets = constraint(query=True, targetLi... | How to query any constraint's target list without knowing the constraint type? | In Maya, I have a list of constraints gathered by the following code. I want to iterate the constraints and query the targets for each of them:
cons = ls(type='constraint')
for con in cons:
targets = constraint(query=True, targetList=True)
The problem, there is no general constraint command for manipulating all c... | [
"listConnections on the .target attr\nthe cleanup in mel:\nstring $cons[] = `ls -type \"constraint\"`;\nfor ( $con in $cons ){\n string $targetAttrString = ( $con+ \".target\" );\n string $connections[] = `listConnections $targetAttrString`;\n string $connectionsFlattened[] = stringArrayRemoveDuplicates($c... | [
2
] | [] | [] | [
"3d",
"constraints",
"maya",
"mel",
"python"
] | stackoverflow_0000778083_3d_constraints_maya_mel_python.txt |
Q:
Other than basic python syntax, what other key areas should I learn to get a website live?
Other than basic python syntax, what other key areas should I learn to get a website live?
Is there a web.config in the python world?
Which libraries handle things like authentication? or is that all done manually via sessi... | Other than basic python syntax, what other key areas should I learn to get a website live? | Other than basic python syntax, what other key areas should I learn to get a website live?
Is there a web.config in the python world?
Which libraries handle things like authentication? or is that all done manually via session cookies and database tables?
Are there any web specific libraries?
Edit: sorry!
I am well ver... | [
"Basic Python syntax isn't half of what you need to know.\n\nAll of the Python built-in data structures.\nObject-oriented design.\nWhat python module and packages are.\nThe Python libraries -- almost everything you could ever want has already been written.\n\nTo name a few things.\nIf you've done some web developme... | [
4,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000777924_python.txt |
Q:
regex for parsing SQL statements
I've got an IronPython script that executes a bunch of SQL statements against a SQL Server database. the statements are large strings that actually contain multiple statements, separated by the "GO" keyword. That works when they're run from sql management studio and some other to... | regex for parsing SQL statements | I've got an IronPython script that executes a bunch of SQL statements against a SQL Server database. the statements are large strings that actually contain multiple statements, separated by the "GO" keyword. That works when they're run from sql management studio and some other tools, but not in ADO. So I split up th... | [
"Is \"GO\" always on a line by itself? You could just split on \"^GO$\".\n",
"since you can have comments inside comments, nested comments, comments inside queries, etc, there is no sane way to do it with regexes.\nJust immagine the following script:\nINSERT INTO table (name) VALUES (\n-- GO NOW GO\n'GO to GO /*... | [
8,
5,
5,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000778969_python_regex.txt |
Q:
Identifying the types of all variables in a C project
I am trying to write a program to check that some C source code conforms to a variable naming convention. In order to do this, I need to analyse the source code and identify the type of all the local and global variables.
The end result will almost certainly b... | Identifying the types of all variables in a C project | I am trying to write a program to check that some C source code conforms to a variable naming convention. In order to do this, I need to analyse the source code and identify the type of all the local and global variables.
The end result will almost certainly be a python program, but the tool to analyse the code could ... | [
"There are a number of Python parser packages that can be used to describe a syntax and then it will generate Python code to parse that syntax.\nNed Batchelder wrote a very nice summary\nOf those, Ply was used in a project called pycparser that parses C source code. I would recommend starting with this.\nSome of t... | [
5,
3,
2,
2,
0
] | [] | [] | [
"c",
"code_analysis",
"coding_style",
"python",
"variables"
] | stackoverflow_0000778468_c_code_analysis_coding_style_python_variables.txt |
Q:
How to center a GNOME pop-up notification?
To display a GNOME pop-up notification at (200,400) on the screen (using Python):
import pynotify
n = pynotify.Notification("This is my title", "This is my description")
n.set_hint('x', 200)
n.set_hint('y', 400)
n.show()
I'm a gtk noob. How can I make this Notification... | How to center a GNOME pop-up notification? | To display a GNOME pop-up notification at (200,400) on the screen (using Python):
import pynotify
n = pynotify.Notification("This is my title", "This is my description")
n.set_hint('x', 200)
n.set_hint('y', 400)
n.show()
I'm a gtk noob. How can I make this Notification show up centered on the screen, or at the botto... | [
"Since you're using GNOME, here's the GTK way of getting the screen resolution\nimport gtk.gdk\nimport pynotify\n\nn = pynotify.Notification(\"This is my title\", \"This is my description\")\nn.set_hint('x', gtk.gdk.screen_width()/2.)\nn.set_hint('y', gtk.gdk.screen_height()/2.)\nn.show()\n\n",
"A bit of a hack, ... | [
4,
0
] | [
"on windows, \n from win32api import GetSystemMetrics\n width = GetSystemMetrics (0)\n height = GetSystemMetrics (1)\n print \"Screen resolution = %dx%d\" % (width, height)\n\nI cant seem to find the linux version for it tho. \n"
] | [
-4
] | [
"gtk",
"pynotify",
"python",
"user_interface"
] | stackoverflow_0000778660_gtk_pynotify_python_user_interface.txt |
Q:
How to upload a pristine Python package to PyPI?
What's the magic "python setup.py some_incantation_here" command to upload a package to PyPI, in a form that can be downloaded to get the original package in its original form?
I have a package with some source and a few image files (as package_data). If I do "setu... | How to upload a pristine Python package to PyPI? | What's the magic "python setup.py some_incantation_here" command to upload a package to PyPI, in a form that can be downloaded to get the original package in its original form?
I have a package with some source and a few image files (as package_data). If I do "setup.py sdist register upload", the .tar.gz has the image... | [
"When you perform an \"sdist\" command, then what controls the list of included files is your \"MANIFEST.in\" file sitting next to \"setup.py\", not whatever you have listed in \"package_data\". This has something to do with the schizophrenic nature of the Python packaging solutions today; \"sdist\" is powered by ... | [
16
] | [] | [] | [
"packaging",
"pypi",
"python"
] | stackoverflow_0000778980_packaging_pypi_python.txt |
Q:
How do I get the last number from the range() function?
Is there a way to get the last number from the range() function?
I need to get the last number in a Fibonacci sequence for first 20 terms or should I use a list instead of range()?
A:
Not quite sure what you are after here but here goes:
rangeList = range(0... | How do I get the last number from the range() function? | Is there a way to get the last number from the range() function?
I need to get the last number in a Fibonacci sequence for first 20 terms or should I use a list instead of range()?
| [
"Not quite sure what you are after here but here goes:\nrangeList = range(0,21)\nlastNumber = rangeList[len(rangeList)-1:][0]\n\nor:\nlastNumber = rangeList[-1]\n\n",
"by in a range, do you mean last value provided by a generator? If so, you can do something like this:\ndef fibonacci(iterations):\n # generate ... | [
12,
3,
1,
0
] | [] | [] | [
"fibonacci",
"python",
"range"
] | stackoverflow_0000780057_fibonacci_python_range.txt |
Q:
Generating unique and opaque user IDs in Google App Engine
I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows... | Generating unique and opaque user IDs in Google App Engine | I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows people to browse its users' pages.
To do this, I need a way to ... | [
"Your timing is impeccable: Just yesterday, a new release of the SDK came out, with support for unique, permanent user IDs. They meet all the criteria you specified.\n",
"I think you should distinguish between two types of users:\n1) users that have logged in via Google Accounts or that have already registered on... | [
7,
3,
1
] | [] | [] | [
"google_app_engine",
"guid",
"python",
"uniqueidentifier"
] | stackoverflow_0000778965_google_app_engine_guid_python_uniqueidentifier.txt |
Q:
How to automatically reload a python file when it is changed
If I make some changes to one of the files belonging to a running app, is there a way to tell the python runtime to automatically reload the module/file?
A:
Take at look at CherryPy's Autoreload feature. I think it looks quite simple and always worked ... | How to automatically reload a python file when it is changed | If I make some changes to one of the files belonging to a running app, is there a way to tell the python runtime to automatically reload the module/file?
| [
"Take at look at CherryPy's Autoreload feature. I think it looks quite simple and always worked well for me.\n",
"Here is a very old module that I posted nearly ten years ago. I may no longer work with current Python versions (I have not checked) but it may give some ideas.\nhttp://mail.python.org/pipermail/pyth... | [
5,
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0000780526_python.txt |
Q:
Add Quotes in url string from file
I need script to add quotes in url string from url.txt
from http://www.site.com/info.xx to "http://www.site.com/info.xx"
A:
url = '"%s"' % url
Example:
line = 'http://www.site.com/info.xx \n'
url = '"%s"' % line.strip()
print url # "http://www.site.com/info.xx"
Remember, add... | Add Quotes in url string from file | I need script to add quotes in url string from url.txt
from http://www.site.com/info.xx to "http://www.site.com/info.xx"
| [
"url = '\"%s\"' % url\n\nExample:\nline = 'http://www.site.com/info.xx \\n'\nurl = '\"%s\"' % line.strip()\nprint url # \"http://www.site.com/info.xx\"\n\nRemember, adding a backslash before a quotation mark will escape it and therefore won't end the string.\n",
"url = '\"%s\"' % url\n\nExample:\n>>> url = \"htt... | [
7,
4,
0,
0,
0
] | [] | [] | [
"perl",
"python",
"ruby"
] | stackoverflow_0000543199_perl_python_ruby.txt |
Q:
How to set correct value for Django ROOT_URLCONF setting in different branches
I've put site directory created by django-admin startproject under version control (Mercurial). Let's say, the site is called frobnicator.
Now I want to make some serious refactoring, so I clone the site using command
hg clone frobnicat... | How to set correct value for Django ROOT_URLCONF setting in different branches | I've put site directory created by django-admin startproject under version control (Mercurial). Let's say, the site is called frobnicator.
Now I want to make some serious refactoring, so I clone the site using command
hg clone frobnicator frobnicator-refactoring`
but ROOT_URLCONF in settings.py still says frobnicator.... | [
"Simply remove project name from the ROOT_URLCONF definition - it is optional. Then you can have project folders with different names.\n"
] | [
13
] | [] | [] | [
"django",
"mercurial",
"python"
] | stackoverflow_0000781211_django_mercurial_python.txt |
Q:
Python Multiprocessing: Sending data to a process
I have subclassed Process like so:
class EdgeRenderer(Process):
def __init__(self,starter,*args,**kwargs):
Process.__init__(self,*args,**kwargs)
self.starter=starter
Then I define a run method which uses self.starter.
That starter object is of ... | Python Multiprocessing: Sending data to a process | I have subclassed Process like so:
class EdgeRenderer(Process):
def __init__(self,starter,*args,**kwargs):
Process.__init__(self,*args,**kwargs)
self.starter=starter
Then I define a run method which uses self.starter.
That starter object is of a class State that I define.
Is it okay that I do this?... | [
"On unix systems, multiprocessing uses os.fork() to create the children, on windows, it uses some subprocess trickery and serialization to share the data. So to be cross platform, yes - it must be serializable. The child will get a new copy.\nThat being said, here's an example:\nfrom multiprocessing import Process\... | [
8
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0000779384_multiprocessing_python.txt |
Q:
Communicating with a Python service
Problem:
I have a python script that I have running as a service. It's a subclass of the win32 class win32serviceutil.ServiceFramework. I want a simple straightforward way of sending arbitrary commands to it via the command line.
What I've looked at:
It looks like the standa... | Communicating with a Python service | Problem:
I have a python script that I have running as a service. It's a subclass of the win32 class win32serviceutil.ServiceFramework. I want a simple straightforward way of sending arbitrary commands to it via the command line.
What I've looked at:
It looks like the standard way of controlling the service once it... | [
"Not really.\nYou have many, many ways to do \"Interprocess Communication\" (IPC) in Python.\n\nSockets\nNamed Pipes (see http://developers.sun.com/solaris/articles/named_pipes.html) -- it involves a little bit of OS magic to create, but then it's just a file that you read and write.\nShared Memory (see http://en.w... | [
2
] | [] | [] | [
"command_line",
"python",
"service",
"winapi"
] | stackoverflow_0000781594_command_line_python_service_winapi.txt |
Q:
Playing and controlling mp3 files in Python?
First things first, I am a Python beginner, with a typical C++/Java background for object oriented stuff.
I was convinced to try Python for this current endeavor I am working on, and so far I like it. One issue I am having though is finding a good mp3 module.
I have tri... | Playing and controlling mp3 files in Python? | First things first, I am a Python beginner, with a typical C++/Java background for object oriented stuff.
I was convinced to try Python for this current endeavor I am working on, and so far I like it. One issue I am having though is finding a good mp3 module.
I have tried TkSnack, which installed and ran fine with no e... | [
"Sorry I can't help you with PyMad or pyMedia, but I have other suggestions.\nExisting music players written in Python:\n\nExaile\nFUPlayer\nListen\n\nAll of the above use the Python bindings for the GStreamer multimedia framework. Docs for the bindings are scarce, but check here, here, here, and examples from the ... | [
2,
1
] | [] | [] | [
"audio",
"audio_streaming",
"mp3",
"python"
] | stackoverflow_0000780711_audio_audio_streaming_mp3_python.txt |
Q:
Emacs function to message the python function I'm in
I'm editing some Python code with rather long functions and decided it would be useful to quickly get the function name without scrolling up. I put this bit of code together to do it. Is there something built in to emacs in general, or the standard python mode i... | Emacs function to message the python function I'm in | I'm editing some Python code with rather long functions and decided it would be useful to quickly get the function name without scrolling up. I put this bit of code together to do it. Is there something built in to emacs in general, or the standard python mode in particular, which I can use instead?
(defun python-show-... | [
"You may find decent results with which-function-mode:\n\nWhich Function mode is a minor mode\n that displays the current function\n name in the mode line, updating it as\n you move around in a buffer.\nTo either enable or disable Which\n Function mode, use the command M-x\n which-function-mode. This command i... | [
21,
2,
0
] | [] | [] | [
"elisp",
"emacs",
"python"
] | stackoverflow_0000782357_elisp_emacs_python.txt |
Q:
Implementing a 'function-calling function'
I would like to write a bit of code that calls a function specified by a given argument. EG:
def caller(func):
return func()
However what I would also like to do is specify optional arguments to the 'caller' function so that 'caller' calls 'func' with the arguments ... | Implementing a 'function-calling function' | I would like to write a bit of code that calls a function specified by a given argument. EG:
def caller(func):
return func()
However what I would also like to do is specify optional arguments to the 'caller' function so that 'caller' calls 'func' with the arguments specified (if any).
def caller(func, args):
# ca... | [
"You can do this by using arbitrary argument lists and unpacking argument lists.\n>>> def caller(func, *args, **kwargs):\n... return func(*args, **kwargs)\n...\n>>> def hello(a, b, c):\n... print a, b, c\n...\n>>> caller(hello, 1, b=5, c=7)\n1 5 7\n\nNot sure why you feel the need to do it, though.\n",
"T... | [
12,
7
] | [] | [] | [
"function",
"functional_programming",
"python"
] | stackoverflow_0000782605_function_functional_programming_python.txt |
Q:
How to hide __methods__ in python?
I just wondered, how to hide special
__.*__
methods in python*? Especially I am using an interactive python interpreter with tab-completion, and I would like to display only the methods my modules expose ...
thanks,
/ myyn /
*(at least from the user, who uses a python shell)... | How to hide __methods__ in python? | I just wondered, how to hide special
__.*__
methods in python*? Especially I am using an interactive python interpreter with tab-completion, and I would like to display only the methods my modules expose ...
thanks,
/ myyn /
*(at least from the user, who uses a python shell)
it looks like this now:
h[2] >>> Q.
Q.... | [
"I think you should look for a way to get that particular environment/interpreter to stop displaying the \"private\" methods when you press TAB. I don't think there is a way to \"hide\" methods from Python itself, that would be very weird.\n",
"Well, you could create a subclass of rlcompleter.Completer, override\... | [
3,
3,
1
] | [] | [] | [
"facade",
"hide",
"magic_methods",
"python"
] | stackoverflow_0000781667_facade_hide_magic_methods_python.txt |
Q:
English and/or Finnish text validation
Is there an easy-to-use python module that'd do english or finnish text validation?
It'd be ok if I could just check the words exist in user-defined dictionary and possibly checking that the grammar is somewhat okay.
I am planning to implement a fancy validation for a directo... | English and/or Finnish text validation | Is there an easy-to-use python module that'd do english or finnish text validation?
It'd be ok if I could just check the words exist in user-defined dictionary and possibly checking that the grammar is somewhat okay.
I am planning to implement a fancy validation for a directory contents I did while ago back. This invol... | [
"I'm not sure what you're trying to do, but if you're looking for something that can say 'this is valid English' or 'this is valid Finnish', then you're looking at a class of problems that is quite likely unsolvable.\nIf not, then use a dictionary and/or letter frequencies and Bayesian analysis to determine whether... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0000783189_python.txt |
Q:
Send data to the browser while waiting (Python)
I have the following code
print "Starting stage 1<br>"
# Something that takes about 5 seconds
time.sleep(5)
print "Stage 1 complete"
I view the script with my browser as it's part of a web-app, the problem is that it's displaying all of it together. I want it to d... | Send data to the browser while waiting (Python) | I have the following code
print "Starting stage 1<br>"
# Something that takes about 5 seconds
time.sleep(5)
print "Stage 1 complete"
I view the script with my browser as it's part of a web-app, the problem is that it's displaying all of it together. I want it to display first the starting message before it starts an... | [
"Try flush the output after the first print using sys.stdout.flush()\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0000783262_python.txt |
Q:
wxPython: Using EVT_IDLE
I defined an handler for EVT_IDLE that does a certain background task for me. (That task is to take completed work from a few processes and integrate it into some object, making a visible change in the GUI.)
The problem is that when the user is not moving the mouse or doing anything, EVT_I... | wxPython: Using EVT_IDLE | I defined an handler for EVT_IDLE that does a certain background task for me. (That task is to take completed work from a few processes and integrate it into some object, making a visible change in the GUI.)
The problem is that when the user is not moving the mouse or doing anything, EVT_IDLE doesn't get called more th... | [
"Something like this (executes at most every second):\n...\n\ndef On_Idle(self, event):\n if not self.queued_batch:\n wx.CallLater(1000, self.Do_Batch)\n self.queued_batch = True\n\ndef Do_Batch(self):\n # <- insert your stuff here\n self.queued_batch = False\n\n...\n\nOh, and don't forget to... | [
2,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0000783023_python_wxpython.txt |
Q:
seek(), then read(), then write() in python
When running the following python code:
>>> f = open(r"myfile.txt", "a+")
>>> f.seek(-1,2)
>>> f.read()
'a'
>>> f.write('\n') ... | seek(), then read(), then write() in python | When running the following python code:
>>> f = open(r"myfile.txt", "a+")
>>> f.seek(-1,2)
>>> f.read()
'a'
>>> f.write('\n')
I get th... | [
"This appears to be a Windows-specific problem - see http://bugs.python.org/issue1521491 for a similar issue.\nEven better, a workaround given and explained at http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html, insert:\nf.seek(f.tell())\n\nbetween the read() and write() calls.\n",
"the a+ ... | [
5,
1,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0000783792_file_io_python.txt |
Q:
SQLAlchemy - Dictionary of tags
I have question regarding the SQLAlchemy. How can I add into my mapped class the dictionary-like attribute, which maps the string keys into string values and which will be stored in the database (in the same or another table as original mapped object). I want this add support for ar... | SQLAlchemy - Dictionary of tags | I have question regarding the SQLAlchemy. How can I add into my mapped class the dictionary-like attribute, which maps the string keys into string values and which will be stored in the database (in the same or another table as original mapped object). I want this add support for arbitrary tags of my objects.
I found t... | [
"The simple answer is yes.\nJust use an association proxy:\nfrom sqlalchemy import Column, Integer, String, Table, create_engine\nfrom sqlalchemy import orm, MetaData, Column, ForeignKey\nfrom sqlalchemy.orm import relation, mapper, sessionmaker\nfrom sqlalchemy.orm.collections import column_mapped_collection\nfrom... | [
22
] | [
"The simple answer is 'no'.\nSQLAlchemy is wrapper on a SQL database.\nThe relation examples you quote translate a relationship between SQL tables into a Python map-like structure to make it slightly simpler to do the SQL SELECT statements and locate rows in another table.\nThe \nitem.notes['color'] = Note('color',... | [
-6
] | [
"python",
"sqlalchemy"
] | stackoverflow_0000780774_python_sqlalchemy.txt |
Q:
Python Module/Class Variable Bleeding
Okay, it took me a little while to narrow down this problem, but it appears python is doing this one purpose. Can someone explain why this is happening and what I can do to fix this?
File: library/testModule.py
class testClass:
myvars = dict()
def __getattr__(self, k... | Python Module/Class Variable Bleeding | Okay, it took me a little while to narrow down this problem, but it appears python is doing this one purpose. Can someone explain why this is happening and what I can do to fix this?
File: library/testModule.py
class testClass:
myvars = dict()
def __getattr__(self, k):
if self.myvars.has_key(k):
... | [
"myvars is a property of the class, not the instance. This means that when you insert an attribute into myvars from the instance c1, the attribute gets associated with the class testClass, not the instance c1 specifically. Since c2 is an instance of the same class, it also has the same attribute.\nYou could get th... | [
7,
2,
0
] | [] | [] | [
"class",
"oop",
"python"
] | stackoverflow_0000784149_class_oop_python.txt |
Q:
Penalties of a script constantly looping in the background
I know this topic has been discussed in the past, but I am a tiny bit paranoid about resource usage.
I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:
whil... | Penalties of a script constantly looping in the background | I know this topic has been discussed in the past, but I am a tiny bit paranoid about resource usage.
I am looking into writing a daemon for queing jobs to archive files into zip files for a web app i am working on. It would behave something like this:
while True:
while morejobs():
zipfile()
sleep(15seco... | [
"Sleep involves no overhead. The Linux OS uses a very simple signal to wake a sleeping process.\nWhat you're showing is the \"busy-waiting\" design pattern.\nTo eliminate overhead, you want to be woken ONLY when there's work to do.\nWays to do this.\n\nWait on read.\nWait on a select function call. See http://doc... | [
4,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"performance",
"python",
"queue",
"resources"
] | stackoverflow_0000781896_performance_python_queue_resources.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.