content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python or Django: handle raised exception from imported library without internal server error
I've created a library that connects to some remote JSON api. I have a Django application that will render a internal server error, if my library fails connecting to the resource (504 error). Here is a hypothetical exampl... | Python or Django: handle raised exception from imported library without internal server error | I've created a library that connects to some remote JSON api. I have a Django application that will render a internal server error, if my library fails connecting to the resource (504 error). Here is a hypothetical example that kind of shows the layout of my library's code.
mymodule.py
...
class Error(Exception):
... | [
"Figured my problem out. I feel stupid, because the solution is so simple. Hopefully, this will help someone out in the future who runs into the same issue. If a HTTP connection fails on an imported library, you can avoid rendering a server error page and produce a friendly notification for the client. \nAll it ... | [
1
] | [] | [] | [
"django",
"exception",
"python"
] | stackoverflow_0006326077_django_exception_python.txt |
Q:
python: creating instance from variable name
***EDIT2: Sorry about the broken code. Here is working code which illustrates the same issue:
class bead():
def printmsg(a):
print('test message')
chain1=bead()
x='chain1'
eval(x + '.printmsg()')
***EDIT: Thank you gnibbler for answering the original quest... | python: creating instance from variable name | ***EDIT2: Sorry about the broken code. Here is working code which illustrates the same issue:
class bead():
def printmsg(a):
print('test message')
chain1=bead()
x='chain1'
eval(x + '.printmsg()')
***EDIT: Thank you gnibbler for answering the original question. Here's a better worded version of my question... | [
"Instead of the eval(), you could say\ngetattr(locals()[x], y)\n\nor\ngetattr(locals().get(x), y)\n\nIs that what you mean?\n",
"I think I understand. What you probably want is:\n>>> class testClass():\n... test1='test1 text'\n... \n>>> getattr(testClass, 'test1')\n'test1 text'\n\n\nStill that isn't creating ... | [
12,
1
] | [] | [] | [
"class",
"instance",
"python"
] | stackoverflow_0006367164_class_instance_python.txt |
Q:
Slicing url with Python
Hi how to use python to transform the url of a article to it's print url.
article url:http://www.indianexpress.com/news/second-time-as-farce/800228/0
print url:http://www.indianexpress.com/story-print/800228/
How to convert article url to print url?
A:
Use urllib.parse.urlparse() to carve... | Slicing url with Python | Hi how to use python to transform the url of a article to it's print url.
article url:http://www.indianexpress.com/news/second-time-as-farce/800228/0
print url:http://www.indianexpress.com/story-print/800228/
How to convert article url to print url?
| [
"Use urllib.parse.urlparse() to carve the path from the rest of the url, and posixpath.split() and posixpath.join() to reform the path, and urllib.parse.urlunparse() to put it all back together again.\n",
"from urllib.parse import urlparse\n\ndef transform(url):\n parsed = urlparse(url)\n return '{0}://{1}/... | [
6,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006367280_python_python_3.x.txt |
Q:
How to install the django site (tar.gz) downloaded from internet
I have downloaded this project http://code.google.com/p/django-budget/
How can i install it. Do i need to execute some commands or just extract it to some folder.
DO i need to use syncdb.
I am newbie so don't know much
A:
PS. It's been moved to ht... | How to install the django site (tar.gz) downloaded from internet | I have downloaded this project http://code.google.com/p/django-budget/
How can i install it. Do i need to execute some commands or just extract it to some folder.
DO i need to use syncdb.
I am newbie so don't know much
| [
"PS. It's been moved to https://github.com/toastdriven/django-budget for a while now.\nThere is information on the frontpage of the site:\n\nInstallation\n\nEither copy/symlink the budget app\n into your project or place it\n somewhere on your PYTHONPATH.\nAdd the budget.categories,\n budget.transactions and bud... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006367467_django_python.txt |
Q:
Syntax error when using an assignment (of a lambda) in eval()?
How come when I type the following
eval("mult = lambda x,y: (x*y)")
I get this as an error? What's going on?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
mult = lambda x,y: (x*y)
^
Syn... | Syntax error when using an assignment (of a lambda) in eval()? | How come when I type the following
eval("mult = lambda x,y: (x*y)")
I get this as an error? What's going on?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
mult = lambda x,y: (x*y)
^
SyntaxError: invalid syntax
What am I doing wrong? If I enter the expr... | [
"You want to use exec instead of eval. I don't know why you would want to do this though when you can just use mult = lambda x,y : (x*y)\n>>> exec(\"mult = lambda x,y : (x*y)\")\n>>> mult\n<function <lambda> at 0x1004ac1b8>\n>>> mult(3,6)\n18\n\n",
"Eval does expressions, it doesn't assign.\n>>> eval(\"lambda x,... | [
12,
9,
2
] | [] | [] | [
"eval",
"lambda",
"python"
] | stackoverflow_0006367618_eval_lambda_python.txt |
Q:
Best practice for handling exceptions from libraries imported by other libraries in Python?
What is the appropriate way for handling exceptions from libraries imported by other libraries in Python?
For example, I have a library called "pycontrol" that I import into my main program. "pycontrol" imports the "suds" l... | Best practice for handling exceptions from libraries imported by other libraries in Python? | What is the appropriate way for handling exceptions from libraries imported by other libraries in Python?
For example, I have a library called "pycontrol" that I import into my main program. "pycontrol" imports the "suds" library. The "suds" library, in turn, imports the "urllib2" library. I've noticed that when the "s... | [
"I think you answered you question yourself. Import urllib2 and catch the exception in your module.\nfrom urllib2 import URLError\n\ntry:\n # something\nexcept URLError, e:\n # Do something in case of error.\n\n",
"Why do you need to catch specific exceptions at all? After all, any exception (not only URLEr... | [
2,
0
] | [] | [] | [
"exception",
"exception_handling",
"python",
"suds"
] | stackoverflow_0006366799_exception_exception_handling_python_suds.txt |
Q:
poplib.error_proto: -ERR Protocol error. 17
I try to get emails with python poplib, but I get:
File "/usr/lib64/python2.6/poplib.py", line 189, in pass_
return self._shortcmd('PASS %s' % pswd)
File "/usr/lib64/python2.6/poplib.py", line 152, in _shortcmd
return self._getresp()
File "/usr/lib64/python... | poplib.error_proto: -ERR Protocol error. 17 | I try to get emails with python poplib, but I get:
File "/usr/lib64/python2.6/poplib.py", line 189, in pass_
return self._shortcmd('PASS %s' % pswd)
File "/usr/lib64/python2.6/poplib.py", line 152, in _shortcmd
return self._getresp()
File "/usr/lib64/python2.6/poplib.py", line 128, in _getresp
raise e... | [
"In my case there was a non-ASCII character in the password. The admin created a new password for me, and now all works well.\nRelated: \nhttp://social.technet.microsoft.com/Forums/en-US/exchangesvrgeneral/thread/e5badd24-2d11-4bdd-a746-3aee50242ccb\n"
] | [
1
] | [] | [] | [
"pop3",
"python"
] | stackoverflow_0006358062_pop3_python.txt |
Q:
Zenoss - Device Access Control Lists for Customers
We're evaluating Zenoss and are interested in Device Access Control. We would like to set up the system so that our customers could access Zenoss and only see their devices and status. This feature apparently only exists in the enterprise version as can be seen he... | Zenoss - Device Access Control Lists for Customers | We're evaluating Zenoss and are interested in Device Access Control. We would like to set up the system so that our customers could access Zenoss and only see their devices and status. This feature apparently only exists in the enterprise version as can be seen here.
In the user configuration page there is a "Administe... | [
"I am working on this right now. Part of the issue is that there are a number of bugs around the Zenoss Administered Objects concept. I have posted some findings at the Zenoss forum at http://community.zenoss.org/message/59100#59100 . I have also opened a number of tickets with Zenoss (referenced in the previous ... | [
1
] | [] | [] | [
"acl",
"nms",
"python",
"zenoss",
"zope"
] | stackoverflow_0006357690_acl_nms_python_zenoss_zope.txt |
Q:
django/python logging
I have a pretty weird problem with my logging facility i use inside django/python. The logging is not working anymore since i upgraded to django 1.3. It seems to be related to the logging level and the 'debug=' setting in the settings.py file.
1) When i log INFO messages and debug=False, the ... | django/python logging | I have a pretty weird problem with my logging facility i use inside django/python. The logging is not working anymore since i upgraded to django 1.3. It seems to be related to the logging level and the 'debug=' setting in the settings.py file.
1) When i log INFO messages and debug=False, the logging won't happen, my fi... | [
"Since Django 1.3 contains its own logging configuration, you need to ensure that anything you're doing doesn't clash with it. For example, if the root logger has handlers already configured by Django by the time your module first gets imported, your basicConfig() call won't have any effect.\nWhat you're describing... | [
3
] | [] | [] | [
"django",
"django_settings",
"django_views",
"logging",
"python"
] | stackoverflow_0006367927_django_django_settings_django_views_logging_python.txt |
Q:
How Do We Add Python Library(google_meter.py) in IronPython?
Hi i am going to code for retrieving google data i am using Iron Python then can you please let me know how do we add google_meter.py file in iron python and access its methods as i am new to python?
Thanks in Advance,
-Mohsin
A:
I suggest you read the... | How Do We Add Python Library(google_meter.py) in IronPython? | Hi i am going to code for retrieving google data i am using Iron Python then can you please let me know how do we add google_meter.py file in iron python and access its methods as i am new to python?
Thanks in Advance,
-Mohsin
| [
"I suggest you read the part of the Python manual that explains how modules work.\n"
] | [
2
] | [] | [] | [
".net",
"ironpython",
"python"
] | stackoverflow_0006368410_.net_ironpython_python.txt |
Q:
Python - How do I implement readers/writers in a Bulletin Board Pattern with encrypted posts
I have the following classes:
class MessageBoard:
def __init__(self):
self.messages = []
self.readers = {}
def post(self, message):
self.messages.append(message)
def register_reader(s... | Python - How do I implement readers/writers in a Bulletin Board Pattern with encrypted posts | I have the following classes:
class MessageBoard:
def __init__(self):
self.messages = []
self.readers = {}
def post(self, message):
self.messages.append(message)
def register_reader(self, reader):
self.readers[reader.name] = reader.public_key
class Reader:
def __ini... | [
"If you really want to do this (generate and store private keys centrally), see these instructions - relevant code snippet below for reference:\n>>> from Crypto.PublicKey import RSA\n>>> from Crypto import Random\n>>> random_generator = Random.new().read\n>>> private_key = RSA.generate(1024, random_generator)\n>>> ... | [
2
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0006367645_encryption_python.txt |
Q:
How are basic data types (strings and integers) implemented in Python and Perl
I've been wondering lately how various operations I perform on basic types like strings and integers work in terms of performance, and I figure I could get a much better idea of this if I knew how those basic types were implemented (i.e... | How are basic data types (strings and integers) implemented in Python and Perl | I've been wondering lately how various operations I perform on basic types like strings and integers work in terms of performance, and I figure I could get a much better idea of this if I knew how those basic types were implemented (i.e. I've heard strings and integers are immutable in Python. Does that mean any operat... | [
"In python, some_string[5] = 'a' would be an error, but the closest equivalent operation, some_string = some_string[5:] + 'a' + some_string[6:] would indeed be O(n). But that's not just true of immutable objects. The same is true for concatenating lists: [1,2,3] + [4,5,6] generates a new list and is O(n). \nAdding ... | [
7,
6
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0006364430_perl_python.txt |
Q:
Should you use attribute references in Python?
Allowing 'Attribute references ' is against Encapsulation/Data Hiding.
In development we sholud avoid using it. right ?
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
MyClass.i=98765
A:
"Data hiding" is s... | Should you use attribute references in Python? | Allowing 'Attribute references ' is against Encapsulation/Data Hiding.
In development we sholud avoid using it. right ?
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
MyClass.i=98765
| [
"\"Data hiding\" is simply one aspect of OOP, not part of the definition of it. And \"encapsulation\" is a separate concept.\n",
"Python most certainly is not pure OOP. For one, it doesn't enforce data hiding. Also, users of objects can add attributes on the fly. Also, there are several APIs in the libraries that... | [
2,
2,
1,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0006368174_oop_python.txt |
Q:
counting (large number of) strings within (very large) text
I've seen a couple variations of the "efficiently search for strings within file(s)" question on Stackoverflow but not quite like my situation.
I've got one text file which contains a relatively large number (>300K) of strings. The vast majority of... | counting (large number of) strings within (very large) text | I've seen a couple variations of the "efficiently search for strings within file(s)" question on Stackoverflow but not quite like my situation.
I've got one text file which contains a relatively large number (>300K) of strings. The vast majority of these strings are multiple words (for ex., "Plessy v. Ferguson",... | [
"An easy way to solve this is to build a trie with your queries (simply a prefix tree, list of nodes with a single character inside), and when you search through your 10gb file you go through your tree recursively as the text matches. \nThis way you prune a lot of options really early on in your search for each cha... | [
2,
0,
0,
0
] | [
"I don't know if this idea is extremely stupid or not, please let me know...\nDivide the files to be searched into reasonably sized numbers 10/100/1000... and for each \"chunk\" use an indexing SW available for SW. Here I'm thinking about ctags gnu global or perhaps the ptx utility or using a technique described in... | [
-1
] | [
"full_text_search",
"lucene",
"nltk",
"python"
] | stackoverflow_0006361600_full_text_search_lucene_nltk_python.txt |
Q:
WMI to report Windows swapping
We are using Tim Golden's WMI Python hooks to report on the status of Windows system state to try and get similar reports to our Linux servers.
We are presently extracting the 'FreePhysicalMemory' and 'TotalVisibleMemorySize' from a 'Win32_OperatingSystem' class call.
Our problem is... | WMI to report Windows swapping | We are using Tim Golden's WMI Python hooks to report on the status of Windows system state to try and get similar reports to our Linux servers.
We are presently extracting the 'FreePhysicalMemory' and 'TotalVisibleMemorySize' from a 'Win32_OperatingSystem' class call.
Our problem is that memory is often reported at 10... | [
"After going through the various memory classes, it appears that the following will provide at least an indication of swapping:\nSELECT PagesPersec FROM Win32_PerfFormattedData_PerfOS_Memory\n\nAccording to wmifun.net, PagesPersec is\n\nPages/sec is the rate at which pages are read from or written to disk to resolv... | [
0
] | [] | [] | [
"memory",
"performance",
"python",
"wmi"
] | stackoverflow_0006365470_memory_performance_python_wmi.txt |
Q:
Facebook Graph API create_event error password parameter required
I'm trying to create an event from my Django app using the Facebook Graph API (via the python-sdk). I'm using the http://github.com/mscheibe/python-sdk fork, which is all good. I log my user in, get and store the access token etc.
The problem is wh... | Facebook Graph API create_event error password parameter required | I'm trying to create an event from my Django app using the Facebook Graph API (via the python-sdk). I'm using the http://github.com/mscheibe/python-sdk fork, which is all good. I log my user in, get and store the access token etc.
The problem is when I go to push the new event up I'm getting this error message back: "... | [
"Oh dear, right the error message I was getting back was misleading me. What was actually happening was a error in a loop in my form. It was converting my entire dictionary output into a json string, rather than the individual parameters (if necessary) in the dictionary.\nSo thats easily fixed! Now I'm only using j... | [
0
] | [] | [] | [
"django",
"facebook",
"facebook_graph_api",
"python"
] | stackoverflow_0006356020_django_facebook_facebook_graph_api_python.txt |
Q:
Pixel manipulation with PIL.Image and ctypes
I have a C function that does some pixel manipulation on a raw 2D array of 8 bit RGB values. I get the response in a c_ubyte array. My code looks roughly like this:
from ctypes import cdll, CDLL, Structure, byref, c_utype, c_uint
# get a reference to the C shared libra... | Pixel manipulation with PIL.Image and ctypes | I have a C function that does some pixel manipulation on a raw 2D array of 8 bit RGB values. I get the response in a c_ubyte array. My code looks roughly like this:
from ctypes import cdll, CDLL, Structure, byref, c_utype, c_uint
# get a reference to the C shared library
cdll.loadLibrary(path_to_my_c_lib)
myclib = CDL... | [
"I am not a PIL user, but usually, the frombuffer methods are designed for this kind of job:\nHave you tested Image.frombuffer?\nhttp://effbot.org/imagingbook/image.htm\nedit:\nApparently sometime the solution is right under our noses:\nim = Image.frombuffer('RGB', (img.width, img.height), buff, 'raw', 'RGB', 0, 1)... | [
2
] | [] | [] | [
"ctypes",
"python",
"python_imaging_library"
] | stackoverflow_0006368645_ctypes_python_python_imaging_library.txt |
Q:
Django elegant rendering engine redirect quest
I'm trying to find a nice and elegant solution for detecting rendering engines (mozilla, webkit, etc) and redirecting visitors to the right templates and css.
Currently I have this setup:
detection(middleware):
import re
class BrowserDetectionMiddleware(object):
... | Django elegant rendering engine redirect quest | I'm trying to find a nice and elegant solution for detecting rendering engines (mozilla, webkit, etc) and redirecting visitors to the right templates and css.
Currently I have this setup:
detection(middleware):
import re
class BrowserDetectionMiddleware(object):
def __init__(self):
self.data_browser = [
... | [
"The most elegant solution is to use a cross-browser CSS framework (like blueprint, 960.gs, 52framework, etc). There are a ton out there, pick one...\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006368794_django_python.txt |
Q:
In django, is there a way to keep a user on a stage of a wizard until they're reado to move on?
In django, is there a way to keep users on a stage of a forms wizard until they're ready?
Where if a user clicks on yes, the current contents of that stage are saved, the stage cleared and so on.
A:
You can use javas... | In django, is there a way to keep a user on a stage of a wizard until they're reado to move on? | In django, is there a way to keep users on a stage of a forms wizard until they're ready?
Where if a user clicks on yes, the current contents of that stage are saved, the stage cleared and so on.
| [
"You can use javascript to control form validation, submission, workflow, etc. I'm not entirely sure what you want, but if you need more precise control over the client-side interaction you'll almost certainly need to use javascript.\n"
] | [
0
] | [] | [] | [
"django",
"django_formwizard",
"python",
"user_interface"
] | stackoverflow_0006368999_django_django_formwizard_python_user_interface.txt |
Q:
How to create a thread-safe singleton in python
I would like to hold running threads in my Django application. Since I cannot do so in the model or in the session, I thought of holding them in a singleton. I've been checking this out for a while and haven't really found a good how-to for this.
Does anyone know how... | How to create a thread-safe singleton in python | I would like to hold running threads in my Django application. Since I cannot do so in the model or in the session, I thought of holding them in a singleton. I've been checking this out for a while and haven't really found a good how-to for this.
Does anyone know how to create a thread-safe singleton in python?
EDIT: ... | [
"Unless you have a very good reason - you should execute the long running threads in a different process altogether, and use Celery to execute them:\n\nCelery is an open source asynchronous\n task queue/job queue based on\n distributed message passing. It is\n focused on real-time operation, but\n supports sche... | [
3,
1
] | [] | [] | [
"django",
"python",
"singleton",
"thread_safety"
] | stackoverflow_0006368302_django_python_singleton_thread_safety.txt |
Q:
Django: Create a queryset
I have a Friendship model which looks like this:
from_user = ForeignKey(User, related_name='friends')
to_user = ForeignKey(User, related_name='friends_')
I have a manager to get all the Friendship models of a user:
def for_user(self, user):
return self.filter( Q(to_user=user) | Q(fro... | Django: Create a queryset | I have a Friendship model which looks like this:
from_user = ForeignKey(User, related_name='friends')
to_user = ForeignKey(User, related_name='friends_')
I have a manager to get all the Friendship models of a user:
def for_user(self, user):
return self.filter( Q(to_user=user) | Q(from_user=user) )
So now I would ... | [
"User.objects.filter(Q(friends__to_user=someuser)|Q(friends___from_user=someuser))\n\nNo clue if that second Q() will actually work, but that's what you've decided to call the related field.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006369539_django_python.txt |
Q:
How to get a .bmp Image file pixels value with jython
i want to get a pixel RGB with jython.
how can i get the pixel value of a .bmp file with a usual module or no module in jython.
A:
Have a look @ PIL google tells me this it should work with jython.
| How to get a .bmp Image file pixels value with jython | i want to get a pixel RGB with jython.
how can i get the pixel value of a .bmp file with a usual module or no module in jython.
| [
"Have a look @ PIL google tells me this it should work with jython.\n"
] | [
1
] | [] | [] | [
"bitmap",
"image",
"jython",
"python"
] | stackoverflow_0006369621_bitmap_image_jython_python.txt |
Q:
Model an equation as a tree
i want to model an equation as a tree in python.
for example:
x = exp(((-0.5)*((f/sqrt(d))**2)))
how do i do this? i want to be able to switch tree branches,
delete parts of the tree etc, and then convert it back into
a new equation in text form.
can you give me example code/ Libra... | Model an equation as a tree | i want to model an equation as a tree in python.
for example:
x = exp(((-0.5)*((f/sqrt(d))**2)))
how do i do this? i want to be able to switch tree branches,
delete parts of the tree etc, and then convert it back into
a new equation in text form.
can you give me example code/ Libraries that can do this?
cheers
ed... | [
"Operators and functions are parent nodes, and operands are the leaves.\nx = exp(((-0.5)*((f/sqrt(d))**2)))\n\nStart with a top-down approach: [ operator { operand1, operand2 }]\n[ = { x, exp(((-0.5)*((f/sqrt(d))**2))) }]\n\nfollowed by:\n[ = { x, [ * { exp(((-0.5), ((f/sqrt(d))**2))) }] }]\n\nthen: \n[ = { x, [ * ... | [
1,
0,
0
] | [] | [] | [
"binary_tree",
"parsing",
"python"
] | stackoverflow_0006369851_binary_tree_parsing_python.txt |
Q:
python - Change multiple files of same extensions
I am running a script that would change the contents inside a file with extension hgx.
E.g. test.hgx
Now, I have multiple files with extension hgx and I would like to run this same script for all the files (with extension hgx).
My current script looks like:
file_na... | python - Change multiple files of same extensions | I am running a script that would change the contents inside a file with extension hgx.
E.g. test.hgx
Now, I have multiple files with extension hgx and I would like to run this same script for all the files (with extension hgx).
My current script looks like:
file_name = "test.hgx"
x = open(file_name,'r')
....(and so on... | [
"Use glob.iglob():\nfor filename in glob.iglob(\"*.hgx\"):\n with open(filename) as f:\n # process file f here\n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0006370034_python.txt |
Q:
pythonic way to split list?
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I Have a function like below:
def split_list(self,my_list,num):
.....
.....
where my_list is:
my_list = [['1','one'],['2','two'],['3','three'],['4','four'],['5','five'],['6','six'],['7','... | pythonic way to split list? |
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
I Have a function like below:
def split_list(self,my_list,num):
.....
.....
where my_list is:
my_list = [['1','one'],['2','two'],['3','three'],['4','four'],['5','five'],['6','six'],['7','seven'],['8','eight']]
I want t... | [
"I'd just use a list comprehension/generator:\n[my_list[x:x+num] for x in range(0, len(my_list), num)]\n\n",
"def split_list(lst, num):\n def splitter(lst, num):\n while lst:\n head = lst[:num]\n lst = lst[num:]\n yield head\n return list(splitter(lst, num))\n\nHere i... | [
3,
0,
0
] | [] | [] | [
"list",
"python",
"split"
] | stackoverflow_0006369734_list_python_split.txt |
Q:
Updating a utility to show the date last modified
I am creating SIMPLE LOG FILE UTLITY gui using python. Each time I run the program, the source file is copied to the destination file and the source file is deleted. When the utility is started I want the display to say "The Log file was last updated (date goes he... | Updating a utility to show the date last modified | I am creating SIMPLE LOG FILE UTLITY gui using python. Each time I run the program, the source file is copied to the destination file and the source file is deleted. When the utility is started I want the display to say "The Log file was last updated (date goes here)". I have created a function named modification() us... | [
"You can find the answers on the Python docs :\nThe getmtime function (http://docs.python.org/library/os.path.html#os.path.getmtime) returns the number of seconds\nThanks to the Time module (http://docs.python.org/library/time.html), you can convert the number you get into local time (localtime()) or UTC time (with... | [
1,
0
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0006370138_python_user_interface.txt |
Q:
No module named optparse (IRON PYTHON)
when i add get_events_devices.py to the ironpython and import it at namespace it gave me error
"No module named optparse" and take me to hilight that error in its code "get_events_devices.py" at this line (from optparse import OptionParser)
please help me out
Regards,
... | No module named optparse (IRON PYTHON) | when i add get_events_devices.py to the ironpython and import it at namespace it gave me error
"No module named optparse" and take me to hilight that error in its code "get_events_devices.py" at this line (from optparse import OptionParser)
please help me out
Regards,
| [
"The latest version of optparse from 2.6.x\n"
] | [
1
] | [] | [] | [
".net",
"ironpython",
"python"
] | stackoverflow_0006370596_.net_ironpython_python.txt |
Q:
Making list of first line and everything else from a string
There is a string:
str = "first line\n xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz"
I need to get a list with two elements: first line and everything else:
list = ['first line\n', ' xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz']
How can I do it?
A:
print str.split('\n', 1)
['... | Making list of first line and everything else from a string | There is a string:
str = "first line\n xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz"
I need to get a list with two elements: first line and everything else:
list = ['first line\n', ' xxxxxxxxxxxxx\n zzzzzzzzzzzzzzz']
How can I do it?
| [
"print str.split('\\n', 1)\n['first line', ' xxxxxxxxxxxxx\\n zzzzzzzzzzzzzzz']\n\nThe first element don't have '\\n' if you want to keep it do:\nsplited = str.partition('\\n') \nprint [splited[0] + splited[1], splited[2]]\n['first line\\n', ' xxxxxxxxxxxxx\\n zzzzzzzzzzzzzzz']\n\nAnd don't name your string str bec... | [
8,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0006370585_python.txt |
Q:
How to parse a file , find out the dict in it , and then create a dict out of it?
# This is an auto-generated Django model module created by ogrinspect.
from django.contrib.gis.db import models
class Parking(models.Model):
name = models.CharField(max_length=80)
descriptio = models.CharField(max_length=80)... | How to parse a file , find out the dict in it , and then create a dict out of it? | # This is an auto-generated Django model module created by ogrinspect.
from django.contrib.gis.db import models
class Parking(models.Model):
name = models.CharField(max_length=80)
descriptio = models.CharField(max_length=80)
geom = models.PointField(srid=4326)
objects = models.GeoManager()
# Auto-gene... | [
"use json module\nmydict = {'name' : 'foo'}\n\n\nwith open('dump.json', 'w') as f:\n json_str = json.dumps(mydict) // save json_str in database \n f.write(json_str)\n\ncontents = None\nwith open('dump.json') as f:\n json_str = json.loads(f.read())\n contents = json_str\n\nYou could walk over contents an... | [
0,
0
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0006366094_django_models_python.txt |
Q:
Python: Pass execution statement as function parameter
retVal = None
retries = 5
success = False
while retries > 0 and success == False:
try:
retVal = graph.put_event(**args)
success = True
except:
retries = retries-1
logging.info('Facebook put_event timed out. Retrying.')
... | Python: Pass execution statement as function parameter | retVal = None
retries = 5
success = False
while retries > 0 and success == False:
try:
retVal = graph.put_event(**args)
success = True
except:
retries = retries-1
logging.info('Facebook put_event timed out. Retrying.')
return success, retVal
In the code above, how can I wrap th... | [
"To directly answer your question:\ndef foo(func, *args, **kwargs):\n retVal = None\n retries = 5\n success = False\n while retries > 0 and success == False:\n try:\n retVal = func(*args, **kwargs)\n success = True\n except:\n retries = retries-1\n ... | [
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0006371041_python.txt |
Q:
Python KeyboardInterrupt button
I'm using red hat 5 linux, and I would like to know what key combination raises a KeyboardInterrupt exception in python 2.6. I know that it is Ctrl+ c under windows.
Regards,
A:
It's still CtrlC. Or you could send a SIGINT to the process.
| Python KeyboardInterrupt button | I'm using red hat 5 linux, and I would like to know what key combination raises a KeyboardInterrupt exception in python 2.6. I know that it is Ctrl+ c under windows.
Regards,
| [
"It's still CtrlC. Or you could send a SIGINT to the process.\n"
] | [
7
] | [] | [] | [
"keyboardinterrupt",
"linux",
"python"
] | stackoverflow_0006371060_keyboardinterrupt_linux_python.txt |
Q:
Python CGI how to save requested information securely?
I have a web page that uses a Python cgi script to store requested information for later retrieval by me. As an example, the web page has a text box that asks "What is your name?" When the user inputs his name and hits the submit button, the web page calls the... | Python CGI how to save requested information securely? | I have a web page that uses a Python cgi script to store requested information for later retrieval by me. As an example, the web page has a text box that asks "What is your name?" When the user inputs his name and hits the submit button, the web page calls the Python cgi script which writes the user's name to mytextfil... | [
"Definitely the wrong tool. Multiple times.\n\nStore the file outside of the document root.\nStore a key to the file in the user's session.\nUse a web framework.\nUse WSGI.\n\n",
"Store it outside the document root.\n"
] | [
2,
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0006371097_cgi_python.txt |
Q:
AnonymousUser problem in Django, Feedback App
user = models.ForeignKey(User,)
I have a user foreignkey in models.py
if request.user.is_authenticated():
feedback.user = request.user
else:
feedback.user = 'something'
In views.py, If user logged in feedback.user area, write username else write something... | AnonymousUser problem in Django, Feedback App | user = models.ForeignKey(User,)
I have a user foreignkey in models.py
if request.user.is_authenticated():
feedback.user = request.user
else:
feedback.user = 'something'
In views.py, If user logged in feedback.user area, write username else write something there.
How can I do this in Django.
I was trying t... | [
"Either require the user to be logged in for the view, or handle it yourself and assign None.\n"
] | [
1
] | [] | [] | [
"authentication",
"django",
"feedback",
"python"
] | stackoverflow_0006371110_authentication_django_feedback_python.txt |
Q:
How to use fb's social plugin for registering users in django
I'm trying to integrate the registration social plugin on my django application, but I'm having some problems reading the signed request that fb sends back.
Are there some examples that show how to decode the request in Python?
A:
This is some sample ... | How to use fb's social plugin for registering users in django | I'm trying to integrate the registration social plugin on my django application, but I'm having some problems reading the signed request that fb sends back.
Are there some examples that show how to decode the request in Python?
| [
"This is some sample code from Facebook on writing a Canvas application. You are writing a website using their API, but the signed request stuff is similar. Here are the relevant parts:\nhttps://github.com/facebook/runwithfriends/blob/master/main.py#L276\nhttps://github.com/facebook/runwithfriends/blob/master/main.... | [
0
] | [] | [] | [
"django",
"facebook",
"python"
] | stackoverflow_0006370405_django_facebook_python.txt |
Q:
How do a debug an exception on python shutdown
When my process ends, I get output to stderr that looks like:
Exception exceptions.TypeError: "'NoneType' object is not callable" in <function <lambda> at 0x5507d70> ignored
My understanding is that this is caused by exceptions being generated during garbage collec... | How do a debug an exception on python shutdown | When my process ends, I get output to stderr that looks like:
Exception exceptions.TypeError: "'NoneType' object is not callable" in <function <lambda> at 0x5507d70> ignored
My understanding is that this is caused by exceptions being generated during garbage collection (del() ?) or the weakref callback which I know ... | [
"Run your Python program with the -v option so you can see at which point during the final stages the exception gets thrown. It helped me when I encountered the same situation; also with sqlalchemy...\n",
"The issue here isn't with lambdas: lambda functions do have debug information.\na = lambda: 1\nprint a.func_... | [
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0003097623_python.txt |
Q:
Http Error 405/500 in Python/Mechanize (using mechanize auto login one website)
Here is the website's address on which i want to using python/mechanize to auto login:
http://www.autohome.com.cn/tools/hometoplogin.html
And here is my code:
br = Browser()
login_url = 'http://www.autohome.com.cn/tools/hometoplogin.h... | Http Error 405/500 in Python/Mechanize (using mechanize auto login one website) | Here is the website's address on which i want to using python/mechanize to auto login:
http://www.autohome.com.cn/tools/hometoplogin.html
And here is my code:
br = Browser()
login_url = 'http://www.autohome.com.cn/tools/hometoplogin.html'
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.open(login_url)
br.select_... | [
"If you can open this page with a browser, chances are that the website does not allow bots or programs like yours to access or log in. In that case you must fake your identity by setting your User-Agent header, as Kimvais said.\n"
] | [
0
] | [] | [] | [
"authentication",
"http",
"mechanize",
"python"
] | stackoverflow_0006369097_authentication_http_mechanize_python.txt |
Q:
Python: Best 3D format for real-time rendering?
What is the most convenient or common 3D format for Python? In terms of 3D model loader, rendering, animation support ?
Thank you!
A:
I think vPython should do your job.
A:
I've found vPython the easiest, however pyopengl is good if you want to get more specific ... | Python: Best 3D format for real-time rendering? | What is the most convenient or common 3D format for Python? In terms of 3D model loader, rendering, animation support ?
Thank you!
| [
"I think vPython should do your job.\n",
"I've found vPython the easiest, however pyopengl is good if you want to get more specific http://pyopengl.sourceforge.net/\n",
"Maybe Panda3d is useful to you.\n"
] | [
2,
1,
1
] | [] | [] | [
"3d",
"python",
"wxpython"
] | stackoverflow_0006371198_3d_python_wxpython.txt |
Q:
strange django import behaviour
Could someone please explain this behaviour:
django project called foo
file bar/models.py:
class MyModelError(TypeError):
pass
class MyModel(models.Model):
...
./manage.py shell
>>> from foo.bar.models import MyModel as m1
>>> from bar.models import MyModel as m2
>>> from ... | strange django import behaviour | Could someone please explain this behaviour:
django project called foo
file bar/models.py:
class MyModelError(TypeError):
pass
class MyModel(models.Model):
...
./manage.py shell
>>> from foo.bar.models import MyModel as m1
>>> from bar.models import MyModel as m2
>>> from foo.bar.models import MyModelError as... | [
"Django uses metaclasses for defining models. There's a check in there to avoid defining a model twice, so when a class is created if it's already been defined then you get the version that was defined before. See django.db.models.base.ModelBase:\nfrom django.db.models.loading import get_model\n\n# Bail out early ... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006371129_django_python.txt |
Q:
Plotting ODEs, Isoclines using Python
I am looking for a Python package that will allow me to plot something similar to the Java applet seen below:
http://math.mit.edu/mathlets/mathlets/isoclines/
Does anyone know any ODE plotting packages for this? I can code something from scratch using Numpy, Matplotlib, but I ... | Plotting ODEs, Isoclines using Python | I am looking for a Python package that will allow me to plot something similar to the Java applet seen below:
http://math.mit.edu/mathlets/mathlets/isoclines/
Does anyone know any ODE plotting packages for this? I can code something from scratch using Numpy, Matplotlib, but I wanted to ask around first.
Thanks,
| [
"I wrote something like this, it seems to work for y'=y^2-x\nfrom pylab import *\nxmax = 4.0\nxmin = -xmax\nD = 20\nymax = 4.0\nymin = -ymax\nx = linspace(xmin, xmax, D)\ny = linspace(ymin, ymax, D)\nX, Y = meshgrid(x, y)\ndeg = arctan(Y**2 - X)\nQP = quiver(X,Y,cos(deg),sin(deg))\nshow()\n\n\n",
"Sage will do th... | [
3,
1
] | [] | [] | [
"matplotlib",
"ode",
"python"
] | stackoverflow_0006370742_matplotlib_ode_python.txt |
Q:
Component-based game entities and type checking
I'm writing a game and it's going to use a component-based entity system. The first two components that I'm implementing are EntityRepresentation and EntityState. The representation holds the animations, and the state decides how the entity should react to game event... | Component-based game entities and type checking | I'm writing a game and it's going to use a component-based entity system. The first two components that I'm implementing are EntityRepresentation and EntityState. The representation holds the animations, and the state decides how the entity should react to game events (examples of EntityStates: standing, jumping, attac... | [
"Assuming that the IDs associated with each EntityState are not needed at compile time, one trick I've used is to use pointers as an ID. This works particularly well if the EntityState is a singleton, in which case you could simply use the address of the singleton instance as the ID. Otherwise statically allocating... | [
1,
1,
1
] | [] | [] | [
"c++",
"components",
"entity_system",
"python"
] | stackoverflow_0006371793_c++_components_entity_system_python.txt |
Q:
Find all coordinates within a circle in geographic data in python
I've got millions of geographic points. For each one of these, I want to find all "neighboring points," i.e., all other points within some radius, say a few hundred meters.
There is a naive O(N^2) solution to this problem---simply calculate the dis... | Find all coordinates within a circle in geographic data in python | I've got millions of geographic points. For each one of these, I want to find all "neighboring points," i.e., all other points within some radius, say a few hundred meters.
There is a naive O(N^2) solution to this problem---simply calculate the distance of all pairs of points. However, because I'm dealing with a prop... | [
"scipy\nFirst things first: there are preexisting algorithms to do things kind of thing, such as the k-d tree. Scipy has a python implementation cKDtree that can find all points in a given range.\nBinary Search\nDepending on what you're doing however, implementing something like that may be nontrivial. Furthermor... | [
8,
7
] | [] | [] | [
"distance",
"geo",
"geospatial",
"gis",
"python"
] | stackoverflow_0006371187_distance_geo_geospatial_gis_python.txt |
Q:
Some Pyramid + AJAX (Jquery) questions
In my Pyramid package directory, if I create a file called somefunction.py and I want to call this function using $.post, what URL would I specify to call this function?
If I have a view function called aview created in views.py, can I call this function by simply referring t... | Some Pyramid + AJAX (Jquery) questions |
In my Pyramid package directory, if I create a file called somefunction.py and I want to call this function using $.post, what URL would I specify to call this function?
If I have a view function called aview created in views.py, can I call this function by simply referring the $.post url as /aview/.
(script files re... | [
"In both cases you have to write the proper routing configuration that maps the view (that has to contain the function you want to call) to a given url. You even have a xhr parameter to further customize the request [1]. I should clarify btw that I'm more a dispatcher than a traversal guy so my answer applies to th... | [
3
] | [] | [] | [
"ajax",
"jquery",
"pylons",
"pyramid",
"python"
] | stackoverflow_0006371276_ajax_jquery_pylons_pyramid_python.txt |
Q:
Paramiko Authentication verification (turns out to be Python exception handling)
I'm writing a script in Python that pulls configurations from Cisco routers using Paramiko for the SSH connection. I am also trying to make it verify that the login credentials are correct for the device without failing.
Right now th... | Paramiko Authentication verification (turns out to be Python exception handling) | I'm writing a script in Python that pulls configurations from Cisco routers using Paramiko for the SSH connection. I am also trying to make it verify that the login credentials are correct for the device without failing.
Right now the code will connect and run the commands that I want if the credentials are correct. G... | [
"Take a look at section 8.3 (handling exceptions) on the Python manual. You can \"catch\" the exception and handle it, this will prevent the exception from causing your program to exit. Your program will only exit on an exception if no code catches it.\ntry:\n ssh = paramiko.SSHClient()\n ssh.set_missing_ho... | [
8
] | [] | [] | [
"authentication",
"paramiko",
"python",
"ssh"
] | stackoverflow_0006372266_authentication_paramiko_python_ssh.txt |
Q:
Is there an Ant task which can fetch an artifact from Hudson/Jenkins?
I've hand-rolled my project's build-system (mostly in Python + Hudson). One of the things I need to do quite often is fetch artifacts from upstream Hudson / Jenkins.
These artifacts could be almost anything - for example a zip-file full of busi... | Is there an Ant task which can fetch an artifact from Hudson/Jenkins? | I've hand-rolled my project's build-system (mostly in Python + Hudson). One of the things I need to do quite often is fetch artifacts from upstream Hudson / Jenkins.
These artifacts could be almost anything - for example a zip-file full of business data to process or even an egg containing a load of python code which ... | [
"The proper solution is to publish the artifacts from Hudson/Jenkins to an artifact manager, such as Nexus or Artifactory, and then pull the artifact versions with something like Ivy or Gradle.\n",
"If you must get the dependencies yourself, you could use the get task. Example:\n<get src=\"http://jenkins/job/proj... | [
7,
4,
0
] | [] | [] | [
"ant",
"hudson",
"java",
"jenkins",
"python"
] | stackoverflow_0006358692_ant_hudson_java_jenkins_python.txt |
Q:
Python use a virtual class to apply a generic "pipe" pattern
I am trying to find out if it would be possible to take the following code, and use the magic of python to simplify code.
Right now I have a command interface that sits on top of a bunch of python sub processes. When I need to communicate with the sub p... | Python use a virtual class to apply a generic "pipe" pattern | I am trying to find out if it would be possible to take the following code, and use the magic of python to simplify code.
Right now I have a command interface that sits on top of a bunch of python sub processes. When I need to communicate with the sub process's I pipe commands to them. Basically it comes down to a st... | [
"You can use __getattr__ to create proxy methods for your stub class:\nclass MasterProcessProxy(object):\n\n def __init__(self, pipe):\n self.pipe = pipe\n\n # This is called when an attribute is requested on the object.\n def __getattr__(self, name):\n # Create a dynamic function that sends ... | [
4,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0006372832_python_python_2.7.txt |
Q:
Problem grabbing parameters using execfile within a class
I have a problem similar to the first problem in this question, which as far as I can see went unanswered.
I have a file "config.py" which contains a lot of parameters to be used by a class (this config.py file will change), however I can't get these to pro... | Problem grabbing parameters using execfile within a class | I have a problem similar to the first problem in this question, which as far as I can see went unanswered.
I have a file "config.py" which contains a lot of parameters to be used by a class (this config.py file will change), however I can't get these to propagate into the class via execfile.
In an example piece of code... | [
"I don't get what you're trying to do (but i don't like it, and this is just me) but to fix your problem do (test in python2.6):\nclass Class():\n def __init__(self):\n execfile('config.py', locals()) # Not recommanded, maybe you want globals().\n print x\n\nBut from the doc:\n\nNote\nThe default ... | [
1,
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0006372703_class_python.txt |
Q:
unable to add app engine administrator for emailing
I want to send emails from my app engine application using one of my Google Apps accounts. According to the GAE python docs:
The From: address can be the email address of a registered administrator (developer) of the application, the current user if signed in wi... | unable to add app engine administrator for emailing | I want to send emails from my app engine application using one of my Google Apps accounts. According to the GAE python docs:
The From: address can be the email address of a registered administrator (developer) of the application, the current user if signed in with Google Accounts, or any valid email receiving address ... | [
"You must restrict your App Engine app to a Google Apps domain upon initial registration of your App Engine application ID. Unfortunately, this setting can only be set during the initial registration of your app ID.\nWhat you'll need to do is register another application ID, set your authentication option for Googl... | [
0,
0
] | [] | [] | [
"google_app_engine",
"java",
"python"
] | stackoverflow_0003183185_google_app_engine_java_python.txt |
Q:
How to Download a file to a specific path in the server : Python
How to download a file through http on to a local folder on my server in jython(or python)
The below code might work
os.chdir("/path/to/change/to")
from urllib2 import urlopen
f = urlopen("http://some.server/some/directory/some.file")
But for this ... | How to Download a file to a specific path in the server : Python | How to download a file through http on to a local folder on my server in jython(or python)
The below code might work
os.chdir("/path/to/change/to")
from urllib2 import urlopen
f = urlopen("http://some.server/some/directory/some.file")
But for this my Current working directory is changed.I want to be in the current wo... | [
"How about urllib.urlretrieve\nimport urllib\nurllib.urlretrieve('http://python.org/images/python-logo.gif', '/tmp/foo.gif')\n\n",
"Use open(..., 'wb') to open the file where you like, urllib2.urlopen() to open the network resource, and shutil.copyfileobj() to copy from one to the other.\n"
] | [
7,
1
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0006373094_jython_python.txt |
Q:
What version of python was this syntax added
I know it is possible to put an If/Else statement all on one line, similar to this.
[True if 1 else False]
What version of python was this added?
A:
It was added in Python 2.5.
A:
That was added in Python 2.5.
A:
2.5, it's talked about on Wikipedia.
| What version of python was this syntax added | I know it is possible to put an If/Else statement all on one line, similar to this.
[True if 1 else False]
What version of python was this added?
| [
"It was added in Python 2.5.\n",
"That was added in Python 2.5.\n",
"2.5, it's talked about on Wikipedia.\n"
] | [
9,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006373278_python.txt |
Q:
Executing A stored Procedure From Python
I am working with Python3 using a Module called ceODBC and trying to call a stored procedure in SQL Server 2005. When I run the stored procedure out of Sql Server Management Studio (without Python involved) I get the correct results and 278 rows are inserted into the desire... | Executing A stored Procedure From Python | I am working with Python3 using a Module called ceODBC and trying to call a stored procedure in SQL Server 2005. When I run the stored procedure out of Sql Server Management Studio (without Python involved) I get the correct results and 278 rows are inserted into the desired table, however in Python it stops after 31. ... | [
"Looking at http://ceodbc.sourceforge.net/html/cursor.html there is this comment:\nCursor.execdirect(statement)\nExecute a statement against the database using SQLExecDirect instead of SQLExecute. This is necessary in some situations due to bugs in ODBC drivers such as exhibited by the SQL Server ODBC driver when c... | [
1
] | [] | [] | [
"database",
"odbc",
"python",
"sql",
"stored_procedures"
] | stackoverflow_0006372894_database_odbc_python_sql_stored_procedures.txt |
Q:
What is the most pythonic way to import modules in python
Can anyone suggest me what is the most pythonic way to import modules in python?
Let me explain - i have read a lot of python code and found several different ways of how to import modules or if to be more precise - when to import:
Use one module/several ... | What is the most pythonic way to import modules in python | Can anyone suggest me what is the most pythonic way to import modules in python?
Let me explain - i have read a lot of python code and found several different ways of how to import modules or if to be more precise - when to import:
Use one module/several modules which include all the imports(third party modules) whic... | [
"It really doesn't matter, so long as you don't from ... import *. The rest is all taste and getting around cyclic import issues. PEP 8 states that you should import at the top of the script, but even that isn't set in stone.\n",
"People have already commented on the major style issues (at the top of the script, ... | [
17,
6,
3,
3
] | [] | [] | [
"python",
"python_import"
] | stackoverflow_0006372159_python_python_import.txt |
Q:
help() with unicode __author__ string
In the beginning of my scripts in Python 2.6, I would like to write my name as it is spelled, i.e. "Joël" (with trema on e). So I write __author__ = u'Joël', and I can retrieve it by a simple print __author__.
Problem appears with the built-in help() function, as I get an erro... | help() with unicode __author__ string | In the beginning of my scripts in Python 2.6, I would like to write my name as it is spelled, i.e. "Joël" (with trema on e). So I write __author__ = u'Joël', and I can retrieve it by a simple print __author__.
Problem appears with the built-in help() function, as I get an error message:
UnicodeEncodeError: 'ascii' code... | [
"Pydoc explicitly wants to convert the author name to ascii:\n File \"/usr/local/Cellar/python/2.7.1/lib/python2.7/pydoc.py\", line 1111, in docmodule\n result = result + self.section('AUTHOR', str(object.__author__))\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\xeb' in position 2: ordinal not ... | [
1,
1
] | [] | [] | [
"author",
"character_encoding",
"pydoc",
"python"
] | stackoverflow_0006373447_author_character_encoding_pydoc_python.txt |
Q:
Find all words placed on a Scrabble board
Any idea whats a simple and fast way to get all words placed on a Scrabble board while the board is represented by 2D Array of chars?
Thanks in advance
A:
This is similar to Artsiom's answer, but covers for the fact that a Scrabble board will have spaces in between words... | Find all words placed on a Scrabble board | Any idea whats a simple and fast way to get all words placed on a Scrabble board while the board is represented by 2D Array of chars?
Thanks in advance
| [
"This is similar to Artsiom's answer, but covers for the fact that a Scrabble board will have spaces in between words. \nSo assuming your \"2D Array of chars\" looks like this:\nboard = [['s','t','a','c','k',' ',' ',' '],\n ['p',' ',' ','a',' ','c',' ',' '],\n ['o','v','e','r','f','l','o','w'],\n ... | [
5,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006372616_python.txt |
Q:
App Engine TimeOut Error: Serving a third-party API with an image stored on App Engine
I'm building an application in Python on App Engine. My application receives images as email attachments. When an email comes in, I grab the image and need to send it to a third party API.
The first thing I did was:
1) make a PO... | App Engine TimeOut Error: Serving a third-party API with an image stored on App Engine | I'm building an application in Python on App Engine. My application receives images as email attachments. When an email comes in, I grab the image and need to send it to a third party API.
The first thing I did was:
1) make a POST request to the third party API with the image data
I stopped this method because I had so... | [
"If you directly use the App Engine URLfetch API, you can adjust the timeout for your request. The default is 5 seconds, and it can be increased to 10 seconds for normal handlers, or to 10 minutes for fetches within task queue tasks or cron jobs.\nIf the external API is going to take more than 10 seconds to respond... | [
1
] | [] | [] | [
"api",
"google_app_engine",
"image",
"python",
"timeout"
] | stackoverflow_0006370335_api_google_app_engine_image_python_timeout.txt |
Q:
Learning Python hit a snag on symple a simple program
I am just teaching myself python and trying to write a simple program. the goal is to calculate the number of pieces of equipment (HCAM) per 12 linear feet. I feel like I'm doing this the long way and I need to figure out how to write the equation so it only pr... | Learning Python hit a snag on symple a simple program | I am just teaching myself python and trying to write a simple program. the goal is to calculate the number of pieces of equipment (HCAM) per 12 linear feet. I feel like I'm doing this the long way and I need to figure out how to write the equation so it only produces 1 answer if the feet are greater than 24. Basically ... | [
"You missed the part on elif.\n",
"25 is greater than 12, and greater than 24, so it prints both. You want to check the greater number first (24) and then use elif (else if) so that it stops going through the other if statements.\n",
"As others have said before, your first issue is how you divide up your logic... | [
2,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006373734_python.txt |
Q:
image loading performance problems with python and gobject
I have a script with a GTK(GObject) interface I use for posting to my photo blog.
I'm trying to improve it's responsiveness by loading the images in a background thread.
I've had no luck trying to populate GdkPixbuf objects from a background thread, everyt... | image loading performance problems with python and gobject | I have a script with a GTK(GObject) interface I use for posting to my photo blog.
I'm trying to improve it's responsiveness by loading the images in a background thread.
I've had no luck trying to populate GdkPixbuf objects from a background thread, everything I've tried just jams solid.
So as an alternate I thought I'... | [
"My guess: you are doing something wrong. I've just compared libjpeg-turbo with gdk.PixbufLoader and found virtually no speed differences. The code I used is below.\nFor the libjpeg-turbo (jpegload.c):\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/time.h>\n\n#include <jpeglib.h>\n\nvo... | [
2,
1
] | [] | [] | [
"gobject",
"gtk",
"performance",
"python"
] | stackoverflow_0005839891_gobject_gtk_performance_python.txt |
Q:
add creation/modified time to python template in vim script
I wrote a simple python template in ~/.vim/template/pythontmp.txt,
and use
$> autocmd bufnewfile *.py :0r ~/.vim/template/pythontmp.txt
to load the template when i create a new python script.
The problem is that i'd like to add creation time to the com... | add creation/modified time to python template in vim script | I wrote a simple python template in ~/.vim/template/pythontmp.txt,
and use
$> autocmd bufnewfile *.py :0r ~/.vim/template/pythontmp.txt
to load the template when i create a new python script.
The problem is that i'd like to add creation time to the comment of the document.
How can I do this? Thanks!
| [
"You can use strftime function for this:\nif exists('*strftime')\n au BufNewFile *.py :call append(0, '# Created: '.strftime('%a, %d %b %Y %T %z'))\nendif\n\nAccording to the documentation, strftime is not present on some systems. See man strftime (if you are on *nix) for details of format.\n"
] | [
4
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0006366686_python_vim.txt |
Q:
Python client server communication
I'm trying to send some data from the server to the client, but the client doesn't get all the data.
Server:
def handle( self ):
#self.request.setblocking( 0 )
i = 10;
while True:
if( self.clientname == 'MasterClient' ): ... | Python client server communication | I'm trying to send some data from the server to the client, but the client doesn't get all the data.
Server:
def handle( self ):
#self.request.setblocking( 0 )
i = 10;
while True:
if( self.clientname == 'MasterClient' ):
try: ... | [
"Make sure you are receiving all data as it's not guaranteed to be sent in a single chunk. For example:\ndata = \"\"\nwhile True:\n chunk = sock.recv(4096)\n if not chunk:\n break\n data += chunk\n\n",
"Reads are not symmetrical with writes when using TCP, very often the receiving OS will return ... | [
1,
1
] | [] | [] | [
"client_server",
"python"
] | stackoverflow_0006370683_client_server_python.txt |
Q:
Animate an image sequence in OpenCV
I am trying to take a series of images captured from a webcam (jpgs) and animate them via OpenCV / Python. I know I can play back a pre-recorded video file via cv.CreateFileCapture and cv.QueryFrame, but how does this work with a folder of still images?
A:
You could simply do ... | Animate an image sequence in OpenCV | I am trying to take a series of images captured from a webcam (jpgs) and animate them via OpenCV / Python. I know I can play back a pre-recorded video file via cv.CreateFileCapture and cv.QueryFrame, but how does this work with a folder of still images?
| [
"You could simply do a cvShowImage and then a cvWaitKey(delay) in a loop and set delay to something appropriate for your desired framerate.\nimport glob\nimport opencv.highgui\n\nhighgui.cvNamedWindow('mahMovie')\n\n# Assumes an ordered sequence of filenames (001.jpg, 002.jpg, etc)\nfor filename in sorted(glob.glob... | [
2,
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0005760841_opencv_python.txt |
Q:
Is there anything for Python that is like readability.js?
I'm looking for a package / module / function etc. that is approximately the Python equivalent of Arc90's readability.js
http://lab.arc90.com/experiments/readability
http://lab.arc90.com/experiments/readability/js/readability.js
so that I can give it some i... | Is there anything for Python that is like readability.js? | I'm looking for a package / module / function etc. that is approximately the Python equivalent of Arc90's readability.js
http://lab.arc90.com/experiments/readability
http://lab.arc90.com/experiments/readability/js/readability.js
so that I can give it some input.html and the result is cleaned up version of that html pag... | [
"Please try my fork https://github.com/buriy/python-readability which is fast and has all features of latest javascript version.\n",
"We've just launched a new natural language processing API over at repustate.com. Using a REST API, you can clean any HTML or PDF and get back just the text parts. Our API is free s... | [
11,
4,
3,
1,
0
] | [
"I think BeautifulSoup is the best HTML parser for python. But you still need to figure out what the \"main\" part of the site is. \nIf you're only parsing a single domain, it's fairly straight forward, but finding a pattern that works for any site is not so easy. \nMaybe you can port the readability.js approach to... | [
-3
] | [
"heuristics",
"html_content_extraction",
"javascript",
"python"
] | stackoverflow_0002921237_heuristics_html_content_extraction_javascript_python.txt |
Q:
Can i transform java classes in Django project
I don't have much experience with Django. I have the class diagram with 25 classes and attributes and getters and setters. And the UML Diagram of all classes.
Now i Initially design that so that i make project in java / hibernate.
But now i have to make the site in Dj... | Can i transform java classes in Django project | I don't have much experience with Django. I have the class diagram with 25 classes and attributes and getters and setters. And the UML Diagram of all classes.
Now i Initially design that so that i make project in java / hibernate.
But now i have to make the site in Django. so i want to know that does django also suppor... | [
"This is a really hard question to answer. Keep in mind the Django is not a language in and of itself, but is a frame work built on python. It therefor supports everything python does.\nSo... \nStep 1: Learn python.\nGood tutorials include:\nthe official python tutorial: http://docs.python.org/tutorial/\nLearn pyth... | [
2,
1
] | [] | [] | [
"class",
"django",
"python"
] | stackoverflow_0006374031_class_django_python.txt |
Q:
Run "python manage.py runserver" from a bash script
I want to run "python manage.py runserver" from a bash script
First if I wanted to run from a terminal "python manage.py runserver &" but it doesn't work. I found the fix for this in (https://code.djangoproject.com/changeset/16327). Manually in a terminal runnin... | Run "python manage.py runserver" from a bash script | I want to run "python manage.py runserver" from a bash script
First if I wanted to run from a terminal "python manage.py runserver &" but it doesn't work. I found the fix for this in (https://code.djangoproject.com/changeset/16327). Manually in a terminal running "python manage.py runserver &" works fine.
I've added ... | [
"The problem is probably that hudson is not running as your user... you could run\nsource /home/your_user/.bashrc && django_serve \n\nto make it run that alias, but I think you'll probably need to switch users\n-- or --\nhave hudson run the dev server from it's own checkout of the source\nEdit: Looking at your erro... | [
6,
0
] | [] | [] | [
"bash",
"django",
"hudson",
"python",
"selenium"
] | stackoverflow_0006369054_bash_django_hudson_python_selenium.txt |
Q:
Python-brisa works in Eclipse but not in the shell
The next python-brisa code works in Eclipse but gets stuck if I execute it from the shell. I think that the problem is in reactor.main(). Because if I comment it and I create a infinite loop the program works in Eclipse and in the shell. Any idea of how can I fix ... | Python-brisa works in Eclipse but not in the shell | The next python-brisa code works in Eclipse but gets stuck if I execute it from the shell. I think that the problem is in reactor.main(). Because if I comment it and I create a infinite loop the program works in Eclipse and in the shell. Any idea of how can I fix it?
The python version is the 2.6.6 and I am using Debia... | [
"I found the \"error\". The solution was substitute the line:\ncommand = str(raw_input('>>>'))\n\nby\nprint '>>> ',\ncommand = sys.stdin.readline().replace('\\n','')\n\nI am not sure but maybe the reason of this can be in this explanation:\nhttp://pydev.org/faq.html#why_raw_input_input_does_not_work_correctly\nIf s... | [
0
] | [] | [] | [
"linux",
"pydev",
"python",
"scripting"
] | stackoverflow_0006368793_linux_pydev_python_scripting.txt |
Q:
Python--Timedelta expression ignoring days (treating 6 mins the same as 24 hours + 6mins)
I'm trying to calculate the number of hours since a post has gone live. It works, except it treats 24 hours later as 0 hours. In other words, it seems to just subtract the current time from the baseline time without taking ... | Python--Timedelta expression ignoring days (treating 6 mins the same as 24 hours + 6mins) | I'm trying to calculate the number of hours since a post has gone live. It works, except it treats 24 hours later as 0 hours. In other words, it seems to just subtract the current time from the baseline time without taking into consideration day differentials.
def hours_live(self):
diff=((datetime.datet... | [
"You want total_seconds(), not seconds.\n",
"Don't forget you can use Django timesince filter too as an option :)\n>>> import datetime\n>>> past = datetime.datetime.now() - datetime.timedelta(hours=6, minutes=20)\n>>>\n>>> from django.template.defaultfilters import timesince\n>>> timesince(past)\nu'6 hours, 20 mi... | [
6,
3
] | [] | [] | [
"datetime",
"django",
"python"
] | stackoverflow_0006374527_datetime_django_python.txt |
Q:
How do redirect from Django Authentication backend
We use custom authentication for our django webapp, where we hit the company ldap. Since we're using a custom backend, we seem to only be able to return None, or the username of a user from our db.
def authenticate(self,username,password):
"""
Authenticat... | How do redirect from Django Authentication backend | We use custom authentication for our django webapp, where we hit the company ldap. Since we're using a custom backend, we seem to only be able to return None, or the username of a user from our db.
def authenticate(self,username,password):
"""
Authenticate the username credentials, and return the
"""
... | [
"I'd look at raising a custom exception in your auth backend, and catch it in your login view. Returning None from your auth backend simply means \"I couldn't authenticate these credentials - try the next backend\".\nSo, in pseudo-code,\nclass LoginView(TemplateView):\n def post(self, request):\n try:\n ... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006374584_django_python.txt |
Q:
Django create groups on init, extending superuser profile
I create a site in Django and here is my Question
How to make something like this:
On init (for example, when someone run "syncdb"?)
I need to create a group with permissions
and extend superuser profile from User to UserProfile(when user register it's not ... | Django create groups on init, extending superuser profile | I create a site in Django and here is my Question
How to make something like this:
On init (for example, when someone run "syncdb"?)
I need to create a group with permissions
and extend superuser profile from User to UserProfile(when user register it's not a problem but first admin/superuser is autocreated when app is ... | [
"2 steps:\n\nTake a dump from an existing database containing all the required data using the command dumpdata\nAfter syncdb, load the fixture using the command loaddata\n\n",
"Hook the post_syncdb signal in your management subpackage and do the work there.\n",
"I guess fixtures can help you out with your probl... | [
6,
2,
1
] | [] | [] | [
"django",
"django_syncdb",
"python"
] | stackoverflow_0006374899_django_django_syncdb_python.txt |
Q:
Django tagging-tags how to get queryset of top tags?
I want to write a manager function for a class that returns the associated tags for a model and assigns a count value to each tag.
For example:
#models.py
class Snippet(models.Model):
...
tags = TagField()
objects = managers.SnippetManager()
-------... | Django tagging-tags how to get queryset of top tags? | I want to write a manager function for a class that returns the associated tags for a model and assigns a count value to each tag.
For example:
#models.py
class Snippet(models.Model):
...
tags = TagField()
objects = managers.SnippetManager()
-------------
#managers.py:
from tagging.models import Tag
class... | [
"So here's a way I've found to do it.\nBasically I'm ignoring the view data completely and using the tagging-tags template tags to directly access the model contents.\nSo\n#managers.py\nclass SnippetManager(models.Manager):\ndef top_tags(self, klass):\n return Tag.objects.all()\n\nand then...\n{% comment %} top_... | [
0
] | [] | [] | [
"count",
"django",
"django_models",
"python",
"tagging"
] | stackoverflow_0006364922_count_django_django_models_python_tagging.txt |
Q:
Unknown screen output of manually installed Python 2.7
I installed Python 2.7 today using:
./configure --prefix=/home/zhanwu/local --enable-shared --enable-profiling --with-pydebug
make install
Then I keep getting something like "[37745 refs]" on screen after each function call:
[zhanwu@cluster ~]$ ~/local/bin/py... | Unknown screen output of manually installed Python 2.7 | I installed Python 2.7 today using:
./configure --prefix=/home/zhanwu/local --enable-shared --enable-profiling --with-pydebug
make install
Then I keep getting something like "[37745 refs]" on screen after each function call:
[zhanwu@cluster ~]$ ~/local/bin/python
Python 2.7.1 (r271:86832, Jun 16 2011, 17:45:05)
[GCC ... | [
"You get these because you configured the build with --with-pydebug. They denote the number of references Python is currently keeping track of. To get rid of them, configure without --with-pydebug.\n"
] | [
10
] | [] | [] | [
"python"
] | stackoverflow_0006375120_python.txt |
Q:
Using signal to pop-up a screen
I'm having a little trouble using a signal to make a little screen appear.
Shortening all i have so far, this following code should show my problem.
import sys
from PyQt4 import QtGui, QtCore
qApp = QtGui.QApplication(sys.argv)
class InformatieVenster(QtGui.QMainWindow):
def ... | Using signal to pop-up a screen | I'm having a little trouble using a signal to make a little screen appear.
Shortening all i have so far, this following code should show my problem.
import sys
from PyQt4 import QtGui, QtCore
qApp = QtGui.QApplication(sys.argv)
class InformatieVenster(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWi... | [
"The window is shown, because you are actually calling .show() during your connect. You have to pass a function object, not the result of a function invocation, as argument to .connect(). Moreover the function to be invoked, if a signal is emitted, is called \"slot\", the second SIGNAL() is completely misplaced.\... | [
3
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qmainwindow"
] | stackoverflow_0006374474_pyqt_pyqt4_python_qmainwindow.txt |
Q:
How to reference self as a model with django-ajax-related-fields
I'm trying to use django-ajax-related-fields, and the foreignkey field I'm trying to create a relation to is the model itself. I've tried 'self', Node, and even self (no quotes), with the same results.
This is approximately how I'm trying to use it:... | How to reference self as a model with django-ajax-related-fields | I'm trying to use django-ajax-related-fields, and the foreignkey field I'm trying to create a relation to is the model itself. I've tried 'self', Node, and even self (no quotes), with the same results.
This is approximately how I'm trying to use it:
class Node(models.Model):
parent = ForeignKeyByLetter('self', fie... | [
"According to the documentation, ForeignKeyByLetter is a form field not a model field, which explains why it's not working for you.\nI'm not familiar with django-ajax-related-fields either, but from the looks of it, you'll want to try something along the lines of:\n# in models.py\nclass Node(models.Model):\n par... | [
1
] | [] | [] | [
"ajax",
"django",
"python"
] | stackoverflow_0006375358_ajax_django_python.txt |
Q:
Python : How to choose modules that can be import from a package?
I have four packages in my program, among them i would like one and only one, to be accessible from the outside, by a user of my program. Brievly, my programm, should be like a black box with only one entry(one of the package).
A:
You can't. But ... | Python : How to choose modules that can be import from a package? | I have four packages in my program, among them i would like one and only one, to be accessible from the outside, by a user of my program. Brievly, my programm, should be like a black box with only one entry(one of the package).
| [
"You can't. But prefixing the \"implementation\" modules with a single underscore will act as an indicator that they should not be used directly.\n"
] | [
6
] | [] | [] | [
"import",
"package",
"python"
] | stackoverflow_0006375769_import_package_python.txt |
Q:
What is the best way to deal with import cycle in Python?
In our projects we have level 'controls' with the following modules: 'grid', 'gridcell', 'combo' and etc. Grid module imports gridcell module since grid consists of cells, while any cell can contain combo inside it. So initially we starting to use 'from ...... | What is the best way to deal with import cycle in Python? | In our projects we have level 'controls' with the following modules: 'grid', 'gridcell', 'combo' and etc. Grid module imports gridcell module since grid consists of cells, while any cell can contain combo inside it. So initially we starting to use 'from ... import ...' statements inside these classes the following way:... | [
"import controls.gridcell as gridcell\n\netc. etc. etc. etc. \n",
"you can also move the imports into the functions.\ndef foo():\n from controls.gridcell import cell\n from controls.combo import combo\n\nif you have an init() function this can be convenient.\n"
] | [
9,
4
] | [] | [] | [
"python",
"python_import"
] | stackoverflow_0006375574_python_python_import.txt |
Q:
Returning value to calling class in Python
I’m new to Python and OOP (& StackOverflow), so excuse me if the question is too naïve, but I can’t seem to get it solved on my own. I’ve just written a very simple program to see how OOP works, which I reproduce below:
from System import *
class trial(object):
def _... | Returning value to calling class in Python | I’m new to Python and OOP (& StackOverflow), so excuse me if the question is too naïve, but I can’t seem to get it solved on my own. I’ve just written a very simple program to see how OOP works, which I reproduce below:
from System import *
class trial(object):
def __init__(self, counter):
self.counter = c... | [
"Integers in Python are immutable. Pass the trial to the person, and increment the attribute on the saved trial instead.\n",
"I believe that each class has it's own counter. Modify your 'passon' function the following way and you will see this:\ndef passon(self):\n p = person(self.counter)\n print 't', self... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006372423_python.txt |
Q:
RPY2: importr fails with .Renviron
Here's what should and does happen using rpy2.robjects.packages.importr for base R-packages (e.g. stats):
>>> from rpy2.robjects.packages import importr
>>> importr('stats')
<rpy2.robjects.packages.SignatureTranslatedPackage object at 0x7f3810>
but with an external package (e.g.... | RPY2: importr fails with .Renviron | Here's what should and does happen using rpy2.robjects.packages.importr for base R-packages (e.g. stats):
>>> from rpy2.robjects.packages import importr
>>> importr('stats')
<rpy2.robjects.packages.SignatureTranslatedPackage object at 0x7f3810>
but with an external package (e.g. ggplot2) this is the result:
>>> import... | [
"By default, rpy2 is initializing in \"vanilla\" mode, and this ignores R_LIBS and friends.\n>>> import rpy2.rinterface \n>>> rpy2.rinterface.get_initoptions()\n('rpy2', '--quiet', '--vanilla', '--no-save')\n>>> \n\nYou can use 'rinterface.set_initoptions()' to change those.\nFor example:\nimport rpy2.rinterface as... | [
2
] | [] | [] | [
"ggplot2",
"macos",
"python",
"r",
"rpy2"
] | stackoverflow_0006364082_ggplot2_macos_python_r_rpy2.txt |
Q:
Killing a program using multiprocessing
I'm using the multiprocessing module to do parallel processing in my program. When I'm testing it, I'll often want to kill the program early when I notice a bug, since it takes a while to run to completion. In my Linux environment, I run my program from a terminal, and use... | Killing a program using multiprocessing | I'm using the multiprocessing module to do parallel processing in my program. When I'm testing it, I'll often want to kill the program early when I notice a bug, since it takes a while to run to completion. In my Linux environment, I run my program from a terminal, and use Ctrl+C to kill it. With multiprocessing, th... | [
"Hit Ctrl-Z to suspend the Python process, then do kill %1 to kill it. You can also just hit Ctrl-\\ (backslash), but that may cause the process to leave a core file.\n",
"But wait ... isn't there a way of handling the KeyboardException event to kill the processes in the pool?\nI tried:\nexcept KeyboardInterrupt... | [
23,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0003686677_python.txt |
Q:
Best framework if moving from Python/AppEngine to PHP
I'm been programming with Python in AppEngine for the last months, and I need to use PHP for a new project.
What PHP framework could you recommend me that feels like working with AppEngine?
Some things I'd want to keep are:
Easy database definition (models.py)... | Best framework if moving from Python/AppEngine to PHP | I'm been programming with Python in AppEngine for the last months, and I need to use PHP for a new project.
What PHP framework could you recommend me that feels like working with AppEngine?
Some things I'd want to keep are:
Easy database definition (models.py) and abstraction
Easy URI definitions
Easy deploy
One thin... | [
"Try the symfony webframework. It uses the twig templating engine which is similar to the one Django uses. Furthermore it is fairly inspired by Django in the way it is build, and there is an easy way of doing datamapping.\n"
] | [
4
] | [] | [] | [
"frameworks",
"google_app_engine",
"php",
"python"
] | stackoverflow_0006376105_frameworks_google_app_engine_php_python.txt |
Q:
Pickle linked objects
I want to pickle an object and a second object that references the first. When I naively pickle/unpickle the two objects, the reference becomes a copy. How do I preserve the link between the two objects foo and bar.foo_ref?
import pickle
class Foo(object):
pass
foo = Foo()
bar = Foo()... | Pickle linked objects | I want to pickle an object and a second object that references the first. When I naively pickle/unpickle the two objects, the reference becomes a copy. How do I preserve the link between the two objects foo and bar.foo_ref?
import pickle
class Foo(object):
pass
foo = Foo()
bar = Foo()
bar.foo_ref = foo
with op... | [
"My previous answer was missing your point. The problem with your code is that you're not using the Pickler and Unpickler objects. Here's a working version with multiple dump calls:\nimport pickle\n\nclass Foo(object):\n pass\n\nfoo = Foo()\nbar = Foo()\nbar.foo_ref = foo\n\nf = open('tmp.pkl', 'wb')\np = pickle... | [
7,
1,
0
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0006376081_pickle_python.txt |
Q:
Using xmlrpc in web2py for command line interface for a web application
I have an application in web2py. To create the command line interface of the gui (web-interface), I want to use xmlrpc service. For example if I have following function :
@auth.requires_login
def example():
temp = request.args[0]
//do ... | Using xmlrpc in web2py for command line interface for a web application | I have an application in web2py. To create the command line interface of the gui (web-interface), I want to use xmlrpc service. For example if I have following function :
@auth.requires_login
def example():
temp = request.args[0]
//do something on temp
return dict(temp=temp)
How can I call this function in... | [
"You need to use service to expose function with xmlrpc\nauth.settings.allow_basic_login = True\n\n@service.xmlrpc\ndef example(temp):\n return ...\n\n\n@auth.requires_login()\ndef call(): return service()\n\nYou can read more in the book.\n"
] | [
1
] | [] | [] | [
"command_line_interface",
"python",
"web2py",
"xml_rpc"
] | stackoverflow_0006375229_command_line_interface_python_web2py_xml_rpc.txt |
Q:
Are there any lightweight markups that are easily customized?
I've written some amounts of LaTeX but nowadays I'm feeling lazy and I would like to write my next bigger project in Markdown, reStructuredText or Textile for easy readability. Unfortunately, I'd like to have some of that TeX customizability and write s... | Are there any lightweight markups that are easily customized? | I've written some amounts of LaTeX but nowadays I'm feeling lazy and I would like to write my next bigger project in Markdown, reStructuredText or Textile for easy readability. Unfortunately, I'd like to have some of that TeX customizability and write some own syntax constructs to meet my semantic needs.
One thing I wa... | [
"Look at \nhttp://sphinx.pocoo.org/ \nusing \nRestructured Text\nhttp://docutils.sourceforge.net/rst.html\n"
] | [
2
] | [] | [] | [
"markdown",
"python",
"restructuredtext"
] | stackoverflow_0006376225_markdown_python_restructuredtext.txt |
Q:
Prevent lxml from touching data in
I'm trying to write a python script that modifies the contents of <script> tag in files I'm parsing. I'm using lxml.html (as opposed to BeautifulSoup, etc.) for this due to its speed. The contents of script tag are surrounded in comment tags (<!-- and -->):
<script>
<!--
...
-->... | Prevent lxml from touching data in | I'm trying to write a python script that modifies the contents of <script> tag in files I'm parsing. I'm using lxml.html (as opposed to BeautifulSoup, etc.) for this due to its speed. The contents of script tag are surrounded in comment tags (<!-- and -->):
<script>
<!--
...
-->
</script>
The problem is when I try som... | [
"Put them in a CDATA section.\n",
"An alternative solution I just found that seems to work as well is using tostring() instead of write():\nmain = open('file.html', 'w')\nmain.write(lxml.html.tostring(htmlTree))\nmain.close()\n\ninstead of\nhtmlTree.write('file.html', pretty_print=False)\n\nFigured I'd post it he... | [
4,
0
] | [] | [] | [
"html_parsing",
"lxml",
"python"
] | stackoverflow_0006375986_html_parsing_lxml_python.txt |
Q:
Python: htmllib.HTMLParser problem with url extraction when present
I have found a strange thing with htmllib.HTMLParser
here is a code
import htmllib, formatter, sys
class LinksExtractor(htmllib.HTMLParser):
def __init__(self, formatter) :
htmllib.HTMLParser.__init__(self, formatter)
... | Python: htmllib.HTMLParser problem with url extraction when present | I have found a strange thing with htmllib.HTMLParser
here is a code
import htmllib, formatter, sys
class LinksExtractor(htmllib.HTMLParser):
def __init__(self, formatter) :
htmllib.HTMLParser.__init__(self, formatter)
self.links = []
def start_a(self, attrs) :
... | [
"Problem is not the div tag, but infact the < br/ > tag. Parser looks for start tag in the format < X > and end tag in the format < /X >. And for tags like < p > abd < br > it doesnt mind having no end tag. Hence replace < /br > with < br > and you should be fine.\nOfcourse if you need to have this custom html wor... | [
0,
0
] | [] | [] | [
"html_parsing",
"python",
"url"
] | stackoverflow_0006376288_html_parsing_python_url.txt |
Q:
Font module error when using pygame2exe
I used Pygame2exe from the Pygame website and that got rid of the problem with the .dlls but there's still an error that remains.
The only font I'm using is the standard pygame font (freesansbold.ttf) and I've included a copy of it in my game directory.
Also,
I'm using the F... | Font module error when using pygame2exe | I used Pygame2exe from the Pygame website and that got rid of the problem with the .dlls but there's still an error that remains.
The only font I'm using is the standard pygame font (freesansbold.ttf) and I've included a copy of it in my game directory.
Also,
I'm using the Font class and not the SysFonts class which I ... | [
"Your problem looks like very similar to this one : http://thadeusb.com/weblog/2009/4/15/pygame_font_and_py2exe\nTry to add \"sdl_ttf.dll\" to the list of system dlls like this :\norigIsSystemDLL = py2exe.build_exe.isSystemDLL # save the orginal before we edit it\ndef isSystemDLL(pathname):\n # checks if the fre... | [
3
] | [] | [] | [
"py2exe",
"pygame",
"python"
] | stackoverflow_0006376194_py2exe_pygame_python.txt |
Q:
writing and formatting datetime.date objects using xlwt
I'm having some trouble with this bit of code
#data_list = some data
wb = xlwt.Workbook()
s = wb.add_sheet("Test Sheet")
for c, data in enumerate(data_list):
xf=None
if isinstance(data, datetime.time):
xf = xlwt.easyxf(num_form... | writing and formatting datetime.date objects using xlwt | I'm having some trouble with this bit of code
#data_list = some data
wb = xlwt.Workbook()
s = wb.add_sheet("Test Sheet")
for c, data in enumerate(data_list):
xf=None
if isinstance(data, datetime.time):
xf = xlwt.easyxf(num_format_str='HH:MM:SS') #works
elif isinstance(data, datet... | [
"Just thinking about this some more, if your problem is that the columns are too narrow, you can fix it by setting the column width explicitly in your script.\nfor c, data in enumerate(data_list):\n xf=None\n sheet.col(c).width = len(str(data))*256 \n if isinstance(data, datetime.time):\n\nThe width in xlw... | [
6
] | [] | [] | [
"python",
"xlwt"
] | stackoverflow_0006375131_python_xlwt.txt |
Q:
Which Python 3 API to get started?
I have Programming experience with C, C++ and Java and in the last week I learned Python 3 with the official tutorial and A Byte of Python. I want to start programming in Python, and my ideas for the first projects are either a browser-based simple blog-software (just login & pos... | Which Python 3 API to get started? | I have Programming experience with C, C++ and Java and in the last week I learned Python 3 with the official tutorial and A Byte of Python. I want to start programming in Python, and my ideas for the first projects are either a browser-based simple blog-software (just login & poste - nothing more to keep it simple) or ... | [
"PyQt supports python 3.\n",
"CherryPy runs on Python 2.3 and above (yep Python 3 as well.) \nIt is quite easy to get into as well, which might align with your stated goals of simplicity. It won't provide you with a templating engine or ORM though like Django. But this can be obtained separately, for example SQL ... | [
4,
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006376896_python_python_3.x.txt |
Q:
Python webrowser open url with bookmarks like www.something.com/file.html#top
I am using a hmtl file as a help document for my program, and would really like to be able to open the file at a specific point. i assumed i would be able to do this using the built in webbrowser module by specifying a url with a bookmar... | Python webrowser open url with bookmarks like www.something.com/file.html#top | I am using a hmtl file as a help document for my program, and would really like to be able to open the file at a specific point. i assumed i would be able to do this using the built in webbrowser module by specifying a url with a bookmark.
this is my html file name: help.html
i assumed that i would be able to use: help... | [
"webbrowser.open() calls the browser from the command line. So you might try to do that yourself first. If that doesn't work, it's likely that your browser just doesn't support that for local files or something.\nWith Ubuntu+Firefox for example, webbrowser.open() does what you ask. (but - as Dave Webb said in his a... | [
3,
1
] | [] | [] | [
"browser",
"html",
"python"
] | stackoverflow_0006374761_browser_html_python.txt |
Q:
How to make a FigureCanvas fit a Panel?
I'm trying to display some data using Matplotlib and wxPython. I've got a Figure that's added to a FigureCanvasWxAgg. The canvas is then added to a BoxSizer and set to wx.EXPAND|wx.ALL, the BoxSizer on its turn is set by SetSizerAndFit.
self.figure = Figure(None, dpi = 75)
s... | How to make a FigureCanvas fit a Panel? | I'm trying to display some data using Matplotlib and wxPython. I've got a Figure that's added to a FigureCanvasWxAgg. The canvas is then added to a BoxSizer and set to wx.EXPAND|wx.ALL, the BoxSizer on its turn is set by SetSizerAndFit.
self.figure = Figure(None, dpi = 75)
self.displaycanvas = FigureCanvas(self, -1, se... | [
"Instead of getting your axes from the add_subplot method, you can create an axes object with explicit boundaries. So instead of \nself.axes = self.figure.add_subplot(111)\n\nuse\nself.axes = self.figure.add_axes([0,0,1,1])\n\nThe four numbers are the left edge, bottom edge, width and height of the axes in fractio... | [
6
] | [] | [] | [
"matplotlib",
"python",
"wxpython"
] | stackoverflow_0006374272_matplotlib_python_wxpython.txt |
Q:
Python: Non-blocking socket or Asynchronos I/O
I am new to Python and currently have to write a python socket to be run as a script that communicates with a device over TCP/IP (a weather station).
The device acts as the Server Side (listening over IP:PORT, accepting connection, receiving request, transferring data... | Python: Non-blocking socket or Asynchronos I/O | I am new to Python and currently have to write a python socket to be run as a script that communicates with a device over TCP/IP (a weather station).
The device acts as the Server Side (listening over IP:PORT, accepting connection, receiving request, transferring data).
I only need to send one message, receive the answ... | [
"You can try a timeout approach, like Russel code or you can use a non-blocking socket, as shown in the code below. It will never block at socket.recv and you can use it inside a loop to retry as many times you want. This way your program will not hang at timeout. This way, you can test if data is available and if ... | [
11,
3,
1
] | [] | [] | [
"nonblocking",
"python",
"sockets"
] | stackoverflow_0006374685_nonblocking_python_sockets.txt |
Q:
How to represent a strange graph in some data structure
A simple way to represent a graph is with a data structure of the form:
{1:[2,3],
2:[1,3],
3:[1,2]}
Where the keys in this dictionary are nodes, and the edges are represented by a list of other nodes they are connected to. This data structure could also ea... | How to represent a strange graph in some data structure | A simple way to represent a graph is with a data structure of the form:
{1:[2,3],
2:[1,3],
3:[1,2]}
Where the keys in this dictionary are nodes, and the edges are represented by a list of other nodes they are connected to. This data structure could also easily represent a directed graph if the links are not symmetri... | [
"This could be represented by a directed graph.\nNodes in your graph could be represented as two nodes in the graph.\nThink of the nodes as representing locations on particular sides of a street -- the edges being like inbound and outbound lanes.\n\n",
"You could implement it as a basic graph with nodes and edges... | [
7,
1,
1
] | [] | [] | [
"data_structures",
"graph",
"language_agnostic",
"python"
] | stackoverflow_0006376586_data_structures_graph_language_agnostic_python.txt |
Q:
Pylons webhelpers minify file name too long
I'm using the pylons "minify" webhelper to minify and combine all of my javascript/css files. It seems the helper concatenates all of the file names and uses the result as the name for the combined version. I have a lot of JavaScript files that are being combined and the... | Pylons webhelpers minify file name too long | I'm using the pylons "minify" webhelper to minify and combine all of my javascript/css files. It seems the helper concatenates all of the file names and uses the result as the name for the combined version. I have a lot of JavaScript files that are being combined and the resulting file name is giving the error:
IOError... | [
"Basicaly MinificationWebHelpers adds following options to the WebHelpers javascript_link and stylesheet_link functions:\n\nminified (bool): Minifies/reduces as much as possible each of the files passed to it’s minimum size to reduce page load times.\ncombined (bool): Joins all files passed into a single one to red... | [
2
] | [] | [] | [
"helpers",
"minify",
"pylons",
"python"
] | stackoverflow_0006377486_helpers_minify_pylons_python.txt |
Q:
Does this regex do what I think it does?
I'm attempting to do the Python challenge. I'm currently stuck on problem #3. The problem gives you a bunch of text, and tells your to extract any lowercase letter surrounded by exactly 3 uppercase letters. For example: XXXsXXX should return s as a match.
I'm came up with t... | Does this regex do what I think it does? | I'm attempting to do the Python challenge. I'm currently stuck on problem #3. The problem gives you a bunch of text, and tells your to extract any lowercase letter surrounded by exactly 3 uppercase letters. For example: XXXsXXX should return s as a match.
I'm came up with this regex to perform to look for matches.
mes... | [
"I shouldn't have taken comments on merit without checking if they work. Silly of me. your regex does not work as written. You are looking for something like this:\nmessage = re.findall(r'[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]', data)\n\nwhich would capture the letter you are looking for.\n",
"The problem with your ... | [
3,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006377289_python_regex.txt |
Q:
Receiving HTTP ERROR with Django Uploadify S3
I am using Django Uplodify S3 and I am having issues getting it to work. Files start to upload (progress is shown), then they just either pause indefinitely or result in a 'Http Error'.
My python code is pretty much identical to the example code given. I am running thi... | Receiving HTTP ERROR with Django Uploadify S3 | I am using Django Uplodify S3 and I am having issues getting it to work. Files start to upload (progress is shown), then they just either pause indefinitely or result in a 'Http Error'.
My python code is pretty much identical to the example code given. I am running this on my local machine with the dev server.
I keep g... | [
"This might be a long shot, but have you tried renaming the field from file_upload to file?\n",
"I believe your upload needs to be changed from 'filedata' to be named 'file'.\nTake a look here for sample code:\nhttp://developer.amazonwebservices.com/connect/entry.jspa?externalID=1092&categoryID=47\n"
] | [
0,
0
] | [] | [] | [
"amazon_s3",
"django",
"python"
] | stackoverflow_0006274484_amazon_s3_django_python.txt |
Q:
Python Compilation Error for Code implemented on Windows and trying to run on Linux
I am 100% new to Python I am bumping into this weird issue regarding compatibility when switching between Windows and Linux. I implemented a small program that implements a TCP/IP socket that communicates with a device that support... | Python Compilation Error for Code implemented on Windows and trying to run on Linux | I am 100% new to Python I am bumping into this weird issue regarding compatibility when switching between Windows and Linux. I implemented a small program that implements a TCP/IP socket that communicates with a device that supports server socket over TCP/IP. My program works fine when running on Windows so I decided t... | [
"You have a module named socket, and you're trying to import the socket module from it. The module is obviously shadowing the builtin socket module (i.e. your socket is importing itself). If this module isn't a package, move it to a package. If/when the module is already in a package (I assume weatherData is a pack... | [
2
] | [] | [] | [
"compilation",
"linux",
"python",
"windows"
] | stackoverflow_0006378359_compilation_linux_python_windows.txt |
Q:
Could you explain why this regex is not working?
>>> d = "Batman,Superman"
>>> m = re.search("(?<!Bat)\w+",d)
>>> m.group(0)
'Batman'
Why isn't group(0) matching Superman? This lookaround tutorial says:
(?<!a)b matches a "b" that is not
preceded by an "a", using negative
lookbehind
A:
Batman isn't directly... | Could you explain why this regex is not working? | >>> d = "Batman,Superman"
>>> m = re.search("(?<!Bat)\w+",d)
>>> m.group(0)
'Batman'
Why isn't group(0) matching Superman? This lookaround tutorial says:
(?<!a)b matches a "b" that is not
preceded by an "a", using negative
lookbehind
| [
"Batman isn't directly preceded by Bat, so that matches first. In fact, neither is Superman; there's a comma in-between in your string which will do just fine to allow that RE to match, but that's not matched anyway because it's possible to match earlier in the string.\nMaybe this will explain better: if the string... | [
6,
1,
1,
1,
1
] | [] | [] | [
"negative_lookbehind",
"python",
"regex"
] | stackoverflow_0006378236_negative_lookbehind_python_regex.txt |
Q:
Subprocess wait() function doesn't seem to be waiting for the subprocess to complete
I'm trying to run a php script with python's subprocess module.
proc = subprocess.Popen(['php', '-f', test.php], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retCode = proc.wait
print retCode
val = float(kprocess.stdout.read... | Subprocess wait() function doesn't seem to be waiting for the subprocess to complete | I'm trying to run a php script with python's subprocess module.
proc = subprocess.Popen(['php', '-f', test.php], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retCode = proc.wait
print retCode
val = float(kprocess.stdout.read())
return val
I've also tried:
proc = subprocess.Popen(['php', '-f', test.php], stdout=... | [
"You have to actually call the processes' wait function:\nproc = subprocess.Popen(...)\nretCode = proc.wait # retCode will be the function wait\nretCode = proc.wait() # retCode will be the return code\n\nHowever, since you are redirecting the output to, you should heed the warning in the wait docs and use communica... | [
5
] | [] | [] | [
"communicate",
"python",
"subprocess",
"wait"
] | stackoverflow_0006378288_communicate_python_subprocess_wait.txt |
Q:
Reading unicode elements into numpy array
Consider a text file called "new.txt" containing the following elements:
μm
∂r
∆λ
In Python 2.7, I can read the file by typing:
>>> import codecs
>>> f = codecs.open('new.txt', encoding='utf-8')
>>> lines = [line.strip() for line in f2.readlines()]
>>> lines
[u'\u03bcm', ... | Reading unicode elements into numpy array | Consider a text file called "new.txt" containing the following elements:
μm
∂r
∆λ
In Python 2.7, I can read the file by typing:
>>> import codecs
>>> f = codecs.open('new.txt', encoding='utf-8')
>>> lines = [line.strip() for line in f2.readlines()]
>>> lines
[u'\u03bcm', u'\u2202r', u'\u2206\u03bb']
>>> print lines[0]... | [
"In memory, unicode strings are represented as UCS-2 or UCS-4, depending on how your Python interpreter was compiled. Your file is encoded in UTF-8, so you need to recode it before you can map it to the NumPy array. loadtxt() can't do the recoding for you -- after all NumPy is mainly targeted at numerical arrays.... | [
10,
2
] | [] | [] | [
"numpy",
"python",
"unicode"
] | stackoverflow_0006375343_numpy_python_unicode.txt |
Q:
many-many model join with SQLAlchemy
I'm having the worst time trying to get a many-many join to work using models in SQLAlchemy. I've found lots of examples online, but I can't ever seem to figure out if their strings represent the column names they'd like versus what the database tables actually have, or they'r... | many-many model join with SQLAlchemy | I'm having the worst time trying to get a many-many join to work using models in SQLAlchemy. I've found lots of examples online, but I can't ever seem to figure out if their strings represent the column names they'd like versus what the database tables actually have, or they're using Table instead of a declarative mod... | [
"The tricky part with mine was the composite foreign key to the Tag table. Here's my setup:\nclass TagTest(Base):\n __table_args__ = (ForeignKeyConstraint(['TG_TAG_ID', 'TG_TYPE'],\n ['TAG.TG_TAG_ID', 'TAG.TG_TYPE']), {})\n tagID = Column(u'TG_TAG_ID', INTEGER(), primary_key=True, nullable=False)\n ... | [
1
] | [] | [] | [
"foreign_key_relationship",
"model",
"python",
"sqlalchemy"
] | stackoverflow_0006374096_foreign_key_relationship_model_python_sqlalchemy.txt |
Q:
Build soap message only, using SUDS
Currently I'm struggling while trying to generate soap message with SUDS. Things I want to achieve is something like
xml_string = client.service.getPercentBodyFat('jeff', 68, 170)
instead of calling remote procedure I want to get soap message as xml string or object.
Thank You... | Build soap message only, using SUDS | Currently I'm struggling while trying to generate soap message with SUDS. Things I want to achieve is something like
xml_string = client.service.getPercentBodyFat('jeff', 68, 170)
instead of calling remote procedure I want to get soap message as xml string or object.
Thank You!
| [
"If you make the actual remote call, even if the service is not available, you can then capture the request with\nxml_string = client.last_sent()\nprint xml_string\n\n"
] | [
1
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0004062728_python_soap_suds.txt |
Q:
Xml parsing with Python using recursion. Problem with return value
I am somewhat new to Python and programming in general so I apologize. By the way, thanks in advance.
I am parsing an xml document (kml specifically which is used in Google Earth) using Python 2.5, cElementTree and expat. I am trying to pull out ... | Xml parsing with Python using recursion. Problem with return value | I am somewhat new to Python and programming in general so I apologize. By the way, thanks in advance.
I am parsing an xml document (kml specifically which is used in Google Earth) using Python 2.5, cElementTree and expat. I am trying to pull out all the text from the 'name', 'description' and 'coordinates' nodes insi... | [
"With recursion you want to pay attention to your base cases, and your recursive cases.\nWhatever your base cases happen to be, if you expect to be able to collect information from your recursion, they have to return data that your recursive cases can (and more importantly do) use. Similarly you need to make sure t... | [
6,
0
] | [] | [] | [
"python",
"recursion",
"xml"
] | stackoverflow_0006378350_python_recursion_xml.txt |
Q:
Trying to Graph a Simple Square in pyOpenGL
I'm trying to teach myself OpenGL using pyopengl and I'm struck on trying to render a simple 2D square centered at the origin. Whenever I set an array value greater than or equal to 1, the shape takes up the entire screen as if I am only viewing a small section of the ax... | Trying to Graph a Simple Square in pyOpenGL | I'm trying to teach myself OpenGL using pyopengl and I'm struck on trying to render a simple 2D square centered at the origin. Whenever I set an array value greater than or equal to 1, the shape takes up the entire screen as if I am only viewing a small section of the axis. I have tried to base it off the NeHe tutorial... | [
"You need to set the projection matrix and the viewport. Python allows us to use a little bit functional programming to do it the sane way:\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\n\ndef display(w, h):\n aspect = float(w)/float(h)\n glViewport(0, 0, w, h)\n glMatrixMod... | [
3,
0
] | [] | [] | [
"opengl",
"pyopengl",
"python"
] | stackoverflow_0006378297_opengl_pyopengl_python.txt |
Q:
Python Urllib form help
I am trying to make a program that will access http://mailfreeonline.com/free_anonymous_mail and send me an email. This is what I have so far, it says there is a syntax error with the second colon?
import urllib
params = urllib.urlencode(
{'tomailget': 'myemail@gmail.com',
'fromna... | Python Urllib form help | I am trying to make a program that will access http://mailfreeonline.com/free_anonymous_mail and send me an email. This is what I have so far, it says there is a syntax error with the second colon?
import urllib
params = urllib.urlencode(
{'tomailget': 'myemail@gmail.com',
'fromnameget': 'Matt'
'frommail... | [
"You have to add comma after each parameter, you forgot to do that\n params = urllib.urlencode( {'tomailget': 'myemail@gmail.com', \n 'fromnameget': 'Matt', \n 'frommailget': 'test@test.com', \n 'subjectget': ... | [
0,
0
] | [] | [] | [
"email",
"forms",
"python",
"urllib"
] | stackoverflow_0006378658_email_forms_python_urllib.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.