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:
How can I search for Flickr photos using one parameter (like the name) and get its url using python?
I have the Flickr api key. Any help would be appreciated.
A:
Here is the code that fetches ids of photos for url
#!/usr/bin/env python
from lxml import etree
import urllib
f=urllib.urlopen('http://api.flickr.co... | How can I search for Flickr photos using one parameter (like the name) and get its url using python? | I have the Flickr api key. Any help would be appreciated.
| [
"Here is the code that fetches ids of photos for url\n#!/usr/bin/env python\n\nfrom lxml import etree\nimport urllib\n\nf=urllib.urlopen('http://api.flickr.com/services/rest/?method=flickr.photos.search&text=sometextyousearch&extras=url_sq')\n\ndoc = etree.XML(f.read())\n\nprint [ photo.get('id') for photo in doc.i... | [
2
] | [] | [] | [
"flickr",
"python",
"search"
] | stackoverflow_0008304621_flickr_python_search.txt |
Q:
Raise error with only last line of stack trace
It seems to me that commonly you may want a Python program to print (usually to standard error) only the last line of the stack trace, e.g.:
IOError: Error reading file 'b'plunk'': b'failed to load external entity "plunk"'
I've got this solution:
def print_error(ex:E... | Raise error with only last line of stack trace | It seems to me that commonly you may want a Python program to print (usually to standard error) only the last line of the stack trace, e.g.:
IOError: Error reading file 'b'plunk'': b'failed to load external entity "plunk"'
I've got this solution:
def print_error(ex:Exception, file) -> None:
print('{0}: {1}'.format... | [
"I don't know if there's a better way of doing it, but considering that it's all of 6 lines of code and I can't imagine it takes long to carry out at all, I don't think that you need a better one.\n"
] | [
2
] | [] | [] | [
"exception_handling",
"python",
"python_3.x",
"stack_trace"
] | stackoverflow_0008305246_exception_handling_python_python_3.x_stack_trace.txt |
Q:
Subclassing datetime: Is there a better way to maintain resulting object type after arithmetic operations?
I recently ran into a situatiton where I needed to subclass datetime.datetime and datetime.timedelta in order to add a few methods. I immediately found, though, that any arithmetic operations would return a ... | Subclassing datetime: Is there a better way to maintain resulting object type after arithmetic operations? | I recently ran into a situatiton where I needed to subclass datetime.datetime and datetime.timedelta in order to add a few methods. I immediately found, though, that any arithmetic operations would return a datetime.datetime object when I expected it to return a mydatetime.mydatetime instance instead. Below is the so... | [
"Well, this is the right way to do it (i'd just split the converter method into two). Python allows you to reduce code duplication though:\nfrom datetime import *\n\ndef convproxy(methods,converter):\n def f(cls):\n def _proxyfactory(method):\n def _convproxy(self,*args,**kwargs):\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008304457_python.txt |
Q:
GDB run as subprocess stops parent process after receiving a 'kill -9'
I am running automated tests in python by running a script that runs a batched instance of GDB. If the output meets certain conditions I kill the pid of gdb so I can launch a new instance of GDB. I am running GDB only to log backtraces in cas... | GDB run as subprocess stops parent process after receiving a 'kill -9' | I am running automated tests in python by running a script that runs a batched instance of GDB. If the output meets certain conditions I kill the pid of gdb so I can launch a new instance of GDB. I am running GDB only to log backtraces in case of segfaults. My issue is that killing the GDB instance in the script or ... | [
"\nI am running GDB only to log backtraces in case of segfaults\n\nAlternatives:\n\nglibc's catchsegv / libSegFault.so.\nsegv_handler\nInstall a handler for those signals you're interested in (SIGSEGV,\nSIGABRT, etc.) which launches gstack or gdb, attaches to itself and dumps the relevant trace.\n\n"
] | [
1
] | [] | [] | [
"gdb",
"kill",
"linux",
"python",
"subprocess"
] | stackoverflow_0008302261_gdb_kill_linux_python_subprocess.txt |
Q:
Python Package for Categorizing Keywords
I am looking for a python package for categorizing keywords. I.e. I want to input Baseball and get "Sports and Outdoors". Any suggestions?
A:
Your best bet is probably the natural language toolkit.In particular ntlk.corpus.wordnet
But you will probably want to read up on ... | Python Package for Categorizing Keywords | I am looking for a python package for categorizing keywords. I.e. I want to input Baseball and get "Sports and Outdoors". Any suggestions?
| [
"Your best bet is probably the natural language toolkit.In particular ntlk.corpus.wordnet\nBut you will probably want to read up on some theory so spend some time with the book.\nhttp://www.nltk.org/book\n",
"I am not aware of any python library that categorizes keywords, but here is a simple hack/workaround to m... | [
1,
0
] | [] | [] | [
"keyword",
"python"
] | stackoverflow_0008300488_keyword_python.txt |
Q:
Using Django Admin History with a custom Login_backend and user model
I have a django application using a custom (ldap) login backend and my own extended user model that is used by other applications.
I'm using the django admin extensively but I've only just noticed that the history link leads to a yellow page. I ... | Using Django Admin History with a custom Login_backend and user model | I have a django application using a custom (ldap) login backend and my own extended user model that is used by other applications.
I'm using the django admin extensively but I've only just noticed that the history link leads to a yellow page. I realised that this was due to the fact that I was not using django.contrib.... | [
"You can define what is shown in the history of each model by customizing the history view, or you can simply remove the link from the admin site by overriding the admin templates.\nEither of these are recommended as they are upgrade friendly and don't involve any changes to the django codebase.\nTo use your custom... | [
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0008299720_django_django_admin_python.txt |
Q:
django-socialregistration error on loading button
With django-socialregistration, got following error:
Caught ImportError while rendering: No module named httplib2
Error found in:
<form class="connect-button" name="login" method="post" action="{% url socialregistration:facebook:redirect %}">
How to get this righ... | django-socialregistration error on loading button | With django-socialregistration, got following error:
Caught ImportError while rendering: No module named httplib2
Error found in:
<form class="connect-button" name="login" method="post" action="{% url socialregistration:facebook:redirect %}">
How to get this right?
| [
"Install httplib2. Either:\npip install httplib2\n\nor maybe on a debian-based system (ubuntu):\nsudo apt-get install python-httplib2\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008306271_django_python.txt |
Q:
Python: Extract variables out of namespace
I'm using argparse in python to parse commandline arguments:
parser = ArgumentParser()
parser.add_argument("--a")
parser.add_argument("--b")
parser.add_argument("--c")
args = parser.parse_args()
Now I want to do some calculations with a, b, and c. However, I find it tire... | Python: Extract variables out of namespace | I'm using argparse in python to parse commandline arguments:
parser = ArgumentParser()
parser.add_argument("--a")
parser.add_argument("--b")
parser.add_argument("--c")
args = parser.parse_args()
Now I want to do some calculations with a, b, and c. However, I find it tiresome to write args.a + args.b + args.c all the ... | [
"If you want them as globals, you can do:\nglobals().update(vars(args))\n\nIf you're in a function and want them as local variables of that function, you can do this in Python 2.x as follows:\ndef foo(args):\n locals().update(vars(args)) \n print a, b, c\n return\n exec \"\" # forces Python to use a ... | [
9,
0
] | [] | [] | [
"argparse",
"command_line_arguments",
"python"
] | stackoverflow_0008306171_argparse_command_line_arguments_python.txt |
Q:
why is this test case failing even though both the functions in assertEqual are returning the same value?
why the test case is failing even though both of the functions return the same vaule ?
import unittest
def first():
return 4312
def second():
return 4312
class testcase(unittest.TestCase):
def c... | why is this test case failing even though both the functions in assertEqual are returning the same value? | why the test case is failing even though both of the functions return the same vaule ?
import unittest
def first():
return 4312
def second():
return 4312
class testcase(unittest.TestCase):
def case1(self):
self.assertEqual(first(),second())
def test():
print first(),second()
unittest.ma... | [
"Your test case isn't running because the method in your test case needs to start with the letters \"test\" (e.g., \"test_me()\") to be identified as a test case. Change the name of case1 to test1, and your test will run.\n"
] | [
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0008306169_python_unit_testing.txt |
Q:
Django: how to use reverse() in any class
I have a class file something like myclass.py in project/myapp/myclass.py
how can I use reverse() in there? I can't find any information how to import urlConf! without getting urls, i have exception NoReverseMatch
in fact django-jqgrid using this kind of method in their ex... | Django: how to use reverse() in any class | I have a class file something like myclass.py in project/myapp/myclass.py
how can I use reverse() in there? I can't find any information how to import urlConf! without getting urls, i have exception NoReverseMatch
in fact django-jqgrid using this kind of method in their example: https://github.com/gerry/django-jqgrid
| [
"You can always import django.core.urlresolvers.reverse and pass it necessary args and kwargs to reverse.\nThe reverse defnition is:\nreverse(viewname[, urlconf=None, args=None, kwargs=None, current_app=None])\n\nIn your view you can always do:\nfrom django.core.urlresolvers import reverse\n\ndef myview(request):\n... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008306203_django_python.txt |
Q:
Serialize a single object?
I have a single object I want to serialize:
from django.core import serializers
...
return HttpResponse(serializers.serialize("json", get_object_or_404(Animal, pk=1)), mimetype="application/json")
This throws a "Not Iterable" error, as it seems that it expects that the second param... | Serialize a single object? | I have a single object I want to serialize:
from django.core import serializers
...
return HttpResponse(serializers.serialize("json", get_object_or_404(Animal, pk=1)), mimetype="application/json")
This throws a "Not Iterable" error, as it seems that it expects that the second parameter should be iterable. How can... | [
"You can always wrap the object you want into a list and take back only the first element. Your second argument can be:\n[get_object_or_404(Animal, pk=1),]\n\nand when you deserialize,\nmy_obj = deserialize()[0]\n\n",
"In order to use serializers.serialize you need to pass an iterable (queryset). get_object_or_40... | [
3,
2
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0008305705_django_json_python.txt |
Q:
Django query foreign object that occurs more than once
I am having a hard time putting this question into words, so I apologize. Here's the situation.
I have a table of user's Foursquare Checkins. Each checkin has a foreign key to a location. I'd like to say "Show me all user checkins, sorted by how many times the... | Django query foreign object that occurs more than once | I am having a hard time putting this question into words, so I apologize. Here's the situation.
I have a table of user's Foursquare Checkins. Each checkin has a foreign key to a location. I'd like to say "Show me all user checkins, sorted by how many times they checked into each location, with the checkin count as part... | [
"You just annotate the Checkin model and order it in reverse\nfrom django.db.models import Count\nCheckins.objects.filter(user=my_user).annotate(chkn_count=Count('location')).order_by('-chkn_count')\n\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0008304532_django_django_models_django_queryset_python.txt |
Q:
Segfault with ctypes when returning a struct - 32 bit linux
so I am getting a segfault from ctypes on a 32 bit linux machine that I can't reproduce on 64 bit darwin or linux.
Here is the C:
typedef struct {
void *ptr;
} doodle;
doodle C_intpointerfunction(int *a)
{
*a = 41;
doodle foo;
foo.ptr = a;
re... | Segfault with ctypes when returning a struct - 32 bit linux | so I am getting a segfault from ctypes on a 32 bit linux machine that I can't reproduce on 64 bit darwin or linux.
Here is the C:
typedef struct {
void *ptr;
} doodle;
doodle C_intpointerfunction(int *a)
{
*a = 41;
doodle foo;
foo.ptr = a;
return foo;
}
which is compiled with:
gcc -c intpointerlibrary.c
g... | [
"Not sure why you're setting restype = c_void_p;\nclass DOODLE(Structure):\n _fields_ = [('ptr', c_void_p)]\n_libintpointer.C_intpointerfunction.restype = DOODLE\n\nworks as expected for me, on Linux x86-64.\n"
] | [
5
] | [] | [] | [
"ctypes",
"linux",
"python"
] | stackoverflow_0008304555_ctypes_linux_python.txt |
Q:
When I try to use easy_install, it shows can't decompress data; zlib not available
Possible Duplicate:
Installing Python-2.7 on Ubuntu 10.4
I am using CentOS, which bundled with python 2.4. But python 2.4 didn't come with a lot of new features so I downloaded source of 2.7.
After ./configure, make, make install,... | When I try to use easy_install, it shows can't decompress data; zlib not available |
Possible Duplicate:
Installing Python-2.7 on Ubuntu 10.4
I am using CentOS, which bundled with python 2.4. But python 2.4 didn't come with a lot of new features so I downloaded source of 2.7.
After ./configure, make, make install, when I try to install setuptools or easy_install, it shows "zipimport.ZipImportError: ... | [
"Somehow I found a workaround.\nI noticed the output of make/make install, it did output the zlibmodule.o in the ./Modules directory, but for some reason it did not link the zlibmodule.o into a zlibmodule.so and copy it into lib directory.\nSo I run gcc for myself, get the zlibmodule.so and copied it into /usr/loca... | [
2
] | [] | [] | [
"centos",
"python",
"zlib"
] | stackoverflow_0008297173_centos_python_zlib.txt |
Q:
Sliding sprites
I want my sprite to slide like he's on ice. So if he's on ground then he can walk normally, but when he touches ice he will slide until something stops him.
Does anyone know how one can do that?
Thanks
A:
Manipulate the friction coefficients like the "Sprite Movement Towards a Target" example (mo... | Sliding sprites | I want my sprite to slide like he's on ice. So if he's on ground then he can walk normally, but when he touches ice he will slide until something stops him.
Does anyone know how one can do that?
Thanks
| [
"Manipulate the friction coefficients like the \"Sprite Movement Towards a Target\" example (modified below):\nclass Sprite(pygame.sprite.Sprite):\n ICE = 0.01\n LAND = 1.\n\n def __init__(self):\n # ...\n self.normal_friction = .95 # friction while accelerating\n self.slowing_friction... | [
1
] | [] | [] | [
"pygame",
"python",
"slide",
"sprite"
] | stackoverflow_0008306471_pygame_python_slide_sprite.txt |
Q:
What is wrong with this python list removal loop?
I have been up far too long tonight working on a long program. But I have hit a simple roadblock. Can any one tell me why this code is working the way it is?
I have two lists. I want list2 to only contain numbers that are not in list1.
logically this seems like i... | What is wrong with this python list removal loop? | I have been up far too long tonight working on a long program. But I have hit a simple roadblock. Can any one tell me why this code is working the way it is?
I have two lists. I want list2 to only contain numbers that are not in list1.
logically this seems like it should work. But it doest at all. Why?
list1 = [1,2,... | [
"When you modify a sequence you are iterating over, it will yield unexpected results. I'd do it this way, which takes advantage of fast set operations.\nlist2 = list(set(list2) - set(list1))\n\nWhether this is faster or slower than using a list comprehension depends on the sizes of list1 and list2, and whether you ... | [
9,
5,
1
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0008306606_list_loops_python.txt |
Q:
Python - \n interfering
Hopefully a quick for for this one. I have a script replacing a specific value with a file location. The location unfortunetly seems to quite often contain \n or n\ in (it because the current directory is in the temp folders), causing the line to either break or remove itself from the line ... | Python - \n interfering | Hopefully a quick for for this one. I have a script replacing a specific value with a file location. The location unfortunetly seems to quite often contain \n or n\ in (it because the current directory is in the temp folders), causing the line to either break or remove itself from the line entirely making the folder lo... | [
"If you are specifying the directory name within your script, you should use a raw string literal by prefixing the literal with r. For example, r\"C:\\Users\\Admin\\AppData\\Local\\Temp\\nsfCDAC.tmp\\Firefox\". This will keep the backslashes from being interpreted.\n",
"Your string in memory has plain backslash c... | [
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008306070_python.txt |
Q:
Python documentation: iterable many times?
In documenting a Python function, I find it more Pythonic to say:
def Foo(i):
"""i: An interable containing…"""
…rather than…
def Foo(i):
"""i: A list of …"""
When i really doesn't need to be a list. (Foo will happily operate on a set, tuple, etc.) The problem i... | Python documentation: iterable many times? | In documenting a Python function, I find it more Pythonic to say:
def Foo(i):
"""i: An interable containing…"""
…rather than…
def Foo(i):
"""i: A list of …"""
When i really doesn't need to be a list. (Foo will happily operate on a set, tuple, etc.) The problem is generators. Generators typically only allow 1 ... | [
"I don't know of a standard term for this, at least not offhand, but I think \"reusable iterable\" would get the point across if you need a short phrase.\nIn practice, it's generally possible to structure your function so that you don't need to iterate over i more than once. Alternatively, you can create a list out... | [
2,
1
] | [] | [] | [
"duck_typing",
"python"
] | stackoverflow_0008306465_duck_typing_python.txt |
Q:
Django view works in "shell", but not when imported into existing view
Goal: Display a countdown "clock" immediately after a page is loaded. (FWIW, it's intended to generate a visually loud and clear reminder of an impending deadline)
Platform: Windows
countdown.py:
import datetime, os, time
from Tkinter import *... | Django view works in "shell", but not when imported into existing view | Goal: Display a countdown "clock" immediately after a page is loaded. (FWIW, it's intended to generate a visually loud and clear reminder of an impending deadline)
Platform: Windows
countdown.py:
import datetime, os, time
from Tkinter import *
from sys import exit
root = Tk()
time = ""
clock = Label(root, font=('tim... | [
"The problem seems to be with your urlconf, it could not find the entire view.\n",
"If you comment out root.mainloop() from your code, the error will go away but this is not going to solve your problem of showing a window on the desktop.\nTo do that, you need to have a program on the desktop (perhaps the same pro... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008304044_django_python.txt |
Q:
Python: Parse Text file with '|' to MySql table
I have a text file which has the following structure:
341|18 Hello world|20090225230048AAnhStI|90|$0.30|10|289|2|2|2|Is that foo or
boo bar? 18 |Is it boo foo and foo bar?| |I beleive its foo.|396545163|foo
& bar>foo & boo
Basically each data element is separ... | Python: Parse Text file with '|' to MySql table | I have a text file which has the following structure:
341|18 Hello world|20090225230048AAnhStI|90|$0.30|10|289|2|2|2|Is that foo or
boo bar? 18 |Is it boo foo and foo bar?| |I beleive its foo.|396545163|foo
& bar>foo & boo
Basically each data element is separated by |. I am planning on using a Python script to ... | [
"Your current code is fine. You can also use the csv.reader:\nimport csv\nwith open('datafile.txt', 'rb') as f:\n for row in csv.reader(f, delimiter='|'):\n ...\n\n"
] | [
3
] | [] | [] | [
"extract",
"parsing",
"python",
"text_files"
] | stackoverflow_0008306791_extract_parsing_python_text_files.txt |
Q:
Django - Render a List of File Names to Template
I am generating a template for an image gallery page. My approach is as follows:
Host the images from a sub directory of an images folder
The image folder will be titled the same as the gallery title
The view passes a list of filenames to the template
The templa... | Django - Render a List of File Names to Template | I am generating a template for an image gallery page. My approach is as follows:
Host the images from a sub directory of an images folder
The image folder will be titled the same as the gallery title
The view passes a list of filenames to the template
The template loops through the list and creates img tags
So my ... | [
"Your dictionary is not a valid python code because you are using \"=\" instead of \":\". It should be:\nvariables = RequestContext(request,{\n 'user' : request.user,\n 'title' : 'something',\n 'files' : os.listdir('/path/to/gallery')\n})\n\nOne last thing, listdir expects an abosulte path, you can get the... | [
2,
2
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python",
"twisted"
] | stackoverflow_0008304547_django_django_templates_django_views_python_twisted.txt |
Q:
Independent models relationship
Let's say i have several different models in django project. Now i need to implement reddit-like rating system, that can be easily added to any model in the project. Model look like this:
class Rating(models.Model):
vote = models.IntegerField(blank=False, null=False)
user ... | Independent models relationship | Let's say i have several different models in django project. Now i need to implement reddit-like rating system, that can be easily added to any model in the project. Model look like this:
class Rating(models.Model):
vote = models.IntegerField(blank=False, null=False)
user = models.ForeignKey(User)
The questi... | [
"First (and with the disclaimer that I don't know anything about Reddits rating system), unless you want users to put in ratings from negative millions to positive millions, why not use choices?\nNow to the problem at hand: A model that is rate-able should have a relation that allows many ratings to one model. Unfo... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008306734_django_python.txt |
Q:
Deleting an object from an SQLAlchemy session before it's been persisted
My application allows users to create and delete Site objects. I have implemented this using session.add() and session.delete(). I then have 'Save' and 'Reset' buttons that call session.commit() and session.rollback().
If I add a new Site, th... | Deleting an object from an SQLAlchemy session before it's been persisted | My application allows users to create and delete Site objects. I have implemented this using session.add() and session.delete(). I then have 'Save' and 'Reset' buttons that call session.commit() and session.rollback().
If I add a new Site, then save/commit it, and then delete it, everything goes OK. However, if I try t... | [
"You can Session.expunge() it. I think the rationale with delete() being that way is, it worries you're not keeping track of things if you send it a pending. But I can see the other side of the story on that, I'll think about it. Basically the state implied by delete() includes some assumptions of persiste... | [
19
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0008306506_python_sqlalchemy.txt |
Q:
How to extend SQLite with Python functions in Django?
It's possible to define new SQL functions for SQLite in Python. How can I do this in Django so that the functions are available everywhere?
An example use case is a query which uses the GREATEST() and LEAST() PostgreSQL functions, which are not available in SQL... | How to extend SQLite with Python functions in Django? | It's possible to define new SQL functions for SQLite in Python. How can I do this in Django so that the functions are available everywhere?
An example use case is a query which uses the GREATEST() and LEAST() PostgreSQL functions, which are not available in SQLite. My test suite runs this query, and I'd like to be able... | [
"Here's a Django code example that extends SQLite with GREATEST() and LEAST() methods by calling Python's built-in max() and min():\nfrom django.db.backends.signals import connection_created\nfrom django.dispatch import receiver\n\n@receiver(connection_created)\ndef extend_sqlite(connection=None, **kwargs):\n co... | [
11
] | [] | [] | [
"django",
"python",
"sqlite"
] | stackoverflow_0008307242_django_python_sqlite.txt |
Q:
get logged in user data using facebook api in python and store in mongo database
i have already developed a FB app.now,i am trying to harvest the user data and store it into the database.But, one thing i am not understanding is how to store the data of the logged in user in mongo db using graph api? prior to that ... | get logged in user data using facebook api in python and store in mongo database | i have already developed a FB app.now,i am trying to harvest the user data and store it into the database.But, one thing i am not understanding is how to store the data of the logged in user in mongo db using graph api? prior to that how to fetch data in python?
I know this is repetitive but,i am not able to clear my c... | [
"Assuming that you have access token of the user:\nimport facebook as fb \ngraph = fb.GraphAPI(access_token) \nprofile = graph.get_object(\"me\") \n# if you want to get the user's profile picture (you need to have the session UID) \nprofile.update({\"picture\": \"http://graph.facebook.com/%s/picture?type=large\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008282361_python.txt |
Q:
Python JSON RPC with jQuery - ServiceRequestNotTranslatable
I'm writing a web application using python JSON-RPC implementation - http://json-rpc.org/wiki/python-json-rpc on server side and jQuery axaj API on client side.
This is my first JSON service implementation in python, so I've copied the example from mentio... | Python JSON RPC with jQuery - ServiceRequestNotTranslatable | I'm writing a web application using python JSON-RPC implementation - http://json-rpc.org/wiki/python-json-rpc on server side and jQuery axaj API on client side.
This is my first JSON service implementation in python, so I've copied the example from mentioned site (CGI run on Apache 2.2):
#!/usr/bin/env python
from jso... | [
"This is how to make a JSON RPC call in jQuery:\n$.ajax({url: \"bin/controller.py\",\n type: \"POST\",\n contentType: \"application/json\",\n data: JSON.stringify({\"jsonrpc\": \"2.0\",\n \"method\": \"echo\", \"params\": [\"hello\",], \"id\": 1,\n }),\n dataType: \"json\",\n success: funct... | [
4,
3
] | [] | [] | [
"ajax",
"jquery",
"json_rpc",
"python"
] | stackoverflow_0005903475_ajax_jquery_json_rpc_python.txt |
Q:
Python multiprocessor programming
In python, is there a way to find out which CPU a process is running on? For example if I create different processes for different tasks, using the multiprocessing module, is it possible to identify the core in which each process is running?
A:
Short answer
No, it is not possibl... | Python multiprocessor programming | In python, is there a way to find out which CPU a process is running on? For example if I create different processes for different tasks, using the multiprocessing module, is it possible to identify the core in which each process is running?
| [
"Short answer\nNo, it is not possible.\nLong answer\nin a general situation you cannot do that since processes are not bound to specific cores. \nProcesses do not have fixed CPUs that they are always guaranteed to run on: it is up to the operating system to decide, which core it uses for running a specific process ... | [
3,
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0008307369_multiprocessing_python.txt |
Q:
How to tell Configparser to open the config file, that has the same name, as the module, opening it?
I'm writing a testing framework using Python's unittest. I have separate modules for separate parts of the tested application (part1 - part1.py, part2 - part2.py etc.). I want to create a helper module, which will ... | How to tell Configparser to open the config file, that has the same name, as the module, opening it? | I'm writing a testing framework using Python's unittest. I have separate modules for separate parts of the tested application (part1 - part1.py, part2 - part2.py etc.). I want to create a helper module, which will read configuration settings for each of the modules, with the config file name being the same as the modul... | [
"def module_config(mod):\n '''Loads the config residing next to the module.'''\n import configparser, os.path\n cp = configparser.ConfigParser()\n cp.read_file(open(os.path.splitext(mod.__file__)[0] + '.conf'))\n return cp\n\n# load config for some module\nimport some_module\nmodule_config(some_modul... | [
1
] | [] | [] | [
"configparser",
"python",
"unit_testing"
] | stackoverflow_0008307514_configparser_python_unit_testing.txt |
Q:
Is wx.StaticText thread safe?
For example, I'm using a wx.StaticText object as a counter, is it thread safe? For example:
class TaskFrame(wx.Frame):
def __init__(self):
self.Counter = wx.StaticText(MainPanel, id = -1, label = "0")
What would happen if I GetLabel and SetLabel for self.Counter in differ... | Is wx.StaticText thread safe? | For example, I'm using a wx.StaticText object as a counter, is it thread safe? For example:
class TaskFrame(wx.Frame):
def __init__(self):
self.Counter = wx.StaticText(MainPanel, id = -1, label = "0")
What would happen if I GetLabel and SetLabel for self.Counter in different threads at the same time? Would... | [
"It isn't thread safe. To quote this excellent blog post:\n\nIn the wxPython world, there are three related “threadsafe” methods. If you do not use one of these three when you go to update your user interface, then you may experience weird issues. Sometimes your GUI will work just fine. Other times, it will crash P... | [
2
] | [] | [] | [
"multithreading",
"python",
"thread_safety",
"wxpython"
] | stackoverflow_0008306735_multithreading_python_thread_safety_wxpython.txt |
Q:
Regular expression mismatch in django
I am currently trying to run some tests on a RESTful web service and use the django test client to test the following get request using Client.get:
'/api/browse=ia?filter=General'
These are my urls:
(r'^api/browse=([\w\s]+)$', 'webservice_browse_nofilter')
(r'^api/browse=([... | Regular expression mismatch in django | I am currently trying to run some tests on a RESTful web service and use the django test client to test the following get request using Client.get:
'/api/browse=ia?filter=General'
These are my urls:
(r'^api/browse=([\w\s]+)$', 'webservice_browse_nofilter')
(r'^api/browse=([\w\s]+)\?filter=(\w+)$', 'webservice_browse... | [
"These patterns are technically the same URL, just with different query strings. \nDid you think about consolidating them to a single view, and testing to see if request.GET.get('filter') returns anything?\nI don't think reversing them will do anything -- I believe Django ignores the query string when it processes ... | [
1,
1,
1
] | [] | [] | [
"django",
"python",
"regex"
] | stackoverflow_0008304375_django_python_regex.txt |
Q:
ValueError: Cannot assign in django
I have encountered a problem when I was trying to add/post a data to my models.
this is what i have done in my python manage.py shell:
>>> from booking.models import *
>>> qa = Product.objects.get(id=5)
>>> sd = Booking.objects.create(
... date_select = '2011-11-29',
... product... | ValueError: Cannot assign in django | I have encountered a problem when I was trying to add/post a data to my models.
this is what i have done in my python manage.py shell:
>>> from booking.models import *
>>> qa = Product.objects.get(id=5)
>>> sd = Booking.objects.create(
... date_select = '2011-11-29',
... product_name = qa.name,
... quantity = 1,
... pr... | [
"You assign the product as\nproduct = qa.id\n\nWhile you should do\nproduct = qa\n\n",
"product = qa\n\nUsing ForeingKey you should assing an object, not id.\n"
] | [
8,
6
] | [] | [] | [
"django",
"django_piston",
"python",
"xml"
] | stackoverflow_0008307710_django_django_piston_python_xml.txt |
Q:
Python MySQL connection pooling
I've looked through stackoverflow and can see some oldish posts on this and wondered what the current thinking is about pooling connections in Python for MySQL.
We have a set of python processes that are threading with each thread creating a connection to MySQL. This all works fin... | Python MySQL connection pooling | I've looked through stackoverflow and can see some oldish posts on this and wondered what the current thinking is about pooling connections in Python for MySQL.
We have a set of python processes that are threading with each thread creating a connection to MySQL. This all works fine, but we can have over 150 connectio... | [
"See DBUtils\nMaybe you have an abstract layer for MySQL, you can modify this layer to avoid rewriting all the code.\nIf not, you have to hack your Python-MySQL driver.\n"
] | [
1
] | [] | [] | [
"multithreading",
"mysql",
"pooling",
"process",
"python"
] | stackoverflow_0007709866_multithreading_mysql_pooling_process_python.txt |
Q:
Passing an object to C module, in Python
I ran into a situation with pure python and C python module.
To summarize, how can I accept and manipulate python object in C module?
My python part will look like this.
#!/usr/bin/env python
import os, sys
from c_hello import *
class Hello:
busyH... | Passing an object to C module, in Python | I ran into a situation with pure python and C python module.
To summarize, how can I accept and manipulate python object in C module?
My python part will look like this.
#!/usr/bin/env python
import os, sys
from c_hello import *
class Hello:
busyHello = _sayhello_obj
class Man:
d... | [
"To extract an argument from an invocation of your method, you need to look at the functions documented in Parsing arguments and building values, such as PyArg_ParseTuple. (That's for if you're only taking positional args! There are others for positional-and-keyword args, etc.)\nThe object you get back from PyArg_P... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0008307701_python.txt |
Q:
ItemNotFoundError with select choices in a form using Python mechanize
Here is the form:
<p><label for="version_id">Version</label>
<select id="version_id" name="version_id"><option></option>
<option value="value1">2.1.1</option>
<option value="value2">2.1.2</option>
<option value="value3">2.1.3</option>
<option v... | ItemNotFoundError with select choices in a form using Python mechanize | Here is the form:
<p><label for="version_id">Version</label>
<select id="version_id" name="version_id"><option></option>
<option value="value1">2.1.1</option>
<option value="value2">2.1.2</option>
<option value="value3">2.1.3</option>
<option value="value4">2.1.4</option></select></p>
My python code:
import mechanize
... | [
"Looking a little bit at the API, I think you can use set_value_by_label:\n>>> br.form.set_value(['value2'], name='version_id')\n>>> br.form.set_value_by_label(['2.1.2'], name='version_id')\n>>> br.form['version_id']\n['value2']\n>>> br.form.get_value('version_id')\n['value2']\n>>> br.form.get_value_by_label('versi... | [
0,
0
] | [] | [] | [
"forms",
"html",
"mechanize_python",
"python"
] | stackoverflow_0008307678_forms_html_mechanize_python_python.txt |
Q:
How to Open Schema.sql in the Blog Demo of Tornado?
I am able to execute the chat and similar basic Python projects with
the command prompt, though I do not know yet how to execute a project
with an SQL database.
Can somebody suggest me a way to open the SQL file schema.sql so I can
have a look at the blog demo? ... | How to Open Schema.sql in the Blog Demo of Tornado? | I am able to execute the chat and similar basic Python projects with
the command prompt, though I do not know yet how to execute a project
with an SQL database.
Can somebody suggest me a way to open the SQL file schema.sql so I can
have a look at the blog demo?
I am using Python 2.7 with the recent version of Tornado ... | [
"If you have XAMPP running, the easiest for you would be to go in Php My Admin (http://localhost/phpmyadmin). Then, in the SQL tab, copy-paste the SQL file you want and press OK.\nJust run the Tornado server then, and it should work fine. \n"
] | [
0
] | [] | [] | [
"mysql",
"python",
"sql",
"tornado"
] | stackoverflow_0008266352_mysql_python_sql_tornado.txt |
Q:
Limiting StaticText width
I have a panel with several sizers and some gauges that I want to expand to the size of the area or frame that the panel is placed in which is working fine. I'm experiencing a problem however when a StaticText increases to a size that will be larger than the space available, expanding the... | Limiting StaticText width | I have a panel with several sizers and some gauges that I want to expand to the size of the area or frame that the panel is placed in which is working fine. I'm experiencing a problem however when a StaticText increases to a size that will be larger than the space available, expanding the edges of the panel and the gau... | [
"You you can't wrap the StaticText content, then the only solution I\ncan see is to \"ellipsize\" it, i.e. shortening it by prepending or\nappending \"...\" to the file path. To do that, however, I believe your\nbest bet would be to go owner-drawn (or simply subclass\nwx.lib.stattext), measuring the text size on th... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008302301_python_wxpython.txt |
Q:
Save email attachment (python3, pop3_ssl, gmail)
I'm trying to save email attachment from Google mail account.
AFAIK, it can be done 'walking' the message and getting its payload,
for part in message.walk():
# getting payload, saving attach etc.
but it does not work.
See the whole example below:
def test_sav... | Save email attachment (python3, pop3_ssl, gmail) | I'm trying to save email attachment from Google mail account.
AFAIK, it can be done 'walking' the message and getting its payload,
for part in message.walk():
# getting payload, saving attach etc.
but it does not work.
See the whole example below:
def test_save_attach(self):
self.connection = poplib.POP3_SSL(... | [
"response = self.connection.retr(i+1)\nraw_message = response[1]\n\nraw_message is not a string. retr returns the message as a list of single lines. you are trying to convert the list into a string with str(raw_message) - that doesn't work.\ninstead, join these lines together, eg, replace\nstr_message = email.messa... | [
9
] | [] | [] | [
"email",
"gmail",
"pop3",
"python",
"python_3.x"
] | stackoverflow_0008307809_email_gmail_pop3_python_python_3.x.txt |
Q:
wsgi application is using an older python version
I have deployed a Pyramid app using mod_wsgi.
I have setup the python path in the virtualhost:
WSGIDaemonProcess MyApp user=myUser group=staff threads=4 python-path=/home/myapp/env/lib/python2.7/site-packages
WSGIScriptAlias / /home/myapp/env/pyramid.wsgi
for debu... | wsgi application is using an older python version | I have deployed a Pyramid app using mod_wsgi.
I have setup the python path in the virtualhost:
WSGIDaemonProcess MyApp user=myUser group=staff threads=4 python-path=/home/myapp/env/lib/python2.7/site-packages
WSGIScriptAlias / /home/myapp/env/pyramid.wsgi
for debugging purposes, in pyramid.wsgi, I have also put:
impor... | [
"mod_wsgi doesn't care what version python is. It's built against the Python library itself, so if you want it to use a different version then you need to rebuild it.\n",
"Instead of using apache with mod_wsgi you should look at using a more relevant webserver for python such as gunicorn. Gunicorn is written in... | [
2,
1
] | [] | [] | [
"mod_wsgi",
"python"
] | stackoverflow_0008275900_mod_wsgi_python.txt |
Q:
Django: templatetags pass variable value
I want to pass value of a variable from template to a templatetag but in the token list I get picture.uri as a string [u'thumbnail', u'picture.uri']
{% thumbnail picture.uri %}
Templatetag code:
from django.template import Library
register = Library()
@register.tag()
de... | Django: templatetags pass variable value | I want to pass value of a variable from template to a templatetag but in the token list I get picture.uri as a string [u'thumbnail', u'picture.uri']
{% thumbnail picture.uri %}
Templatetag code:
from django.template import Library
register = Library()
@register.tag()
def thumbnail(parser, token):
...
...
H... | [
"It is very well-documented\nBut I recommend to use some framework for creating tags, I use this.\n"
] | [
3
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0008308599_django_django_templates_python.txt |
Q:
How to make sure a script runs once and only once
I am writing a widget template, which will be included in a page where it is installed.
One may install several of the same kind of widget in one page, so my template may get included several times.
Now I have written some JavaScript to initialize the widget, you k... | How to make sure a script runs once and only once | I am writing a widget template, which will be included in a page where it is installed.
One may install several of the same kind of widget in one page, so my template may get included several times.
Now I have written some JavaScript to initialize the widget, you know, the clickings and hoverings.
My problem is that th... | [
"What about a similar solution to the one that's been used in C to prevent header-files to be included multiple times?\nFor example in the file \"example.html\" you could wrap your code in an if-statement like this:\n<script type=text/javascript>\n if (!window._EXAMPLE_HTML_) {\n window._EXAMPLE_HTML_ = t... | [
5
] | [] | [] | [
"javascript",
"jquery",
"jquery_events",
"mako",
"python"
] | stackoverflow_0008308597_javascript_jquery_jquery_events_mako_python.txt |
Q:
Suggest some projects on parallel computing or HPC
I am in need of doing some projects on parallel computing or HPC , can any one suggest me good projects on that , I prefer to use Python as the programming language, can I use it for these also? Please help me in this. Thanks in advance.
A:
Python and High Perfo... | Suggest some projects on parallel computing or HPC | I am in need of doing some projects on parallel computing or HPC , can any one suggest me good projects on that , I prefer to use Python as the programming language, can I use it for these also? Please help me in this. Thanks in advance.
| [
"Python and High Performance Computing? I would use it only as front-end language for managing and monitoring the system... The actual computations should be done in a more machine-friendly language if performance is what you are seeking.\nAbout problems that are fit to be solved in parallel, as always, those compo... | [
1
] | [] | [] | [
"hpc",
"parallel_processing",
"python"
] | stackoverflow_0008307696_hpc_parallel_processing_python.txt |
Q:
Python: How to consolidate all calender items into a single csv file?
Could anybody suggest a method to 'extract' all outlook calender items into a csv file per each work week (e.g. 10 weeks back)?
Say point of reference is current week.
As an example output:
Week 10
Meeting 1
Meeting 2
Meeting 3
Week 9
Meeting A... | Python: How to consolidate all calender items into a single csv file? | Could anybody suggest a method to 'extract' all outlook calender items into a csv file per each work week (e.g. 10 weeks back)?
Say point of reference is current week.
As an example output:
Week 10
Meeting 1
Meeting 2
Meeting 3
Week 9
Meeting A
Meeting B
Meeting C
and so on till current week, i.e. Week 1.
I have litt... | [
"take a look at http://www.five-ten-sg.com/libpst/ they also have python bindings so you can use the library directly from within python.\n"
] | [
0
] | [] | [] | [
"csv",
"outlook",
"python"
] | stackoverflow_0008307804_csv_outlook_python.txt |
Q:
Efficient way to get the position info of the biggest item in a Python list
Possible Duplicate:
Pythonic way to find maximum value and its index in a list?
Say, in list [2, 3, 6, 9, 2, 3, 1, 5, 7], I want to get 3 (position of item 9) as output.
A similar question but for numpy array
My intuition is to build a t... | Efficient way to get the position info of the biggest item in a Python list |
Possible Duplicate:
Pythonic way to find maximum value and its index in a list?
Say, in list [2, 3, 6, 9, 2, 3, 1, 5, 7], I want to get 3 (position of item 9) as output.
A similar question but for numpy array
My intuition is to build a tuple, and sort the tuple, and get the biggest item's position. I believe there a... | [
"pos = mylist.index(max(mylist))\n\nThis includes all internal python logic - Therefore the best possible implementation.\n",
"Like this:\nlst = [2, 3, 6, 9, 2, 3, 1, 5, 7]\nmaxval = max(lst)\nmaxpos = lst.index(maxval)\n\n"
] | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0008309343_python.txt |
Q:
Python/Tkinter Image and Text label collision
I've been tinkering around with Python lately and wanted to make a GUI that reads from a CSV and displays it correctly.
CSV build up:
name,description,image location
steven,some guy,/res/pic/steven.gif
the first two entries should be put in text labels, and the last en... | Python/Tkinter Image and Text label collision | I've been tinkering around with Python lately and wanted to make a GUI that reads from a CSV and displays it correctly.
CSV build up:
name,description,image location
steven,some guy,/res/pic/steven.gif
the first two entries should be put in text labels, and the last entry should be used as an image.
In my code I got as... | [
"The problem is that you are using grid() and pack() to position widgets within the same master widget (mainGUI). That won't work, because by default both of those geometry managers attempt to manage the size of the parent widget and end up fighting over the size (which blocks the GUI from ever appearing as a side ... | [
3
] | [] | [] | [
"python",
"tk_toolkit",
"tkinter"
] | stackoverflow_0008309251_python_tk_toolkit_tkinter.txt |
Q:
How to do this using regex in python.
A bit confused trying to do a string match that accepts this:
Lets say a string S = "Download" Here, S can be "Download" or "DOWNLOAD" or "DoWNload". Thus, any character in the string can be an uppercase or a lowercase. Its rather easy to write a regex match for all upper case... | How to do this using regex in python. | A bit confused trying to do a string match that accepts this:
Lets say a string S = "Download" Here, S can be "Download" or "DOWNLOAD" or "DoWNload". Thus, any character in the string can be an uppercase or a lowercase. Its rather easy to write a regex match for all upper case or all lower case letters or even a mix of... | [
"To check if \"download\" appears in a string regardless of case, you don't even need a regular expression.\n\"download\" in s.lower()\n\nwill also work fine.\n",
"First, you can covert the string before the match\nre.search(expr, s.lower())\n\nIf you want to ingore the case, you can use flag re.IGNORECASE\nre.se... | [
6,
5,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008309498_python.txt |
Q:
How to Setup PyDev/Eclipse in Lion?
I'm a little bit confused about how to approach this. I had never used OS X before and I don't know how to configure it. After downloading PyDev with Eclipse I go to "Preferences > PyDev > Interpeter - Python > Auto Config" as I would normally do. I select the packages:
image
Bu... | How to Setup PyDev/Eclipse in Lion? | I'm a little bit confused about how to approach this. I had never used OS X before and I don't know how to configure it. After downloading PyDev with Eclipse I go to "Preferences > PyDev > Interpeter - Python > Auto Config" as I would normally do. I select the packages:
image
But then I keep getting this message:
image... | [
"Well, it may have Python installed, but PyDev wants to be able to view the source of the python files to enable autocompletion.\nInstall Xcode, yeah. Xcode ships with the developer version of Python, which includes all those .py files. I'm fairly sure that you don't actually need to build Python from scratch (I ne... | [
0,
0
] | [] | [] | [
"eclipse",
"osx_lion",
"pydev",
"python"
] | stackoverflow_0008279429_eclipse_osx_lion_pydev_python.txt |
Q:
Python replacing characters selectively from a string
I have a string which contains a fixed character. Can I generate a permutation of strings by replacing it with another character or string??
Say, I have something like this:
designatedstring="u"
replacerstring="ough"
s="thruput"
I want an output like:
l=["thr... | Python replacing characters selectively from a string | I have a string which contains a fixed character. Can I generate a permutation of strings by replacing it with another character or string??
Say, I have something like this:
designatedstring="u"
replacerstring="ough"
s="thruput"
I want an output like:
l=["throughput","thrupought","throughpought"]
Is there any way to... | [
"More itertools sugar:\n>>> parts = s.split(designatedstring)\n>>> num = len(parts) - 1\n>>> replacements = itertools.product([designatedstring, replacerstring], repeat=num)\n>>> replacements = list(replacements)\n>>> replacements.remove((designatedstring,) * num)\n>>> for r in replacements:\n... print ''.join(... | [
4,
0
] | [
"From the input given in your question, this will produce the list requested:\ns=\"thruput\"\ndesignatedstring=\"u\"\nreplacerstring=\"ough\"\n\nl = []\nfor i in range(len(s)):\n if s[i] == designatedstring:\n l += [s[:i] + replacerstring + s[i + 1:]]\n\nl += [s.replace(designatedstring, replacerstring)]\... | [
-1
] | [
"python",
"regex",
"string"
] | stackoverflow_0008308058_python_regex_string.txt |
Q:
Configuring PyDev for Eclipse in Mac X Lion
Mac's default Python client is v2.7. How can i configure PyDev for Eclipse to use 3.2 instead? I cannot find the interpreter for Python 3.2.
A:
Install a new python version from http://python.org and when configuring PyDev, point to that version (ideally, never use a... | Configuring PyDev for Eclipse in Mac X Lion | Mac's default Python client is v2.7. How can i configure PyDev for Eclipse to use 3.2 instead? I cannot find the interpreter for Python 3.2.
| [
"Install a new python version from http://python.org and when configuring PyDev, point to that version (ideally, never use any installed version already in the system and always download and use the version from http://python.org for development purposes as Mac versions are not suitable for development as they don'... | [
0
] | [] | [] | [
"eclipse",
"macos",
"pydev",
"python",
"python_3.x"
] | stackoverflow_0008290657_eclipse_macos_pydev_python_python_3.x.txt |
Q:
Send fake Return key key presses to QPlainTextEdit
I'm trying to write some unittests for my QPlainTextEdit based widget, so I need to send fake key presses to it.
I can successfully send ordinary a-z key presses, but when I try to send a new line my keyPressEvent handler doesn't receive the key press.
In the code... | Send fake Return key key presses to QPlainTextEdit | I'm trying to write some unittests for my QPlainTextEdit based widget, so I need to send fake key presses to it.
I can successfully send ordinary a-z key presses, but when I try to send a new line my keyPressEvent handler doesn't receive the key press.
In the code below the first sendEvent is working fine, but the seco... | [
"Would\nglobal_objects.app.sendEvent(editor,\n QtGui.QKeyEvent(QtCore.QEvent.KeyPress, QtCore.Qt.Key_Return,\n QtCore.Qt.NoModifier, '\\n'))\n\nwork? (Note the extra argument to QtGui.QKeyEvent.)\n",
"Putting word \"Return\" into the QKeyEvent constructor's text parameter should do the trick. Pls, check if ... | [
0,
0,
0
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0004844252_pyqt_python_qt.txt |
Q:
Python Appengine Mapreduce gives Bad Entity Kind on run
I've been struggling with this for hours...
In my project, I have my models.py defined in folder "project", under the main root. I also have the mapreduce files in folder "mapreduce", inside the "project" folder. Files system looks like:
Main Root
-Project ... | Python Appengine Mapreduce gives Bad Entity Kind on run | I've been struggling with this for hours...
In my project, I have my models.py defined in folder "project", under the main root. I also have the mapreduce files in folder "mapreduce", inside the "project" folder. Files system looks like:
Main Root
-Project folder
-> models.py
-> Mapreduce folder
I have the mapr... | [
"Same issue here, re-arranging works, but I can't now rearrange my folder structure. In my case, I have a _init_.py under the \"projects\" directory. Also tried to add a _init_.py under the root directory where app.yaml and mapreduce.yaml reside (to no avail)\nStrangely, my error is different. Using your example, i... | [
1
] | [] | [] | [
"google_app_engine",
"mapreduce",
"python"
] | stackoverflow_0005813293_google_app_engine_mapreduce_python.txt |
Q:
Adding support for flair to reddit_api
I'm trying to add support for reddit flair api to reddit_api, but I don't seem to be getting anywhere.
I've added the following to urls.py:
("api/", {
...
"flair": "flair/"
}),
And the following to reddit.py:
@require_login
def set_flair(... | Adding support for flair to reddit_api | I'm trying to add support for reddit flair api to reddit_api, but I don't seem to be getting anywhere.
I've added the following to urls.py:
("api/", {
...
"flair": "flair/"
}),
And the following to reddit.py:
@require_login
def set_flair(self, subreddit, user, text='', css_class=''... | [
"Here is a working set_flair function:\n@require_login\ndef set_flair(self, subreddit, user, text='', css_class=''):\n \"\"\"Set flair of user in given subreddit\"\"\"\n url = urls[\"flair\"]\n params = {'r': subreddit,\n 'name': user,\n 'text': text,\n 'css_class': c... | [
2
] | [] | [] | [
"api",
"python",
"reddit"
] | stackoverflow_0008263581_api_python_reddit.txt |
Q:
Corba python integration with web service java
i'm working on a project thata i need develop one web service ( in java ) that get one simple number from a Corba python implementation... how can i proceed with this??
im using omniOrb and already done the server.py that genetares one simple number!
thx a lot
A:
Yo... | Corba python integration with web service java | i'm working on a project thata i need develop one web service ( in java ) that get one simple number from a Corba python implementation... how can i proceed with this??
im using omniOrb and already done the server.py that genetares one simple number!
thx a lot
| [
"You will need a Java CORBA provider - for example IONA or JacORB. Generate the IDL files for your python service and then use whatever IDL -> stub compiler your Java ORB provides to generate the java client-side bindings.\nFrom there it should be as simple as binding to the corbaloc:// at which your python server... | [
4
] | [] | [] | [
"corba",
"java",
"python",
"web_services"
] | stackoverflow_0008310262_corba_java_python_web_services.txt |
Q:
Popen does not work anymore with apache/wsgi and python 2.7.2?
My django application that used to make some shell commands by using python subprocess.Popen does not work anymore since I upgrade to ubuntu to 11.10
To simplify the problem, I put the faulty code into the wsgi script :
import os
import sys
from subpr... | Popen does not work anymore with apache/wsgi and python 2.7.2? | My django application that used to make some shell commands by using python subprocess.Popen does not work anymore since I upgrade to ubuntu to 11.10
To simplify the problem, I put the faulty code into the wsgi script :
import os
import sys
from subprocess import Popen,PIPE
p=Popen(['/usr/bin/id'],stdout=PIPE,stderr=P... | [
"Because latest Python 2.7 has a bug in it which causes fork run in sub interpreters to fail.\nhttp://bugs.python.org/issue13156\nPresuming only hosting the one WSGI application, force use of the main interpreter rather than a sub interpreter by adding to your Apache configuration:\nWSGIApplicationGroup %{GLOBAL}\n... | [
16
] | [] | [] | [
"apache",
"mod_wsgi",
"python"
] | stackoverflow_0008309465_apache_mod_wsgi_python.txt |
Q:
handling '++' sign in python regex
i have a list of words
i am creating a list of regex objects based on this list of words
import re
word = 'This is word of spy++'
wl = ['spy++','cry','fpp']
regobjs = [re.compile(r"\b%s\b" % word.lower() ) for word in wl]
for reobj in regobjs:
print re.search(regobj, word).g... | handling '++' sign in python regex | i have a list of words
i am creating a list of regex objects based on this list of words
import re
word = 'This is word of spy++'
wl = ['spy++','cry','fpp']
regobjs = [re.compile(r"\b%s\b" % word.lower() ) for word in wl]
for reobj in regobjs:
print re.search(regobj, word).group()
but i am getting error(error: mu... | [
"Besides re.escape() you also need to remove the \\b word boundaries before/after a non-alphanumeric character, or the match will fail.\nSomething like this (not very elegant, but I hope it gets the point across):\nimport re\nwords = 'This is word of spy++'\nwl = ['spy++','cry','fpp']\nregobjs = []\n\nfor word in w... | [
6,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008295774_python_regex.txt |
Q:
Treeview doesn't contain records when refresh the page in openerp?
I added a tree view to a page of my notebook element. While adding data to the tree view it is saving in the database, and it is also displayed in the tree view. When I reload the page, the data in the tree view vanishes and it's empty.
The code lo... | Treeview doesn't contain records when refresh the page in openerp? | I added a tree view to a page of my notebook element. While adding data to the tree view it is saving in the database, and it is also displayed in the tree view. When I reload the page, the data in the tree view vanishes and it's empty.
The code looks like this:
<field name="arch" type="xml">
<notebook colspan="4">... | [
"As Don Kirkby said, first, you must check all the conditions which he asked.\nmoreover, as per my point of view, there is one2many field \"block_line\" in your treeview,\nfor this field you should check below conditions.\nIn py : \nthis field should have referenced to many2one field (you can call block_id) in your... | [
1,
0
] | [] | [] | [
"openerp",
"postgresql_9.1",
"python"
] | stackoverflow_0008054024_openerp_postgresql_9.1_python.txt |
Q:
Tried to get data from ManyToManyField
I tried to get data from ManyToManyField but found not luck. Will you please help me?
Here is My Song App Models.
class Artist(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique = True,max_length=100,help_text="Suggested value auto... | Tried to get data from ManyToManyField | I tried to get data from ManyToManyField but found not luck. Will you please help me?
Here is My Song App Models.
class Artist(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique = True,max_length=100,help_text="Suggested value automatically generated from name. Must be uniqu... | [
"ManyRelatedManager is the object that handles the ManyToMany relation there. To get the list of objects that you're looking for, you need to use its all() method. \nIn this case, you'd use {{song_list.artist.all}}, which will give you a QuerySet that you can then iterate over in your template.\n",
"ManyToManyFie... | [
15,
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008310522_django_python.txt |
Q:
Anyone know of a good Python based web crawler that I could use?
I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of open source crawlers but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikip... | Anyone know of a good Python based web crawler that I could use? | I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of open source crawlers but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyon... | [
"\nMechanize is my favorite; great high-level browsing capabilities (super-simple form filling and submission).\nTwill is a simple scripting language built on top of Mechanize\nBeautifulSoup + urllib2 also works quite nicely.\nScrapy looks like an extremely promising project; it's new.\n\n",
"Use Scrapy.\nIt is a... | [
56,
44,
6,
3,
3,
3,
2,
0
] | [] | [] | [
"python",
"web_crawler"
] | stackoverflow_0000419235_python_web_crawler.txt |
Q:
Web mining or scraping or crawling? What tool/library should I use?
I want to crawl and save some webpages as HTML. Say, crawl into hundreds popular websites and simply save their frontpages and the "About" pages.
I've looked into many questions, but didn't find an answer to this from either web crawling or web sc... | Web mining or scraping or crawling? What tool/library should I use? | I want to crawl and save some webpages as HTML. Say, crawl into hundreds popular websites and simply save their frontpages and the "About" pages.
I've looked into many questions, but didn't find an answer to this from either web crawling or web scraping questions.
What library or tool should I use to build the solution... | [
"When going Python, you might be interested in mechanize and BeautifulSoup.\nMechanize sort of simulates a browser (including options for proxying, faking browser identifications, page redirection etc.) and allows easy fetching of forms, links, ... The documentation is a bit rough/sparse though.\nSome example code ... | [
6,
4,
3,
3,
2,
1
] | [] | [] | [
"java",
"python",
"web_crawler",
"web_mining",
"web_scraping"
] | stackoverflow_0007722876_java_python_web_crawler_web_mining_web_scraping.txt |
Q:
What languages are good for writing a web crawler?
I have substantial PHP experience, although I realize that PHP probably isn't the best language for a large-scale web crawler because a process can't run indefinitely. What languages do people suggest?
A:
Most languages would probably be a reasonable fit, the cr... | What languages are good for writing a web crawler? | I have substantial PHP experience, although I realize that PHP probably isn't the best language for a large-scale web crawler because a process can't run indefinitely. What languages do people suggest?
| [
"Most languages would probably be a reasonable fit, the critical components are \n\nLibraries to deal with the Internet Protcols\nLibraries to deal with regular expressions\nLibraries to parse HTML content\n\nToday most languages have libraries with good support for the above, of course you will need some way to pe... | [
10,
6,
1,
0,
0,
0
] | [
"C# and C++ are probably the best two languages for this, it's just a matter of which you know better and which is faster (C# is probably easier).\nI wouldn't recommend Python, Javascript, or PHP. They will usually be slower in text processing compared to a C-family language. If you're looking to crawl any signific... | [
-3
] | [
"c++",
"php",
"python",
"web_crawler"
] | stackoverflow_0003664016_c++_php_python_web_crawler.txt |
Q:
colour terminal text effects with Python
I'm trying to implement colour cycling on my text in Python, ie i want it to cycle through the colour of every character typed (amongst other effects) My progress so far has been hacked together from an ansi colour recipe improvement suggestions welcomed.
I was also vaguely... | colour terminal text effects with Python | I'm trying to implement colour cycling on my text in Python, ie i want it to cycle through the colour of every character typed (amongst other effects) My progress so far has been hacked together from an ansi colour recipe improvement suggestions welcomed.
I was also vaguely aware of, but never used: termcolor, colorama... | [
"This is a rather convoluted code - but, sticking to you r question, about the lines:\ncmd.append(format % (colours[tmpword]+fgoffset))\nThis expression appends to the list named cmd the interpolation of the string contained in the variable format with the result of the expression (colours[tmpword]+fgoffset))- whic... | [
0
] | [] | [] | [
"colors",
"python"
] | stackoverflow_0008310782_colors_python.txt |
Q:
Wondering About GeoDjango and Mapping Services
I'm trying to build my first GIS app with GeoDjango and I have a few questions before I begin:
First: What exactly is GeoDjango for in relation to Google Maps? Is it simply for processing the information, which is then passed to a service like Google Maps?
If this is... | Wondering About GeoDjango and Mapping Services | I'm trying to build my first GIS app with GeoDjango and I have a few questions before I begin:
First: What exactly is GeoDjango for in relation to Google Maps? Is it simply for processing the information, which is then passed to a service like Google Maps?
If this is true, what's the advantage of using GeoDjango vs si... | [
"As said in documentation:\n\nGeoDjango is an add-on for Django that turns it into a world-class\n geographic Web framework. GeoDjango strives to make it as simple as\n possible to create geographic Web applications, like location-based\n services. Some features include:\n\nDjango model fields for OGC geometries... | [
10
] | [] | [] | [
"database",
"django",
"geodjango",
"google_maps",
"python"
] | stackoverflow_0008276740_database_django_geodjango_google_maps_python.txt |
Q:
Multi-request pycurl running forever ( Infinite loop)
I want to perform Multi-request using Pycurl. Code is:
m.add_handle(handle)
requests.append((handle, response))
# Perform multi-request.
SELECT_TIMEOUT = 1.0
num_handles = len(requests)
while num_handles:
ret = m.select(SELEC... | Multi-request pycurl running forever ( Infinite loop) | I want to perform Multi-request using Pycurl. Code is:
m.add_handle(handle)
requests.append((handle, response))
# Perform multi-request.
SELECT_TIMEOUT = 1.0
num_handles = len(requests)
while num_handles:
ret = m.select(SELECT_TIMEOUT)
if ret == -1: continue
while 1:
... | [
"Did you go through PyCurl official codes? The following code implement multi stuff and I tried executing it and I was able to crawl around 10,000 urls in 300 secs in parallel. I think this is exactly what you want to achieve? Correct me, if am wrong.\n#! /usr/bin/env python\n# -*- coding: iso-8859-1 -*-\n# vi:ts=4... | [
7,
1
] | [] | [] | [
"pycurl",
"python",
"web_crawler"
] | stackoverflow_0005809033_pycurl_python_web_crawler.txt |
Q:
Boto script freezing when trying to deploy and configure EC2 instances
I'm using boto in Python to automate some of my EC2 workflow.
The issue is very strange - the script appears to freeze on an assignment of a simple variable, but it is continuing in the background. Eventually the script prints everything out.
W... | Boto script freezing when trying to deploy and configure EC2 instances | I'm using boto in Python to automate some of my EC2 workflow.
The issue is very strange - the script appears to freeze on an assignment of a simple variable, but it is continuing in the background. Eventually the script prints everything out.
When I repeat the script line by line in iPython there are no problems and no... | [
"Perhaps your output is being buffered.\nTry writing directly to stderr in order to rule that out:\nimport sys\nsys.stderr.write(\"Equivalent message here\\n\")\n\nOr:\nimport sys\nsys.stdout.write(\"Equivalent message here\\n\")\nsys.stdout.flush()\n\n"
] | [
2
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"boto",
"python"
] | stackoverflow_0008260788_amazon_ec2_amazon_web_services_boto_python.txt |
Q:
Python: Reading New Information Added To Massive Files
I'm working on a Python script to parse Squid(http://www.squid-cache.org/) log files. While the logs are rotated every day to stop them getting to big, they do reach between 40-90MB by the end of each day.
Essentially what I'm doing is reading the file line by... | Python: Reading New Information Added To Massive Files | I'm working on a Python script to parse Squid(http://www.squid-cache.org/) log files. While the logs are rotated every day to stop them getting to big, they do reach between 40-90MB by the end of each day.
Essentially what I'm doing is reading the file line by line, parsing out the data I need(IP, Requested URL, Time) ... | [
"One way to achieve this is by emulating tail -f. The script would constantly monitor the file and process each new line as it appears.\nFor a discussion and some recipes, see tail -f in python with no time.sleep\n",
"One way to do this is to use file system monitoring with py-inotify http://pyinotify.sourceforg... | [
2,
0
] | [] | [] | [
"file",
"parsing",
"python"
] | stackoverflow_0008310529_file_parsing_python.txt |
Q:
Amazon Autoscaling trigger not working, how do I debug it?
I'm trying to use autoscaling to create new EC2 instances whenever average CPU load on existing instances goes high. Here's the situation:
I'm setting up autoscaling using this boto script (with keys and image names removed). http://balti.ukcod.org.uk/~f... | Amazon Autoscaling trigger not working, how do I debug it? | I'm trying to use autoscaling to create new EC2 instances whenever average CPU load on existing instances goes high. Here's the situation:
I'm setting up autoscaling using this boto script (with keys and image names removed). http://balti.ukcod.org.uk/~francis/tmp/start_scaling_ptdaemon.nokeys.py
I've got min_size se... | [
"I'm sure you've already found these and it would be good to use AWS tool first before the Python tool to get the idea.:)\nhttp://ec2-downloads.s3.amazonaws.com/AutoScaling-2009-05-15.zip\nhttp://docs.amazonwebservices.com/AutoScaling/latest/DeveloperGuide/\nCheers,\nRodney \n",
"Also, take a look at something li... | [
1,
0
] | [] | [] | [
"amazon_ec2",
"boto",
"python",
"scaling"
] | stackoverflow_0003024645_amazon_ec2_boto_python_scaling.txt |
Q:
Can you use python-daemon with Python 2.4?
I'm converting my program to run as a daemon on Linux. I'd like to use the python-daemon package to save repeating the work. However, I need to support python 2.4.
The example given on the page uses the with keyword so implies python 2.5; context managers are also liste... | Can you use python-daemon with Python 2.4? | I'm converting my program to run as a daemon on Linux. I'd like to use the python-daemon package to save repeating the work. However, I need to support python 2.4.
The example given on the page uses the with keyword so implies python 2.5; context managers are also listed as being supported from 2.5.
Can I just call t... | [
"As far as I can tell from the source code, it should be easily possible to use python-daemon in Python 2.4. (I don't have a Python 2.4 installation around to actually try, though.) The __enter__() and __exit__() methods of DaemonContext are essentially aliases for open() and close(), so the equivalent of\nwith d... | [
3
] | [] | [] | [
"daemon",
"linux",
"python"
] | stackoverflow_0008309301_daemon_linux_python.txt |
Q:
Domain Not working properly in search view
In Opportunity I have 2 categories of user horizontal and vertical.When a vertical user logs in ,his/her name appears in vertical field,but when a hortizontal user logs in his/her name also appears in vertical user field instead of horizontal user field.I have applied dom... | Domain Not working properly in search view | In Opportunity I have 2 categories of user horizontal and vertical.When a vertical user logs in ,his/her name appears in vertical field,but when a hortizontal user logs in his/her name also appears in vertical user field instead of horizontal user field.I have applied domain in search view as below-
for Horizontal user... | [
"I'm not really sure what you're asking, but here's a hint for debugging search conditions. Put a breakpoint or a debug statement in the server code's orm._search() method. In version 6.0.3, it's on line 4029 of server/bin/osv/orm.py and looks like this:\n cr.execute('SELECT \"%s\".id FROM ' % self._table + from... | [
0,
0
] | [] | [] | [
"openerp",
"python"
] | stackoverflow_0007885164_openerp_python.txt |
Q:
How to capture stdout of a Python script executed with pythonw?
When a script is executed with pythonw it will not open a console.
Is there a way to capture the stdout of such a script by keeping the usage of pythonw?
Note, I am looking for a solution that does not require the modification of the script (I know th... | How to capture stdout of a Python script executed with pythonw? | When a script is executed with pythonw it will not open a console.
Is there a way to capture the stdout of such a script by keeping the usage of pythonw?
Note, I am looking for a solution that does not require the modification of the script (I know that I can use logging)
Update: pythonw script.py >somefile seems to wo... | [
"It was obvious: pythonw script.py|more\n",
"If you can change how you invoke it (as you do in the update), why don't you just run it with python instead of pythonw?\npython script.py\n\n"
] | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0008310404_python.txt |
Q:
How to get strings and coordinates from the screenshot using python or monkeyrunner
Lets say i captured a screen shot using monkey runner. This screen shot contains some text ex: Contacts, Dialer et.c. I want to extract the strings and coordinates from the screenshot. So, in my monkey runner script, i can search f... | How to get strings and coordinates from the screenshot using python or monkeyrunner | Lets say i captured a screen shot using monkey runner. This screen shot contains some text ex: Contacts, Dialer et.c. I want to extract the strings and coordinates from the screenshot. So, in my monkey runner script, i can search for the string and get the coordinates. Using this coordinate i can use monkey runner to t... | [
"This is a question of OCR.\nTry here:\nhttps://code.google.com/p/pytesser/\nIt is probably easier to access the low level user interface elements than trying to figure out what reads on the screenshot. However, the question lacks related information about used software, operating system, etc. \n"
] | [
1
] | [] | [] | [
"android",
"monkeyrunner",
"ocr",
"python"
] | stackoverflow_0008311615_android_monkeyrunner_ocr_python.txt |
Q:
Boost Python - Limits to the number of arguments when wrapping a function
I'm using Boost Python to wrap some C++ functions that I've created. One of my C++ functions contains 22 arguments. Boost complains when I try to compile my solution with this function, and I'm trying to figure out if it is just because th... | Boost Python - Limits to the number of arguments when wrapping a function | I'm using Boost Python to wrap some C++ functions that I've created. One of my C++ functions contains 22 arguments. Boost complains when I try to compile my solution with this function, and I'm trying to figure out if it is just because this function has too many arguments.
Does anyone know if such a limit exists? I... | [
"Yes there is a limit. You can find those limits here. It appears to be 15, though I believe you can change it, according to the link. \n"
] | [
7
] | [] | [] | [
"boost",
"boost_python",
"python"
] | stackoverflow_0008300058_boost_boost_python_python.txt |
Q:
multiply() in numpy python
It seems to me there are two versions of numpy function multiply():
c = multiply( a, b )
multiply(a, b, c )
My questions is two fold:
What is the difference between the two versions?
I need to use dot() function, and I know c = dot( a, b) works. But dot(a, b, c) does not.
A:
The di... | multiply() in numpy python | It seems to me there are two versions of numpy function multiply():
c = multiply( a, b )
multiply(a, b, c )
My questions is two fold:
What is the difference between the two versions?
I need to use dot() function, and I know c = dot( a, b) works. But dot(a, b, c) does not.
| [
"\nThe difference between the two versions of multiply():\nc = multilpy(a, b)\n\nmultiplies the arrays a and b element-wise, creating a new array as result. The name c is bound to this new array. If c pointed to a different array before, this might or might not trigger garbage collection of the array c pointed to... | [
6,
1
] | [] | [] | [
"numpy",
"performance",
"python"
] | stackoverflow_0008312474_numpy_performance_python.txt |
Q:
Copy a layer from an image to another
I am building a Gimp plugin in python. I would like to load a layer in memory, based on an file, and then adding it to several images (thus avoiding the loading time from file).
I could not find anything in the documentation to do that: all function adds layers into a specific... | Copy a layer from an image to another | I am building a Gimp plugin in python. I would like to load a layer in memory, based on an file, and then adding it to several images (thus avoiding the loading time from file).
I could not find anything in the documentation to do that: all function adds layers into a specific image (so i would have to load from file e... | [
"I think the easiest way is to use \"copy\" and \"paste\" via the PDB -\npdb.gimp_edit_copy (original_layer)\n\nfloating = pdb.gimp_edit_paste (target_layer)\n\n(where target layer is a layer on the other image).\nThis creates, like doing the same thing interactively,a \"floating selection\".\nTo have the floatin... | [
4
] | [] | [] | [
"gimp",
"python"
] | stackoverflow_0008312446_gimp_python.txt |
Q:
psycopg2 NotSupportedError on "current" when I'm using current_date
I'm using psycopg2 to access a postgresql 8.4 database, and on an update query I get the following exception:
File "/home/alf/cubicweb/cubicweb/server/sources/native.py", line 744, in doexec
cursor.execute(str(query), args)
NotSupportedError... | psycopg2 NotSupportedError on "current" when I'm using current_date | I'm using psycopg2 to access a postgresql 8.4 database, and on an update query I get the following exception:
File "/home/alf/cubicweb/cubicweb/server/sources/native.py", line 744, in doexec
cursor.execute(str(query), args)
NotSupportedError: ERREUR: la valeur « current » pour la date et heure n'est plus support... | [
"You are giving the string 'CURRENT_DATE' to a date-column. Most likely it uses _ as an accepted separator when parsing the string as a date.\nWhat you want is CURRENT_DATE not 'CURRENT_DATE'.\nSo try this:\nUPDATE cw_ImportLog SET cw_import_date = current_date;\n\nEdit: If you have to feed it a string, use now ins... | [
2
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0008312828_postgresql_psycopg2_python.txt |
Q:
How can I convince Python to import a class from a submodule when you import the package?
Example: mypkg/submodule.py with class MyClass inside.
I want to be able to do:
import mypkg
obj = MyClass()
What I need to do in order to make this work with default import?
I note that from pkg import * and import pkg.subm... | How can I convince Python to import a class from a submodule when you import the package? | Example: mypkg/submodule.py with class MyClass inside.
I want to be able to do:
import mypkg
obj = MyClass()
What I need to do in order to make this work with default import?
I note that from pkg import * and import pkg.submodule works are working but I want to change the behaviour of the default import.
This is clear... | [
"You can't do that normally (I guess with some crazy hacks it could be possible). You either have:\nfrom mypkg.submodule import MyClass\n\nOr if you setup __init__.py in the package appropriately, you could have:\nfrom mypkg import MyClass\n\n",
"It is not possible, a simple python import will only add the module... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0008311971_python.txt |
Q:
How to remove item from a python list in a loop?
Possible Duplicate:
Remove items from a list while iterating in Python
I'm trying to remove an item from a list in python:
x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x:
if len(item) != 2:
print "length of %s is: %s" %(item, len(item))
... | How to remove item from a python list in a loop? |
Possible Duplicate:
Remove items from a list while iterating in Python
I'm trying to remove an item from a list in python:
x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x:
if len(item) != 2:
print "length of %s is: %s" %(item, len(item))
x.remove(item)
But it doesn't remove "fren" item. An... | [
"You can't remove items from a list while iterating over it. It's much easier to build a new list based on the old one:\ny = [s for s in x if len(s) == 2]\n\n",
"hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a sl... | [
110,
47,
7,
2,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008312829_list_python.txt |
Q:
unigram using python
i'm trying to generate unigram from a text file. But only the bigram for the first line of the given file is shown. I want to show unigram for all the sentences in the file.
import string;
import sys;
import tokenize;
f = open("data.txt", 'r');
line=f.readline();
while line:
line = line.r... | unigram using python | i'm trying to generate unigram from a text file. But only the bigram for the first line of the given file is shown. I want to show unigram for all the sentences in the file.
import string;
import sys;
import tokenize;
f = open("data.txt", 'r');
line=f.readline();
while line:
line = line.rstrip();
list = line.s... | [
"First off, if you are using a somewhat current version of python, you can simply do: for line in f which is much simpler than this readline stuff. Also you don't have to use ; at every line. It is only used if you want to make several statements in one line.\nThe following lines work just fine for me:\nf = open(\"... | [
3,
3
] | [] | [] | [
"n_gram",
"python"
] | stackoverflow_0008312935_n_gram_python.txt |
Q:
In python, is there a way to automatically substitute for missing values?
I'm trying to parse a JSON object that consists of an array of objects. Each object contains several fields, but fields are often missing. Here's an example:
{
'objects' : [{
'fieldA' : 1,
'fieldB' : 2,
'fieldC' ... | In python, is there a way to automatically substitute for missing values? | I'm trying to parse a JSON object that consists of an array of objects. Each object contains several fields, but fields are often missing. Here's an example:
{
'objects' : [{
'fieldA' : 1,
'fieldB' : 2,
'fieldC' : 3,
},
{
'fieldA' : 7,
'fieldC' : 8,
},
{},
... | [
"You need the dict.get() method:\nfieldA = [obj.get(\"fieldA\", \"missing\") for obj in json[\"objects\"]]\n\nNote that the items of a dictionary are accessed with [\"key\"], not with .key.\n"
] | [
12
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008313464_list_python.txt |
Q:
Post save process using ManyToMany with intermediary model in admin
I have a model relationship as defined by the examples in the Django docs on ManyToMany relationship with an intermediary model.
I know how this normally works, but this is a quick little app that only uses the Django Admin and this is causing a s... | Post save process using ManyToMany with intermediary model in admin | I have a model relationship as defined by the examples in the Django docs on ManyToMany relationship with an intermediary model.
I know how this normally works, but this is a quick little app that only uses the Django Admin and this is causing a slight bump in the road.
Here is what I have:
class Item(models.Model):
... | [
"Ok, after much research I found someone else that solved this http://igorsobreira.com/blog/2011/2/12/change-object-after-saving-all-inlines-in-django-admin/\nIn the invoice admin:\nclass InvoiceAdmin(admin.ModelAdmin):\n inlines = [\n SoldItemAdmin,\n ]\n\n def response_add(self, request, new_obje... | [
1
] | [] | [] | [
"django",
"entity_relationship",
"orm",
"python"
] | stackoverflow_0008303179_django_entity_relationship_orm_python.txt |
Q:
Calling a back end URL using javascript channel API
Handler Implementation
class TestHandler(RequestHandler, Jinja2Mixin):
def get(self):
channel_id = str(random.randint(1, 10000)) + str(datetime.now())
chat_token = channel.create_channel(channel_id)
context = {'channel_id': channel_id, 'chat_token': ... | Calling a back end URL using javascript channel API | Handler Implementation
class TestHandler(RequestHandler, Jinja2Mixin):
def get(self):
channel_id = str(random.randint(1, 10000)) + str(datetime.now())
chat_token = channel.create_channel(channel_id)
context = {'channel_id': channel_id, 'chat_token': chat_token}
return self.render_response('test.html', ... | [
"You access a back end with a url like http://instance.backend.appid.appspot.com (see the docs). Since you can't make an XHR to a page like this from an page rendered on http://appid.appspot.com, you have basically two options:\nYou can marshal the request to your backend via a servlet on your frontend. So you coul... | [
1
] | [] | [] | [
"google_app_engine",
"jquery",
"python"
] | stackoverflow_0008306350_google_app_engine_jquery_python.txt |
Q:
Error on connecting to python libraries
I have a project that has code which will communicate with a python script and call python functions. In the proj file, i've added the includePath for the python header files, and added external python library to the project (python27.a). However the qt compiler gave me an e... | Error on connecting to python libraries | I have a project that has code which will communicate with a python script and call python functions. In the proj file, i've added the includePath for the python header files, and added external python library to the project (python27.a). However the qt compiler gave me an error:
No rule to make target
/home/pgeng/wor... | [
"It seems like libpython2 is missing.\nYou will have to :\n\nFind out what package provides this library.\nYou can Google for that.\nOr search a repo for the lib.\n\n"
] | [
1
] | [] | [] | [
"dll",
"pyqt",
"python",
"qt"
] | stackoverflow_0008313051_dll_pyqt_python_qt.txt |
Q:
UnboundExecutionError in SQLAlchemy
Note: This is in SQLAlchemy 0.5.7. It appears that this is not possible as the "lazy" does not work on one-to-one mapping. If it does and I got it wrong, please post your answer.
I have the following method, which should return all instances of any class those parent is Par... | UnboundExecutionError in SQLAlchemy | Note: This is in SQLAlchemy 0.5.7. It appears that this is not possible as the "lazy" does not work on one-to-one mapping. If it does and I got it wrong, please post your answer.
I have the following method, which should return all instances of any class those parent is Parent. Note that a class Child has an attr... | [
"From Relationship API documentation (scroll down to the explanation of lazy parameter):\nlazy=’select’ – specifies how the related items should be loaded. Default value is select. Values include:\n ...\n noload - no loading should occur at any time. This is to support “write-only” attributes, or attributes w... | [
2
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0008313914_python_sqlalchemy.txt |
Q:
Access c_char_p_Array_256 in Python using ctypes
I have a native python bridge to some C code, which returns a pointer to an array (array of structs). The struct contains some character arrays (strings). But how can I get from a c_char_p_Array_NNN to an actual Python string?
typedef struct td_Group
{
unsigned ... | Access c_char_p_Array_256 in Python using ctypes | I have a native python bridge to some C code, which returns a pointer to an array (array of structs). The struct contains some character arrays (strings). But how can I get from a c_char_p_Array_NNN to an actual Python string?
typedef struct td_Group
{
unsigned int group_id;
char groupname[256];
char date_c... | [
"The type should be c_char*256, not c_char_p*256, because it's a char[256], not a char *[256].\nstring_at(theGroupName, sizeof(theGroupName))\n"
] | [
2
] | [] | [] | [
"c",
"ctypes",
"python"
] | stackoverflow_0008314275_c_ctypes_python.txt |
Q:
Data type convert in Mysql or python
I have a .txt file which contains a column of unixtime, like (1322485992.420381000), the number of digits before and after the dot are the same for all data. First I want to import this column into a Mysql table, how should I define the data type?
CREATE TABLE videoinfo (id I... | Data type convert in Mysql or python | I have a .txt file which contains a column of unixtime, like (1322485992.420381000), the number of digits before and after the dot are the same for all data. First I want to import this column into a Mysql table, how should I define the data type?
CREATE TABLE videoinfo (id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, un... | [
"Looks like a DOUBLE(11,9) although such a large number may cause problems on 32-bit systems. Consider using a VARCHAR(21) if that's an issue.\nAlso, MySQL simply understands FROM_UNIXTIME(1322485992.420381000).\n-edit-\nWhen it says \"requires a float\", why don't you just use float(result) ?\n"
] | [
1
] | [] | [] | [
"mysql",
"python",
"types"
] | stackoverflow_0008314635_mysql_python_types.txt |
Q:
How can a function return a dynamic value that depends on the number of receivers in Python?
I was trying to do a "strange" (but useful in my case) function that can return a dynamic list whose len depends on the amount of receiver.
For example:
f() returns a dynamic list of None, so I can do the following:
a = f(... | How can a function return a dynamic value that depends on the number of receivers in Python? | I was trying to do a "strange" (but useful in my case) function that can return a dynamic list whose len depends on the amount of receiver.
For example:
f() returns a dynamic list of None, so I can do the following:
a = f() => a = None
a, b = f() => a=b= None
(a, b) = f() => a=b= None
(a, b, c, d, e, f) = f() => a=b... | [
"This is not possible in Python. The function on the right hand site has no knowledge of the context it was called in. The right hand site is evaluated before any of the name bindings take place.\n",
"If you don't mind using Python 3, you can ignore what you don't need, for example:\na, b, c, d, *_ = (x for x i... | [
3,
1,
1,
0,
0,
0
] | [] | [] | [
"iterator",
"list_comprehension",
"multiple_resultsets",
"python"
] | stackoverflow_0008313705_iterator_list_comprehension_multiple_resultsets_python.txt |
Q:
How to change last letter of filename to lowercase if it is a letter?
I have been given data which cannot be interpreted by my software unless it has a lowercase letter at the end. The data was delivered with an uppercase letter at the end.
Somehow I need to first recursively loop through all folders and find whet... | How to change last letter of filename to lowercase if it is a letter? | I have been given data which cannot be interpreted by my software unless it has a lowercase letter at the end. The data was delivered with an uppercase letter at the end.
Somehow I need to first recursively loop through all folders and find whether the filename ends with a letter and then change it to lowercase.
I thin... | [
"import fnmatch\nimport os\n\nrootPath = '/'\npattern = '*.mp3'\n\nfor root, dirs, files in os.walk(rootPath):\n for filename in fnmatch.filter(files, pattern):\n os.rename(filename, filename[:-1] + filename[-1:].lower())\n\nSources:\nhttp://rosettacode.org/wiki/Walk_a_directory/Recursively#Python\nRename... | [
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0008314983_python.txt |
Q:
Converting excel files to python to frequency
Essentially I've got an excel files with voltage in the first column, and time in the second. I want to find the period of the voltages, as it returns a graph of voltage in y axis and time in x axis with a periodicity, looking similar to a sine function.
To find the fr... | Converting excel files to python to frequency | Essentially I've got an excel files with voltage in the first column, and time in the second. I want to find the period of the voltages, as it returns a graph of voltage in y axis and time in x axis with a periodicity, looking similar to a sine function.
To find the frequency I have uploaded my excel file to python as ... | [
"I'm not sure how much you know about the Fourier transform, so forgive me if this is too much background.\nYour signal does not have \"a frequency\", it is but it can be thought of as the sum of many frequencies. The Fourier transform will tell you the weights of all the frequencies that make up your signal. Unfor... | [
1
] | [] | [] | [
"excel",
"fft",
"frequency",
"python",
"time"
] | stackoverflow_0008314840_excel_fft_frequency_python_time.txt |
Q:
Python UUID badly formed hexadecimal string
Trying to generate a UUID based on an 6.6 XY coordinate pair and the date. However I am giving the function a 'badly formed hexadecimal UUID string'. Python noob plz help.
def LeID(Xv,Yv,Dv):
import uuid
import string
import arcpy
X_val = "%.6f" % Xv
... | Python UUID badly formed hexadecimal string | Trying to generate a UUID based on an 6.6 XY coordinate pair and the date. However I am giving the function a 'badly formed hexadecimal UUID string'. Python noob plz help.
def LeID(Xv,Yv,Dv):
import uuid
import string
import arcpy
X_val = "%.6f" % Xv
Y_val = "%.6f" % Yv
date = Dv
xarr = st... | [
"It won't work the way you think.\nThere are several types of UUID: based on time (UUID1), randomly (UUID4) or based on another UUID plus data, put together via MD5 (UUID3) or SHA1 (UUID5).\nSo you would take one previously defined UUID, maybe UUID('f82aa75f-56a8-442b-89d2-eb7aaae6f9c3'), as a namespace and derive ... | [
3
] | [] | [] | [
"arcmap",
"python"
] | stackoverflow_0008315225_arcmap_python.txt |
Q:
Python re: negating part of a regular expression
Perhaps a silly question, but though google returned lots of similar cases, I could not find this exact situation: what regular expression will match all string NOT containing a particular string. For example, I want to match any string that does not contain 'foo_'.... | Python re: negating part of a regular expression | Perhaps a silly question, but though google returned lots of similar cases, I could not find this exact situation: what regular expression will match all string NOT containing a particular string. For example, I want to match any string that does not contain 'foo_'.
Now,
re.match('(?<!foo_).*', 'foo_bar')
returns a ... | [
"You're using lookbehind assertions where you need lookahead assertions:\nre.match(r\"(?!.*foo_).*\", \"foo_bar\")\n\nwould work (i. e. not match).\n(?!.*foo_) means \"Assert that it is impossible to match .*foo_ from the current position in the string. Since you're using re.match(), that position is automatically ... | [
4,
3,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008315487_python_regex.txt |
Q:
Adapting script to read from text file
I have the following script that I need to adapt to read from a file, specifically I need to pull the 'domain' and 'expected responses'. currently they are manually written in the code as I'm not skilled enough to refactor it more efficiently.
#!/usr/bin/python
import dns.re... | Adapting script to read from text file | I have the following script that I need to adapt to read from a file, specifically I need to pull the 'domain' and 'expected responses'. currently they are manually written in the code as I'm not skilled enough to refactor it more efficiently.
#!/usr/bin/python
import dns.resolver
from smtplib import SMTP
import datet... | [
"http://docs.python.org/library/configparser.html\nThis may be more what you're looking for. Using an *.ini file seems to be a pretty standard practice for configuration files.\n"
] | [
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008314569_csv_python.txt |
Q:
Plone 4: how to get the context for a sub-folder with a hyphen in the shortname
I am writing a python script to import content from another CMS into Plone 4.1. For a number of reasons I am running it like so: bin/instance run path/to/myscript
The question I have is how to get the correct context for a folder with ... | Plone 4: how to get the context for a sub-folder with a hyphen in the shortname | I am writing a python script to import content from another CMS into Plone 4.1. For a number of reasons I am running it like so: bin/instance run path/to/myscript
The question I have is how to get the correct context for a folder with a hyphen in the ID/shortname. For example from the root of a plone site called mysite... | [
"That's because if you use:\napp.mysite.sub-folder\n\npython thinks that you're trying to do a difference between app.mysite.sub and folder.\nInstead you have to use this syntax:\nsecondlevel = mysite['sub-folder']['2nd-level']\n\nor\nsecondlevel = mysite.restrictedTraverse('/mysite/sub-folder/2nd-level')\n\n",
"... | [
4,
0
] | [] | [] | [
"import",
"plone",
"python",
"zope"
] | stackoverflow_0008285950_import_plone_python_zope.txt |
Q:
Opening various main.py files in Eclipse without creating a new project
I have a python project developed in eclipse. Independantly there are various data directories in various locations and it is desirable to operate on each with a different main.py that imports the python project. If I store a main.py with my d... | Opening various main.py files in Eclipse without creating a new project | I have a python project developed in eclipse. Independantly there are various data directories in various locations and it is desirable to operate on each with a different main.py that imports the python project. If I store a main.py with my data, how can I open it in eclipse and run the debugger?
I can run ipython in... | [
"You could do this by setting up each main.py + data directory as its own Eclipse project, each with a custom run/debug configuration. You do have extra projects, but they don't require any ongoing maintenance.\nAfter the initial setup, you continue work on the real python project and debugging any given data dire... | [
0,
0
] | [] | [] | [
"eclipse",
"python"
] | stackoverflow_0008067673_eclipse_python.txt |
Q:
Empty a dictionary subclass in python
I'm using a django module that uses a class that inherits from dict. Let's call it ExtendedDict. Suppose I'm given an instance, e_d, of the ExtendedDict class and I want to clear it out. What's the most pythonic way to empty it?
This feels clunky:
for key in e_d: e_d.pop(key... | Empty a dictionary subclass in python | I'm using a django module that uses a class that inherits from dict. Let's call it ExtendedDict. Suppose I'm given an instance, e_d, of the ExtendedDict class and I want to clear it out. What's the most pythonic way to empty it?
This feels clunky:
for key in e_d: e_d.pop(key)
Is there a better solution?
| [
"Since your class inherits from dict, its instances should have a clear() method:\ne_d.clear()\n\n",
"Can't you just use clear() and do:\ne_d.clear() \n\n",
"Dictionaries have a clear method. Can't you use that?\n"
] | [
4,
3,
3
] | [] | [] | [
"class",
"dictionary",
"python"
] | stackoverflow_0008316053_class_dictionary_python.txt |
Q:
validate file before upload
I have different categories like English,French and I've applied key language = models.ForeignKey(Category) I want to validate the file before it upload to disk.
I want if category is english then file upload to english/album_name if category is french then file upload to french/album_... | validate file before upload | I have different categories like English,French and I've applied key language = models.ForeignKey(Category) I want to validate the file before it upload to disk.
I want if category is english then file upload to english/album_name if category is french then file upload to french/album_name. I've written forms.py file.... | [
"I think what you really want is to validate it after upload, but before saving it really.\nWhen files are uploaded, they are in a temporary folder, so you can do all checks you want before saving it to the appropriate folder.\nHowever, if you really mean pre-upload checks, you have to use Javascript (because it is... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008315736_django_python.txt |
Q:
How can virtualenv be used effectively with libraries stored in source control?
I am aware of 2 suggested practices which seem to be at odds with each other:
Store everything you need for your project in source control. When working with C++ apps we'd check all our libs into source control so that a new developer... | How can virtualenv be used effectively with libraries stored in source control? | I am aware of 2 suggested practices which seem to be at odds with each other:
Store everything you need for your project in source control. When working with C++ apps we'd check all our libs into source control so that a new developer always has everything he or she needs to build and run the project, even if the 3rd ... | [
"I would check a pip bundle into source control: http://www.pip-installer.org/en/latest/usage.html#bundles\nYou can use --index-url to tell pip where to get the packages if you want to store them on your network so they don't have to get them from PyPI or wherever: http://www.pip-installer.org/en/latest/usage.html#... | [
2,
2
] | [] | [] | [
"dependencies",
"python",
"version_control",
"virtualenv"
] | stackoverflow_0008315896_dependencies_python_version_control_virtualenv.txt |
Q:
Empty ModelFormset in Django's FormWizard
I'm using Django's FormWizard. It works fine but I'm having trouble getting any empty model formset to display correctly.
I have a model called Domain. I'm creating a ModelFormset like this:
DomainFormset = modelformset_factory(Domain)
I pass this to the FormWizard like t... | Empty ModelFormset in Django's FormWizard | I'm using Django's FormWizard. It works fine but I'm having trouble getting any empty model formset to display correctly.
I have a model called Domain. I'm creating a ModelFormset like this:
DomainFormset = modelformset_factory(Domain)
I pass this to the FormWizard like this:
BuyNowWizardView.as_view([DomainFormset])
... | [
"The Django docs give two ways to change the queryset for a formset. \nThe first way is to pass the queryset as an argument when instantiating the formset. With the formwizard, you can do this by passing instance_dict\n# set the queryset for step '0' of the formset\ninstance_dict = {'0': Domain.objects.none()}\n\n#... | [
6
] | [] | [] | [
"django",
"django_forms",
"django_formwizard",
"python"
] | stackoverflow_0008316145_django_django_forms_django_formwizard_python.txt |
Q:
implementing a spinner type object in a class as a subprocess
I'm a total beginner and only started doing classes today, and im trying to make a sort of 'spinner' object i can call something like this: One of the things im confused about is whether to use 'thread', 'threading' or 'processes'. I just read somewhere... | implementing a spinner type object in a class as a subprocess | I'm a total beginner and only started doing classes today, and im trying to make a sort of 'spinner' object i can call something like this: One of the things im confused about is whether to use 'thread', 'threading' or 'processes'. I just read somewhere that an instance of a thread costs 8meg, as this is a simple text ... | [
"I have altered your code slightly. Now it runs! First a commented version:\nThe first line tells python that this source file contains utf-8 characters\n# -*- coding: utf-8 -*- \n\nThen you need to import all the stuff that you will eventually use. You dont have to do it at the top of the file like this, but I'm a... | [
2
] | [] | [] | [
"class",
"multithreading",
"process",
"python"
] | stackoverflow_0008315249_class_multithreading_process_python.txt |
Q:
iterate over pyqt objects
Problem :
I used Qt Designer and created 20 Graphics Views.
I want to iterate on them and change there background color inside the loop.
How i can do this?
Extra:
what i am trying to do:
I have 20 computers and i want to notify the user which terminals are not Used.
I have this date on fi... | iterate over pyqt objects | Problem :
I used Qt Designer and created 20 Graphics Views.
I want to iterate on them and change there background color inside the loop.
How i can do this?
Extra:
what i am trying to do:
I have 20 computers and i want to notify the user which terminals are not Used.
I have this date on files and every 2 min i will read... | [
" class MyWidget(QtGui.QWidget):\n ...\n\n def my_method(self):\n\n for child in self.children():\n\n if isinstance(child, QtGui.QGraphicsView): \n ...\n\n"
] | [
1
] | [] | [] | [
"oop",
"pyqt",
"python"
] | stackoverflow_0008316177_oop_pyqt_python.txt |
Q:
Print HTML text of a selenium webelement in Python
I am using Selenium webdriver in Python for a web-scraping project.
How to print the HTML text of the selenium.WebElement ?
I intend to use the BeautifulSoup to parse the HTML to extract the data of interest.
Thanks
A:
It's not possible to get the raw HTML from ... | Print HTML text of a selenium webelement in Python | I am using Selenium webdriver in Python for a web-scraping project.
How to print the HTML text of the selenium.WebElement ?
I intend to use the BeautifulSoup to parse the HTML to extract the data of interest.
Thanks
| [
"It's not possible to get the raw HTML from a WebElement.\nYou can get the page source from the browser object though: browser.page_source.\n"
] | [
12
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"urllib2",
"web_scraping"
] | stackoverflow_0008316152_beautifulsoup_python_selenium_urllib2_web_scraping.txt |
Q:
python c extension: multithreading and random numbers
I have implemented a work queue pattern in C (within a python extension) and I am disappointed with performance.
I have a simulation with a list of particles ("elements"), and I benchmark the time taken to perform all the calculations required for a timestep an... | python c extension: multithreading and random numbers | I have implemented a work queue pattern in C (within a python extension) and I am disappointed with performance.
I have a simulation with a list of particles ("elements"), and I benchmark the time taken to perform all the calculations required for a timestep and record this along with the number of particles involved. ... | [
"Python threads aren't real threads. All python threads are run in the same OS level thread, and are executed one-at-a-time thanks to GIL - the Global Interpreter Lock. Rewriting your code with processes might do the trick, if the workers are relatively long-lived in the context.\nWikipedia's page on GIL\n----Edit-... | [
0,
0,
0
] | [] | [] | [
"c",
"multithreading",
"python",
"random"
] | stackoverflow_0008315481_c_multithreading_python_random.txt |
Q:
Convert mp4 to .wav or mp3 with python
Does anybody have experience with converting mp4 files to .wav or mp3 files? I am able to do this in Linux (bash), but I try to do everything in Python that I do in other languages, call me an enthusiast. I have been looking over the Pymedia library, but have not made progres... | Convert mp4 to .wav or mp3 with python | Does anybody have experience with converting mp4 files to .wav or mp3 files? I am able to do this in Linux (bash), but I try to do everything in Python that I do in other languages, call me an enthusiast. I have been looking over the Pymedia library, but have not made progress as of yet.
| [
"You can use Python bindings for GStreamer, and create a pipeline to do the conversion:\nMore info here:\nhttp://pygstdocs.berlios.de/pygst-tutorial/pipeline.html\nExample of pipeline in another SO question:\nconverting wav to mp3 (and vice versa) using GStreamer\n",
"You might find the python audio tools of some... | [
1,
1
] | [] | [] | [
"media",
"python"
] | stackoverflow_0008316619_media_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.