content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to track memory for a python script
We have a system that only has one interpreter. Many user scripts come through this interpreter. We want put a cap on each script's memory usage. There is only process, and that process invokes tasklets for each script. So since we only have one interpreter and one process, ... | How to track memory for a python script | We have a system that only has one interpreter. Many user scripts come through this interpreter. We want put a cap on each script's memory usage. There is only process, and that process invokes tasklets for each script. So since we only have one interpreter and one process, we don't know a way to put a cap on each scri... | [
"I don't think that it's possible at all. Your questions implies that the memory used by your tasklets is completly separated, which is probably not the case. Python is optimizing small objects like integers. As far as I know, for example each 3 in your code is using the same object, which is not a problem, because... | [
3,
0
] | [] | [] | [
"memory_management",
"python",
"stackless"
] | stackoverflow_0007367206_memory_management_python_stackless.txt |
Q:
Redirect subprocess to a variable as a string
With the following command, it prints '640x360'
>>> command = subprocess.call(['mediainfo', '--Inform=Video;%Width%x%Height%',
'/Users/Desktop/1video.mp4'])
640x360
How would I set a variable equal to the string of the output, so I can get x='640x360'? Thank you.
A... | Redirect subprocess to a variable as a string | With the following command, it prints '640x360'
>>> command = subprocess.call(['mediainfo', '--Inform=Video;%Width%x%Height%',
'/Users/Desktop/1video.mp4'])
640x360
How would I set a variable equal to the string of the output, so I can get x='640x360'? Thank you.
| [
"If you're using 2.7, you can use subprocess.check_output():\n>>> import subprocess\n>>> output = subprocess.check_output(['echo', '640x360'])\n>>> print output\n640x360\n\nIf not:\n>>> p = subprocess.Popen(['echo', '640x360'], stdout=subprocess.PIPE)\n>>> p.communicate()\n('640x360\\n', None)\n\n",
"import subpr... | [
13,
4
] | [] | [] | [
"python"
] | stackoverflow_0007367550_python.txt |
Q:
urlopen windows ftp error
This code works perfectly at linux, but windows at there are errors. What's wrong?
import urllib, urllib2
a = 'ftp://ftp.arin.net/pub/stats/arin/delegated-arin-latest'
urllib.urlopen(a)
IOError: [Errno ftp error] proxy support for ftp protocol currently not implemented
urllib2.urlopen(... | urlopen windows ftp error | This code works perfectly at linux, but windows at there are errors. What's wrong?
import urllib, urllib2
a = 'ftp://ftp.arin.net/pub/stats/arin/delegated-arin-latest'
urllib.urlopen(a)
IOError: [Errno ftp error] proxy support for ftp protocol currently not implemented
urllib2.urlopen(a)
URLError: <urlopen error ftp... | [
"Check if you have some proxy settings in your Internet Explorer: Menu Extras->Internet Options, there Connections->\"LAN settings\" (or something similar). If you have a Proxy server setting, urllib will not work.\n"
] | [
0
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0007367713_python_urllib_urllib2.txt |
Q:
python compile for exec
I am using compile with exec to execute a python code specified by user. Below are 2 cases reprsenting the usert code that needs to be compiled. The user code is read into a string and then compiled as shown below. The compile works fine for case 1 while it throws a syntax error - "SyntaxEr... | python compile for exec | I am using compile with exec to execute a python code specified by user. Below are 2 cases reprsenting the usert code that needs to be compiled. The user code is read into a string and then compiled as shown below. The compile works fine for case 1 while it throws a syntax error - "SyntaxError: unexpected character aft... | [
"You have a space after the \\n before the elif, causing the elif block to be indented, and therefore, a syntax error.\n",
"In case 2, there's an additional space before elif that causes this error. Also note that you can only use return inside a function, so you need a def somewhere.\n",
"Watch the spaces: I c... | [
1,
1,
0,
0
] | [] | [] | [
"exec",
"python"
] | stackoverflow_0007367748_exec_python.txt |
Q:
Perplexing assignment behavior with h5py object as instance variable
I'm using h5py to access HDF5 files and store the h5py File objects in a class. But I'm experiencing some strange behavior in attempting to reassign a closed h5py file instance variable with a new one:
class MyClass:
def __init__(self, filena... | Perplexing assignment behavior with h5py object as instance variable | I'm using h5py to access HDF5 files and store the h5py File objects in a class. But I'm experiencing some strange behavior in attempting to reassign a closed h5py file instance variable with a new one:
class MyClass:
def __init__(self, filename):
self.h5file = None
self.filename = filename
def ... | [
"Not sure if this will help, but searching through the source code I found this (abbreviated):\nclass HLObject(object):\n def __nonzero__(self):\n register_thread()\n return self.id.__nonzero__()\n\nclass Group(HLObject, _DictCompat):\n ...\n\nclass File(Group):\n def __repr__(self):\n ... | [
1,
1
] | [] | [] | [
"h5py",
"python"
] | stackoverflow_0007355545_h5py_python.txt |
Q:
Compiling vim 7.3 with python and perl support on ubuntu 11.04
I compiled vim 7.3 with
./configure --enable-gnome-check --enable-cscope --with-features=huge --enable-perlinterp \
--enable- ythoninterp --enable-rubyinterp --enable-multibyte --enable-python3interp \
--with-compiledby=tahoang@something.com
on Ubuntu... | Compiling vim 7.3 with python and perl support on ubuntu 11.04 | I compiled vim 7.3 with
./configure --enable-gnome-check --enable-cscope --with-features=huge --enable-perlinterp \
--enable- ythoninterp --enable-rubyinterp --enable-multibyte --enable-python3interp \
--with-compiledby=tahoang@something.com
on Ubuntu 11.04 in order to have proper indentation and syntax highlighting. ... | [
"on Ubuntu 11.04 in order to have proper indentation and syntax highlighting\nYou don't need to link Python, Ruby, or Perl to get syntax highlighting or indentation in Vim.\nThey're only used to run Python/Ruby/Perl code inside Vim.\n"
] | [
1
] | [] | [] | [
"linux",
"python",
"vim"
] | stackoverflow_0007368014_linux_python_vim.txt |
Q:
reading info from text file and passing read lines to urlencode python function
I'm trying to send urlencode() data to my web server.
The data used for the urlencode() function is read from a text file located on my local machine.
When I read the input data for the urlencode() function from the .py script no error... | reading info from text file and passing read lines to urlencode python function | I'm trying to send urlencode() data to my web server.
The data used for the urlencode() function is read from a text file located on my local machine.
When I read the input data for the urlencode() function from the .py script no error is being thrown.
However, if the input data for the urlencode() function is comming ... | [
"I'll go ahead and post my comment as an answer, as it is the answer. You're calling dict() on a string. The dict() function expects one of two types of input. Either A. a list of tuples that form (key, value) pairs, or B. keyword arguments that come in the form key = value. You're not passing either of those.\... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007368239_python.txt |
Q:
How can I handle NameError and AttributeError gracefully in the Mako runtime environment?
I've found that trying to access an undefined variable within a Mako template raises a NameError, and quite logically so. In some applications, however, it's desirable to fail more gracefully, perhaps substituting the empty s... | How can I handle NameError and AttributeError gracefully in the Mako runtime environment? | I've found that trying to access an undefined variable within a Mako template raises a NameError, and quite logically so. In some applications, however, it's desirable to fail more gracefully, perhaps substituting the empty string on such errors (AttributeError is another candidate). This is the default behavior in the... | [
"Well, turns out that a little more googling makes it plain:\nimport mako.runtime\nmako.runtime.UNDEFINED = ''\n\nNow undefined variables will produce the empty string.\nReading the source for the original value of UNDEFINED is enlightening:\nclass Undefined(object):\n \"\"\"Represents an undefined value in a te... | [
12
] | [] | [] | [
"mako",
"python",
"template_engine",
"templates"
] | stackoverflow_0007365848_mako_python_template_engine_templates.txt |
Q:
Insert tabs with .join in python
This is probably basic, but I can't find a solution. I have a string, e.g.,
s = 'a,b,c,d'
I'd like to convert the commas to tabs. But using .replace, e.g.,
s.replace(',', '\t')
gives me
>>> s.replace(',', '\t')
'a\tb\tc\td'
I also tried converting to a list and then adding th... | Insert tabs with .join in python | This is probably basic, but I can't find a solution. I have a string, e.g.,
s = 'a,b,c,d'
I'd like to convert the commas to tabs. But using .replace, e.g.,
s.replace(',', '\t')
gives me
>>> s.replace(',', '\t')
'a\tb\tc\td'
I also tried converting to a list and then adding the tabs with a .join, e.g.,
'\t'.join(s... | [
">>> print s.replace(',', '\\t')\na b c d\n\nRight now you are see'ing repr(s.replace(',', '\\t')) in the interpreter without the print statement. repr() will show each actual character in a string and the interpreter uses that as the default method to print out the result of operations.\nUnless you wante... | [
9
] | [] | [] | [
"python"
] | stackoverflow_0007368503_python.txt |
Q:
Is test suite deprecated in PyUnit?
Following the example in PyUnit, I came up with the following unittest code that works fine.
import unittest
class Board:
def __init__(self, x, y):
self.x = x; self.y = y;
def __eq__(self, other):
return self.x == other.x and self.y == other.y
class BoardTest(un... | Is test suite deprecated in PyUnit? | Following the example in PyUnit, I came up with the following unittest code that works fine.
import unittest
class Board:
def __init__(self, x, y):
self.x = x; self.y = y;
def __eq__(self, other):
return self.x == other.x and self.y == other.y
class BoardTest(unittest.TestCase):
def setUp(self):
... | [
"unittest.TestSuite is not necessary if you want to run all the tests in a single module as unittest.main() will dynamically examine the module it is called from and find all classes that derive from unittest.TestCase\nHowever, the TestSuite class is still handy in a number of scenarios:\n\nYou want to build a set ... | [
4,
3
] | [] | [] | [
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0003121107_python_python_unittest_unit_testing.txt |
Q:
os.system('exit') in python
My friend is in a macOS environment and he wanted to call os.system('exit') at the end of his python script to make the terminal close. It doesn't. This doesn't surprise me but I would like to know what exactly is going on between the python script and the terminal when this call is mad... | os.system('exit') in python | My friend is in a macOS environment and he wanted to call os.system('exit') at the end of his python script to make the terminal close. It doesn't. This doesn't surprise me but I would like to know what exactly is going on between the python script and the terminal when this call is made.
In my mental simulation the te... | [
"read the help:\nExecute the command (a string) in a subshell.\n\nA subshell is launched, and exit is run in that subshell.\nTo exit the enclosing terminal, you have to kill the parent. One way to do it is:\nos.system(\"kill -9 %d\"%(os.getppid())\n\n",
"The system function starts another shell to execute a comm... | [
5,
2,
1
] | [] | [] | [
"exit",
"process",
"python",
"terminal",
"terminate"
] | stackoverflow_0007368523_exit_process_python_terminal_terminate.txt |
Q:
Syntax error on While loop in python
I get a syntax error at the first while loop, specifically at the "Y"
#Calculates trajectory under various angles
from math import*
from Density import*
from Fdrag import*
from pylab import title, xlabel, ylabel, show, plot, legend
#constants
rho0=1.2 #standard dens... | Syntax error on While loop in python | I get a syntax error at the first while loop, specifically at the "Y"
#Calculates trajectory under various angles
from math import*
from Density import*
from Fdrag import*
from pylab import title, xlabel, ylabel, show, plot, legend
#constants
rho0=1.2 #standard density of air at ground (kg/m^3)
g=9.81 ... | [
"While has to be written with a lowercase 'w', otherwise Python wont recognize it/\n",
"While should be lowercase (while)\n",
"While should be while (lower case 'w') in the While Y>=0: line at the end of the script.\n"
] | [
2,
1,
0
] | [] | [] | [
"python",
"syntax",
"while_loop"
] | stackoverflow_0007368577_python_syntax_while_loop.txt |
Q:
Picasa albums title encoding. Not unicode?
I wrote a simple client for Googles Picasa service. What I want is to create a folder with albums title name and download original photo from the service to this folder.
If there is any non-latin characters in title I got an IOError:
IOError: [Errno 2] No such file or di... | Picasa albums title encoding. Not unicode? | I wrote a simple client for Googles Picasa service. What I want is to create a folder with albums title name and download original photo from the service to this folder.
If there is any non-latin characters in title I got an IOError:
IOError: [Errno 2] No such file or directory:
'\xd0\x9e\xd1\x81\xd0\xb5\xd0\xbd\xd1... | [
"You say:\n@rocksportrocker repr(album.title.text) returns str:\n'\\xd0\\x92\\xd0\\xb8\\xd0\\xb4 \\xd0\\xb8\\xd0\\xb7 \\xd0\\xbe\\xd0\\xba\\xd0\\xbd\\xd0\\xb0'\n\nand\n@d-k Yep, I've tried it. The result is the same.\nFor example repr(album.title.text.encode('utf-8')) returns str:\n'\\xd0\\x92\\xd0\\xb8\\xd0\\xb4 \... | [
1
] | [] | [] | [
"gdata",
"picasa",
"python"
] | stackoverflow_0007366197_gdata_picasa_python.txt |
Q:
Regex replacement
I have a string like this one:
{{foobar
| option1 = foo
| option2 = foo
| <!-- more options -->
| something = xxx
| thisoption = xxx
| <!-- more options -->
}}
I want it to be "thisoption = xxx" to be replaced by "thisoption = abc". It shouldn't matchany of the following:
{{foobar
| option1 = fo... | Regex replacement | I have a string like this one:
{{foobar
| option1 = foo
| option2 = foo
| <!-- more options -->
| something = xxx
| thisoption = xxx
| <!-- more options -->
}}
I want it to be "thisoption = xxx" to be replaced by "thisoption = abc". It shouldn't matchany of the following:
{{foobar
| option1 = foo
| option2 = foo
| thi... | [
"The question is a little vague, but try this:\nre.sub(r'(?P<name>foobar[^}]* = xxx\\b)', r'\\g<name>2', string)\n\nIt looks for a match for foobar and a match for xxx without any closing braces in between, i.e. xxx is in foobar.\n>>> string = '{{foobar\\n| option1 = foo\\n| option2 = foo\\n| <!-- more options -->\... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007367213_python_regex.txt |
Q:
Python 3 httplib2 cookies
Fixed, httplin2 can't handle more than one cookie, the patch can be found here: http://code.google.com/p/httplib2/issues/detail?id=146
I am coding a facebook login script to get my last notifications but
I'm having a problem. I've changed from urllib to httplib2 because it
seemed eas... | Python 3 httplib2 cookies | Fixed, httplin2 can't handle more than one cookie, the patch can be found here: http://code.google.com/p/httplib2/issues/detail?id=146
I am coding a facebook login script to get my last notifications but
I'm having a problem. I've changed from urllib to httplib2 because it
seemed easier and faster to me. Using the... | [
"Fixed, httplin2 can't handle more than one cookie, the patch can be found here: http://code.google.com/p/httplib2/issues/detail?id=146\n"
] | [
1
] | [] | [] | [
"cookies",
"httplib2",
"python",
"python_3.x"
] | stackoverflow_0007340818_cookies_httplib2_python_python_3.x.txt |
Q:
py2exe command prompt exe change shell window size and colors?
i'm trying to change the compiled exe's icon and such using this script for my setup.py:
setup(name = "Program Title",
version = "1.0",
options = {"py2exe" : {"compressed" : 1,
"optimize" : 2,
... | py2exe command prompt exe change shell window size and colors? | i'm trying to change the compiled exe's icon and such using this script for my setup.py:
setup(name = "Program Title",
version = "1.0",
options = {"py2exe" : {"compressed" : 1,
"optimize" : 2,
"bundle_files" : 2 }},
console=[{'script': 'progra... | [
"Check out these tutorials for a colored console:\nBring Colors to the Windows Console with Python\nChange Windows Console Character Attribute\nThe Console Module\n\nFor the icon, try this suggestion from CustomIcons:\n\"Important Note For Adding Multiple Icons On Systems Where This Method Is Not Working: After muc... | [
0
] | [] | [] | [
"cmd",
"py2exe",
"python"
] | stackoverflow_0007369015_cmd_py2exe_python.txt |
Q:
Why can't I delete an method/attribute from a Tkinter Window?
I'm trying to remove a method from an class instance derived from a Tkinter window using the delattr built in function. However, I get the following error. What am I doing wrong?
Error :
AttributeError: Class instance has no attribute 'wm_title'
An ex... | Why can't I delete an method/attribute from a Tkinter Window? | I'm trying to remove a method from an class instance derived from a Tkinter window using the delattr built in function. However, I get the following error. What am I doing wrong?
Error :
AttributeError: Class instance has no attribute 'wm_title'
An example :
import Tkinter as tk
class Class (tk.Tk) :
def __init_... | [
"You can't delete a class method that way because class methods are properties of classes, not objects.\nWhen you invoke a method via object.method(), python is actually calling Class.method(object). (This is also why you must declare a self argument in class methods, yet you do not actually pass any value for sel... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007368017_python_tkinter.txt |
Q:
How to extract data from XML using python minidom
given this xml file, i would like to extract the data out from it. However, i have trouble extracting the data from <LandmarkPointListXml> onwards.
The XML file:
<?xml version="1.0" encoding="utf-8"?>
<Map xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x... | How to extract data from XML using python minidom | given this xml file, i would like to extract the data out from it. However, i have trouble extracting the data from <LandmarkPointListXml> onwards.
The XML file:
<?xml version="1.0" encoding="utf-8"?>
<Map xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MapName... | [
"This code is quite fragile. It makes strong assumptions on the XML input, and would fail if the XML was modified in a valid way (e.g. if is not immediately after ).\nI suggest using a standard library when parsing XML, such as Element Tree ( http://docs.python.org/library/xml.etree.elementtree.html ) or lxml ( ht... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007342394_python.txt |
Q:
Python utf-8 accents problem
I am having some problems with accents.
I did a python script that are getting the word "refeição" from some input (IMAP fetch), this word is in Portuguese and I need convert it to be human readable. After decode, it should appear like "refeição" but I am not getting this result...
... | Python utf-8 accents problem | I am having some problems with accents.
I did a python script that are getting the word "refeição" from some input (IMAP fetch), this word is in Portuguese and I need convert it to be human readable. After decode, it should appear like "refeição" but I am not getting this result...
>>> print a
refeição
>>> ENCODI... | [
"It looks like your terminal window displays text in the single-byte ISO-8859-1 charset, (\"latin-1\"), but your python interpreter thinks the terminal is speaking UTF-8. We can see from u'refei\\xe7\\xe3o' that Python has the correct internal representation of the Portugese letters. Apparently, the print command t... | [
2,
0
] | [] | [] | [
"diacritics",
"python"
] | stackoverflow_0006968329_diacritics_python.txt |
Q:
Using boto library on S3
Is there a way to change the key of an S3 file? For example, I want to be able to do the equivalent of:
>>> from boto.s3.key import Key
>>> k=Key(bucket)
>>> k.key='cli-images/image-thumb.jpg' # this is the original key
>>> k.key='cli-images/moved/image-thumb.jpg' # this is the key I want ... | Using boto library on S3 | Is there a way to change the key of an S3 file? For example, I want to be able to do the equivalent of:
>>> from boto.s3.key import Key
>>> k=Key(bucket)
>>> k.key='cli-images/image-thumb.jpg' # this is the original key
>>> k.key='cli-images/moved/image-thumb.jpg' # this is the key I want to change it to
>>> k.save()
... | [
"just copy the object to the same bucket and delete the original one:\nfrom boto.s3.key import Key\nk=Key(bucket)\nk.key='cli-images/image-thumb.jpg'\nk.copy('bucketname', 'cli-images/moved/image-thumb.jpg')\nk.delete()\n\n"
] | [
11
] | [] | [] | [
"amazon_s3",
"boto",
"python"
] | stackoverflow_0007368999_amazon_s3_boto_python.txt |
Q:
Algorithm fast compare images \ matrix
There is one image (imA) size 10x10px and more 60 000 images (imN) 10x10
All images are black and white
The task of finding the minimum number of points with which to distinguish the first image (imA) from all others (imN) - sorry for my bad English, I add img and comment
The... | Algorithm fast compare images \ matrix | There is one image (imA) size 10x10px and more 60 000 images (imN) 10x10
All images are black and white
The task of finding the minimum number of points with which to distinguish the first image (imA) from all others (imN) - sorry for my bad English, I add img and comment
The first thing I did, it turned all the images... | [
"If I understand your question correctly, you need to calculate the number of points on the first picture, which is different from all the other pictures, irrespective of how the other pictures differ from each other?\nIf this is case, unless I'm missing something, can you not simply do something like the following... | [
1,
0
] | [
"10x10 = 100. 100 comparisons between two images. you have 60000 images. I think that algorithm have to be O(100 * 60000) = O(6000000). I don't know python, but pseudo-algorithm should be like that:\nint minDistinguishPoints = 100; \nint currentPointsDiff;\nImage imA;\n\nforeach (Image myImg in ImageItems)\n{\n ... | [
-1,
-1
] | [
"algorithm",
"image",
"python"
] | stackoverflow_0007359267_algorithm_image_python.txt |
Q:
How to use order_by with annotate() in a custom model manager
I have these models; with one custom manager.
class OrderByHighestScoreManager(models.Manager):
def get_query_set(self, *args, **kwargs):
qs = super(OrderByHighestScoreManager, self).get_query_set(*args, **kwargs)
return qs.annot... | How to use order_by with annotate() in a custom model manager | I have these models; with one custom manager.
class OrderByHighestScoreManager(models.Manager):
def get_query_set(self, *args, **kwargs):
qs = super(OrderByHighestScoreManager, self).get_query_set(*args, **kwargs)
return qs.annotate(score=Count('votes'),).order_by('score')
class AbstractEntry(... | [
"Thanks, your response was helpful in figuring out my own, slightly different approach.\nclass AbstractEntryManager(models.Manager): \n def by_score(self): \n qs = super(OrderByHighestScoreManager, self).get_query_set() \n return qs.annotate(score=Count('votes')).order_by('score')\n\nclass Abstract... | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007130710_django_django_models_python.txt |
Q:
How to insert correctly different pictures to a single file
I don't know if it's possible, since my knowledge of image processing is low. I need to put my passport size photo on an A4 sheet so that I could print it out out. I tried using GIMP, great tool. Like I said earlier my expertise is very low in this field... | How to insert correctly different pictures to a single file | I don't know if it's possible, since my knowledge of image processing is low. I need to put my passport size photo on an A4 sheet so that I could print it out out. I tried using GIMP, great tool. Like I said earlier my expertise is very low in this field. I find it difficult to place the photos efficiently in A4 sheet.... | [
"Use imagemagick:\n$ convert -append photo1.jpg photo2.jpg photo3.jpg row1.jpg\n\nOr try +append to change the orientation.\nRepeat as needed:\n$ convert +append row1.jpg row2.jpg row3.jpg a4.jpg\n\nI may have gotten the -append and the +append mixed up.\n",
"You can use imagemagick\nImagemaick command line tools... | [
1,
0
] | [] | [] | [
"gimp",
"image",
"image_processing",
"linux",
"python"
] | stackoverflow_0007369360_gimp_image_image_processing_linux_python.txt |
Q:
MySQL query fails in Python
The following query works on MySQL Query Analyzer and PHP but fails in Python:
update home_recipient
set
process = 'PROCESS_ID', processed_on = current_timestamp
where
sent_on is null or
timestampdiff(minute, processed_on, current_timestamp) > 60
... | MySQL query fails in Python | The following query works on MySQL Query Analyzer and PHP but fails in Python:
update home_recipient
set
process = 'PROCESS_ID', processed_on = current_timestamp
where
sent_on is null or
timestampdiff(minute, processed_on, current_timestamp) > 60
order by id limit 45
The error ... | [
"The three \" are the problem \n\"\"\" This is a string for documentation\"\"\"\n\nhttp://docs.python.org/tutorial/introduction.html\ncurs.execute(\"update home_recipient set process = 'PROCESS_ID', processed_on = current_timestamp where sent_on is null or timestampdiff(minute, processed_on, current_timestamp) > 60... | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0007368431_mysql_python.txt |
Q:
Capturing Windows click events with Python
I'm trying to capture left/right/double click events with Python on Windows. Can I do this with win32api?
For example, every time I click somewhere, I want it to print out the exact coordinates of the place it was clicked and what type of click it was.
Someone want to po... | Capturing Windows click events with Python | I'm trying to capture left/right/double click events with Python on Windows. Can I do this with win32api?
For example, every time I click somewhere, I want it to print out the exact coordinates of the place it was clicked and what type of click it was.
Someone want to point me in the right direction, please?
| [
"Maybe PyHook is what you are looking for\n",
"Try with this code:\n#!/usr/bin/env python\n# coordinates.py\n\nimport gtk\n\nclass Coordinates(gtk.Window):\n\n def __init__(self):\n gtk.Window.__init__(self)\n self.connect(\"expose_event\", self.expose)\n self.connect(\"motion_notify_event... | [
4,
1
] | [] | [] | [
"mouseevent",
"python",
"windows"
] | stackoverflow_0007365247_mouseevent_python_windows.txt |
Q:
Twisted deferred not callable after connection failure
Having my client factory here:
import logging, traceback
from twisted.internet.protocol import ClientFactory
from twisted.internet import defer, reactor, ssl
from twisted.application import service
from protocols.smpp.protocol import SMPPClientProtocol
class ... | Twisted deferred not callable after connection failure | Having my client factory here:
import logging, traceback
from twisted.internet.protocol import ClientFactory
from twisted.internet import defer, reactor, ssl
from twisted.application import service
from protocols.smpp.protocol import SMPPClientProtocol
class SMPPClientFactory(ClientFactory):
protocol = SMPPClient... | [
"On your launch code, you instantiated an SMPPClientFactory and called connect() on it. This particular instance will have the connectDeferred attribute. However, connect also instantiated another SMPPClientFactory: factory = SMPPClientFactory(self.config, self.msgHandler) and this is the instance you used to creat... | [
2
] | [] | [] | [
"deferred",
"factory",
"python",
"twisted"
] | stackoverflow_0007368891_deferred_factory_python_twisted.txt |
Q:
How do I terminate a program in Python?
This is my project description:
Write a program that displays the following menu:
1) Convert Fahrenheit to Celsius
2) Convert Celsius to Fahrenheit
Enter 1, 2, or 0 to exit:
In the case of options 1 and 2, the program should then prompt the user for the temperature, p... | How do I terminate a program in Python? | This is my project description:
Write a program that displays the following menu:
1) Convert Fahrenheit to Celsius
2) Convert Celsius to Fahrenheit
Enter 1, 2, or 0 to exit:
In the case of options 1 and 2, the program should then prompt the user for the temperature, perform the conversion, and output the result.... | [
"\nGet rid of the second x = raw_input(... line. You don't need it.\nCalculate y right before you print it, inside the if block. No point doing math the user didn't want.\nSame for z: calculate it right before you need it.\nPut this after the a = raw_input(... line:\n\nCode:\nif a == 0:\n import sys\n sys.exi... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007369527_python.txt |
Q:
Numpy and 16-bit PGM
What is an efficient and clear way to read 16-bit PGM images in Python with numpy?
I cannot use PIL to load 16-bit PGM images due to a PIL bug. I can read in the header with the following code:
dt = np.dtype([('type', 'a2'),
('space_0', 'a1', ),
('x', 'a3', ),
... | Numpy and 16-bit PGM | What is an efficient and clear way to read 16-bit PGM images in Python with numpy?
I cannot use PIL to load 16-bit PGM images due to a PIL bug. I can read in the header with the following code:
dt = np.dtype([('type', 'a2'),
('space_0', 'a1', ),
('x', 'a3', ),
('space_1', 'a... | [
"import re\nimport numpy\n\ndef read_pgm(filename, byteorder='>'):\n \"\"\"Return image data from a raw PGM file as numpy array.\n\n Format specification: http://netpbm.sourceforge.net/doc/pgm.html\n\n \"\"\"\n with open(filename, 'rb') as f:\n buffer = f.read()\n try:\n header, width, ... | [
25,
4,
1,
1,
0
] | [] | [] | [
"16_bit",
"numpy",
"pgm",
"python"
] | stackoverflow_0007368739_16_bit_numpy_pgm_python.txt |
Q:
is there a way to do range() with ast.literal_eval?
or another way to ask I suppose is there a literal which will literal_eval to the equivalent of the range function (without sending the entire array as a range).
the following
import ast
ast.literal_eval("range(0,3)")
ast.literal_eval("[0, 1, 2, 3][0:3]")
result... | is there a way to do range() with ast.literal_eval? | or another way to ask I suppose is there a literal which will literal_eval to the equivalent of the range function (without sending the entire array as a range).
the following
import ast
ast.literal_eval("range(0,3)")
ast.literal_eval("[0, 1, 2, 3][0:3]")
results in:
Traceback (most recent call last):
File "<stdin>"... | [
"http://docs.python.org/library/ast.html#ast.literal_eval\n\nast.literal_eval(node_or_string)\nSafely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007370270_python.txt |
Q:
Why do I have to type ctrl-d twice?
For my own amusement, I've cooked up a python script that allows me to use python for bash one-liners; Supply a python generator expression; and the script iterates over it. Here's the script:
DEFAULT_MODULES = ['os', 're', 'sys']
_g = {}
for m in DEFAULT_MODULES:
_g[m] = ... | Why do I have to type ctrl-d twice? | For my own amusement, I've cooked up a python script that allows me to use python for bash one-liners; Supply a python generator expression; and the script iterates over it. Here's the script:
DEFAULT_MODULES = ['os', 're', 'sys']
_g = {}
for m in DEFAULT_MODULES:
_g[m] = __import__(m)
import sys
sys.stdout.writ... | [
"Ctrl-D is recognized not necessarily as EOF, but as \"terminate current read() call\".\nIf you have an empty line (or just pressed Ctrl-D) and press Ctrl-D, your read() terminates immediately and returns 0 read bytes. And this is a sign for EOF.\nIf you have data in a line and press Ctrl-D, your read() terminates ... | [
12,
3,
0
] | [] | [] | [
"eof",
"python",
"tty"
] | stackoverflow_0007369170_eof_python_tty.txt |
Q:
Can Haystack filter by a geodjango PointField?
I want to be able to use django-haystack to do full text searches on a model. This model uses a PointField to store coordinates. I want to filter the results of a search based on the distance from a point. Is this possible with Haystack? Is there a better way to d... | Can Haystack filter by a geodjango PointField? | I want to be able to use django-haystack to do full text searches on a model. This model uses a PointField to store coordinates. I want to filter the results of a search based on the distance from a point. Is this possible with Haystack? Is there a better way to do this?
from django.contrib.gis.db import models
c... | [
"It sounds like you want users to input geographic information, like an address or zipcode into the text search. This is how I did it, though I'm not sure how it scales yet. I just finished this 5 minutes ago. \nYou should create a custom search form subclassed from SearchForm or one of the other options (for me it... | [
3
] | [] | [] | [
"django",
"django_haystack",
"full_text_search",
"geodjango",
"python"
] | stackoverflow_0007365016_django_django_haystack_full_text_search_geodjango_python.txt |
Q:
Image to ASCII in python using a PPM file. PIL not allowed
Needing a little help/direction with a project. Our task is to take in a .ppm file (the one we are required to test with is found here: http://beastie.cs.ua.edu/cs250/projects/asciiart/tux.ppm) and reprint it out on the screen using ascii characters. We ar... | Image to ASCII in python using a PPM file. PIL not allowed | Needing a little help/direction with a project. Our task is to take in a .ppm file (the one we are required to test with is found here: http://beastie.cs.ua.edu/cs250/projects/asciiart/tux.ppm) and reprint it out on the screen using ascii characters. We are required to convert the pixels to greyscale. This is really wh... | [
"The PPM isn't hard to parse.\nThe header:\nP3\n50 50\n255\n\n\nP3 means that the image is an ASCII pixmap (color).\n50 50 is the width and height.\n255 is the max color value.\n\nThe body:\n254 254 252 254 254 252 254 254 252 254 254 252 254 254 252 254 254 252 \n254 254 252 254 254 252 254 254 252 254 254 252 254... | [
3,
1
] | [] | [] | [
"ascii",
"python"
] | stackoverflow_0007369756_ascii_python.txt |
Q:
Unable to get OAuth "Request Token" while working with the Tumblr API using Python
I've been using libraries to handle OAuth so far, but lately I've been digging deeper trying to understand the underlying OAuth process. Currently, I'm trying to connect to Tumblr API v2 using OAuth 1.0a with this simple code:
impor... | Unable to get OAuth "Request Token" while working with the Tumblr API using Python | I've been using libraries to handle OAuth so far, but lately I've been digging deeper trying to understand the underlying OAuth process. Currently, I'm trying to connect to Tumblr API v2 using OAuth 1.0a with this simple code:
import urllib, urllib2, time, random, hmac, base64, hashlib
def makenonce():
random_numb... | [
"Solved it after making just 2 simple changes in the above code:\n\nnormalized_http_method = 'GET' #not POST\noauth_header = 'OAuth realm=\"http://www...' # The word \"Authorization\" is unnecessary. I had taken this out earlier as listed in \"Things I've tried without any success\", but the error listed in (1) thr... | [
4
] | [] | [] | [
"api",
"oauth",
"python",
"tumblr"
] | stackoverflow_0007309478_api_oauth_python_tumblr.txt |
Q:
Search imap using parsed date from another email
Using Python and imaplib
I am connecting to 2 imap servers (gmail) and trying to match emails between them using the date their date time.
I am having 2 problems.
The date returned by parsing the header is not directly usable in searching, the format is wrong.
It i... | Search imap using parsed date from another email | Using Python and imaplib
I am connecting to 2 imap servers (gmail) and trying to match emails between them using the date their date time.
I am having 2 problems.
The date returned by parsing the header is not directly usable in searching, the format is wrong.
It is not clear to me which imap search to use to search b... | [
"It looks like the problem is just date formatting. In which case this:\na = datetime.strptime(pmsg['Date'],\"%a, %d %b %Y %H:%M:%S %z\")\n\nwill give you a date time object and this will give you the message:\nsearchfor = '(ON \"%s\")' %(a.strftime(\"%d-%b-%Y\")\n\nBear in mind this will give all messages from tha... | [
2
] | [] | [] | [
"imap",
"imaplib",
"python",
"search"
] | stackoverflow_0007310003_imap_imaplib_python_search.txt |
Q:
Django-lettuce: where to keep language file
I've added lettuce into my django project, where to keep the languages.py file in django project instead of modifying lettuce itself?
Sultan
A:
I do not know of lettuce, but I am guessing that you can include your file languages.py anywhere python can find it.
I do t... | Django-lettuce: where to keep language file | I've added lettuce into my django project, where to keep the languages.py file in django project instead of modifying lettuce itself?
Sultan
| [
"I do not know of lettuce, but I am guessing that you can include your file languages.py anywhere python can find it. \nI do this by appending the directory containing my files into sys.path. You could overwrite PYTHONPATH instead. A directory containing python code should have a __init__.py file. \nI am not sure i... | [
0
] | [] | [] | [
"bdd",
"django",
"lettuce",
"python"
] | stackoverflow_0007370757_bdd_django_lettuce_python.txt |
Q:
Regex in python
How to write regex for string like:
'$12.78..'
I googled and found "re" is the Python module to do it using import re.
But I couldn't figured out the exact way to do it.
A:
As a starter:
import re
print re.match("\$\d\d\.\d+", "$12.1")
print re.match("\$\d\d\.\d+", "12.1")
print re.match("\$... | Regex in python | How to write regex for string like:
'$12.78..'
I googled and found "re" is the Python module to do it using import re.
But I couldn't figured out the exact way to do it.
| [
"As a starter:\n import re\n print re.match(\"\\$\\d\\d\\.\\d+\", \"$12.1\")\n print re.match(\"\\$\\d\\d\\.\\d+\", \"12.1\")\n print re.match(\"\\$\\d\\d\\.\\d+\", \"$123.1\")\n print re.match(\"\\$\\d\\d\\.\\d+\", \"$12.\")\n\nIf you want to learn more about regular expressions in Python I recommend:\n\nhttp://di... | [
5
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007370755_python_regex.txt |
Q:
Django:Map urls to class like in web.py
i am learning django but gave web.py a try first.
while reading django's documentation i found that in i need to check for the request type in each method.. like:
def myview():
if request.method == "POST":
#blah balh
#ke$ha (jst kiddn)
else:
#(balh)x2
can ... | Django:Map urls to class like in web.py | i am learning django but gave web.py a try first.
while reading django's documentation i found that in i need to check for the request type in each method.. like:
def myview():
if request.method == "POST":
#blah balh
#ke$ha (jst kiddn)
else:
#(balh)x2
can the web.py type classes be implemented in dja... | [
"Yes, that's possible with the new (as in Django 1.3) class-based views:\nfrom django.views.generic.base import View\n\nclass MyView(View):\n\n def get(self, request, *args, **kwargs):\n # return a response here\n\n def post(self, request, *args, **kwargs):\n # return a response here\n\nUsually,... | [
3
] | [] | [] | [
"django",
"python",
"web",
"web.py"
] | stackoverflow_0007370935_django_python_web_web.py.txt |
Q:
selecting an item in a combobox pygtk glade3
Using pygtk 2.24 and glade 3 I'm having trouble with a combobox. When I click on an item in it I get the following error message
interface.py:94: Warning: unable to set property `text' of type `gchararray' from
value of type `glong'
gtk.main()
My code for the combobox... | selecting an item in a combobox pygtk glade3 | Using pygtk 2.24 and glade 3 I'm having trouble with a combobox. When I click on an item in it I get the following error message
interface.py:94: Warning: unable to set property `text' of type `gchararray' from
value of type `glong'
gtk.main()
My code for the combobox is here
#get the combo box out of the builder and... | [
"I have this that works (but I do not use glade) :\nliststore = gtk.ListStore(gobject.TYPE_STRING)\ncombobox = gtk.ComboBox(liststore)\ncell = gtk.CellRendererText()\ncombobox.pack_start(cell, True)\ncombobox.add_attribute(cell, 'text', 0)\n\nSo I suspect your self.cbmoRepresentation not to be of the righ... | [
0
] | [] | [] | [
"combobox",
"glade",
"gtk",
"pygtk",
"python"
] | stackoverflow_0007371645_combobox_glade_gtk_pygtk_python.txt |
Q:
Function Design
I have an array contanining the position of the different objects in my scene.
To calculate the next movement step
I want to build a function like this:
f(x) = 1/(x-pos1)^2 + 1/(x-pos2)^2 + ...
^term1 ^term2 ^term_n
I don't know how many objects are in my scene so I want to ... | Function Design | I have an array contanining the position of the different objects in my scene.
To calculate the next movement step
I want to build a function like this:
f(x) = 1/(x-pos1)^2 + 1/(x-pos2)^2 + ...
^term1 ^term2 ^term_n
I don't know how many objects are in my scene so I want to add terms in the func... | [
"Why not loop over them?\nIt's not going to be very much slower than otherwise.\ndef f(x,poslist):\n v = 0\n for pos in poslist:\n v += 1/((x-pos)*(x-pos))\n return v\n\nIf you really want to do it in python you can do it like this (but I beleive it's going to be very slow)\ndef addterm(f, pos):\n def g(x):\... | [
2,
1,
0
] | [] | [] | [
"c++",
"function",
"python"
] | stackoverflow_0007371804_c++_function_python.txt |
Q:
Filtering an embedded list in MongoEngine
If I have these models:
class Sub(EmbeddedDocument):
name = StringField()
class Main(Document):
subs = ListField(EmbeddedDocumentField(Sub))
I want to have a query that returns the Mains, with the subs being filtered by name existing
Main.objects.filter(subs__nam... | Filtering an embedded list in MongoEngine | If I have these models:
class Sub(EmbeddedDocument):
name = StringField()
class Main(Document):
subs = ListField(EmbeddedDocumentField(Sub))
I want to have a query that returns the Mains, with the subs being filtered by name existing
Main.objects.filter(subs__name__exists=True)
This returns the correct Mains... | [
"MongoDB doesn't support exactly this operation that you're requesting, and therefore neither does Mongoengine.\nYou can perform slicing operations on arrays (lists), but not ad-hoc filtering. Slicing in MongoDB arrays works similarly to slicing lists in Python, and you can do it with Mongoengine using the slice__ ... | [
3
] | [] | [] | [
"mongodb",
"mongoengine",
"python"
] | stackoverflow_0007368695_mongodb_mongoengine_python.txt |
Q:
File Renaming by Convention - All within a folder
I often find myself in a situation where I have a folder containing files which are named according to a certain file naming convention, and I have to go through them manually to rename them to the one I want. A laborious repetitive task.
E.g. 01_artist_name_-_albu... | File Renaming by Convention - All within a folder | I often find myself in a situation where I have a folder containing files which are named according to a certain file naming convention, and I have to go through them manually to rename them to the one I want. A laborious repetitive task.
E.g. 01_artist_name_-_album_title_-_song_title_somethingelse.mp3 -> Song_Title.mp... | [
"For your special case:\nimport glob, shutil, os.path\n\n# glob.glob returns a list with all pathes according to the given pattern \nfor path in glob.glob(\"music_folder/*.mp3\"):\n\n # os.path.dirname gives the directory name, here it is \"music_folder\"\n dirname = os.path.dirname(path)\n\n # example... | [
1
] | [] | [] | [
"file",
"filenames",
"python",
"regex",
"windows"
] | stackoverflow_0007372121_file_filenames_python_regex_windows.txt |
Q:
How to delete line from the file in python
I have a file F, content huge numbers e.g F = [1,2,3,4,5,6,7,8,9,...]. So i want to loop over the file F and delete all lines contain any numbers in file say f = [1,2,4,7,...].
F = open(file)
f = [1,2,4,7,...]
for line in F:
if line.contains(any number in f):
... | How to delete line from the file in python | I have a file F, content huge numbers e.g F = [1,2,3,4,5,6,7,8,9,...]. So i want to loop over the file F and delete all lines contain any numbers in file say f = [1,2,4,7,...].
F = open(file)
f = [1,2,4,7,...]
for line in F:
if line.contains(any number in f):
delete the line in F
| [
"You can not immediately delete lines in a file, so have to create a new file where you write the remaining lines to. That is what chonws example does.\n",
"It's not clear to me what the form of the file you are trying to modify is. I'm going to assume it looks like this:\n1,2,3\n4,5,7,19\n6,2,57\n7,8,9\n128\n\nS... | [
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007372139_python.txt |
Q:
RSA-PSSR with a server-side scripting language (php, perl, python, shell, ...)
I'm developing a cryptographic software license system based on digital signature with message recovery (RSA-PSSR).
It means that the signed message (in this case, the license block) is encoded directly in the signature (where we usuall... | RSA-PSSR with a server-side scripting language (php, perl, python, shell, ...) | I'm developing a cryptographic software license system based on digital signature with message recovery (RSA-PSSR).
It means that the signed message (in this case, the license block) is encoded directly in the signature (where we usually encode only the hash of the message that we want to sign).
The license keys will b... | [
"phpseclib, a pure PHP RSA implementation, supports PSS. Just do $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PSS). Doesn't do PSS-R though...\n",
"I don't know of any scripting languages supporting Probabilistic Signature Scheme.\nHowever, Perl does have PSS support:\n\nCrypt::RSA::SS::PSS. Use sample in \"On Pe... | [
2,
1
] | [] | [] | [
"cryptography",
"openssl",
"perl",
"php",
"python"
] | stackoverflow_0007339799_cryptography_openssl_perl_php_python.txt |
Q:
Effective way to find total number of files in a directory
I am building a Music file organizer(in python2) in which I read the metadata of all files & then put those file in the required folder.
Now, I am already ready with the command line interface but this script shows feedback in a way that it shows "Which fi... | Effective way to find total number of files in a directory | I am building a Music file organizer(in python2) in which I read the metadata of all files & then put those file in the required folder.
Now, I am already ready with the command line interface but this script shows feedback in a way that it shows "Which file is it working on right now?".
If the directory contains say 5... | [
"I'm sorry to say this but no there isn't any way to do it more efficiently than recursively finding the files (at least that is platform (or filesystem) independent).\nIf the filesystem can help you it will, and you can't do anything to help it.\nThe reason it's not possible to do it without recursive scanning is ... | [
2,
1
] | [] | [] | [
"algorithm",
"archlinux",
"linux",
"python"
] | stackoverflow_0007371878_algorithm_archlinux_linux_python.txt |
Q:
overview of differences between inheritance in python and java
I have a background in java, and I'm learning python. I'll need to be using inheritance soon, and I want to find out what any key differences are between how things are done in each of them. I've had a look online and found some information about diffe... | overview of differences between inheritance in python and java | I have a background in java, and I'm learning python. I'll need to be using inheritance soon, and I want to find out what any key differences are between how things are done in each of them. I've had a look online and found some information about differences between the two and what to look out for, and I've found that... | [
"Java has a fairly straightforward inheritance model: classes must have one (and only one) parent . You can't inherit from multiple parents, although you can implement multiple interfaces, which can be seen as Java's version of \"multiple inheritance.\"\nMost methods in Java classes are dynamically (late) bound, wi... | [
4,
2
] | [] | [] | [
"inheritance",
"java",
"multiple_inheritance",
"python"
] | stackoverflow_0007371765_inheritance_java_multiple_inheritance_python.txt |
Q:
Installing packages from source into EPD Python on Mac OS X
I recently compiled the shogun library from source, but I'm not sure where I need to place the python files created. make install placed them in '/usr/local/lib/python2.7/dist-packages' which I assume is valid on linux systems.
sys.path in python doesn't... | Installing packages from source into EPD Python on Mac OS X | I recently compiled the shogun library from source, but I'm not sure where I need to place the python files created. make install placed them in '/usr/local/lib/python2.7/dist-packages' which I assume is valid on linux systems.
sys.path in python doesn't have a dist-packages in its path, only a site-packages
| [
"When you configure shogun, you need to specify the python path. \nhttp://www.shogun-toolbox.org/doc/en/current/installation.html\n./configure --pydir /path to epd\n\nThen remake and reinstall. \n",
"Workaround: Decided to simply add a .pth file to my site-packages directory which points to /usr/local/lib/python... | [
0,
0
] | [] | [] | [
"import",
"macos",
"python"
] | stackoverflow_0007369271_import_macos_python.txt |
Q:
Why is Python 3 not available in PyCharm?
This is the changelog of version 1.2 of PyCharm and they say it is compatible with Python 3.2. Now version 1.5.4 say that it's working until Python 3.1.
I'm running the trial version on Mac, and the program it's using 2.6 python-default framework and I can't get python 3.2... | Why is Python 3 not available in PyCharm? | This is the changelog of version 1.2 of PyCharm and they say it is compatible with Python 3.2. Now version 1.5.4 say that it's working until Python 3.1.
I'm running the trial version on Mac, and the program it's using 2.6 python-default framework and I can't get python 3.2 one (I can't find it in Python.framework). I'm... | [
"Pycharm does not include python so you need to get it in another fashion.\nOSX only includes a python from the 2.x series so you need to install a python from the 3.x series\nthere are various ways of doing this\n1) Install from python.org - thus requires nothing else.\n2) Install from a package manager e.g. macpo... | [
3
] | [] | [] | [
"incompatibility",
"pycharm",
"python",
"python_3.x"
] | stackoverflow_0007372619_incompatibility_pycharm_python_python_3.x.txt |
Q:
Destructor isn't called after adding a qmenubar
I have the following files (Main window/UI):
files
UI:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Sat Apr 23 15:53:12 2011
# by: PyQt4 UI code generator 4.7.3
#
# WARNING! All changes made in this fi... | Destructor isn't called after adding a qmenubar | I have the following files (Main window/UI):
files
UI:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Sat Apr 23 15:53:12 2011
# by: PyQt4 UI code generator 4.7.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
cl... | [
"You can't rely on __del__ being called for all of your objects, especially when your program is ending (see that other answer)\nAccording to PyQt documentation:\n\nHowever, if a slot is a lambda function or a partial function then\n its reference count is automatically incremented to prevent it from\n being imme... | [
2
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0007371474_pyqt_pyqt4_python_qt_qt4.txt |
Q:
Plotting points on Image using gnuplot.py
Is there a way to plot some points on an image using Gnuplot.py .
I have a text file containing the co-ordinates of the point which i want to plot on an image(as a background.)
A:
Why is it that you want to use gnuplot.py? I would recommend using the Python Imaging Libra... | Plotting points on Image using gnuplot.py | Is there a way to plot some points on an image using Gnuplot.py .
I have a text file containing the co-ordinates of the point which i want to plot on an image(as a background.)
| [
"Why is it that you want to use gnuplot.py? I would recommend using the Python Imaging Library (PIL), it has a ImageDraw module, which allows you to draw on top of images. It would be very straight forward to do this in python. \nI appologise if this is not the answer you are looking for, but I have had great resul... | [
0
] | [] | [] | [
"gnuplot",
"python"
] | stackoverflow_0007372582_gnuplot_python.txt |
Q:
Retrieving binary file content using Javascript, base64 encode it and reverse-decode it using Python
I'm trying to download a binary file using XMLHttpRequest (using a recent Webkit) and base64-encode its contents using this simple function:
function getBinary(file){
var xhr = new XMLHttpRequest();
xhr.o... | Retrieving binary file content using Javascript, base64 encode it and reverse-decode it using Python | I'm trying to download a binary file using XMLHttpRequest (using a recent Webkit) and base64-encode its contents using this simple function:
function getBinary(file){
var xhr = new XMLHttpRequest();
xhr.open("GET", file, false);
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(... | [
"So I'm answering to myself — and sorry for that — but I think it might be useful for someone as lost as I was ;)\nSo you have to use ArrayBuffer and set the responseType property of your XMLHttpRequest object instance to arraybuffer for retrieving a native array of Bytes, which can be converted to base64 using the... | [
79
] | [] | [] | [
"base64",
"encoding",
"javascript",
"python",
"xmlhttprequest"
] | stackoverflow_0007370943_base64_encoding_javascript_python_xmlhttprequest.txt |
Q:
Change text using perl or python
There is no "sed" on my server so I should use python or perl to change recursive in all files old_text to new_text. Help me please to do it using perl or python.
A:
perl -p -i -e 's/old_text/new_text/g' file1 file2 ...
| Change text using perl or python | There is no "sed" on my server so I should use python or perl to change recursive in all files old_text to new_text. Help me please to do it using perl or python.
| [
"perl -p -i -e 's/old_text/new_text/g' file1 file2 ...\n\n"
] | [
5
] | [] | [] | [
"perl",
"python"
] | stackoverflow_0007372799_perl_python.txt |
Q:
Extending my application - Pyramid/Pylons/Python
Simple question about extending my application
Lets say I have a "Main Application", and in this application I have the following in the _init_.py file:
config.add_route('image_upload', '/admin/image_upload/',
view='mainapp.views.uploader',
view_renderer='/... | Extending my application - Pyramid/Pylons/Python | Simple question about extending my application
Lets say I have a "Main Application", and in this application I have the following in the _init_.py file:
config.add_route('image_upload', '/admin/image_upload/',
view='mainapp.views.uploader',
view_renderer='/site/upload.mako')
and in the views.py I have:
def up... | [
"You don't have to copy your code to do this. Use the Configurator.include method to include your \"Main Application\" configuration in your new application. The documentation explains this pretty well both here and here, but the essentially, if you declare your main apps configuration inside a callable:\ndef main_... | [
2
] | [] | [] | [
"pylons",
"pyramid",
"python"
] | stackoverflow_0007372720_pylons_pyramid_python.txt |
Q:
How to access a 'window' of elements from a list in every iteration?
Suppose I have a list [a,b,c,d,e], I want to create a list of tuples [(a,b,c),(b,c,d),(c,d,e)]. Is it possible without using array indices as my loop variable? What is the best way of doing this?
A:
zip(li, li[1:],li[2:])
This zips together th... | How to access a 'window' of elements from a list in every iteration? | Suppose I have a list [a,b,c,d,e], I want to create a list of tuples [(a,b,c),(b,c,d),(c,d,e)]. Is it possible without using array indices as my loop variable? What is the best way of doing this?
| [
"zip(li, li[1:],li[2:])\n\nThis zips together the elements. Each iteration corresponds to li[i], li[i+1], li[i+2], hence solving the original problem.\n",
"Not sure this satisfies your constraints, but it should do it.\nthe_list = [1,2,3,4,5,6,7]\ntuple_size = 3\ntuple_list = [tuple(the_list[i-tuple_size:i]) for ... | [
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007372441_list_python.txt |
Q:
Python Modules: When one imports them, do they go into memory?
I just finished this exercise for beginners on creating and importing modules in python.
I was wondering does everything in the module get imported into the computer's memory?
Will there be implications later on with memory as the code gets longer and... | Python Modules: When one imports them, do they go into memory? | I just finished this exercise for beginners on creating and importing modules in python.
I was wondering does everything in the module get imported into the computer's memory?
Will there be implications later on with memory as the code gets longer and the modules imported become more numerous?
Will I need to know memo... | [
"Your modules are automatically compiled (.pyc files) which are then imported into memory, but you do not have to be affraid of getting out of memory: modules are very small; it is common to have thousands of modules loaded at a time!\nYou do not need to know memory management as Python does all the work for you.\n... | [
9,
3,
1
] | [] | [] | [
"python",
"python_module"
] | stackoverflow_0007372966_python_python_module.txt |
Q:
What to put in a python module docstring?
Ok, so I've read both PEP 8 and PEP 257, and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should document the functions and classes that the module exports, but I... | What to put in a python module docstring? | Ok, so I've read both PEP 8 and PEP 257, and I've written lots of docstrings for functions and classes, but I'm a little unsure about what should go in a module docstring. I figured, at a minimum, it should document the functions and classes that the module exports, but I've also seen a few modules that list author na... | [
"Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:\n\"\"\"This module does blah blah.\"\"\"\n\nclass... | [
237,
60
] | [] | [] | [
"documentation",
"module",
"python"
] | stackoverflow_0002557110_documentation_module_python.txt |
Q:
get the DST boundaries of a given timezone in python
Is it possible to get the DST boundaries of a given timezone with pytz?
A:
It doesn't seem to be officially supported. However, you can poke at the internals of a DstTzInfo object and get it from there:
>>> from pytz import timezone
>>> tz = timezone('Europe/L... | get the DST boundaries of a given timezone in python | Is it possible to get the DST boundaries of a given timezone with pytz?
| [
"It doesn't seem to be officially supported. However, you can poke at the internals of a DstTzInfo object and get it from there:\n>>> from pytz import timezone\n>>> tz = timezone('Europe/London')\n>>> tz._utc_transition_times\n[datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1916, 5, 21, 2, 0),\n...\ndatetime.d... | [
21
] | [] | [] | [
"python",
"pytz"
] | stackoverflow_0007373389_python_pytz.txt |
Q:
Attribute getters in python
I vaguely remember learning about some sort of built-in function that would do the equivalent of
f = lambda x: x.attr
Am I just imagining this or does such a thing exist?
A:
operator.attrgetter()
A:
getattr(obj, 'attr')
will get the attribute attr from obj, or raise AttributeErro... | Attribute getters in python | I vaguely remember learning about some sort of built-in function that would do the equivalent of
f = lambda x: x.attr
Am I just imagining this or does such a thing exist?
| [
"operator.attrgetter()\n",
"getattr(obj, 'attr')\n\nwill get the attribute attr from obj, or raise AttributeError if it doesn't exist. You can also supply a default value:\ngetattr(obj, 'attr', None)\n\nin which case the default will be returned instead of raising an exception if the attribute can not be found o... | [
11,
3
] | [] | [] | [
"python"
] | stackoverflow_0007373219_python.txt |
Q:
How to tweet from GAE
I want to be able to Tweet from my app running on GAE.
Please suggest some Python library or HTTP API for the purpose.
A:
About python-twitter: I think you can use this lib it seems to be compatible with GAE: http://code.google.com/p/python-twitter/source/browse/twitter.py
Also:
Twitter has... | How to tweet from GAE | I want to be able to Tweet from my app running on GAE.
Please suggest some Python library or HTTP API for the purpose.
| [
"About python-twitter: I think you can use this lib it seems to be compatible with GAE: http://code.google.com/p/python-twitter/source/browse/twitter.py\nAlso:\nTwitter has a very great REST API https://dev.twitter.com/docs/api, You can also to simply use urlfetch and simplejson from appengine.\nFor authentication... | [
1,
0,
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"twitter"
] | stackoverflow_0007344887_google_app_engine_python_twitter.txt |
Q:
TypeError: 'str' object is not callable when using CherryPy 3.2 Basic Authentication
My site configures CherryPy by way of a configuration file. In the configuration file I am trying to setup basic authentication. I have specified the fully qualified path to a "checkpassword" function. But I'm getting an error ... | TypeError: 'str' object is not callable when using CherryPy 3.2 Basic Authentication | My site configures CherryPy by way of a configuration file. In the configuration file I am trying to setup basic authentication. I have specified the fully qualified path to a "checkpassword" function. But I'm getting an error about the tools.auth_basic.checkpassword line.
Most of the samples online, do not use a ... | [
"CherryPy config options are always regular python values. If you want to describe a module variable, you have to find a way to import it into the config file. \n[/]\ntools.auth_basic.on = True\ntools.auth_basic.realm = \"some site\"\ntools.auth_basic.checkpassword = __import__(\"Infrastructure.App.Authentication... | [
0,
0
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0007373572_cherrypy_python.txt |
Q:
SQLite3 problem in Python
I am trying to do some basic iterating over a database in Python. I am using a table that already exists and iterating some int values into it. Pretty simple stuff but I can't seem to get it working. Here is my non-functional code.
When I run the code it doesn't return any errors, but whe... | SQLite3 problem in Python | I am trying to do some basic iterating over a database in Python. I am using a table that already exists and iterating some int values into it. Pretty simple stuff but I can't seem to get it working. Here is my non-functional code.
When I run the code it doesn't return any errors, but when I check the table in the data... | [
"The code as written will work assuming you are actually connecting to your database. Are you sure you are connecting to your database? Right CWD?\nThis is a shell session showing it working\nMake a database: \n(~/): sqlite3 mydbase.sqlite\nSQLite version 3.7.2\nEnter \".help\" for instructions\nEnter SQL statement... | [
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0007218152_python_sqlite.txt |
Q:
How to delete a db.BlobProperty from many entities?
I've got stored data that's not needed and therefore I want to clean it. I could migrate from datastore to blobstore and therefore at least the field small=db.BlobProperty(default=None) is redundant so I'd like to remove it and also remove it from the entities th... | How to delete a db.BlobProperty from many entities? | I've got stored data that's not needed and therefore I want to clean it. I could migrate from datastore to blobstore and therefore at least the field small=db.BlobProperty(default=None) is redundant so I'd like to remove it and also remove it from the entities that are in the datastore since the variable called "full" ... | [
"I would go with the Mapreduce api that should be the best tool for the job in this case *:\n1 . Register the mapper\n2 . Update the entities \nfrom mapreduce import operation as op \ndef process(entity):\n entity.small = None\n yield op.db.Put(entity) \n\n* In case the number of entities is not that big, ... | [
1
] | [] | [] | [
"blob",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007373741_blob_google_app_engine_google_cloud_datastore_python.txt |
Q:
exiting a Python function call
How can my program exit a function call? I have a recursive function that, when a condition is satisfied, calls itself.
def function( arg ):
if (condition):
...
return function( arg + 1 )
My guess at how it works: if the condition is not satisfied, the function ... | exiting a Python function call | How can my program exit a function call? I have a recursive function that, when a condition is satisfied, calls itself.
def function( arg ):
if (condition):
...
return function( arg + 1 )
My guess at how it works: if the condition is not satisfied, the function call will terminate. In my program, ... | [
"As listed, your code will always just return None. It goes through all the recursion, and does this until the condition is not met, and then drops out the end of the function and returns None.\nFor example, try this:\ndef f(x):\n if (x<10):\n return f(x+1)\n return x\n\nand build up from this to do so... | [
3,
0
] | [
"If a Python function does not explicitly return a value, it returns None. That implicit return None is analagous to return in C like languages.\n"
] | [
-1
] | [
"exit",
"if_statement",
"python"
] | stackoverflow_0007373845_exit_if_statement_python.txt |
Q:
Methods for entering equations while programming in C/C++ , Python or Fortran
I am writing a code which had long mathematical equations with many trigonometric and other identities. Is there a way of visualising the same expression in latex and making a C or python expression from it or the other way around.
How d... | Methods for entering equations while programming in C/C++ , Python or Fortran | I am writing a code which had long mathematical equations with many trigonometric and other identities. Is there a way of visualising the same expression in latex and making a C or python expression from it or the other way around.
How do you enter and check mathematical expressions to see if the brackets etc are in th... | [
"Have you looked at Sympy? It has a module for generating LaTeX from python code, but it's actually quite a bit more.\nSympy, as you can probably guess from the name, is a python library for symbolic computation.\nThe Sympy library also includes it's own built-in interpreter (cd to the sympy directory in site-packa... | [
16,
3,
2,
0
] | [] | [] | [
"fortran",
"numpy",
"python",
"scientific_computing",
"scipy"
] | stackoverflow_0007307191_fortran_numpy_python_scientific_computing_scipy.txt |
Q:
How should I refactor/redesign my code
I'm writing a game in Python and I'm looking for some advice on how to redesign my code. Below is the definition of the movement component for a game entity.
The load function takes a PropertyTree object and sets the attributes of self accordingly. The save function does the ... | How should I refactor/redesign my code | I'm writing a game in Python and I'm looking for some advice on how to redesign my code. Below is the definition of the movement component for a game entity.
The load function takes a PropertyTree object and sets the attributes of self accordingly. The save function does the opposite: based on the attributes of self, a... | [
"As a starting point:\nclass Movement(EntityComponent):\n def __init__(self):\n # Default values\n self.speed = 0\n self.acceleration = 0\n\n serializable_fields = [\n ('speed', int),\n ('acceleration', int)\n ]\n\ndef load(object, source):\n for name, field_type in ob... | [
1
] | [] | [] | [
"duplicate_removal",
"python",
"refactoring"
] | stackoverflow_0007374145_duplicate_removal_python_refactoring.txt |
Q:
descriptor 'getter' requires a 'property' object but received a 'function'
So I have this code below for a Table object, and it has a property for fieldnames.
class Table(object):
'''A CSV backed SQL table.'''
@property
def fieldnames(self):
with open(self.filename) as f:
return csv... | descriptor 'getter' requires a 'property' object but received a 'function' | So I have this code below for a Table object, and it has a property for fieldnames.
class Table(object):
'''A CSV backed SQL table.'''
@property
def fieldnames(self):
with open(self.filename) as f:
return csv.DictReader(f).fieldnames
@property.setter
def fieldnames(self, fieldna... | [
"I guess it's the equivalent to TypeError: unbound method ... must be called with ... instance as first argument (got ... instance instead). To add a setter to a property via a decorator, you have to use .setter as a member/method of the property object, not as a static method/classmethod of property. The code is s... | [
23
] | [] | [] | [
"decorator",
"properties",
"python",
"setter"
] | stackoverflow_0007374666_decorator_properties_python_setter.txt |
Q:
python script to dump ELF (core and out)?
I am looking for a python script that can dump ELF file (of type core-dump).
Any pointers to existing scripts ?
A:
I suggest you use GDB to look at the core dump file. You can control GDB from Python:
Invoke and control GDB from Python
But recent versions of GDB have P... | python script to dump ELF (core and out)? | I am looking for a python script that can dump ELF file (of type core-dump).
Any pointers to existing scripts ?
| [
"I suggest you use GDB to look at the core dump file. You can control GDB from Python:\nInvoke and control GDB from Python\nBut recent versions of GDB have Python built in! You might be able to to what you want from within GDB, rather than running GDB from within Python.\nhttp://sourceware.org/gdb/wiki/PythonGdb\... | [
2
] | [] | [] | [
"coredump",
"elf",
"python"
] | stackoverflow_0007373515_coredump_elf_python.txt |
Q:
float deviation in python list
Possible Duplicate:
Python float - str - float weirdness
I run the following code in python on codepad.org:
num = 1.6
print num
list = [num]
print list
num2 = list[0]
print num2
And I get the following output:
1.6
[1.6000000000000001]
1.6
Why the tiny deviation in the list?
A:
... | float deviation in python list |
Possible Duplicate:
Python float - str - float weirdness
I run the following code in python on codepad.org:
num = 1.6
print num
list = [num]
print list
num2 = list[0]
print num2
And I get the following output:
1.6
[1.6000000000000001]
1.6
Why the tiny deviation in the list?
| [
"list.__str__ calls repr on its elements, where as print calls str:\n>>> str(1.6)\n'1.6'\n>>> repr(1.6)\n'1.6000000000000001'\n\nSince floating point numbers are not guaranteed to be exact (and cannot be exact for values that can't be expressed as a * 2b for integers a,b), both representations are correct, or, in o... | [
3
] | [] | [] | [
"floating_point",
"python",
"rounding"
] | stackoverflow_0007374836_floating_point_python_rounding.txt |
Q:
Django equivalent of New Relic RPM for Rails?
Does Django have anything equivalent to the New Relic RPM performance monitoring app for Rails (http://www.newrelic.com/)?
Looking to do an app in Django, but would really like to be able to use something like New Relic for monitoring performance.
A:
YES! We (New Re... | Django equivalent of New Relic RPM for Rails? | Does Django have anything equivalent to the New Relic RPM performance monitoring app for Rails (http://www.newrelic.com/)?
Looking to do an app in Django, but would really like to be able to use something like New Relic for monitoring performance.
| [
"YES! We (New Relic) just announced our Python agent at DjangoCon this week. Sign up at newrelic.com and enjoy!\n",
"None that I'm aware. django-debug-toolbar is a fairly popular app which can provide you with performance info for a particular page, but feature-wise it doesn't even come close to what the New Rel... | [
7,
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001203494_django_python.txt |
Q:
Python: normalizing a text file
I have a text file which contains several spelling variants of many words:
For e.g.
identification ... ID .. identity...contract.... contr.... contractor...medicine...pills..tables
So I want to have a synonym text file which contains the words synonyms and would like to replace all... | Python: normalizing a text file | I have a text file which contains several spelling variants of many words:
For e.g.
identification ... ID .. identity...contract.... contr.... contractor...medicine...pills..tables
So I want to have a synonym text file which contains the words synonyms and would like to replace all the variants with the primary word. ... | [
"Just a thought: Instead of having a list of all variation of a word, have a look at difflib\n>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])\n['apple', 'ape']\n>>> import keyword\n>>> get_close_matches('wheel', keyword.kwlist)\n['while']\n>>> get_close_matches('apple', keyword.kwlist)\n[]\n>>> g... | [
3,
3
] | [] | [] | [
"normalization",
"python",
"synonym"
] | stackoverflow_0007374851_normalization_python_synonym.txt |
Q:
Is this entity definition model too verbose?
I'm developing video game, and I'd like it to be highly modable. Currently, all my game logic is defined in Python, my engine logic in C++, and my data in XML. I'd like to explain to you how an entity is defined in my game and listen to what you think; for example, is i... | Is this entity definition model too verbose? | I'm developing video game, and I'd like it to be highly modable. Currently, all my game logic is defined in Python, my engine logic in C++, and my data in XML. I'd like to explain to you how an entity is defined in my game and listen to what you think; for example, is it too verbose?
First, some background:
Entities a... | [
"Have you considered using json instead of XML? It is less verbose, more readable, and can be converted into a ready-to-use Python data structure:\nFor example:\nimport json\n\nx='''{\"Field\": [{\"Name\": \"health\", \"Value\": 100}, {\"Name\": \"toxicity\", \"Value\": 78}],\n \"Name\": \"life\",\n \"Class\"... | [
1
] | [] | [] | [
"python",
"verbosity",
"xml"
] | stackoverflow_0007374995_python_verbosity_xml.txt |
Q:
depth-first graph search that returns path to goal
I've been trying this all week and cannot, for the life of me, figure it out.
I know that I need to have a helper function that will recurse and return pathSoFar. I can't seem to get my head around the recursion.
I'm so confused that I can't even formulate exactly... | depth-first graph search that returns path to goal | I've been trying this all week and cannot, for the life of me, figure it out.
I know that I need to have a helper function that will recurse and return pathSoFar. I can't seem to get my head around the recursion.
I'm so confused that I can't even formulate exactly what the problem is besides recursion.
Thanks for any h... | [
"Wikipedia actually has some pretty good pseudocode for depth-first traversal. These traversal algorithms label all the nodes in the graph with the order they appear in a traversal. You instead want to immediately return the path to the goal when the goal is found.\nSo let's modify the Wikipedia algorithm:\n( INC... | [
9,
1
] | [] | [] | [
"depth_first_search",
"graph",
"python",
"recursion",
"search"
] | stackoverflow_0007375020_depth_first_search_graph_python_recursion_search.txt |
Q:
Task management daemon
i have to do some long-time (2-3 days i think) tasks with my django ORM data. I look around and didnt find any good solutions.
django-tasks - http://code.google.com/p/django-tasks/ is not well documented, and i dont have any ideas how to use it.
celery - http://ask.github.com/celery/ is ex... | Task management daemon | i have to do some long-time (2-3 days i think) tasks with my django ORM data. I look around and didnt find any good solutions.
django-tasks - http://code.google.com/p/django-tasks/ is not well documented, and i dont have any ideas how to use it.
celery - http://ask.github.com/celery/ is excessive for my tasks. Is it ... | [
"Use Celery Sub-Tasks. This will allow you to start a long-running task (with many short-running subtasks underneath it), and keep good data on it's execution status within Celery's task result store. As an added bonus, subtasks will be spread across worker proccesses allowing you to take full advantage of multi-co... | [
1
] | [] | [] | [
"django",
"python",
"task"
] | stackoverflow_0007373909_django_python_task.txt |
Q:
Dynamically generating a function tree in Python.
I want to do is something like this
def mult(x, y):
return x * y
def add(x, y):
return x + y
treeFunction = mult(2, add(x, y))
#outputs 10 (2 * ( 2 + 3 ))
print treeFunction(2, 3)
basically, is there a way during run-time to change add()'s return valu... | Dynamically generating a function tree in Python. | I want to do is something like this
def mult(x, y):
return x * y
def add(x, y):
return x + y
treeFunction = mult(2, add(x, y))
#outputs 10 (2 * ( 2 + 3 ))
print treeFunction(2, 3)
basically, is there a way during run-time to change add()'s return value by multiplying it by some value.
| [
"I think what you're asking for is a lambda function:\ntreeFunction = lambda x,y: mult(2, add(x, y))\n\nThen just use it as:\ntreeFunction(2, 3)\n\nEDIT\nHave a read about closures in python. Definitely worth your time to learn.\n"
] | [
7
] | [] | [] | [
"metaprogramming",
"python",
"python_2.7"
] | stackoverflow_0007375775_metaprogramming_python_python_2.7.txt |
Q:
list extend() to index, inserting list elements not only to the end
I'm looking for the most pythonic way to implement a version of the list extend function, where it extends to a given index instead of the end of the list.
a_list = [ "I", "rad", "list" ]
b_li... | list extend() to index, inserting list elements not only to the end | I'm looking for the most pythonic way to implement a version of the list extend function, where it extends to a given index instead of the end of the list.
a_list = [ "I", "rad", "list" ]
b_list = [ "am", "a" ]
a_list.my_extend( b_list, 1 ) # insert the items from ... | [
"Sure, you can use slice indexing:\na_list[1:1] = b_list\n\nJust to demonstrate the general algorithm, if you were to implement the my_extend function in a hypothetical custom list class, it would look like this:\ndef my_extend(self, other_list, index):\n self[index:index] = other_list\n\nBut don't actually make... | [
83
] | [] | [] | [
"insert",
"list",
"python"
] | stackoverflow_0007376019_insert_list_python.txt |
Q:
Python/Django - Web Application Performance
I'm currently working on a social web application using python/django. Recently I heard about the PHP's weakness on large scale projects, and how hippo-php helped Facebook to overcome this barrier. Considering a python social web application with lot of utilization, coul... | Python/Django - Web Application Performance | I'm currently working on a social web application using python/django. Recently I heard about the PHP's weakness on large scale projects, and how hippo-php helped Facebook to overcome this barrier. Considering a python social web application with lot of utilization, could you please tell me if a similar custom tool cou... | [
"The portion to rewrite in C++ is the portion that is too slow in Python. You need to figure out where your bottleneck is, which you can do by load testing or just waiting until users complain.\nOf course, even rewriting in C++ might not help. Your bottleneck might be the database (move to a separate, faster DB ser... | [
3,
1,
1
] | [] | [] | [
"django",
"performance",
"php",
"python"
] | stackoverflow_0007373299_django_performance_php_python.txt |
Q:
Google OAuth AttributeError: "'module' object has no attribute 'docs'"
I'm trying to set up OAuth with Google services. Following the example here, I'm using:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import gdata.calendar.data
import gdata.calendar.client
i... | Google OAuth AttributeError: "'module' object has no attribute 'docs'" | I'm trying to set up OAuth with Google services. Following the example here, I'm using:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import gdata.calendar.data
import gdata.calendar.client
import gdata.acl.data
import gdata
import atom
import getopt
import sys
impor... | [
"You've imported gdata but not gdata.docs.client. Add this with the rest of your imports:\nimport gdata.docs.client\n\n"
] | [
2
] | [] | [] | [
"oauth",
"python"
] | stackoverflow_0007376107_oauth_python.txt |
Q:
Tornado with Django
I'm working on Django project (RSS and Tweet aggregator)
how to use tornado with django in this project ( all I need form
tornado is synchronize "real time update feature")
How to use django orm and django forms with tornado to hmm to do
things easier with tornado
A:
Those hacks are no lo... | Tornado with Django | I'm working on Django project (RSS and Tweet aggregator)
how to use tornado with django in this project ( all I need form
tornado is synchronize "real time update feature")
How to use django orm and django forms with tornado to hmm to do
things easier with tornado
| [
"Those hacks are no longer necessary as of Tornado 2.0.\nNow you can use tornado.wsgi.WSGIContainer to wrap django and run it on tornado. You can even specify that some urls go to tornado and get the async benefits and some go to django!\nPlease see https://github.com/bdarnell/django-tornado-demo for a\n",
"take ... | [
21,
0
] | [] | [] | [
"django",
"python",
"tornado"
] | stackoverflow_0007190431_django_python_tornado.txt |
Q:
Reading a file with unproperly marked dictionaries
I have a file with a list of dictionaries, most of them being unproperly marked with quotations marks. An example is the following:
{game:Available,player:Available,location:"Chelsea, London, England",time:Available}
{"game":"Available","player":"Available","locat... | Reading a file with unproperly marked dictionaries | I have a file with a list of dictionaries, most of them being unproperly marked with quotations marks. An example is the following:
{game:Available,player:Available,location:"Chelsea, London, England",time:Available}
{"game":"Available","player":"Available","location":"Chelsea, London, England","time":"Available","date... | [
"If it's more complicated then what you have given as examples, or if it has to be faster, you should probably look into pyparsing. \nOtherwise you could write something more hacky like this:\ncontentlines = [\"\"\"{\"game\":\"Available\",\"player\":\"Available\",\"location\":\"Chelsea, London, England\",\"time\":\... | [
1,
1,
0,
0
] | [] | [] | [
"dictionary",
"formatting",
"python"
] | stackoverflow_0007368302_dictionary_formatting_python.txt |
Q:
Handling foreign characters in HTTP POST with gae python
It's puzzling me that I've got 2 functions with HTTP POST where one breaks foreign characters and I just do self.request.POST.get('text') to get the value in both functions. The difference I see is that where it breaks it inherits blobstoreuploadhandler so t... | Handling foreign characters in HTTP POST with gae python | It's puzzling me that I've got 2 functions with HTTP POST where one breaks foreign characters and I just do self.request.POST.get('text') to get the value in both functions. The difference I see is that where it breaks it inherits blobstoreuploadhandler so therefore I suspect that it might have to do with that change. ... | [
"xcTW is the result of base-64 encoding the cp1252 or latin1 encoding of those 3 characters; see the following IDLE session:\n>>> import base64; print repr(base64.b64decode('xcTW'))\n'\\xc5\\xc4\\xd6'\n>>> print repr('ÅÄÖ')\n'\\xc5\\xc4\\xd6'\n>>>\n\nBUT base-64 encoding mangles ASCII characters as well:\n>>> base6... | [
1,
1
] | [] | [] | [
"google_app_engine",
"http",
"post",
"python"
] | stackoverflow_0007375673_google_app_engine_http_post_python.txt |
Q:
Python, Brew, and MySQLdb
I have been running python from a brew install. I went to install the mysql_python egg with setup tools (standard install according to mysql_python instructions) and it installed to /usr/local/lib/python2.7/site-packages/. The dependencies processed, etc.
Then I went to run python consol... | Python, Brew, and MySQLdb | I have been running python from a brew install. I went to install the mysql_python egg with setup tools (standard install according to mysql_python instructions) and it installed to /usr/local/lib/python2.7/site-packages/. The dependencies processed, etc.
Then I went to run python console. I can import other things (e... | [
"In trying to duplicate your error I did the following (I assume, being a homebrewer, you have done the same).\n1) brew install python To install Python 2.7\n2) brew install mysql To install mysql to the system (needed for various drivers)\n3) Configured mysql per homebrew's recommendations\n4) Downloaded mysql_pyt... | [
15
] | [] | [] | [
"homebrew",
"mysql",
"mysql_python",
"python"
] | stackoverflow_0007375199_homebrew_mysql_mysql_python_python.txt |
Q:
Sending a json object from extjs page to backend
I am new to Extjs. I wanted to know how can I send a json object to the backend from an extjs page. I am using python to connect to the databse. What I wanted to do was, if an user enters data on the form, that data to be transfered to the database. I am not getting... | Sending a json object from extjs page to backend | I am new to Extjs. I wanted to know how can I send a json object to the backend from an extjs page. I am using python to connect to the databse. What I wanted to do was, if an user enters data on the form, that data to be transfered to the database. I am not getting any good tutorials online. Can someone please help?? ... | [
"There are two ways to send Json Object from a form to the Server side for processing and saving in database. \n1st way:\nExt.Ajax.request({\n url : 'your-server-url-to-post-to',\n method : 'POST', //or GET, PUT, DELETE.. case sensitive\n jsonData : your-json-object\n params : {\n //your-request-parameters\n ... | [
4
] | [] | [] | [
"extjs",
"json",
"python"
] | stackoverflow_0007376318_extjs_json_python.txt |
Q:
Python integer issues
EDIT: SOLVED--SOURCE CODE HERE: http://matthewdowney20.blogspot.com/2011/09/source-code-for-roku-remote-hack.html
thanks in advance for reading and possibly answering this. So I have a slice of code that looks like this (the commands Down() Select() and Up() are all predefined):
def c1(row):
... | Python integer issues | EDIT: SOLVED--SOURCE CODE HERE: http://matthewdowney20.blogspot.com/2011/09/source-code-for-roku-remote-hack.html
thanks in advance for reading and possibly answering this. So I have a slice of code that looks like this (the commands Down() Select() and Up() are all predefined):
def c1(row):
row_down = row
row_up... | [
"Perhaps you meant \nwhile row_down > 1:\n\n(note 1 is written without quotes). If so, call c1 with c1(3) not c1('3').\n\nAlso, in CPython (version 2, but not version 3) integers are comparable to strings, but the answer is not what you might expect:\n3 > '1'\n# False\n\nWhen comparing any integer to any string, th... | [
4,
1,
0
] | [] | [] | [
"integer",
"python",
"string"
] | stackoverflow_0007375697_integer_python_string.txt |
Q:
AttributeError: 'module' object has no attribute 'QtString'
My development eviroment:
os: windows xp
python: python-3.1.2.msi
pyqt: PyQt-Py3.1-gpl-4.7.4-1.exe
code:
import sys
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication(sys.argv)
s = QtCore.QtString()
sys.exit(app.exec_())
It always... | AttributeError: 'module' object has no attribute 'QtString' | My development eviroment:
os: windows xp
python: python-3.1.2.msi
pyqt: PyQt-Py3.1-gpl-4.7.4-1.exe
code:
import sys
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication(sys.argv)
s = QtCore.QtString()
sys.exit(app.exec_())
It always show me
in 'module'
s = QtCore.QtString()
AttributeError: 'modu... | [
"The issue is explained here http://inputvalidation.blogspot.com/2010/10/python3-pyqt4-and-missing-qstring.html\nThe reason why you couldn't load QString is that it is missing from PyQt4 (maybe earlier, who knows). Since Py3k, as opposed to Py2k, supports Unicode by default, there's no need in this class.\nInstead ... | [
6,
2
] | [] | [] | [
"pyqt4",
"python",
"qt"
] | stackoverflow_0003510890_pyqt4_python_qt.txt |
Q:
Proper care and safety when dealing with traceback objects from sys.exc_info()
I'm aware that the sys.exc_info documentation says to take care when dealing with traceback objects, but am still uncertain of how safe or unsafe some cases are. Additionally, the documentation says "Warning: Don't do this!", followed ... | Proper care and safety when dealing with traceback objects from sys.exc_info() | I'm aware that the sys.exc_info documentation says to take care when dealing with traceback objects, but am still uncertain of how safe or unsafe some cases are. Additionally, the documentation says "Warning: Don't do this!", followed immediately by "Note: Actually, its ok", which further confuses me.
In any case, the... | [
"\nWhat, exactly, does \"local variable\" mean in this context? I'm struggling for terminology, but: does this mean only variables created in the function, or also variable created by the function parameters? What about other variables in scope, e.g, globals or self?\n\n\"Local variables\" are all name bindings cre... | [
4
] | [] | [] | [
"circular_reference",
"error_handling",
"exception",
"python"
] | stackoverflow_0007375492_circular_reference_error_handling_exception_python.txt |
Q:
How to set Secure Cookie on WSGI applications in python
How to set Secure Cookie on WSGI applications in python
With Secure Cookie I mean one that can be read on only https
A:
The Response.set_cookie function accepts an optional secure parameter. Example:
>>> res.set_cookie('key', 'value', max_age=360, path='/',... | How to set Secure Cookie on WSGI applications in python | How to set Secure Cookie on WSGI applications in python
With Secure Cookie I mean one that can be read on only https
| [
"The Response.set_cookie function accepts an optional secure parameter. Example:\n>>> res.set_cookie('key', 'value', max_age=360, path='/',\n... domain='example.org', secure=True)\n>>> res.headers['Set-Cookie']\n'key=value; Domain=example.org; Max-Age=360; Path=/; expires=... GMT; secure'\n\nYou can ... | [
6
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0007376932_django_google_app_engine_python.txt |
Q:
How to know the width and the height of image using app-engine image API wit python?
How to know the width and the height of image using app-engine image API wit python, someone adviesed me to use the composite function - pass your image in as the sole input image, and specify the canvas size as the desired size ... | How to know the width and the height of image using app-engine image API wit python? | How to know the width and the height of image using app-engine image API wit python, someone adviesed me to use the composite function - pass your image in as the sole input image, and specify the canvas size as the desired size of the output image.
but i didn't understand that!!
any simple example will be very helpfu... | [
"If i understand your question, you just need to use the attributes width and height from a reference of google.appengine.api.images.Image.\nAn example:\nflux = img.read() # From your request\n\nimage_ref = Image(image_data=flux)\nw = image_ref.width\nh = image_ref.height\n\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"image",
"python"
] | stackoverflow_0007375779_google_app_engine_image_python.txt |
Q:
Upgrading Python in Virtual Env
I have python 2.6.1 installed on Mac OS X. I wanted to play around with python 3.2, so i created a virtual enviromant using
virtualenv python3.0
and then activated it using
source python3.0/bin/activate
if I update the python in the virtualenv will it leave my system python untouc... | Upgrading Python in Virtual Env | I have python 2.6.1 installed on Mac OS X. I wanted to play around with python 3.2, so i created a virtual enviromant using
virtualenv python3.0
and then activated it using
source python3.0/bin/activate
if I update the python in the virtualenv will it leave my system python untouched? If yes, do I just install python... | [
"When you create through \nvirtualenv python3.0\n\nIt creates a symlink in the virtual env folder bin directory :\nlrwxr-xr-x 1 --- --- 6 Aug 23 13:28 python2.6 -> python\n\nSo you can not do just pip install to upgrade python. \nOn mac osx, you can have multiple versions of python installed. In your case , ... | [
4,
1
] | [] | [] | [
"macos",
"python",
"virtualenv"
] | stackoverflow_0003713097_macos_python_virtualenv.txt |
Q:
Low memory and fastest querying database for a Python project
I'm migrating a GAE/Java app to Python (non-GAE) due new pricing, so I'm getting a little server and I would like to find a database that fits the following requirements:
Low memory usage (or to be tuneable or predictible)
Fastest querying capability f... | Low memory and fastest querying database for a Python project | I'm migrating a GAE/Java app to Python (non-GAE) due new pricing, so I'm getting a little server and I would like to find a database that fits the following requirements:
Low memory usage (or to be tuneable or predictible)
Fastest querying capability for simple document/tree-like data identified by key (I don't care a... | [
"The path of least resistance for migrating an app engine application will probably be using AppScale, which implements a major portion of the app engine API. In particular, you might want to use the HyperTable data-store, which closely mirrors the Google App Engine datastore.\nEdit: ok, so you're going for a rede... | [
3,
1
] | [] | [] | [
"database",
"nosql",
"python",
"rdbms"
] | stackoverflow_0007375415_database_nosql_python_rdbms.txt |
Q:
Multiprocessing infinite loop on windows (Python)
I'm trying to make my first simulation using multiple processes, right now each simulation takes about an hour to complete. For that im using the multiprocessing import.
All the code works fine when i run simulation() inside a for loop. When the program is run all ... | Multiprocessing infinite loop on windows (Python) | I'm trying to make my first simulation using multiple processes, right now each simulation takes about an hour to complete. For that im using the multiprocessing import.
All the code works fine when i run simulation() inside a for loop. When the program is run all the workers in the pool start doing the same task, so i... | [
"Define calculate() outside of if __name__==\"__main__\" block. Child processes don't see it on Windows.\n"
] | [
1
] | [] | [] | [
"infinite_loop",
"multiprocessing",
"python",
"windows_7"
] | stackoverflow_0007374166_infinite_loop_multiprocessing_python_windows_7.txt |
Q:
Convert complex command into python subprocess
I have the following command:
$ ffmpeg -i http://url/1video.mp4 2>&1 | perl -lane 'print $1 if /(\d+x\d+)/'
640x360
I'm trying to set the output of this command into a python variable. Here is what I have so far:
>>> from subprocess import Popen, PIPE
>>> p1 = Popen(... | Convert complex command into python subprocess | I have the following command:
$ ffmpeg -i http://url/1video.mp4 2>&1 | perl -lane 'print $1 if /(\d+x\d+)/'
640x360
I'm trying to set the output of this command into a python variable. Here is what I have so far:
>>> from subprocess import Popen, PIPE
>>> p1 = Popen(['ffmpeg', '-i', 'http://url/1video.mp4', '2>&1'], s... | [
"In general, you can replace a shell pipeline with this pattern:\np1 = Popen([\"dmesg\"], stdout=PIPE)\np2 = Popen([\"grep\", \"hda\"], stdin=p1.stdout, stdout=PIPE)\np1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.\noutput = p2.communicate()[0]\n\nHowever, in this case, no pipeline is necessary:\nim... | [
3,
3,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0007374733_python_subprocess.txt |
Q:
What is the shortest way to get argument passed into program?
What is the shortest way to get argument passed into program. Shortest = at least count of characters. I need it because i do puzzles that requires arguments and it repeats in every puzzle. I use now import sys, but i'm not sure if it's shortest way.
im... | What is the shortest way to get argument passed into program? | What is the shortest way to get argument passed into program. Shortest = at least count of characters. I need it because i do puzzles that requires arguments and it repeats in every puzzle. I use now import sys, but i'm not sure if it's shortest way.
import sys
a = sys.argv[1]
| [
"We can sandpaper off a few bytes:\nimport sys\nv = sys.argv\n\nNow you'll save seven characters every time you use v[] instead of sys.argv[]\n",
"Using tuple unpacking can shave one character\na=sys.argv[1]\n_,a=sys.argv\n\nand many more if you have more arguments\n_,a,b,c,d,e,f=sys.argv\n\nusing __import__ may ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007377004_python.txt |
Q:
How to install pythonext extension in Firefox without creating FF application?
pythonext doc at http://code.google.com/p/pythonext/ says: "The Python extension is downloaded and installed into a Mozilla application as a regular extension"
I don't have a Mozilla application. Just trying to get my .py code to run i... | How to install pythonext extension in Firefox without creating FF application? | pythonext doc at http://code.google.com/p/pythonext/ says: "The Python extension is downloaded and installed into a Mozilla application as a regular extension"
I don't have a Mozilla application. Just trying to get my .py code to run in FF browser.
| [
"\nI downloaded pythonext-6.0.0.20110820-WINNT_x86-msvc.xpi for PythonExt 6 Windows with FF 6, but .xpi is not recognized by Windows 7, so not clear how to install it.\n\nGo to the addon mananger and click on the gear button.\nThen click Install addon from file.\n",
"Ehm... it's the first sentence under title: \"... | [
3,
1
] | [] | [] | [
"browser",
"python"
] | stackoverflow_0007377646_browser_python.txt |
Q:
two views in one url
Hello all I have two views in two app
and I want to get them in main url file
how I Can do that ?
first view in project/app_news/views.py
def article_index(request):
return render_to_response('news/index.html', {
'news_slide': Article.objects.filter(status=1, statusslide... | two views in one url | Hello all I have two views in two app
and I want to get them in main url file
how I Can do that ?
first view in project/app_news/views.py
def article_index(request):
return render_to_response('news/index.html', {
'news_slide': Article.objects.filter(status=1, statusslide=1)[:6],
'sect... | [] | [] | [
"urlpatterns = pattern('',\n url(r\"^$\", \"app_news.views.article_index\", name=\"index\"),\n url(r\"^questions/last/\", \"app_poll.views.questionlast\", name=\"question-last\"),\n)\n\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0007377610_django_python.txt |
Q:
Cannot use the sqlite3 parameter substitution with PRAGMA?
I'm trying to change the user_version of an SQLite database via Python 2.6, and I've tried to do the following:
cur.execute( "PRAGMA user_version = ?" , (version,) )
It fails with the following error:
cur.execute( "PRAGMA user_version = ?" , (version,... | Cannot use the sqlite3 parameter substitution with PRAGMA? | I'm trying to change the user_version of an SQLite database via Python 2.6, and I've tried to do the following:
cur.execute( "PRAGMA user_version = ?" , (version,) )
It fails with the following error:
cur.execute( "PRAGMA user_version = ?" , (version,) )
sqlite3.OperationalError: near "?": syntax error
I've tried... | [
"Only certain values can be parametrized. Even table and column names can not be parametrized. Your experiment shows pragma values also can not be parametrized.\nThe user_version is expected to be an integer.\nYou can use string formatting and protect yourself at the same time with\ncur.execute( \"PRAGMA user_versi... | [
6
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0007377988_python_sqlite.txt |
Q:
Python - Determine if ip is proxy or not
Is there any way how to find out, if ip address comming to the server is proxy in Python?
I tried to scan most common ports, but i don't want to ban all ips with open 80 port, because it don't have to be proxy.
Is there any way how to do it in Python? I would prefere it bef... | Python - Determine if ip is proxy or not | Is there any way how to find out, if ip address comming to the server is proxy in Python?
I tried to scan most common ports, but i don't want to ban all ips with open 80 port, because it don't have to be proxy.
Is there any way how to do it in Python? I would prefere it before using some external/paid services.
| [
"If it's a HTTP traffic, you can scan for headers like X-Forwarded-For. \nBut whatever you do it will always be only a heuristic.\n"
] | [
1
] | [] | [] | [
"proxy",
"python",
"sockets"
] | stackoverflow_0007371442_proxy_python_sockets.txt |
Q:
How to make a persistent com server in Python
I'd like to create a COM server that can hold it state across the calls. My goal is to have a thread-safe in-memory database. And provide an access to it via COM interface.
Is that possible?
A:
http://www.devshed.com/c/a/Python/Windows-Programming-in-Python-Creating-... | How to make a persistent com server in Python | I'd like to create a COM server that can hold it state across the calls. My goal is to have a thread-safe in-memory database. And provide an access to it via COM interface.
Is that possible?
| [
"http://www.devshed.com/c/a/Python/Windows-Programming-in-Python-Creating-COM-Servers/\n",
"Given the lack of popularity of COM I've ended up providing XMLRPC interface at least I know how to diagnose errors if they occur.\n"
] | [
1,
1
] | [] | [] | [
"com",
"python"
] | stackoverflow_0000831217_com_python.txt |
Q:
Excluding fields when dynamically creating a pseudo model in Django to initiate a Form
I've been reading up on Dynamic Models and have been trying to create one. I'm creating the model from scratch without the help of any helper functions. The docs point to a helper function called create_model which I can't seem ... | Excluding fields when dynamically creating a pseudo model in Django to initiate a Form | I've been reading up on Dynamic Models and have been trying to create one. I'm creating the model from scratch without the help of any helper functions. The docs point to a helper function called create_model which I can't seem to find in Django 1.3. Any ideas, why? Due to this missing helper function, I'm creating the... | [
"This did it:\n setattr(Person, 'first_name', 'John')\n\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007378122_django_django_models_python.txt |
Q:
how to run block of code inside python case statement
I'm new to python and I really like concept of using dictionaries instead of switch/case statements, but there is one problem I can't figure out
Let's say we have a 'pythonic case' statement
{
'a': somemethod,
'b': othermethod
}['a']()
This works fine,... | how to run block of code inside python case statement | I'm new to python and I really like concept of using dictionaries instead of switch/case statements, but there is one problem I can't figure out
Let's say we have a 'pythonic case' statement
{
'a': somemethod,
'b': othermethod
}['a']()
This works fine, but I can't figure out how to run some block of code like ... | [
"Dictionary values have to be objects of some kind. This means that you essentially must encapsulate the code you want to run within a function defined elsewhere. You could toy with exec -- you could create a dict of strings, and then exec a string from the dict, for example -- but I wouldn't recommend it. \nlambd... | [
3,
3,
2
] | [] | [] | [
"case",
"dictionary",
"lambda",
"python",
"switch_statement"
] | stackoverflow_0007378212_case_dictionary_lambda_python_switch_statement.txt |
Q:
How to programmatically(python) authenticate username/password using OS users
I'm writing a python program which allow user to login to it. I don't want to implement my own authentication but would rather take advantage of the OS(linux) mechanism. That is, when the user is trying to sign in my app by inputing user... | How to programmatically(python) authenticate username/password using OS users | I'm writing a python program which allow user to login to it. I don't want to implement my own authentication but would rather take advantage of the OS(linux) mechanism. That is, when the user is trying to sign in my app by inputing username/password pair(which should be a valid OS user), I need to authenticate the pai... | [
"Try using PAM via Python PAM or similar\n",
"That should be possible by having your script read the /etc/passwd and /etc/shadow files, which contain details about usernames and passwords on a Linux system. Do note that the script will have to have read access to the files, which depending on the situation may or... | [
5,
2
] | [] | [] | [
"authentication",
"linux",
"python"
] | stackoverflow_0007378427_authentication_linux_python.txt |
Q:
Howto customize DB(or Form) Validator in web2py?
Here are my 2 tables defintion:
db.define_table('question',
Field('category_id',db.category),
Field('content'),
Field('number_of_options','integer'),
Field('has_options_detail','boolean',default=False)) ## Has or not has detail for each option
db.de... | Howto customize DB(or Form) Validator in web2py? | Here are my 2 tables defintion:
db.define_table('question',
Field('category_id',db.category),
Field('content'),
Field('number_of_options','integer'),
Field('has_options_detail','boolean',default=False)) ## Has or not has detail for each option
db.define_table('options_detail', ## This table only for op... | [
"This should do it:\ndb.options_detail.question_id.requires = IS_IN_DB(\n db(db.question.has_options_detail==True), 'question.id')\n\nNote, the IS_IN_DB validator can take a DAL Set object as the first argument (see here), which enables you to filter the referenced table based on any criteria.\n(You could also s... | [
2
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0007376787_python_web2py.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.