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:
Fastest nested loops over a single list (with elements remove or not)
I am looking for advice about how to parse a single list, using two nested loops, in the fastest way, avoiding doing len(list)^2 comparisons, and avoiding duplicate files in groups.
More precisely: I have a list of 'file' objects, that each has ... | Fastest nested loops over a single list (with elements remove or not) | I am looking for advice about how to parse a single list, using two nested loops, in the fastest way, avoiding doing len(list)^2 comparisons, and avoiding duplicate files in groups.
More precisely: I have a list of 'file' objects, that each has a timestamp. I want to group the files by their timestamp and a time offset... | [
"A simple solution that works by sorting the list then using a generator to create groups:\ndef time_offsets(files, offset):\n\n files = sorted(files, key=lambda x:x.timestamp)\n\n group = [] \n timestamp = 0\n\n for f in files:\n if f.timestamp < timestamp + offset:\n group.append(f)\n ... | [
3,
1,
1
] | [] | [] | [
"list",
"nested_loops",
"performance",
"python"
] | stackoverflow_0001579771_list_nested_loops_performance_python.txt |
Q:
python, lxml and xpath - html table parsing
I 'am new to lxml, quite new to python and could not find a solution to the following:
I need to import a few tables with 3 columns and an undefined number of rows starting at row 3.
When the second column of any row is empty, this row is discarded and the processing of ... | python, lxml and xpath - html table parsing | I 'am new to lxml, quite new to python and could not find a solution to the following:
I need to import a few tables with 3 columns and an undefined number of rows starting at row 3.
When the second column of any row is empty, this row is discarded and the processing of the table is aborted.
The following code prints t... | [
"This is a generator:\ndef process_row(row): \n for cell in row.xpath('./td'): \n print cell.text_content() \n yield cell.text_content() \n\nYou're calling it as though you thought it returns a list. It doesn't. There are contexts in which it behaves like a list:\nprint [r for r in process_... | [
2,
0
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0001577487_lxml_python_xpath.txt |
Q:
How can I check that a column in a tab-delimited file has valid values?
I have a large file named CHECKME which is tab delimited. There are 8 columns in each row. Column 4 is integers.
By using Perl or Python, is it possible to verify that each row in CHECKME has 8 columns and that column 4 is an integer?
A:
In ... | How can I check that a column in a tab-delimited file has valid values? | I have a large file named CHECKME which is tab delimited. There are 8 columns in each row. Column 4 is integers.
By using Perl or Python, is it possible to verify that each row in CHECKME has 8 columns and that column 4 is an integer?
| [
"In Perl\nwhile(<>) {\n my @F=split/\\t/;\n die \"Invalid line: $_\" if @F!=8 or $F[3]!~/^-?\\d+$/;\n}\n\n",
"In Python:\ndef isfileok(filename):\n f = open(filename)\n for line in f:\n pieces = line.split('\\t')\n if len(pieces) != 8:\n return False\n if not pieces[3].isdigit():\n retu... | [
8,
5,
4,
2,
1,
0
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0001575936_perl_python.txt |
Q:
Mixing Python web platforms PHP, e.g. - Mediawiki, Wordpress, etc
Is anyone developing application integrated with Mediawiki - using Django or other Python web development platforms using mod_wsgi?
Would be very interested to find out what has been done in this direction and maybe there is some code available for... | Mixing Python web platforms PHP, e.g. - Mediawiki, Wordpress, etc | Is anyone developing application integrated with Mediawiki - using Django or other Python web development platforms using mod_wsgi?
Would be very interested to find out what has been done in this direction and maybe there is some code available for re-use. (I've started creating wiki extensions working with MW databas... | [
"There are so many different ways to do this.\n\nYou can make a mediawiki skin that uses iframes and inserts things from a Python server.\nYou can write a python app that accesses mediawikis data somehow and outputs it.\nYou can put a Python server in front that extracts the content from mediawiki and put's it into... | [
2,
1
] | [] | [] | [
"mediawiki",
"mod_wsgi",
"php",
"python",
"wordpress"
] | stackoverflow_0001580245_mediawiki_mod_wsgi_php_python_wordpress.txt |
Q:
Key compare using dictionary
I have a file with the following structure:
system.action.webMessage=An error has happened during web access.
system.action.okMessage=Everything is ok.
core.alert.inform=Error number 5512.
I need a script to compare the keys in 2 files with this structure. I was working in a script to ... | Key compare using dictionary | I have a file with the following structure:
system.action.webMessage=An error has happened during web access.
system.action.okMessage=Everything is ok.
core.alert.inform=Error number 5512.
I need a script to compare the keys in 2 files with this structure. I was working in a script to convert the file into a dictionary... | [
"file = open('system.keys','r')\nlines = []\nfor i in file:\n lines.append(i.partition('='))\n\ndic = {}\nfor k,_,v in lines:\n dic[k] = v\n\nor using split\nmyfile = open('system.keys','r')\ndic = dict(i.split(\"=\",1) for i in myfile)\n\nsince dict() knows how to make a dictionary from a sequence of (key,va... | [
2,
0
] | [] | [] | [
"compare",
"dictionary",
"file",
"list",
"python"
] | stackoverflow_0001580563_compare_dictionary_file_list_python.txt |
Q:
How do I know what data type to use in Python?
I'm working through some tutorials on Python and am at a position where I am trying to decide what data type/structure to use in a certain situation.
I'm not clear on the differences between arrays, lists, dictionaries and tuples.
How do you decide which one is approp... | How do I know what data type to use in Python? | I'm working through some tutorials on Python and am at a position where I am trying to decide what data type/structure to use in a certain situation.
I'm not clear on the differences between arrays, lists, dictionaries and tuples.
How do you decide which one is appropriate - my current understanding doesn't let me dist... | [
"How do you decide which data type to use? Easy:\nYou look at which are available and choose the one that does what you want. And if there isn't one, you make one.\nIn this case a dict is a pretty obvious solution.\n",
"Best type for counting elements like this is usually defaultdict\nfrom collections import defa... | [
6,
3,
3,
0,
0
] | [] | [] | [
"arrays",
"python",
"tuples",
"types"
] | stackoverflow_0001579744_arrays_python_tuples_types.txt |
Q:
Python - Twisted and Unit Tests
I'm writing unit tests for a portion of an application that runs as an HTTP server. The approach I have been trying to take is to import the module that contains the HTTP server, start it. Then, the unit tests will use urllib2 to connect, send data, and check the response.
Our HTT... | Python - Twisted and Unit Tests | I'm writing unit tests for a portion of an application that runs as an HTTP server. The approach I have been trying to take is to import the module that contains the HTTP server, start it. Then, the unit tests will use urllib2 to connect, send data, and check the response.
Our HTTP server is using Twisted. One probl... | [
"Here's some info: Writing tests for Twisted code using Trial\nYou should also look at the -help of the trial command. There'a lot of good stuff in trial! But it's not always easy to do testing in a async application. Good luck!\n",
"I believe that for unit testing within Twisted you're supposed to use TwistedTri... | [
18,
7,
4,
3
] | [] | [] | [
"python",
"twisted",
"unit_testing"
] | stackoverflow_0001575966_python_twisted_unit_testing.txt |
Q:
Replace SRC of all IMG elements using Parser
I am looking for a way to replace the SRC attribute in all IMG tags not using Regular expressions. (Would like to use any out-of-the box HTML parser included with default Python install) I need to reduce the source from what ever it may be to:
<img src="cid:imagename">
... | Replace SRC of all IMG elements using Parser | I am looking for a way to replace the SRC attribute in all IMG tags not using Regular expressions. (Would like to use any out-of-the box HTML parser included with default Python install) I need to reduce the source from what ever it may be to:
<img src="cid:imagename">
I am trying to replace all src tags to point to t... | [
"There is a HTML parser in the Python standard library, but it’s not very useful and it’s deprecated since Python 2.6. Doing this kind of things with BeautifulSoup is really easy:\nfrom BeautifulSoup import BeautifulSoup\nfrom os.path import basename, splitext\nsoup = BeautifulSoup(my_html_string)\nfor img in soup.... | [
27,
1
] | [] | [] | [
"html",
"image",
"parsing",
"python",
"src"
] | stackoverflow_0001579133_html_image_parsing_python_src.txt |
Q:
How to avoid excessive parameter passing?
I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I ext... | How to avoid excessive parameter passing? | I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the b... | [
"Create objects of types relevant to your program, and store the command line options relevant to each in them. Example:\nimport WidgetFrobnosticator\nf = WidgetFrobnosticator()\nf.allow_oncave_widgets = option_allow_concave_widgets\nf.respect_weasel_pins = option_respect_weasel_pins\n\n# Now the methods of Widget... | [
8,
4,
2,
2,
1,
1
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0001580792_design_patterns_python.txt |
Q:
Can a WIN32 program authenticate into Django authentication system, using MYSQL?
I have a web service with Django Framework.
My friend's project is a WIN32 program and also a MS-sql server.
The Win32 program currently has a login system that talks to a MS-sql for authentication.
However, we would like to INTEGRATE... | Can a WIN32 program authenticate into Django authentication system, using MYSQL? | I have a web service with Django Framework.
My friend's project is a WIN32 program and also a MS-sql server.
The Win32 program currently has a login system that talks to a MS-sql for authentication.
However, we would like to INTEGRATE this login system as one.
Please answer the 2 things:
I want scrap the MS-SQL to use... | [
"The Win32 client can act like a web client to pass the user's credentials to the server. You will want to store the session cookie you get once you are authenticated and use that cookie in all following requests\n"
] | [
1
] | [] | [] | [
"django",
"mysql",
"python",
"windows"
] | stackoverflow_0001533259_django_mysql_python_windows.txt |
Q:
Django inheritance: how to have one method for all subclasses?
I have a model
BaseModel
and several subclasses of it
ChildModelA(BaseModel), ChildModelB(BaseModel), ...
using multi-table inheritance. In future I plan to have dozens of subclass models.
All subclasses have some implementation of method
do_som... | Django inheritance: how to have one method for all subclasses? | I have a model
BaseModel
and several subclasses of it
ChildModelA(BaseModel), ChildModelB(BaseModel), ...
using multi-table inheritance. In future I plan to have dozens of subclass models.
All subclasses have some implementation of method
do_something()
How can I call do_somthing from a BaseModel instance?
Almo... | [
"If you want to avoid checking all possible subclasses, the only way I can think of would be to store the class name associated with the subclass in a field defined on the base class. Your base class might have a method like this:\ndef resolve(self):\n module, cls_name = self.class_name.rsplit(\".\",1)\n mod... | [
2,
1,
0
] | [] | [] | [
"django",
"django_models",
"inheritance",
"overloading",
"python"
] | stackoverflow_0001581024_django_django_models_inheritance_overloading_python.txt |
Q:
How to perform a "Group By" query in Django 1.1?
I have seen a lot of talk about 1.1's aggregation, but I am not sure how to use it to perform a simple group by.
I am trying to use Django's sitemap framework to create a sitemap.xml file that Google can crawl to find all the pages of my site. Currently I am passing... | How to perform a "Group By" query in Django 1.1? | I have seen a lot of talk about 1.1's aggregation, but I am not sure how to use it to perform a simple group by.
I am trying to use Django's sitemap framework to create a sitemap.xml file that Google can crawl to find all the pages of my site. Currently I am passing it all the objects, as in Model.objects.all() - howev... | [
"Django models are lazy loaded. It will be the same amount of overhead if your code walks across your model relationships as if the sitemap did. The models fields are essentially proxies until you request related models.\n",
"May be Distinct will help you?\n\nModel.objects.values('name').all().distinct()\n\n"
] | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001581383_django_python.txt |
Q:
How do I make these relative imports work in Python 3?
I have a directory structure that looks like this:
project/
__init__.py
foo/
__init.py__
first.py
second.py
third.py
plum.py
In project/foo/__init__.py I import classes from first.py, sec... | How do I make these relative imports work in Python 3? | I have a directory structure that looks like this:
project/
__init__.py
foo/
__init.py__
first.py
second.py
third.py
plum.py
In project/foo/__init__.py I import classes from first.py, second.py and third.py and put them in __all__.
There's a class... | [
"Edit: I did misunderstand the question: No __all__ is not restricted to just modules.\nOne question is why you want to do a relative import. There is nothing wrong with doing from project.foo import *, here. Secondly, the __all__ restriction on foo won't prevent you from doing from project.foo.first import Wonderf... | [
3
] | [] | [] | [
"import",
"python",
"python_3.x",
"relative_path"
] | stackoverflow_0001581260_import_python_python_3.x_relative_path.txt |
Q:
How do i use perspective projection in this library
i found a library called pyeuclid and it seems to do what i want in respect to 3D math.
it contins a 3D vector class and a 4X4 matrix class capable of transformations like rotate,translate and scale.
matrix creation is simple, simply pass along the arguments and... | How do i use perspective projection in this library | i found a library called pyeuclid and it seems to do what i want in respect to 3D math.
it contins a 3D vector class and a 4X4 matrix class capable of transformations like rotate,translate and scale.
matrix creation is simple, simply pass along the arguments and the matrix is created.
>>> m = Matrix4()
>>> m.translat... | [
"This tutorial explains the arguments to gluPerspective(), and should transfer over since your library is written with that as a model.\nI would expect the new_perspective() method to work like a constructor, i.e. it returns a Matrix set up as a perspective transformation. You should then be able to transform world... | [
0,
0
] | [] | [] | [
"3d",
"matrix",
"projection",
"python",
"vector"
] | stackoverflow_0001559083_3d_matrix_projection_python_vector.txt |
Q:
phpDocumentor goes to PHP, as X goes to Python (Django)
phpDocumentor goes to PHP, as X goes to Python (Django)
What is the X?
A:
Or Sphinx, as seen on TV and at python.org.
A:
Epydoc, pydoctor or standard pydoc.
| phpDocumentor goes to PHP, as X goes to Python (Django) | phpDocumentor goes to PHP, as X goes to Python (Django)
What is the X?
| [
"Or Sphinx, as seen on TV and at python.org.\n",
"Epydoc, pydoctor or standard pydoc.\n"
] | [
7,
5
] | [] | [] | [
"django",
"php",
"phpdoc",
"python"
] | stackoverflow_0001582145_django_php_phpdoc_python.txt |
Q:
Python TCP stack implementation
Is there a python library which implements a standalone TCP stack?
I can't use the usual python socket library because I'm receiving a stream of packets over a socket (they are being tunneled to me over this socket). When I receive a TCP SYN packet addressed to a particular port, I... | Python TCP stack implementation | Is there a python library which implements a standalone TCP stack?
I can't use the usual python socket library because I'm receiving a stream of packets over a socket (they are being tunneled to me over this socket). When I receive a TCP SYN packet addressed to a particular port, I'd like to accept the connection (sen... | [
"You don't say which platform you are working on, but if you are working on linux, I'd open a tun/tap interface and get the IP packets back into the kernel as a real network interface so the kernel can do all that tricky TCP stuff.\nThis is how (for example) OpenVPN works - it receives the raw IP packets over UDP o... | [
7,
2,
0,
0,
0
] | [] | [] | [
"network_programming",
"network_protocols",
"python",
"raw_sockets",
"tcp"
] | stackoverflow_0001581087_network_programming_network_protocols_python_raw_sockets_tcp.txt |
Q:
IronPython libraries for scientific plots
What are good python libraries which IronPython supports (current version wise) for drawing scientific plots on Win ?
By "scientific plots" I mean simple x-y plots, x-y-z surface plots and x-y-z shaded plots.
A:
According to this it's possible to use matplotlib with Iron... | IronPython libraries for scientific plots | What are good python libraries which IronPython supports (current version wise) for drawing scientific plots on Win ?
By "scientific plots" I mean simple x-y plots, x-y-z surface plots and x-y-z shaded plots.
| [
"According to this it's possible to use matplotlib with IronPython. Which will at least get you 2D plots. Another way of running matplotlib.\ngnuplot can generate 3D charts - http://www.resolverhacks.net/gnuplot_plotting.html might be a starting point.\n",
"If you get Resolver, then this Resolver Spreadsheet Chal... | [
8,
0
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0001412412_ironpython_python.txt |
Q:
Using/Creating Python objects with Jython
HI,
lets say I have a Java interface B, something like this. B.java :
public interface B { String FooBar(String s); }
and I want to use it with a Python class D witch inherits B, like this. D.py :
class D(B):
def FooBar(s)
return s + 'e'
So now how do I get ... | Using/Creating Python objects with Jython | HI,
lets say I have a Java interface B, something like this. B.java :
public interface B { String FooBar(String s); }
and I want to use it with a Python class D witch inherits B, like this. D.py :
class D(B):
def FooBar(s)
return s + 'e'
So now how do I get an instance of D in java? I'm sorry im asking s... | [
"Code for your example above. You also need to change the FooBar implementation to take a self argument since it is not a static method.\nYou need to have jython.jar on the classpath for this example to compile and run.\nimport org.python.core.PyObject;\nimport org.python.core.PyString;\nimport org.python.util.Pyth... | [
4
] | [] | [] | [
"java",
"jython",
"python"
] | stackoverflow_0001582674_java_jython_python.txt |
Q:
Selenium IDE - can't select "table" tab
Can someone tell me why I can't select the "table" tab?
Here is a pic:
alt text http://img110.imageshack.us/img110/935/imgzx.jpg
A:
What "Format" are you using? The table is available in HTML only. I think.
Select Options/Format/HTML from the menu and the Table tab should... | Selenium IDE - can't select "table" tab | Can someone tell me why I can't select the "table" tab?
Here is a pic:
alt text http://img110.imageshack.us/img110/935/imgzx.jpg
| [
"What \"Format\" are you using? The table is available in HTML only. I think. \nSelect Options/Format/HTML from the menu and the Table tab should be activated.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001582679_python.txt |
Q:
String matching in python with re
I have a file in this structure:
009/foo/bar/hi23123/foo/bar231123/foo/bar/yo232131
What i need is to find the exact match of a string; e.g. only /foo/bar among /foo/bar/hi and /foo/bar/yo
One solution came up in my mind is like to check for ending "/" for the input string. Becau... | String matching in python with re | I have a file in this structure:
009/foo/bar/hi23123/foo/bar231123/foo/bar/yo232131
What i need is to find the exact match of a string; e.g. only /foo/bar among /foo/bar/hi and /foo/bar/yo
One solution came up in my mind is like to check for ending "/" for the input string. Because if there is ending "/" in the possib... | [
"So you want /foo/bar not followed by a /? If so, then you're looking for a \"negative lookahead\", \nr = re.compile(r'/foo/bar(?!/)')\n\nand then r.search to your heart's content.\n"
] | [
8
] | [] | [] | [
"python",
"regex",
"string_matching"
] | stackoverflow_0001582895_python_regex_string_matching.txt |
Q:
Reposition a VLC window programmatically
I'm sure others have run into this problem too...
I often watch videos in a small VLC window while working on other tasks, but no matter where the window is placed, I eventually need to access something in the GUI behind it, and have to manually reposition the video window ... | Reposition a VLC window programmatically | I'm sure others have run into this problem too...
I often watch videos in a small VLC window while working on other tasks, but no matter where the window is placed, I eventually need to access something in the GUI behind it, and have to manually reposition the video window first.
This could be solved by having the VLC ... | [
"Here is a windows only solution. You dont need to actually put the mouse over the window. All you need to do is Find the window using its name and send WM_MOVE. I dont know the name of the window which VLC uses. You could use Spy++ to find its name.\n",
"This is a bit OOT, but in Windows 7, shaking the active wi... | [
1,
0
] | [] | [] | [
"c#",
"cross_platform",
"python",
"vlc",
"windows"
] | stackoverflow_0001581782_c#_cross_platform_python_vlc_windows.txt |
Q:
XML-RPC C# and Python RPC Server
On my server, I'm using the standard example for Python (with an extra Hello World Method) and on the Client side I'm using the XML-RPC.NET Library in C#.
But everytime I run my client I get the exception that the method is not found. Any Ideas how fix that.
thanks!
Python:
from S... | XML-RPC C# and Python RPC Server | On my server, I'm using the standard example for Python (with an extra Hello World Method) and on the Client side I'm using the XML-RPC.NET Library in C#.
But everytime I run my client I get the exception that the method is not found. Any Ideas how fix that.
thanks!
Python:
from SimpleXMLRPCServer import SimpleXMLRPCS... | [
"Does it work if you change the declaration to this?\n[XmlRpcUrl(\"http://188.40.xxx.xxx:8000/RPC2\")]\n\nFrom the Python docs:\n\nSimpleXMLRPCRequestHandler.rpc_paths\nAn attribute value that must be a tuple listing valid path portions of the URL for receiving XML-RPC requests. Requests posted to other paths will ... | [
5
] | [] | [] | [
"c#",
"python",
"xml_rpc"
] | stackoverflow_0001583017_c#_python_xml_rpc.txt |
Q:
Naming convention for actually choosing the words in Python, PEP8 compliant
I’m looking for a better way to name everything in Python. Yes, I’ve read PEP8, Spolsky’s wonderful rant, and various other articles. But I’m looking for more guidance in choosing the actual words.
And yes I know
A Foolish Consistency i... | Naming convention for actually choosing the words in Python, PEP8 compliant | I’m looking for a better way to name everything in Python. Yes, I’ve read PEP8, Spolsky’s wonderful rant, and various other articles. But I’m looking for more guidance in choosing the actual words.
And yes I know
A Foolish Consistency is the Hobgoblin
of Little Minds.
But, you can keep consistent with PEP8 etc, a... | [
"I believe that the need for complex variable naming conventions goes away with good object-oriented design. In the Spolsky article, much focus is on how variable naming helps preventing errors. I believe that those errors will more often occur when you have many variables in the same scope; this can be avoided by ... | [
4,
2,
1
] | [] | [] | [
"naming_conventions",
"python"
] | stackoverflow_0001563673_naming_conventions_python.txt |
Q:
Python: Int not iterable error
I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the fol... | Python: Int not iterable error | I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:
TypeError: 'int' obje... | [
"In the for-loop \nfor numbers in x:\n\n\"numbers\" steps through the elements in x one at a time, for each pass through the loop.\nIt would be perhaps better to name the variable \"number\" because you are only getting\none number at a time. \"numbers\" equals an integer each time through the loop.\nsum(numbers)\n... | [
7,
5,
1,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001583148_python.txt |
Q:
Long, slow operation in Django view causes timeout. Any way for Python to speak AJAX instead?
I've been programming Python a while, but DJango and web programming in general is new to me.
I have a very long operation performed in a Python view. Since the local() function in my view takes so long to return, there's... | Long, slow operation in Django view causes timeout. Any way for Python to speak AJAX instead? | I've been programming Python a while, but DJango and web programming in general is new to me.
I have a very long operation performed in a Python view. Since the local() function in my view takes so long to return, there's an HTTP timeout. Fair enough, I understand that part.
What's the best way to give an HTTPresponse ... | [
"Ajax doesn't require any particular technology on the server side. All you need is to return a response in some form that some Javascript on the client side can understand. JSON is an excellent choice here, as it's easy to create in Python (there's a json library in 2.6, and Django has django.utils.simplejson for ... | [
7,
6,
1
] | [] | [] | [
"ajax",
"django",
"python",
"timeout"
] | stackoverflow_0001582708_ajax_django_python_timeout.txt |
Q:
activestate pythonwin missing import modules?
I'm working my way through DiveIntoPython.com and I'm having trouble getting the import to work. I've installed ActiveState's Pythonwin on a windows xp prof environment.
In the website, there is an exercise which involves 'import odbchelper' and odbchelper.name
http:... | activestate pythonwin missing import modules? | I'm working my way through DiveIntoPython.com and I'm having trouble getting the import to work. I've installed ActiveState's Pythonwin on a windows xp prof environment.
In the website, there is an exercise which involves 'import odbchelper' and odbchelper.name
http://www.diveintopython.org/getting_to_know_python/tes... | [
"This module doesn't come packaged with Python2.6 for sure (just tried on my machine). Have you tried googling where this module might be?\nConsider this post.\n",
"figured it out.. \nfound this: \nhttp://www.faqs.org/docs/diveintopython/odbchelper_divein.html\n\ndownloaded the file and then put it into a folder.... | [
1,
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0001583947_import_python.txt |
Q:
Apache2 + RewriteMap + Python -- when returning 'NULL', apache hangs
[SOLVED: See solution below.]
I'm having a problem writing a RewriteMap program (using Python). I have a RewriteMap directive pointing to a Python script which determines if the requested URL needs to be redirected elsewhere.
When the script out... | Apache2 + RewriteMap + Python -- when returning 'NULL', apache hangs | [SOLVED: See solution below.]
I'm having a problem writing a RewriteMap program (using Python). I have a RewriteMap directive pointing to a Python script which determines if the requested URL needs to be redirected elsewhere.
When the script outputs a string terminated by a linebreak, Apache redirects accordingly. Ho... | [
"You have to return a single newline, not 'NULL'. \nApache waits for a newline to know when the URL to be rewrite to ends. If your script sends no newline, Apache waits forever.\nSo just change return ('NULL') to return ('NULL\\n'), this will then redirect to /. If you don't want this to happen, have the program to... | [
6,
3
] | [] | [] | [
"apache",
"apache2",
"python",
"rewrite"
] | stackoverflow_0001580780_apache_apache2_python_rewrite.txt |
Q:
What does "lambda" mean in Python, and what's the simplest way to use it?
Can you give an example and other examples that show when and when not to use Lambda?
My book gives me examples, but they're confusing.
A:
Lambda, which originated from Lambda Calculus and (AFAIK) was first implemented in Lisp, is basicall... | What does "lambda" mean in Python, and what's the simplest way to use it? | Can you give an example and other examples that show when and when not to use Lambda?
My book gives me examples, but they're confusing.
| [
"Lambda, which originated from Lambda Calculus and (AFAIK) was first implemented in Lisp, is basically an anonymous function - a function which doesn't have a name, and is used in-line, in other words you can assign an identifier to a lambda function in a single expression as such:\n>>> addTwo = lambda x: x+2\n>>> ... | [
40,
4,
3
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0001583617_lambda_python.txt |
Q:
Python xpath not working?
Okay, this is starting to drive me a little bit nuts. I've tried several xml/xpath libraries for Python, and can't figure out a simple way to get a stinkin' "title" element.
The latest attempt looks like this (using Amara):
def view(req, url):
req.content_type = 'text/plain'
doc =... | Python xpath not working? | Okay, this is starting to drive me a little bit nuts. I've tried several xml/xpath libraries for Python, and can't figure out a simple way to get a stinkin' "title" element.
The latest attempt looks like this (using Amara):
def view(req, url):
req.content_type = 'text/plain'
doc = amara.parse(urlopen(url))
... | [
"You probably just have to take into account the namespace of the document which you're dealing with.\nI'd suggest looking up how to deal with namespaces in Amara:\nhttp://www.xml3k.org/Amara/Manual#namespaces\nEdit: Using your code snippet I made some edits. I don't know what version of Amara you're using but base... | [
1,
1
] | [] | [] | [
"amara",
"python",
"xml",
"xml_namespaces",
"xpath"
] | stackoverflow_0001584180_amara_python_xml_xml_namespaces_xpath.txt |
Q:
Making a C extension to Python that requires another extension
I have a couple of Python functions that I use to make game development with Pygame easier. I have them in a file called helper.py in my Python-path, so I can import them from any game I make. I thought, as an exercise to learn about Python extensions,... | Making a C extension to Python that requires another extension | I have a couple of Python functions that I use to make game development with Pygame easier. I have them in a file called helper.py in my Python-path, so I can import them from any game I make. I thought, as an exercise to learn about Python extensions, to convert this module to C. My first problem is that I need to use... | [
"/* get the sys.modules dictionary */\nPyObject* sysmodules PyImport_GetModuleDict();\nPyObject* pygame_module;\nif(PyMapping_HasKeyString(sysmodules, \"pygame\")) {\n pygame_module = PyMapping_GetItemString(sysmodules, \"pygame\");\n} else {\n PyObject* initresult;\n pygame_module = PyImport_ImportModule(... | [
6,
3,
0
] | [] | [] | [
"c",
"pygame",
"python"
] | stackoverflow_0001583077_c_pygame_python.txt |
Q:
Unit testing a method called during initialization?
I have a class like the following:
class Positive(object):
def __init__(self, item):
self._validate_item(item)
self.item = item
def _validate_item(self, item):
if item <= 0:
raise ValueError("item should be positive.")... | Unit testing a method called during initialization? | I have a class like the following:
class Positive(object):
def __init__(self, item):
self._validate_item(item)
self.item = item
def _validate_item(self, item):
if item <= 0:
raise ValueError("item should be positive.")
I'd like to write a unit test for _validate_item(), lik... | [
"If you're not using self in the method's body, it's a hint that it might not need to be a class member. You can either move the _validate_item function into module scope:\ndef _validate_item(item):\n if item <= 0:\n raise ValueError(\"item should be positive.\")\n\nOr if it really has to stay in the cla... | [
7,
1,
1
] | [] | [] | [
"oop",
"python",
"testing",
"unit_testing"
] | stackoverflow_0001584220_oop_python_testing_unit_testing.txt |
Q:
Apparently my app. runs but I don't see anything
I'm learning python and Qt to create graphical desktop apps. I designed the UI with Qt Designer and converted the .ui to .py using pyuic, according to the tutorial I'm following, I should be able to run my app. but when I do it, a terminal window opens and it says:
... | Apparently my app. runs but I don't see anything | I'm learning python and Qt to create graphical desktop apps. I designed the UI with Qt Designer and converted the .ui to .py using pyuic, according to the tutorial I'm following, I should be able to run my app. but when I do it, a terminal window opens and it says:
cd '/Users/andresacevedo/' && '/opt/local/bin/python2.... | [
"The problem is that your python code is merely defining a class, but has no main program which invokes the class or causes QT to pop up a window. \nIt seems a little unusual that your Ui_MainWindow class isn't actually a subclass of QMainWindow; it isn't a widget itself, but it merely configures the MainWindow wh... | [
1,
1,
0
] | [] | [] | [
"macos",
"pyqt",
"python"
] | stackoverflow_0001583437_macos_pyqt_python.txt |
Q:
How to concatenate multiple Python source files into a single file?
(Assume that: application start-up time is absolutely critical; my application is started a lot; my application runs in an environment in which importing is slower than usual; many files need to be imported; and compilation to .pyc files is not av... | How to concatenate multiple Python source files into a single file? | (Assume that: application start-up time is absolutely critical; my application is started a lot; my application runs in an environment in which importing is slower than usual; many files need to be imported; and compilation to .pyc files is not available.)
I would like to concatenate all the Python source files that de... | [
"If this is on google app engine as the tags indicate, make sure you are using this idiom\ndef main(): \n #do stuff\nif __name__ == '__main__':\n main()\n\nBecause GAE doesn't restart your app every request unless the .py has changed, it just runs main() again.\nThis trick lets you write CGI style apps withou... | [
3,
1,
0,
0
] | [] | [] | [
"concatenation",
"google_app_engine",
"import",
"module",
"python"
] | stackoverflow_0001580746_concatenation_google_app_engine_import_module_python.txt |
Q:
Is there a standalone Python type conversion library?
Are there any standalone type conversion libraries?
I have a data storage system that only understands bytes/strings, but I can tag metadata such as the type to be converted to.
I could hack up some naive system of type converters, as every other application ha... | Is there a standalone Python type conversion library? | Are there any standalone type conversion libraries?
I have a data storage system that only understands bytes/strings, but I can tag metadata such as the type to be converted to.
I could hack up some naive system of type converters, as every other application has done before me, or I could hopefully use a standalone lib... | [
"You've got two options, either use the struct or pickle modules.\nWith struct you specify a format and it compacts your data to byte array. This is useful for working with C structures or writing to networked apps that require are binary protocol.\npickle can automatically serialise and deserialise complex Python ... | [
3,
3,
1
] | [] | [] | [
"python",
"type_conversion"
] | stackoverflow_0000468639_python_type_conversion.txt |
Q:
web2py - require selected dropdown values validate from db
i have a table member that include SQLField("year", db.All_years)
and All_years table as the following:
db.define_table("All_years",
SQLField("fromY","integer"),
SQLField("toY","integer")
)
and constrains are :
db.member.year.requires = IS_IN_DB(db... | web2py - require selected dropdown values validate from db | i have a table member that include SQLField("year", db.All_years)
and All_years table as the following:
db.define_table("All_years",
SQLField("fromY","integer"),
SQLField("toY","integer")
)
and constrains are :
db.member.year.requires = IS_IN_DB(db, 'All_years.id','All_years.fromY')
The problem is when I selec... | [
"I see your project is progressing well!\nThe validator is IS_IN_DB(dbset, field, label). So you should try:\ndb.member.year.requires = IS_IN_DB(db, 'All_years.id', '%(fromY)d')\n\nto have a correct label in your drop-down list.\nNow from your table it looks like you would rather choose an interval rather than just... | [
2
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0001584909_python_web2py.txt |
Q:
Grep multi-layered iterable for strings that match (Python)
Say that we have a multilayered iterable with some strings at the "final" level, yes strings are iterable, but I think that you get my meaning:
['something',
('Diff',
('diff', 'udiff'),
('*.diff', '*.patch'),
('text/x-diff', 'text/x-patch')),
('Delphi',... | Grep multi-layered iterable for strings that match (Python) | Say that we have a multilayered iterable with some strings at the "final" level, yes strings are iterable, but I think that you get my meaning:
['something',
('Diff',
('diff', 'udiff'),
('*.diff', '*.patch'),
('text/x-diff', 'text/x-patch')),
('Delphi',
('delphi', 'pas', 'pascal', 'objectpascal'),
('*.pas',),
('text/... | [
"I'd split recursive enumeration from grepping:\ndef enumerate_recursive(iter, base=()):\n for index, item in enumerate(iter):\n if isinstance(item, basestring):\n yield (base + (index,)), item\n else:\n for pair in enumerate_recursive(item, (base + (index,))):\n ... | [
3,
1,
0
] | [] | [] | [
"data_structures",
"python",
"regex",
"search",
"string"
] | stackoverflow_0001584864_data_structures_python_regex_search_string.txt |
Q:
Python optional parameters
Guys, I just started python recently and get confused with the optional parameters, say I have the program like this:
class B:
pass
class A:
def __init__(self, builds = B()):
self.builds = builds
If I create A twice
b = A()
c = A()
and print their builds
print b.builds
... | Python optional parameters | Guys, I just started python recently and get confused with the optional parameters, say I have the program like this:
class B:
pass
class A:
def __init__(self, builds = B()):
self.builds = builds
If I create A twice
b = A()
c = A()
and print their builds
print b.builds
print c.builds
I found they are... | [
"You need to understand how default values work in order to use them effectively.\nFunctions are objects. As such, they have attributes. So, if I create this function:\n>>> def f(x, y=[]):\n y.append(x)\n return y\n\nI've created an object. Here are its attributes:\n>>> dir(f)\n['__call__', '__clas... | [
47,
15,
6
] | [] | [] | [
"optional_arguments",
"python"
] | stackoverflow_0001585247_optional_arguments_python.txt |
Q:
django Unicode GET Parameter Values
I'm trying to get a GET parameter value that looks like this:
http://someurl/handler.json?&q=%E1%F8%E0%F1%F8%E9
The q parameter in this case is Hebrew.
I'm trying to read the value using the following code:
request.GET.get("q", None)
I'm getting gybrish instead of the correct t... | django Unicode GET Parameter Values | I'm trying to get a GET parameter value that looks like this:
http://someurl/handler.json?&q=%E1%F8%E0%F1%F8%E9
The q parameter in this case is Hebrew.
I'm trying to read the value using the following code:
request.GET.get("q", None)
I'm getting gybrish instead of the correct text.
Any idea what's wrong here? Am I m... | [
"The query string is in ISO-8859-8, but Django's default encoding is UTF-8. You will have to change either DEFAULT_CHARSET or HttpRequest.encoding to ISO-8859-8 to get the correct Unicode data.\n"
] | [
3
] | [] | [] | [
"django",
"python",
"unicode"
] | stackoverflow_0001585439_django_python_unicode.txt |
Q:
sending email from wave robot
Anyone know how to send an email using google wave python api?
Thanks
A:
Being a wave robot is nothing special here - you've got to determine at what point you want to send email, but you haven't told us anything about that, so it's hard to advise you.
When you've worked out what yo... | sending email from wave robot | Anyone know how to send an email using google wave python api?
Thanks
| [
"Being a wave robot is nothing special here - you've got to determine at what point you want to send email, but you haven't told us anything about that, so it's hard to advise you.\nWhen you've worked out what you want to send, just follow the normal instructions for sending email from Python in AppEngine.\n"
] | [
5
] | [] | [] | [
"api",
"google_app_engine",
"google_wave",
"python"
] | stackoverflow_0001585487_api_google_app_engine_google_wave_python.txt |
Q:
Is the Python GIL really per interpreter?
I often see people talking that the GIL is per Python Interpreter (even here on stackoverflow).
But what I see in the source code it seems to be that the GIL is a global variable and therefore there is one GIL for all Interpreters in each python process. I know they did th... | Is the Python GIL really per interpreter? | I often see people talking that the GIL is per Python Interpreter (even here on stackoverflow).
But what I see in the source code it seems to be that the GIL is a global variable and therefore there is one GIL for all Interpreters in each python process. I know they did this because there is no interpreter object passe... | [
"The GIL is indeed per-process, not per-interpreter. This is unchanged in 3.x.\n",
"Perhaps the confusion comes about because most people assume Python has one interpreter per process. I recall reading that the support for multiple interpreters via the C API was largely untested and hardly ever used. (And when I ... | [
12,
3,
0
] | [] | [] | [
"gil",
"multithreading",
"python"
] | stackoverflow_0001585181_gil_multithreading_python.txt |
Q:
Better way to do string filtering/manipulation
mystring = '14| "Preprocessor Frame Count Not Incrementing; Card: Motherboard, Port: 2"|minor'
So I have 3 elements (id, message and level) divided by pipe ("|"). I want to get each element so I have written these little functions:
def get_msg(i):
x = i.sp... | Better way to do string filtering/manipulation | mystring = '14| "Preprocessor Frame Count Not Incrementing; Card: Motherboard, Port: 2"|minor'
So I have 3 elements (id, message and level) divided by pipe ("|"). I want to get each element so I have written these little functions:
def get_msg(i):
x = i.split("|")
return x[1].strip().replace('"','')... | [
"I think the most pythonic way is to use the csv module.\nFrom PyMotW with delimiter option:\nimport csv\nimport sys\n\nf = open(sys.argv[1], 'rt')\ntry:\n reader = csv.reader(f, delimiter='|')\n for row in reader:\n print row\nfinally:\n f.close()\n\n",
"lst = msg.split('|')\nlevel = lst[2].strip... | [
5,
2,
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001584639_python_string.txt |
Q:
Storing wiki revisions on Google App Engine/Django - Modifying This Existing Code
In the past, I created a Django wiki, and it was fairly straightforward to make a Page table for the current wiki entries, and then to store old revisions into a Revision table.
More recently, I decided to set up a website on Google ... | Storing wiki revisions on Google App Engine/Django - Modifying This Existing Code | In the past, I created a Django wiki, and it was fairly straightforward to make a Page table for the current wiki entries, and then to store old revisions into a Revision table.
More recently, I decided to set up a website on Google App Engine, and I used some wiki code that another programmer wrote. Because he created... | [
"The code in your first snippet is not a model - it's a custom class that uses the low-level datastore module. If you want to extend it, I would recommend throwing it out and replacing it with actual models, along similar lines to the Article model you demonstrated in your second snippet.\nAlso, they're App Engine ... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"google_app_engine",
"python"
] | stackoverflow_0001583595_django_django_models_google_app_engine_python.txt |
Q:
sqlite3 and cursor.description
When using the sqlite3 module in python, all elements of cursor.description except the column names are set to None, so this tuple cannot be used to find the column types for a query result (unlike other DB-API compliant modules). Is the only way to get the types of the columns to us... | sqlite3 and cursor.description | When using the sqlite3 module in python, all elements of cursor.description except the column names are set to None, so this tuple cannot be used to find the column types for a query result (unlike other DB-API compliant modules). Is the only way to get the types of the columns to use pragma table_info(table_name).fetc... | [
"No, it's not the only way. Alternatively, you can also fetch one row, iterate over it, and inspect the individual column Python objects and types. Unless the value is None (in which case the SQL field is NULL), this should give you a fairly precise indication what the database column type was.\nsqlite3 only uses s... | [
5,
2
] | [] | [] | [
"python",
"python_db_api",
"sqlite"
] | stackoverflow_0001583350_python_python_db_api_sqlite.txt |
Q:
Does anyone know a "working" Python library that can read .ARC files?
An ARC file is a lossless data-compression format.
http://en.wikipedia.org/wiki/ARC_%28file_format%29
I've tried googling some, but the Python ARC readers are 404 errors, or cannot be found.
Anyone know of any library I can use?
A:
If you are... | Does anyone know a "working" Python library that can read .ARC files? | An ARC file is a lossless data-compression format.
http://en.wikipedia.org/wiki/ARC_%28file_format%29
I've tried googling some, but the Python ARC readers are 404 errors, or cannot be found.
Anyone know of any library I can use?
| [
"If you are able to use SWIG then possibly the ARC source code from FreeBSD could be used. Or you could have a look at the source, and perhaps reimplement it in Python. I remember ARC and it did not last very long as a popular tool so I suspect that it is not overly complex. \n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001569836_python.txt |
Q:
union with sort in Google-App-Engine
I have a class:
class Transaction(db.Model):
accountDebit = db.ReferenceProperty(reference_class=Account,
collection_name="kontoDuguje")
accountCredit = db.ReferenceProperty(reference_class=Account,
... | union with sort in Google-App-Engine | I have a class:
class Transaction(db.Model):
accountDebit = db.ReferenceProperty(reference_class=Account,
collection_name="kontoDuguje")
accountCredit = db.ReferenceProperty(reference_class=Account,
collection_name="kontoPotrazuje")
... | [
"You can do an OR (Python laboriously synthesizes it for you at application level), which takes care of the \"union with sorty\". However, if you need to worry about > 1000 transactions, that won't help (nor will offset and limit: the sum of offset + limit is what's limited to 1000!). You'll need to slice by somet... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001585299_google_app_engine_python.txt |
Q:
Using SWIG with pointer to function in C struct
I'm trying to write a SWIG wrapper for a C library that uses pointers to functions in its structs. I can't figure out how to handle structs that contain function pointers. A simplified example follows.
test.i:
/* test.i */
%module test
%{
typedef struct {
int... | Using SWIG with pointer to function in C struct | I'm trying to write a SWIG wrapper for a C library that uses pointers to functions in its structs. I can't figure out how to handle structs that contain function pointers. A simplified example follows.
test.i:
/* test.i */
%module test
%{
typedef struct {
int (*my_func)(int);
} test_struct;
int add1(int n) { r... | [
"I found an answer. If I declare the function pointer as a SWIG \"member function\", it seems to work as expected:\n%module test\n%{\n\ntypedef struct {\n int (*my_func)(int);\n} test_struct;\n\nint add1(int n) { return n+1; }\n\ntest_struct *init_test()\n{\n test_struct *t = (test_struct*) malloc(sizeof(test_... | [
1,
0
] | [] | [] | [
"c",
"function",
"pointers",
"python",
"swig"
] | stackoverflow_0001583293_c_function_pointers_python_swig.txt |
Q:
django and executing a separate .py to manipute a database
I want to execute a random .py file, say foo.py on the myproject/myapp folder by using crobjob by some periods
I have this basic model in my model.py for the app:
class Mymodel(models.Model):
content = models.TextField()
Say I have this in my foo.py, ... | django and executing a separate .py to manipute a database | I want to execute a random .py file, say foo.py on the myproject/myapp folder by using crobjob by some periods
I have this basic model in my model.py for the app:
class Mymodel(models.Model):
content = models.TextField()
Say I have this in my foo.py, I want to check if there is any Mymodel object that has a conten... | [
"You have two separate questions here - it would have been better to split them out.\nTo run a separate script, you're best off creating a ./manage.py command. See the documentation on how to do this.\nFor your second question, the code you give is not valid Python, since there is no 'null' value - you mean None. H... | [
5,
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001586041_django_django_models_python.txt |
Q:
Human-readable binary data using Python
My work requires that I perform a mathematical simulation whose parameters come from a binary file. The simulator can read such binary file without a problem.
However, I need to peek inside the binary file to make sure the parameters are what I need them to be, and I cannot ... | Human-readable binary data using Python | My work requires that I perform a mathematical simulation whose parameters come from a binary file. The simulator can read such binary file without a problem.
However, I need to peek inside the binary file to make sure the parameters are what I need them to be, and I cannot seem to be able to do it.
I would like to wri... | [
"You can read the file's content into a string in memory:\nthedata = open(thefilename, 'rb').read()\n\nand then locate a string in it:\nwhere = thedata.find('CENTRAL_BODY')\n\nand finally slice off the part you care about:\nthepart = thedata[where:where+50] # or whatever length\n\nand display it as you prefer (e.g... | [
4,
1,
1,
0
] | [] | [] | [
"ascii",
"binary_data",
"format",
"python"
] | stackoverflow_0001585950_ascii_binary_data_format_python.txt |
Q:
parsing string to a dict
I have a string output which is in form of a dict ex.
{'key1':'value1','key2':'value2'}
how can make easily save it as a dict and not as a string?
A:
astr is a string which is "in the form of a dict".
ast.literal_eval converts it to a python dict object.
In [110]: import ast
In [111]... | parsing string to a dict | I have a string output which is in form of a dict ex.
{'key1':'value1','key2':'value2'}
how can make easily save it as a dict and not as a string?
| [
"astr is a string which is \"in the form of a dict\".\nast.literal_eval converts it to a python dict object.\nIn [110]: import ast\n\nIn [111]: astr=\"{'key1':'value1','key2':'value2'}\"\n\nIn [113]: ast.literal_eval(astr)\nOut[113]: {'key1': 'value1', 'key2': 'value2'}\n\n",
"This is best if you're on Python 2.6... | [
6,
4,
1,
1
] | [] | [] | [
"abstract_syntax_tree",
"eval",
"parsing",
"python",
"string"
] | stackoverflow_0001585267_abstract_syntax_tree_eval_parsing_python_string.txt |
Q:
Given a string, how do I know if it needs decoding
I'm using python's base64 module and I get a string that can be encoded or not encoded. I would like to do something like:
if isEncoded(s):
output = base64.decodestring(s)
else:
output = s
ideas?
A:
In general, it's impossible; if you receive string 'MjMj... | Given a string, how do I know if it needs decoding | I'm using python's base64 module and I get a string that can be encoded or not encoded. I would like to do something like:
if isEncoded(s):
output = base64.decodestring(s)
else:
output = s
ideas?
| [
"In general, it's impossible; if you receive string 'MjMj', for example, how could you possibly know whether it's already decoded and needs to be used as is, or decoded into '23#'?\n",
"You could just try it, and see what happens:\nimport base64\n\ndef decode_if_necessary(s):\n try:\n return base64.dec... | [
11,
5,
5
] | [] | [] | [
"base64",
"python"
] | stackoverflow_0001532567_base64_python.txt |
Q:
google wave OnBlipSubmitted
I'm trying to create a wave robot, and I have the basic stuff working. I'm trying to create a new blip with help text when someone types @help but for some reason it doesnt create it. I'm getting no errors in the log console, and I'm seeing the info log 'in @log'
def OnBlipSubmitted(pro... | google wave OnBlipSubmitted | I'm trying to create a wave robot, and I have the basic stuff working. I'm trying to create a new blip with help text when someone types @help but for some reason it doesnt create it. I'm getting no errors in the log console, and I'm seeing the info log 'in @log'
def OnBlipSubmitted(properties, context):
# Get the bl... | [
"if it just started working, I have two suggestions...\n-->Have you been updating the Robot Version in the constructor? You should change the values as you update changes so that the caches can be updated.\nif __name__ == '__main__': \n myRobot = robot.Robot('waverobotdev... | [
1,
0,
0
] | [] | [] | [
"google_app_engine",
"google_wave",
"python"
] | stackoverflow_0001584406_google_app_engine_google_wave_python.txt |
Q:
Custom Django-admin command issue
trying to understand how custom admin commands work, I have my project named "mailing" and app inside named "msystem", I have written this retrieve.py to the mailing/msystem/management/commands/ folder and I have pasted an empty init.py both to the management and cpmmands folders.... | Custom Django-admin command issue | trying to understand how custom admin commands work, I have my project named "mailing" and app inside named "msystem", I have written this retrieve.py to the mailing/msystem/management/commands/ folder and I have pasted an empty init.py both to the management and cpmmands folders.
from django.core.management.base impor... | [
"Your indentation needs to be consistent through the entire file, which it isn't in the snippet you posted above.\nThe \"help = \" line is indented four spaces after \"class\" but then the \"x =\" line is indented many more than four.\nMaybe you are mixing spaces and tabs and thus have two tabs before \"x =\"?\nYou... | [
4,
2
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0001587282_django_django_admin_python.txt |
Q:
How to write a program that will automically generate sample exam questions from a file?
How can I write a program that will automatically generate a sample examination?
For example, the user will be prompted to supply four categories of questions to be included in the a 6 question exam from the following list:
... | How to write a program that will automically generate sample exam questions from a file? | How can I write a program that will automatically generate a sample examination?
For example, the user will be prompted to supply four categories of questions to be included in the a 6 question exam from the following list:
Loops
Functions
Decisions
Data Types
Built-in functions
Recursion
Algorithms
Top-down design
... | [
"In the absence of additional information required to answer this specific problem, I will outline the general approach I would use to solve this problem. My solution would involve using LaTeX to typeset the exam and the probsoln package to define problems.\nThe probsoln package provides a format for defining and ... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0001587248_python.txt |
Q:
what is the correct way to process 4 bits inside an octet in python
I'm writing an application to parse certain network packets. A packet field contains the protocol version number in an octet, so that 4 high bits are the 'major' and low 4 are the 'minor' version. Currently I am parsing them as follows, but am won... | what is the correct way to process 4 bits inside an octet in python | I'm writing an application to parse certain network packets. A packet field contains the protocol version number in an octet, so that 4 high bits are the 'major' and low 4 are the 'minor' version. Currently I am parsing them as follows, but am wondering if there is a prettier or more 'pythonic' way of doing it:
v =... | [
"You can write binary literals like this0b1111000\nFor your example I would proabbly use hex though\nv = ord(data[17])\nmajor = (v & 0xF0) >> 4\nminor = (v & 0x0F)\n\nYou might also want to use the struct module to break the packet into its components\n",
"Well named functions are always a good way to hide ugline... | [
3,
2,
1,
0
] | [] | [] | [
"bit_manipulation",
"python"
] | stackoverflow_0001587496_bit_manipulation_python.txt |
Q:
How to clear cookies using python 2.6.x cookielib
It seems my previous description was not clear, so rewriting it.
Using python urllib2, I am automating fileupload task in my webapp. And am using Cookielib to store session information, and also I could able to successfully automate the fileupload task. Problem is... | How to clear cookies using python 2.6.x cookielib | It seems my previous description was not clear, so rewriting it.
Using python urllib2, I am automating fileupload task in my webapp. And am using Cookielib to store session information, and also I could able to successfully automate the fileupload task. Problem is, when I change the login credentials and did not suppl... | [
"you need to install the opener that you have built, otherwise it will just keep using the default\n",
"Instead of relying on cookies, I am restricting page access based response headers. Now, I could able to stop the file upload process when wrong credentials supplied. Thanks guys.\n"
] | [
0,
0
] | [] | [] | [
"cookies",
"python"
] | stackoverflow_0001530464_cookies_python.txt |
Q:
PHP, Python, Ruby application with multiple RDBMS
I start feeling old fashioned when I see all these SQL generating database abstraction layers and all those ORMs out there, although I am far from being old. I understand the need for them, but their use spreads to places they normally don't belong to.
I firmly bel... | PHP, Python, Ruby application with multiple RDBMS | I start feeling old fashioned when I see all these SQL generating database abstraction layers and all those ORMs out there, although I am far from being old. I understand the need for them, but their use spreads to places they normally don't belong to.
I firmly believe that using database abstraction layers for SQL gen... | [
"If you want to leverage the bells and whistles of various RDBMSes, you can certainly do it. Just apply standard OO Principles. Figure out what kind of API your persistence layer will need to provide. \nYou'll end up writing a set of isomorphic persistence adapter classes. From the perspective of your model cod... | [
2,
2,
0,
0
] | [] | [] | [
"database",
"php",
"python",
"ruby_on_rails"
] | stackoverflow_0001586008_database_php_python_ruby_on_rails.txt |
Q:
Caching system for dynamically created files?
I have a web server that is dynamically creating various reports in several formats (pdf and doc files). The files require a fair amount of CPU to generate, and it is fairly common to have situations where two people are creating the same report with the same input.
In... | Caching system for dynamically created files? | I have a web server that is dynamically creating various reports in several formats (pdf and doc files). The files require a fair amount of CPU to generate, and it is fairly common to have situations where two people are creating the same report with the same input.
Inputs:
raw data input as a string (equations, numbe... | [
"This is what Apache is for.\nCreate a directory that will have the reports.\nConfigure Apache to serve files from that directory.\nIf the report exists, redirect to a URL that Apache will serve.\nOtherwise, the report doesn't exist, so create it. Then redirect to a URL that Apache will serve.\n\nThere's no \"hash... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001587991_python.txt |
Q:
Using different versions of a python library in the same process
We've got a python library that we're developing. During development, I'd like to use some parts of that library in testing the newer versions of it. That is, use the stable code in order to test the development code. Is there any way of doing this i... | Using different versions of a python library in the same process | We've got a python library that we're developing. During development, I'd like to use some parts of that library in testing the newer versions of it. That is, use the stable code in order to test the development code. Is there any way of doing this in python?
Edit: To be more specific, we've got a library (LibA) that h... | [
"If you \"test\" libA-dev using libT which depends on libA (stable), then you are not really testing libA-dev as it would behave in a production environment. The only way to really test libA-dev is to take the full plunge and make libT depend on libA-dev. If this breaks your unit tests then that is a good thing -- ... | [
1,
1,
0
] | [] | [] | [
"circular_dependency",
"dependencies",
"python",
"testing"
] | stackoverflow_0001587776_circular_dependency_dependencies_python_testing.txt |
Q:
how to determine if webpage has been modified
I have snapshots of multiple webpages taken at 2 times. What is a reliable method to determine which webpages have been modified?
I can't rely on something like an RSS feed, and I need to ignore minor noise like date text.
Ideally I am looking for a Python solution, b... | how to determine if webpage has been modified | I have snapshots of multiple webpages taken at 2 times. What is a reliable method to determine which webpages have been modified?
I can't rely on something like an RSS feed, and I need to ignore minor noise like date text.
Ideally I am looking for a Python solution, but an intuitive algorithm would also be great.
Than... | [
"Well, first you need to decide what is noise and what isn't. You can use a HTML parser like BeautifulSoup to remove the noise, pretty-print the result, and compare it as a string.\nIf you are looking for an automatic solution, you can use difflib.SequenceMatcher to calculate the differences between the pages, calc... | [
8,
3,
0
] | [
"just take snapshots of the files with MD5 or SHA1...if the values differ the next time you check, then they are modified.\n"
] | [
-1
] | [
"diff",
"python",
"snapshot",
"webpage"
] | stackoverflow_0001587902_diff_python_snapshot_webpage.txt |
Q:
Light-weight renderer HTML with CSS in Python
Sorry, perhaps I haven't described the problem well first time. All your answers are interesting, but most of them are almost full-featured web browsers, my task is much simpler.
I'm planning to write a GUI application using one of the available on linux GUI frameworks... | Light-weight renderer HTML with CSS in Python | Sorry, perhaps I haven't described the problem well first time. All your answers are interesting, but most of them are almost full-featured web browsers, my task is much simpler.
I'm planning to write a GUI application using one of the available on linux GUI frameworks (I haven't yet chosen one). I shall use html in my... | [
"You should use a UI framework:\n\nQt: The simplest class to use would be QWebView\nGtk: pywebkitgtk would be the best answer, but you can find others in the PyGTK page.\nIn Tk is the TkHtml widget from here\n\nAn other option is to open the OS default web browser through something like this:\nimport webbrowser\nur... | [
15,
0,
0
] | [] | [] | [
"browser",
"html",
"python"
] | stackoverflow_0001587637_browser_html_python.txt |
Q:
What are the use cases for non relational datastores?
I'm looking at using CouchDB for one project and the GAE app engine datastore in the other. For relational stuff I tend to use postgres, although I much prefer an ORM.
Anyway, what use cases suit non relational datastores best?
A:
Here is a nice little art... | What are the use cases for non relational datastores? | I'm looking at using CouchDB for one project and the GAE app engine datastore in the other. For relational stuff I tend to use postgres, although I much prefer an ORM.
Anyway, what use cases suit non relational datastores best?
| [
"Here is a nice little article (spread over three pages) that covers the use-case for non-relational databases.\nhttp://www.readwriteweb.com/enterprise/2009/02/is-the-relational-database-doomed.php\nIn a nutshell, when you need massive scalability then you probably need a non-realtional db. Of course, you may well ... | [
7,
2,
0
] | [] | [] | [
"couchdb",
"google_app_engine",
"python"
] | stackoverflow_0001588708_couchdb_google_app_engine_python.txt |
Q:
A good data model for finding a user's favorite stories
Original Design
Here's how I originally had my Models set up:
class UserData(db.Model):
user = db.UserProperty()
favorites = db.ListProperty(db.Key) # list of story keys
# ...
class Story(db.Model):
title = db.StringProperty()
# ...
On e... | A good data model for finding a user's favorite stories | Original Design
Here's how I originally had my Models set up:
class UserData(db.Model):
user = db.UserProperty()
favorites = db.ListProperty(db.Key) # list of story keys
# ...
class Story(db.Model):
title = db.StringProperty()
# ...
On every page that displayed a story I would query UserData for t... | [
"What you've described is a good solution. You can optimise it further, however: For each favorite, create a 'UserFavorite' entity as a child entity of the relevant Story entry (or equivalently, as a child entity of a UserInfo entry), with the key name set to the user's unique ID. This way, you can determine if a u... | [
2,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001562131_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python XMLRPC with concurrent requests
I'm looking for a way to prevent multiple hosts from issuing simultaneous commands to a Python XMLRPC listener. The listener is responsible for running scripts to perform tasks on that system that would fail if multiple users tried to issue these commands at the same time. Is... | Python XMLRPC with concurrent requests | I'm looking for a way to prevent multiple hosts from issuing simultaneous commands to a Python XMLRPC listener. The listener is responsible for running scripts to perform tasks on that system that would fail if multiple users tried to issue these commands at the same time. Is there a way I can block all incoming reques... | [
"I think python SimpleXMLRPCServer module is what you want. I believe the default behavior of that model is blocking new requests when current request is processing. The default behavior gave me lots of trouble and I changed that behavior by mix in ThreadingMixIn class so that my xmlrpc server could respond multipl... | [
17,
0,
0
] | [] | [] | [
"python",
"xml_rpc"
] | stackoverflow_0001589150_python_xml_rpc.txt |
Q:
Python: Difference between 'global' & globals().update(var)
What is the difference between initializing a variable as global var or calling globals().update(var).
Thanks
A:
When you say
global var
you are telling Python that var is the same var that was defined in a global context.
You would use it in the follo... | Python: Difference between 'global' & globals().update(var) | What is the difference between initializing a variable as global var or calling globals().update(var).
Thanks
| [
"When you say\nglobal var\n\nyou are telling Python that var is the same var that was defined in a global context.\nYou would use it in the following way:\nvar=0\ndef f():\n global var\n var=1\nf()\nprint(var)\n# 1 <---- the var outside the \"def f\" block is affected by calling f()\n\nWithout the global sta... | [
29
] | [] | [] | [
"global",
"python",
"variables"
] | stackoverflow_0001589968_global_python_variables.txt |
Q:
Must two SQLAlchemy declarative models share the same declarative_base()?
Is it necessary for two SQLAlchemy models to inherit from the same instance of declarative_base() if they must participate in the same Session? This is likely to be the case when importing two or more modules that define SQLAlchemy models.
f... | Must two SQLAlchemy declarative models share the same declarative_base()? | Is it necessary for two SQLAlchemy models to inherit from the same instance of declarative_base() if they must participate in the same Session? This is likely to be the case when importing two or more modules that define SQLAlchemy models.
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base... | [
"I successfully use different declarative bases in single session. This can be useful when using several databases: each base is created with own metadata and each metadata is bound to separate database. Some of your declarative bases could define additional methods or they could use another metaclass to install ex... | [
5,
4
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0001589748_orm_python_sqlalchemy.txt |
Q:
How do I write a unix filter in python?
I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars x from stdin.
A:
Read from sys.stdin and write to sys.stdout (or use prin... | How do I write a unix filter in python? | I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars x from stdin.
| [
"Read from sys.stdin and write to sys.stdout (or use print). Your example program:\nimport sys\n\nfor line in sys.stdin:\n print line.replace(\"x\", \"\"),\n\nThere isn't a standard way to make stdin unbuffered, and you don't want that. Let the OS buffer it.\n",
"You can use the fileinput class, which lets yo... | [
15,
15,
6,
4
] | [] | [] | [
"filter",
"python",
"unix"
] | stackoverflow_0001589994_filter_python_unix.txt |
Q:
Django admin won't let me delete a user in its auth admin application
This may be more of a serverfault question I'm not sure.
I have two practically identical servers - I cloned the DB from one to the other, and now when I try to delete a user in the Admin > Auth application Django gives the following error:
File... | Django admin won't let me delete a user in its auth admin application | This may be more of a serverfault question I'm not sure.
I have two practically identical servers - I cloned the DB from one to the other, and now when I try to delete a user in the Admin > Auth application Django gives the following error:
File "/usr/lib/python2.5/site-packages/django/db/models/sql/query.py", line 206... | [
"This was resolved by doing a ./manage.py syncdb\nIt must have got out of date somehow.\n"
] | [
0
] | [] | [] | [
"django",
"pinax",
"python"
] | stackoverflow_0001578372_django_pinax_python.txt |
Q:
Python Deprecation Warnings with Monostate __new__ -- Can someone explain why?
I have a basic Monostate with Python 2.6.
class Borg(object):
__shared_state = {}
def __new__(cls, *args, **kwargs):
self = object.__new__(cls, *args, **kwargs)
self.__dict__ = cls.__shared_state
return s... | Python Deprecation Warnings with Monostate __new__ -- Can someone explain why? | I have a basic Monostate with Python 2.6.
class Borg(object):
__shared_state = {}
def __new__(cls, *args, **kwargs):
self = object.__new__(cls, *args, **kwargs)
self.__dict__ = cls.__shared_state
return self
def __init__(self, *args, **kwargs):
noSend = kwargs.get("noSend", ... | [
"See python-singleton-object-instantiation, and note Alex Martelli's singleton example:\nclass Singleton(object):\n\n __instance = None\n\n def __new__(cls):\n if cls.__instance == None:\n __instance = type.__new__(cls)\n __instance.name = \"The one\"\n return __instance\n\... | [
6,
1
] | [] | [] | [
"deprecated",
"monostate",
"python"
] | stackoverflow_0001590477_deprecated_monostate_python.txt |
Q:
How to generate random 'greenish' colors
Anyone have any suggestions on how to make randomized colors that are all greenish? Right now I'm generating the colors by this:
color = (randint(100, 200), randint(120, 255), randint(100, 200))
That mostly works, but I get brownish colors a lot.
A:
Simple solution: Use... | How to generate random 'greenish' colors | Anyone have any suggestions on how to make randomized colors that are all greenish? Right now I'm generating the colors by this:
color = (randint(100, 200), randint(120, 255), randint(100, 200))
That mostly works, but I get brownish colors a lot.
| [
"Simple solution: Use the HSL or HSV color space instead of rgb (convert it to RGB afterwards if you need this). The difference is the meaning of the tuple: Where RGB means values for Red, Green and Blue, in HSL the H is the color (120 degree or 0.33 meaning green for example) and the S is for saturation and the V ... | [
54,
21,
16,
9,
5,
3,
1,
0,
0
] | [] | [] | [
"colors",
"language_agnostic",
"python",
"random"
] | stackoverflow_0001586147_colors_language_agnostic_python_random.txt |
Q:
Python| How can I make this variable global without initializing it as 'global'
I have this code here. The only part I can add code to is in main_____ AFTER the 'i=1' line. This script will be executing multiple times and will have some variable (might not be 'i', could be 'xy', 'var', anything), incrementing by 1... | Python| How can I make this variable global without initializing it as 'global' | I have this code here. The only part I can add code to is in main_____ AFTER the 'i=1' line. This script will be executing multiple times and will have some variable (might not be 'i', could be 'xy', 'var', anything), incrementing by 1 each time. I have gotten this to work by declaring 'i' as global above the method, b... | [
"If you want to use a global variable you have to declare it as global. What's wrong with that?\nIf you need to store state between calls, you should be using a class\n>>> class F():\n... def __init__(self):\n... self.i=0\n... def __call__(self):\n... print self.i\n... self.i+=1\n...... | [
1
] | [] | [] | [
"global",
"python"
] | stackoverflow_0001590712_global_python.txt |
Q:
Preserving whitespace with Pygments
I'm currently writing an application that uses Pygments to perform syntax highlighting. The problem I'm having is any code I process with Pygments has the leading and trailing whitespace in the file removed, and a single line break added to the end. Is there a way to make Pygm... | Preserving whitespace with Pygments | I'm currently writing an application that uses Pygments to perform syntax highlighting. The problem I'm having is any code I process with Pygments has the leading and trailing whitespace in the file removed, and a single line break added to the end. Is there a way to make Pygments preserve the whitespace?
| [
"I think you want to make your own lexer, e.g.\nlexer = lexers.get_lexer_by_name(\"python\", stripnl=False)\n\nand explicitly pass it to pygment.highlight. See the lexers' reference here.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0001591024_python.txt |
Q:
Scheduled tasks in Win32
I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:
Daily
Start time: 12:03 AM
Schedule task daily: every 1 day
Start date: some time in the past
Repeat task: every 5 minutes
Until: Duration 24 hours
Basically, i want the script to run every five minutes, ... | Scheduled tasks in Win32 | I have a Scheduled Task on a WinXP SP2 machine that is set up to run a python script:
Daily
Start time: 12:03 AM
Schedule task daily: every 1 day
Start date: some time in the past
Repeat task: every 5 minutes
Until: Duration 24 hours
Basically, i want the script to run every five minutes, for ever.
My problem is the ta... | [
"you can schedule it from another script and kick this off once a day or after each reboot:\n#!/usr/bin/env python\n\nimport subprocess\n\ninterval = 300 # secs\n\nwhile True:\n p = subprocess.Popen(['pythonw.exe', 'foo.py'])\n time.sleep(interval)\n\nThis way you can do sub-minute intervals also.\n",
"On ... | [
3,
1,
1,
1,
1,
1,
0
] | [] | [] | [
"python",
"scheduled_tasks",
"windows_xp"
] | stackoverflow_0001590474_python_scheduled_tasks_windows_xp.txt |
Q:
How to prepare a django project for future changes
As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live... | How to prepare a django project for future changes | As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live and am certain that not long after I do, something new ... | [
"\nDeploy into a pure environment using virtualenv.\nDocument requirements using a pip requirements file.\n\nI'm sure others will suggest their deployment strategies, but making these changes were big positives for me.\n",
"Learn and use South at the outset, so when you make major DB schema changes, you'll have a... | [
8,
7,
5,
4
] | [
"\"something will come up and I'll wish I had implemented it earlier\"\nThat's the definition of a good site. One that evolves and changes.\n\"future-ready as possible ?\"\nWhat can this possibly mean? What specific things are you worried about? Technology is always changing. A good site is always evolving. Wh... | [
-2
] | [
"database",
"django",
"python"
] | stackoverflow_0001588570_database_django_python.txt |
Q:
Cron job to connect to sql server and run a sproc using python
I want to learn python, and my task is the run a sql server 2008 stored procedure via a cron job.
Can someone step through a script for me in python?
A:
I am assuming you mean Microsoft's SQL server...
#! /usr/bin/python
import pymssql
con = pymssql... | Cron job to connect to sql server and run a sproc using python | I want to learn python, and my task is the run a sql server 2008 stored procedure via a cron job.
Can someone step through a script for me in python?
| [
"I am assuming you mean Microsoft's SQL server...\n#! /usr/bin/python\n\nimport pymssql\ncon = pymssql.connect (host='xxxxx',user='xxxx',\n password='xxxxx',database='xxxxx')\ncur = con.cursor()\nquery = \"DECLARE @id INT; EXECUTE sp_GetUserID; SELECT @id;\"\ncur.execute(query)\noutputparamete... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001591477_python.txt |
Q:
From PHP workers to Python threads
Right now I'm running 50 PHP (in CLI mode) individual workers (processes) per machine that are waiting to receive their workload (job). For example, the job of resizing an image. In workload they receive the image (binary data) and the desired size. The worker does it's work and ... | From PHP workers to Python threads | Right now I'm running 50 PHP (in CLI mode) individual workers (processes) per machine that are waiting to receive their workload (job). For example, the job of resizing an image. In workload they receive the image (binary data) and the desired size. The worker does it's work and returns the resized image back. Then it ... | [
"Linux has shared libraries, so those 50 php processes use mostly the same libraries. \nYou don't sound like you even have a problem at all.\n\"this does not sound very effective.\" is not a problem description, if anything those words are a problem on their own. Writing code needs a real reason, else you're just w... | [
4,
4,
1
] | [] | [] | [
"multithreading",
"php",
"python"
] | stackoverflow_0001591555_multithreading_php_python.txt |
Q:
os.popen subprocess conversion
This snippet gets me the dotted quad of my BSD network interface.
I would like to figure out how to use the subprocess module instead.
ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines()
x = string.split(ifcfg_lines[3])[1]
Seems as if I can't use subprocess in exactly the same... | os.popen subprocess conversion | This snippet gets me the dotted quad of my BSD network interface.
I would like to figure out how to use the subprocess module instead.
ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines()
x = string.split(ifcfg_lines[3])[1]
Seems as if I can't use subprocess in exactly the same way.
I don't think I want shell=Tru... | [
"from subprocess import Popen, PIPE\n\nifcfg_lines = Popen(\"/sbin/ifconfig fxp0\",shell=True,stdout=PIPE).stdout.readlines()\nx = string.split(ifcfg_lines[3])[1]\n\nFor a little more elegance, hide the details:\ndef getBSDIP():\n from subprocess import Popen, PIPE\n import string\n\n CURRENT = Popen(\"/sbin/... | [
1,
0
] | [] | [] | [
"indexing",
"python",
"string",
"subprocess"
] | stackoverflow_0001591798_indexing_python_string_subprocess.txt |
Q:
PHP Sockets or Python, Perl, Bash Sockets?
I'm trying to implement a socket server that will run in most shared PHP hosting.
The requirements are that the Socket server can be installed, started and stopped from PHP automatically without the user doing anything. It doesn't matter what language the socket server is... | PHP Sockets or Python, Perl, Bash Sockets? | I'm trying to implement a socket server that will run in most shared PHP hosting.
The requirements are that the Socket server can be installed, started and stopped from PHP automatically without the user doing anything. It doesn't matter what language the socket server is written in, as long as it will run on the major... | [
"Any server can be stopped or started by PHP under Linux. Of course, if you are running a server which accepts sockets from the internet, then you can just connect directly to the server and tell it to shutdown. No need to go via PHP!\nAs for \"starting a server from PHP\", well, under Linux, anything can be star... | [
7,
2
] | [] | [] | [
"bash",
"perl",
"php",
"python",
"sockets"
] | stackoverflow_0001047991_bash_perl_php_python_sockets.txt |
Q:
Subclass lookup
(I'm developing in Python 3.1, so if there's some shiny new 3.x feature I should know about for this, please let me know!)
I've got a class (we'll just call it "Packet") that serves as the parent for a bunch of child classes representing each of a few dozen packet types in a legacy client-server pr... | Subclass lookup | (I'm developing in Python 3.1, so if there's some shiny new 3.x feature I should know about for this, please let me know!)
I've got a class (we'll just call it "Packet") that serves as the parent for a bunch of child classes representing each of a few dozen packet types in a legacy client-server protocol over which I h... | [
"\"I'd like the table built at runtime by examining all of the subclasses of Packet,\" \nThis is guaranteed to cause endless problems. This kind of thing puts a strange constraint on your subclasses. You can't use any abstract superclasses to simplify things.\nHere's a specific example of what won't work if you \... | [
3,
3,
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0001592089_python_python_3.x.txt |
Q:
Python binary data reading
A urllib2 request receives binary response as below:
00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
Its structure i... | Python binary data reading | A urllib2 request receives binary response as below:
00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41
97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47
0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41
97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00
00 01 16 7A 53 7C 80 FF FF
Its structure is:
DATA, TYPE, DESCRIPTION
00 ... | [
"So here's my best shot at interpreting the data you're giving...:\nimport datetime\nimport struct\n\nclass Printable(object):\n specials = ()\n def __str__(self):\n resultlines = []\n for pair in self.__dict__.items():\n if pair[0] in self.specials: continue\n resultlines.append('%10s %s' % pair)... | [
10,
6,
5,
2,
1,
0
] | [] | [] | [
"binary_data",
"python"
] | stackoverflow_0001591920_binary_data_python.txt |
Q:
Qt being now released under LGPL, would you recommend it over wxWidgets?
I am quite a heavy user of wxWidgets, partly because of licensing reasons.
How do you see the future of wxWidgets in prospect of the recent announcement of Qt now being released under LGPL?
Do you think wxwidget is still a good technical cho... | Qt being now released under LGPL, would you recommend it over wxWidgets? | I am quite a heavy user of wxWidgets, partly because of licensing reasons.
How do you see the future of wxWidgets in prospect of the recent announcement of Qt now being released under LGPL?
Do you think wxwidget is still a good technical choice for new projects ? Or would you recommand adopting Qt, because it is going... | [
"For those of us who are drawn to wxWidgets because it is the cross-platform library that uses native controls for proper look and feel the licensing change of Qt has little to no consequences.\nEdit:\nRegarding\n\nQt not having native controls but native drawing functions\n\nlet me quote the wxWidgets wiki page co... | [
17,
13,
8,
8,
3,
3,
2
] | [] | [] | [
"python",
"qt",
"wxpython",
"wxwidgets"
] | stackoverflow_0000464463_python_qt_wxpython_wxwidgets.txt |
Q:
Rendering different part of templates according to the request values in Django
In my view to render my template I receive different parameters through my request.
According to these parameters I need to render different "part" in my templates.
For example let say that if I receive in my request
to_render = ["tabl... | Rendering different part of templates according to the request values in Django | In my view to render my template I receive different parameters through my request.
According to these parameters I need to render different "part" in my templates.
For example let say that if I receive in my request
to_render = ["table", "bar_chart"]
I want to render a partial template for table and an other for bar_... | [
"just manage it in your template\n",
"Sure, you can manage this in your view. The template API shows clearly how to use the templating system in Python.\n"
] | [
2,
1
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0001592331_django_django_templates_django_views_python.txt |
Q:
How to make all combinations of the elements in an array?
I have a list. It contains x lists, each with y elements.
I want to pair each element with all the other elements, just once, (a,b = b,a)
EDIT: this has been criticized as being too vague.So I'll describe the history.
My function produces random equations a... | How to make all combinations of the elements in an array? | I have a list. It contains x lists, each with y elements.
I want to pair each element with all the other elements, just once, (a,b = b,a)
EDIT: this has been criticized as being too vague.So I'll describe the history.
My function produces random equations and using genetic techniques, mutates and crossbreeds them, sele... | [
"itertools.product is your friend.\nabout removing the duplicates, try with a set of sets.\nNow it's a little bit clearer what you want:\nimport itertools\n\ndef recombinate(families):\n \"families is the list of 8 elements, each one with 12 individuals\"\n for fi, fj in itertools.combinations(families, 2):\n... | [
7,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001591762_python.txt |
Q:
How to install 64-bit Python on Solaris?
I am trying to install Python 2.6 on Solaris by building the source on Solaris machine. I installed one this way and it appears that it is 32-bit. I downloaded some source tar ball as Linux or Unix for this purpose. Everything works well but I need 64-bit Python.
I looked ... | How to install 64-bit Python on Solaris? | I am trying to install Python 2.6 on Solaris by building the source on Solaris machine. I installed one this way and it appears that it is 32-bit. I downloaded some source tar ball as Linux or Unix for this purpose. Everything works well but I need 64-bit Python.
I looked up the Python download site and there is no se... | [
"It's currently an acknowledged bug that Solaris 64-bit support is suboptimal, but that bug report looks to contain some flags that you might want to use. See also this mailing list posting.\n",
"I would strongly suggest seeing if you can get away with the 32 bit version of Python. If your new to compiling stuff... | [
3,
3
] | [] | [] | [
"python",
"solaris"
] | stackoverflow_0001396678_python_solaris.txt |
Q:
Decoding Mac OS text in Python
I'm writing some code to parse RTF documents, and need to handle the various codepages they can use. Python comes with decoders for all the necessary Windows codepages, but I'm not sure how to handle the Mac ones:
# 77: "10000", # Mac Roman
# 78: "10001", # Mac Shift Jis
# 79: "10003... | Decoding Mac OS text in Python | I'm writing some code to parse RTF documents, and need to handle the various codepages they can use. Python comes with decoders for all the necessary Windows codepages, but I'm not sure how to handle the Mac ones:
# 77: "10000", # Mac Roman
# 78: "10001", # Mac Shift Jis
# 79: "10003", # Mac Hangul
# 80: "10008", # Mac... | [
"You can use the python codecs for these that are known by their names 'mac-roman', 'mac-turkish', etc.\n>>> 'foo'.decode('mac-turkish')\nu'foo'\n\nYou'll have to refer to them by their names, these numbers you've got in your question don't appear in the source files. For more information look at $pylib/encodings/m... | [
9,
3,
1
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0001592925_macos_python.txt |
Q:
How to use twistedweb with django on windows
I'm looking for a super easy way to deploy django application on windows.
Basically my plan is to set up any python web server with my app on it and the boundle everything together using py2exe into a single executable.
I've tried using cherrypy however the newest (3.1.... | How to use twistedweb with django on windows | I'm looking for a super easy way to deploy django application on windows.
Basically my plan is to set up any python web server with my app on it and the boundle everything together using py2exe into a single executable.
I've tried using cherrypy however the newest (3.1.2) server doesn't work with Windows XP with Nod32 ... | [
"I would rather suggest Portable LightTPD (i.e. the .zip) and Portable Python. It is very easy to set up LightTPD for FastCGI, and very easy to set up sqlite and FastCGI with Django in the Portable Python distro. This is probably your fastest and simplest route to getting an easily-deployable Django app going. I... | [
0,
0
] | [] | [] | [
"django",
"python",
"twisted",
"windows"
] | stackoverflow_0001590651_django_python_twisted_windows.txt |
Q:
Python Queue get()/task_done() issue
My consumer side of the queue:
m = queue.get()
queue.task_done()
<rest of the program>
Questions:
Does task_done() effectively pops m off the queue and release whatever locks the consumer has on the queue?
I need to use m during the rest of the program. Is it safe, or do I n... | Python Queue get()/task_done() issue | My consumer side of the queue:
m = queue.get()
queue.task_done()
<rest of the program>
Questions:
Does task_done() effectively pops m off the queue and release whatever locks the consumer has on the queue?
I need to use m during the rest of the program. Is it safe, or do I need to copy it before I call task_done() o... | [
"No, queue.get() pops the item off the queue. After you do that, you can do whatever you want with it, as long as the producer works like it should and doesn't touch it anymore. queue.task_done() is called only to notify the queue that you are done with something (it doesn't even know about the specific item, it ju... | [
58
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0001593299_multithreading_python_queue.txt |
Q:
How to get all related/parent instances from set of child instances without looping through latter set
Please regard the following Django models:
ParentModel(models.Model):
...
ChildModel(models.Model):
parent = models.ForeignKey(ParentModel, related_name='children')
Let's assume there is certain subset... | How to get all related/parent instances from set of child instances without looping through latter set | Please regard the following Django models:
ParentModel(models.Model):
...
ChildModel(models.Model):
parent = models.ForeignKey(ParentModel, related_name='children')
Let's assume there is certain subset of all children in the database available as a queryset (call it the 1st set).
Now, I'd like to gain acces... | [
"Assuming you have a queryset called children:\nParentModel.objects.filter(children__in=children)\n\n"
] | [
4
] | [] | [] | [
"django",
"django_views",
"foreign_key_relationship",
"python"
] | stackoverflow_0001593306_django_django_views_foreign_key_relationship_python.txt |
Q:
How do I check if the python debug option is set from within a script
If I'm in debug mode, I want to do other stuff than when I'm not.
if DEBUG:
STORED_DATA_FILE = os.path.join(TEMP_DIR, 'store.dat')
LOG_LEVEL = logging.DEBUG
print "debug mode"
else:
STORED_DATA_FILE = os.path.join(SCRIPT_PATH, 's... | How do I check if the python debug option is set from within a script | If I'm in debug mode, I want to do other stuff than when I'm not.
if DEBUG:
STORED_DATA_FILE = os.path.join(TEMP_DIR, 'store.dat')
LOG_LEVEL = logging.DEBUG
print "debug mode"
else:
STORED_DATA_FILE = os.path.join(SCRIPT_PATH, 'store.dat')
LOG_LEVEL = logging.INFO
print "not debug mode"
then:
p... | [
"you can use python -O with the __debug__ variable\nwhere -O means optimise. so __debug__ is false\n-d turns on debugging for the parser, which is not what you want\n",
"Parser debug mode is enabled with -d commandline option or PYTHONDEBUG environment variable and starting from python 2.6 is reflected in sys.fla... | [
14,
7
] | [] | [] | [
"python",
"script_debugging"
] | stackoverflow_0001593274_python_script_debugging.txt |
Q:
Constructors in Python
I need help in writing code for a Python constructor method.
This constructor method would take the following three parameters:
x, y, angle
What is an example of this?
A:
class MyClass(object):
def __init__(self, x, y, angle):
self.x = x
self.y = y
self.angle = angle
Th... | Constructors in Python | I need help in writing code for a Python constructor method.
This constructor method would take the following three parameters:
x, y, angle
What is an example of this?
| [
"class MyClass(object):\n def __init__(self, x, y, angle):\n self.x = x\n self.y = y\n self.angle = angle\n\nThe constructor is always written as a function called __init__(). It must always take as its first argument a reference to the instance being constructed. This is typically called self. The rest o... | [
19,
6,
2
] | [
"\nclass MyClass(SuperClass):\n def __init__(self, *args, **kwargs):\n super(MyClass, self).__init__(*args, **kwargs)\n # do initialization\n\n"
] | [
-4
] | [
"constructor",
"python"
] | stackoverflow_0001593441_constructor_python.txt |
Q:
getpos() coding
just wanted to know how to write the getpos() command which must return an (x,y) tuple of the current position.
does it start like this:
def getpos(x 100, y 100)
not sure need help
A:
This is a bit underspecified, but this might work:
def getpos(self):
return (self.x, self.y)
This is how to r... | getpos() coding | just wanted to know how to write the getpos() command which must return an (x,y) tuple of the current position.
does it start like this:
def getpos(x 100, y 100)
not sure need help
| [
"This is a bit underspecified, but this might work:\ndef getpos(self):\n return (self.x, self.y)\n\nThis is how to return a tuple, from values assumed to be instance variables.\n",
"In Python you can't force a return type on a function from its header. The return type can change from one call to another.\nWhen y... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001593599_python.txt |
Q:
String replacing in a file by given position
I have a file opened in 'ab+' mode.
What I need to do is replacing some bytes in the file with another string's bytes such that:
FILE:
thisissomethingasperfectlygood.
string:
01234
So, for example, I seek for the position (4, 0) and I want to write 01234 in the place ... | String replacing in a file by given position | I have a file opened in 'ab+' mode.
What I need to do is replacing some bytes in the file with another string's bytes such that:
FILE:
thisissomethingasperfectlygood.
string:
01234
So, for example, I seek for the position (4, 0) and I want to write 01234 in the place of "issom" in the file. Last appearance would be:
... | [
"You could mmap() your file and then use slice notation to update specific byte ranges in the file. The example here should help.\n",
"You can use mmap for that\nimport os,mmap\nf=os.open(\"afile\",os.O_RDWR)\nm=mmap.mmap(f,0)\nm[4:9]=\"01234\"\nos.close(f)\n\n"
] | [
2,
2
] | [] | [] | [
"python",
"replace",
"seek",
"string"
] | stackoverflow_0001593576_python_replace_seek_string.txt |
Q:
python constructing functions on the fly
I have several little functions f1, f2, f3 and a function f.
I want f to be a "container" to f1, f2, f3: to do the some of operations f1, f2, f3, depending on the program configuration (for example f1 and f2 or f1 and f3 or all the three) and nothing more.
I see two simple ... | python constructing functions on the fly | I have several little functions f1, f2, f3 and a function f.
I want f to be a "container" to f1, f2, f3: to do the some of operations f1, f2, f3, depending on the program configuration (for example f1 and f2 or f1 and f3 or all the three) and nothing more.
I see two simple solutions: first to add some if's in the funct... | [
"If f1, f2 etc. are functions with side effects, than you should use an explicit for loop (no fancy map solution). Perhaps you want something like this?\nconfigurations = {\n 'config_1': (f1, f2, f3),\n 'config_2': (f1, f2),\n}\n\ndef f(config='config_1'):\n for op in configurations[config]:\n op()\n\nI... | [
3,
3,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001593572_python.txt |
Q:
Python: Get name of instantiating class?
Example:
class Class1:
def __init__(self):
self.x = Class2('Woo!')
class Class2:
def __init__(self, word):
print word
meow = Class1()
How do I derive the class name that created the self.x instance? In other words, if I was given the instance self... | Python: Get name of instantiating class? | Example:
class Class1:
def __init__(self):
self.x = Class2('Woo!')
class Class2:
def __init__(self, word):
print word
meow = Class1()
How do I derive the class name that created the self.x instance? In other words, if I was given the instance self.x, how do I get the name 'Class1'? Using self... | [
"You can't, unless you pass an instance of the 'creator' to the Class2() constructor. e.g.\nclass Class1(object):\n def __init__(self, *args, **kw):\n self.x = Class2(\"Woo!\", self)\n\nclass Class2(object):\n def __init__(self, word, creator, *args, **kw):\n self._creator = creator\n pri... | [
6,
1,
0
] | [] | [] | [
"class",
"instance",
"python"
] | stackoverflow_0001593632_class_instance_python.txt |
Q:
forward and back command
wanted to know how to write a forward and back command in a superclass not sure but i gave it a try dont know if its right or wrong some help plz
def forward(self):
return (self.100)
def back(self):
return (self.50)
A:
def forward(self):
self.position += self.distance
return (se... | forward and back command | wanted to know how to write a forward and back command in a superclass not sure but i gave it a try dont know if its right or wrong some help plz
def forward(self):
return (self.100)
def back(self):
return (self.50)
| [
"def forward(self):\n self.position += self.distance\n return (self.position)\n\ndef back(self):\n self.position -= self.distance\n return (self.position)\n\nEDIT:\nI assumed you are doing something like progress bar of install app, where some operation advances progress (copying files), and if user cancels ins... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001593818_python.txt |
Q:
SVN hook environment issues with Python script
I am experiencing issues with my SVN post-commit hook and the fact that it is executed with an empty environment. Everything was working fine till about two weeks ago when my systems administrator upgraded a few things on the server.
My post-commit hook executes a Py... | SVN hook environment issues with Python script | I am experiencing issues with my SVN post-commit hook and the fact that it is executed with an empty environment. Everything was working fine till about two weeks ago when my systems administrator upgraded a few things on the server.
My post-commit hook executes a Python script that uses a SVN module to email informat... | [
"Your system administrator might have forgotten to execute this command.\necho /usr/local/lib/svn-python \\\n> /usr/local/lib/python2.x/site-packages/subversion.pth\n\nThis is written in subversion/bindings/swig/INSTALL in the source distribution.\n",
"Got it! I missed the export in my post-commit hook script!\n... | [
1,
1
] | [] | [] | [
"python",
"svn"
] | stackoverflow_0001576784_python_svn.txt |
Q:
Get the request uri outside of a RequestHandler in Google App Engine (Python)
So, within a webapp.RequestHandler subclass I would use self.request.uri to get the request URI. But, I can't access this outside of a RequestHandler and so no go. Any ideas?
I'm running Python and I'm new at it as well as GAE.
A:
You ... | Get the request uri outside of a RequestHandler in Google App Engine (Python) | So, within a webapp.RequestHandler subclass I would use self.request.uri to get the request URI. But, I can't access this outside of a RequestHandler and so no go. Any ideas?
I'm running Python and I'm new at it as well as GAE.
| [
"You should generally be doing everything within some sort of RequestHandler or the equivalent in your non-WebApp framework. However, if you really insist on being stuck in the early 1990s and writing plain CGI scripts, the environment variables SERVER_NAME and PATH_INFO may be what you want; see a CGI reference f... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001593483_google_app_engine_python.txt |
Q:
angles commands in superclass
how do you write a command that turn left or right at an angle in a superclass is it like this:
def left(self):
self.position += self.angle
return (self.position)
is it the same as the forward and back command
A:
It looks like you are interested by something like the logo turtl... | angles commands in superclass | how do you write a command that turn left or right at an angle in a superclass is it like this:
def left(self):
self.position += self.angle
return (self.position)
is it the same as the forward and back command
| [
"It looks like you are interested by something like the logo turtle. Look at http://docs.python.org/library/turtle.html\nIf so, the left function doesn't change the position of the turtle but its orientation.\ndef left(self, angle):\n self.angle -= angle*2*math.pi/360\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001594090_python.txt |
Q:
Permissions for a site only
I have a multilingual Django project. Every language is a different subdomain.
So we've decided to use the "sites" application and to create one different site for every language.
On that project, I also have a "pages" application, which is quite similar to a CMS. The user can create pa... | Permissions for a site only | I have a multilingual Django project. Every language is a different subdomain.
So we've decided to use the "sites" application and to create one different site for every language.
On that project, I also have a "pages" application, which is quite similar to a CMS. The user can create pages with content and they'll be d... | [
"You could create a Group (http://docs.djangoproject.com/en/dev/topics/auth/)\nper site / language and add the users to the groups accordingly.\nThen, you can check if the request.user.groups belongs to the group.\n(You can do this with a decorator:\ndef group_required(func):\n def _decorator(request, *args, **k... | [
3,
1,
0
] | [] | [] | [
"django",
"permissions",
"python"
] | stackoverflow_0001593423_django_permissions_python.txt |
Q:
Including non-Python files with setup.py
How do I make setup.py include a file that isn't part of the code? (Specifically, it's a license file, but it could be any other thing.)
A:
http://docs.python.org/distutils/setupscript.html#installing-additional-files is all you should need.
Since you mentioned a license ... | Including non-Python files with setup.py | How do I make setup.py include a file that isn't part of the code? (Specifically, it's a license file, but it could be any other thing.)
| [
"http://docs.python.org/distutils/setupscript.html#installing-additional-files is all you should need.\nSince you mentioned a license file, you can include additional meta-data (such as a license) this way.\n"
] | [
4
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0001594838_distutils_python.txt |
Q:
Why do simple math operations on floating point return unexpected (inaccurate) results in VB.Net and Python?
x = 4.2 - 0.1
vb.net gives 4.1000000000000005
python gives 4.1000000000000005
Excel gives 4.1
Google calc gives 4.1
What is the reason this happens?
A:
Float/double precision.
You must remember that i... | Why do simple math operations on floating point return unexpected (inaccurate) results in VB.Net and Python? | x = 4.2 - 0.1
vb.net gives 4.1000000000000005
python gives 4.1000000000000005
Excel gives 4.1
Google calc gives 4.1
What is the reason this happens?
| [
"Float/double precision.\nYou must remember that in binary, 4.1 = 4 + 1/10. 1/10 is an infinitely repeating sum in binary, much like 1/9 is an infinite sum in decimal.\n",
">>> x = 4.2 - 0.1 \n>>> x\n4.1000000000000005\n\n>>>>print(x)\n4.1\n\nThis happens because of how numbers are stored internally.\nComputers r... | [
15,
10,
4,
2
] | [] | [] | [
"floating_point",
"python",
"vb.net"
] | stackoverflow_0001594985_floating_point_python_vb.net.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.