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:
Python code simplification? One line, add all in list
I'm making my way through project Euler and I'm trying to write the most concise code I can. I know it's possible, so how could I simplify the following code. Preferably, I would want it to be one line and not use the int->string->int conversion.
Question: Wh... | Python code simplification? One line, add all in list | I'm making my way through project Euler and I'm trying to write the most concise code I can. I know it's possible, so how could I simplify the following code. Preferably, I would want it to be one line and not use the int->string->int conversion.
Question: What is the sum of the digits of the number 21000?
My answer:... | [
"sum(int(n) for n in str(2**1000))\n\n",
"Not a one-liner, but a cleaner-looking generator solution, also avoiding the int->string->int conversion:\ndef asDigits(n):\n while n:\n n,d = divmod(n,10)\n yield d\n\nprint sum(asDigits(2**1000))\n\nGives 1366.\nInterestingly, the sum of the digits in 2... | [
16,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0003145379_python.txt |
Q:
Which is faster to learn: Django (Python) or Ruby on Rails (Ruby)?
I have done the front-end of my design, but I have no experience in web programming. Would like to pick up a language asap so that I can deploy the product. Which is faster to pick up between the two? I know there is always debate in which is bette... | Which is faster to learn: Django (Python) or Ruby on Rails (Ruby)? | I have done the front-end of my design, but I have no experience in web programming. Would like to pick up a language asap so that I can deploy the product. Which is faster to pick up between the two? I know there is always debate in which is better. I think either one serves well for me, but I want to know which one i... | [
"There is no good answer to this without more background on you, and even then it is going to be nothing more than a guess.\nEither language can be learned depending on your own experiences. Both have similar abilities with a natural language type syntax. The two frameworks you list are similar as well.\nThe real w... | [
7,
5,
2
] | [] | [] | [
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0003145879_django_python_ruby_ruby_on_rails.txt |
Q:
Reisze wx.Dialog horizontally only
Is there a way to allow a custom wx.Dialog to be resized in the horizontal direction only? I've tried using GetSize() and then setting the min and max height of the window using SetSizeHints(), but for some reason it always allows the window to be resized just a little, and it lo... | Reisze wx.Dialog horizontally only | Is there a way to allow a custom wx.Dialog to be resized in the horizontal direction only? I've tried using GetSize() and then setting the min and max height of the window using SetSizeHints(), but for some reason it always allows the window to be resized just a little, and it looks rather tacky. The only other alterna... | [
"If you don't want the height to change, why would it be a bad idea to set min and max height to the same value (the one you want to force)? You can of course get the system estimate of the \"best value\" with GetBetSize or related methods. Though I find the fact that setting the size hints doesn't have the same ... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003145978_python_wxpython.txt |
Q:
IPython with own scope?
I encountered a problem with the scope variables have when IPython is invoked at the end of a python script.
All functions I call in the script itself can modify variables, which will subsequently be used by other functions.
If I call the same functions in ipython, the scripted ones can acc... | IPython with own scope? | I encountered a problem with the scope variables have when IPython is invoked at the end of a python script.
All functions I call in the script itself can modify variables, which will subsequently be used by other functions.
If I call the same functions in ipython, the scripted ones can access the changed variables but... | [
"You could create a class with a static method (decorator: @staticmethod) that returns a singleton instance of that class. That object can contain any number of members that function as globals.\nclass Globals:\n __master = None\n somevar = 1\n othervar = 2\n\n @staticmethod\n def get_master():\n ... | [
0
] | [] | [] | [
"ipython",
"namespaces",
"python",
"scope"
] | stackoverflow_0003142721_ipython_namespaces_python_scope.txt |
Q:
Possible to return instantiator in Python?
class Parent():
def __init__(self):
self.child = Child()
class Child():
def __init__(self):
# get Parent instance
self.parent = self.Instantiator()
I know this isn't proper encapsulation but for interest's sake...
Given a "Parent" class that instantiates... | Possible to return instantiator in Python? | class Parent():
def __init__(self):
self.child = Child()
class Child():
def __init__(self):
# get Parent instance
self.parent = self.Instantiator()
I know this isn't proper encapsulation but for interest's sake...
Given a "Parent" class that instantiates a "Child" object, is it possible from within Ch... | [
"To answer the question, no, there's no way1 the child instance knows about any classes which contain references to it. The common2 way to handle this is:\nclass Parent(object):\n def __init__(self):\n self.child = Child()\n self.child._parent = self\n\n1 Of course, this isn't strictly true. As a... | [
7,
2,
1,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003145652_oop_python.txt |
Q:
How are closures implemented?
"Learning Python, 4th Ed." mentions that:
the enclosing scope variable is looked up when the nested functions
are later called..
However, I thought that when a function exits, all of its local references disappear.
def makeActions():
acts = []
for i in range(5): # Tries to r... | How are closures implemented? | "Learning Python, 4th Ed." mentions that:
the enclosing scope variable is looked up when the nested functions
are later called..
However, I thought that when a function exits, all of its local references disappear.
def makeActions():
acts = []
for i in range(5): # Tries to remember each i
acts.append(... | [
"I think it's pretty obvious what happens when you think of i as a name not some sort of value. Your lambda function does something like \"take x: look up the value of i, calculate i**x\" ... so when you actually run the function, it looks up i just then so i is 4.\nYou can also use the current number, but you have... | [
10,
8,
1,
1,
0
] | [] | [] | [
"closures",
"python"
] | stackoverflow_0003145893_closures_python.txt |
Q:
concat multiple block in jinja2?
I use jinja2 for my template engine in python.
i would like to join content of multiple block and would like to render it at the end of the template, just before tag. { they are various JavaScript snippets throughout the code in multiple template which i would like to move to the... | concat multiple block in jinja2? | I use jinja2 for my template engine in python.
i would like to join content of multiple block and would like to render it at the end of the template, just before tag. { they are various JavaScript snippets throughout the code in multiple template which i would like to move to the end of the file, how do i do it ? }
... | [
"I assume that by multiple children, you mean that there are templates inheriting from templates inheriting from templates ... inheriting from the base template. If that's the case, you need to define the same javascript block in each template and call super() in all of the children, in addition to adding more Jav... | [
22
] | [] | [] | [
"jinja2",
"python",
"templates"
] | stackoverflow_0003127502_jinja2_python_templates.txt |
Q:
Automagically expanding a Python list with formatted output
Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.
... | Automagically expanding a Python list with formatted output | Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.
For instance, in the code below, I'd like to have the numeric val... | [
"try:\n\",\".join( map(str, record_ids) )\n\n\",\".join( list_of_strings ) joins a list of string by separating them with commas\nif you have a list of numbers, map( str, list ) will convert it to a list of strings\n",
"I do stuff like this (to ensure I'm using bindings):\nsqlStmt=(\"UPDATE apps.sometable SET las... | [
17,
3,
2,
0
] | [
"Alternitavely, using replace:\nsqlStmt=\"UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in \" +\n record_ids.__str__().replace('[','(').replace(']',')')\n\n"
] | [
-1
] | [
"list",
"mysql",
"python"
] | stackoverflow_0000315672_list_mysql_python.txt |
Q:
How to sort a list of inter-linked tuples?
lst = [(u'course', u'session'), (u'instructor', u'session'), (u'session', u'trainee'), (u'person', u'trainee'), (u'person', u'instructor'), (u'course', u'instructor')]
I've above list of tuple, I need to sort it with following logic....
each tuple's 2nd element is depend... | How to sort a list of inter-linked tuples? | lst = [(u'course', u'session'), (u'instructor', u'session'), (u'session', u'trainee'), (u'person', u'trainee'), (u'person', u'instructor'), (u'course', u'instructor')]
I've above list of tuple, I need to sort it with following logic....
each tuple's 2nd element is dependent on 1st element, e.g. (course, session) -> se... | [
"You're looking for what's called a topological sort. The wikipedia page shows the classic Kahn and depth-first-search algorithms for it; Python examples are here (a bit dated, but should still run fine), on pypi (stable and reusable -- you can also read the code online here) and here (Tarjan's algorithm, that kin... | [
5,
4
] | [] | [] | [
"list",
"python",
"sorting",
"topological_sort",
"tuples"
] | stackoverflow_0003146700_list_python_sorting_topological_sort_tuples.txt |
Q:
Django - managing multiple pages with multiple fields
I am using Django for developing a website and I want to allow my staff to be able to add/edit/delete pages with multiple text fields. I am planning to use Django's admin framework for this as the staff is a non-technical one.But I have no clue on how to go abo... | Django - managing multiple pages with multiple fields | I am using Django for developing a website and I want to allow my staff to be able to add/edit/delete pages with multiple text fields. I am planning to use Django's admin framework for this as the staff is a non-technical one.But I have no clue on how to go about doing this so that people can login and edit the content... | [
"Follow the Django tutorial, replacing the concept of Polls with Pages, and Choices with Content blocks and you'll be most of the way there (Django's built in Admin will allow you to edit these models).\nFor a more advanced CMS based on Django take a look at either Django CMS or FeinCMS.\n"
] | [
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003146904_django_django_admin_python.txt |
Q:
Convert array to string
I have a reeeealy huge string, which looks like ['elem1','elem2',(...)] and contains about 100,000(!) elements.
What is the best method to change it back to a list?
A:
eval("['elem1','elem2']") gives you back list ['elem1','elem2']
If you had string looking like this ["elem1","elem2",(...... | Convert array to string | I have a reeeealy huge string, which looks like ['elem1','elem2',(...)] and contains about 100,000(!) elements.
What is the best method to change it back to a list?
| [
"eval(\"['elem1','elem2']\") gives you back list ['elem1','elem2']\nIf you had string looking like this [\"elem1\",\"elem2\",(...)] you might use json.read() (in python 2.5 or earlier) or json.loads() (in python 2.6) from json module to load it safely.\n",
"One possible solution is:\ninput = \"['elem1', 'elem2' ]... | [
3,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003147570_list_python.txt |
Q:
How do you set a background image in a frame with pygtk?
I mean like a frame with some widgets which overlap the background (the image), basically how do you partially overlap/clobber an Image?
Like a background in a Firefox theme, for instance.
A:
I think that this is a FAQ.
| How do you set a background image in a frame with pygtk? | I mean like a frame with some widgets which overlap the background (the image), basically how do you partially overlap/clobber an Image?
Like a background in a Firefox theme, for instance.
| [
"I think that this is a FAQ.\n"
] | [
2
] | [] | [] | [
"pygtk",
"python",
"user_interface"
] | stackoverflow_0003147020_pygtk_python_user_interface.txt |
Q:
Command not defined in Python - Real basics, but confused!
I have written this short script (which I've stripped away some minor detail for size) and I'm getting a very simple error, yet, I don't understand why! I'm very new to Python, so maybe someone can explain the issue and why it's not working?
The error seem... | Command not defined in Python - Real basics, but confused! | I have written this short script (which I've stripped away some minor detail for size) and I'm getting a very simple error, yet, I don't understand why! I'm very new to Python, so maybe someone can explain the issue and why it's not working?
The error seems to fall when I wish to print the full custom serial write stri... | [
"It could be because you're missing the self argument:\n def send_command(self, commands):\n\n",
"you've got an indentation error in def send_command(commands):\nand your first parameter should be \"self\" :\nclass ArialApp(object):\n\n<snap>\n\n def send_command(self, commands):\n ser.write(\"#\" + m... | [
2,
1,
1
] | [] | [] | [
"eclipse",
"glade",
"pydev",
"pygtk",
"python"
] | stackoverflow_0003147786_eclipse_glade_pydev_pygtk_python.txt |
Q:
PyArg_ParseTuple causing segmentation fault
I'm trying to call a c function from my extension and have narrowed the problem down to this test case.
#import "Python.h"
...
// Called from python with test_method(0, 0, 'TEST')
static PyObject*
test_method(PyObject *args)
{
int ok, x, y, size;
const char *s... | PyArg_ParseTuple causing segmentation fault | I'm trying to call a c function from my extension and have narrowed the problem down to this test case.
#import "Python.h"
...
// Called from python with test_method(0, 0, 'TEST')
static PyObject*
test_method(PyObject *args)
{
int ok, x, y, size;
const char *s;
// this causes Segmentation fault
//ok... | [
"Hmmm. I think the signature of your method should be this:\nstatic PyObject* test_method(PyObject* self, PyObject* args)\n\nIf you are invoking your test_method as a bound method (i.e. a method of some object instance), self will be the object itself. If test_method is a module function, self is the pointer passed... | [
1
] | [] | [] | [
"argument_passing",
"c",
"python",
"python_c_extension"
] | stackoverflow_0003147869_argument_passing_c_python_python_c_extension.txt |
Q:
How to convert comma-separated key value pairs into a dictionary using lambda functions
I'm having a little problem figuring out lamba functions. Could someone show me how to split the following string into a dictionary using lambda functions?
fname:John,lname:doe,mname:dunno,city:Florida
Thanks
A:
There is not... | How to convert comma-separated key value pairs into a dictionary using lambda functions | I'm having a little problem figuring out lamba functions. Could someone show me how to split the following string into a dictionary using lambda functions?
fname:John,lname:doe,mname:dunno,city:Florida
Thanks
| [
"There is not really a need for a lambda here.\ns = \"fname:John,lname:doe,mname:dunno,city:Florida\"\nsd = dict(u.split(\":\") for u in s.split(\",\"))\n\n",
"You don't need lambda functions to do this:\n>>> s = \"fname:John,lname:doe,mname:dunno,city:Florida\"\n>>> dict(item.split(\":\") for item in s.split(\",... | [
17,
2,
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0003147554_lambda_python.txt |
Q:
Configuration inheritance mechanism
I have the following structure:
config
|-- groups
|-- rootgroup
|-- group1 (includes rootgroup)
|-- group2 (includes group1)
|-- group3 (includes rootgroup)
|-- users
|-- Fred (includes group3 and group2)
So inheritance tree for Fred will look like:
... | Configuration inheritance mechanism | I have the following structure:
config
|-- groups
|-- rootgroup
|-- group1 (includes rootgroup)
|-- group2 (includes group1)
|-- group3 (includes rootgroup)
|-- users
|-- Fred (includes group3 and group2)
So inheritance tree for Fred will look like:
_Fred_
v v
group2 group3
v ... | [
"Well after reading about directed acyclic graphs (DAG) I came up with following solution:\ndef getNodeDepsTree(self, node, back_path=None):\n \"\"\"Return whole dependency tree for given node\"\"\"\n # List of current node dependencies\n node_deps = []\n\n if not back_path:\n back_path = []\n\n ... | [
0
] | [] | [] | [
"inheritance",
"python",
"recursion"
] | stackoverflow_0003139915_inheritance_python_recursion.txt |
Q:
approaching django model fields through a field name mapping
Django newbie here,
I have several types of models, in each of them the fields have different names (e.g. first_name, forename, prenom) and I want each of the models to contain a mapping so that I can easily approach each of the fields using one conventi... | approaching django model fields through a field name mapping | Django newbie here,
I have several types of models, in each of them the fields have different names (e.g. first_name, forename, prenom) and I want each of the models to contain a mapping so that I can easily approach each of the fields using one conventional name (e.g. first_name for all of the field names). what's a g... | [
"I think the best way would be to use conventional names in your models and provide only one obvious way to access it. If you don't wan't to change the database columns too, you can use the db_column option. Example:\nclass Person(models.Model):\n first_name = models.CharField(max_length=255, db_column='prenom')... | [
4,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003148027_django_django_models_python.txt |
Q:
Is it possible to access the source code of a python script passed to python on standard in?
This is a bit of a random question that is more out of curiosity than any specific need.
Is it possible to write some python code that will print some stuff out, including the source code itself, without having the python ... | Is it possible to access the source code of a python script passed to python on standard in? | This is a bit of a random question that is more out of curiosity than any specific need.
Is it possible to write some python code that will print some stuff out, including the source code itself, without having the python code stored in a file? For example, doing something like this at the Bash prompt:
$ echo '
> prin... | [
"That's the closest I'm getting:\necho 'import __main__,inspect;print inspect.getsource(__main__)' | python\n\nwhich fails... In any case, the original code is eaten up (read from stdin) by the interpreter at startup. At most you may be able to get to the compiled code, again through the __main__ module.\nUpdate:\... | [
3,
2,
1,
1
] | [] | [] | [
"python",
"quine",
"stdin"
] | stackoverflow_0003147823_python_quine_stdin.txt |
Q:
HTML generation in Python
What's the easiest way to quickly create some simple HTML in Python? All I've found so far are complex templating systems or classes for HTML generation with APIs that seem much heavier than what I need.
I could just do it myself by sticking strings together but I thought there might be a... | HTML generation in Python | What's the easiest way to quickly create some simple HTML in Python? All I've found so far are complex templating systems or classes for HTML generation with APIs that seem much heavier than what I need.
I could just do it myself by sticking strings together but I thought there might be a library that could save me a l... | [
"quixote is an old-ish but still fascinating framework -- it basically \"embeds HTML in Python\" (rather than vice versa, as all popular templating systems do).\nOne simple example from the overview:\ndef format_row [html] (head, value):\n \"<tr valign=top align=left>\\n\"\n \" <th align=left>%s</th>\\n\" % ... | [
2,
1,
1,
0
] | [] | [] | [
"html_generation",
"python"
] | stackoverflow_0003145935_html_generation_python.txt |
Q:
Inserting records into Sqlite using Python parameter substitution where some fields are blank
I am running this sort of query:
insert into mytable (id, col1, col2)
values (:ID, :COL1, :COL2)
In Python, a dictionary of this form can be used in conjuction with the query above for parameter substitution:
d = { 'ID' ... | Inserting records into Sqlite using Python parameter substitution where some fields are blank | I am running this sort of query:
insert into mytable (id, col1, col2)
values (:ID, :COL1, :COL2)
In Python, a dictionary of this form can be used in conjuction with the query above for parameter substitution:
d = { 'ID' : 0, 'COL1' : 'hi', 'COL2' : 'there' }
cursor.execute(sql_insert, d)
But in the real problem, ther... | [
"I haven't checked that this works, but I think it should:\nfrom collections import defaultdict\nd = { 'ID' : 0, 'COL1' : 'hi' }\ncursor.execute(sql_insert, defaultdict(str, d))\n\ndefaultdict is a specialised dictionary where any missing keys generate a new value instead of throwing a KeyError.\nOf course this onl... | [
7,
0,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003148315_python_sqlite.txt |
Q:
How to pickle a empty file?
I want to pickle a file that sometime's is empty. Right now its empty, but my idea is that its going to grow over time.
How do i check if a file is "pickable" since it seems that you can not pickle a empty file?
A:
Simply use a try/except block.
def example():
try:
return pickle... | How to pickle a empty file? | I want to pickle a file that sometime's is empty. Right now its empty, but my idea is that its going to grow over time.
How do i check if a file is "pickable" since it seems that you can not pickle a empty file?
| [
"Simply use a try/except block.\ndef example():\n try:\n return pickle.loads(\"\")\n except EOFError:\n return None\n\nIt's easier to ask forgiveness than permission. :)\n",
"Pickle is considered unsafe. Try Cerealizer instead. It might incidentally solve your empty file problem.\n"
] | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0003148656_python.txt |
Q:
Are Interfaces just "Syntactic Sugar"?
I've been playing mostly with PHP and Python.
I've been reading about Interfaces in OO programming and can't see an advantage in using it.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
Why do I need to create an Inte... | Are Interfaces just "Syntactic Sugar"? | I've been playing mostly with PHP and Python.
I've been reading about Interfaces in OO programming and can't see an advantage in using it.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
Why do I need to create an Interface "with no implementation" - mainly a "c... | [
"First, and foremost, try not to compare and contrast between Python and Java. They are different languages, with different semantics. Compare and contrast will only lead to confusing questions like this where you're trying to compare something Python doesn't use with something Java requires. \nIt's a lot like c... | [
13,
12,
5,
4,
3,
1,
1,
1,
0
] | [] | [] | [
"interface",
"oop",
"php",
"python"
] | stackoverflow_0003134531_interface_oop_php_python.txt |
Q:
How do I get the class of a ManyToMany field in django models?
I have some fields in a model that are ManyToMany, I want the ManyToMany class itself, when I only have the field name. Is there any way I can retrieve it?
A:
If model_obj were an instance of the Model class that defines a ManyToManyField named foom2... | How do I get the class of a ManyToMany field in django models? | I have some fields in a model that are ManyToMany, I want the ManyToMany class itself, when I only have the field name. Is there any way I can retrieve it?
| [
"If model_obj were an instance of the Model class that defines a ManyToManyField named foom2m, then you could do this:\nrelated_model = model_obj.__class_.foom2m.field.rel.to\n\n"
] | [
1
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0003148879_django_models_python.txt |
Q:
How to set up Atana Studio 3 Themes in Pydev
I've installed the Aptana Studio 3 preview and noticed it has support for themes (such as a bespin style or Ruby envy) and I'd love to use the Bespin one in Pydev but so far I've had no luck getting it to work, anyone have a clue as to how to get it to work?
Video show... | How to set up Atana Studio 3 Themes in Pydev | I've installed the Aptana Studio 3 preview and noticed it has support for themes (such as a bespin style or Ruby envy) and I'd love to use the Bespin one in Pydev but so far I've had no luck getting it to work, anyone have a clue as to how to get it to work?
Video showing the themes in action.
| [
"\nWindow->Preferences\nAptana->Themes\n\n"
] | [
1
] | [] | [] | [
"aptana",
"pydev",
"python",
"themes"
] | stackoverflow_0002880193_aptana_pydev_python_themes.txt |
Q:
One-to-one relationships between entities in the Python Google App Engine
Is to possible to create one-to-one relations in the Python version of Google App Engine? I know it is possible in Java.
A:
Sure - just use a ReferenceProperty that references an entity not referenced by anything else.
| One-to-one relationships between entities in the Python Google App Engine | Is to possible to create one-to-one relations in the Python version of Google App Engine? I know it is possible in Java.
| [
"Sure - just use a ReferenceProperty that references an entity not referenced by anything else.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003148719_google_app_engine_python.txt |
Q:
Manipulating the db with SQL Server 2005 - Django
I'm trying to accomplish the following:
Grab the db schema
Grab any constraints*
Alter tables
Add/Drop tables
I'm currently using pyodbc backend for Django.
I would like to perform all these tasks within a view file.
I'm using the following in order to grab fiel... | Manipulating the db with SQL Server 2005 - Django | I'm trying to accomplish the following:
Grab the db schema
Grab any constraints*
Alter tables
Add/Drop tables
I'm currently using pyodbc backend for Django.
I would like to perform all these tasks within a view file.
I'm using the following in order to grab fields of tables starting with 'core_':
SELECT table_name,... | [
"Try this by using a wildcard %\nSELECT table_name,ordinal_position,column_name,data_type, \nis_nullable,character_maximum_length FROM \ninformation_schema.COLUMNS WHERE table_name LIKE 'core_%' \nORDER BY ordinal_position \n\n"
] | [
3
] | [] | [] | [
"django",
"pyodbc",
"python",
"sql",
"sql_server"
] | stackoverflow_0003149396_django_pyodbc_python_sql_sql_server.txt |
Q:
Opening SSL URLs with Python
I'm using mechanize to navigate pages, it works pretty well.
Unfortunately I have a random error come up, by random I mean it occasionally appears.
URLError at /test/
urlopen error [Errno 1] _ssl.c:1325: error:140943FC:SSL routines:SSL3_READ_BYTES:sslv3 alert bad record mac>
I really... | Opening SSL URLs with Python | I'm using mechanize to navigate pages, it works pretty well.
Unfortunately I have a random error come up, by random I mean it occasionally appears.
URLError at /test/
urlopen error [Errno 1] _ssl.c:1325: error:140943FC:SSL routines:SSL3_READ_BYTES:sslv3 alert bad record mac>
I really need help on this one :)
any id... | [
"I had a similar error and found that PycURL works way better than urllib.\nDjango request XML file with SSL IO error\n"
] | [
1
] | [] | [] | [
"django",
"linux",
"mechanize",
"python",
"ssl"
] | stackoverflow_0002603119_django_linux_mechanize_python_ssl.txt |
Q:
Python Script Hangs, Potentially an Infinite Loop?
Once again working on Project Euler, this time my script just hangs there. I'm pretty sure I'm letting it run for long enough, and my hand-trace (as my father calls it) yields no issues. Where am I going wrong?
I'm only including the relevant portion of the code, ... | Python Script Hangs, Potentially an Infinite Loop? | Once again working on Project Euler, this time my script just hangs there. I'm pretty sure I'm letting it run for long enough, and my hand-trace (as my father calls it) yields no issues. Where am I going wrong?
I'm only including the relevant portion of the code, for once.
def main():
f, n = 0, 20
while f != 20... | [
"Python doesn't have increment (++). It's interpreted as +(+(a)). + is the unary plus operator, which basically does nothing. Use += 1\n",
"Here in your case 'f' value can never reach 20 and hence never exit\n1) At 1st break (when n=20 and x =3) it again set f=0.\nSimilarly for next loop also n get increased ... | [
3,
0
] | [] | [] | [
"infinite_loop",
"python"
] | stackoverflow_0003149496_infinite_loop_python.txt |
Q:
How to recognize current location in python?
My client has two offices in Germany and USA and a python program should recognize the office location. What will be the most elegant way to implement this? It only have to recognize the country. Furthermore it also could happens that there will be no permanent internet... | How to recognize current location in python? | My client has two offices in Germany and USA and a python program should recognize the office location. What will be the most elegant way to implement this? It only have to recognize the country. Furthermore it also could happens that there will be no permanent internet connection. The program works on windows but the ... | [
"AFAIK, there's no elegant solution. You can make educated guesses, but then, take this example: I unplug my laptop in Germany and go to the USA. I plug it in the US office - the regional settings are the same, the time zone didn't change, now what?\nThings from which you can make a guess:\n\nregional and language ... | [
5
] | [] | [] | [
"geolocation",
"python"
] | stackoverflow_0003149579_geolocation_python.txt |
Q:
How do I get the index of the largest list inside a list of lists using Python?
I am storing animation key frames from Cinema4D(using the awesome py4D) into a lists of lists:
props = [lx,ly,lz,sx,sy,sz,rx,ry,rz]
I printed out the keyframes for each property/track in an arbitrary animation and they are of differen... | How do I get the index of the largest list inside a list of lists using Python? | I am storing animation key frames from Cinema4D(using the awesome py4D) into a lists of lists:
props = [lx,ly,lz,sx,sy,sz,rx,ry,rz]
I printed out the keyframes for each property/track in an arbitrary animation and they are of different lengths:
track Position . X has 24 keys
track Position . Y has 24 keys
track Positi... | [
"max(enumerate(props), key = lambda tup: len(tup[1]))\n\nThis gives you a tuple containing (index, list) of the longest list in props.\n",
"You can use a generator expression:\nmaxLen = max(len(p) for p in props)\n\n"
] | [
26,
8
] | [] | [] | [
"blender",
"cinema_4d",
"list",
"python"
] | stackoverflow_0003149502_blender_cinema_4d_list_python.txt |
Q:
ctypes outputting unknown value at end of correct values
I have the following DLL ('arrayprint.dll') function that I want to use in Python via ctypes:
__declspec(dllexport) void PrintArray(int* pArray) {
int i;
for(i = 0; i < 5; pArray++, i++) {
printf("%d\n",*pArray);
}
}
My Python script is ... | ctypes outputting unknown value at end of correct values | I have the following DLL ('arrayprint.dll') function that I want to use in Python via ctypes:
__declspec(dllexport) void PrintArray(int* pArray) {
int i;
for(i = 0; i < 5; pArray++, i++) {
printf("%d\n",*pArray);
}
}
My Python script is as follows:
from ctypes import *
fiveintegers = c_int * 5
x =... | [
"mydll.PrintArray.restype = None\nmydll.PrintArray(px)\n\nBy default ctypes assumes the function returns an integral type, which causes undefined behavior (reading a garbage memory location).\n"
] | [
3
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003149768_ctypes_python.txt |
Q:
How can I avoid circular imports in Python?
I'm having a problem with circular imports. I have three Python test modules: robot_test.py which is my main script, then two auxiliary modules, controller_test.py and servo_test.py. The idea is that I want controller_test.py to define a class for my microcontroller and... | How can I avoid circular imports in Python? | I'm having a problem with circular imports. I have three Python test modules: robot_test.py which is my main script, then two auxiliary modules, controller_test.py and servo_test.py. The idea is that I want controller_test.py to define a class for my microcontroller and servo_test.py to define a class for my servos. ... | [
"\nOne workaround I have found is to pass\n the myController object to the Servo\n class as an argument, but I was hoping\n to avoid having to do this.\n\nWhy ever would you want to avoid it? It's a classic case of a crucial Design Pattern (maybe the most important one that wasn't in the original Gang of Four m... | [
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003149796_python.txt |
Q:
Python-dependency, windows (CMake)
I have a large, crossplatform, python-dependent project, which is built by CMake.
In linux, python is either preinstalled or easily retrived by shell script. But on windows build, i have to install python manually from .msi before running CMake. Is there any good workaround using... | Python-dependency, windows (CMake) | I have a large, crossplatform, python-dependent project, which is built by CMake.
In linux, python is either preinstalled or easily retrived by shell script. But on windows build, i have to install python manually from .msi before running CMake. Is there any good workaround using cmake scripts?
PS All other external de... | [
"Python doesn't really have to be installed to function properly. For my own CMake based projects on Windows, I just use a .zip file containing the entire python tree. All you need to do is extract it to a temporary directory, add it to your path, and set your PYTHONHOME/PYTHONPATH environment variables. Once that'... | [
2
] | [] | [] | [
"c++",
"cmake",
"installation",
"python"
] | stackoverflow_0003147754_c++_cmake_installation_python.txt |
Q:
web2py: how to enable "request_reset_password" function?
I'm new to web2py but eager to learn it fast.
I try to enable "request_reset_passwor" function but every time I enter this page:
http://127.0.0.1:8000/project/default/user/request_reset_password
I receive message that the function is disabled.
Can you ple... | web2py: how to enable "request_reset_password" function? | I'm new to web2py but eager to learn it fast.
I try to enable "request_reset_passwor" function but every time I enter this page:
http://127.0.0.1:8000/project/default/user/request_reset_password
I receive message that the function is disabled.
Can you please tell me what should I do and where to get it working?
Tha... | [
"I think you need to set up your mail server in db.py first...\n"
] | [
1
] | [] | [] | [
"frameworks",
"python",
"web2py"
] | stackoverflow_0003121586_frameworks_python_web2py.txt |
Q:
How to parse the "" using feedparser?
The rss file is shown as below, i want to get the content in section media:group . I check the document of feedparser, but it seems not mention this. How to do it? Any help is appreciated.
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:ymusic="http://music.yahoo.com/rss/1... | How to parse the "" using feedparser? | The rss file is shown as below, i want to get the content in section media:group . I check the document of feedparser, but it seems not mention this. How to do it? Any help is appreciated.
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:ymusic="http://music.yahoo.com/rss/1.0/ymusic/" xmlns:media="http://search.yaho... | [
"feedparser 4.1 as available from PyPi has this bug.\nthe solution for me was to get the latest feedparser.py (4.2 pre) from the repository.\nsvn checkout http://feedparser.googlecode.com/svn/trunk/ feedparser-readonly\ncd feedparser-readonly\npython setup.py install\n\nnow you can access all mrss items\n>>> import... | [
6,
0
] | [] | [] | [
"feedparser",
"python",
"rss"
] | stackoverflow_0002461853_feedparser_python_rss.txt |
Q:
py2exe not making exe?
I am following the tutorial for py2exe from this site http://www.py2exe.org/index.cgi/Tutorial
this is the setup code:
from distutils.core import setup
import py2exe
setup(console=['script.py'])
when I type in cmd:
python setup.py install
I get this:
running install
running build
my sc... | py2exe not making exe? | I am following the tutorial for py2exe from this site http://www.py2exe.org/index.cgi/Tutorial
this is the setup code:
from distutils.core import setup
import py2exe
setup(console=['script.py'])
when I type in cmd:
python setup.py install
I get this:
running install
running build
my script works fine and I even t... | [
"To build an exe, the command is:\npython setup.py py2exe\n\n"
] | [
3
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0003150593_py2exe_python.txt |
Q:
Python code refactoring question. Applying functions to multiple elements
I have code that looks something like this:
self.ui.foo.setEnabled(False)
self.ui.bar.setEnabled(False)
self.ui.item.setEnabled(False)
self.ui.item2.setEnabled(False)
self.ui.item3.setEnabled(False)
And I would like to turn it into somethin... | Python code refactoring question. Applying functions to multiple elements | I have code that looks something like this:
self.ui.foo.setEnabled(False)
self.ui.bar.setEnabled(False)
self.ui.item.setEnabled(False)
self.ui.item2.setEnabled(False)
self.ui.item3.setEnabled(False)
And I would like to turn it into something like this:
items = [foo,bar,item,item2,item3]
for elm in items:
self.ui.e... | [
"Grab the object to have the function called on it by its attribute name using the built-in getattr function:\nitems = ['foo', 'bar', 'item', 'item2', 'item3']\nfor elm in items:\n getattr(self.ui, elm).setEnabled(False)\n\n"
] | [
4
] | [
"You could try something like:\nitems = [foo,bar,item,item2,item3]\nui = self.ui\nfor elm in items:\n ui.elm.setEnabled(False)\n\n"
] | [
-3
] | [
"list",
"python",
"refactoring"
] | stackoverflow_0003150856_list_python_refactoring.txt |
Q:
Newbie Python question about sys.argv
I'm currently going through a few tutorials to get myself up and running on Python, but I seem to hit the same problem a few times. The tutorial I'm currently following is Aloha.py in Introduction to Simulation by Norm Matloff.
The problem I'm hitting seems to be in the follow... | Newbie Python question about sys.argv | I'm currently going through a few tutorials to get myself up and running on Python, but I seem to hit the same problem a few times. The tutorial I'm currently following is Aloha.py in Introduction to Simulation by Norm Matloff.
The problem I'm hitting seems to be in the following code:
import random, sys
class node: # ... | [
"The traceback shows that you actually have this in your code:\ns = int(sys.argv[0])\n\nso you are referring to argument 0 - the script name itself - rather than 1.\n",
"sys.argv is for collecting the options given to the program on the command-line. So instead of just running the file, you'll want to run python ... | [
4,
3,
1
] | [
"try \ns = int(sys.argv[-1])\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0003151019_python.txt |
Q:
Netbeans + sqlite3 = Fail?
I've decided to give Python a try on Netbeans. The problem so far is when try to run program I know works, i.e. if I ran it through the terminal. For the project I selected the correct Python version (2.6.5). And received the following error:
Traceback (most recent call last): File
... | Netbeans + sqlite3 = Fail? | I've decided to give Python a try on Netbeans. The problem so far is when try to run program I know works, i.e. if I ran it through the terminal. For the project I selected the correct Python version (2.6.5). And received the following error:
Traceback (most recent call last): File
"/Users/XXX/NetBeansProjects/New... | [
"Search for PYTHONPATH. You probably have different settings in your OS and Netbeans.\n"
] | [
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003149370_python_sqlite.txt |
Q:
Python: Are class attributes equivalent to local variables when inside a method?
In python, I know that looking up a locally scoped variable is significantly faster than looking up a global scoped variable. So:
a = 4
def function()
for x in range(10000):
<do something with 'a'>
Is slower than
def func... | Python: Are class attributes equivalent to local variables when inside a method? | In python, I know that looking up a locally scoped variable is significantly faster than looking up a global scoped variable. So:
a = 4
def function()
for x in range(10000):
<do something with 'a'>
Is slower than
def function()
a = 4
for x in range(10000):
<do something with 'a'>
So, when ... | [
"Locally scoped variables are fast because the interpreter doesn't need to do a dictionary lookup. It knows at compile-time exactly how many local variables there will be and it creates instructions to access them as an array.\nMember attributes require a dictionary lookup, so they execute similar to your first ex... | [
4
] | [] | [] | [
"attributes",
"class",
"methods",
"python"
] | stackoverflow_0003151068_attributes_class_methods_python.txt |
Q:
Retrieving a lot url addresses
Edit: Just for clarification I am using python, and would like to do this within python.
I am in the middle of collecting data for a research project at our university. Basically I need to scrape a lot of information from a website that monitors the European Parliament. Here is an ex... | Retrieving a lot url addresses | Edit: Just for clarification I am using python, and would like to do this within python.
I am in the middle of collecting data for a research project at our university. Basically I need to scrape a lot of information from a website that monitors the European Parliament. Here is an example of how the url of one site loo... | [
"Can you use python and wget ? Loop through the sessions that exist, and create a string to give to wget? Or is that overkill?\n",
"If I understand correctly, you just want to be able to loop over the parliments?\ni.e. you want A7, A6, A5...? \nIf that's what you want a simple loop could handle it:\nfor p in xr... | [
1,
1,
1,
0
] | [] | [] | [
"python",
"screen_scraping",
"web_scraping"
] | stackoverflow_0003150621_python_screen_scraping_web_scraping.txt |
Q:
App Engine template values not showing
I'm trying to read a line from a static file and insert it into a template in Google App engine using the Webapp framework. However, the line does not render, not matter what I try. Is there something that I'm overlooking?
main.py:
def get(self):
...
question = random... | App Engine template values not showing | I'm trying to read a line from a static file and insert it into a template in Google App engine using the Webapp framework. However, the line does not render, not matter what I try. Is there something that I'm overlooking?
main.py:
def get(self):
...
question = randomLine("data/questions.csv")
data = questi... | [
"Never mind, I solved it. I had renamed main.py, but I didn't update it in app.yaml so even though I had cleared my cache and the datastore, it was still somehow loading what was left. Doh!\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python",
"templates"
] | stackoverflow_0003151425_google_app_engine_python_templates.txt |
Q:
library for representing 3D polyhedra
Are there any libraries that provide 3D polyhedra, and support calculating the intersection of two polyhedra?
If it makes a difference, the polyhedra I want to model do not have 'holes' in them.
The focus would be on correctness first and speed a close second!
Ideally this lib... | library for representing 3D polyhedra | Are there any libraries that provide 3D polyhedra, and support calculating the intersection of two polyhedra?
If it makes a difference, the polyhedra I want to model do not have 'holes' in them.
The focus would be on correctness first and speed a close second!
Ideally this library would:
have existing tidy python bind... | [
"CGAL offers rather more than you're asking for, but does in particular include polyhedra and \"boolean\"-like operations on them (I'm not sure about \"view from any angle\" as a primitive, though -- as I recall it wasn't there when I last used it, but that was a while ago -- you may have to iterate projecting the ... | [
5
] | [] | [] | [
"3d",
"polygon",
"python"
] | stackoverflow_0003151524_3d_polygon_python.txt |
Q:
python: how to find \r\n\r\n in one single search
I have to split the file content based on first occurrence of \r\n\r\n
I need flexibility such a way that the lines can just ends with \r\n\r\n or \n\n.
How to split the text?
Example added:
\===================FILE BEGIN==========================================
... | python: how to find \r\n\r\n in one single search | I have to split the file content based on first occurrence of \r\n\r\n
I need flexibility such a way that the lines can just ends with \r\n\r\n or \n\n.
How to split the text?
Example added:
\===================FILE BEGIN==========================================
name: about
title: About
publish: True
order: -1
\r... | [
"import re\n\nlinend = re.compile(r'\\r\\n\\r\\n|\\n\\n')\ns = 'an example\\n\\nstring\\n\\nhere'\nprint linend.split(s, 1)\ns = 'another\\r\\n\\r\\nexample\\r\\n\\r\\nhere'\nprint linend.split(s, 1)\n\nprints:\n['an example', 'string\\n\\nhere']\n['another', 'example\\r\\n\\r\\nhere']\n\nas requested.\n",
"The r... | [
2,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003151842_python_regex_string.txt |
Q:
How to decode a Google App Engine entity Key path str in Python?
In Google App Engine, an entity has a Key. A key can be made from a path, in which case str(key) is an opaque hex string. Example:
from google.appengine.ext import db
foo = db.Key.from_path(u'foo', u'bar', _app=u'baz')
print foo
gives
agNiYXpyDAsS... | How to decode a Google App Engine entity Key path str in Python? | In Google App Engine, an entity has a Key. A key can be made from a path, in which case str(key) is an opaque hex string. Example:
from google.appengine.ext import db
foo = db.Key.from_path(u'foo', u'bar', _app=u'baz')
print foo
gives
agNiYXpyDAsSA2ZvbyIDYmFyDA
if you set up the right paths to run the code.
So, how... | [
"from google.appengine.ext import db\n\nk = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA')\n_app = k.app()\npath = []\nwhile k is not None:\n path.append(k.id_or_name())\n path.append(k.kind())\n k = k.parent()\npath.reverse()\nprint 'app=%r, path=%r' % (_app, path)\n\nwhen run in a Development Console, this outputs:\napp... | [
7,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003151379_google_app_engine_python.txt |
Q:
Python + SQLAlchemy problem: The transaction is inactive due to a rollback in a subtransaction
I have a problem with Python + SQLAlchemy.
When something goes wrong (in my case it is an integrity error, due to a race condition) and the database error is raised, all following requests result in the error being raise... | Python + SQLAlchemy problem: The transaction is inactive due to a rollback in a subtransaction | I have a problem with Python + SQLAlchemy.
When something goes wrong (in my case it is an integrity error, due to a race condition) and the database error is raised, all following requests result in the error being raised:
InvalidRequestError: The transaction is inactive due to a rollback in a subtransaction. Issue ro... | [
"The easiest thing is to make sure you are using a new SQLAlchemy Session when you start work in your controller. in /project/lib/base.py, add a method for BaseController:\ndef __before__(self):\n model.Session.close()\n\nSession.close() will clear out the session and close any open transactions if there are an... | [
3,
0
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0003139211_pylons_python_sqlalchemy.txt |
Q:
Trying to match '#' in a text
I'm trying to match a "#" followed by letters if and only if it's preceded by newline, whitespace or is the first character in a string. The first two I've done, but I'm having a hard time matching if it's the first character in a string. I'm trying to find a use for '\A', but it does... | Trying to match '#' in a text | I'm trying to match a "#" followed by letters if and only if it's preceded by newline, whitespace or is the first character in a string. The first two I've done, but I'm having a hard time matching if it's the first character in a string. I'm trying to find a use for '\A', but it doesn't work to just add it to the clas... | [
"I think this is what you're looking for:\nresult = re.findall(\"(?:^|\\s)(#[a-zA-Z]+)\", text, re.MULTILINE)\n\nThe (?:^|\\s) is a set of non-grouping parentheses (we don't want this part in our results). With the multiline flag, it will match the beginning of the string, or a preceding newline or whitespace. The ... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003150899_python_regex.txt |
Q:
to get number of frames between a time range?
I want to find the number of frames in wav file between certain time range that is generally using the function wave.getnframes we can get the number of frames in the complete wave file but here i want to know how to find the number frames between a certain time range ... | to get number of frames between a time range? | I want to find the number of frames in wav file between certain time range that is generally using the function wave.getnframes we can get the number of frames in the complete wave file but here i want to know how to find the number frames between a certain time range such number of frames between 5.43 sec to 5.81 secs... | [
"frame rate is equal to the number of frames per a second\nso 5.81 minus 5.43 equals 0.38 seconds\nnumber of frames is equal to 0.38 * wave.getframerate()\nLike so:\nimport wave\n\nstart_time = 5.43\nstop_time = 5.81\ntime_period = stop_time - start_time\nwav = wave.open('test.wav')\ntime_period_frames = time_perio... | [
5
] | [] | [] | [
"python",
"wav"
] | stackoverflow_0003152196_python_wav.txt |
Q:
Splitting items in a list into two and appending one of them to another list
Hey all. Trying to get a little more efficient with lists in Python but I cant seem to figure out if I can do what I want or even if it is worth figuring out.
stream is a list. Each item in the list is something like :
10,123400FFFE001DB9... | Splitting items in a list into two and appending one of them to another list | Hey all. Trying to get a little more efficient with lists in Python but I cant seem to figure out if I can do what I want or even if it is worth figuring out.
stream is a list. Each item in the list is something like :
10,123400FFFE001DB9AA
I am trying to get to the second part of each item after the comma so I run thr... | [
"incoming_data = [item.split(\",\")[1] for item in stream if item]\n\nThe if item discards the blank lines in stream.\n",
"You can use Python's handy-dandy list comprehensions to do this in one line:\nincoming_data = [ item.split(',')[1] for item in stream ]\n\n",
"Actually, you could do incoming_data.append(it... | [
5,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003152815_python.txt |
Q:
python refactoring (similar methods in class)
Python refactoring
Both the add and sub are very similar. How does one re-factor code like this? The logic is basically inverse of each other.
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def add( self, p ):
... | python refactoring (similar methods in class) | Python refactoring
Both the add and sub are very similar. How does one re-factor code like this? The logic is basically inverse of each other.
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def add( self, p ):
x = self.x + p.x
y = self.y + p.y
... | [
"First, standard practice is to capitalize classes (so Point, not point). I'd make use of the __add__ and __sub__ (and possibly __iadd__ and __isub__) methods, as well. A first cut might look like this:\nclass Point(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add_... | [
2,
2,
0
] | [] | [] | [
"python",
"refactoring"
] | stackoverflow_0003152820_python_refactoring.txt |
Q:
How can I change name of option in django select box
I got 2 models
class Category(models.Model):
name = models.CharField(max_length=30, unique=True)
class Post(models.Model):
......
category = models.ForeginKey(Category)
........
And when I create a form, in select box i got options "Category ob... | How can I change name of option in django select box | I got 2 models
class Category(models.Model):
name = models.CharField(max_length=30, unique=True)
class Post(models.Model):
......
category = models.ForeginKey(Category)
........
And when I create a form, in select box i got options "Category object", but i would like to display name of category, i am... | [
"class Category(models.Model):\n name = models.CharField(max_length=30, unique=True)\n\n def __unicode__(self):\n return self.name\n\n"
] | [
1
] | [] | [] | [
"django_forms",
"python"
] | stackoverflow_0003153092_django_forms_python.txt |
Q:
Python Class scope & lists
I'm still fairly new to Python, and my OO experience comes from Java. So I have some code I've written in Python that's acting very unusual to me, given the following code:
class MyClass():
mylist = []
mynum = 0
def __init__(self):
# populate lis... | Python Class scope & lists | I'm still fairly new to Python, and my OO experience comes from Java. So I have some code I've written in Python that's acting very unusual to me, given the following code:
class MyClass():
mylist = []
mynum = 0
def __init__(self):
# populate list with some value.
... | [
"tlayton's answer is part of the story, but it doesn't explain everything.\nAdd a \nprint MyClass.mynum\n\nto become even more confused :). It will print '0'. Why? Because the line\nself.mynum += 1\n\ncreates an instance variable and subsequently increases it. It doesn't increase the class variable.\nThe story of t... | [
8,
5,
5
] | [] | [] | [
"python"
] | stackoverflow_0003153017_python.txt |
Q:
Expose __main__
is this legal in python?. Seems to work ...
Thanks
# with these lines you not need global variables anymore
if __name__ == '__main__':
import __main__ as main
else:
main = __import__(os.path.basename(os.path.splitext(__file__)))
var_in_main = 0 # now any var is a global var, you can acc... | Expose __main__ | is this legal in python?. Seems to work ...
Thanks
# with these lines you not need global variables anymore
if __name__ == '__main__':
import __main__ as main
else:
main = __import__(os.path.basename(os.path.splitext(__file__)))
var_in_main = 0 # now any var is a global var, you can access any var from ever... | [
"if __name__ == '__main__':\n import __main__ as main\nelse:\n main = __import__(os.path.basename(os.path.splitext(__file__)))\n\nThis is quite a fragile approach, since it relies on relative import behavior for all modules from within a package. There is a much better solution -- faster, more concise, and m... | [
3
] | [] | [] | [
"function",
"iterable",
"program_entry_point",
"python"
] | stackoverflow_0003153112_function_iterable_program_entry_point_python.txt |
Q:
Localhost bottleneck with python sockets
I'm sending a very large string from one application to another on localhost using sockets in python. Small strings move instantly, but large strings seem to take a while longer (I say large, but I'm talking maybe a MB or two at the very most). Enough that I have to sit and... | Localhost bottleneck with python sockets | I'm sending a very large string from one application to another on localhost using sockets in python. Small strings move instantly, but large strings seem to take a while longer (I say large, but I'm talking maybe a MB or two at the very most). Enough that I have to sit and wait a few seconds after I do something in o... | [
"You are still moving the data through the entire network stack, just not going out through the network interface card itself. \nThere may be some shortcuts taken around the network stack with localhost, but it's most likely dependent on how the stack is implemented on the system you are using. Regardless shared m... | [
3
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003153147_python_sockets.txt |
Q:
Choosing a random sample from each row of Numpy array, excluding negative numbers
I have a Numpy array that looks like
>>> a
array([[ 3. , 2. , -1. ],
[-1. , 0.1, 3. ],
[-1. , 2. , 3.5]])
I would like to select a value from each row at random, but I would like to exclude the -1 values from the ... | Choosing a random sample from each row of Numpy array, excluding negative numbers | I have a Numpy array that looks like
>>> a
array([[ 3. , 2. , -1. ],
[-1. , 0.1, 3. ],
[-1. , 2. , 3.5]])
I would like to select a value from each row at random, but I would like to exclude the -1 values from the random sampling.
What I do currently is:
x=[]
for i in range(a.shape[0]):
idx=numpy... | [
"I really don't think that you will find anything in Numpy that does exactly what you are asking as packaged so I've decided to offer what optimizations I could think up.\nThere are several things that could make this slow here. First off, numpy.where() is rather slow because it has to check every value in the slic... | [
3
] | [] | [] | [
"numpy",
"python",
"random"
] | stackoverflow_0003151157_numpy_python_random.txt |
Q:
Open a file in a function and write to it
I created the function below:
def print_form(x):
f = open('/home/rv/Plone/Zope-2.10.11-final-py2.4/Extensions/test.fasta', 'w')
f.write(str(x))
f.close()
return x
The function returns and prints, but doesnt write it to a file or creates it?
EDIT
I editied... | Open a file in a function and write to it | I created the function below:
def print_form(x):
f = open('/home/rv/Plone/Zope-2.10.11-final-py2.4/Extensions/test.fasta', 'w')
f.write(str(x))
f.close()
return x
The function returns and prints, but doesnt write it to a file or creates it?
EDIT
I editied the above code the so the file is created in a... | [
"The file 'form.fasta' will be created in the current working directory. This is usually whatever directory you're in when you invoke the script.\nTo see what your current directory is, add:\nprint(os.path.abspath(os.curdir))\n\nor equivalent.\nAlso, make sure f.write(x) converts x to something fit to be written; ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003153730_python.txt |
Q:
Perspective detection with OpenCv
If I want to detect perspective distorted objects (e.g rectangles) and calculate the correction transformation, what would be a good method?
For example, I have a lot of photos of papers lying on a flat surface (the photos are shot from an angle), and I want to correct the perspec... | Perspective detection with OpenCv | If I want to detect perspective distorted objects (e.g rectangles) and calculate the correction transformation, what would be a good method?
For example, I have a lot of photos of papers lying on a flat surface (the photos are shot from an angle), and I want to correct the perspective and crop them.
I am thinking of us... | [
"You have to specify exactly what you mean with detecting the distortion. I assume you want to detect the corners of such a paper (or your table/flat surface) and make it axis-parallel to your display. This can be done using cvFindHomography and cvWarpPerspective. I have written some example code a while ago for py... | [
3
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0003151034_opencv_python.txt |
Q:
slice (unsorted) array at value in python
Given the array a = [1,1,12,3,5,8,13,21] I can slice off the first 3 elements like a[:3] giving [1,1,2]. What I want is to slice off up to the element of vlaue i (e.g. if i=8 I want [1,1,12,3,5,8] or [1,1,12,3,5] (I can work with either)).
This works:
return a[:a.index(i... | slice (unsorted) array at value in python | Given the array a = [1,1,12,3,5,8,13,21] I can slice off the first 3 elements like a[:3] giving [1,1,2]. What I want is to slice off up to the element of vlaue i (e.g. if i=8 I want [1,1,12,3,5,8] or [1,1,12,3,5] (I can work with either)).
This works:
return a[:a.index(i)]
but only if I give it a value that's in the... | [
"\nThat's a list.\nTry \n>>> a = [1,1,2,3,5,8,13,21]\n>>> import itertools\n>>> for x in itertools.takewhile(lambda val: val != 8, a):\n... print x\n...\n1\n1\n2\n3\n5\n\n\n",
"Assuming the array is sorted, use a binary search. The function is in the bisect module.\nfrom bisect import bisect_right\na[:bisect_... | [
5,
0,
0
] | [] | [] | [
"arrays",
"python",
"slice"
] | stackoverflow_0003153975_arrays_python_slice.txt |
Q:
How to pass a specific argument to a decorator in python
I want to write a python function decorator that tests that certain arguments to a function pass some criterion. For eg, Suppose I want to test that some arguments are always even, then I want to be able to do something like this (not valid python code)
def... | How to pass a specific argument to a decorator in python | I want to write a python function decorator that tests that certain arguments to a function pass some criterion. For eg, Suppose I want to test that some arguments are always even, then I want to be able to do something like this (not valid python code)
def ensure_even( n ) :
def decorator( function ) :
@functo... | [
"You can do this:\ndef ensure_even(argnum):\n def fdec(func):\n def f(*args, **kwargs):\n assert(args[argnum] % 2 == 0) #or assert(not args[argnum] % 2)\n return func(*args, **kwargs)\n return f\n return fdec\n\nSo then:\n@ensure_even(1) #2nd argument must be even\ndef test(arg1, arg2):\n print... | [
11,
4
] | [] | [] | [
"decorator",
"function",
"python"
] | stackoverflow_0003152007_decorator_function_python.txt |
Q:
lexical analyse or series of regular expressions to parse unstructured text into structured form
I am trying to write some code that will function like google calendars quick add feature . You know the One where you can input any of the following :
1) 24th sep 2010 , Johns Birthday
2) John's Birthday , 24/9/10
3)... | lexical analyse or series of regular expressions to parse unstructured text into structured form | I am trying to write some code that will function like google calendars quick add feature . You know the One where you can input any of the following :
1) 24th sep 2010 , Johns Birthday
2) John's Birthday , 24/9/10
3) 24 September 2010 , Birthday of John Doe
4) 24-9-2010 : John Does Birthday
5) John Does Birthday 24th... | [
"NOTE: The python code here is not correct! It is just a rough pseudo-code of how it might look.\nRegular Expressions are good at finding and extracting data from text in a fixed format (e.g. a DD/MM/YYYY date).\nA lexer/parser pair is good at processing data in a structured, but somewhat variable format. Lexers sp... | [
2
] | [] | [] | [
"lexical_analysis",
"parsing",
"python",
"regex"
] | stackoverflow_0003153869_lexical_analysis_parsing_python_regex.txt |
Q:
Python XLWT adjusting column widths
I am enormously impressed with the ease of use of XLWT, but there is one thing I have not figured out how to do. I am trying to adjust certain rows to the minimum width they would need to display all characters (in other words, what excel would do if you double clicked on the d... | Python XLWT adjusting column widths | I am enormously impressed with the ease of use of XLWT, but there is one thing I have not figured out how to do. I am trying to adjust certain rows to the minimum width they would need to display all characters (in other words, what excel would do if you double clicked on the divider between cells).
I know how to ad... | [
"Width is 1/256 the width of the zero character for the default font. A good enough approximation is:\ndef get_width(num_characters):\n return int((1+num_characters) * 256)\n\n"
] | [
29
] | [] | [] | [
"python",
"xlwt"
] | stackoverflow_0003154270_python_xlwt.txt |
Q:
Cleaning up and removing tags with BeautifulSoup
I have the following script so far:
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import urllib2
br = Browser()
br.open("http://www.foo.com")
html = br.response().read();
soup = BeautifulSoup(html)
items = soup.findAll(id="info"... | Cleaning up and removing tags with BeautifulSoup | I have the following script so far:
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import urllib2
br = Browser()
br.open("http://www.foo.com")
html = br.response().read();
soup = BeautifulSoup(html)
items = soup.findAll(id="info")
and it runs perfectly, and results in the following... | [
"This will do it for this EXACT html. Obviously this isn't tolerant of any deviation, so you'll want to add quite a lot of bounds checking and null checking, but here's the nuts and bolts to get your data into plain text.\nitems = soup.findAll(id=\"info\")\nprint items[0].span.b.contents[0]\nprint items[0].content... | [
1
] | [] | [] | [
"beautifulsoup",
"extract",
"python",
"web_scraping"
] | stackoverflow_0003153882_beautifulsoup_extract_python_web_scraping.txt |
Q:
How to mock a free function in python?
I have a python program with a global function that is painful to test (it needs a large dataset to work properly). What is the best way to get around this while testing functions that call it?
I've found that the following works (but it make me feel dirty to use it).
module ... | How to mock a free function in python? | I have a python program with a global function that is painful to test (it needs a large dataset to work properly). What is the best way to get around this while testing functions that call it?
I've found that the following works (but it make me feel dirty to use it).
module foo:
def PainLiesHere():
return 4; #guaran... | [
"This is a perfectly fine way to do it. As long as you know that BlissLiesHere does not change the overall behavior of the unit you are testing...\nEDIT:\nThis is what is being done, under all the nice extras they provide, by different kinds of mocking libraries, such as Mock, Mox, etc.\n"
] | [
8
] | [] | [] | [
"mocking",
"python"
] | stackoverflow_0003154441_mocking_python.txt |
Q:
'METHODNAME' as Client method versus irc_'METHODNAME' in twisted
Looking at twisted.words.protocols.irc.IRCClient, it seems to me like there are some strangely redundant methods. For instance, there is a method 'privmsg' but also a method 'irc_PRIVMSG'
As another example consider 'join' and 'irc_JOIN'
What I want ... | 'METHODNAME' as Client method versus irc_'METHODNAME' in twisted | Looking at twisted.words.protocols.irc.IRCClient, it seems to me like there are some strangely redundant methods. For instance, there is a method 'privmsg' but also a method 'irc_PRIVMSG'
As another example consider 'join' and 'irc_JOIN'
What I want to know is why the redundancy, those are just two examples of many. Ar... | [
"You're on the right track about the two different types of methods being used in different contexts. This can actually be seen quite easily by examining the way IRCClient handles data it receives. First it parses them into lines, then it splits the lines up and passes the pieces to its own handleCommand method:\... | [
4
] | [] | [] | [
"client",
"irc",
"libraries",
"python",
"twisted"
] | stackoverflow_0003153666_client_irc_libraries_python_twisted.txt |
Q:
How do I pipe the output of file to a variable in Python?
How do I pipe the output of file to a variable in Python?
Is it possible? Say to pipe the output of netstat to a variable x in Python?
A:
It is possible. See:
http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote
In Python 2.4 an... | How do I pipe the output of file to a variable in Python? | How do I pipe the output of file to a variable in Python?
Is it possible? Say to pipe the output of netstat to a variable x in Python?
| [
"It is possible. See:\nhttp://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote\nIn Python 2.4 and above:\nfrom subprocess import *\nx = Popen([\"netstat\", \"-x\", \"-y\", \"-z\"], stdout=PIPE).communicate()[0]\n\n",
"Two parts:\nShell\nnetstat | python read_netstat.py\n\nPython read_netst... | [
6,
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0003153460_python.txt |
Q:
Django form.save step by step
Let's say I have a form for adding/editing products (with field 'user' being a foreign key to my User) triggered from two separate view functions - add/edit :
def product_add(request):
userprofile = UserProfile.objects.get(user=request.user)
if request.method == 'POST':
... | Django form.save step by step | Let's say I have a form for adding/editing products (with field 'user' being a foreign key to my User) triggered from two separate view functions - add/edit :
def product_add(request):
userprofile = UserProfile.objects.get(user=request.user)
if request.method == 'POST':
form = ProductAddForm(request.POS... | [
"\nself.instance.user = user \n\nSave the user argument into the self.instance object's user attribute\n\npost = super(ProductAddForm, self).save(*args, **kwargs)\n\nInvoke the superclass save method to get a resulting object.\n\npost.save()\n\nSave the resulting object. This may be needless, or it may be essentia... | [
3
] | [] | [] | [
"django",
"python",
"super"
] | stackoverflow_0003154624_django_python_super.txt |
Q:
Problem about recursion
Please suggest me the solution to the following problem
consider a function
function recurse(a):
for child in a.childs:
recurse(child)
Now I want to execute some code lets say
print "Program ends here"
when the program is done with recursion,so how can I know when the recursio... | Problem about recursion | Please suggest me the solution to the following problem
consider a function
function recurse(a):
for child in a.childs:
recurse(child)
Now I want to execute some code lets say
print "Program ends here"
when the program is done with recursion,so how can I know when the recursion will end?
Thank you
| [
"The various answers proposed so far, which sum up to \"do it outside of recurse\", are fine. But if you're keen to do it inside recurse, that's not hard either (just marginally less efficient):\nfunction recurse(a, _toplevel=True):\n for child in a.childs:\n recurse(child, False)\n if _toplevel:\n pri... | [
3,
2,
2,
0,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0003154651_python_recursion.txt |
Q:
Breaking a parent function from within a child function (PHP Preferrably)
I was challenged how to break or end execution of a parent function without modifying the code of the parent, using PHP
I cannot figure out any solution, other than die(); in the child, which would end all execution, and so anything after th... | Breaking a parent function from within a child function (PHP Preferrably) | I was challenged how to break or end execution of a parent function without modifying the code of the parent, using PHP
I cannot figure out any solution, other than die(); in the child, which would end all execution, and so anything after the parent function call would end. Any ideas?
code example:
function victim() {
... | [
"function victim() {\n echo \"I should be run\";\n killer();\n echo \"I should not\";\n}\nfunction killer() {\n throw new Exception('Die!');\n}\n\ntry {\n victim();\n} catch (Exception $e) {\n // note that catch blocks shouldn't be empty :)\n}\necho \"This should still run\";\n\n",
"Note that Ex... | [
7,
1
] | [] | [] | [
"break",
"function",
"php",
"python"
] | stackoverflow_0003154489_break_function_php_python.txt |
Q:
Good resources to start python for web development?
I'm really interested in learning Python for web development. Can anyone point me in the right direction? I've been looking at stuff on Google, but haven't really found anything that shows proper documentation and how to get started. Any recommended frameworks? T... | Good resources to start python for web development? | I'm really interested in learning Python for web development. Can anyone point me in the right direction? I've been looking at stuff on Google, but haven't really found anything that shows proper documentation and how to get started. Any recommended frameworks? Tutorials?
I've been doing PHP for 5 years now, so I just ... | [
"Django is probably the best starting point. It's got great documentation and an easy tutorial (at http://djangoproject.com/) and a free online book too (http://www.djangobook.com/).\n",
"Web Server Gateway Interface\nAbout\n\nhttp://www.wsgi.org/en/latest/index.html\nhttp://en.wikipedia.org/wiki/Web_Server_Gatew... | [
5,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003154921_python.txt |
Q:
why does response codes returned by httplib and urllib not match?
I'm writing a dead link detector and wondering which lib i should use, httplib and urllib, so I tried both.
def http_response_code(url):
host = urlparse(url)[1]
req = '/'.join(urlparse(url)[2:5])
conn = httplib.HTTPConnection(host)
c... | why does response codes returned by httplib and urllib not match? | I'm writing a dead link detector and wondering which lib i should use, httplib and urllib, so I tried both.
def http_response_code(url):
host = urlparse(url)[1]
req = '/'.join(urlparse(url)[2:5])
conn = httplib.HTTPConnection(host)
conn.request('HEAD', req)
res = conn.getresponse()
return res.st... | [
"302 is the HTTP status code for a redirect (see for example here), and httplib (the lower-level library) returns it faithfully, while urllib is automatically following the redirect and giving you the final resulting status code (200 for \"everything OK\").\nPick the library that best suits the abstraction layer yo... | [
5
] | [] | [] | [
"http",
"python"
] | stackoverflow_0003155073_http_python.txt |
Q:
extract parts of the string in python
I have to parse an input string in python and extract certain parts from it.
the format of the string is
(xx,yyy,(aa,bb,...)) // Inner parenthesis can hold one or more characters in it
I want a function to return xx, yyyy and a list containing aa, bb ... etc
I can ofcourse d... | extract parts of the string in python | I have to parse an input string in python and extract certain parts from it.
the format of the string is
(xx,yyy,(aa,bb,...)) // Inner parenthesis can hold one or more characters in it
I want a function to return xx, yyyy and a list containing aa, bb ... etc
I can ofcourse do it by trying to split of the parenthesis ... | [
"If your parenthesis nesting can be arbitrarily deep, then regexen won't do, you'll need a state machine or a parser. Pyparsing supports recursive grammars using forward-declaration class Forward:\nfrom pyparsing import *\n\nLPAR,RPAR,COMMA = map(Suppress,\"(),\")\nnestedParens = Forward()\nlistword = Word(alphas)... | [
3,
3,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003154743_python.txt |
Q:
creating and intersecting hexahedrons with CGAL
Using the Python bindings for CGAL, I can't work out how create a hexahedron, nor how to calculate its intersection with another hexahedron.
I have 8 input points, which are the corners of the hexahedron:
My code does this:
P = Polyhedron_3()
bottom = P.make_tetrahe... | creating and intersecting hexahedrons with CGAL | Using the Python bindings for CGAL, I can't work out how create a hexahedron, nor how to calculate its intersection with another hexahedron.
I have 8 input points, which are the corners of the hexahedron:
My code does this:
P = Polyhedron_3()
bottom = P.make_tetrahedron(p[0],p[1],p[2],p[3])
top = P.make_tetrahedron(p[... | [
"You're going to want to create an initial tetrahedron, then use split_edge three times and moving the newly created vertices to where they are supposed to be. Then use another combination of split_facet and split_edge to \"mold\" the hexahedron into place.\nSee Section 25.3.7 of CGAL Documentation to see this bei... | [
1
] | [] | [] | [
"cgal",
"geometry",
"python"
] | stackoverflow_0003154269_cgal_geometry_python.txt |
Q:
Python 2.6: parallel parsing with urllib2
I'm currently retrieving and parsing pages from a website using urllib2. However, there are many of them (more than 1000), and processing them sequentially is painfully slow.
I was hoping there was a way to retrieve and parse pages in a parallel fashion. If that's a good ... | Python 2.6: parallel parsing with urllib2 | I'm currently retrieving and parsing pages from a website using urllib2. However, there are many of them (more than 1000), and processing them sequentially is painfully slow.
I was hoping there was a way to retrieve and parse pages in a parallel fashion. If that's a good idea, is it possible, and how do I do it?
Also... | [
"You can always use threads (i.e. run each download in a separate thread). For large numbers, this could be a little too resource hogging, in which case I recommend you take a look at gevent and specifically this example, which may be just what you need.\n(from gevent.org: \"gevent is a coroutine-based Python netwo... | [
3
] | [] | [] | [
"parallel_processing",
"parsing",
"python",
"urllib2"
] | stackoverflow_0003155382_parallel_processing_parsing_python_urllib2.txt |
Q:
Python's lambda iteration not working as intended
In the code below I intend to have two buttons, and when each is pressed '0' and '1' are to be printed to stdout, respectively. However when the program is run, they both print '1', which is the last value i had in the for iteration. Why?
import Tkinter as tk
impo... | Python's lambda iteration not working as intended | In the code below I intend to have two buttons, and when each is pressed '0' and '1' are to be printed to stdout, respectively. However when the program is run, they both print '1', which is the last value i had in the for iteration. Why?
import Tkinter as tk
import sys
root = tk.Tk()
for i in range(0,2):
cmd = ... | [
"The i is not captured in the lambda when you create it (as you wanted). Instead, both functions refer back to the i in the external for loop, which changes after the function is created and before it is run. To capture it, you can use a default value:\nfor i in range(0,2):\n cmd = lambda i=i: sys.stdout.write(s... | [
5,
3,
1
] | [] | [] | [
"lambda",
"python",
"tkinter"
] | stackoverflow_0003155603_lambda_python_tkinter.txt |
Q:
How to test a function that deals with setting file ownership without being root
I wrote a function that copies the /etc/skel directory on a linux machine during a "create new user" RPC call. Now, there is quite a few things about this I want to test, for example the files in /etc/skel and the targets of symlinks ... | How to test a function that deals with setting file ownership without being root | I wrote a function that copies the /etc/skel directory on a linux machine during a "create new user" RPC call. Now, there is quite a few things about this I want to test, for example the files in /etc/skel and the targets of symlinks should not have changed permissions afterwards, whereas the copied files including the... | [
"You could make an object which does the chmod, and inject a mock when testing. This mock would not really do the chmod, but make it possible to test if it was called with the right parameters.\n"
] | [
2
] | [] | [] | [
"linux",
"python",
"testing"
] | stackoverflow_0003155748_linux_python_testing.txt |
Q:
XML instance generation from XML schema (xsd)
I was wondering if there's a way I can automate the generation of XML files from XSD schemas given that I have the data and the labels. I'd like to do this in python/java. It seems very possible, yet I can't find any library that allows me to do this. I'm looking for a... | XML instance generation from XML schema (xsd) | I was wondering if there's a way I can automate the generation of XML files from XSD schemas given that I have the data and the labels. I'd like to do this in python/java. It seems very possible, yet I can't find any library that allows me to do this. I'm looking for a fairly quick solution..
Any ideas?
See also: how-... | [
"Look at pyXSD for Python tools that are similar to JAXB.\nXSD's are used to create Python classes. Python objects are used to emit XML. \n",
"Microsoft has published a \"document generator\" tool as a sample. This is an article that describes the architecture and operation of the sample app in some detail. \nI... | [
8,
3,
2,
1,
0
] | [] | [] | [
"java",
"python",
"xml",
"xsd"
] | stackoverflow_0000307616_java_python_xml_xsd.txt |
Q:
python for loop range(bigint)
In Python, is there some short way to do something like
"for i in range(n)"
when n is too big for Python to actually create the array range(n)?
(short because otherwise I'd just use a while loop)
A:
You could use xrange()... although that is restricted to "short" integers in CPython... | python for loop range(bigint) | In Python, is there some short way to do something like
"for i in range(n)"
when n is too big for Python to actually create the array range(n)?
(short because otherwise I'd just use a while loop)
| [
"You could use xrange()... although that is restricted to \"short\" integers in CPython:\n\nCPython implementation detail:\n xrange() is intended to be simple and\n fast. Implementations may impose\n restrictions to achieve this. The C\n implementation of Python restricts all\n arguments to native C longs (“sh... | [
5,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003155441_python.txt |
Q:
Any way to improve this python function?
def __number():
# This line returns the number of the latest created object
# as a "Factura" object in format "n/year"
last = Factura.objects.filter(f_type__exact=False).latest('number')
# We convert it into a string and split it to get only the first numbe... | Any way to improve this python function? | def __number():
# This line returns the number of the latest created object
# as a "Factura" object in format "n/year"
last = Factura.objects.filter(f_type__exact=False).latest('number')
# We convert it into a string and split it to get only the first number
spl = str(last).split('/')[0]
# Con... | [
"This is really just the beginning, but I'd start by replacing some comments with self-documenting code.\ndef __number():\n # \"Factura\" object in format \"n/year\"\n latest_object = Factura.objects.filter(f_type__exact=False).latest('number')\n\n # Better name can be available if you explain why the firs... | [
2,
1,
0
] | [] | [] | [
"django",
"function",
"python"
] | stackoverflow_0003152913_django_function_python.txt |
Q:
Global Exception Handling in Google App Engine
Instead of encapsulating my entire code in a try{} except{} block, is there someway of catching exceptions globally?
Basically I am looking for a way to have a global exception handler which will handle all unhandled exceptions in the my python application written for... | Global Exception Handling in Google App Engine | Instead of encapsulating my entire code in a try{} except{} block, is there someway of catching exceptions globally?
Basically I am looking for a way to have a global exception handler which will handle all unhandled exceptions in the my python application written for google app engine
| [
"If you're using the webapp framework, you should already be defining a subclass of RequestHandler that serves as a base class, with all your app's handlers extending that. You can simply override handle_exception, which serves as a global exception handler for any uncaught exceptions.\nThe default implementation c... | [
1,
0,
0
] | [] | [] | [
"exception_handling",
"global",
"google_app_engine",
"python"
] | stackoverflow_0003154900_exception_handling_global_google_app_engine_python.txt |
Q:
Filtering treeview content recursively
I have GUI application with gtk.Treeview component. It's model is set to gtk.Treestore, which I fill with a hierarchical structure. Everything is working fine - the treeview is what I expect it to be.
Now I'd like to filter the leaf nodes to contain only a given string. I tri... | Filtering treeview content recursively | I have GUI application with gtk.Treeview component. It's model is set to gtk.Treestore, which I fill with a hierarchical structure. Everything is working fine - the treeview is what I expect it to be.
Now I'd like to filter the leaf nodes to contain only a given string. I tried creating model filter like this:
self.mo... | [
"I've never used the toolkit, but after browsing through the api docs... wouldn't the following work?\ndef visible_cb(self, model, iter, data):\n return model.iter_has_child(iter) or data.lower() in model.get_value(iter, 0).lower()\n\nNot sure why you're passing self.txt to set_visible_func and not using the cor... | [
1
] | [] | [] | [
"gtk",
"python",
"user_interface"
] | stackoverflow_0003155842_gtk_python_user_interface.txt |
Q:
What should itertools.product() yield when supplied an empty list?
I guess it's an academic question, but the second result does not make sense to me. Shouldn't it be as thoroughly empty as the first? What is the rationale for this behavior?
from itertools import product
one_empty = [ [1,2], [] ]
all_empty = []
... | What should itertools.product() yield when supplied an empty list? | I guess it's an academic question, but the second result does not make sense to me. Shouldn't it be as thoroughly empty as the first? What is the rationale for this behavior?
from itertools import product
one_empty = [ [1,2], [] ]
all_empty = []
print [ t for t in product(*one_empty) ] # []
print [ t for t in produc... | [
"From a mathematical point of view the product over no elements should yield the neutral element of the operation product, whatever that is.\nFor example on integers the neutral element of multiplication is 1, since 1 ⋅ a = a for all integers a. So an empty product of integers should be 1. When implementing a pytho... | [
11,
4
] | [] | [] | [
"cross_product",
"python",
"python_itertools"
] | stackoverflow_0003154301_cross_product_python_python_itertools.txt |
Q:
os.chdir(path) not working as expected due to path formatting in Python 2.6.5?
I cannot os.chdir(path) in Python 2.6.5 under WindowsXP SP2. It works fine under CygWin and MAC OS X, but for WinXP regardless of path format, I always get this error:
AttributeError: 'str' object has no attribute 'chdir'.
I thought i... | os.chdir(path) not working as expected due to path formatting in Python 2.6.5? | I cannot os.chdir(path) in Python 2.6.5 under WindowsXP SP2. It works fine under CygWin and MAC OS X, but for WinXP regardless of path format, I always get this error:
AttributeError: 'str' object has no attribute 'chdir'.
I thought it was the problem with format of path but after trying r"C:\WINDOWS", 'C:\WINDOWS' a... | [
"It seems that problem is that in some place you redefine 'os'. Somewhere in your code you do something like this:\nimport os\nos = 'some string'\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0003156314_python.txt |
Q:
How to broadcast to ALL subscribers w/identical queue name/routing key vals on a direct exchange
Consider a tier of N-many subscribers, all connected to a direct exchange using identical queue name and routing key values. This creates a load-balanced system where an inbound message is send round-robin to 1 of the... | How to broadcast to ALL subscribers w/identical queue name/routing key vals on a direct exchange | Consider a tier of N-many subscribers, all connected to a direct exchange using identical queue name and routing key values. This creates a load-balanced system where an inbound message is send round-robin to 1 of the subscribers. This works very well for dealing with scale-out issues as more subscribers can be added... | [
"If I understand correctly, this is your setup:\n\nyou have a producer publishing to a direct exchange;\nyou have a queue bound to that exchange;\nyou have many subscribers, all consuming from the above queue.\n\nThis works perfectly for sending a message to an arbitrary subscriber (thus sort-of load balancing), bu... | [
2
] | [] | [] | [
"python",
"rabbitmq"
] | stackoverflow_0003151989_python_rabbitmq.txt |
Q:
how do I set a value for a ShapeKey in Blender Python?
I've managed to insert Shape Keys from Python using:
ob = Scene.GetCurrent().object.active;
if(ob.activeShape == 0):
ob.insertShapeKey()
ob.insertShapeKey()
Now how do I change a key value ?
A:
Ok here's how I did it:
#get the key
k = ob.getData().get... | how do I set a value for a ShapeKey in Blender Python? | I've managed to insert Shape Keys from Python using:
ob = Scene.GetCurrent().object.active;
if(ob.activeShape == 0):
ob.insertShapeKey()
ob.insertShapeKey()
Now how do I change a key value ?
| [
"Ok here's how I did it:\n#get the key\nk = ob.getData().getKey()\n#create a new Ipo\nni = Ipo.New('Key','ni')\n#if there check if there already a key by that name, otherwise add key\nif(k.ipo['Key 1'] == None): k.ipo.addCurve('Key 1')\n#add a point to the 'Key 1' ipo curve\nk.ipo['Key 1'].append(BezTriple.New(6.... | [
0
] | [] | [] | [
"3d",
"blender",
"bpy",
"bpython",
"python"
] | stackoverflow_0003104908_3d_blender_bpy_bpython_python.txt |
Q:
Is IronPython usable as a replacement for CPython?
Has IronPython gotten to a point where you can just drop it in as a replacement for CPython?
To clarify: I mean can IronPython run applications originally written for CPython (no .NET involved, of course)
A:
Yes, pretty much, at least on Windows with "real" (Mic... | Is IronPython usable as a replacement for CPython? | Has IronPython gotten to a point where you can just drop it in as a replacement for CPython?
To clarify: I mean can IronPython run applications originally written for CPython (no .NET involved, of course)
| [
"Yes, pretty much, at least on Windows with \"real\" (Microsoft) .NET underneath. If you're depending on C-coded extensions, chances are that ironclad can bail you out; you get 2.6 support, just about every CPython standard library or third-party extension module (maybe not trivial for those coded in Fortran, or C... | [
8,
3
] | [
"Ironpython have some prolbems to replace the cpython,like\nBase on cpy, you can use some libs directly, but, in ipy, you must use ironclad, and the effiencency is insufferable.\nAnd, if you want use py files, there will be many errors, even if you use same gramma.\nSo, there are two different things, only same gra... | [
-1
] | [
"cpython",
"dynamic_language_runtime",
"ironpython",
"python"
] | stackoverflow_0001905023_cpython_dynamic_language_runtime_ironpython_python.txt |
Q:
Python, unittest: Can one make the TestRunner completely quiet?
Is there a way to make unittest.TextTestRunner completely quiet, meaning it never prints to output on its own? Even at verbosity=0 it prints results when done.
I want to process the TestResult object returned by the runner before anything is printed.
... | Python, unittest: Can one make the TestRunner completely quiet? | Is there a way to make unittest.TextTestRunner completely quiet, meaning it never prints to output on its own? Even at verbosity=0 it prints results when done.
I want to process the TestResult object returned by the runner before anything is printed.
| [
"TextTestRunner has a stream=sys.stderr in its constructor:\ndef __init__(self, stream=sys.stderr, descriptions=1, verbosity=1)\n\nChange it to a null stream. \nresult = unittest.TextTestRunner(stream = open(os.devnull, 'w')).run(alltests)\nif len(result.failures) or len(result.errors):\n print \"Sorry.\"\n\n"
] | [
8
] | [] | [] | [
"python",
"unit_testing",
"verbosity"
] | stackoverflow_0003157456_python_unit_testing_verbosity.txt |
Q:
What can be the use of SymbolType in Python?
Here's the SymbolType package that adds symbols to Python. Can those who have done anything useful with Lisp/Scheme tell me what how can I take advantage of this type in Python?
Can it be used to isolate strings coming from outside (from the web) from internal code?
$ s... | What can be the use of SymbolType in Python? | Here's the SymbolType package that adds symbols to Python. Can those who have done anything useful with Lisp/Scheme tell me what how can I take advantage of this type in Python?
Can it be used to isolate strings coming from outside (from the web) from internal code?
$ sudo easy_install SymbolType
$ ipython
Unfortunate... | [
"Symbols are not a replacement for strings. While both are represented by a \nsequence of characters, a symbol shouldn't be used in place of a string when\nthis is the dominant property. Symbols represent a unique identity. \nThis means that pointer equality\n(instead of content equality) can be used to compare the... | [
3
] | [] | [] | [
"lisp",
"python",
"scheme",
"symbols",
"types"
] | stackoverflow_0003123935_lisp_python_scheme_symbols_types.txt |
Q:
setuptools easyinstall mysql-python-1.2.3
I have read a bunch of threads on setuptools here.
A lot of people seem not to like it very much.
But I need to install MySQL-python-1.2.3. and when I do that I get this error:
MySQL-python-1.2.3 X$ python setup.py cleanTraceback (most recent call last):
File "setup... | setuptools easyinstall mysql-python-1.2.3 | I have read a bunch of threads on setuptools here.
A lot of people seem not to like it very much.
But I need to install MySQL-python-1.2.3. and when I do that I get this error:
MySQL-python-1.2.3 X$ python setup.py cleanTraceback (most recent call last):
File "setup.py", line 5, in <module>
from setuptoo... | [
"You should use virtualenv and pip.\nVirtualenv automatically creates a setuptools version within the new environment, so the default one is intact.\nYou may want to read how the packaging and installing works: 1, 2\n"
] | [
0
] | [] | [] | [
"mysql",
"mysql_python",
"python",
"setuptools"
] | stackoverflow_0003156337_mysql_mysql_python_python_setuptools.txt |
Q:
Integration testing in python, suggested tools and practices?
I've some hard time understanding Integration testing in general, I want to do some integration testing in python expecially for network programming in twisted (but I want to know something more in general).
There are any good resource I must read, and ... | Integration testing in python, suggested tools and practices? | I've some hard time understanding Integration testing in general, I want to do some integration testing in python expecially for network programming in twisted (but I want to know something more in general).
There are any good resource I must read, and tools (python tools if possible), practices that introduces me in i... | [
"The recent Pycon had many talks on testing. All of the videos are available on Vimeo and the slides can be downloaded.: http://us.pycon.org/2010/conference/talks/?filter=testing\nSpecifically, I recommend the talk by Ned Batchelder. The other ones are probably good too. (altho' I haven't seen them)\n"
] | [
6
] | [] | [] | [
"integration_testing",
"python"
] | stackoverflow_0003156421_integration_testing_python.txt |
Q:
Upload a file with rest
I created a rest api using django and piston and I need to create a script that uploads a file to that api.
currently I'm using this code:
import urllib
import urllib2
user = 'patrick'
password = 'my_password'
url = 'http://localhost:8000/api/odl/'
password_manager = urllib2.HTTPPasswordM... | Upload a file with rest | I created a rest api using django and piston and I need to create a script that uploads a file to that api.
currently I'm using this code:
import urllib
import urllib2
user = 'patrick'
password = 'my_password'
url = 'http://localhost:8000/api/odl/'
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password... | [
"You should include content of the file as a part of the POST data and modify the headers of the Request, to tell the server that there is a file in the post.\n"
] | [
1
] | [] | [] | [
"file_upload",
"python",
"rest",
"upload"
] | stackoverflow_0003157568_file_upload_python_rest_upload.txt |
Q:
ctypes initializing c_int array by reading file
Using a Python array, I can initialize a 32,487,834 integer array (found in a file HR.DAT) using the following (not perfectly Pythonic, of course) commands:
F = open('HR.DAT','rb')
HR = array('I',F.read())
F.close()
I need to do the same in ctypes. So far the best I... | ctypes initializing c_int array by reading file | Using a Python array, I can initialize a 32,487,834 integer array (found in a file HR.DAT) using the following (not perfectly Pythonic, of course) commands:
F = open('HR.DAT','rb')
HR = array('I',F.read())
F.close()
I need to do the same in ctypes. So far the best I have is:
HR = c_int * 32487834
I'm not sure how to ... | [
"File objects have a 'readinto(..)' method that can be used to fill objects that support the buffer interface.\nSo, something like this should work:\nf = open('hr.dat', 'rb')\narray = (c_int * 32487834)()\nf.readinto(array)\n\n",
"Try something like this to convert array to ctypes array\n>>> from array import arr... | [
11,
1
] | [] | [] | [
"arrays",
"ctypes",
"initialization",
"python"
] | stackoverflow_0003154439_arrays_ctypes_initialization_python.txt |
Q:
What's the best library for video capture in Python on linux?
I want to write an application to video capture from web-cams in linux. Is there a python library to do that?
A:
You should look at Gstreamer and its Python bindings. Here http://pygstdocs.berlios.de/pygst-tutorial/webcam-viewer.html is some sample co... | What's the best library for video capture in Python on linux? | I want to write an application to video capture from web-cams in linux. Is there a python library to do that?
| [
"You should look at Gstreamer and its Python bindings. Here http://pygstdocs.berlios.de/pygst-tutorial/webcam-viewer.html is some sample code to display video from a webcam. To record the video you would have to change the pipeline definition from autovideosink to an encoder and filesink.\n",
"You could look into... | [
3,
1,
1,
0,
0
] | [] | [] | [
"linux",
"python",
"video_capture",
"webcam"
] | stackoverflow_0003155961_linux_python_video_capture_webcam.txt |
Q:
Python: concatenating bytes with a string
I'm working on a python project in 2.6 that also has future support for python 3 being worked in. Specifically I'm working on a digest-md5 algorithm.
In python 2.6 without running this import:
from __future__ import unicode_literals
I am able to write a piece of code... | Python: concatenating bytes with a string | I'm working on a python project in 2.6 that also has future support for python 3 being worked in. Specifically I'm working on a digest-md5 algorithm.
In python 2.6 without running this import:
from __future__ import unicode_literals
I am able to write a piece of code such as this:
a1 = hashlib.md5("%s:%s:%s" % (s... | [
"The reason for the behaviour you observed is that from __future__ import unicode_literals switches the way Python works with strings:\n\nIn the 2.x series, strings without the u prefix are treated as sequences of bytes, each of which may be in the range \\x00-\\xff (inclusive). Strings with the u prefix are ucs-2 ... | [
8,
3
] | [] | [] | [
"md5",
"python",
"string"
] | stackoverflow_0003157529_md5_python_string.txt |
Q:
WxPython: deriving wx.ListItem but wx.ListCtrl only returns old class
I've got a small issue with derived classes, namely wx.ListItem with wx.ListCtrl. I succesfully derived wx.ListItem as a MediaItem, the code is not finished but you get the point:
class MediaItem(wx.ListItem):
def __init__ (self, fullname):... | WxPython: deriving wx.ListItem but wx.ListCtrl only returns old class | I've got a small issue with derived classes, namely wx.ListItem with wx.ListCtrl. I succesfully derived wx.ListItem as a MediaItem, the code is not finished but you get the point:
class MediaItem(wx.ListItem):
def __init__ (self, fullname):
wx.ListItem.__init__(self)
self.fullname = fullname
... | [
"I guess I should just suck it up, and regress to the suboptimal manual bookkeeping. When done tastefully, it's not a big deal but I had higher hopes for wxPython.\nSupposedly (from what I searched and collected) the issue is with the proxy nature of wxPython class base. Were they written in pure Python, or I coded... | [
2
] | [] | [] | [
"listctrl",
"python",
"wxpython"
] | stackoverflow_0003152153_listctrl_python_wxpython.txt |
Q:
Django: ImageField disable image deletion
Greetings
Having an ImageField object in my Foo model as such:
class Foo(models.Model):
name = models.CharField(max_length=50)
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
I want Foo to disable to delete the uploaded photo once a Foo object... | Django: ImageField disable image deletion | Greetings
Having an ImageField object in my Foo model as such:
class Foo(models.Model):
name = models.CharField(max_length=50)
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
I want Foo to disable to delete the uploaded photo once a Foo object is deleted and a specific . How can I do this?... | [
"the best thing is to write a custom File Storage:\nhttp://docs.djangoproject.com/en/dev/howto/custom-file-storage/#howto-custom-file-storage\noverride the delete method and set it the like described in \nhttp://docs.djangoproject.com/en/dev/topics/files/#the-built-in-filesystem-storage-class\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003158272_django_django_models_python.txt |
Q:
Loop Java HashMap like Python Dictionary?
In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:
for k,v in d.iteritems():
print k,v
Is there a way to do this with Java HashMaps?
A:
Yes - for example:
Map<String, String> map = new HashMap<String, String>();
... | Loop Java HashMap like Python Dictionary? | In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:
for k,v in d.iteritems():
print k,v
Is there a way to do this with Java HashMaps?
| [
"Yes - for example:\nMap<String, String> map = new HashMap<String, String>();\n// add entries to the map here\n\nfor (Map.Entry<String, String> entry : map.entrySet()) {\n String k = entry.getKey();\n String v = entry.getValue();\n System.out.printf(\"%s %s\\n\", k, v);\n}\n\n",
"The HashMap.entrySet() w... | [
21,
6,
6,
3,
1
] | [] | [] | [
"equivalent",
"hashmap",
"java",
"python"
] | stackoverflow_0003157558_equivalent_hashmap_java_python.txt |
Q:
Django formsets required
How to make all forms in django formset required? I tried to validate presence of all fields in cleaned_data overriding formset's clean() method but it just fails silently without any error displayed.
Thanks!
Source code:
class BaseScheduleForm(forms.ModelForm):
def __init__(self, *ar... | Django formsets required | How to make all forms in django formset required? I tried to validate presence of all fields in cleaned_data overriding formset's clean() method but it just fails silently without any error displayed.
Thanks!
Source code:
class BaseScheduleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(B... | [
"It's a bit hard to understand where the errors are not being displayed.\nIf is_valid is False, then good, the validation it self is working. Then the next place to look is for the templating layer. How are you checking for errors? {{form.errors}} or {{somefield.errors}}.\nThe way the clean methods are setup here, ... | [
0,
0
] | [] | [] | [
"django",
"forms",
"formset",
"python"
] | stackoverflow_0001636923_django_forms_formset_python.txt |
Q:
Creating/making directories in python (complex)
I am trying to create a bunch of directories/subdirectories that I can copy files into. I am working with Python and I can't seem to find a good way to do this. I have a main path that I will branch off of. Then after that, I have Weights and No_Weights. Male and ... | Creating/making directories in python (complex) | I am trying to create a bunch of directories/subdirectories that I can copy files into. I am working with Python and I can't seem to find a good way to do this. I have a main path that I will branch off of. Then after that, I have Weights and No_Weights. Male and Female following. Within each of Male and Female fol... | [
"import itertools\nimport os\n\ndirs = [[\"Weights\", \"No_Weights\"],\n [\"Male\", \"Female\"],\n [\"Caucasian\", \"African-American\", \"Asian\", \"Hispanic\", \"Indo\", \"Other\", \"Unknown\"], \n [\"B20\", \"20\", \"30\", \"40\", \"50\", \"60\", \"70\"]]\n\nfor item in itertools.product(*di... | [
18,
3,
2,
0,
0
] | [] | [] | [
"directory",
"mkdir",
"python"
] | stackoverflow_0003158921_directory_mkdir_python.txt |
Q:
Do you know any other programming languages that have interactive mode like Python?
Python language has a well known feature named interactive mode where the interpreter can read commands directly from tty.
I typically use this mode to test if a given module is in the classpath or to play around and test some sni... | Do you know any other programming languages that have interactive mode like Python? | Python language has a well known feature named interactive mode where the interpreter can read commands directly from tty.
I typically use this mode to test if a given module is in the classpath or to play around and test some snippets.
Do you know any other programming languages that have Interactive Mode?
If you can... | [
"Most (all?) lisps (including common lisp, scheme and clojure), sml, ocaml, haskell, F#, erlang, scala, ruby, python, lua, groovy, prolog.\n",
"\nPHP can do that too: PHP from the command line\nDoes mySQL count? mySQL Commands\nJavaScript shell in SpiderMonkey (including, but not limited to, Firefox)\n\n",
"bas... | [
26,
5,
5,
5,
5,
5,
3,
3,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"language_agnostic",
"language_features",
"programming_languages",
"python"
] | stackoverflow_0002575219_language_agnostic_language_features_programming_languages_python.txt |
Q:
Logging activity on Django's admin - Django
I need to track/log activity on the Django admin.
I know there are messages stored by admin somewhere, but I don't know how to access them in order to use them as a simple log.
I'm trying to track the following:
User performing the action
Action committed
Datetime of a... | Logging activity on Django's admin - Django | I need to track/log activity on the Django admin.
I know there are messages stored by admin somewhere, but I don't know how to access them in order to use them as a simple log.
I'm trying to track the following:
User performing the action
Action committed
Datetime of action
Thanks guys.
| [
"I had to do something similar and I used something like this:\nfrom django.contrib.admin.models import LogEntry\n\nlogs = LogEntry.objects.all() #or you can filter, etc.\nfor l in logs:\n #perform action\n\nYou can see all of the attributes for LogEntry, but I think the ones you are looking for are l.user, l.ac... | [
31,
17,
5
] | [] | [] | [
"django",
"django_admin",
"logging",
"python"
] | stackoverflow_0003157875_django_django_admin_logging_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.