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:
_lsprof.c profiler behaviour towards python multi-threading
This is a question about Python native c file _lsprof.
How does _lsprof.profile() profiler counts total time spent on a function f in a multi-threaded program if the execution of f is interrupted by another thread?
For example:
def f():
linef1
linef... | _lsprof.c profiler behaviour towards python multi-threading | This is a question about Python native c file _lsprof.
How does _lsprof.profile() profiler counts total time spent on a function f in a multi-threaded program if the execution of f is interrupted by another thread?
For example:
def f():
linef1
linef2
linef3
def g():
lineg1
lineg2
And at the execution we... | [
"Quoting from the documentation for setprofile:\n\nThe function is thread-specific, but\n there is no way for the profiler to\n know about context switches between\n threads, so it does not make sense to\n use this in the presence of multiple\n threads.\n\n",
"Thank you for this answer! Actually I am running... | [
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0000443082_multithreading_python.txt |
Q:
How to Alter Photographed Document to Look "Scanned"
How can I do this in Python/PIL? I.e., given the four points of an offset rectangle (a photographed document), make it look flat on as if it were scanned. Is there a simple algorithm for it?
Also, are there any other manipulations I should do to make it look mo... | How to Alter Photographed Document to Look "Scanned" | How can I do this in Python/PIL? I.e., given the four points of an offset rectangle (a photographed document), make it look flat on as if it were scanned. Is there a simple algorithm for it?
Also, are there any other manipulations I should do to make it look more "scan-like"?
I want to make a simple version of this pr... | [
"Look at transform() with method set to QUAD\nhttps://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.transform\n\nim.transform(size, QUAD, data) => image\nim.transform(size, QUAD, data, filter) => image\n\nMaps a quadrilateral (a region defined by four corners) from the image to a rectangle wi... | [
8
] | [] | [] | [
"image_processing",
"image_scanner",
"python",
"python_imaging_library"
] | stackoverflow_0000662638_image_processing_image_scanner_python_python_imaging_library.txt |
Q:
Help with subprocess.call on a Windows machine
I am trying to modify a trac plugin that allows downloading of wiki pages to word documents. pagetodoc.py throws an exception on this line:
# Call the subprocess using convenience method
retval = subprocess.call(command, shell=True, stderr=errptr, stdout=outptr, close... | Help with subprocess.call on a Windows machine | I am trying to modify a trac plugin that allows downloading of wiki pages to word documents. pagetodoc.py throws an exception on this line:
# Call the subprocess using convenience method
retval = subprocess.call(command, shell=True, stderr=errptr, stdout=outptr, close_fds = True)
Saying that close_fds is not supported... | [
"close_fds is supported on Windows (search for \"close_fds\" after that link) starting with Python 2.6 (if stdin/stdout/stderr are not redirected). You might consider upgrading.\nFrom the linked doc:\n\nNote that on Windows, you cannot set close_fds to true and also\nredirect the standard handles by setting stdin, ... | [
0
] | [] | [] | [
"python",
"python_2.4",
"trac"
] | stackoverflow_0000662641_python_python_2.4_trac.txt |
Q:
HTML Entity Codes to Text
Does anyone know an easy way in Python to convert a string with HTML entity codes (e.g. < &) to a normal string (e.g. < &)?
cgi.escape() will escape strings (poorly), but there is no unescape().
A:
HTMLParser has the functionality in the standard library. It is, unfortunately, un... | HTML Entity Codes to Text | Does anyone know an easy way in Python to convert a string with HTML entity codes (e.g. < &) to a normal string (e.g. < &)?
cgi.escape() will escape strings (poorly), but there is no unescape().
| [
"HTMLParser has the functionality in the standard library. It is, unfortunately, undocumented:\n(Python2 Docs)\n>>> import HTMLParser\n>>> h= HTMLParser.HTMLParser()\n>>> h.unescape('alpha < β')\nu'alpha < \\u03b2'\n\n(Python 3 Docs)\n>>> import html.parser\n>>> h = html.parser.HTMLParser()\n>>> h.unescape(... | [
45,
12,
1,
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0000663058_beautifulsoup_html_python.txt |
Q:
Can I write Python web application for Windows and Linux platforms at the same time?
Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?
CGI? Maybe something new? WSGI | FastCGI ?
A:
Yes you can. But you can also use apache on windows. If yo... | Can I write Python web application for Windows and Linux platforms at the same time? | Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?
CGI? Maybe something new? WSGI | FastCGI ?
| [
"Yes you can. But you can also use apache on windows. If you go the IIS way there's only CGI and it's pretty hard to set up. You can also use python based server like CherryPy which is pretty good and will work on all platforms with python.\nSome frameworks like django support both CGI and WSGI, so you don't have t... | [
7,
2,
2,
2,
0,
0
] | [] | [] | [
"cgi",
"fastcgi",
"python",
"wsgi"
] | stackoverflow_0000662762_cgi_fastcgi_python_wsgi.txt |
Q:
write a table with empty cells based on dictionary of values
I have this view in my app:
def context_detail(request, context_id):
c = get_object_or_404(Context, pk=context_id)
scs = SherdCount.objects.filter(assemblage__context=c).exclude(count__isnull=True)
total = sum(sc.count for sc in scs)
table = []
forms = [... | write a table with empty cells based on dictionary of values | I have this view in my app:
def context_detail(request, context_id):
c = get_object_or_404(Context, pk=context_id)
scs = SherdCount.objects.filter(assemblage__context=c).exclude(count__isnull=True)
total = sum(sc.count for sc in scs)
table = []
forms = []
for a in c.assemblage_set.all():
for sc in a.sherdcount_set.... | [
"Here's the data structure.\n[{<Type1>: 16,\n <Type2>: 10,\n <Type3>: 12,\n <Type4>: 7,\n <Type5>: 0,\n 'assemblage': <Assemblage1>},\n {<Type1>: 85,\n <Type2>: 18,\n <Type3>: 21,\n <Type4>: 12,\n <Type5>: 2,\n 'assemblage': <Assemblage2>},\n ...]\n\nThe problem is that the resulting table must be generat... | [
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0000662463_django_django_templates_python.txt |
Q:
Using PyQT, how do you filter mousePressEvent for a QComboBox with custom list
I've got a QComboBox with a custom list object.
The custom list object has a custom mousePressEvent so that when the user click on one of the circles with a +/- (a twisty), the list is expanded/collapsed.
When I use the list with the... | Using PyQT, how do you filter mousePressEvent for a QComboBox with custom list | I've got a QComboBox with a custom list object.
The custom list object has a custom mousePressEvent so that when the user click on one of the circles with a +/- (a twisty), the list is expanded/collapsed.
When I use the list with the combo box, when the user clicks on a twisty, the list is expanded/collapsed, but th... | [
"QT has a eventFilter that \"captures\" QEvent.MouseButtonRelease. So what I have done is installed my own eventFilter that filters QEvent.MouseButtonRelease events if the user click on a node. \nIn my list object I have the following method:\ndef mousePressEvent (self, e):\n self.colapse_expand_click = False\n ... | [
2,
1
] | [] | [] | [
"pyqt",
"python",
"qcombobox",
"qt",
"qt4"
] | stackoverflow_0000603528_pyqt_python_qcombobox_qt_qt4.txt |
Q:
Using norwegian letters æøå in python
I'm learning python and PyGTK now, and have created a simple Music Organizer.
http://pastebin.com/m2b596852
But when it edits songs with the Norwegian letters æ, ø, and å it's just changing them to a weird character.
So is there any good way of opening or encode the names into... | Using norwegian letters æøå in python | I'm learning python and PyGTK now, and have created a simple Music Organizer.
http://pastebin.com/m2b596852
But when it edits songs with the Norwegian letters æ, ø, and å it's just changing them to a weird character.
So is there any good way of opening or encode the names into utf-8 characters?
Two relevant places from... | [
"You want to start by decoding the input FROM the charset it is in TO utf-8 (in Python, encode means \"take it from unicode/utf-8 to some other charset\"). \nSome googling suggests the Norwegian charset is plain-ole 'iso-8859-1'... I hope someone can correct me if I'm wrong on this detail. Regardless, whatever the ... | [
8,
1,
1
] | [] | [] | [
"python",
"utf_8"
] | stackoverflow_0000664372_python_utf_8.txt |
Q:
How do I format positional argument help using Python's optparse?
As mentioned in the docs the optparse.OptionParser uses an IndentedHelpFormatter to output the formatted option help, for which which I found some API documentation.
I want to display a similarly formatted help text for the required, positional argu... | How do I format positional argument help using Python's optparse? | As mentioned in the docs the optparse.OptionParser uses an IndentedHelpFormatter to output the formatted option help, for which which I found some API documentation.
I want to display a similarly formatted help text for the required, positional arguments in the usage text. Is there an adapter or a simple usage pattern ... | [
"The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done.\n#!/usr/bin/env python\nfrom optparse import OptionParser, Option, IndentedHelpFormatter\n\nclass PosOptionPar... | [
20,
8,
1,
0
] | [] | [] | [
"command_line",
"command_line_arguments",
"formatting",
"optparse",
"python"
] | stackoverflow_0000642648_command_line_command_line_arguments_formatting_optparse_python.txt |
Q:
python postgres cursor timestamp issue
I am somewhat new to transactional databases and have come across an issue I am trying to understand.
I have created a simple demonstration where a database connection is stored inside each of the 5 threads created by cherrypy. I have a method that displays a table of time... | python postgres cursor timestamp issue | I am somewhat new to transactional databases and have come across an issue I am trying to understand.
I have created a simple demonstration where a database connection is stored inside each of the 5 threads created by cherrypy. I have a method that displays a table of timestamps stored in the database and a button t... | [
"Try calling c.close() as described in the module documentation: http://tools.cherrypy.org/wiki/Databases\ndef add_timestamp(self):\n c = cherrypy.thread_data.db.cursor()\n now = datetime.datetime.now()\n c.execute(\"insert into test (given_time) values ('%s')\" % now)\n c.connection.com... | [
3,
2,
0
] | [] | [] | [
"cherrypy",
"postgresql",
"python"
] | stackoverflow_0000655125_cherrypy_postgresql_python.txt |
Q:
Uninitialized value in Python?
What's the uninitialized value in Python, so I can compare if something is initialized, like:
val
if val == undefined ?
EDIT: added a pseudo keyword.
EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.
A:
Will throw a NameError exce... | Uninitialized value in Python? | What's the uninitialized value in Python, so I can compare if something is initialized, like:
val
if val == undefined ?
EDIT: added a pseudo keyword.
EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.
| [
"Will throw a NameError exception:\n>>> val\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'val' is not defined\n\nYou can either catch that or use 'val' in dir(), i.e.:\ntry:\n val\nexcept NameError:\n print(\"val not set\")\n\nor\nif 'val' in dir():\n print(... | [
10,
5,
5,
4,
1,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000664219_python.txt |
Q:
box drawing in python
Platform: WinXP SP2, python 2.5.4.3. (activestate distribution)
Has anyone succeded in writing out box drawing characters in python?
When I try to run this:
print u'\u2500'
print u'\u2501'
print u'\u2502'
print u'\u2503'
print u'\u2504'
All tips appreciated. What am I doing wrong ? Does pyth... | box drawing in python | Platform: WinXP SP2, python 2.5.4.3. (activestate distribution)
Has anyone succeded in writing out box drawing characters in python?
When I try to run this:
print u'\u2500'
print u'\u2501'
print u'\u2502'
print u'\u2503'
print u'\u2504'
All tips appreciated. What am I doing wrong ? Does python support full unicode ? I... | [
"Your problem is not in Python but in cmd.exe. It has to be set to support UTF-8. Unfortunately, it is not very easy to switch windows console (cmd.exe) to UTF-8 \"Python-compatible\" way.\nYou can use command (in cmd.exe) to switch to UTF8:\nchcp 65001\n\nbut Python (2.5) does not recognize that encoding. Anyway y... | [
6,
2,
1,
0
] | [] | [] | [
"python",
"unicode",
"windows"
] | stackoverflow_0000664991_python_unicode_windows.txt |
Q:
How can I improve this "register" view in Django?
I've got a Django-based site that allows users to register (but requires an admin to approve the account before they can view certain parts of the site). I'm basing it off of django.contrib.auth. I require users to register with an email address from a certain doma... | How can I improve this "register" view in Django? | I've got a Django-based site that allows users to register (but requires an admin to approve the account before they can view certain parts of the site). I'm basing it off of django.contrib.auth. I require users to register with an email address from a certain domain name, so I've overridden the UserCreationForm's save... | [
"You don't even need this code, but I think the style:\npk = None\ntry: pk = User.objects.filter(username=username)[0].pk\nexcept: pass\n\nis more naturally written like:\ntry:\n user = User.objects.get(username=username)\nexcept User.DoesNotExist:\n user = None\n\nand then in your admin notify template use {... | [
4,
3,
0
] | [] | [] | [
"django",
"python",
"user_registration"
] | stackoverflow_0000664937_django_python_user_registration.txt |
Q:
Extract array from list in python
If I have a list like this:
>>> data = [(1,2),(40,2),(9,80)]
how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ?
A:
The unzip operation is:
In [1]: data = [(1,2),(40,2),(9,80)]
In ... | Extract array from list in python | If I have a list like this:
>>> data = [(1,2),(40,2),(9,80)]
how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ?
| [
"The unzip operation is:\nIn [1]: data = [(1,2),(40,2),(9,80)]\nIn [2]: zip(*data)\nOut[2]: [(1, 40, 9), (2, 2, 80)]\n\nEdit: You can decompose the resulting list on assignment:\nIn [3]: first_elements, second_elements = zip(*data)\n\nAnd if you really need lists as results:\nIn [4]: first_elements, second_elements... | [
27,
14,
5
] | [] | [] | [
"arrays",
"list",
"python"
] | stackoverflow_0000665652_arrays_list_python.txt |
Q:
Decorator classes in Python
I want to construct classes for use as decorators with the following principles intact:
It should be possible to stack multiple such class decorators on top off 1 function.
The resulting function name pointer should be indistinguishable from the same function without a decorator, save ... | Decorator classes in Python | I want to construct classes for use as decorators with the following principles intact:
It should be possible to stack multiple such class decorators on top off 1 function.
The resulting function name pointer should be indistinguishable from the same function without a decorator, save maybe for just which type/class i... | [
"A do-nothing decorator class would look like this:\nclass NullDecl (object):\n def __init__ (self, func):\n self.func = func\n for name in set(dir(func)) - set(dir(self)):\n setattr(self, name, getattr(func, name))\n\n def __call__ (self, *args):\n return self.func (*args)\n\nAnd then you... | [
24,
10,
8
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0000666216_decorator_python.txt |
Q:
What errors/exceptions do I need to handle with urllib2.Request / urlopen?
I have the following code to do a postback to a remote URL:
request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
... | What errors/exceptions do I need to handle with urllib2.Request / urlopen? | I have the following code to do a postback to a remote URL:
request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
checksLogger.error('HTTPError = ' + str(e.code))
except urllib2.URLError, e:
... | [
"Add generic exception handler:\nrequest = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })\n\ntry: \n response = urllib2.urlopen(request)\nexcept urllib2.HTTPError, e:\n checksLogger.error('HTTPError = ' + str(e.code))\nexcept urllib2.URLError, e:\n checksLogger.... | [
65,
20,
15,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000666022_python.txt |
Q:
qt design issue
i'm trying to design interface like this one
http://www.softpedia.com/screenshots/FlashFXP_2.png
i'm using the QT design and programming with python
well on the left it's a treeWidget
but what is on the right side ? as everytime i change the cursor on the tree
all widgets replace...
thanks :p
A:
... | qt design issue | i'm trying to design interface like this one
http://www.softpedia.com/screenshots/FlashFXP_2.png
i'm using the QT design and programming with python
well on the left it's a treeWidget
but what is on the right side ? as everytime i change the cursor on the tree
all widgets replace...
thanks :p
| [
"Use QStackedWidget. You insert several widgets which correspond to the pages. Changing the active item in tree should switch the active widget/page inside the stacked widget.\n"
] | [
8
] | [] | [] | [
"python",
"qt",
"user_interface"
] | stackoverflow_0000666712_python_qt_user_interface.txt |
Q:
How to get whole text of an Element in xml.minidom?
I want to get the whole text of an Element to parse some xhtml:
<div id='asd'>
<pre>skdsk</pre>
</div>
begin E = div element on the above example, I want to get
<pre>skdsk</pre>
How?
A:
Strictly speaking:
from xml.dom.minidom import parse, parseString
tree... | How to get whole text of an Element in xml.minidom? | I want to get the whole text of an Element to parse some xhtml:
<div id='asd'>
<pre>skdsk</pre>
</div>
begin E = div element on the above example, I want to get
<pre>skdsk</pre>
How?
| [
"Strictly speaking:\nfrom xml.dom.minidom import parse, parseString\ntree = parseString(\"<div id='asd'><pre>skdsk</pre></div>\")\nroot = tree.firstChild\nnode = root.childNodes[0]\nprint node.toxml()\n\nIn practice, though, I'd recommend looking at the http://www.crummy.com/software/BeautifulSoup/ library. Finding... | [
2
] | [] | [] | [
"minidom",
"python"
] | stackoverflow_0000666724_minidom_python.txt |
Q:
Unable to decode unicode string in Python 2.4
This is in python 2.4. Here is my situation. I pull a string from a database, and it contains an umlauted 'o' (\xf6). At this point if I run type(value) it returns str. I then attempt to run .decode('utf-8'), and I get an error ('utf8' codec can't decode bytes in posit... | Unable to decode unicode string in Python 2.4 | This is in python 2.4. Here is my situation. I pull a string from a database, and it contains an umlauted 'o' (\xf6). At this point if I run type(value) it returns str. I then attempt to run .decode('utf-8'), and I get an error ('utf8' codec can't decode bytes in position 1-4).
Really my goal here is just to successfu... | [
"Your string is not in UTF8 encoding. If you want to 'decode' string to unicode, your string must be in encoding you specified by parameter. I tried this and it works perfectly:\nprint 'w\\xf6rner'.decode('cp1250')\n\nEDIT\nFor writing unicode strings to the file you can use codecs module:\nimport codecs\nf = code... | [
10,
5,
3,
2
] | [] | [] | [
"decode",
"python",
"unicode"
] | stackoverflow_0000666417_decode_python_unicode.txt |
Q:
Uses for Dynamic Languages
My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templ... | Uses for Dynamic Languages | My primary language right now is D, and I'm in the process of learning Python because it's required for a course I'm taking. While I understand why dynamic languages would be a breath of fresh air for people programming in static languages without type inference or templates (IMHO templates are to a large extent compi... | [
"In theory, there's nothing that dynamic languages can do and static languages can't. Smart people put a lot of work into making very good dynamic languages, leading to a perception at the moment that dynamic languages are ahead while static ones need to catch up.\nIn time, this will swing the other way. Already va... | [
15,
3,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0
] | [
"Compiled languages tend to be used when efficiency and type safety are the priorities. Otherwise I can't think of any reason why anyone wouldn't be using ruby :)\n"
] | [
-2
] | [
"duck_typing",
"dynamic_languages",
"language_design",
"programming_languages",
"python"
] | stackoverflow_0000493973_duck_typing_dynamic_languages_language_design_programming_languages_python.txt |
Q:
Best continuously updated resource about python web "plumbing"
I'm a programmer in Python who works on web-applications. I know a fair bit about the application level. But not so much about the underlying "plumbing" which I find myself having to configure or debug.
I'm thinking of everything from using memcached t... | Best continuously updated resource about python web "plumbing" | I'm a programmer in Python who works on web-applications. I know a fair bit about the application level. But not so much about the underlying "plumbing" which I find myself having to configure or debug.
I'm thinking of everything from using memcached to flup, fcgi, WSGI etc.
When looking for information about these, on... | [
"Buy this. http://www.amazon.com/Scalable-Internet-Architectures-Developers-Library/dp/067232699X\n",
"\nGeneral info about highly efficient web architecture: http://highscalability.com/\nInteresting Python related articles: http://www.onlamp.com/python/ \nPrinted magazine: http://pythonmagazine.com/\n\n",
"Zo... | [
1,
1,
0,
0
] | [] | [] | [
"flup",
"python",
"wsgi"
] | stackoverflow_0000665848_flup_python_wsgi.txt |
Q:
Crunching xml with python
I need to remove white spaces between xml tags, e.g. if the original xml looks like:
<node1>
<node2>
<node3>foo</node3>
</node2>
</node1>
I'd like the end-result to be crunched down to single line:
<node1><node2><node3>foo</node3></node2></node1>
Please note that I will ... | Crunching xml with python | I need to remove white spaces between xml tags, e.g. if the original xml looks like:
<node1>
<node2>
<node3>foo</node3>
</node2>
</node1>
I'd like the end-result to be crunched down to single line:
<node1><node2><node3>foo</node3></node2></node1>
Please note that I will not have control over the xml s... | [
"This is pretty easily handled with lxml (note: this particular feature isn't in ElementTree):\nfrom lxml import etree\n\nparser = etree.XMLParser(remove_blank_text=True)\n\nfoo = \"\"\"<node1>\n <node2>\n <node3>foo </node3>\n </node2>\n</node1>\"\"\"\n\nbar = etree.XML(foo, parser)\nprint etree.tost... | [
8,
5,
4,
2
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0000667359_python_xml.txt |
Q:
Alternatives to ffmpeg as a cli tools for video still extraction?
I need to extract stills from video files. Currently I am using ffmpeg, but I am looking for a simpler tool and for a tool that my collegues can just install. No need to compile it from a svn checkout.
Any hints? A python interface would be nice.
A... | Alternatives to ffmpeg as a cli tools for video still extraction? | I need to extract stills from video files. Currently I am using ffmpeg, but I am looking for a simpler tool and for a tool that my collegues can just install. No need to compile it from a svn checkout.
Any hints? A python interface would be nice.
| [
"Your requirements \"cli tool\" and \"python interface\" aren't entirely compatible. Which do you want?\nThe following media libraries all have Python bindings: GStreamer, libVLC (pyvlc provides w32 binaries), Xine (via Pyxine). I'm pretty sure none of them will be easier than using the ffmpeg or mplayer command-... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0000668240_python.txt |
Q:
Problem Extending Python(Linking Error )?
I have installed Python 3k(C:\Python30) and Visual Studio Professional Edition 2008.
I'm studying this.
Here is a problem:
C:\hello>dir
Volume in drive C has no label.
Volume Serial Number is 309E-14FB
Directory of C:\hello
03/21/2009 01:15 AM <DIR> .
03/... | Problem Extending Python(Linking Error )? | I have installed Python 3k(C:\Python30) and Visual Studio Professional Edition 2008.
I'm studying this.
Here is a problem:
C:\hello>dir
Volume in drive C has no label.
Volume Serial Number is 309E-14FB
Directory of C:\hello
03/21/2009 01:15 AM <DIR> .
03/21/2009 01:15 AM <DIR> ..
03/21/20... | [
"If Python is installed in c:\\python30, why are you searching for the libraries in c:\\Python24\\libs\\python30?\nAnd now that you've changed the question to fix this :-),\nI don't think Py_InitModule is available any more, you have to use PyModule_Create (this may have changed since the early betas of Py3k which ... | [
2
] | [] | [] | [
"c",
"linker",
"python",
"visual_studio",
"visual_studio_2008"
] | stackoverflow_0000668971_c_linker_python_visual_studio_visual_studio_2008.txt |
Q:
Can someone explain Gtk2 packing?
I need to use Gtk2 for a project. I will be using python/ruby for it. The problem is that packing seems kind of mystical to me. I tried using a VBox so that I could have the following widgets in my window ( in the following order ):
menubar
toolbar
text view/editor control
I've ... | Can someone explain Gtk2 packing? | I need to use Gtk2 for a project. I will be using python/ruby for it. The problem is that packing seems kind of mystical to me. I tried using a VBox so that I could have the following widgets in my window ( in the following order ):
menubar
toolbar
text view/editor control
I've managed to "guess" my way with pack_sta... | [
"Box packing is really simple, so perhaps your failure to understand it is because you imagine it is more complicated than it is.\nLayout is either Vertical (like a pile of bricks) or horizontal (like a queue of people). Each element in that layout can expand or it can not expand.\nHorizontal (HBox)\n[widget][widge... | [
14
] | [] | [] | [
"gtk2",
"packing",
"pygtk",
"python",
"ruby"
] | stackoverflow_0000668226_gtk2_packing_pygtk_python_ruby.txt |
Q:
PyS60: Bluetooth sockets
From the website http://www.mobilepythonbook.org/ I found the following example of bluetooth sockets: BT chat example
Here in function chat_server() the bind method accepts a tuple with two elements. The first one has been used as a null string. What does it signify?
Which node will act as... | PyS60: Bluetooth sockets | From the website http://www.mobilepythonbook.org/ I found the following example of bluetooth sockets: BT chat example
Here in function chat_server() the bind method accepts a tuple with two elements. The first one has been used as a null string. What does it signify?
Which node will act as master in the Bluetooth, the ... | [
"For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents INADDR_ANY, and the string '' represents INADDR_BROADCAST -- http://docs.python.org/library/socket.html\nThere you'll find more than enough information. Basically what INADDR_ANY means that it will bind to any... | [
1,
0
] | [] | [] | [
"bluetooth",
"nokia",
"pys60",
"python"
] | stackoverflow_0000599737_bluetooth_nokia_pys60_python.txt |
Q:
Can I use a single file as a buffer? I.e. write to and read from at same time
I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality.
The simplest way I can think to do t... | Can I use a single file as a buffer? I.e. write to and read from at same time | I want to have an application writing out information at the same time that a monitor is reading it. The application is "embedded" (and on Win32 XP) and so has restricted memory and I/O functionality.
The simplest way I can think to do this is by writing the data to a buffer file from the application, and then read the... | [
"Most systems has several solutions for what you want to do, such as pipes and unix sockets. These are intended for this, unlike regular files. There are however programs that does this on regular files, and I think the clearest example of this is the unix-utility tail, which can \"follow\" a file.\nTake a look at\... | [
4,
2,
1
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0000661826_file_io_python.txt |
Q:
How can I change the display text of a MenuItem in Gtk2?
I need to change the display text of a MenuItem. Is there any way of doing this without removing the MenuItem and then adding another one with a different text?
A:
It somewhat depends how you created the menu item, since a MenuItem is a container that can ... | How can I change the display text of a MenuItem in Gtk2? | I need to change the display text of a MenuItem. Is there any way of doing this without removing the MenuItem and then adding another one with a different text?
| [
"It somewhat depends how you created the menu item, since a MenuItem is a container that can contain anything. If you created it like:\nmenuitem = gtk.MenuItem('This is the label')\n\nThen you can access the label widget in the menu item with:\nlabel = menuitem.child\n\nAnd can then treat that as a normal label:\nl... | [
3
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0000669152_gtk_pygtk_python.txt |
Q:
Why GQL Query does not match?
What I want to do is build some mini cms which hold pages with a uri.
The last route in my urls.py points to a function in my views.py, which checks in the datastore if there's a page available with the same uri of the current request, and if so show the page.
I have a model:
class P... | Why GQL Query does not match? | What I want to do is build some mini cms which hold pages with a uri.
The last route in my urls.py points to a function in my views.py, which checks in the datastore if there's a page available with the same uri of the current request, and if so show the page.
I have a model:
class Page(db.Model):
title = db.String... | [
"I've found the solution!\nThe problem lies in the model. \nApp engines datastore does not index a TextProperty. Using that type was wrong from the beginning, so i changed it to StringProperty, which does get indexed, and thus which datastore allows us to use in a WHERE clause.\nExample of working model:\n class ... | [
4,
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0000669043_google_app_engine_google_cloud_datastore_python.txt |
Q:
Highlighting trailing whitespace in Textmate for Python?
I would like to do something like this Textmate tip, so that trailing whitespace are always highlighted in some way when I code something in Python - it makes it easier to correct it immediately and other editors such as Emacs can do it.
Unfortunately the di... | Highlighting trailing whitespace in Textmate for Python? | I would like to do something like this Textmate tip, so that trailing whitespace are always highlighted in some way when I code something in Python - it makes it easier to correct it immediately and other editors such as Emacs can do it.
Unfortunately the discussion after that post seems to suggest it's difficult to do... | [
"I don't know how to highlight the trailing space but you can remove it by going to\nBundles -> Text -> Converting/Stripping -> Remove trailing spaces in document\nAlso, because textmate has emacs bindings, you may be able to do it the same way you would do it in emacs.\n",
"This code works (but not with comment)... | [
5,
5
] | [] | [] | [
"macos",
"python",
"textmate"
] | stackoverflow_0000641794_macos_python_textmate.txt |
Q:
Hierarchy traversal and comparison modules for Python?
I deal with a lot of hierarchies in my day to day development. File systems, nested DAG nodes in Autodesk Maya, etc.
I'm wondering, are there any good modules for Python specifically designed to traverse and compare hierarchies of objects?
Of particular inter... | Hierarchy traversal and comparison modules for Python? | I deal with a lot of hierarchies in my day to day development. File systems, nested DAG nodes in Autodesk Maya, etc.
I'm wondering, are there any good modules for Python specifically designed to traverse and compare hierarchies of objects?
Of particular interest would be ways to do 'fuzzy' comparisons between two near... | [
"I'm not sure I see the need for a complete module -- hierarchies are a design pattern, and each hierarchy has enough unique features that it's hard to generalize.\nclass Node( object ):\n def __init__( self, myData, children=None )\n self.myData= myData\n self.children= children if children is not... | [
4,
2,
1
] | [] | [] | [
"hierarchy",
"module",
"python",
"traversal",
"tree"
] | stackoverflow_0000664898_hierarchy_module_python_traversal_tree.txt |
Q:
Encoding of string returned by GetUserName()
How do I get the encoding that is used for the string returned by GetUserName from the win32 API? I'm using pywin32 and it returns an 8-bit string. On my German XP, this string is obviously encoded using Latin-1, but this might not be the case for other Windows installa... | Encoding of string returned by GetUserName() | How do I get the encoding that is used for the string returned by GetUserName from the win32 API? I'm using pywin32 and it returns an 8-bit string. On my German XP, this string is obviously encoded using Latin-1, but this might not be the case for other Windows installations.
I could use GetUserNameW, but I would have ... | [
"You can call GetACP to find the current ANSI codepage, which is what non-Unicode APIs use. You can also use MultiByteToWideChar, and pass zero as the codepage (CP_ACP is defined as zero in the Windows headers) to convert a codepage string to Unicode.\n",
"I realize this isn't answering your question directly, bu... | [
5,
5,
4,
0
] | [] | [] | [
"encoding",
"python",
"pywin32",
"winapi"
] | stackoverflow_0000669770_encoding_python_pywin32_winapi.txt |
Q:
Unable to find files/folders with permissions 777 by AWK/SED/Python
Problems
to get permissions
of each file in every folder
to find files
which have 777 permissions, and then
print the filenames with their paths
to a list
We can get permissions for files in one folder by
ls -ls
I do not know how you can get p... | Unable to find files/folders with permissions 777 by AWK/SED/Python | Problems
to get permissions
of each file in every folder
to find files
which have 777 permissions, and then
print the filenames with their paths
to a list
We can get permissions for files in one folder by
ls -ls
I do not know how you can get permissions of each file in every folder effectively.
How can you find fil... | [
"Are you looking for find?\nfind /some/path -perm 0777\n\n",
"find /some/path -perm 0777 -type f\n"
] | [
6,
4
] | [] | [] | [
"awk",
"python",
"sed"
] | stackoverflow_0000670269_awk_python_sed.txt |
Q:
Any DAL/ORM on GAE?
Is there any Database Abstraction Layer (DAL) or Object Relational Mapper (ORM) that works on Google App Engine (GAE), and on normal relational databases (RDBS), other than web2py's?
If not, is anybody working on porting one of the existing DAL/ORM to GAE?
A:
There is an ORM for Google App E... | Any DAL/ORM on GAE? | Is there any Database Abstraction Layer (DAL) or Object Relational Mapper (ORM) that works on Google App Engine (GAE), and on normal relational databases (RDBS), other than web2py's?
If not, is anybody working on porting one of the existing DAL/ORM to GAE?
| [
"There is an ORM for Google App Engine. There are some differences between it and SQLAlchemy, but looks like it works. Check this page: http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html\n",
"Web2Py has a DAL that is compatible to GAE. In fact, the whole framework can be deployed to GAE... | [
4,
2,
0
] | [] | [] | [
"data_access_layer",
"google_app_engine",
"orm",
"python",
"rdbms"
] | stackoverflow_0000310890_data_access_layer_google_app_engine_orm_python_rdbms.txt |
Q:
Python : is it ok returning both boolean and string?
Original Question
I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false if not. This is quite convenient, but I was wondering if it is considered bad practi... | Python : is it ok returning both boolean and string? | Original Question
I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false if not. This is quite convenient, but I was wondering if it is considered bad practice or not ?
Clarification :
The primary goal is to wait fo... | [
"Would it not be more suitable to return a None instead of False?\n",
"I believe the orthodox Python design would be to return None. The manual says:\n\nNone\nThis type has a single value. There is\n a single object with this value. This\n object is accessed through the\n built-in name None. It is used to\n s... | [
27,
11,
8,
6,
5,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0000657857_python.txt |
Q:
unsubscriptable object
I'm using PIL
im = Image.open(teh_file)
if im:
colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color
red = colors[0] # and so on, some operations on color data
The problem is, on a few (very few, particulary don't know why tho... | unsubscriptable object | I'm using PIL
im = Image.open(teh_file)
if im:
colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color
red = colors[0] # and so on, some operations on color data
The problem is, on a few (very few, particulary don't know why those exactly, simple jpegs) I ... | [
"From the PIL docs:\ngetpixel\n\nim.getpixel(xy) => value or tuple\n\nReturns the pixel at the given position. If the image is a multi-layer image, this method returns a tuple.\n\nSo it seems that some of your images are multilayer, and some are single-layer.\n",
"As noted in another answer, getpixel returns eith... | [
4,
2,
2
] | [] | [] | [
"colors",
"image",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0000671363_colors_image_image_processing_python_python_imaging_library.txt |
Q:
How do I create a D-Bus service that dynamically creates multiple objects?
I'm new to D-Bus (and to Python, double whammy!) and I am trying to figure out the best way to do something that was discussed in the tutorial.
However, a text editor application
could as easily own multiple bus names
(for example, org... | How do I create a D-Bus service that dynamically creates multiple objects? | I'm new to D-Bus (and to Python, double whammy!) and I am trying to figure out the best way to do something that was discussed in the tutorial.
However, a text editor application
could as easily own multiple bus names
(for example, org.kde.KWrite in
addition to generic TextEditor), have
multiple objects (maybe... | [
"1) Mostly yes, I would only change one thing in the connect method as I explain in 2). \n2) D-Bus connections are not persistent, everything is done with request/response messages, no connection state is stored unless you implement this in third objects as you do with your flickerObject. The d-bus objects in pytho... | [
2
] | [] | [] | [
"dbus",
"python"
] | stackoverflow_0000667760_dbus_python.txt |
Q:
How do you send AT GSM commands using python?
How do i send AT GSM commands using python?
Am able to do this quite easily using Delphi and some comport component (TComport), but how do i talk to my modem using python?
Gath
A:
I do it like this with pyserial:
import serial
serialPort = serial.Serial(port=1,baudr... | How do you send AT GSM commands using python? | How do i send AT GSM commands using python?
Am able to do this quite easily using Delphi and some comport component (TComport), but how do i talk to my modem using python?
Gath
| [
"I do it like this with pyserial:\nimport serial\n\nserialPort = serial.Serial(port=1,baudrate=115200,timeout=0,rtscts=0,xonxoff=0)\ndef sendatcmd(cmd):\n serialPort.write('at'+cmd+'\\r')\n\nprint 'Loading profile...',\nsendatcmd('+npsda=0,2')\n\nThen I listen for an answer...\n",
"I don't know if there is an ... | [
15,
4
] | [] | [] | [
"modem",
"python"
] | stackoverflow_0000672366_modem_python.txt |
Q:
Getting the value of href attributes in all tags on a html file with Python
I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().
Currently I h... | Getting the value of href attributes in all tags on a html file with Python | I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().
Currently I have this code that uses regex (I'm not very good at it) to search for links in eve... | [
"Beautiful Soup can do this almost trivially:\nfrom BeautifulSoup import BeautifulSoup as soup\n\nhtml = soup('<body><a href=\"123\">qwe</a><a href=\"456\">asd</a></body>')\nprint [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})]\n\n",
"Another alternative to BeautifulSoup is lxml (http://lxml.de... | [
11,
8,
4,
3,
3,
1,
1
] | [] | [] | [
"html",
"parsing",
"python",
"regex"
] | stackoverflow_0000671323_html_parsing_python_regex.txt |
Q:
On interface up, possible to scan for a specific MAC address?
I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.
So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a pyth... | On interface up, possible to scan for a specific MAC address? | I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.
So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/h... | [
"Just make sure Avahi / Bonjour's running, then type hostname.local (or also try hostname.localdomain) - it resolves using mDNS, so you don't have to care what your IP is or rigging /etc/hosts.\n",
"Sorry, it looks like an attempt to create a problem where no problem exists, and subsequently solve it using a bit ... | [
1,
1,
1,
0
] | [] | [] | [
"linux",
"networking",
"python",
"sysadmin"
] | stackoverflow_0000637399_linux_networking_python_sysadmin.txt |
Q:
Python Programming - Rules/Advice for developing enterprise-level software in Python?
I'm a somewhat advanced C++/Java Developer who recently became interested in Python and I enjoy its dynamic typing and efficient coding style very much. I currently use it on my small programming needs like solving programming ri... | Python Programming - Rules/Advice for developing enterprise-level software in Python? | I'm a somewhat advanced C++/Java Developer who recently became interested in Python and I enjoy its dynamic typing and efficient coding style very much. I currently use it on my small programming needs like solving programming riddles and scripting, but I'm curious if anyone out there has successfully used Python in an... | [
"I'm using Python for developing a complex insurance underwriting application.\nOur application software essentially repackages our actuarial model in a form that companies can subscribe to it. This business is based on our actuaries and their deep thinking. We're not packaging a clever algorithm that's relatively... | [
17,
3
] | [] | [] | [
"design_patterns",
"dynamic_typing",
"java",
"programming_languages",
"python"
] | stackoverflow_0000672781_design_patterns_dynamic_typing_java_programming_languages_python.txt |
Q:
Django Custom Queryset filters
Is there, in Django, a standard way to write complex, custom filters for QuerySets?
Just as I can write
MyClass.objects.all().filter(field=val)
I'd like to do something like this :
MyClass.objects.all().filter(customFilter)
I could use a generator expression
(x for x in MyClass.o... | Django Custom Queryset filters | Is there, in Django, a standard way to write complex, custom filters for QuerySets?
Just as I can write
MyClass.objects.all().filter(field=val)
I'd like to do something like this :
MyClass.objects.all().filter(customFilter)
I could use a generator expression
(x for x in MyClass.objects.all() if customFilter(x))
bu... | [
"The recommendation to start using manager methods is a good one, but to answer your question more directly: yes, use Q objects. For example:\nfrom django.db.models import Q\n\ncomplexQuery = Q(name__startswith='Xa') | ~Q(birthdate__year=2000)\n\nMyModel.objects.filter(complexQuery)\n\nQ objects can be combined wi... | [
16,
9
] | [] | [] | [
"django",
"django_queryset",
"generator_expression",
"python"
] | stackoverflow_0000672182_django_django_queryset_generator_expression_python.txt |
Q:
What signals should I catch for clipboard pasting and character insertion in GTK?
I have a Window with a TextView, and I would like to perform some actions when the user pastes some text.
I would also like to know what signal(s) should I catch in order to perform something when the user presses a key inside the T... | What signals should I catch for clipboard pasting and character insertion in GTK? | I have a Window with a TextView, and I would like to perform some actions when the user pastes some text.
I would also like to know what signal(s) should I catch in order to perform something when the user presses a key inside the TextView.
Can you tell me what are the signals I must connect?
| [
"For paste: Take a look at the paste-done signal of the GtkTextBuffer class, it sounds about right.\nFor regular character insert: insert-text.\n"
] | [
2
] | [] | [] | [
"clipboard",
"gtk",
"pygtk",
"python",
"signals"
] | stackoverflow_0000673605_clipboard_gtk_pygtk_python_signals.txt |
Q:
python: arbitrary order by
In Oracle SQL there is a feature to order as follow:
order by decode("carrot" = 2
,"banana" = 1
,"apple" = 3)
What is the best way to implement this in python?
I want to be able to order a dict by its keys. And that order isn't necessarily alphabetically or... | python: arbitrary order by | In Oracle SQL there is a feature to order as follow:
order by decode("carrot" = 2
,"banana" = 1
,"apple" = 3)
What is the best way to implement this in python?
I want to be able to order a dict by its keys. And that order isn't necessarily alphabetically or anything - I determine the orde... | [
"Use the key named keyword argument of sorted().\n#set up the order you want the keys to appear here\norder = [\"banana\", \"carrot\", \"apple\"]\n\n# this uses the order list to sort the actual keys.\nsorted(keys, key=order.index)\n\nFor higher performance than list.index, you could use dict.get instead.\n#this bu... | [
17,
4,
2,
1,
1,
0
] | [] | [] | [
"python",
"sql_order_by"
] | stackoverflow_0000673867_python_sql_order_by.txt |
Q:
Using PiL to take a screenshot of HTML/CSS
I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery.
After they've made the image the way they want it, is there a way i can take a s... | Using PiL to take a screenshot of HTML/CSS | I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery.
After they've made the image the way they want it, is there a way i can take a screenshot of that image (using PiL) and save it ... | [
"Taking a \"screenshot\" of the picture is neither the best, nor the proper way to do it. To take a screenshot, you need to execute code on the client machine, which is \"not possible\" in a website scenario.\nHave a look at lolcat builder (I can't think of a more serious example right now ;). Everytime you click t... | [
2,
1,
0,
0
] | [] | [] | [
"css",
"jquery",
"python",
"python_imaging_library",
"xhtml"
] | stackoverflow_0000673725_css_jquery_python_python_imaging_library_xhtml.txt |
Q:
How to read from an os.pipe() without getting blocked?
I'm trying to read from an open os.pipe() to see if it's empty at the moment of the reading. The problem is that calling read() causes the program to block there until there is actually something to read there however there won't be any, if the test I'm doing ... | How to read from an os.pipe() without getting blocked? | I'm trying to read from an open os.pipe() to see if it's empty at the moment of the reading. The problem is that calling read() causes the program to block there until there is actually something to read there however there won't be any, if the test I'm doing succeeded.
I know I can use select.select() with a timeout ... | [
"You might try this. \nimport os, fcntl\nfcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK) \n\nWith this thePipe.read() should be non-blocking. \nFrom pipe(7) man page:\n\nIf a process attempts to read from an\n empty pipe, then read(2) will block\n until data is available. (...)\n Non-blocking I/O is possible ... | [
17
] | [] | [] | [
"file",
"pipe",
"python"
] | stackoverflow_0000673844_file_pipe_python.txt |
Q:
How should I best emulate and/or avoid enum's in Python?
I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations?
Class code here:
class Enum(object):
'''Simple Enum Class
Example Usage:
>>> codes = Enum('FOO BAR BAZ') # cod... | How should I best emulate and/or avoid enum's in Python? | I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations?
Class code here:
class Enum(object):
'''Simple Enum Class
Example Usage:
>>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...'''
def __init__(self, names):
... | [
"Enums have been proposed for inclusion into the language before, but were rejected (see http://www.python.org/dev/peps/pep-0354/), though there are existing packages you could use instead of writing your own implementation:\n\nenum: http://pypi.python.org/pypi/enum\nSymbolType (not quite the same as enums, but sti... | [
5,
4,
3,
3,
2,
1
] | [] | [] | [
"enums",
"python"
] | stackoverflow_0000108523_enums_python.txt |
Q:
In Python 2.6, How Might You Pass a List Object to a Method Which Expects A List of Arguments?
I have a list full of various bits of information that I would like to pass to several strings for inclusion via the new string format method. As a toy example, let us define
thelist = ['a', 'b', 'c']
I would like to d... | In Python 2.6, How Might You Pass a List Object to a Method Which Expects A List of Arguments? | I have a list full of various bits of information that I would like to pass to several strings for inclusion via the new string format method. As a toy example, let us define
thelist = ['a', 'b', 'c']
I would like to do a print statement like print '{0} {2}'.format(thelist) and print '{1} {2}'.format(thelist)
When I ... | [
".format(*thelist)\nIt's part of the calling syntax in Python. I don't know the name either, and I'm not convinced it has one. See the tutorial.\nIt doesn't just work on lists, though, it works for any iterable object.\n",
"'{0} {2}'.format(*thelist)\n\ndocs\n"
] | [
10,
2
] | [] | [] | [
"arguments",
"list",
"python"
] | stackoverflow_0000674690_arguments_list_python.txt |
Q:
How to display errors to the user while still logging it?
I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs.
My issue is that I need to catch an exception when it happens and let... | How to display errors to the user while still logging it? | I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs.
My issue is that I need to catch an exception when it happens and let the user know that it happened, but still let the traceback pr... | [
"I think you are thinking about this in the wrong way. You shouldn't be re-raising the error simply to log it further down the line. The cannonical way of doing this in Python is to use the logging module. Adapted from the docs:\nimport logging\nLOG_FILENAME = '/tmp/logging_example.out'\nlogging.basicConfig(filenam... | [
6,
3,
1
] | [] | [] | [
"error_handling",
"error_logging",
"exception_handling",
"pyqt4",
"python"
] | stackoverflow_0000674067_error_handling_error_logging_exception_handling_pyqt4_python.txt |
Q:
benchmarking PHP vs Pylons
I want to benchmark PHP vs Pylons. I want my comparison of both to be as even as possible, so here is what I came up with:
PHP 5.1.6 with APC, using a smarty template connecting to a MySQL database
Python 2.6.1, using Pylons with a mako template connecting the the same MySQL database
I... | benchmarking PHP vs Pylons | I want to benchmark PHP vs Pylons. I want my comparison of both to be as even as possible, so here is what I came up with:
PHP 5.1.6 with APC, using a smarty template connecting to a MySQL database
Python 2.6.1, using Pylons with a mako template connecting the the same MySQL database
Is there anything that I should c... | [
"If you're not using an ORM in PHP you should not use the SQLAlchemy ORM or SQL-Expression language either but use raw SQL commands. If you're using APC you should make sure that Python has write privileges to the folder your application is in, or that the .py files are precompiled.\nAlso if you're using the smart... | [
3,
2
] | [] | [] | [
"benchmarking",
"php",
"pylons",
"python"
] | stackoverflow_0000674739_benchmarking_php_pylons_python.txt |
Q:
How to upload a file with django (python) and s3?
I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code:
View:
def submitpicture(request):
fuser = request.session["login"]
copied_data = request.POST.copy()... | How to upload a file with django (python) and s3? | I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code:
View:
def submitpicture(request):
fuser = request.session["login"]
copied_data = request.POST.copy()
copied_data.update(request.FILES)
content_type... | [
"You will have to provide the enctype attribute to the FORM element (I've been bitten by this before). For example, your FORM tag should look like: \n<form action=\"/submitpicture/\" method=\"POST\" enctype=\"multipart/form-data\" >\n\nWithout the enctype, you will find yourself with an empty request.FILES.\n",
"... | [
19,
5,
2
] | [] | [] | [
"amazon_s3",
"django",
"file_upload",
"python"
] | stackoverflow_0000319923_amazon_s3_django_file_upload_python.txt |
Q:
Python, __init__ and self confusion
Alright, so I was taking a look at some source when I came across this:
>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... ... | Python, __init__ and self confusion | Alright, so I was taking a look at some source when I came across this:
>>> def __parse(self, filename):
... "parse ID3v1.0 tags from MP3 file"
... self.clear()
... try:
... fsock = open(filename, "rb", 0)
... try:
... fsock.seek(-128, 2)
... ... | [
"The def __parse was inside some class definition.\nYou can't pull the method defs out of the class definitions. The method function definition is part of the class.\nLook at these two examples:\ndef add( a, b ):\n return a + b\n\nAnd\nclass Adder( object ):\n def __init__( self ):\n self.grand_total ... | [
8,
2,
1,
0,
0
] | [] | [] | [
"init",
"python",
"self"
] | stackoverflow_0000674600_init_python_self.txt |
Q:
learning python 3.0 on ubuntu
[resolved]
I tweaked the preferences in komodo edit and ended up with:
don't auto indent
don't allow file contents to override tab settings
prefer tab characters over spaces
4 spaces per indent
4 width of each tab char
I also set komodo to show whitespace and tabs, which eneded up rev... | learning python 3.0 on ubuntu | [resolved]
I tweaked the preferences in komodo edit and ended up with:
don't auto indent
don't allow file contents to override tab settings
prefer tab characters over spaces
4 spaces per indent
4 width of each tab char
I also set komodo to show whitespace and tabs, which eneded up revealing the screwed up sections.
yea... | [
"The example used python 2.x , since python apparently referred to python2.x (for some x), not python3.0 (which is good, since most programs are for 2.x).\nThe second two examples used python 3.0 . You mixed tabs and spaces in your source, and should get rid of the tab characters (don't retype-- use regular-express... | [
2
] | [] | [] | [
"development_environment",
"komodo",
"python",
"ubuntu"
] | stackoverflow_0000675754_development_environment_komodo_python_ubuntu.txt |
Q:
Does Python have something like Perl 5.10's "state" variables?
In Perl 5.10, I can say:
sub foo () {
state $x = 1;
say $x++;
}
foo();
foo();
foo();
...and it will print out:
1
2
3
Does Python have something like this?
A:
A class may be a better fit here (and is usually a better fit for anything involving ... | Does Python have something like Perl 5.10's "state" variables? | In Perl 5.10, I can say:
sub foo () {
state $x = 1;
say $x++;
}
foo();
foo();
foo();
...and it will print out:
1
2
3
Does Python have something like this?
| [
"A class may be a better fit here (and is usually a better fit for anything involving \"state\"):\nclass Stateful(object):\n\n def __init__(self):\n self.state_var = 0\n\n def __call__(self):\n self.state_var = self.state_var + 1\n print self.state_var\n\nfoo = Stateful()\nfoo()\nfoo()\n\... | [
18,
12,
9,
9,
5,
3,
2,
2,
2,
1,
1
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0000604622_perl_python.txt |
Q:
Is there a Python library for easily writing zoomable UI's?
My next work is going to be heavily focused on working with data that is best understood when organized on a two-dimensional zoomable plane or canvas, instead of using lists and property forms.
The library can be based on OpenGL, GTK+ or Cairo. It should ... | Is there a Python library for easily writing zoomable UI's? | My next work is going to be heavily focused on working with data that is best understood when organized on a two-dimensional zoomable plane or canvas, instead of using lists and property forms.
The library can be based on OpenGL, GTK+ or Cairo. It should allow me to:
build widgets out of vector shapes and text (perhap... | [
"Qt has this covered... check PyQt\n",
"I think Clutter is perfect for you.\nFrom the web site:\n\nClutter is an open source software\n library for creating fast, visually\n rich and animated graphical user\n interfaces.\n\nClutter is written in C, but it has great Python bindings.\nA very similar project is P... | [
3,
2
] | [] | [] | [
"cairo",
"gtk",
"opengl",
"python",
"user_interface"
] | stackoverflow_0000673434_cairo_gtk_opengl_python_user_interface.txt |
Q:
Error while deploying Django on Apache
I have a small Django website which I am trying to run on an Apache 2.2 HTTP-Server.
The application is running fine using "python manage.py runserver".
Django Version: 1.0.2 final
Python: 2.5
OS: Windows 2000
I wen't through the steps described in the documentation and aft... | Error while deploying Django on Apache | I have a small Django website which I am trying to run on an Apache 2.2 HTTP-Server.
The application is running fine using "python manage.py runserver".
Django Version: 1.0.2 final
Python: 2.5
OS: Windows 2000
I wen't through the steps described in the documentation and after some fiddling, came out with the followin... | [
"The problem is that you are importing your app (\"main\") as if it lives directly on the Python path, and your URLconf (\"therap.urls\") as if it lives within a \"therap\" module on the Python path. This can only work if both \"D:/therap\" and \"D:/therap/therap\" are BOTH on the Python path (which runserver does... | [
3
] | [] | [] | [
"apache",
"django",
"mod_python",
"python",
"windows"
] | stackoverflow_0000673936_apache_django_mod_python_python_windows.txt |
Q:
Is it possible to implement properties in languages other than C#?
During a bout of C# and WPF recently, I got to like C#'s properties:
public double length_inches
{
get { return length_metres * 39.0; }
set { length_metres = value/39.0; }
}
Noticing, of course, that length_metres may change from being a f... | Is it possible to implement properties in languages other than C#? | During a bout of C# and WPF recently, I got to like C#'s properties:
public double length_inches
{
get { return length_metres * 39.0; }
set { length_metres = value/39.0; }
}
Noticing, of course, that length_metres may change from being a field to a property, and the code need not care. WPF can also bind UI ele... | [
"Python definitely supports properties:\nclass Foo(object):\n\n def get_length_inches(self):\n return self.length_meters * 39.0\n\n def set_length_inches(self, val):\n self.length_meters = val/39.0\n\n length_inches = property(get_length_inches, set_length_inches)\n\nStarting in Python 2.5, s... | [
18,
8,
6,
4,
3,
3,
2,
2,
2,
1,
0,
0,
0,
0,
0,
0
] | [
"The convention is to implement a get_PropertyName() and a set_PropertyName() method (that's all it is in the CLR as well. Properties are just syntactic sugar in VB.NET/C# - which is why a change from field to property or vice-versa is breaking and requires client code to recompile.\npublic int get_SomeValue() { re... | [
-1
] | [
"c#",
"javascript",
"php",
"properties",
"python"
] | stackoverflow_0000675161_c#_javascript_php_properties_python.txt |
Q:
Create static graphics files (png, gif, jpg) using Ruby or Python
I'd like to create a graphic image on the fly based on user input, and then present that image as a PNG file (or jpg or gif if necessary, but PNG is preferred).
This is actually for an astrology application; what I'd like to do is generate the chart... | Create static graphics files (png, gif, jpg) using Ruby or Python | I'd like to create a graphic image on the fly based on user input, and then present that image as a PNG file (or jpg or gif if necessary, but PNG is preferred).
This is actually for an astrology application; what I'd like to do is generate the chart in PNG for display.
Python or Ruby is fine; in fact, the library avail... | [
"Maybe a vectorial format is better suited for your needs, but is hard to tell without having a concrete example of what you'd like to get.\nFor example, if the images are all alike, you could create a SVG base image with Inkscape, then edit it programmaticaly from Python or Ruby (either by editing the text or usin... | [
11,
9,
3,
2,
2,
1
] | [] | [] | [
"graphics",
"png",
"python",
"ruby"
] | stackoverflow_0000676159_graphics_png_python_ruby.txt |
Q:
How do I generate test data for my Python script?
A equation takes values in the following form :
x = [0x02,0x00] # which is later internally converted to in the called function to 0x300
y = [0x01, 0xFF]
z = [0x01, 0x0F]
How do I generate a series of test values for this function ?
for instance I w... | How do I generate test data for my Python script? | A equation takes values in the following form :
x = [0x02,0x00] # which is later internally converted to in the called function to 0x300
y = [0x01, 0xFF]
z = [0x01, 0x0F]
How do I generate a series of test values for this function ?
for instance I want to send a 100 odd values from a for loop
for i in ... | [
"use generators:\ndef gen_xyz( max_iteration ):\n for i in xrange( 0, max_iteration ):\n # code which will generate next ( x, y, z )\n yield ( x, y, z ) \n\nfor x, y, z in gen_xyz( 1000 ):\n f( x, y, z )\n\n",
"The hex() function?\nimport random\nfor i in range(10):\n a1, a2 = random.randint(1,... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0000676198_python.txt |
Q:
Are there any built-in cross-thread events in python?
Is there any built-in syntax in python that allows me to post a message to specific python thread inside my problem? Like 'queued connected signal' in pyQt or ::PostMessage() in Windows. I need this for asynchronous communication between program parts: there is... | Are there any built-in cross-thread events in python? | Is there any built-in syntax in python that allows me to post a message to specific python thread inside my problem? Like 'queued connected signal' in pyQt or ::PostMessage() in Windows. I need this for asynchronous communication between program parts: there is a number of threads that handle network events and they ne... | [
"The Queue module is python is well suited to what you're describing.\nYou could have one queue set up that is shared between all your threads. The threads that handle the network events can use queue.put to post events onto the queue. The logic thread would use queue.get to retrieve events from the queue.\nimpor... | [
11,
1
] | [] | [] | [
"delegates",
"events",
"python"
] | stackoverflow_0000676485_delegates_events_python.txt |
Q:
verbose_name_plural unexpected in a model?
I've been doing some models of a future app, and, after adding verbose_name and verbose_name_plural to every entry on a working model, for making it 'beautiful', I've found that at validate time, Django doesn't like that, so it says:
File "/home/andor/Documentos/desarro... | verbose_name_plural unexpected in a model? | I've been doing some models of a future app, and, after adding verbose_name and verbose_name_plural to every entry on a working model, for making it 'beautiful', I've found that at validate time, Django doesn't like that, so it says:
File "/home/andor/Documentos/desarrollo/grundymanage/../grundymanage/concursantes/mo... | [
"There is no verbose_name_plural. It does not make sense to have both singular and plural for one field. They are mutually exclusive. In Django, they share the same name: verbose_name.\nIf your data represents multiple items (e.g. in a one-to-many relationship) use a plural form in verbose_name. Otherwise, if y... | [
5,
5
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000677172_django_django_models_python.txt |
Q:
What's the best online tutorial for starting with Spring Python
Spring Python seems to be the gold-standard for how to define good quality APIs in Python - it's based on Spring which also seems to be the gold-standard for Java APIs.
My manager has complained (with good reason) that our APIs are in a mess - we need... | What's the best online tutorial for starting with Spring Python | Spring Python seems to be the gold-standard for how to define good quality APIs in Python - it's based on Spring which also seems to be the gold-standard for Java APIs.
My manager has complained (with good reason) that our APIs are in a mess - we need to impose some order on them. Since we will be re-factoring it makes... | [
"How did you come to decide on Spring Python as your API of choice? Spring works well on Java where there's a tradition of declarative programming; defining your application primarily using XML to control a core engine is a standard pattern in Java. \nIn Python, while the underlying patterns like Inversion of Contr... | [
11,
1
] | [] | [] | [
"python",
"spring"
] | stackoverflow_0000677255_python_spring.txt |
Q:
How to check if an RGB image contains only one color?
I'm using Python and PIL.
I have images in RGB and I would like to know those who contain only one color (say #FF0000 for example) or a few very close colors (#FF0000 and #FF0001).
I was thinking about using the histogram but it is very hard to figure out somet... | How to check if an RGB image contains only one color? | I'm using Python and PIL.
I have images in RGB and I would like to know those who contain only one color (say #FF0000 for example) or a few very close colors (#FF0000 and #FF0001).
I was thinking about using the histogram but it is very hard to figure out something with the 3 color bands, so I'm looking for a more clev... | [
"Try the ImageStat module. If the values returned by extrema are the same, you have only a single color in the image.\n",
"First, you should define a distance between two colors.\nThen you just have to verify for each pixel that it's distance to your color is small enough.\n",
"Here's a little snippet you could... | [
6,
0,
0
] | [] | [] | [
"colors",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0000677395_colors_image_python_python_imaging_library.txt |
Q:
How to extract from a list of objects a list of specific attribute?
I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.
Is there any built-in functions to do that?
A:
A list comprehension would work just fine:
[o.my_attr for o in my_lis... | How to extract from a list of objects a list of specific attribute? | I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class.
Is there any built-in functions to do that?
| [
"A list comprehension would work just fine:\n[o.my_attr for o in my_list]\n\nBut there is a combination of built-in functions, since you ask :-)\nfrom operator import attrgetter\nmap(attrgetter('my_attr'), my_list)\n\n",
"are you looking for something like this?\n[o.specific_attr for o in objects]\n\n",
"The fi... | [
88,
10,
9,
4
] | [] | [] | [
"python"
] | stackoverflow_0000677656_python.txt |
Q:
Yahoo Pipes, simplejson and slashes
Im trying to use http://www.javarants.com/2008/04/13/using-google-app-engine-to-extend-yahoo-pipes/ as inspiration, but I'm having some troubles with the output.
Its obvious when testing with the console and the App Engine "django util simplejson":
/cygdrive/c/Program Files/Goog... | Yahoo Pipes, simplejson and slashes | Im trying to use http://www.javarants.com/2008/04/13/using-google-app-engine-to-extend-yahoo-pipes/ as inspiration, but I'm having some troubles with the output.
Its obvious when testing with the console and the App Engine "django util simplejson":
/cygdrive/c/Program Files/Google/google_appengine/lib/django
$ python
P... | [
"Nothing here to see. The ticket is there, but thats it, as far as I can see\n"
] | [
0
] | [] | [] | [
"python",
"simplejson",
"yahoo_pipes"
] | stackoverflow_0000610205_python_simplejson_yahoo_pipes.txt |
Q:
Using 'old' database with django
I'm using a hand built (Postgres) database with Django. With "inspectdb" I was able to automatically create a model for it. The problem is that some tables have multiple primary keys (for many-to-many relations) and they are not accessible via Django.
What's the best way to access... | Using 'old' database with django | I'm using a hand built (Postgres) database with Django. With "inspectdb" I was able to automatically create a model for it. The problem is that some tables have multiple primary keys (for many-to-many relations) and they are not accessible via Django.
What's the best way to access these tables?
| [
"There is no way to use composite primary keys in Django's ORM as of now (up to v1.0.2).\nI can only think of three solutions/workarounds:\n\nThere is a fork of django with a composite pk patch at github that you might want to try.\nYou could use SQLAlchemy together with Django.\nYou have to add a single field prim... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000677476_django_python.txt |
Q:
python and symbian - keystroke capture
I'm trying to write a simple prototyping appliaction in python to capture a users keystrokes while writing a text messages (SMS) to collect some stat info for use in a biometric application for Symbian based phones. I have never used python before and have had very little exp... | python and symbian - keystroke capture | I'm trying to write a simple prototyping appliaction in python to capture a users keystrokes while writing a text messages (SMS) to collect some stat info for use in a biometric application for Symbian based phones. I have never used python before and have had very little exposure to it. However, I did come across an e... | [
"I think you are searching for the wrong thing here.\nKey codes and keypress events will only capture up, down, etc. (actual buttons), as you already stated. The user can enter letters in multiple ways, which is all done through software (e.g. 22 is a 'b', or 228 might be 'cat' or 'bat') and there is no way to tell... | [
1
] | [] | [] | [
"pys60",
"python",
"symbian"
] | stackoverflow_0000677846_pys60_python_symbian.txt |
Q:
Doctest for dynamically created objects
What is the best way to test code like this (the one below obviously fails while object is created in different block every time):
def get_session(db_name, verbose, test):
"""Returns current DB session from SQLAlchemy pool.
>>> get_session('Mmusc20090126', False, True)
<sql... | Doctest for dynamically created objects | What is the best way to test code like this (the one below obviously fails while object is created in different block every time):
def get_session(db_name, verbose, test):
"""Returns current DB session from SQLAlchemy pool.
>>> get_session('Mmusc20090126', False, True)
<sqlalchemy.orm.session.Session object at 0xfb5ff... | [
"I think you want to use ellipsis, like this:\n>>> get_session('Mmusc20090126', False, True) #doctest: +ELLIPSIS\n<sqlalchemy.orm.session.Session object at 0x...>\n\nSee here for more info.\n"
] | [
10
] | [] | [] | [
"docstring",
"doctest",
"python",
"sqlalchemy",
"testing"
] | stackoverflow_0000677931_docstring_doctest_python_sqlalchemy_testing.txt |
Q:
Specifying different template names in Django generic views
I have the code in my urls.py for my generic views;
infodict = {
'queryset': Post.objects.all(),
'date_field': 'date',
'template_name': 'index.html',
'template_object_name': 'latest_post_list',
}
urlpatterns += patterns('django.views.generic.date_based',... | Specifying different template names in Django generic views | I have the code in my urls.py for my generic views;
infodict = {
'queryset': Post.objects.all(),
'date_field': 'date',
'template_name': 'index.html',
'template_object_name': 'latest_post_list',
}
urlpatterns += patterns('django.views.generic.date_based',
(r'^gindex/$', 'archive_index', infodict),
)
So going to the ad... | [
"Use the dict() constructor:\ninfodict = {\n 'queryset': Post.objects.all(),\n 'date_field': 'date',\n 'template_name': 'index.html',\n 'template_object_name': 'latest_post_list',\n}\n\nurlpatterns = patterns('django.views.generic.date_based',\n url(r'^gindex/$', 'archive_index', dict(infodict, templ... | [
8,
1,
0,
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0000677793_django_django_urls_python.txt |
Q:
What payment processing frameworks, like ActiveMerchant, are available for other languages?
Rails has frameworks such as ActiveMerchant and Freemium (which uses ActiveMerchant) to simplify dealing with payment processing. What other frameworks are there for other programming languages such as PHP or Python?
A:
E... | What payment processing frameworks, like ActiveMerchant, are available for other languages? | Rails has frameworks such as ActiveMerchant and Freemium (which uses ActiveMerchant) to simplify dealing with payment processing. What other frameworks are there for other programming languages such as PHP or Python?
| [
"Edit For processing payments, there are several GetPaid modules available for Python.\nCheck out the core package, as well as some extensions for different payment methods.\n----------original answer------------\nFrom a StackOverflow search: Satchmo is a Python alternative.\nSee that question link above for othe... | [
3
] | [] | [] | [
"activemerchant",
"php",
"programming_languages",
"python",
"ruby_on_rails"
] | stackoverflow_0000678525_activemerchant_php_programming_languages_python_ruby_on_rails.txt |
Q:
Fill Django application with data using very large Python script
I wrote a program that outputs a Python program that fills my Django application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this?
Another possible solution to fill the database would be using ... | Fill Django application with data using very large Python script | I wrote a program that outputs a Python program that fills my Django application with data. This program however is 23 MB large and my computer won't run it. Is there a solution for this?
Another possible solution to fill the database would be using a fixture. The problem is that I don't know the new primary keys yet..... | [
"In most cases, you can find a natural hierarchy to your objects. Sometimes there is some kind of \"master\" and all other objects have foreign key (FK) references to this master and to each other.\nIn this case, you can use an XML-like structure with each master object \"containing\" a lot of subsidiary objects. ... | [
1,
0,
0,
0
] | [] | [] | [
"database",
"django",
"migration",
"python"
] | stackoverflow_0000677962_database_django_migration_python.txt |
Q:
What's the correct way to add extra find-links to easy_install when called as a function?
I need to call easy_install as a function to install some Python eggs from a bunch of servers. Precisely what I install and where I get it from is determined at run-time: For example which servers I use depends on the geograp... | What's the correct way to add extra find-links to easy_install when called as a function? | I need to call easy_install as a function to install some Python eggs from a bunch of servers. Precisely what I install and where I get it from is determined at run-time: For example which servers I use depends on the geographic location of the computer.
Since I cannot guarantee that any single server will always be av... | [
"Quote:\nmyargs = ['-vv', '-m', '-a', '-f', '//filesrver/eggs http://webserver1/python_eggs http://webserver2/python_eggs, 'myproject==trunk-99']\n\nsetuptools.command.easy_install.main( myargs )\n\nThis first problem I see with this is that you're missing a single quote on the end of your list of servers to look i... | [
3
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0000659575_python_setuptools.txt |
Q:
Select Distinct Years and Months for Django Archive Page
I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So i... | Select Distinct Years and Months for Django Archive Page | I want to make an archive_index page for my django site. However, the date-based generic views really aren't any help. I want the dictionary returned by the view to have all the years and months for which at least one instance of the object type exists. So if my blog started in September 2007, but there were no posts i... | [
"This will give you a list of unique posting dates:\nPosts.objects.filter(draft=False).dates('post_date','month',order='DESC')\n\nOf course you might not need the draft filter, and change 'post_date' to your field name, etc.\n",
"I found the answer to my own question. \nIt's on this page in the documentation.\nTh... | [
41,
14,
1
] | [] | [] | [
"datetime",
"django",
"django_queryset",
"django_views",
"python"
] | stackoverflow_0000678927_datetime_django_django_queryset_django_views_python.txt |
Q:
SQLAlchemy with count, group_by and order_by using the ORM
I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the ind... | SQLAlchemy with count, group_by and order_by using the ORM | I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to do ... | [
"What you're trying to do maps directly to a SQLAlchemy join between a subquery [made from your current select call] and a table. You'll want to move the ordering out of the subselect and create a separate, labeled column with count(desc); order the outer select by that column.\nOther than that, I don't see much th... | [
1,
1,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0000370174_python_sqlalchemy.txt |
Q:
min heap in python
I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap?
A:
Two options... | min heap in python | I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap?
| [
"Two options (aside from Devin Jeanpierre's suggestion):\n\nDecorate your data before using the heap. This is the equivalent of the key= option to sorting. e.g. if you (for some reason) wanted to heapify a list of numbers according to their sine:\ndata = [ # list of numbers ]\nheap = [(math.sin(x), x) for x in da... | [
16,
14
] | [] | [] | [
"heap",
"min_heap",
"object",
"python"
] | stackoverflow_0000679731_heap_min_heap_object_python.txt |
Q:
Python 2.5.2 continued
This is a continuation of my question Python2.5.2
The code i developed is working fine with clr.Addreference().
Now thee problem is I have to load ny script which uses dll developed in .NET to another application.They had used QT for its implementation.There is a Script console in that appli... | Python 2.5.2 continued | This is a continuation of my question Python2.5.2
The code i developed is working fine with clr.Addreference().
Now thee problem is I have to load ny script which uses dll developed in .NET to another application.They had used QT for its implementation.There is a Script console in that application.When ii entered 'impo... | [
"You won't be able to run your script in that application. The script console in that QT application doubtlessly uses plain ol' CPython instead of IronPython. There's no real good way to change that without significant surgery to the application that's hosting the python console.\n"
] | [
3
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0000680336_ironpython_python.txt |
Q:
Why does windows give an sqlite3.OperationalError and linux does not?
The problem
I've got a programm that uses storm 0.14 and it gives me this error on windows:
sqlite3.OperationError: database table is locked
The thing is, under linux it works correctly.
I've got the impression that it happens only after a cer... | Why does windows give an sqlite3.OperationalError and linux does not? | The problem
I've got a programm that uses storm 0.14 and it gives me this error on windows:
sqlite3.OperationError: database table is locked
The thing is, under linux it works correctly.
I've got the impression that it happens only after a certain amount of changes have been done, as it happens in some code, that cop... | [
"The \"database table is locked\" error is often a generic/default error in SQLite, so narrowing down your problem is not obvious.\nAre you able to execute any SQL queries? I would start there, and get some basic SELECT statements working. It could just be a permissions issue.\n",
"Hard to say without a little m... | [
1,
1,
1,
1,
1
] | [] | [] | [
"linux",
"python",
"sqlite",
"windows"
] | stackoverflow_0000679162_linux_python_sqlite_windows.txt |
Q:
wxPython: Making a scrollable DC
I am drawing inside a wx.Window using a PaintDC. I am drawing circles and stuff like that into that window. Problem is, sometimes the circles go outside the scope of the window. I want a scrollbar to automatically appear whenever the drawing gets too big. What do I do?
A:
Use a w... | wxPython: Making a scrollable DC | I am drawing inside a wx.Window using a PaintDC. I am drawing circles and stuff like that into that window. Problem is, sometimes the circles go outside the scope of the window. I want a scrollbar to automatically appear whenever the drawing gets too big. What do I do?
| [
"Use a wx.ScrolledWindow and set the size of the window as soon as your 'drawing go outside' the window with\nSetVirtualSize(width,height)\n\nIf this size is bigger than the client size, then wx will show scrollbars. When drawing in the window make sure to use CalcUnscrolledPosition and CalcScrolledPosition\nHere y... | [
1
] | [] | [] | [
"python",
"scroll",
"scrollbar",
"wxpython"
] | stackoverflow_0000677590_python_scroll_scrollbar_wxpython.txt |
Q:
How can I make the Django contrib Admin change list for a particular model class editable with drop downs for related items displayed in the listing?
Basically I want to have an editable form for related entries instead of a static listing.
A:
Try Django 1.1 beta. It's got the option to make items in the chang... | How can I make the Django contrib Admin change list for a particular model class editable with drop downs for related items displayed in the listing? | Basically I want to have an editable form for related entries instead of a static listing.
| [
"Try Django 1.1 beta. It's got the option to make items in the changelist editable (as well as incorporating the django-batchadmin project) \n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0000673970_django_django_admin_django_forms_django_templates_python.txt |
Q:
Python dynamic function names
I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function
if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
... | Python dynamic function names | I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function
if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
ret... | [
"you might find getattr useful, I guess\nimport module\ngetattr(module, status.lower())(*args, **kwargs)\n\n",
"The canonical way to do this is to use a dictionary to emulate switch or if/elif. You will find several questions to similar problems here on SO.\nPut your functions into a dictionary with your status c... | [
38,
20,
15,
5,
4,
3,
1,
0
] | [] | [] | [
"factory",
"python"
] | stackoverflow_0000680941_factory_python.txt |
Q:
Python: How to extract variable name of a dictionary entry?
I'm wondering how I would go about finding the variable name of a dictionary element:
For example:
>>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
... | Python: How to extract variable name of a dictionary entry? | I'm wondering how I would go about finding the variable name of a dictionary element:
For example:
>>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
How can I... | [
"A variable name is just a name--it has no real meaning as far as the program is concerned, except as a convenience to the programmer (this isn't quite true in Python, but bear with me). As far as the Python interpreter is concerned, the name dict1 is just the programmer's way of telling Python to look at memory ad... | [
9,
7,
4,
1,
1,
0,
0
] | [] | [] | [
"dictionary",
"lookup",
"python",
"variables"
] | stackoverflow_0000680032_dictionary_lookup_python_variables.txt |
Q:
Whats the difference between list[-1:][0] and list[len(list)-1]?
Lest say you want the last element of a python list: what is the difference between
myList[-1:][0]
and
myList[len(myList)-1]
I thought there was no difference but then I tried this
>>> list = [0]
>>> list[-1:][0]
0
>>> list[-1:][0] += 1
>>> list
[... | Whats the difference between list[-1:][0] and list[len(list)-1]? | Lest say you want the last element of a python list: what is the difference between
myList[-1:][0]
and
myList[len(myList)-1]
I thought there was no difference but then I tried this
>>> list = [0]
>>> list[-1:][0]
0
>>> list[-1:][0] += 1
>>> list
[0]
>>> list[len(list)-1] += 1
>>> list
[1]
I was a little surprised..... | [
"if you use slicing [-1:], the returned list is a shallow-copy, not reference. so [-1:][0] modifies the new list. [len(list)-1] is reference to last object.\n",
"list[-1:] creates a new list. To get the same behaviour as list[len(list)-1] it would have to return a view of some kind of list, but as I said, it crea... | [
14,
9,
3
] | [] | [] | [
"list",
"python",
"slice"
] | stackoverflow_0000681123_list_python_slice.txt |
Q:
Web crawlers and Google App Engine Hosted applications
Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version?
A:
While Google hadn't exposed scheduling, queue and background tasks API, you can do any processing only as an answer to external HTTP... | Web crawlers and Google App Engine Hosted applications | Is it impossible to run a web crawler on GAE along side with my app considering the I am running the free startup version?
| [
"While Google hadn't exposed scheduling, queue and background tasks API, you can do any processing only as an answer to external HTTP request. You'd need some heartbeat service that will process one item from crawler's queue at a time (not to hit GAE limits).\nTo do crawling from GAE, you have to split your applica... | [
3,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"web_crawler"
] | stackoverflow_0000676460_google_app_engine_python_web_crawler.txt |
Q:
Game map from Code
It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)
I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things... | Game map from Code | It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)
I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is c... | [
"I'd store a game map in code as a graph. \nEach node would represent a country/city and each edge would represent adjacency. Once you have a map like that, I'm sure you can find many resources on AI (pathfinding, strategy, etc.) online.\nIf you want to be able to build an image of the map programattically, consi... | [
5,
3,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0000681310_python.txt |
Q:
How is string.find implemented in CPython?
I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so http://docs.python.org/library/stdtypes.html is of no help. Could someo... | How is string.find implemented in CPython? | I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so http://docs.python.org/library/stdtypes.html is of no help. Could someone please point me to the relevant source code?
| [
"The comment on the implementation has the following to say:\n\nfast search/count implementation,\n based on a mix between boyer-moore\n and horspool, with a few more bells\n and whistles on the top.\nfor some more background, see: http://effbot.org/zone/stringlib.htm\n\n—https://github.com/python/cpython/blob/m... | [
22,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0000681649_python.txt |
Q:
Redirecting function definitions in python
This is a very contrived example as it's not easy to explain the context in which I have ended up implementing this solution. However, if anyone can answer why this particular peculiarity happens, I'd be grateful.
The example:
class A(dict):
def __init__(self):
... | Redirecting function definitions in python | This is a very contrived example as it's not easy to explain the context in which I have ended up implementing this solution. However, if anyone can answer why this particular peculiarity happens, I'd be grateful.
The example:
class A(dict):
def __init__(self):
self['a'] = 'success'
def __getitem__(s... | [
"When you use brackets [] python looks in the class. You must set the method in the class.\nHere's your code adapted:\nclass A(dict): \n def __init__(self):\n self['a'] = 'success'\n\n def __getitem__(self, name):\n print 'getitem!'\n return dict.__getitem__(self, name)\n\nclass B(object... | [
7,
1
] | [] | [] | [
"class_attributes",
"python"
] | stackoverflow_0000682822_class_attributes_python.txt |
Q:
Dynamically change the choices in a wx.ComboBox()
I didn't find a better way to change the different choices in a wx.ComboBox() than swap the old ComboBox with a new one. Is there a better way?
Oerjan Pettersen
#!/usr/bin/python
#20_combobox.py
import wx
import wx.lib.inspection
class MyFrame(wx.Frame):
def... | Dynamically change the choices in a wx.ComboBox() | I didn't find a better way to change the different choices in a wx.ComboBox() than swap the old ComboBox with a new one. Is there a better way?
Oerjan Pettersen
#!/usr/bin/python
#20_combobox.py
import wx
import wx.lib.inspection
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__in... | [
"wx.ComboBox derives from wx.ItemContainer, which has methods for Appending, Clearing, Inserting and Deleting items, all of these methods are available on wx.ComboBox.\nOne way to do what you want would be to define the text_return() method as follows:\ndef text_return(self, event):\n self.st.Clear()\n self.s... | [
37
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0000682923_python_wxpython_wxwidgets.txt |
Q:
Timeout on a HTTP request in python
Very occasionally when making a http request, I am waiting for an age for a response that never comes. What is the recommended way to cancel this request after a reasonable period of time?
A:
Set the HTTP request timeout.
A:
The timeout parameter to urllib2.urlopen, or http... | Timeout on a HTTP request in python | Very occasionally when making a http request, I am waiting for an age for a response that never comes. What is the recommended way to cancel this request after a reasonable period of time?
| [
"Set the HTTP request timeout.\n",
"The timeout parameter to urllib2.urlopen, or httplib. The original urllib has no such convenient feature. You can also use an asynchronous HTTP client such as twisted.web.client, but that's probably not necessary.\n",
"If you are making a lot of HTTP requests, you can change ... | [
2,
1,
1
] | [] | [] | [
"httpwebrequest",
"python"
] | stackoverflow_0000683493_httpwebrequest_python.txt |
Q:
how to put a function and arguments into python queue?
I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments... | how to put a function and arguments into python queue? | I have a python program with 2 threads ( let's name them 'source' and
'destination' ). Source thread sometimes post a message to destination
thread with some arguments. Than destination thread picks a message it
must call a corresponding function with aruments saved in message.
This task can be solved multiple ways. Th... | [
"So simple:\ndef DestinationThread( a ) :\n while True :\n items = q.get()\n func = items[0]\n args = items[1:]\n func(*args)\n\n",
"Another interesting option is simply to pass in a lambda.\nq.put(lambda: HandleMsg(1,2))\nq.put(lambda: HandleAnother(8, \"hello\", extra=\"foo\"))\n\ndef DestinationTh... | [
31,
14,
10,
2,
0,
0
] | [
"Why don't you subclass Queue?\n\nclass MyQueue(Queue):\n # by using *args, you can have a variable number of arguments\n def put(self,*args):\n for arg in args:\n Queue.put(self,arg)\n\nor, why don't you put a list?\n\nlist = [function_obj]\nfor arg in function_args:\n list.append(arg)\nqueue.put(list... | [
-2
] | [
"multithreading",
"python"
] | stackoverflow_0000683542_multithreading_python.txt |
Q:
How to save an xml file to disk?
I did something similar to this, but couldn't find a way to write the result to an xml file.
A:
The code on the web page you linked to uses doc.toprettyxml to create a string from the XML DOM, so you can just write that string to a file:
f = open("output.xml", "w")
try:
f.wri... | How to save an xml file to disk? | I did something similar to this, but couldn't find a way to write the result to an xml file.
| [
"The code on the web page you linked to uses doc.toprettyxml to create a string from the XML DOM, so you can just write that string to a file:\nf = open(\"output.xml\", \"w\")\ntry:\n f.write(doc.toprettyxml(indent=\" \"))\nfinally:\n f.close()\n\nIn Python 2.6 (or 2.7 I suppose, whenever it comes out), you ... | [
11,
9,
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0000683494_python_xml.txt |
Q:
can you distinguish between a test & a variable setting?
I like doctest but when you have complex arguments that you need to
set before you pass to a function it become really hard to read..
Hence, you start using multiple lines assigning then calling the
function that you would like to test.. This approach howeve... | can you distinguish between a test & a variable setting? | I like doctest but when you have complex arguments that you need to
set before you pass to a function it become really hard to read..
Hence, you start using multiple lines assigning then calling the
function that you would like to test.. This approach however, will
report that you have multiple tests rather then the re... | [
"Prepend three periods to indicate that you want to continue the current line, like so:\ndef returnme(x):\n \"\"\"\n Returns what you pass\n\n >>> y = (2, 3, 5, 7)\n ... returnme(y) # Note the difference here.\n ... # Another blank line ends this test.\n (2, 3, 5, 7)\n \"\"\"... | [
5
] | [] | [] | [
"doctest",
"python",
"unit_testing"
] | stackoverflow_0000684109_doctest_python_unit_testing.txt |
Q:
XML schema
I've a schema file (.xsd), I'd like to generate a xml document using this schema. Is there any online tool available,if not what is quickest way (like couple of lines of code using vb.net).
Thanks for your help.
-Vuppala
A:
If I'm understanding you correct, this tool might help.
XML Generator
It's ... | XML schema | I've a schema file (.xsd), I'd like to generate a xml document using this schema. Is there any online tool available,if not what is quickest way (like couple of lines of code using vb.net).
Thanks for your help.
-Vuppala
| [
"If I'm understanding you correct, this tool might help.\nXML Generator\nIt's what I usually use when working with XML.\nIf you want a solution through code you can use this:\nXmlTextWriter textWriter = new XmlTextWriter(\"po.xml\", null);\ntextWriter.Formatting = Formatting.Indented;\nXmlQualifiedName qname =... | [
1,
0
] | [] | [] | [
"c#",
"python",
"ruby"
] | stackoverflow_0000684117_c#_python_ruby.txt |
Q:
Django Template if tag not working under FastCGI when checking bool True
I have a strange issue specific to my Django deployment under Python 2.6 + Ubuntu + Apache 2.2 + FastCGI.
If I have a template as such:
{% with True as something %}
{%if something%}
It Worked!!!
{%endif%}
{%endwith%}
it should ou... | Django Template if tag not working under FastCGI when checking bool True | I have a strange issue specific to my Django deployment under Python 2.6 + Ubuntu + Apache 2.2 + FastCGI.
If I have a template as such:
{% with True as something %}
{%if something%}
It Worked!!!
{%endif%}
{%endwith%}
it should output the string "It Worked!!!". It does not on my production server with mod_f... | [
"Hmm... True is not a valid token in django template language, is it? I have no idea how it worked locally -- unless it's being added to the context with a non-zero value somewhere. Therefore, I think your second problem may not be related to the first one.\n"
] | [
3
] | [] | [] | [
"django",
"fastcgi",
"python",
"python_2.6",
"templates"
] | stackoverflow_0000684371_django_fastcgi_python_python_2.6_templates.txt |
Q:
Hierarchy / Flyweight / Instancing Problem in Python
Here is the problem I am trying to solve, (I have simplified the actual problem, but this should give you all the relevant information). I have a hierarchy like so:
1.A
1.B
1.C
2.A
3.D
4.B
5.F
(This is hard to illustrate - each number is the parent, each letter... | Hierarchy / Flyweight / Instancing Problem in Python | Here is the problem I am trying to solve, (I have simplified the actual problem, but this should give you all the relevant information). I have a hierarchy like so:
1.A
1.B
1.C
2.A
3.D
4.B
5.F
(This is hard to illustrate - each number is the parent, each letter is the child).
Creating an instance of the 'letter' obje... | [
"A basic approach will use builtin data types. If I get your drift, the Letter object should be created by a factory with a dict cache to keep previously generated Letter objects. The factory will create only one Letter object for each key.\nA Number object can be a sub-class of list that will hold the Letter objec... | [
0
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0000685253_design_patterns_python.txt |
Q:
Handling file attributes in python 3.0
I am currently developing an application in python 3 and i need to be able to hide certain files from the view of people. i found a few places that used the win32api and win32con but they don't seem to exist in python 3.
Does anyone know if this is possible without rolling ba... | Handling file attributes in python 3.0 | I am currently developing an application in python 3 and i need to be able to hide certain files from the view of people. i found a few places that used the win32api and win32con but they don't seem to exist in python 3.
Does anyone know if this is possible without rolling back or writing my own attribute library in C+... | [
"You need the pywin32 Python Extensions for Windows. Recently released for Python 3.\n",
"You can use ctypes to directly access functions from kernel32.dll. \nThe function you're looking for is windll.kernel32.SetFileAttributesA\n"
] | [
5,
3
] | [] | [] | [
"python",
"python_3.x",
"windows"
] | stackoverflow_0000685488_python_python_3.x_windows.txt |
Q:
django : using admin datepicker
I'm trying to use the admin datepicker in my own django forms.
Roughly following the discussion here : http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html
I've
a) In my forms.py included the line
from django.contrib.admin import widgets
b) and used the widget li... | django : using admin datepicker | I'm trying to use the admin datepicker in my own django forms.
Roughly following the discussion here : http://www.mail-archive.com/django-users@googlegroups.com/msg72138.html
I've
a) In my forms.py included the line
from django.contrib.admin import widgets
b) and used the widget like this :
date = forms.DateTimeField(... | [
"No, it's not a bug. \nIt's trying to call the gettext() internationalization function in js. You can do js internationalization much like you do it in python code or templates, it's only a less known feature.\nIf you don't use js internationalization in your project you can just put.\n<script>function gettext... | [
5,
2,
1
] | [] | [] | [
"date",
"django",
"django_forms",
"forms",
"python"
] | stackoverflow_0000660898_date_django_django_forms_forms_python.txt |
Q:
Is there any particular reason why this syntax is used for instantiating a class?
I was wondering if anyone knew of a particular reason (other than purely stylistic) why the following languages these syntaxes to initiate a class?
Python:
class MyClass:
def __init__(self):
x = MyClass()
Ruby:
class AnotherCla... | Is there any particular reason why this syntax is used for instantiating a class? | I was wondering if anyone knew of a particular reason (other than purely stylistic) why the following languages these syntaxes to initiate a class?
Python:
class MyClass:
def __init__(self):
x = MyClass()
Ruby:
class AnotherClass
def initialize()
end
end
x = AnotherClass.new()
I can't understand why the... | [
"When you are creating an object of a class, you are doing more than just initializing it. You are allocating the memory for it, then initializing it, then returning it.\nNote also that in Ruby, new() is a class method, while initialize() is an instance method. If you simply overrode new(), you would have to create... | [
5,
4,
0
] | [] | [] | [
"constructor",
"python",
"ruby"
] | stackoverflow_0000685713_constructor_python_ruby.txt |
Q:
Any alternatives to IronPython, Python for .NET for accessing CLR from python?
Are there any alternatives to Python for .NET or IronPython for accessing .NET CLR? Both of these seem to have downsides in that Python for .NET is not under active development (as far as I can tell) and you lose some features available... | Any alternatives to IronPython, Python for .NET for accessing CLR from python? | Are there any alternatives to Python for .NET or IronPython for accessing .NET CLR? Both of these seem to have downsides in that Python for .NET is not under active development (as far as I can tell) and you lose some features available in CPython if you use IronPython. So are there any alternatives?
| [
"Apart from Python for .NET (which works pretty well for me), the only other solution I'm aware of is exposing the .NET libraries via COM interop, so you can use them via the pywin32 extensions. \n(I don't know much about .NET com interop yet, so hopefully someone else can provide further explanation on that.)\n",
... | [
4,
1,
1,
1
] | [] | [] | [
".net",
"clr",
"ironpython",
"python"
] | stackoverflow_0000681853_.net_clr_ironpython_python.txt |
Q:
separate threads in pygtk application
I'm having some problems threading my pyGTK application. I give the thread some time to complete its task, if there is a problem I just continue anyway but warn the user. However once I continue, this thread stops until gtk.main_quit is called. This is confusing me.
The rel... | separate threads in pygtk application | I'm having some problems threading my pyGTK application. I give the thread some time to complete its task, if there is a problem I just continue anyway but warn the user. However once I continue, this thread stops until gtk.main_quit is called. This is confusing me.
The relevant code:
class MTP_Connection(threading.... | [
"Firstly, don't subclass threading.Thread, use Thread(target=callable).start().\nSecondly, and probably the cause of your apparent block is that gtk.main_iteration takes a parameter block, which defaults to True, so your call to gtk.main_iteration will actually block when there are no events to iterate on. Which ca... | [
9
] | [] | [] | [
"multithreading",
"pygtk",
"python"
] | stackoverflow_0000685224_multithreading_pygtk_python.txt |
Q:
Writing binary data to a socket (or file) with Python
Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer tha... | Writing binary data to a socket (or file) with Python | Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer that denotes the length of message, then another unsigned byte... | [
"Use the struct module to build a buffer and write that.\n",
"A very elegant way to handle theses transitions between Python objects and a binary representation (both directions) is using the Construct library.\nIn their documentation you'll find many nice examples of using it. I've been using it myself for sever... | [
11,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0000686296_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.