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:
paths not being consistent python django
I'm trying to import sorl-thumbnail into my app in django. Now the way that I have the site set up, using mod_wsgi on CentOS 5 with cpanel, the path for the apps must have the project name when importing... which is a pain.
Obviously this is a cause of concern with portabil... | paths not being consistent python django | I'm trying to import sorl-thumbnail into my app in django. Now the way that I have the site set up, using mod_wsgi on CentOS 5 with cpanel, the path for the apps must have the project name when importing... which is a pain.
Obviously this is a cause of concern with portability of the app. I'm importing sorl-thumbnail, ... | [
"You shouldn't need to use the project name when importing - just make sure that the apps are somewhere on your python path. Something along the lines of:\nsys.path.append('/etc/django/domains/mydomain.com/myproject/')\n\n... in your .wsgi file should do it (with the path to your own project, of course).\nIdeally r... | [
3
] | [] | [] | [
"django",
"import",
"python",
"sorl_thumbnail"
] | stackoverflow_0001628129_django_import_python_sorl_thumbnail.txt |
Q:
Naming Python loggers
In Django, I've got loggers all over the place, currently with hard-coded names.
For module-level logging (i.e., in a module of view functions) I have the urge to do this.
log = logging.getLogger(__name__)
For class-level logging (i.e., in a class __init__ method) I have the urge to do this.... | Naming Python loggers | In Django, I've got loggers all over the place, currently with hard-coded names.
For module-level logging (i.e., in a module of view functions) I have the urge to do this.
log = logging.getLogger(__name__)
For class-level logging (i.e., in a class __init__ method) I have the urge to do this.
self.log = logging.getLogg... | [
"I typically don't use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple:\nimport logging\nLOG = logging.getLogger(__name__)\n\nAt the top of the module and subsequent:\nLOG.info('Spam and eggs are tasty!')\n\nfrom anywhere in the file typically gets me to where I want... | [
68,
3,
2
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0000401277_django_logging_python.txt |
Q:
Is it possible access other webpages from within another page
Basically, what I'm trying to do is simply make a small script that accesses finds the most recent post in a forum and pulls some text or an image out of it. I have this working in python, using the htmllib module and some regex. But, the script still... | Is it possible access other webpages from within another page | Basically, what I'm trying to do is simply make a small script that accesses finds the most recent post in a forum and pulls some text or an image out of it. I have this working in python, using the htmllib module and some regex. But, the script still isn't very convenient as is, it would be much nicer if I could som... | [
"As Greg mentions, an Ajax solution will not work \"out of the box\" when trying to load from remote servers.\nIf, however, you are trying to load from the same server, it should be fairly straightforward. I'm presenting this answer to show how this could be done using jQuery in just a few lines of code.\n<div id=\... | [
3,
1,
0
] | [] | [] | [
"javascript",
"jquery",
"python"
] | stackoverflow_0001628564_javascript_jquery_python.txt |
Q:
python script to match C function signature in multiple lines
I am reading .c file to look out for functions defined in it and count number of lines in each function.
My problem is that I am unable to look for function name/signature spanned across multiple ines.
I have the list of function names of .c file and ... | python script to match C function signature in multiple lines | I am reading .c file to look out for functions defined in it and count number of lines in each function.
My problem is that I am unable to look for function name/signature spanned across multiple ines.
I have the list of function names of .c file and i am matching the function names of this list with functions in .c ... | [
"I suggest you write a simple parser for the C language.\nOne of the examples in the ANTLR book does something similar to what you're after.\nPyparsing is a very nice Python library for writing parsers.\nHere is a parser for ANSI C: http://code.google.com/p/pycparser/ (written using another Python parser library, P... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001629611_python.txt |
Q:
python: sth like parametrized inheritance
I want my classes X and Y to have a method f(x) which calls a function func(x, y) so that X.f(x) always calls func(x, 1) and Y.f(x) always calls func(x, 2)
class X(object):
def f(self, x):
func(x, 1)
class Y(object):
def f(self, x):
func(x, 2)
But... | python: sth like parametrized inheritance | I want my classes X and Y to have a method f(x) which calls a function func(x, y) so that X.f(x) always calls func(x, 1) and Y.f(x) always calls func(x, 2)
class X(object):
def f(self, x):
func(x, 1)
class Y(object):
def f(self, x):
func(x, 2)
But I want to place f in a common base class B for... | [
"Python is more flexible than you give it credit.\nI think you want something like this:\nclass B(object):\n def f(self,x):\n func(x, self.param)\n\nclass X(B):\n param=1\n\nclass Y(B):\n param=2\n\nNB \n\nnote the method f has self as the\nfirst parameter.\nthe param= lines are class variables.\n\n... | [
6,
1
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0001629597_inheritance_python.txt |
Q:
Python string formatting special characters
How do you make the following code work?
example = "%%(test)%" % {'test':'name',}
print example
Where the desired output is "%name%"
Thanks
A:
An alternative is to use the new Advanced String Formatting
>>> example = "%{test}%".format(test="name")
>>> print example
%n... | Python string formatting special characters | How do you make the following code work?
example = "%%(test)%" % {'test':'name',}
print example
Where the desired output is "%name%"
Thanks
| [
"An alternative is to use the new Advanced String Formatting\n>>> example = \"%{test}%\".format(test=\"name\")\n>>> print example\n%name%\n\n",
"example = \"%%%(test)s%%\" % {'test':'name',}\nprint example\n\n%(key)s is a placeholder for a string identified by key. %% escapes % when using the % operator.\n"
] | [
7,
5
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0001629755_python_string_formatting.txt |
Q:
Are there any known issues with django and multithreading?
I need to develop an app that runs side by side with a django-app.
This will be the first time i develop a multithreaded app that runs next to a django-app so are there any 'gotchas' and 'traps' i should be aware of?
A:
Generally, your Django app already... | Are there any known issues with django and multithreading? | I need to develop an app that runs side by side with a django-app.
This will be the first time i develop a multithreaded app that runs next to a django-app so are there any 'gotchas' and 'traps' i should be aware of?
| [
"Generally, your Django app already is multi-threaded. That's the way most of the standard Django servers operate -- they can tolerate multiple WSGI threads sending requests to them.\nFurther, you'll almost always have Django running under Apache, which is also multi-threaded.\nIf you use mod_wsgi, then Django may... | [
2,
0,
0
] | [] | [] | [
"django",
"multithreading",
"python"
] | stackoverflow_0001629800_django_multithreading_python.txt |
Q:
django flatpage redirects
I want to make sure all of my flatpages have the www subdomain and redirect to it if they don't.
I've looked at some middlewares that redirect to www, but (1), they usually redirect all urls to www and (2), the ones I've found don't work with flatpages.
I don't want all of my site urls... | django flatpage redirects | I want to make sure all of my flatpages have the www subdomain and redirect to it if they don't.
I've looked at some middlewares that redirect to www, but (1), they usually redirect all urls to www and (2), the ones I've found don't work with flatpages.
I don't want all of my site urls to redirect to include the www... | [
"One option is to modify a middleware, so that it only redirects if response.status_code == 404. Put the middleware just before the flatpage middleware in settings.py. This would redirect\nhttp://example.com/flatpage/ -> http://www.example.com/flatpage/\n\nbut also\nhttp://example.com/invalidurl/ -> http://www.exam... | [
0,
0
] | [] | [] | [
"django",
"django_flatpages",
"python"
] | stackoverflow_0001627146_django_django_flatpages_python.txt |
Q:
Alter XML while preserving layout
What would you use to alter an XML-file while preserving as much as possible of layout, including indentation and comments?
My problem is that I have a couple of massive hand-edited XML-files describing a user interface, and now I need to translate several attributes to another la... | Alter XML while preserving layout | What would you use to alter an XML-file while preserving as much as possible of layout, including indentation and comments?
My problem is that I have a couple of massive hand-edited XML-files describing a user interface, and now I need to translate several attributes to another language.
I've tried doing this using Pyt... | [
"Any DOM manipulation module should suite your needs. Layout is just a text data, so it's represented as text nodes in DOM:\n>>> from xml.dom.minidom import parseString\n>>> dom = parseString('''\\\n... <message>\n... <text>\n... Hello!\n... </text>\n... </message>''')\n>>> dom.childNodes[0].childNodes\n[<D... | [
2,
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0001629687_elementtree_python_xml.txt |
Q:
virtualenv confusion
So I open a terminal, cd to my desktop, and run:
virtualenv test_env
I then create the following file in my normal environment:
/home/jesse/.local/lib/python2.6/site-packages/foo_package/__init__.py
This file contains one line:
print "importing from normal env"
In the test_env I create:
/home/... | virtualenv confusion | So I open a terminal, cd to my desktop, and run:
virtualenv test_env
I then create the following file in my normal environment:
/home/jesse/.local/lib/python2.6/site-packages/foo_package/__init__.py
This file contains one line:
print "importing from normal env"
In the test_env I create:
/home/jesse/Desktop/test_env/lib... | [
"You're running into a bug in virtualenv. It has not yet been updated to handle .local directories properly. I've filed an issue for this at the bug tracker.\nUPDATE: this bug is now fixed in virtualenv 1.4.2 and later.\n",
"From the steps you mentioned, it seems you haven't activated the virtual env. Do:\nsource... | [
7,
2,
0,
0
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0001624245_python_virtualenv.txt |
Q:
SAS and Web Data
I have been taking a few graduate classes with a professor I like alot and she raves about SAS all of the time. I "grew up" learning stats using SPSS, and with their recent decisions to integrate their stats engine with R and Python, I find it difficult to muster up the desire to learn anything e... | SAS and Web Data | I have been taking a few graduate classes with a professor I like alot and she raves about SAS all of the time. I "grew up" learning stats using SPSS, and with their recent decisions to integrate their stats engine with R and Python, I find it difficult to muster up the desire to learn anything else. I am not that st... | [
"Incidentally, SAS is now offering integration with R. \nhttp://support.sas.com/rnd/app/studio/Rinterface2.html\nThere are all sorts of ways to get data off the web. One example is to use the url access methods on filename statements to pull in xml data off the web. \nFor example:\nfilename cmap \"yldmap.map\"; /*... | [
6,
5
] | [] | [] | [
"python",
"sas",
"statistics"
] | stackoverflow_0001628372_python_sas_statistics.txt |
Q:
Django Zip upload permission problem
I have few uploads in this app, uploading csv files is working fine.
I have a model that has zip upload in it. Zip file is uploaded, can be viewed, but having issues extracting it.
class Message(models.Model):
uploadFile = models.FileField(_('images file (.zip)'),
... | Django Zip upload permission problem | I have few uploads in this app, uploading csv files is working fine.
I have a model that has zip upload in it. Zip file is uploaded, can be viewed, but having issues extracting it.
class Message(models.Model):
uploadFile = models.FileField(_('images file (.zip)'),
upload_to='mes... | [
"It's not really an issue with the zip file, it's probably an issue with your directory's permissions.\nTake a look at the permissions for /backend/media/new. Is new a folder being created by the zip or is that where you're trying to unzip too? Make sure the groups for the folders also match.\nHere's a great tutori... | [
1,
0
] | [] | [] | [
"django",
"python",
"zip"
] | stackoverflow_0001630427_django_python_zip.txt |
Q:
In django, how to write a query that selects all possible combinations of four integers?
I'm writing a Game Website, where the draw is a series of four digits. e.g 1234
I"m trying to write a query in django that will select all winners based on the four digits entered. winners are any combination of the same numbe... | In django, how to write a query that selects all possible combinations of four integers? | I'm writing a Game Website, where the draw is a series of four digits. e.g 1234
I"m trying to write a query in django that will select all winners based on the four digits entered. winners are any combination of the same numbers or the same combination, 1 2 3 4, 2 3 1 4, 4 1 3 2 are all winners.
how is the most effici... | [
"I'd advise adjusting the code to save the digits so that they are saved in sorted order. E.g. if the user puts in \"5262\" then it should store that as \"2256\". Then, when you select a winning set of digits, you can sort those, and filter by simple equality. This will perform much, much better than trying to c... | [
5,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001631333_django_django_models_python.txt |
Q:
Python: Public methods calling their 'brother' private methods
I have been writing Python code for only a couple of weeks, so I'm still figuring out the lay of the land. But let's say I have a method that MAY be called on by a 'user' on occasion as well as used HEAVILY internally (ie, the arguments have already be... | Python: Public methods calling their 'brother' private methods | I have been writing Python code for only a couple of weeks, so I'm still figuring out the lay of the land. But let's say I have a method that MAY be called on by a 'user' on occasion as well as used HEAVILY internally (ie, the arguments have already been checked before the call). Here is what I am currently doing:
#The... | [
"That is fine. The call to the \"brother\" method is wrong in your code, though. You should do it like this:\n# Now call the 'brother' method that does the real work.\nreturn self._do_something(arg1, arg2, arg3, arg3)\n\nThat is, you should call it \"through\" the self reference, since it's an object method and not... | [
2,
0,
0
] | [
"I'm just learning python myself (and enjoying it) but I think that's the way to do it.\nHowever, the private method should have two underscores and called like 'self.__do_something()'.\n"
] | [
-1
] | [
"methods",
"public_method",
"python"
] | stackoverflow_0001631855_methods_public_method_python.txt |
Q:
How to check if a FileField has been modified in the Admin of Django?
I am trying to do a model with a file that shouldn't be modified. But the comment of the file can be.
Here is what I did, but we cannot modify the comment.
How can I test if a new file (using the browse button) as been sent and in this case only... | How to check if a FileField has been modified in the Admin of Django? | I am trying to do a model with a file that shouldn't be modified. But the comment of the file can be.
Here is what I did, but we cannot modify the comment.
How can I test if a new file (using the browse button) as been sent and in this case only, create a new instance of the model ? If no upload of a new file, update t... | [
"if 'file' in form.changed_data:\n \"\"\"\n File is changed\n \"\"\"\n raise forms.ValidationError(\"No, don't change the file because blah blah\")\nelse:\n \"\"\"\n File is not changed\n \"\"\"\n\n"
] | [
8
] | [] | [] | [
"django",
"django_admin",
"django_file_upload",
"django_forms",
"python"
] | stackoverflow_0001628676_django_django_admin_django_file_upload_django_forms_python.txt |
Q:
How to allow scaling with uniform aspect ratio in (Py)Qt?
If you have a QImage wrapped inside a QLabel, is it possible to scale it up or down when you resize the window and maintain the aspect ratio (so the image doesn't become distorted)? I figured out that it can scale using setScaledContents(), and you can set ... | How to allow scaling with uniform aspect ratio in (Py)Qt? | If you have a QImage wrapped inside a QLabel, is it possible to scale it up or down when you resize the window and maintain the aspect ratio (so the image doesn't become distorted)? I figured out that it can scale using setScaledContents(), and you can set a minimum and maximum size, but the image still loses its aspec... | [
"I'm showing this as C++, which is what the documentation I'm looking at is in. It shouldn't be too difficult to convert to python.\nYou need to create a custom derivative of QLayoutItem, which overrides bool hasHeightForWidth() and int heightForWidth( int width) to preserve the aspect ratio somehow. You could ei... | [
2,
0
] | [] | [] | [
"pyqt",
"python",
"qt",
"user_interface"
] | stackoverflow_0001631574_pyqt_python_qt_user_interface.txt |
Q:
Python LDAP old password still working
I have the LDAP python module installed to authorise logins via active directory, but if I change the password, the new and the old one work together. Does anyone know how to resolve this issue?
A:
I strongly suspect that it is active directory who is caching the credentia... | Python LDAP old password still working | I have the LDAP python module installed to authorise logins via active directory, but if I change the password, the new and the old one work together. Does anyone know how to resolve this issue?
| [
"I strongly suspect that it is active directory who is caching the credentials -at least for some time after the change- ; have a look at this link.\n"
] | [
2
] | [] | [] | [
"authentication",
"ldap",
"python"
] | stackoverflow_0001631739_authentication_ldap_python.txt |
Q:
How to access a forms instance in a modelformset django
In my view I create a formset of photos belonging to a specific article, this works brilliantly, and I am able to render and process the forms. However for the image field I would like to display the already uploaded image. Normally I would access the path th... | How to access a forms instance in a modelformset django | In my view I create a formset of photos belonging to a specific article, this works brilliantly, and I am able to render and process the forms. However for the image field I would like to display the already uploaded image. Normally I would access the path through the instance form.instance.image.get_thumbnail_url howe... | [
"Not sure, but it may be that you don't need instance:\n{% for form in formset.forms %}\n {{ form.image.get_thumbnail_url }}\n{% endfor %}\n\n"
] | [
2
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0001632043_django_django_forms_python.txt |
Q:
Real time update of relative leaderboard for each user among friends
Ive been working on a feature of my application to implement a leaderboard - basically stack rank users according to their score. Im currently tracking the score on an individual basis. My thought is that this leaderboard should be relative ins... | Real time update of relative leaderboard for each user among friends | Ive been working on a feature of my application to implement a leaderboard - basically stack rank users according to their score. Im currently tracking the score on an individual basis. My thought is that this leaderboard should be relative instead of absolute i.e. instead of having the top 10 highest scoring users a... | [
"If writes are very rare compared to reads (a key assumption in most key-value stores, and not just in those;-), then you might prefer to take a time hit when you need to update scores (a write) rather than to get the relative leaderboards (a read). Specifically, when a user's score change, queue up tasks for each... | [
4,
1
] | [] | [] | [
"google_app_engine",
"leaderboard",
"python"
] | stackoverflow_0001628562_google_app_engine_leaderboard_python.txt |
Q:
Parsing XML - right scripting languages / packages for the job?
I know that any language is capable of parsing XML; I'm really just looking for advantages or drawbacks that you may have come across in your own experiences. Perl would be my standard go to here, but I'm open to suggestions.
Thanks!
UPDATE: I ended ... | Parsing XML - right scripting languages / packages for the job? | I know that any language is capable of parsing XML; I'm really just looking for advantages or drawbacks that you may have come across in your own experiences. Perl would be my standard go to here, but I'm open to suggestions.
Thanks!
UPDATE: I ended up going with XML::Simple which did a nice job, but I have one piece ... | [
"XML::Twig is very nice, especially because it’s not as awfully verbose as some of the other options.\n",
"If you are using Perl then I would recommend XML::Simple:\n\nAs more and more Web sites begin using\n XML for their content, it's\n increasingly important for Web\n developers to know how to parse XML\n ... | [
10,
10,
7,
6,
4,
3,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"perl",
"python",
"ruby",
"xml"
] | stackoverflow_0001613042_perl_python_ruby_xml.txt |
Q:
Getting a Python library listed in easy_setup and pip?
Every Python developer is familiar with easy_install and setup tools.
If I want to install a library that's well known, all I have to do is this:
sudo easy_setup install django
Now I have a library that I've written and would love to see widespread. How do yo... | Getting a Python library listed in easy_setup and pip? | Every Python developer is familiar with easy_install and setup tools.
If I want to install a library that's well known, all I have to do is this:
sudo easy_setup install django
Now I have a library that I've written and would love to see widespread. How do you get added to this library list?
| [
"Upload it to PyPI. See the tutorial.\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0001633180_python.txt |
Q:
python re: no such group
I'm newbie in Python. I can't understand why this code does not work:
reOptions = re.search(
"[\s+@twitter\s+(?P<login>\w+):(?P<password>.*?)\s+]",
document_text)
if reOptions:
login = reOptions.group('login')
password = reOptions.group('password')
I'm having an error:
Ind... | python re: no such group | I'm newbie in Python. I can't understand why this code does not work:
reOptions = re.search(
"[\s+@twitter\s+(?P<login>\w+):(?P<password>.*?)\s+]",
document_text)
if reOptions:
login = reOptions.group('login')
password = reOptions.group('password')
I'm having an error:
IndexError: no such group
With do... | [
"You need to escape the brackets [ and ] as \\[ and \\].\n\\[\\s+@twitter\\s+(?P<login>\\w+):(?P<password>.*?)\\s+\\]\n\n",
"The [ and ] are special regular expression characters. Escape them to match literal [ and ].\nSee Regular Expression Syntax.\n"
] | [
4,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001633181_python_regex.txt |
Q:
Using properties defined at a per-instance level not per-class
What I am trying to achieve is something like this:
class object:
def __init__(self):
WidthVariable(self)
print self.width
#Imagine I did this 60frames/1second later
print self.width
#output:
>>0
>>25
What I want ... | Using properties defined at a per-instance level not per-class | What I am trying to achieve is something like this:
class object:
def __init__(self):
WidthVariable(self)
print self.width
#Imagine I did this 60frames/1second later
print self.width
#output:
>>0
>>25
What I want happening (as above): When WidthVariable - a class - is created it a... | [
"Since, as @Jonathan says, descriptors (including properties) are per-class, not per-instance, the only way to get different per-instance descriptors is to have each instance individualize its own class. That's pretty shallow and easy as far as metaprogramming goes;-)...:\nclass Individualistic(object_or_whatever_b... | [
6,
1,
0,
0
] | [] | [] | [
"properties",
"python",
"python_2.6"
] | stackoverflow_0001632170_properties_python_python_2.6.txt |
Q:
Python File Slurp w/ endian conversion
It was recently asked how to do a file slurp in python, and the accepted answer suggested something like:
with open('x.txt') as x: f = x.read()
How would I go about doing this to read the file in and convert the endian representation of the data?
For example, I have a 1GB b... | Python File Slurp w/ endian conversion | It was recently asked how to do a file slurp in python, and the accepted answer suggested something like:
with open('x.txt') as x: f = x.read()
How would I go about doing this to read the file in and convert the endian representation of the data?
For example, I have a 1GB binary file that's just a bunch of single pre... | [
"Slightly modified @Alex Martelli's answer:\narr = numpy.fromfile(filename, numpy.dtype('>f4'))\n# no byteswap is needed regardless of endianess of the machine\n\n",
"with open(fileName, \"rb\") as f:\n arrayName = numpy.fromfile(f, numpy.float32)\narrayName.byteswap(True)\n\nPretty hard to beat for speed AND co... | [
7,
6,
0,
0
] | [] | [] | [
"endianness",
"mmap",
"numpy",
"python",
"struct"
] | stackoverflow_0001632673_endianness_mmap_numpy_python_struct.txt |
Q:
Is a Python closure a good replacement for `__all__`?
Is it a good idea to use a closure instead of __all__ to limit the names exposed by a Python module? This would prevent programmers from accidentally using the wrong name for a module (import urllib; urllib.os.getlogin()) as well as avoiding "from x import *" n... | Is a Python closure a good replacement for `__all__`? | Is it a good idea to use a closure instead of __all__ to limit the names exposed by a Python module? This would prevent programmers from accidentally using the wrong name for a module (import urllib; urllib.os.getlogin()) as well as avoiding "from x import *" namespace pollution as __all__.
def _init_module():
globa... | [
"I am a fan of writing code that is absolutely as brain-dead simple as it can be.\n__all__ is a feature of Python, added explicitly to solve the problem of limiting what names are made visible by a module. When you use it, people immediately understand what you are doing with it.\nYour closure trick is very nonsta... | [
7,
4,
1
] | [] | [] | [
"closures",
"python"
] | stackoverflow_0001632739_closures_python.txt |
Q:
Amazon Web Service ItemSearch DetailPageURL's with Associate IDs?
DetailPageURL's returned by ItemSearch seem to include an incorrect ID/tag rather than the associate ID I requested the search with.
I'm getting:
http://www.amazon.co.uk/gp/product/1590595009?SubscriptionId=XXX&tag=foo-12&linkCode=as2&camp=1634&cre... | Amazon Web Service ItemSearch DetailPageURL's with Associate IDs? | DetailPageURL's returned by ItemSearch seem to include an incorrect ID/tag rather than the associate ID I requested the search with.
I'm getting:
http://www.amazon.co.uk/gp/product/1590595009?SubscriptionId=XXX&tag=foo-12&linkCode=as2&camp=1634&creative=19450&creativeASIN=1590595009
When I expect:
http://www.amazon.... | [
"Simple error in the end..... I was including the tag in the initial search:\n\nfor searchResult in\n ecs.ItemSearch(item,\n SearchIndex=index,\n AssociateTag='wwwmydomain-12')\n\nBut not in the secondary loop that steps through each result getting more details:\n\nfor item in\n ecs.ItemSearch(searchResult.ASIN... | [
2
] | [] | [] | [
"amazon",
"amazon_web_services",
"python"
] | stackoverflow_0001633357_amazon_amazon_web_services_python.txt |
Q:
lambda versus list comprehension performance
I recently posted a question using a lambda function and in a reply someone had mentioned lambda is going out of favor, to use list comprehensions instead. I am relatively new to Python. I ran a simple test:
import time
S=[x for x in range(1000000)]
T=[y**2 for y in ra... | lambda versus list comprehension performance | I recently posted a question using a lambda function and in a reply someone had mentioned lambda is going out of favor, to use list comprehensions instead. I am relatively new to Python. I ran a simple test:
import time
S=[x for x in range(1000000)]
T=[y**2 for y in range(300)]
#
#
time1 = time.time()
N=[x for x in S ... | [
"Your tests are doing very different things. With S being 1M elements and T being 300:\n[x for x in S for y in T if x==y]= 54.875\n\nThis option does 300M equality comparisons.\n \nfilter(lambda x:x in S,T)= 0.391000032425\n\nThis option does 300 linear searches through S.\n \n[val for val in S if val in T]= 12.608... | [
30,
25,
19,
8,
4,
2,
1,
1,
0,
0
] | [] | [] | [
"algorithm",
"lambda",
"list_comprehension",
"python",
"set"
] | stackoverflow_0001632902_algorithm_lambda_list_comprehension_python_set.txt |
Q:
Unix paths that work for any platform in Python?
Can all paths in a Python program use ".." (for the parent directory) and / (for separating path components), and still work whatever the platform?
On one hand, I have never seen such a claim in the documentation (I may have missed it), and the os and os.path module... | Unix paths that work for any platform in Python? | Can all paths in a Python program use ".." (for the parent directory) and / (for separating path components), and still work whatever the platform?
On one hand, I have never seen such a claim in the documentation (I may have missed it), and the os and os.path modules do provide facilities for handling paths in a platfo... | [
"I've never had any problems with using .., although it might be a good idea to convert it to an absolute path using os.path.abspath. Secondly, I would recommend always using os.path.join whereever possible. There are a lot of corner cases (aside from portability issues) in joining paths, and it's good not to hav... | [
11,
6,
3,
3,
3,
1,
0
] | [] | [] | [
"path",
"portability",
"python",
"relative_path"
] | stackoverflow_0001633643_path_portability_python_relative_path.txt |
Q:
GUI + multithreading support + regex support. Which language? JAVA / Python / Ruby?
I'm interested in learning a programming language with support for GUI, multithreading and easy test manipulation (support for regex).
Mainly on Windows but preferably cross-platform. What does the Stack Overflow community suggest?... | GUI + multithreading support + regex support. Which language? JAVA / Python / Ruby? | I'm interested in learning a programming language with support for GUI, multithreading and easy test manipulation (support for regex).
Mainly on Windows but preferably cross-platform. What does the Stack Overflow community suggest?
| [
"My suggestion would be Java. You can do all of that and much more.\n",
"I am a fan of Erlang: \n\nWx GUI tool\nRegex (module regexp)\nCross-platform\nMulti-threading (of course !)\nEUnit testing\n\nOf course Python is really appropriate too!\n",
"If you really like typing go for Java, if you really like whites... | [
5,
1,
1,
0,
0
] | [] | [] | [
"java",
"multithreading",
"python",
"user_interface"
] | stackoverflow_0001624570_java_multithreading_python_user_interface.txt |
Q:
What is the difference between "is" and "==" in python?
Possible Duplicate:
Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?
Is
a == b
the same as
a is b
?
If not, what is the difference?
Edit:
Why does
a = 1
a is 1
return True, but
a = 100.5
a is 100.5
return False?
A:
No, these aren't th... | What is the difference between "is" and "==" in python? |
Possible Duplicate:
Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?
Is
a == b
the same as
a is b
?
If not, what is the difference?
Edit:
Why does
a = 1
a is 1
return True, but
a = 100.5
a is 100.5
return False?
| [
"No, these aren't the same. is is a check for object identity - ie, checking if a and b are exactly the same object. Example:\na = 100.5\na is 100.5 # => False\na == 100.5 # => True\n\na = [1,2,3]\nb = [1,2,3]\na == b # => True\na is b # => False\na = b\na == b # => True\na is b # => True, because if we chang... | [
13,
5
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0001634352_operators_python.txt |
Q:
Inconsistency in ability to access data member of loaded JSON object
I'm loading a JSON string in Django using simplejson, thus:
obj = json.loads('{"name": "joe"}')
person = obj.name
This throws an error:
'dict' object has no attribute 'name'
but when I pass obj down to the view template and print it out via {{ ... | Inconsistency in ability to access data member of loaded JSON object | I'm loading a JSON string in Django using simplejson, thus:
obj = json.loads('{"name": "joe"}')
person = obj.name
This throws an error:
'dict' object has no attribute 'name'
but when I pass obj down to the view template and print it out via {{ obj.name }}, it works! Why?
| [
"I'm not sure how the Django aspect of it works, but the object you get from json.loads is a Python dict object. That means it doesn't have attributes of its keys, but you can access them like you would any other dictionary:\nobj = json.loads('{\"name\": \"joe\"}')\nperson = obj['name']\n\n",
"json.loads loads js... | [
7,
4
] | [] | [] | [
"django",
"python",
"simplejson"
] | stackoverflow_0001634347_django_python_simplejson.txt |
Q:
Please help me in understanding Class in Python
I am newbie and finding it very hard to grasp the syntax of Class in python. I have a background of C/C++, java and objective C. A very big difference which i am noticing in python is that you don't explicitly declare the "data members" in the class and you just rand... | Please help me in understanding Class in Python | I am newbie and finding it very hard to grasp the syntax of Class in python. I have a background of C/C++, java and objective C. A very big difference which i am noticing in python is that you don't explicitly declare the "data members" in the class and you just randomly add them? And it leads to quite big confusion.
L... | [
"In short, Yes.\nYou're right. Python lets you add (and remove!) members from objects at will, at any time. There's nothing special about a constructor that allows it to do anything that other functions can't.\nIf you want to be sure that all instances of your class have the same members at all times, then by all... | [
5,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001634502_python.txt |
Q:
Best way to construct a "complex" data structure in Python
I need to construct a tool that will be used to create field mappings (between tables) in the most automated manner possible.
Here is the deal: imagine a table being appended to other. (lets ignore field type, just for a second...)
CREATE OR REPLACE TABLE ... | Best way to construct a "complex" data structure in Python | I need to construct a tool that will be used to create field mappings (between tables) in the most automated manner possible.
Here is the deal: imagine a table being appended to other. (lets ignore field type, just for a second...)
CREATE OR REPLACE TABLE fooA(
id,
name,
type,
foo)
CREATE OR REPLACE TABLE otherFooTabl... | [
"I'd honestly just take hints from (or use) SQLAlchemy or Django Models. These are tried and true data representation methods.\n",
"Here is a little wrapper class for FooB's to mimic FooA's, but still retain their FooB-ishness.\nfrom collections import namedtuple\n\n# use namedtuple to define some simple classes ... | [
6,
4,
2,
2
] | [] | [] | [
"data_structures",
"list",
"python"
] | stackoverflow_0001632304_data_structures_list_python.txt |
Q:
Advice on set-up/management of the WSGI stack?
After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide way more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find o... | Advice on set-up/management of the WSGI stack? | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide way more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/... | [
"That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match. \nSince you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a Do-It-Yourself Fr... | [
4,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0001633342_python_wsgi.txt |
Q:
ToscaWidgets CalendarDatePicker pylons
How does one set the date on the CalendarDatePicker. i.e. it defaults to current date and I want to display it with another date which I will set from my controller.
I am displaying the CalendarDatePicker widget in a TableForm from tw.form. I have looked at this for a few hou... | ToscaWidgets CalendarDatePicker pylons | How does one set the date on the CalendarDatePicker. i.e. it defaults to current date and I want to display it with another date which I will set from my controller.
I am displaying the CalendarDatePicker widget in a TableForm from tw.form. I have looked at this for a few hours and can't work out how to do this so any ... | [
"I don't have a copy of twforms laying around, but based on their sample code, it looks like you might want to do something like:\nfrom datetime import datetime\n\nstart = twf.CalendarDatePicker('StartDate', date_format = \"%d/%m/%Y\")\nstart.default = datetime.now() # or any valid datetime object\n\nend = twf.Cale... | [
0
] | [] | [] | [
"pylons",
"python",
"toscawidgets"
] | stackoverflow_0001634793_pylons_python_toscawidgets.txt |
Q:
Designing a simple network packet
I'm learning socket programming (in python) and I was wondering what the best/typical way of encapsulating data is? My packets will be used to issue run, stop, configure, etc. commands on the receiving side. Is it helpful to use JSON or just straight text?
A:
I suggest you use ... | Designing a simple network packet | I'm learning socket programming (in python) and I was wondering what the best/typical way of encapsulating data is? My packets will be used to issue run, stop, configure, etc. commands on the receiving side. Is it helpful to use JSON or just straight text?
| [
"I suggest you use a fixed, or mostly fixed format, as this make things easier.\nBy then using features such as the standard library's struct.Struct, with its pack() and umpack() methods, or possibly a slightly more featured pacakges such as Construct, you should have much of the parsing work done for you ;-)\n",
... | [
1,
1,
0,
0
] | [] | [] | [
"network_programming",
"python"
] | stackoverflow_0001633934_network_programming_python.txt |
Q:
Regular expression implementation details
A question that I answered got me wondering:
How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to change?
I thought that regular expressions would be implemented as DFAs, and ... | Regular expression implementation details | A question that I answered got me wondering:
How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to change?
I thought that regular expressions would be implemented as DFAs, and therefore were very efficient (requiring at mos... | [
"Python's re module was based on PCRE, but has moved on to their own implementation.\nHere is the link to the C code.\nIt appears as though the library is based on recursive backtracking when an incorrect path has been taken.\n\nRegular expression and text size n\na?nan matching an\nKeep in mind that this graph is ... | [
21,
8,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000844183_python_regex.txt |
Q:
CGI & Python - return choice to python script
I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision!
Now I have to implement a web interface, ... | CGI & Python - return choice to python script | I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision!
Now I have to implement a web interface, and here comes the problems ... I created an htm fi... | [
"\"Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my \"original\" python module ??\"\nThis is all very simple.\nHowever, you need to read about what the web really is. You need to read up on web servers, browsers and... | [
9,
1,
0,
0,
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0000796906_cgi_python.txt |
Q:
Google app engine ReferenceProperty relationships
I'm trying to get my models related using ReferenceProperty, but not have a huge amount of luck. I have 3 levels: Group, Topic, then Pros, and Cons. As in a Group houses many topics, and within each topic could be many Pros and Cons.
I am able to store new Groups n... | Google app engine ReferenceProperty relationships | I'm trying to get my models related using ReferenceProperty, but not have a huge amount of luck. I have 3 levels: Group, Topic, then Pros, and Cons. As in a Group houses many topics, and within each topic could be many Pros and Cons.
I am able to store new Groups nice and fine, but I don't have any idea how to store to... | [
"Something that has side effects, such as altering the store (by creating a new object for example) should NOT be an HTTP GET -- GET should essentially only do \"read\" operations. This isn't pedantry, it's a key bit of HTTP semantics -- browsers, caches, proxies, etc, are allowed to act on GET as read-only operati... | [
2,
1,
0,
0
] | [] | [] | [
"django_models",
"django_templates",
"google_app_engine",
"model",
"python"
] | stackoverflow_0001210321_django_models_django_templates_google_app_engine_model_python.txt |
Q:
What is wrong with my django's model field?
I am trying to do a PhoneField that convert the value as a standardized value.
In this case, I want to use this clean method.
def clean(self):
phone = self.cleaned_data.get('phone')
# Is it already standardized ?
if phone.startswith('+'):
mo = re.searc... | What is wrong with my django's model field? | I am trying to do a PhoneField that convert the value as a standardized value.
In this case, I want to use this clean method.
def clean(self):
phone = self.cleaned_data.get('phone')
# Is it already standardized ?
if phone.startswith('+'):
mo = re.search(r'^\+\d{2,3}\.\d{9,11}$', phone)
if not ... | [
"You are mixing up the model fields and form fields.\nForm Fields need to be first defined and then corresponding model Fields need to be asked to use those form fields for a model form.\nSee specifying-the-form-field-for-a-model-field documentation \nBasically you need to define a method called formfield on the mo... | [
6,
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0001635392_django_django_forms_python.txt |
Q:
Django forms: making a disabled field persist between validations
At some point I need to display a "disabled" (greyed out by disabled="disabled" attribute) input of type "select". As specified in the standard (xhtml and html4), inputs of type "select" can not have the "readonly" attribute. Note that this is for p... | Django forms: making a disabled field persist between validations | At some point I need to display a "disabled" (greyed out by disabled="disabled" attribute) input of type "select". As specified in the standard (xhtml and html4), inputs of type "select" can not have the "readonly" attribute. Note that this is for presentation purposes only, the actual value must end up in the POST. So... | [
"Browsers don't POST disabled fields.\nYou can try to copy fields initial value to mock_field in your Form's __init__\ndef __init__(self, *args, **kwargs):\n super(SomeForm, self).__init__(*args, **kwargs)\n mock_initial = self.fields['field'].initial\n self.fields['mock_field'].initial = mock_initial\n\nC... | [
3,
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0001596054_django_django_forms_python.txt |
Q:
How to run django development server at startup?
I added following command to Sessions -> Startup program but it didn't work. I'm using Ubuntu.
sudo -u www-data python manage.py 192.168.1.2:8001
192.168.1.2 is the ip address on ath0. Is it still not available for binding at the stage when this command is executed... | How to run django development server at startup? | I added following command to Sessions -> Startup program but it didn't work. I'm using Ubuntu.
sudo -u www-data python manage.py 192.168.1.2:8001
192.168.1.2 is the ip address on ath0. Is it still not available for binding at the stage when this command is executed?
What I currently do is add another cronjob to restar... | [
"Hopefully you're not trying to run the server in a production environment (according to the django docs). Take a look instead at apache with mod_wsgi.\nIf you are just running for local development, there is no need to run as the www-data user. You might want to look into the @reboot directive for cron, and just ... | [
6,
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001634730_django_python.txt |
Q:
Is there any Python module similar to Distributed Ruby
I am new to Python. Just want to know is there any module in python similar to ruby's drb? Like a client can use object provided by the drb server?
A:
This is generally called "object brokering" and a list of some Python packages in this area can be found by... | Is there any Python module similar to Distributed Ruby | I am new to Python. Just want to know is there any module in python similar to ruby's drb? Like a client can use object provided by the drb server?
| [
"This is generally called \"object brokering\" and a list of some Python packages in this area can be found by browsing the Object Brokering topic area of the Python Package Index here.\nThe oldest and most widely used of these is Pyro.\n",
"Pyro does what I think you're discribing (although I've not used drb).\n... | [
6,
2,
1,
0,
0,
0
] | [] | [] | [
"drb",
"python",
"ruby"
] | stackoverflow_0001635558_drb_python_ruby.txt |
Q:
Any hints on programming Dia with Python extensions?
I'm searching for documentation on how to do it properly. Any hints?
A:
if you google "dia python", you'll find https://wiki.gnome.org/Apps/Dia/Python which is a good starting point
| Any hints on programming Dia with Python extensions? | I'm searching for documentation on how to do it properly. Any hints?
| [
"if you google \"dia python\", you'll find https://wiki.gnome.org/Apps/Dia/Python which is a good starting point\n"
] | [
4
] | [] | [] | [
"dia",
"interface",
"python",
"uml",
"visio"
] | stackoverflow_0001635943_dia_interface_python_uml_visio.txt |
Q:
SQLAlchemy declarative concrete autoloaded table inheritance
I've an already existing database and want to access it using SQLAlchemy. Because, the database structure's managed by another piece of code (Django ORM, actually) and I don't want to repeat myself, describing every table structure, I'm using autoload in... | SQLAlchemy declarative concrete autoloaded table inheritance | I've an already existing database and want to access it using SQLAlchemy. Because, the database structure's managed by another piece of code (Django ORM, actually) and I don't want to repeat myself, describing every table structure, I'm using autoload introspection. I'm stuck with a simple concrete table inheritance.
P... | [
"Your table structures are similar to what is used in joint table inheritance, but they certainly don't correspond to concrete table inheritance where all fields of parent class are duplicated in the table of subclass. Right now you have a subclass with less fields than parent and a reference to instance of parent ... | [
4
] | [] | [] | [
"autoload",
"concrete",
"inheritance",
"python",
"sqlalchemy"
] | stackoverflow_0001633447_autoload_concrete_inheritance_python_sqlalchemy.txt |
Q:
Chaining Deferred Tasks with Google App Engine
I have a website I am looking to stay updated with and scrape some content from there every day. I know the site is updated manually at a certain time, and I've set cron schedules to reflect this, but since it is updated manually it could be 10 or even 20 minutes late... | Chaining Deferred Tasks with Google App Engine | I have a website I am looking to stay updated with and scrape some content from there every day. I know the site is updated manually at a certain time, and I've set cron schedules to reflect this, but since it is updated manually it could be 10 or even 20 minutes later.
Right now I have a hack-ish cron update every 5 m... | [
"The example you give should work just fine. You need to add logging to determine if deferred.defer is being called when you think it is. More information would help, too: How is siteHasNotBeenUpdated set?\n"
] | [
2
] | [] | [] | [
"deferred_execution",
"google_app_engine",
"python"
] | stackoverflow_0001630001_deferred_execution_google_app_engine_python.txt |
Q:
Is there a convenient way to alias only conflicting columns when joining tables in SQLAlchemy?
Sometimes it is useful to map a class against a join instead of a single table when using SQLAlchemy's declarative extension. When column names collide, usually in a one-to-many because all primary keys are named id by d... | Is there a convenient way to alias only conflicting columns when joining tables in SQLAlchemy? | Sometimes it is useful to map a class against a join instead of a single table when using SQLAlchemy's declarative extension. When column names collide, usually in a one-to-many because all primary keys are named id by default, you can use .alias() to prefix every column with its table name. That is inconvenient if you... | [
"You can create alias for each column separately with its label() method. So it's possible something similar to the following (not tested):\nfrom sqlalchemy import select\n\ndef alias_dups(join):\n dups = set(col.key for col in join.left.columns) & \\\n set(col.key for col in join.right.columns)\n... | [
5
] | [] | [] | [
"alias",
"join",
"python",
"sqlalchemy"
] | stackoverflow_0001627429_alias_join_python_sqlalchemy.txt |
Q:
Python debugging in Netbeans
I have a problem with debugging Python programs under the Netbeans IDE. When I start debugging, the debugger writes the following log and error. Thank you for help.
[LOG]PythonDebugger : overall Starting
>>>[LOG]PythonDebugger.taskStarted : I am Starting a new Debugging Session ...
[L... | Python debugging in Netbeans | I have a problem with debugging Python programs under the Netbeans IDE. When I start debugging, the debugger writes the following log and error. Thank you for help.
[LOG]PythonDebugger : overall Starting
>>>[LOG]PythonDebugger.taskStarted : I am Starting a new Debugging Session ...
[LOG]This window is an interactive d... | [
"I just installed Python for NetBeans yesterday and hadn't tried the debugger, so just tried it, and I got the same error. So I thought maybe it's a Firewall issue, disabled my Firewall and retried it, and then it worked.\nHowever I restarted the Firewall and now it's still working, so I don't know. I saw the Netbe... | [
1,
1
] | [] | [] | [
"netbeans",
"python"
] | stackoverflow_0001606746_netbeans_python.txt |
Q:
How am I able to assign a value to a literal? ('a' = 10)
def foo(**args):
for k, v in args.items():
print type(k), type(v)
for k, v in args.items():
k = v
print k
print type(k)
foo(a = 10)
foo(**{'a':10})
Gives me
<type 'str'> <type 'int'>
10
<type 'int'>
<type 'str'> <type 'int'>... | How am I able to assign a value to a literal? ('a' = 10) | def foo(**args):
for k, v in args.items():
print type(k), type(v)
for k, v in args.items():
k = v
print k
print type(k)
foo(a = 10)
foo(**{'a':10})
Gives me
<type 'str'> <type 'int'>
10
<type 'int'>
<type 'str'> <type 'int'>
10
<type 'int'>
So I am confused how am I able to do this as... | [
"k is not a string, it is the name of a variable. You can easily do\nk = 'a'\nk = 10\n\nwithout any problem, since an assignment statement in Python will assign the name to point to whichever value is on the right-hand side.\nStrings are immutable, as you mentioned, but this means that as an object, it has no metho... | [
5,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0001636852_python.txt |
Q:
Removing Array Elements in Python while keeping track of their position
I'v got two numpy arrays. The first array contains some zeros (which are distributed randomly over the length of the array), which I would like to remove.
My issue is that I would also like to remove the entries of the second array at the ind... | Removing Array Elements in Python while keeping track of their position | I'v got two numpy arrays. The first array contains some zeros (which are distributed randomly over the length of the array), which I would like to remove.
My issue is that I would also like to remove the entries of the second array at the index positions where the first array elements are zero.
I only came up with a ... | [
"Is it what you want? I am a NumPy newbie. \nIn [1]: import numpy as np\n\nIn [2]: a = np.array([1,2,0,3,0,4])\n\nIn [3]: b = np.array([1,2,3,4,5,6])\n\nIn [4]: b[np.where(a)] \nOut[4]: array([1, 2, 4, 6])\n\nIn [5]: np.where(a) \nOut[5]: (array([0, 1, 3, 5]),)\n\nIn [6]: a[np.where(a)] \nOut[6]: array([1, 2, 3... | [
4,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0001624395_arrays_numpy_python.txt |
Q:
IDLE and unicode chars (2.5.4)
Why does IDLE handle one symbol correctly but not another?
>>> e = '€'
>>> print unichr(ord(e))
# looks like a very thin rectangle on my system.
>>> p = '£'
>>> print unichr(ord(p))
£
>>> ord(e)
128
>>> ord(p)
163
I tried adding various # coding lines, but that didn't help.
EDI... | IDLE and unicode chars (2.5.4) | Why does IDLE handle one symbol correctly but not another?
>>> e = '€'
>>> print unichr(ord(e))
# looks like a very thin rectangle on my system.
>>> p = '£'
>>> print unichr(ord(p))
£
>>> ord(e)
128
>>> ord(p)
163
I tried adding various # coding lines, but that didn't help.
EDIT: browser should be UTF-8, else thi... | [
"The answer depends what encoding the IDLE REPL is using. You should be more explicit about what's actually unicode text, and what's a byte sequence. Meditate on this example:\n# -*- coding: utf-8 -*-\nc = u'€'\nprint type(c)\nfor b in c.encode('utf-8'):\n print ord(b)\n\nc = '€'\nprint type(c)\nfor b in c:\n ... | [
3,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0001637479_python_unicode.txt |
Q:
Unable to query from entities loaded onto the app engine datastore
I am a newbie to python. I am not able to query from the entities- UserDetails and PhoneBook I loaded to the app engine datastore. I have written this UI below based on the youtube video by Brett on "Developing and Deploying applications on GAE" --... | Unable to query from entities loaded onto the app engine datastore | I am a newbie to python. I am not able to query from the entities- UserDetails and PhoneBook I loaded to the app engine datastore. I have written this UI below based on the youtube video by Brett on "Developing and Deploying applications on GAE" -- shoutout application. Well I just tried to do some reverse engineering ... | [
"I recommend that you read the Python documentation of GAE found here.\nSome comments:\n\nTo use your models found in models.py, you either need to use the prefix models. (e.g. models.UserDetails) or import them using\nfrom models import *\nin MyHandler.get() you don't lookup the username get parameter\nTo fetch va... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001636940_google_app_engine_python.txt |
Q:
How to check which XP theme is enabled
I have a wxPython which works perfectly on window xp theme but on switching to 'classic theme' rich text cntrl comes up without border. I can enable border for classic theme but for that
Q1. I need to know if classic theme is enabled.
Q2.I am also not sure how many different... | How to check which XP theme is enabled | I have a wxPython which works perfectly on window xp theme but on switching to 'classic theme' rich text cntrl comes up without border. I can enable border for classic theme but for that
Q1. I need to know if classic theme is enabled.
Q2.I am also not sure how many different theme could be there which may break my app... | [
"Classic theming is more of a non theme.\nYou check for classic theming by calling IsAppThemed() in UxTheme.dll\nThere should therefore be little reason to worry about different themes.\nLastly, the only choice applications get is whether to try and support theming or not - by including a manifest specifying that t... | [
1
] | [] | [] | [
"c",
"python",
"winapi",
"windows",
"windows_themes"
] | stackoverflow_0001637946_c_python_winapi_windows_windows_themes.txt |
Q:
Problem Using Python's subprocess.communicate() on Windows
I have an application that I am trying to control via Python and the subprocess module. Essentially what I do is start the application using Popen (which opens a command prompt within which the program executes) and then at some point in time later on in ... | Problem Using Python's subprocess.communicate() on Windows | I have an application that I am trying to control via Python and the subprocess module. Essentially what I do is start the application using Popen (which opens a command prompt within which the program executes) and then at some point in time later on in the execution I need to send a string (a command) to the STDIN o... | [
"try:\ncmd = 'quit\\n\\r'\n\nEDIT:\nOnly thing that is working for me is:\napp = subprocess.Popen([\"cmd.exe\",\"testparam\"],stdout=subprocess.PIPE,stdin=subprocess.PIPE)\napp.stdin.write('exit\\r\\n')\n\nBecause as documentation says:\n\nPopen.communicate(input=None)\nInteract with process: Send data to\n stdin.... | [
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0001638405_python_subprocess.txt |
Q:
how can i figure if a vim buffer is listed or unlisted from vim's python api?
for a tool i need to figure all vim buffers that are still listed (there are listed and unlisted buffers)
unfortunately vim.buffers contains all buffers and there doesnt seem to be an attribute to figure if a buffer is listed or unlisted... | how can i figure if a vim buffer is listed or unlisted from vim's python api? | for a tool i need to figure all vim buffers that are still listed (there are listed and unlisted buffers)
unfortunately vim.buffers contains all buffers and there doesnt seem to be an attribute to figure if a buffer is listed or unlisted
the vim command of what i want to do is
:buffers
unfortunately all thats possible... | [
"Here is how you can manage this using just Vim language.\nfunction s:buffers_list()\n let result = []\n\n for buffer_number in range(1, bufnr('$'))\n if !buflisted(buffer_number)\n continue\n endif\n\n call add(result, buffer_number)\n endfor\n\n return result\nendfuncti... | [
6,
2
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0000648638_python_vim.txt |
Q:
is there a way to check if a param contains a class or a class instance?
I want the wrapper my_function to be able to receive either a class or class instance, instead of writing two different functions:
>>> from module import MyClass
>>> my_function(MyClass)
True
>>> cls_inst = MyClass()
>>> my_function(cls_i... | is there a way to check if a param contains a class or a class instance? | I want the wrapper my_function to be able to receive either a class or class instance, instead of writing two different functions:
>>> from module import MyClass
>>> my_function(MyClass)
True
>>> cls_inst = MyClass()
>>> my_function(cls_inst)
True
the problem is that I don't know in advance which type of classes ... | [
">>> class A: pass\n\n>>> isinstance(A, type)\nTrue\n>>> isinstance(A(), type)\nFalse\n\n",
"import types\n\ndef myfun(maybe_class):\n if type(maybe_class) == types.ClassType:\n print \"It's a class.\"\n else:\n print \"It's an instance.\"\n\n",
"Use the type() buitlin function.\nE.g.:\nimpo... | [
7,
1,
0
] | [] | [] | [
"python",
"typechecking"
] | stackoverflow_0001638657_python_typechecking.txt |
Q:
Python bitwise operations confusion
I came up with this "magic string" to meet the ID3 tagging specification:
The ID3v2 tag size is encoded with four bytes where the most significant bit (bit 7) is set to zero in every byte, making a total of 28 bits. The zeroed bits are ignored, so a 257 bytes long tag is repres... | Python bitwise operations confusion | I came up with this "magic string" to meet the ID3 tagging specification:
The ID3v2 tag size is encoded with four bytes where the most significant bit (bit 7) is set to zero in every byte, making a total of 28 bits. The zeroed bits are ignored, so a 257 bytes long tag is represented as $00 00 02 01.
>>> hex_val = 0xF... | [
"I think you are confusing the and and the or operations.\n\nbitwise and: return a number with only bits that are in both operands set.\nbitwise or: return a number with bits that are in either of the operands set.\n\n",
"Sorry getting my 7s and Es confused\nCorrected code:\n>>> str.format('0b{0:07b}{1:07b}{2:07b... | [
2,
1,
1
] | [] | [] | [
"bit_manipulation",
"id3",
"python"
] | stackoverflow_0001638604_bit_manipulation_id3_python.txt |
Q:
Google App Engine and google authentication with redirect and HTTP POST
I have a form and I need to send the content to the server.
I use google authentication because only authorized people can send to the server.
The form is somthing like this:
<form action="/blog/submit" method="post">
...
</form>
The authenti... | Google App Engine and google authentication with redirect and HTTP POST | I have a form and I need to send the content to the server.
I use google authentication because only authorized people can send to the server.
The form is somthing like this:
<form action="/blog/submit" method="post">
...
</form>
The authentication is needed only during the submit, not entering the form page. So in th... | [
"No, it's not possible to have POST data follow an HTTP redirect. \nYou should almost certainly be checking for a login before you display the form that's posting this data in the first place, but once the user gets to the form your best bet is probably to save the content to the datastore linked to a session ID y... | [
3
] | [] | [] | [
"authentication",
"google_app_engine",
"post",
"python"
] | stackoverflow_0001638493_authentication_google_app_engine_post_python.txt |
Q:
gobject io monitoring + nonblocking reads
I've got a problem with using the io_add_watch monitor in python (via gobject). I want to do a nonblocking read of the whole buffer after every notification. Here's the code (shortened a bit):
class SomeApp(object):
def __init__(self):
# some other init that does... | gobject io monitoring + nonblocking reads | I've got a problem with using the io_add_watch monitor in python (via gobject). I want to do a nonblocking read of the whole buffer after every notification. Here's the code (shortened a bit):
class SomeApp(object):
def __init__(self):
# some other init that does a lot of stderr debug writes
fl = fcntl.... | [
"This sounds like a race condition in which there is some delay to setting your callback, or else there is a change in the environment which affects whether or not you can set the callback.\nI would look carefully at what happens before you call io_add_watch(). For instance the Python fcntl docs say:\n\nAll functio... | [
2,
0,
0
] | [] | [] | [
"glib",
"gobject",
"input",
"python"
] | stackoverflow_0001586342_glib_gobject_input_python.txt |
Q:
SQLAlchemy: relation in mappers compile result of function rather than calling the function when the relation is queried
I have a number of mappers that look like this:
mapper(Photo,photo_table, properties = { "locale": relation(PhotoContent, uselist=False, primaryjoin=and_(photo_content_table.c.photoId == photo_t... | SQLAlchemy: relation in mappers compile result of function rather than calling the function when the relation is queried | I have a number of mappers that look like this:
mapper(Photo,photo_table, properties = { "locale": relation(PhotoContent, uselist=False, primaryjoin=and_(photo_content_table.c.photoId == photo_table.c.id, photo_content_table.c.locale == get_lang()), foreign_keys=[photo_content_table.c.photoId, photo_content_table.c.loc... | [
"The relation statements gets executed when the class is loaded, which means every function call gets evaluated.\nTry passing the function instead:\nand_(photo_content_table.c.photoId == photo_table.c.id, photo_content_table.c.locale == get_lang)\n\nNote the missing parenthesis. It now should get evaluated whenever... | [
2
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0001638751_pylons_python_sqlalchemy.txt |
Q:
__init__.py descends dirtree for python, but not from c++; causes "import matplotlib" error
Why or how does the file __init__.py cause the python interpreter to search
subdirectories for a module -- and why does the interpreter not honor this
convention when invoked from C++?
Here's what I know:
Using strace on ... | __init__.py descends dirtree for python, but not from c++; causes "import matplotlib" error | Why or how does the file __init__.py cause the python interpreter to search
subdirectories for a module -- and why does the interpreter not honor this
convention when invoked from C++?
Here's what I know:
Using strace on my program, I can see that the same
python2.5 interpreter is being executed for both the interact... | [
"Looking at (a different version # of) python, I see that import.c has the find_init_module(), which is a part of the find_module(). Not evident why find_init_module() is not executed or fails. \n"
] | [
0
] | [] | [] | [
"c++",
"import",
"init",
"path",
"python"
] | stackoverflow_0001634147_c++_import_init_path_python.txt |
Q:
django generic templates
So, Generic views are pretty cool, but what I'm interested in is something that's a generic template.
so for example, I can give it an object and it'll just tostring it for me.
or if I give it a list, it'll just iterate over the objects and tostring them as a ul (or tr, or whatever else it... | django generic templates | So, Generic views are pretty cool, but what I'm interested in is something that's a generic template.
so for example, I can give it an object and it'll just tostring it for me.
or if I give it a list, it'll just iterate over the objects and tostring them as a ul (or tr, or whatever else it deems necessary).
for most us... | [
"If there's a django model for it, you can just stick to django.contrib.admin or django.contrib.databrowse. If not, then you might manage by skipping the django template altogether. example:\nfrom django.http import HttpResponse\nimport datetime\n\ndef current_datetime(request):\n now = datetime.datetime.now()... | [
5,
1
] | [] | [] | [
"django",
"frameworks",
"python",
"templating"
] | stackoverflow_0001638870_django_frameworks_python_templating.txt |
Q:
python: how to generate a bitmap?
What's the easiest way to generate a bitmap using Python?
Text support would be nice but not required.
(On Mac, I was trying to use Quartz through Python, but Snow Leopard seems to have broken its functionality. Therefore I've decided to look for a solid, simple, cross-platform so... | python: how to generate a bitmap? | What's the easiest way to generate a bitmap using Python?
Text support would be nice but not required.
(On Mac, I was trying to use Quartz through Python, but Snow Leopard seems to have broken its functionality. Therefore I've decided to look for a solid, simple, cross-platform solution that won't break each time the O... | [
"Use the Python Imaging Library:\n\"The Python Imaging Library (PIL) adds image processing capabilities to your Python interpreter. This library supports many file formats, and provides powerful image processing and graphics capabilities.\"\nI'm not a Mac person so I can't help with Mac specifics, but I do know it ... | [
7
] | [] | [] | [
"bitmap",
"python"
] | stackoverflow_0001639470_bitmap_python.txt |
Q:
Facebook API registerUsers - Error 100: Invalid email hash
Using PyFacebook I am trying to register a test user of my site with my facebook application. I can connect to the API fine and return a list of friends etc. However when trying to register an address using:
hashed_emails = facebook.hash_email('foo@bar.com... | Facebook API registerUsers - Error 100: Invalid email hash | Using PyFacebook I am trying to register a test user of my site with my facebook application. I can connect to the API fine and return a list of friends etc. However when trying to register an address using:
hashed_emails = facebook.hash_email('foo@bar.com')
accounts = [hashed_emails]
facebook.connect.registerUsers(acc... | [
"Is the hash being stored as the right type?\nAlso, it may be good to store the hash as a separate variable in case there's some strange race condition popping up..\n",
"My request array to the API was incorrectly formatted. It should have been:\nhashed_emails = facebook.hash_email('foo@bar.com')\n\n# Wrong: acco... | [
0,
0
] | [] | [] | [
"facebook",
"python"
] | stackoverflow_0001625742_facebook_python.txt |
Q:
Use javascript to generate a templatetag based on events after document ready?
I am working with the new version of django-threadedcomments and making some progress; it integrates nicely with django's commenting system, however, I'm stuck and not sure how to proceed.
For threaded comments to work, the user needs t... | Use javascript to generate a templatetag based on events after document ready? | I am working with the new version of django-threadedcomments and making some progress; it integrates nicely with django's commenting system, however, I'm stuck and not sure how to proceed.
For threaded comments to work, the user needs to select a comment to "reply to" and then the correct submit form is brought up (wit... | [
"You could do this with Ajax, passing the id of the comment to a dedicated view which just renders the form, but I don't think there's any need. I haven't looked at threaded-comments, but I guess that each comment is of the same object type. Therefore, the only thing that differs in the rendered form would be the i... | [
1
] | [] | [] | [
"ajax",
"django",
"jquery",
"python"
] | stackoverflow_0001639511_ajax_django_jquery_python.txt |
Q:
python line.split semantic error fromtext file
this section of code is supposed to make a list containing the values of the second column in the text file, but it takes the second letter. anyone know what my problem is?
TEXTFILE
opi 60
kid 60
pou 60
ret 60
kai 60
bob 100
for line in lst: ... | python line.split semantic error fromtext file | this section of code is supposed to make a list containing the values of the second column in the text file, but it takes the second letter. anyone know what my problem is?
TEXTFILE
opi 60
kid 60
pou 60
ret 60
kai 60
bob 100
for line in lst:
line.split(' ')
fire.appen... | [
"You probably want to do something like this:\nmylist = []\n\nfor line in file:\n firstcolval, secondcolval = line.split()\n mylist.append(int(firstcolval))\n\n",
"This should also work\nimport csv\nfor line in csv.reader(open(\"datafile\"), delimiter=\" \"): \n fire.append(int(l... | [
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001634117_python_string.txt |
Q:
Running multiple commands simultaneously from python
I want to run three commands at the same time from python. The command format is query.pl -args
Currently I am doing
os.system("query.pl -results '10000' -serverName 'server1' >> log1.txt")
os.system("query.pl -results '10000' -serverName 'server2' >> log2.txt... | Running multiple commands simultaneously from python | I want to run three commands at the same time from python. The command format is query.pl -args
Currently I am doing
os.system("query.pl -results '10000' -serverName 'server1' >> log1.txt")
os.system("query.pl -results '10000' -serverName 'server2' >> log2.txt")
os.system("query.pl -results '10000' -serverName 'serv... | [
"You could use the subprocess module and have all three running independently: use subprocess.Popen. Take care in setting the \"shell\" parameter correctly.\nUse the wait() or poll() method to determine when the subprocesses are finished.\n",
"os.system(\"query.pl -results '10000' -serverName 'server1' &\") \nos... | [
10,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001639912_python.txt |
Q:
urlretrieve returns an empty file
I'm trying to use urlretrieve to download files from urls that take the form:
http://example.com/download.php?id=6456&name=foo
yet for some reason I just get an empty response.
I've tried the method suggested in this question didn't seem to help because
remotefile.info()
doesn't... | urlretrieve returns an empty file | I'm trying to use urlretrieve to download files from urls that take the form:
http://example.com/download.php?id=6456&name=foo
yet for some reason I just get an empty response.
I've tried the method suggested in this question didn't seem to help because
remotefile.info()
doesn't contain the key 'content-disposition',... | [
"Information from manual:\n\ninfo() — return the meta-information\n of the page, such as headers, in the\n form of an httplib.HTTPMessage\n instance (see Quick Reference to HTTP\n Headers)\n\nWhat keys do you have in dict remotefile.info()?\nCan you get a full header information?\n"
] | [
1
] | [] | [] | [
"download",
"python",
"urllib",
"urllib2"
] | stackoverflow_0001639989_download_python_urllib_urllib2.txt |
Q:
Understanding a factorial function in python
I'm trying to understand if the following Python function:
def factorial(i):
if not hasattr(factorial, 'lstFactorial'):
factorial.lstFactorial = [None] * 1000
if factorial.lstFactorial[i] is None:
iProduct = 1
for iFactor in xrange(1, i+1... | Understanding a factorial function in python | I'm trying to understand if the following Python function:
def factorial(i):
if not hasattr(factorial, 'lstFactorial'):
factorial.lstFactorial = [None] * 1000
if factorial.lstFactorial[i] is None:
iProduct = 1
for iFactor in xrange(1, i+1):
iProduct *= iFactor
factori... | [
"here is main algorithm\niProduct = 1\nfor iFactor in xrange(1, i+1):\n iProduct *= iFactor\n\nother code is for caching results.\n",
"Even without knowing Python, it must be clear to you that the two functions are far from identical. The C# version is calculating the factorial via recursion, whereas the Pytho... | [
4,
2,
2,
1,
1,
1
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0001639976_c#_python.txt |
Q:
Calculating average in interchangable range?
I know it's because of n, but n is supposed to be any variable, and left as n, this is what I have:
def average(n):
if n >= 0:
avg = sum((range(1:int(n)))/float(len(range(1:int(n)))))
print avg
how do I fix it?
A:
The summation of x from 1 to n is sim... | Calculating average in interchangable range? | I know it's because of n, but n is supposed to be any variable, and left as n, this is what I have:
def average(n):
if n >= 0:
avg = sum((range(1:int(n)))/float(len(range(1:int(n)))))
print avg
how do I fix it?
| [
"The summation of x from 1 to n is simply (n + 1) * (n / 2). The number of elements being summed is n . Do a little simplification and your new function is\ndef average(n):\n return (n + 1) / 2.0\n\nYou'll have to adjust this if you actually wanted Python's behavior of an exclusive upper-bound for range() (i.e... | [
2,
1,
0
] | [] | [] | [
"average",
"python",
"variables"
] | stackoverflow_0001640145_average_python_variables.txt |
Q:
Web service for an Excel automation script on Windows
I am tasked to develop a very simple web layer for a very complex algorithm that is implemented as an Excel worksheet. This script would be called from a Ruby on Rails app that would be presenting the user with the forms, check validations and whatnot, and sh... | Web service for an Excel automation script on Windows | I am tasked to develop a very simple web layer for a very complex algorithm that is implemented as an Excel worksheet. This script would be called from a Ruby on Rails app that would be presenting the user with the forms, check validations and whatnot, and should return just a number. After perusing this site, my b... | [
"My first choice would be to move the calculations that are in the Excel workbook into my Ruby application code. While it will likely take some additional work, my guess is that it will take less time to port the Excel app to Ruby than introducing layers of complexity on top of Excel. Additionally, calling into E... | [
1
] | [] | [] | [
"automation",
"excel",
"python",
"winapi"
] | stackoverflow_0001640068_automation_excel_python_winapi.txt |
Q:
Django Forms - Can the initial value of one field be dependant on another?
Example, for this form:
class CommentForm(forms.Form):
name = forms.CharField(initial='class')
action = forms.ChoiceField(...)
Can I have the choices in the action field be different depending on what is in the name field?
A:
How... | Django Forms - Can the initial value of one field be dependant on another? | Example, for this form:
class CommentForm(forms.Form):
name = forms.CharField(initial='class')
action = forms.ChoiceField(...)
Can I have the choices in the action field be different depending on what is in the name field?
| [
"How about wrapping initial in a function or a lambda, so that the value of initial is deferred until form creation. Something like:\nclass CommentForm(forms.Form):\n name = forms.CharField(initial=lambda : self.action) # or more complex logic\n action = forms.ChoiceField(...)\n\n"
] | [
3
] | [] | [] | [
"django",
"django_forms",
"forms",
"python"
] | stackoverflow_0001640204_django_django_forms_forms_python.txt |
Q:
python string replacement with % character/**kwargs weirdness
Following code:
def __init__(self, url, **kwargs):
for key in kwargs.keys():
url = url.replace('%%s%' % key, str(kwargs[key]))
Throws the following exception:
File "/home/wells/py-mlb/lib/fetcher.py", line 25, in __init__
url = url.replace(... | python string replacement with % character/**kwargs weirdness | Following code:
def __init__(self, url, **kwargs):
for key in kwargs.keys():
url = url.replace('%%s%' % key, str(kwargs[key]))
Throws the following exception:
File "/home/wells/py-mlb/lib/fetcher.py", line 25, in __init__
url = url.replace('%%s%' % key, str(kwargs[key]))
ValueError: incomplete format
The ... | [
"You probably want the format string %%%s%% instead of %%s%.\nTwo consecutive % signs are interpreted as a literal %, so in your version, you have a literal %, a literal s, and then a lone %, which is expecting a format specifier after it. You need to double up each literal % to not be interpreted as a format stri... | [
15,
3,
1
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0001640487_python_string_formatting.txt |
Q:
How to handle a tokenize error with unterminated multiline comments (python 2.6)
The following sample code:
import token, tokenize, StringIO
def generate_tokens(src):
rawstr = StringIO.StringIO(unicode(src))
tokens = tokenize.generate_tokens(rawstr.readline)
for i, item in enumerate(tokens):
t... | How to handle a tokenize error with unterminated multiline comments (python 2.6) | The following sample code:
import token, tokenize, StringIO
def generate_tokens(src):
rawstr = StringIO.StringIO(unicode(src))
tokens = tokenize.generate_tokens(rawstr.readline)
for i, item in enumerate(tokens):
toktype, toktext, (srow,scol), (erow,ecol), line = item
print i, token.tok_name... | [
"How you handle tokenize errors depends entirely on why you are tokenizing. You code gives you all the valid tokens up until the beginning of the bad string literal. If that token stream is useful to you, then use it. \nYou have a few options about what to do with the error:\n\nYou could ignore it and have an in... | [
2
] | [] | [] | [
"parsing",
"python",
"python_2.6",
"tokenize"
] | stackoverflow_0001640097_parsing_python_python_2.6_tokenize.txt |
Q:
How would one implement Lazy Evaluation in C?
Take for example,
The follow python code:
def multiples_of_2():
i = 0
while True:
i = i + 2
yield i
How do we translate this into C code?
Edit: I am looking to translate this python code into a similar generator in C, with next() function. What I am not lo... | How would one implement Lazy Evaluation in C? | Take for example,
The follow python code:
def multiples_of_2():
i = 0
while True:
i = i + 2
yield i
How do we translate this into C code?
Edit: I am looking to translate this python code into a similar generator in C, with next() function. What I am not looking for is how to create a function in C to outpu... | [
"You could try to encapsulate this in a struct:\ntypedef struct s_generator {\n int current;\n int (*func)(int);\n} generator;\n\nint next(generator* gen) {\n int result = gen->current;\n gen->current = (gen->func)(gen->current);\n return result;\n}\n\nThen you define you multiples with:\nint next_mu... | [
20,
6,
2,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"c",
"python"
] | stackoverflow_0001635827_c_python.txt |
Q:
Python pysqlite2 dbapi2 problem
I'm having an issue with the line:
from pysqlite2 import dbapi2 as sqlite
The error i'm getting is:
ImportError: /usr/lib/python2.4/site-packages/pysqlite2/_sqlite.so: undefined symbol: sqlite3_enable_shared_cache
What can I do to solve this problem?
Thanks!
A:
Sounds like _sqli... | Python pysqlite2 dbapi2 problem | I'm having an issue with the line:
from pysqlite2 import dbapi2 as sqlite
The error i'm getting is:
ImportError: /usr/lib/python2.4/site-packages/pysqlite2/_sqlite.so: undefined symbol: sqlite3_enable_shared_cache
What can I do to solve this problem?
Thanks!
| [
"Sounds like _sqlite.so was compiled against a newer version of sqlite than you have installed. That function wasn't added to SQLite's API until version 3.5.0.\n",
"The easiest way around this problem is to get the AS package Python 2.6 or later from Activestate and install that. It comes with SQLITE in the stan... | [
2,
0
] | [] | [] | [
"linux",
"python",
"sqlite"
] | stackoverflow_0001640537_linux_python_sqlite.txt |
Q:
PyQt: Trouble with asterisk on modification in QPlainTextEdit
I'm having a problem with a QPlainTextEdit. I want the "contents have been modified" asterisk to appear in the title bar whenever the contents have been modified.
In the example below, type a few letters. The asterisk appears as it should. Hit Ctrl+S... | PyQt: Trouble with asterisk on modification in QPlainTextEdit | I'm having a problem with a QPlainTextEdit. I want the "contents have been modified" asterisk to appear in the title bar whenever the contents have been modified.
In the example below, type a few letters. The asterisk appears as it should. Hit Ctrl+S, the asterisk disappears as it should. But then if you type a few... | [
"Never mind, figured it out. The problem was that in the save method I should've been calling self.document().setModified(False) instead of window.setWindowModified(False)\n"
] | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0001640878_pyqt_pyqt4_python_qt_qt4.txt |
Q:
post_save in django to update instance immediately
I'm trying to immediately update a record after it's saved. This example may seem pointless but imagine we need to use an API after the data is saved to get some extra info and update the record:
def my_handler(sender, instance=False, **kwargs):
t = Test.objec... | post_save in django to update instance immediately | I'm trying to immediately update a record after it's saved. This example may seem pointless but imagine we need to use an API after the data is saved to get some extra info and update the record:
def my_handler(sender, instance=False, **kwargs):
t = Test.objects.filter(id=instance.id)
t.blah = 'hello'
t.sav... | [
"When you find yourself using a post_save signal to update an object of the sender class, chances are you should be overriding the save method instead. In your case, the model definition would look like:\nclass Test(models.Model):\n title = models.CharField('title', max_length=200)\n blah = models.CharField('... | [
21,
6
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001640744_django_django_models_python.txt |
Q:
Python Service Custom Command Arguments
I am currently working on a python program which runs as a windows service using win32service and win32serviceutil. The service runs as it should and even after using py2exe, everything is fine (the service monitors target folder(s) and autmotically FTP's newly created files... | Python Service Custom Command Arguments | I am currently working on a python program which runs as a windows service using win32service and win32serviceutil. The service runs as it should and even after using py2exe, everything is fine (the service monitors target folder(s) and autmotically FTP's newly created files to specified FTP location). I would like, ho... | [
"here is a nice example of how to make a service with a custom HandleCommandLine classmethod -- it's part of pyro but has no dependencies on pyro, rather it's a utility \"abstract base class\" that you can subclass and get a service going with minimum fuss by just setting a few things in your subclass. For your sp... | [
3
] | [] | [] | [
"py2exe",
"python",
"windows_services"
] | stackoverflow_0001640255_py2exe_python_windows_services.txt |
Q:
Android: Java v. Python
Is there any reason to favor Python or Java over the other for developing on Android phones, other than the usual Python v. Java issues?
A:
Java is "more native" on the Android platform; Python is coming after and striving to get parity but not quite there yet AFAIK. Roughly the reverse ... | Android: Java v. Python | Is there any reason to favor Python or Java over the other for developing on Android phones, other than the usual Python v. Java issues?
| [
"Java is \"more native\" on the Android platform; Python is coming after and striving to get parity but not quite there yet AFAIK. Roughly the reverse situation wrt App Engine, where Python's been around for a year longer than Java and so is still more mature and complete (even though Java's catching up).\nSo, in ... | [
11,
2,
1
] | [] | [] | [
"android",
"java",
"python"
] | stackoverflow_0001640806_android_java_python.txt |
Q:
Why can't Python find my path? (django)
import sys
sys.path.append('/home/myuser/svn-repos/myproject')
from myproject.settings import *
But, it says module not found when I run the script?
By the way, settings.py has been set up and manage.py syncdb works.
A:
You want sys.path.append('/home/myuser/svn-repos') i... | Why can't Python find my path? (django) | import sys
sys.path.append('/home/myuser/svn-repos/myproject')
from myproject.settings import *
But, it says module not found when I run the script?
By the way, settings.py has been set up and manage.py syncdb works.
| [
"You want sys.path.append('/home/myuser/svn-repos') instead. Then when you import myproject, it looks in svn-repos for the myproject folder, and looks in that for settings.\nAlternatively, leave it as is and just import settings. This is less good because it's less specific and you may end up importing something ot... | [
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001641393_django_python.txt |
Q:
How to permanently append a path to Python for Linux?
I know there are multiple solutions online, but some are for windows, some are environmental variable, etc..
What is the best way?
A:
Find your site-packages directory and create a new file called myproj.pth
Inside that file, put each directory you want to ad... | How to permanently append a path to Python for Linux? | I know there are multiple solutions online, but some are for windows, some are environmental variable, etc..
What is the best way?
| [
"Find your site-packages directory and create a new file called myproj.pth\nInside that file, put each directory you want to add, one per line like so:\n\n/home/myuser/svn-repos/myproject\n/home/myuser/svn-repos/SomeOtherProject\n\nPython loads *.pth every time it runs, and imports all paths in each of those files.... | [
11,
1
] | [] | [] | [
"python"
] | stackoverflow_0001641418_python.txt |
Q:
Checking arguments in numerical Python code
I find myself writing the same argument checking code all the time for number-crunching:
def myfun(a, b):
if a < 0:
raise ValueError('a cannot be < 0 (was a=%s)' % a)
# more if.. raise exception stuff here ...
return a + b
Is there a better way? I wa... | Checking arguments in numerical Python code | I find myself writing the same argument checking code all the time for number-crunching:
def myfun(a, b):
if a < 0:
raise ValueError('a cannot be < 0 (was a=%s)' % a)
# more if.. raise exception stuff here ...
return a + b
Is there a better way? I was told not to use 'assert' for these things (thou... | [
"assert gets optimized away if you run with python -O (modest optimizations, but sometimes nice to have). One preferable alternative if you have patterns that often repeat may be to use decorators -- great way to factor out repetition. E.g., say you have a zillion functions that must be called with arguments by-p... | [
4,
0
] | [
"I'm not sure if this will answer your question, but it strikes me that checking a lot of arguments at the start of a function isn't very pythonic.\nWhat I mean by this is that it is the assumption of most pythonistas that we are all consenting adults, and we trust each other not to do something stupid. Here's how... | [
-1
] | [
"arguments",
"assert",
"exception",
"python"
] | stackoverflow_0001641591_arguments_assert_exception_python.txt |
Q:
Manual garbage collection in Python
Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call gc.collect()? Working in Python 3.0
A:
Per the docs, gc.get_referrers(thatobject) will tell you why the object is still alive (do it right after a gc.collect() to ... | Manual garbage collection in Python | Is there any way to manually remove an object which the garbage collection refuses to get rid of even when I call gc.collect()? Working in Python 3.0
| [
"Per the docs, gc.get_referrers(thatobject) will tell you why the object is still alive (do it right after a gc.collect() to make sure the undesired \"liveness\" is gonna be persistent). After that, it's somehow of a black art;-). You'll often find that some of the referrers are lists (so WHY is that list referri... | [
28,
4,
4,
1
] | [] | [] | [
"garbage_collection",
"python"
] | stackoverflow_0001641717_garbage_collection_python.txt |
Q:
extract grammar features from sentence on Google App Engine
For my GAE app I need to do some natural language processing to extract the subject and object from an input sentence.
Apparently NLTK can't be installed (easily) on GAE so I am looking for another solution.
I noticed GAE comes with Antlr3 but from brows... | extract grammar features from sentence on Google App Engine | For my GAE app I need to do some natural language processing to extract the subject and object from an input sentence.
Apparently NLTK can't be installed (easily) on GAE so I am looking for another solution.
I noticed GAE comes with Antlr3 but from browsing their documentation it solves a different kind of grammar pro... | [
"With regards to the NLTK problem specifically, my solution would probably be to fix the weird imports that NLTK is doing, and use that as originally planned. When you're done, submit a patch of course.\nThat said, if this ultimately involves touching the data store, the answer is that it probably can't be done in... | [
1,
1
] | [] | [] | [
"antlr3",
"google_app_engine",
"nlp",
"python"
] | stackoverflow_0001641635_antlr3_google_app_engine_nlp_python.txt |
Q:
I'm a python beginner, dictionary is new
Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary.
How to think of the solution?
A:
def transitive_dict_join(d1, ... | I'm a python beginner, dictionary is new | Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary.
How to think of the solution?
| [
"def transitive_dict_join(d1, d2):\n result = dict()\n for a, b in d1.iteritems():\n if b in d2:\n result[a] = d2[b]\n return result\n\nYou can express this more concisely, of course, but I think that, for a beginner, spelling things out is clearer and more instructive.\n",
"I agree with Alex, on the n... | [
6,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0001641612_python.txt |
Q:
Regular expression to match alphanumeric string
If string "x" contains any letter or number, print that string.
How to do that using regular expressions?
The code below is wrong
if re.search('^[A-Z]?[a-z]?[0-9]?', i):
print i
A:
re — Regular expression operations
This question is actually rather tricky. ... | Regular expression to match alphanumeric string | If string "x" contains any letter or number, print that string.
How to do that using regular expressions?
The code below is wrong
if re.search('^[A-Z]?[a-z]?[0-9]?', i):
print i
| [
"re — Regular expression operations\nThis question is actually rather tricky. Unfortunately \\w includes _ and [a-z] solutions assume a 26-letter alphabet. With the below solution please read the pydoc where it talks about LOCALE and UNICODE.\n\"[^_\\\\W]\"\n\nNote that since you are only testing for existence, no ... | [
4,
2,
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001642018_python_regex.txt |
Q:
Why do I have so many DeadlineExceededErrors with google-app-engine-django?
I'm using google-app-engine-django to run Django 1.1 on Google App Engine and I'm getting lots and lots of DeadlineExceededErrors, sometimes with . My entire app is quite simple, and it's happening throughout my app, so I suspect that ther... | Why do I have so many DeadlineExceededErrors with google-app-engine-django? | I'm using google-app-engine-django to run Django 1.1 on Google App Engine and I'm getting lots and lots of DeadlineExceededErrors, sometimes with . My entire app is quite simple, and it's happening throughout my app, so I suspect that there is a problem with my basic settings. Any advice would be greatly appreciated!
S... | [
"This is a known bug that occurs intermittently for some apps. We're working on fixing it ASAP.\n"
] | [
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0001639561_django_google_app_engine_python.txt |
Q:
Why do so many apps/frameworks keep their configuration files in an un-executed format?
Many frameworks keep their configuration files in a language different from the rest of the program. Eg, Appengine keeps the configuration in yaml format. to compare, DJango settings.py is a python module. There are many disadv... | Why do so many apps/frameworks keep their configuration files in an un-executed format? | Many frameworks keep their configuration files in a language different from the rest of the program. Eg, Appengine keeps the configuration in yaml format. to compare, DJango settings.py is a python module. There are many disadvantages I can see with this.
If its in same language as rest of the program, I can
Do interes... | [
"Some framework designers feel that the configuration files are inappropriate places for heavy logic. Just as the MVC framework prevents you from putting logic where it does not belong, the configuration file prevents you from putting programming where it does not belong.\nIt's a matter of taste and philosophy. \nT... | [
12,
5,
5,
2
] | [
"It probably just didn't occur to them that they could do it. Many programmers are from the old days where scripting languages were slow and not really more simple than the programming languages (just look at things like Unix shells). When nifty dynamic languages came along, they just stuck to \"text only config fi... | [
-1
] | [
"configuration",
"python",
"settings",
"yaml"
] | stackoverflow_0001642413_configuration_python_settings_yaml.txt |
Q:
Django Form Validation Framework on AppEngine: How to strip out HTML etc.?
I'm using the Django Form Validation Framework on AppEngine (http://code.google.com/appengine/articles/djangoforms.html), like this:
data = MyForm(data=self.request.POST)
if data.is_valid():
entity = data.save(commit=False)
entity... | Django Form Validation Framework on AppEngine: How to strip out HTML etc.? | I'm using the Django Form Validation Framework on AppEngine (http://code.google.com/appengine/articles/djangoforms.html), like this:
data = MyForm(data=self.request.POST)
if data.is_valid():
entity = data.save(commit=False)
entity.put()
I wonder if there's a way to preprocess the POST data (strip out malicio... | [
"Short answer:\nforms.is_valid() auto populates a dictionary forms.cleaned_data by calling a method called clean(). If you want to do any custom validation define your own 'clean_filed_name' that returns the cleaned field value or raises forms.ValidationError(). On error, the corresponding error on the field is aut... | [
2,
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0001422674_django_google_app_engine_python.txt |
Q:
appengine remote api unable to login
When I go to appengine.google.com/a/mydomain.com i am able to login and
see all my apps and administer them.
However, when I try to use the remote_api the same username/password does not work.
I'm using the interactive console code from http://code.google.com/appengine/articles... | appengine remote api unable to login | When I go to appengine.google.com/a/mydomain.com i am able to login and
see all my apps and administer them.
However, when I try to use the remote_api the same username/password does not work.
I'm using the interactive console code from http://code.google.com/appengine/articles/remote_api.html
| [
"This is a known issue with Google Accounts authentication. If you created an app and set it to use Google Accounts for authentication, and you yourself use a Google Apps account, you will not be able to authenticate against your app as an administrator using that account, even if you've created a Google Account fo... | [
6,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001555469_google_app_engine_python.txt |
Q:
General programming question. When to use OOP?
My program needs to do 2 things.
Extract stuff from a webpage.
Do stuff with a webpage.
However, there are many webpages, such as Twitter and Facebook.
should I do this?
def facebookExtract():
code here
def twitterExtract():
code here
def myspaceExtract():
... | General programming question. When to use OOP? | My program needs to do 2 things.
Extract stuff from a webpage.
Do stuff with a webpage.
However, there are many webpages, such as Twitter and Facebook.
should I do this?
def facebookExtract():
code here
def twitterExtract():
code here
def myspaceExtract():
code here
def facebookProcess():
code here
d... | [
"\"My program needs to do 2 things.\"\nWhen you start out like that, the objects cannot be seen. You're perspective isn't right.\nChange your thinking.\n\"My program works with stuff\"\nThat's OO thinking. What \"stuff\" does your program work with? Define the stuff. Those are your basic classes. There's a cla... | [
21,
15,
3,
3,
1,
1
] | [] | [] | [
"function",
"oop",
"python"
] | stackoverflow_0001641470_function_oop_python.txt |
Q:
Logging events in Python; How to log events inside classes?
I built (just for fun) 3 classes to help me log some events in my work.
here are them:
class logMessage:
def __init__(self,objectName,message,messageType):
self.objectName = objectName
self.message = message
self.messageType =... | Logging events in Python; How to log events inside classes? | I built (just for fun) 3 classes to help me log some events in my work.
here are them:
class logMessage:
def __init__(self,objectName,message,messageType):
self.objectName = objectName
self.message = message
self.messageType = messageType
self.dateTime = datetime.datetime.now()
... | [
"Just create an instance of your classes in the module you posted. Then just import your logging module in every file you want to log from and do something like this:\nyourloggingmodule.handler.newLogMessage(...)\n\nWhere handler is the name of the instance you created.\n",
"You could use the Borg pattern, meanin... | [
1,
1
] | [] | [] | [
"global_variables",
"logging",
"oop",
"python"
] | stackoverflow_0001639468_global_variables_logging_oop_python.txt |
Q:
Is a Python Queue needed for simple byte stream between threads?
I have a simple thread that grabs bytes from a Bluetooth RFCOMM (serial-port-like) socket and dumps them into a Queue.Queue (FIFO), which seems like the typical method to exchange data between threads. Works fine.
Is this overkill though? Could I j... | Is a Python Queue needed for simple byte stream between threads? | I have a simple thread that grabs bytes from a Bluetooth RFCOMM (serial-port-like) socket and dumps them into a Queue.Queue (FIFO), which seems like the typical method to exchange data between threads. Works fine.
Is this overkill though? Could I just use a bytearray then have my reader thread .append(somebyte) and t... | [
"With Queue, you're guaranteed to be threadsafe in any implementation and version of Python. Relying on this or that method of some other object being \"atomic\" (in a given implementation and version) typically leaves you at the mercy of this \"atomicity\" not being a strong guarantee (just an implementation artif... | [
3,
0,
0
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0001640112_multithreading_python_queue.txt |
Q:
I want to create this environment variable for everyone, but it does not load during startup? (linux)
I put this at the top, using "sudo vi /etc/profile":
PYTHONPATH=/home/myuser:/home/myotheruser
When I use putty and log in under my username, the python path does not work!
I type "set", and it is there. But, imp... | I want to create this environment variable for everyone, but it does not load during startup? (linux) | I put this at the top, using "sudo vi /etc/profile":
PYTHONPATH=/home/myuser:/home/myotheruser
When I use putty and log in under my username, the python path does not work!
I type "set", and it is there. But, importing things from that directory still does not work.
When I manually do this, then it will work.
EXPORT P... | [
"You need to export the PYTHONPATH even in /etc/profile.\nMake sure you have these lines both in /etc/profile.\nPYTHONPATH=...\nexport PYTHONPATH\n\nAfter that login again.\n"
] | [
4
] | [] | [] | [
"environment_variables",
"linux",
"python",
"unix"
] | stackoverflow_0001642926_environment_variables_linux_python_unix.txt |
Q:
Django 1.1 forms, models and hiding fields
Consider the following Django models:
class Host(models.Model):
# This is the hostname only
name = models.CharField(max_length=255)
class Url(models.Model):
# The complete url
url = models.CharField(max_length=255, db_index=True, unique=True)
# A fore... | Django 1.1 forms, models and hiding fields | Consider the following Django models:
class Host(models.Model):
# This is the hostname only
name = models.CharField(max_length=255)
class Url(models.Model):
# The complete url
url = models.CharField(max_length=255, db_index=True, unique=True)
# A foreign key identifying the host of this url
# ... | [
"Use commit=False:\nresult = form.save(commit=False)\nresult.host = calculate_the_host_from(result)\nresult.save()\n\n",
"You can use exclude and then in the forms \"clean\" method set whatever you want.\nSo in your form:\nclass myform(models.ModelForm):\n class Meta:\n model=Urls\n exclude= (\"fiel... | [
3,
1
] | [] | [] | [
"django",
"forms",
"models",
"python"
] | stackoverflow_0001643171_django_forms_models_python.txt |
Q:
Introspecting a DLL with python
I'm currently trying to do some introspection on a DLL with python. I want to create automatically a graphical test interface based on a DLL.
I can load my DLL in python quite easily and I call some functions. The main problem is if I call "dir" on the object without calling any met... | Introspecting a DLL with python | I'm currently trying to do some introspection on a DLL with python. I want to create automatically a graphical test interface based on a DLL.
I can load my DLL in python quite easily and I call some functions. The main problem is if I call "dir" on the object without calling any method, I've got in result
>>> dir(myLib... | [
"As far as I know, there is no easy way to do this. You have to use some external tool (e.g. link /dump /exports) or use a PE/DLL parser (e.g. pefile).\n"
] | [
2
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0001642938_ctypes_python.txt |
Q:
visualizing id, x, y, t data
I have the following vehicle data
vehicle_id, position_x, position_y, time
The data represents the position of a vehicle at time 't' . The data is also available as a linear reference. I was wondering what's a simple way to visualize the vehicle movement as an animation? I would pref... | visualizing id, x, y, t data | I have the following vehicle data
vehicle_id, position_x, position_y, time
The data represents the position of a vehicle at time 't' . The data is also available as a linear reference. I was wondering what's a simple way to visualize the vehicle movement as an animation? I would prefer a solution that I can integrate... | [
"What kind of animation did you have in mind? You can try PyGame for desktop app. They have a nice tutorial about this.\n",
"I'd imagine its best done on a map; consider integrating (Google) maps with a custom path representing the vehicle.\n",
"Use pygame for it.\n"
] | [
3,
2,
2
] | [] | [] | [
"animation",
"python",
"visualization"
] | stackoverflow_0001643265_animation_python_visualization.txt |
Q:
Folder and file organization for Python development
What is the best way to organize code that belongs to the same project in a Python development environment? What are the do and donts of Python project organization? Do you separate each class in a file?
Project A
Classes
"subsystem1"
class1... | Folder and file organization for Python development | What is the best way to organize code that belongs to the same project in a Python development environment? What are the do and donts of Python project organization? Do you separate each class in a file?
Project A
Classes
"subsystem1"
class1
class2
subsystem1Module
"su... | [
"Some suggestions are at http://jcalderone.livejournal.com/39794.html and http://infinitemonkeycorps.net/docs/pph/\n",
"There are not that many issues that are going to be applicable only to Python. This website: Software Configuration Management Patterns and the associate book describes some Source Code Manageme... | [
9,
1
] | [] | [] | [
"code_organization",
"organization",
"python"
] | stackoverflow_0001642975_code_organization_organization_python.txt |
Q:
Grouping data on year
mydata = [{'date': datetime.datetime(2009, 1, 31, 0, 0), 'value': 14, 'year': u'2009'},
{'date': datetime.datetime(2009, 2, 28, 0, 0), 'value': 84, 'year': u'2009'},
{'date': datetime.datetime(2009, 3, 31, 0, 0), 'value': 77, 'year': u'2009'},
{'date': datetim... | Grouping data on year | mydata = [{'date': datetime.datetime(2009, 1, 31, 0, 0), 'value': 14, 'year': u'2009'},
{'date': datetime.datetime(2009, 2, 28, 0, 0), 'value': 84, 'year': u'2009'},
{'date': datetime.datetime(2009, 3, 31, 0, 0), 'value': 77, 'year': u'2009'},
{'date': datetime.datetime(2009, 4, 30, 0, ... | [
"import datetime\nfrom itertools import groupby\nfrom pprint import pprint\n\nrequired_data={}\nfor k,g in groupby(mydata,key=lambda x: x.get('year')):\n partial={}\n for datum in g:\n partial[datum.get('date').month]=datum \n required_data[k]=[partial.get(m,{}) for m in range(1,13)]\npprint(requ... | [
7
] | [] | [] | [
"json",
"python"
] | stackoverflow_0001643377_json_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.