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 do certain data processing in python?
I have two lists of strings, which have the following format:
[x1,x2,x3,x4,...] [y1,y2,y3,y4...]
Call it lst1.
lst2 would be:
[x1',x2',x3',x4',...] [y1,y2,y3,y4,...]
you can assume that each string in lst1 has matching y's in the corresponding element in lst2, and the... | how to do certain data processing in python? | I have two lists of strings, which have the following format:
[x1,x2,x3,x4,...] [y1,y2,y3,y4...]
Call it lst1.
lst2 would be:
[x1',x2',x3',x4',...] [y1,y2,y3,y4,...]
you can assume that each string in lst1 has matching y's in the corresponding element in lst2, and the same number of x's, but it would be great to thro... | [
"(sub(a,b) for (a,b) in itertools.izip(lst1, lst2))\n\nwhere sub() is whatever kind of 'substracting' you want to do between respective strings\n",
"Based on the comment above, that - is not actually a subtraction, but a dash in a string,\nFurthermore depending on how you want to deal with the result? As a list:\... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004046062_python.txt |
Q:
quick data processing with python?
I have a file in the following format:
[s1,s2,s3,s4,...] SOME_TEXT
(per line)
For example:
[dog,cat,monkey] 1,2,3
[a,b,c,d,e,f] 13,4,6
the brackets are included.
let's say I have another field like this, which contains two lines:
[banana,cat2,monkey2] 1,2,3
[a2,b2,c2,d,e,... | quick data processing with python? | I have a file in the following format:
[s1,s2,s3,s4,...] SOME_TEXT
(per line)
For example:
[dog,cat,monkey] 1,2,3
[a,b,c,d,e,f] 13,4,6
the brackets are included.
let's say I have another field like this, which contains two lines:
[banana,cat2,monkey2] 1,2,3
[a2,b2,c2,d,e,f] 13,4,6
I want to take two files of t... | [
"def read_file(fp,hash):\n for l in fp:\n p = l[1:].find(']')\n k = l[p+3:-1]\n v = l[1:p+1].split(\",\")\n if k not in hash:\n hash[k] = v\n else:\n hash[k] = zip(hash[k], v)\n\nhash = {}\n\nfor fname in ('f1.txt', 'f2.txt'):\n with open(fname) as fp:\... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004046641_python.txt |
Q:
one-many relationship-google datastore-python
I have two models like below:-
class Food(db.Model):
foodname=db.StringProperty()
cook=db.StringProperty()
class FoodReview(db.Model):
thereview=db.StringProperty()
reviews=db.ReferenceProperty(Food,collections_name='thefoodreviews')
I go ahea... | one-many relationship-google datastore-python | I have two models like below:-
class Food(db.Model):
foodname=db.StringProperty()
cook=db.StringProperty()
class FoodReview(db.Model):
thereview=db.StringProperty()
reviews=db.ReferenceProperty(Food,collections_name='thefoodreviews')
I go ahead and create an entity:-
s=Food(foodname='apple',co... | [
"If to get the food you're always doing db.Query(Food).filter('foodname =','apple') then it looks like your foodname is your key...\nWhy not just use it as a key_name?\nThen, you can even fetch the reviews without fetching the food itself:\nkey = db.Key.from_path('food', 'apple')\nreviews = FoodReview.all().filter(... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004045001_google_app_engine_python.txt |
Q:
Django-CMS 500 error when clicking to add a plugin
Hey guys, when clicking to add a new plugin ("Add Plugin" on a "Page" I get a 500 error. Using firebug I got this traceback:
Environment:
Request Method: POST
Request URL: http://192.168.1.10:81/admin/cms/page/1/add-plugin/
Django Version: 1.2.3
Python Version: 2... | Django-CMS 500 error when clicking to add a plugin | Hey guys, when clicking to add a new plugin ("Add Plugin" on a "Page" I get a 500 error. Using firebug I got this traceback:
Environment:
Request Method: POST
Request URL: http://192.168.1.10:81/admin/cms/page/1/add-plugin/
Django Version: 1.2.3
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'd... | [
"Solution:\nUpgrade from the latest pip version, to the latest version on github. \n"
] | [
0
] | [] | [] | [
"django",
"django_cms",
"python"
] | stackoverflow_0004041847_django_django_cms_python.txt |
Q:
How to get the number of active threads started by specific class?
code looks like below:
class workers1(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
# ...do some stuff
class workers2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
... | How to get the number of active threads started by specific class? | code looks like below:
class workers1(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
# ...do some stuff
class workers2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
# ...do some stuff
if __name__ == "__main__":
# start worker... | [
"This is a minor modification of Doug Hellman's multiprocessing ActivePool example code (to use threading). The idea is to have your workers register themselves in a pool, unregister themselves when they finish, using a threading.Lock to coordinate modification of the pool's active list:\nimport threading\nimport t... | [
21,
2
] | [] | [] | [
"count",
"multithreading",
"python"
] | stackoverflow_0004046986_count_multithreading_python.txt |
Q:
Good learner book for a 12 year old?
My 12 year old brother has recently expressed an interest in learning to program. I of course think this is a great idea, why not start him early? I'm wondering what you guys think with regards a book? I was thinking I should start him off on Java but I'm unsure what book would... | Good learner book for a 12 year old? | My 12 year old brother has recently expressed an interest in learning to program. I of course think this is a great idea, why not start him early? I'm wondering what you guys think with regards a book? I was thinking I should start him off on Java but I'm unsure what book would be best? Any suggestions with regards a b... | [
"Lego Mindstorms? http://mindstorms.lego.com\nNot a book but might be a more fun introduction to programming for a 12 year old.\n",
"Head First Java is a great book for any new Java programmer. It has lots of pictures, fun quips and puzzles to solve. Definitely worth the buy.\n",
"I found Python to be really ea... | [
12,
8,
5,
3,
2,
1,
0
] | [] | [] | [
"java",
"python"
] | stackoverflow_0003472634_java_python.txt |
Q:
Is there a better way to write this?
Is there a better way to do this? I feel like I am doing something wrong by being too repetitive.
O = viz.pick(1, viz.WORLD)
BackSetts = ["set_b1b", "set_b2a", "set_b1a", "set_b2b"]
LeftSetts = ["set_l1a", "set_l1b", "set_l2a", "set_l1b"]
NormSetts = ["set_nr_a", "set_nr_b"]
... | Is there a better way to write this? | Is there a better way to do this? I feel like I am doing something wrong by being too repetitive.
O = viz.pick(1, viz.WORLD)
BackSetts = ["set_b1b", "set_b2a", "set_b1a", "set_b2b"]
LeftSetts = ["set_l1a", "set_l1b", "set_l2a", "set_l1b"]
NormSetts = ["set_nr_a", "set_nr_b"]
Maps = ["MapA","MapB"]
if O.name in BackS... | [
"The trivial transformation is:\nO = viz.pick(1, viz.WORLD)\n\nBackSetts = [\"set_b1b\", \"set_b2a\", \"set_b1a\", \"set_b2b\"]\nLeftSetts = [\"set_l1a\", \"set_l1b\", \"set_l2a\", \"set_l1b\"]\nNormSetts = [\"set_nr_a\", \"set_nr_b\"]\nMaps = [\"MapA\",\"MapB\"]\nanyset = []\n\nif O.name in BackSetts:\n anyset... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004047679_python.txt |
Q:
Which exception to raise if a given string does not match some format?
This is a follow up to an older question.
Given a ISBN number, e.g. 3-528-03851-5 which exception type should I raise if the passed in string doesn't match the format X-XXX-XXXXX-X?
A:
Raise a ValueError.
It's pretty much the standard way of ... | Which exception to raise if a given string does not match some format? | This is a follow up to an older question.
Given a ISBN number, e.g. 3-528-03851-5 which exception type should I raise if the passed in string doesn't match the format X-XXX-XXXXX-X?
| [
"Raise a ValueError.\nIt's pretty much the standard way of saying \"you've given me a value that doesn't make sense\". For example:\n\n>>> int(\"a\")\nTraceback (most recent call last):\n File \"\", line 1, in \nValueError: invalid literal for int() with base 10: 'a'\n>>> import shlex; shlex.split(\"'\")\nTracebac... | [
6,
3,
2
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0004047752_exception_handling_python.txt |
Q:
Is there something wrong with this python code, why does it run so slow compared to ruby?
I was interested in comparing ruby speed vs python so I took the simplest recursive calculation, namely print the fibonacci sequance.
This is the python code
#!/usr/bin/python2.7
def fib(n):
if n ==... | Is there something wrong with this python code, why does it run so slow compared to ruby? | I was interested in comparing ruby speed vs python so I took the simplest recursive calculation, namely print the fibonacci sequance.
This is the python code
#!/usr/bin/python2.7
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1)+fib(... | [
"The recursion efficiency of python is the cause of this overhead. See this article for much more detail. The above solutions that solve this iteratively are better for python since they do not incur the function call overhead recursion does. My assumption about ruby would be that it is clearly optimizing the code ... | [
8,
2,
2,
2,
2
] | [] | [] | [
"fibonacci",
"performance",
"python",
"ruby"
] | stackoverflow_0004046514_fibonacci_performance_python_ruby.txt |
Q:
How to call a python script with command line args?
I have a script, client.py, that reads command line args straight as a script (not wrapped in a function like main()), like so:
opts, args = getopt.getopt(sys.argv[1:], "l:r:a:j:b:f:n:u:")
and prints a bunch of stuff.
I need to call this script from my code (on ... | How to call a python script with command line args? | I have a script, client.py, that reads command line args straight as a script (not wrapped in a function like main()), like so:
opts, args = getopt.getopt(sys.argv[1:], "l:r:a:j:b:f:n:u:")
and prints a bunch of stuff.
I need to call this script from my code (on Google App Engine, if that matters). It seems that callin... | [
"You shouldn't do this unless you have to: if you have two Python scripts they can communicate in Python instead of through a command line parser. Rewrite client.py with an if __name__ == \"__main__\" check and then call its main function directly from your script.\nIf you don't have the option of doing that (and y... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004047656_python.txt |
Q:
Does FastCGI or Apache2 limit upload sizes?
I'm having a problem with file uploading. I'm using FastCGI on Apache2 (unix) to run a WSGI-compliant application. File uploads, in the form of images, are begin saved in a MySQL database. However, larger images are being truncated at 65535 bytes. As far as I can tell, n... | Does FastCGI or Apache2 limit upload sizes? | I'm having a problem with file uploading. I'm using FastCGI on Apache2 (unix) to run a WSGI-compliant application. File uploads, in the form of images, are begin saved in a MySQL database. However, larger images are being truncated at 65535 bytes. As far as I can tell, nothing should be limiting the size of the files a... | [
"If the web server/gateway layer were truncating incoming form submissions I'd expect an error from FieldStorage, since the truncation would not just interrupt the file upload but also the whole multipart/form-data structure. Even if cgi.py tolerated this, it would be very unlikely to have truncated the multipart a... | [
2
] | [] | [] | [
"apache2",
"fastcgi",
"file_upload",
"mysql",
"python"
] | stackoverflow_0004047899_apache2_fastcgi_file_upload_mysql_python.txt |
Q:
What about this mess? Ideas to better rewrite it?
This mess is working well, but if somebody has any ideas to make it look/perform better, it would be greatly appreciated!
def OnButtonClick(b, e, f="none"):
if b == Gui["goleft"] and e == viz.UP: do_Cam([1.475, 7.862, 10.293])
if b == Gui["gocenter"] and ... | What about this mess? Ideas to better rewrite it? | This mess is working well, but if somebody has any ideas to make it look/perform better, it would be greatly appreciated!
def OnButtonClick(b, e, f="none"):
if b == Gui["goleft"] and e == viz.UP: do_Cam([1.475, 7.862, 10.293])
if b == Gui["gocenter"] and e == viz.UP: do_Cam([0, 1, 52])
if b == Gui["gorigh... | [
"I would follow Preet Sangha's advice with these additional improvements.\nReplace\nstr('%.2f'%(POS))\n\nwith\n'%.2f' % POS\n\nI think it is a bad practice to use list comprehension to produce side effects.\n[Griditema[i].alpha(POS) for i in Griditema]\n\nAssuming Griditema is a dict.\nfor item in Griditema.iterval... | [
3,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004047922_python.txt |
Q:
Differences in regex syntax in Python and Java
I have a following working regex in Python and I am trying to convert it to Java, I thought that regex works the same in both languages, but obviously it doesn't.
Python regex: ^\d+;\d+-\d+
My Java attempt: ^\\d+;\\d+-\\d+
Example strings that should be matched:
3;1-2... | Differences in regex syntax in Python and Java | I have a following working regex in Python and I am trying to convert it to Java, I thought that regex works the same in both languages, but obviously it doesn't.
Python regex: ^\d+;\d+-\d+
My Java attempt: ^\\d+;\\d+-\\d+
Example strings that should be matched:
3;1-2,2-3
68;12-15,1-16,66-1,1-2
What is the right solut... | [
"The regex is faulty for the input, don't know what you were doing in Python, but this isn't matching the whole strings in any regex I know. \nThis should do the trick (escaping characters are omitted):\n^\\d+;(\\d+-\\d+,?)+\n\nI.e. you need to continue matching the number pairs separated by commas.\n"
] | [
2
] | [] | [] | [
"java",
"python",
"regex"
] | stackoverflow_0004048088_java_python_regex.txt |
Q:
textarea to list
textarea returns this
[u'a\r\nb\r\nc\r\nd\r\ne']
what is the best way to turn that into a list
['a', 'b', 'c', 'd', 'e']
Thanks!
A:
>>> L = [u'a\r\nb\r\nc\r\nd\r\ne']
>>> L[0].split('\r\n')
[u'a', u'b', u'c', u'd', u'e']
| textarea to list | textarea returns this
[u'a\r\nb\r\nc\r\nd\r\ne']
what is the best way to turn that into a list
['a', 'b', 'c', 'd', 'e']
Thanks!
| [
">>> L = [u'a\\r\\nb\\r\\nc\\r\\nd\\r\\ne']\n>>> L[0].split('\\r\\n')\n[u'a', u'b', u'c', u'd', u'e']\n\n"
] | [
9
] | [] | [] | [
"python",
"textarea"
] | stackoverflow_0004048109_python_textarea.txt |
Q:
Checking if an ISBN number is correct
I'm given some ISBN numbers e.g. 3-528-03851 (not valid) , 3-528-16419-0 (valid). I'm supposed to write a program which tests if the ISBN number is valid.
Here' my code:
def check(isbn):
check_digit = int(isbn[-1])
match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1])
... | Checking if an ISBN number is correct | I'm given some ISBN numbers e.g. 3-528-03851 (not valid) , 3-528-16419-0 (valid). I'm supposed to write a program which tests if the ISBN number is valid.
Here' my code:
def check(isbn):
check_digit = int(isbn[-1])
match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1])
if match:
digits = match.group... | [
"First, try to avoid code like this:\nif Action():\n lots of code\n return True\nreturn False\n\nFlip it around, so the bulk of code isn't nested. This gives us:\ndef check(isbn):\n check_digit = int(isbn[-1])\n match = re.search(r'(\\d)-(\\d{3})-(\\d{5})', isbn[:-1])\n\n if not match:\n retu... | [
17,
4,
3,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004047511_python.txt |
Q:
How can I discover if a program is running from command line or from web?
I have a python script and I wanna know if the request
is from web or from command line. How can I do this?
A:
When run as a CGI, environment variables such as REQUEST_METHOD will be present. If not, then you're not running in a CGI enviro... | How can I discover if a program is running from command line or from web? | I have a python script and I wanna know if the request
is from web or from command line. How can I do this?
| [
"When run as a CGI, environment variables such as REQUEST_METHOD will be present. If not, then you're not running in a CGI environment.\nYou can check this like this:\nimport os\nif os.getenv(\"REQUEST_METHOD\"):\n print(\"running as CGI\")\nelse:\n print(\"not running as CGI\")\n\n"
] | [
9
] | [] | [] | [
"cgi",
"command_line",
"python"
] | stackoverflow_0004048275_cgi_command_line_python.txt |
Q:
Python - A Question on String Editing
I am trying to make a simple text-based game in Python. The idea of which revolves around a deck of playing cards, representing the card face values with A,2,3,4,5,6,7,8,9,10,J,Q, and K (Joker is not used). The suit of the cards will be represented by s,d,h, and c. As an examp... | Python - A Question on String Editing | I am trying to make a simple text-based game in Python. The idea of which revolves around a deck of playing cards, representing the card face values with A,2,3,4,5,6,7,8,9,10,J,Q, and K (Joker is not used). The suit of the cards will be represented by s,d,h, and c. As an example, "Ace of Hearts" would be represented as... | [
"Change it before you concatenate.\nfirstvar = random.choice('A23456789XJQK') \nsecondvar = random.choice('sdhc') \nnewvar = (firstvar + secondvar) if firstvar != 'X' else ('10' + secondvar)\n\nAlternatively, don't use 'X' to begin with:\nfirstvar = random.choice(['A', '2', '3', ..., '10', ...])\n\nAnother alternat... | [
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004048447_python_string.txt |
Q:
parsing options in a config module
I use config module to store variables global to all modules. Is it a good place to parse the script arguments? (Note: config module is my own module, it just contains a bunch of global variables.)
----- config.py -----
from optparse import OptionParser
parser = OptionParser()
p... | parsing options in a config module | I use config module to store variables global to all modules. Is it a good place to parse the script arguments? (Note: config module is my own module, it just contains a bunch of global variables.)
----- config.py -----
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--test", action ... | [
"What are you trying to do? There are 2 ways you can try - \n\nPass argument values to your program from command-line (using optparse).\nor write a config.py import it in your program & proceed.\n\nWhy would you want to do both (& that too in your config file)?\nI see that you have written your config module as .py... | [
0
] | [] | [] | [
"command_line",
"python",
"python_3.x"
] | stackoverflow_0004048495_command_line_python_python_3.x.txt |
Q:
Lock-free implementation of a Thread Library
I have been going through a few published papers which details algorithms and data structures which can be used for implementation of a thread library. I searched online to view any existing implementation of the same, and I could only find LFThreads(only its documentat... | Lock-free implementation of a Thread Library | I have been going through a few published papers which details algorithms and data structures which can be used for implementation of a thread library. I searched online to view any existing implementation of the same, and I could only find LFThreads(only its documentation, not its source code).
Have any of you worked ... | [
"Have you looked at Intel Threading Building Blocks? It's C++, which is not in your tags, but I thought you might be interested since it's open source.\n"
] | [
1
] | [] | [] | [
"c",
"concurrency",
"java",
"lock_free",
"python"
] | stackoverflow_0004029237_c_concurrency_java_lock_free_python.txt |
Q:
plotting a parabola within part of a repeating signal using numpy
I have a repeating signal that varies a little bit with each cycle of a process that repeats roughly every second, though the duration and the contents of each cycle vary from each other a little bit within some parameters. There are a thousand x,y... | plotting a parabola within part of a repeating signal using numpy | I have a repeating signal that varies a little bit with each cycle of a process that repeats roughly every second, though the duration and the contents of each cycle vary from each other a little bit within some parameters. There are a thousand x,y coordinates for every second of my signal data. A small, but importan... | [
"So, as I understand it, you have 3 points that you want to fit a parabola to.\nNormally, it's simplest to just use numpy.polyfit, but if you're really worried about speed, and you're fitting exactly three points, there's no point in using a least-squares fit.\nInstead, we have an even-determined system (fitting a ... | [
8
] | [] | [] | [
"numpy",
"python",
"scientific_computing",
"scipy",
"signal_processing"
] | stackoverflow_0004047804_numpy_python_scientific_computing_scipy_signal_processing.txt |
Q:
How is the second argument of the eval function different from the third argument?
class all_items(dict):
def __getitem__(self, key):
return 1
>>> eval("undefined",dict(),all_items())
1
>>> eval("undefined",all_items(),dict())
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>... | How is the second argument of the eval function different from the third argument? | class all_items(dict):
def __getitem__(self, key):
return 1
>>> eval("undefined",dict(),all_items())
1
>>> eval("undefined",all_items(),dict())
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
eval("undefined",all_items(),dict())
File "<string>", line 1, in <module>
NameErr... | [
"The second argument must be a dictionary. Implementing the mapping protocol isn't enough.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004048830_python.txt |
Q:
Cleaning and stripping of strings/HTML - Python
I have a set of questions, of which I do not have an answer to.
1) Stripping lists of string
input:
'item1, item2, \t\t\t item3, \n\n\n \t, item4, , , item5, '
output:
['item1', 'item2', 'item3', 'item4', 'item5']
Anything more efficient than doing the following?... | Cleaning and stripping of strings/HTML - Python | I have a set of questions, of which I do not have an answer to.
1) Stripping lists of string
input:
'item1, item2, \t\t\t item3, \n\n\n \t, item4, , , item5, '
output:
['item1', 'item2', 'item3', 'item4', 'item5']
Anything more efficient than doing the following?
[x.strip() for x in l.split(',') if x.strip()]
2) C... | [
"For the first one you can use split then a list comprehension to trim the extra whitespace:\nresult = [x.strip() for x in i.split(',')]\n\nAnd to remove the empty strings from the list:\nresult = [x for x in result if x]\n\n",
"To clean HTML use lxml.html\nimport lxml.html\ntext = lxml.html.fromstring(\"...\")\n... | [
2,
2,
1,
1,
1,
1
] | [] | [] | [
"html",
"python",
"sanitization",
"string",
"unicode"
] | stackoverflow_0004047344_html_python_sanitization_string_unicode.txt |
Q:
Java: updated class files not used
I'm developing a Java program through Eclipse locally, and debugging on a remote machine. Whenever I make a change to my program, I copy the corresponding class file to the bin directory on the remote machine. I run my program (a simulator) through a python script via the OS.sys... | Java: updated class files not used | I'm developing a Java program through Eclipse locally, and debugging on a remote machine. Whenever I make a change to my program, I copy the corresponding class file to the bin directory on the remote machine. I run my program (a simulator) through a python script via the OS.system command.
The problem is that my prog... | [
"I would bet dollars for donuts that under some conditions you are not restarting the JVM between tests.\nThe other obvious thought is that the class is not being copied to the target system as expected, or not to the correct location. Or, of course, the program is not being run from where you expect (i.e. there i... | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0004048821_java_python.txt |
Q:
Sharing queues between processes using nested classes (Python)
I have a question about sharing queues between processes in Python. Below, I have three queues, one main process, and three inner processes. Each inner process will be adding and getting values from the various queues (they need easy access to the qu... | Sharing queues between processes using nested classes (Python) | I have a question about sharing queues between processes in Python. Below, I have three queues, one main process, and three inner processes. Each inner process will be adding and getting values from the various queues (they need easy access to the queues).
I think it works as it is right now, but this code is the fou... | [
"I recommend you to use the threading module instead of process. I suggest you to use nested classes only if the child classes are extending on functionality the parent class.\nclass WorkerThread(threading.Thread):\n\nAnother recommendation is to use a shared lock between your child threads in order to prevent ra... | [
1,
0
] | [] | [] | [
"inner_classes",
"process",
"python"
] | stackoverflow_0004048789_inner_classes_process_python.txt |
Q:
Python: unit testing socket-based code?
I'm writing a Python client+server that uses gevent.socket for communication. Are there any good ways of testing the socket-level operation of the code (for example, verifying that SSL connections with an invalid certificate will be rejected)? Or is it simplest to just spawn... | Python: unit testing socket-based code? | I'm writing a Python client+server that uses gevent.socket for communication. Are there any good ways of testing the socket-level operation of the code (for example, verifying that SSL connections with an invalid certificate will be rejected)? Or is it simplest to just spawn a real server?
Edit: I don't believe that "n... | [
"You can easily start a server and then access it in a test case. The gevent's own test suite does exactly that for testing gevent's built-in servers.\nFor example:\nclass SimpleServer(gevent.server.StreamServer):\n\n def handle(self, socket, address):\n socket.sendall('hello and goodbye!')\n\nclass Test(... | [
19,
9,
8
] | [] | [] | [
"gevent",
"python",
"sockets",
"testing"
] | stackoverflow_0004047897_gevent_python_sockets_testing.txt |
Q:
How do I get around not being able to parse a table name into a python sqlite query?
I have a python3 program that I'm making which uses a sqlite database with several tables, I want to create a selector module to allow me to chose which table to pull data from.
I have found out that I can't use parameter substitu... | How do I get around not being able to parse a table name into a python sqlite query? | I have a python3 program that I'm making which uses a sqlite database with several tables, I want to create a selector module to allow me to chose which table to pull data from.
I have found out that I can't use parameter substitution for a table name as shown bellow, so I'm looking for some alternative methods to acco... | [
"Right. You can not use parameter substitution to specify the table.\nSo instead you must do string manipulation:\nc.execute(\"SELECT * FROM {t} \".format(t=tablename))\n\n",
"I don't know if this is a python3 thing but it seems easiest to just do this:\nc.execute(\"SELECT * FROM %s \"% tablename)\n\n",
"\nBloc... | [
1,
1,
0
] | [] | [] | [
"parsing",
"python",
"sqlite"
] | stackoverflow_0004044512_parsing_python_sqlite.txt |
Q:
Is it safe to use SQLalchemy with gevent?
I know that some database drivers and other libraries providing connection to external services are incompatible with coroutine-based network libraries. However, I couldn't find out if SQLAlchemy can be safely used with such libraries (namely, gevent), and if any workaroun... | Is it safe to use SQLalchemy with gevent? | I know that some database drivers and other libraries providing connection to external services are incompatible with coroutine-based network libraries. However, I couldn't find out if SQLAlchemy can be safely used with such libraries (namely, gevent), and if any workarounds should be applied to exclude possible errors... | [
"Did you try searching gevent google group for SQLAlchemy?\nI found this report of using SQLAlchemy + mysql-connector successfully and this of using SQLAlchemy + psycopg2 successfully (make sure you've read this)\nI would think SQLAlchemy should be safe to use with gevent as long as the database driver that SQLAlch... | [
23
] | [] | [] | [
"gevent",
"python",
"sqlalchemy",
"thread_safety"
] | stackoverflow_0004033475_gevent_python_sqlalchemy_thread_safety.txt |
Q:
Analyse source code in Java using Python?
i would like to create a source code analyser for Java Project (like FindBugs and other static analysis programs) that would be able to detect certain method calls.
I would prefer to do it using Python, but any advice would be great !
I'm going to start by studying the Fi... | Analyse source code in Java using Python? | i would like to create a source code analyser for Java Project (like FindBugs and other static analysis programs) that would be able to detect certain method calls.
I would prefer to do it using Python, but any advice would be great !
I'm going to start by studying the FindBugs source code, but if anyone could explain... | [
"Read the book : Language implementation Patterns. It is a very accessible book out there and you can gauge the effort that will be required to achieve what you want to achieve\n\nhttp://www.pragprog.com/titles/tpdsl/language-implementation-patterns\n\n"
] | [
2
] | [] | [] | [
"java",
"python",
"static_analysis"
] | stackoverflow_0004049321_java_python_static_analysis.txt |
Q:
How to return local vars([object]) from function?
I use vars() function for the first time, and noticed this behaviour:
nodes = ['one', 'two', 'three']
for node in nodes:
vars()[node + '_'] = 'some calc ' + node
vars()[node] = vars()[node + '_']
print one
With this snippet Python outputs some calc one a... | How to return local vars([object]) from function? | I use vars() function for the first time, and noticed this behaviour:
nodes = ['one', 'two', 'three']
for node in nodes:
vars()[node + '_'] = 'some calc ' + node
vars()[node] = vars()[node + '_']
print one
With this snippet Python outputs some calc one as expected, but if I use it inside function like this:
... | [
"The reason that it works when called in a modules 'global' scope, is that it is equivalent to globals() in that context which is actually a dictionary stored by python. The locals of non-global scopes are not actually a dictionary in the implementation, (this is to avoid having to lookup dictionary keys when acce... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004049491_python.txt |
Q:
limit_choice_to all objects of a particular model classe in a ForeignKey
Example
class Base():
pass
class A(Base)
parent=models.Foreignkey("self", limit_choices_to=(all members of the B class)
class B(Base)
parent=models.Foreignkey("self", limit_choices_to=(all members of the A class)
What would be the que... | limit_choice_to all objects of a particular model classe in a ForeignKey | Example
class Base():
pass
class A(Base)
parent=models.Foreignkey("self", limit_choices_to=(all members of the B class)
class B(Base)
parent=models.Foreignkey("self", limit_choices_to=(all members of the A class)
What would be the query syntax for limit_choices_to, to get only the
objects of a certain class?)
| [
"Wouldn't this work instead ?\nclass Base(Model):\n parent=models.Foreignkey(\"self\")\n\n class Meta:\n abstract = True\n\n\nclass A(Base):\n parent=models.Foreignkey(\"B\")\n\nclass B(Base):\n parent=models.Foreignkey(\"A\")\n\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004047900_django_django_models_python.txt |
Q:
how do I advance to the next item in a nested list? Python
Working with a couple of lists, iterating over each. Here's a code segment:
self.links = []
self.iter=iter(self.links)
for tgt in self.links:
for link in self.mal_list:
print(link)
if tgt == link:
print("Found Suspicious Link... | how do I advance to the next item in a nested list? Python | Working with a couple of lists, iterating over each. Here's a code segment:
self.links = []
self.iter=iter(self.links)
for tgt in self.links:
for link in self.mal_list:
print(link)
if tgt == link:
print("Found Suspicious Link: {0}".format(tgt))
self.count += 1
else:
... | [
"Not sure, what you are trying to ask but you could simplify your code. Though this is not necessary.\nself.links = []\nself.non_malware_link = [link for link in self.links if link not in self.mal_list]\nresults = map(self.crawl, self.non_malware_link)\n\nOn some issues with your code:\n\nself.count is exactly the ... | [
2,
1,
1
] | [] | [] | [
"iteration",
"list",
"python"
] | stackoverflow_0004049706_iteration_list_python.txt |
Q:
Pylons: Sharing SQLAlchemy MySQL connection with external library
I am running Pylons using SQLAlchemy to connect to MySQL, so when I want to use a database connection in a controller, I can do this:
from myapp.model.meta import Session
class SomeController(BaseController):
def index(self):
conn = Ses... | Pylons: Sharing SQLAlchemy MySQL connection with external library | I am running Pylons using SQLAlchemy to connect to MySQL, so when I want to use a database connection in a controller, I can do this:
from myapp.model.meta import Session
class SomeController(BaseController):
def index(self):
conn = Session.connection()
rows = conn.execute('SELECT whatever')
...
S... | [
"You should not manage connections yourself - it's all done by SQLAlchemy. Just use scoped session object everywhere, and you will be fine.\ndef init_model(engine):\n sm = orm.sessionmaker(autoflush=False, autocommit=False, expire_on_commit=False, bind=engine)\n meta.engine = engine\n meta.Session = orm.sc... | [
2,
1
] | [] | [] | [
"mysql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0004047735_mysql_pylons_python_sqlalchemy.txt |
Q:
How do I see the arguments (and types) of a python method?
$ py twitterDump2.py
Traceback (most recent call last):
File "twitterDump2.py", line 30, in <module>
stream=tweepy.Stream(username,password,listener)
TypeError: __init__() takes exactly 3 arguments (4 given)
My code:
username="abc"
password="abc"
l... | How do I see the arguments (and types) of a python method? | $ py twitterDump2.py
Traceback (most recent call last):
File "twitterDump2.py", line 30, in <module>
stream=tweepy.Stream(username,password,listener)
TypeError: __init__() takes exactly 3 arguments (4 given)
My code:
username="abc"
password="abc"
listener = StreamWatcherListener()
stream=tweepy.Stream(username,... | [
"The first argument to __init__ is usually self so it is expecting you to pass only two arguments.\nSurprising the tweepy.streaming.py code suggests:\nclass Stream(object):\n\n host = 'stream.twitter.com'\n\n def __init__(self, auth, listener, **options):\n self.auth = auth\n self.listener = lis... | [
2,
2
] | [] | [] | [
"class",
"function",
"methods",
"python",
"twitter"
] | stackoverflow_0004050108_class_function_methods_python_twitter.txt |
Q:
Homemade tiny memcache
I'm moving a Google App Engine web application outside "the cloud" to a standard web framework (webpy) and I would like to know how to implement a memcache feature available on Gae.
In my app I just use this cache to store a bunch of data retrieved from a remote api every X hours; in other w... | Homemade tiny memcache | I'm moving a Google App Engine web application outside "the cloud" to a standard web framework (webpy) and I would like to know how to implement a memcache feature available on Gae.
In my app I just use this cache to store a bunch of data retrieved from a remote api every X hours; in other words I don't stress this cac... | [
"It seems to me that your cache can grow inefficiently since it will keep entries that are rarely used. Because, it seems that the entries in your cache don't get removed unless a get operation is requested for an specific key.\nIf you want to improve your cache I'd add the following two simple features:\n\nWhen an... | [
2,
0
] | [] | [] | [
"memcached",
"python"
] | stackoverflow_0004004362_memcached_python.txt |
Q:
Impossible to create a configuration file for an python application inside Google App Engine
I try to create a configuration file, where I can store constants.
Whenever I try with ConfigParser, I get an error
Traceback (most recent call last):
File "/home/baun/google_appengine/google/appengine/ext/webapp ... | Impossible to create a configuration file for an python application inside Google App Engine | I try to create a configuration file, where I can store constants.
Whenever I try with ConfigParser, I get an error
Traceback (most recent call last):
File "/home/baun/google_appengine/google/appengine/ext/webapp /__init__.py", line 511, in __call__
handler.get(*groups)
File "/home/baun/workspace/octopu... | [
"[bucket]\nbucketname= octopus_storage\n\n"
] | [
2
] | [] | [] | [
"configparser",
"configuration",
"configuration_files",
"google_app_engine",
"python"
] | stackoverflow_0004050405_configparser_configuration_configuration_files_google_app_engine_python.txt |
Q:
Python/Tkinter: Using custom mouse cursors under Windows?
Python 2.7/Windows: My understanding is that we can load custom mouse cursors using the cursor='@file.cur' syntax:
widget = tkinter.Label( ..., cursor='@help.cur' )
Here's the traceback I receive:
Traceback (most recent call last):
File "<pyshell#82>", l... | Python/Tkinter: Using custom mouse cursors under Windows? | Python 2.7/Windows: My understanding is that we can load custom mouse cursors using the cursor='@file.cur' syntax:
widget = tkinter.Label( ..., cursor='@help.cur' )
Here's the traceback I receive:
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>
widget.config( cursor='@help.cur' )
Fi... | [
"lbl=Label(root, text=\"toto\", cursor=\"@toto.cur\") works for me on Python 2.6 and Vista. Make sure that the cur file is in the working directory of your script (I have a similar traceback if I try to load a non-existing cursor) and that the file is not corrupted.\nAs an alternative, here is a list of internal cu... | [
5
] | [] | [] | [
"icons",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004049612_icons_python_tkinter_user_interface.txt |
Q:
Broken anydbm.py on ubuntu 10.04 with python 2.6.5?
When trying to run django-celery with beat scheduler:
bin/django celeryd -B --settings=app.development --loglevel=INFO
I got this exception:
Process Beat:
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/multiprocessing/process.py"... | Broken anydbm.py on ubuntu 10.04 with python 2.6.5? | When trying to run django-celery with beat scheduler:
bin/django celeryd -B --settings=app.development --loglevel=INFO
I got this exception:
Process Beat:
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/multiprocessing/process.py", line 237, in _bootstrap
self.run()
File "/home/user/egg... | [
"If /usr/lib/python2.6/anydbm.py is an empty file for you, then yes, your installation is broken. /usr/lib/python2.6/anydbm.py is the correct file, with contents, on my Ubuntu 10.04 system, with python2.6_2.6.5-1ubuntu6 installed. You'll want to make sure you have the latest package installed, and possibly reinstal... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004050519_python.txt |
Q:
Retrieving hierarchial data from datastore
I am building an app with Google App Engine (and Python). I have two questions about retrieving data from datastore.
I have information about users and information about posts made by users. Here is part of DB Models:
class User(db.Model):
country = db.StringProperty(... | Retrieving hierarchial data from datastore | I am building an app with Google App Engine (and Python). I have two questions about retrieving data from datastore.
I have information about users and information about posts made by users. Here is part of DB Models:
class User(db.Model):
country = db.StringProperty()
# many other entities
class Post(db.Mode... | [
"If you want to do this, you need to denormalize: store a copy of the user's country on all their posts, and query on that. The datastore doesn't support joins, which would be required to satisfy this query, and in any case denormalizing is a lot more efficient.\nAs far as retrieving 'all' results goes, you can spe... | [
3,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004041967_google_app_engine_google_cloud_datastore_python.txt |
Q:
BDD in Google App Engine (Python)
I have seen some mention of some form of TDD for Python with Google App Engine, however I've not really seen a discussion of a BDD approach. Is someone familiar with how to string this together properly with GAE? I'm hopeful that things may be in a better position for this now t... | BDD in Google App Engine (Python) | I have seen some mention of some form of TDD for Python with Google App Engine, however I've not really seen a discussion of a BDD approach. Is someone familiar with how to string this together properly with GAE? I'm hopeful that things may be in a better position for this now than they were from notes and articles I... | [
"I did a little bit of development with GAE and the app engine.\nBDD really is a development approach rather than a framework, so you can use any existing test tools. If you're happy switching to Ruby for your scenarios you can always use Cucumber with the Ruby-based web tool of your choice; otherwise you can use y... | [
2
] | [] | [] | [
"bdd",
"google_app_engine",
"python",
"tdd"
] | stackoverflow_0003895239_bdd_google_app_engine_python_tdd.txt |
Q:
How do you generate a random double between these points?
37.807614 to 37.786996
The randomly generated double must have the same precision (num of digits) as those above.
For example, 37.792242 would be good, whereas 37.7823423425 would be bad.
A:
round(random.uniform(num1, num2), 6)
You will occasionally ge... | How do you generate a random double between these points? | 37.807614 to 37.786996
The randomly generated double must have the same precision (num of digits) as those above.
For example, 37.792242 would be good, whereas 37.7823423425 would be bad.
| [
"round(random.uniform(num1, num2), 6)\n\nYou will occasionally get numbers that end with ...0001 or ...9999 or so due to IEEE 754 inaccuracies though.\n",
"Not sure if I'm missing something, but to avoid rounding, and since you want exactly that precision, isn't it easiest to work in integers and then convert to ... | [
5,
0
] | [] | [] | [
"double",
"int",
"python",
"types"
] | stackoverflow_0004050580_double_int_python_types.txt |
Q:
Script to convert Huge Three column table into table
I have a set of data (CSV files) in the following 3 column format:
A, B, C
3277,4733,54.1
3278,4741,51.0
3278,4750,28.4
3278,4768,36.0
3278,4776,50.1
3278,4784,51.4
3279,4792,82.6
3279,4806,78.2
3279,4814,36.4
And I need to get a three-way contingency ... | Script to convert Huge Three column table into table | I have a set of data (CSV files) in the following 3 column format:
A, B, C
3277,4733,54.1
3278,4741,51.0
3278,4750,28.4
3278,4768,36.0
3278,4776,50.1
3278,4784,51.4
3279,4792,82.6
3279,4806,78.2
3279,4814,36.4
And I need to get a three-way contingency table like: (sorry, this doesn't look completely good)
A /... | [
"When all you have is a hammer . . . . .\nConceptually, what you are trying to do is simple but because of the size of your data, it is computationally difficult. I tend to use R for it's analytic and graphics capacity, not it's data wrangling skills. When I need to move around a bunch of data, I usually just stick... | [
1,
1,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"import_from_csv",
"python",
"r",
"scripting"
] | stackoverflow_0004044353_algorithm_import_from_csv_python_r_scripting.txt |
Q:
Getting list of parameter names inside python function
Possible Duplicate:
Getting method parameter names in python
Is there an easy way to be inside a python function and get a list of the parameter names?
For example:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
Thanks
A... | Getting list of parameter names inside python function |
Possible Duplicate:
Getting method parameter names in python
Is there an easy way to be inside a python function and get a list of the parameter names?
For example:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
Thanks
| [
"Well we don't actually need inspect here.\n>>> func = lambda x, y: (x, y)\n>>> \n>>> func.__code__.co_argcount\n2\n>>> func.__code__.co_varnames\n('x', 'y')\n>>>\n>>> def func2(x,y=3):\n... print(func2.__code__.co_varnames)\n... pass # Other things\n... \n>>> func2(3,3)\n('x', 'y')\n>>> \n>>> func2.__defaults__\... | [
465,
278,
187,
145
] | [] | [] | [
"parameters",
"python"
] | stackoverflow_0000582056_parameters_python.txt |
Q:
Django Apps extendability - How to make your django apps easily extendable?
What are your best practises for making your django application easily extendable for other developers?
What are your approaches for enabling other to overwrite your
views
forms
templates
models
classes
In a way that enables a healthy en... | Django Apps extendability - How to make your django apps easily extendable? | What are your best practises for making your django application easily extendable for other developers?
What are your approaches for enabling other to overwrite your
views
forms
templates
models
classes
In a way that enables a healthy environment for extensions to work well together?
| [
"\nuse signals and dispatchers \n\nin your app create files..\n -litseners.py\n -signals.py\nand then implement signals for your models and forms (views not so much)\n\nuse the django plugins pattern\nducktyping for your classes \n\n",
"Basically, what he says. But class based views in Django ... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004051010_django_python.txt |
Q:
print lists in a file in a special format in python
I have a large list of lists like:
X = [['a','b','c','d','e','f'],['c','f','r'],['r','h','l','m'],['v'],['g','j']]
each inner list is a sentence and the members of these lists are actually the word of this sentences.I want to write this list in a file such that ... | print lists in a file in a special format in python | I have a large list of lists like:
X = [['a','b','c','d','e','f'],['c','f','r'],['r','h','l','m'],['v'],['g','j']]
each inner list is a sentence and the members of these lists are actually the word of this sentences.I want to write this list in a file such that each sentence(inner list) is in a separate line in the fi... | [
"with open('somefile.txt', 'w') as fp:\n for i, s in enumerate(X):\n print >>fp, '%d. %s' % (i + 1, ' '.join(s))\n\n",
"with open('file.txt', 'w') as f:\n i=1\n for row in X:\n f.write('%d. %s'%(i, ' '.join(row)))\n i+=1\n\n"
] | [
5,
0
] | [] | [] | [
"file",
"list",
"nested_lists",
"python"
] | stackoverflow_0004051284_file_list_nested_lists_python.txt |
Q:
How do I set max_allowed_packet or equivalent for MySQLdb in python?
It seems as if MySQLdb is restricting the maximum transfer size for SQL statements. I have set the max_allowed_packet to 128M for mysqld. MySQL documentation says that this needs to be done for the client as well.
A:
You need to put max_allowed... | How do I set max_allowed_packet or equivalent for MySQLdb in python? | It seems as if MySQLdb is restricting the maximum transfer size for SQL statements. I have set the max_allowed_packet to 128M for mysqld. MySQL documentation says that this needs to be done for the client as well.
| [
"You need to put max_allowed_packet into the [client] section of my.cnf on the machine where the client runs. If you want to, you can specify a different file or group in mysqldb.connect.\n"
] | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004050257_mysql_python.txt |
Q:
help.....serial port programming
I want to communicate with my serial port in python. I installed pyserial, and uspp for linux. Still, when I run the following code:
import serial
ser = serial.Serial('/dev/pts/1', 19200, timeout=1)
print ser.portstr #check which port was really used
ser.write("hello") #write ... | help.....serial port programming | I want to communicate with my serial port in python. I installed pyserial, and uspp for linux. Still, when I run the following code:
import serial
ser = serial.Serial('/dev/pts/1', 19200, timeout=1)
print ser.portstr #check which port was really used
ser.write("hello") #write a string
ser.close() #
it gives the ... | [
"/dev/tyUSB1 looks like a typo. Device nodes are normally called /dev/ttyXXX\n",
"If you want to open your second USB serial port, you want /dev/ttyUSB1 instead of /dev/tyUSB1.\n"
] | [
7,
2
] | [] | [] | [
"linux",
"python",
"serial_port"
] | stackoverflow_0004051869_linux_python_serial_port.txt |
Q:
Split Python list into several lists based on index
So I've got a string of bytes which represents cubes in three dimensions. The coordinates are ordered like this:
[x0y0z0, x0y1z0, x0y2z0, ..., x0y127z0, x0y0z1, x0y1z1, ..., x15y127z15]
I'd like to split this into 128 lists, one for each Y coordinate. This code ... | Split Python list into several lists based on index | So I've got a string of bytes which represents cubes in three dimensions. The coordinates are ordered like this:
[x0y0z0, x0y1z0, x0y2z0, ..., x0y127z0, x0y0z1, x0y1z1, ..., x15y127z15]
I'd like to split this into 128 lists, one for each Y coordinate. This code already does that, but I think inefficiently. Is there so... | [
"# l = [x0y0z0, ...]\ndef bucketsofun(l, sp=16):\n r = [[] for x in range(sp)]\n for b, e in itertools.izip(itertools.cycle(r), l):\n b.append(e)\n return r\n\n",
"Something like this might be worth trying\nL = file[\"Level\"][\"Blocks\"].value\ncol += [L[i::128] for i in range(127)]\n\n",
"Itertools can ... | [
3,
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004051042_list_python.txt |
Q:
Django creating object from POST
I have a question regarding Djanog views
here is a sample code
def example register ( request ) :
if request.method == ’POST ’ :
username = request.POST.get ( ’ username ’ )
password = request.POST.get ( ’ password ’ )
email = request.POST.get (’email’)
user = User.objects .creat... | Django creating object from POST | I have a question regarding Djanog views
here is a sample code
def example register ( request ) :
if request.method == ’POST ’ :
username = request.POST.get ( ’ username ’ )
password = request.POST.get ( ’ password ’ )
email = request.POST.get (’email’)
user = User.objects .create_user ( username
, email
, password )... | [
"you should be using forms[1] and model-forms [2] to collect such data from the request.\n[1] http://docs.djangoproject.com/en/dev/topics/forms/\n[2] http://docs.djangoproject.com/en/dev/topics/forms/modelforms/\n",
"Why would you ever do it like that anyway? \nfrom django.contrib.auth.forms import UserCreationFo... | [
5,
0
] | [] | [] | [
"django",
"http",
"python"
] | stackoverflow_0004051873_django_http_python.txt |
Q:
Django / MySql not honouring unique_together
I am using django with mysql (InnoDB) and have the following in my django model:
class RowLock(models.Model):
table_name = models.CharField(blank = False, max_length = 30)
locked_row_id = models.IntegerField(null = False)
process_id = models.IntegerField(nul... | Django / MySql not honouring unique_together | I am using django with mysql (InnoDB) and have the following in my django model:
class RowLock(models.Model):
table_name = models.CharField(blank = False, max_length = 30)
locked_row_id = models.IntegerField(null = False)
process_id = models.IntegerField(null = True)
thread_id = models.IntegerField(null... | [
"For completeness , my last update should have probably been added as an answer.\nI fixed the problem by manually editing the forward method of the south migration and added the line:\ndb.create_index('row_locks', ['table_name','locked_row_id'], unique=True)\n\nRob\n"
] | [
6
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003916306_django_mysql_python.txt |
Q:
UnboundLocalError: local variable ... referenced before assignment
I get an UnboundLocalError because I use a template value inside an if statement which is not executed. What is the standard way to handle this situation?
class Test(webapp.RequestHandler):
def get(self):
user = users.get_current... | UnboundLocalError: local variable ... referenced before assignment | I get an UnboundLocalError because I use a template value inside an if statement which is not executed. What is the standard way to handle this situation?
class Test(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
greeting = ('Hello, ' + user.nickna... | [
"Just Switch:\nclass Test(webapp.RequestHandler):\n def err_user_not_found(self):\n self.redirect(users.create_login_url(self.request.uri))\n def get(self): \n user = users.get_current_user()\n # error path\n if not user:\n self.err_user_not_found()\n ret... | [
3,
2
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0004048745_error_handling_python.txt |
Q:
Auto-Completion In wxPython wxComboBox
I've been trying to make a ComboBox which would suggest options as you type, much like an IDE's code suggestions/code-sense, or googles suggestions when you type in a search.
The suggestions would be the items from the ComboBox dropdown, which contained the substring typed in... | Auto-Completion In wxPython wxComboBox | I've been trying to make a ComboBox which would suggest options as you type, much like an IDE's code suggestions/code-sense, or googles suggestions when you type in a search.
The suggestions would be the items from the ComboBox dropdown, which contained the substring typed in the text box of the ComboBox.
I've tried to... | [
"Few years ago I made a control like this by subclassing TextCtrl. It supports HTML formating for suggestions. Here you go.\nThere is also the Combo Box that Suggests Options\n"
] | [
10
] | [] | [] | [
"autocomplete",
"autosuggest",
"combobox",
"python",
"wxpython"
] | stackoverflow_0004051988_autocomplete_autosuggest_combobox_python_wxpython.txt |
Q:
Interpret 0x string as hex in Python
I'm appending some hex bytes into a packet = [] and I want to return these hex bytes in the form of 0x__ as hex data.
packet.append("2a")
packet.append("19")
packet.append("00")
packet.append("00")
packHex = []
for i in packet:
packHex.append("0x"+i) #this is wrong
retur... | Interpret 0x string as hex in Python | I'm appending some hex bytes into a packet = [] and I want to return these hex bytes in the form of 0x__ as hex data.
packet.append("2a")
packet.append("19")
packet.append("00")
packet.append("00")
packHex = []
for i in packet:
packHex.append("0x"+i) #this is wrong
return packHex
How do I go about converting ('... | [
"You don't really want 'hex data', you want integers. Hexadecimal notation only makes sense when you have numbers represented as strings.\nTo solve your problem use a list comprehension:\n[int(x, 16) for x in packet]\n\nOr to get the result as a tuple:\ntuple(int(x, 16) for x in packet)\n\n",
"Why don't you just ... | [
5,
4
] | [] | [] | [
"casting",
"python",
"types"
] | stackoverflow_0004052298_casting_python_types.txt |
Q:
How to automatically move specific MySQL tables from one machine to another?
I have a MySQL database with tables in the form of "shard_0", "shard_1", "shard_2", etc.
These are virtual shards. Now I want to add another DB server and move the even-numbered shards ("shard_0", "shard_2", "shard_4", ...) to the new mac... | How to automatically move specific MySQL tables from one machine to another? | I have a MySQL database with tables in the form of "shard_0", "shard_1", "shard_2", etc.
These are virtual shards. Now I want to add another DB server and move the even-numbered shards ("shard_0", "shard_2", "shard_4", ...) to the new machine.
What is the best way to do that? There are many tables so ideally I wouldn't... | [
"I'd create a single (or perhaps multiple) mysqldump invocations, like so\nprint \"mysqldump database\",\nfor i in range(n):\n print \"shard_\"+str(2*i),\n\nRun this command in a shell, and move the dump file to the new machine, then run it there through mysql.\nThen generate and run the \"drop table\" statement... | [
2,
0
] | [] | [] | [
"database",
"mysql",
"python",
"sharding"
] | stackoverflow_0004048728_database_mysql_python_sharding.txt |
Q:
How to profile combined python and c code
I have an application that consists of multiple python scripts. Some of these scripts are calling C code. The application is now running much slower than it was, so I would like to profile it to see where the problem lies. Is there a tool, software package or just a way to... | How to profile combined python and c code | I have an application that consists of multiple python scripts. Some of these scripts are calling C code. The application is now running much slower than it was, so I would like to profile it to see where the problem lies. Is there a tool, software package or just a way to profile such an application? A tool that will ... | [
"Stackshots work. Since you have combined Python and C you can handle them separately. For Python, you can hit Ctrl-C while it's being slow to examine the stack. Do this several times. That will expose anything you can fix in the python code. For the C code, run the whole thing under a debugger like GDB and hit Ctr... | [
3,
1
] | [] | [] | [
"c",
"profiling",
"python"
] | stackoverflow_0004051117_c_profiling_python.txt |
Q:
A SuggestBox for wxPython?
Is there a widget for wxPython like the SuggestBox in Google Web Toolkit? It is basically a magic text box that can invoke some code to come up with suggestions relevant to whatever the user has entered so far. Like the search box on Google's web page.
If such a widget isn't already floa... | A SuggestBox for wxPython? | Is there a widget for wxPython like the SuggestBox in Google Web Toolkit? It is basically a magic text box that can invoke some code to come up with suggestions relevant to whatever the user has entered so far. Like the search box on Google's web page.
If such a widget isn't already floating out there, I'd appreciate a... | [
"You might want to look at Combo Box that Suggests Options.\nI hope this is what you were thinking of.\n",
"Few years ago I made a control like this by subclassing TextCtrl. It supports HTML formating for suggestions. Here you go.\n"
] | [
4,
1
] | [] | [] | [
"python",
"search",
"suggestbox",
"wxpython"
] | stackoverflow_0000452520_python_search_suggestbox_wxpython.txt |
Q:
Failure loading py2exe'd program when including pysvn
I am attempting to run a py2exe'd program (package.py) that includes pysvn. It is failing to run with the following error:
Traceback (most recent call last):
File "package.py", line 27, in <module>
File "zipextimporter.pyc", line 82, in load_module
... | Failure loading py2exe'd program when including pysvn | I am attempting to run a py2exe'd program (package.py) that includes pysvn. It is failing to run with the following error:
Traceback (most recent call last):
File "package.py", line 27, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "pysvn\__init__.pyc", line 99, in <module>
Fil... | [
"Install PyWin32.\n",
"The py2exe project seems dead, so we rewrote our exes in C++. We can still build for Win7 x64 on our machines, but we couldn't get exe's wrote on Win7 to run on anything older.\n"
] | [
0,
0
] | [] | [] | [
"py2exe",
"pysvn",
"python"
] | stackoverflow_0003189530_py2exe_pysvn_python.txt |
Q:
Convert xml to pdf in Python
I have a problem when I try to convert a XML file in a PDF file, here I’m going to explain briefly how I try to generate a PDF file.
We suppose I get the information from a database, then the code source is the following:
import pyodbc,time,os,shutil,types
import cStringIO
import ho.pi... | Convert xml to pdf in Python | I have a problem when I try to convert a XML file in a PDF file, here I’m going to explain briefly how I try to generate a PDF file.
We suppose I get the information from a database, then the code source is the following:
import pyodbc,time,os,shutil,types
import cStringIO
import ho.pisa as pisa
import urllib
def HTML... | [
"I'm not sure I understand the question fully, but are you expecting pisa to apply the xslt transformation? I don't think it will do that (you might want to look at lxml and use that to apply the xslt before converting to pdf with pisa)\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004043760_python.txt |
Q:
Performing unbiased program/script performance comparison
I want to perform a comparison of multiple implementations of basically the same algorithm, written in Java, C++ and Python, the latter executed using Pypy, Jython and CPython on a Mac OS X 10.6.4 Macbook Pro with normal (non-SSD) HDD.
It's a "decode a stre... | Performing unbiased program/script performance comparison | I want to perform a comparison of multiple implementations of basically the same algorithm, written in Java, C++ and Python, the latter executed using Pypy, Jython and CPython on a Mac OS X 10.6.4 Macbook Pro with normal (non-SSD) HDD.
It's a "decode a stream of data from a file" type of algorithm, where the relevant m... | [
"These are difficult to do well.\nIn many cases the operating system will cache files so the second time they are executed they suddenly perform much better.\nThe other problem is you're comparing interpreted languages against compiled. The interpreted languages require an interpreter loaded into memory somewhere o... | [
1,
0,
0,
0
] | [] | [] | [
"c++",
"java",
"jython",
"performance",
"python"
] | stackoverflow_0004052691_c++_java_jython_performance_python.txt |
Q:
How come a document in MongoDB sometimes gets inserted , but most often don't?
con = pymongo.Connection('localhost',27017)
db = con.MouseDB
post = { ...some stuff }
datasets = db.datasets
datasets.insert(post)
So far, there are only 3 records, and it's supposed to have about 100...
A:
Did you check to make sur... | How come a document in MongoDB sometimes gets inserted , but most often don't? | con = pymongo.Connection('localhost',27017)
db = con.MouseDB
post = { ...some stuff }
datasets = db.datasets
datasets.insert(post)
So far, there are only 3 records, and it's supposed to have about 100...
| [
"Did you check to make sure that you don't have collisions on your primary keys. Take a look at the console and it should tell you why a document is not inserting. I'd also recommend trying to insert one at a time from the command line tool to get better information as to why it may not be inserting correctly. I... | [
0
] | [] | [] | [
"database",
"mongodb",
"nosql",
"python"
] | stackoverflow_0004050989_database_mongodb_nosql_python.txt |
Q:
How can I do this complex SQL query using Django ORM? (sub-query with a join)
I'm used to writing my own SQL queries and I'm trying to get used to the whole ORM thing that seems to be so popular nowadays.
Here's the query:
SELECT * FROM routes WHERE route_id IN (
SELECT DISTINCT t.route_id FROM stop_times AS s... | How can I do this complex SQL query using Django ORM? (sub-query with a join) | I'm used to writing my own SQL queries and I'm trying to get used to the whole ORM thing that seems to be so popular nowadays.
Here's the query:
SELECT * FROM routes WHERE route_id IN (
SELECT DISTINCT t.route_id FROM stop_times AS st
LEFT JOIN trips AS t ON st.trip_id=t.trip_id
WHERE stop_id = %s
)
where... | [
"Correct me if I'm wrong, but I don't think you can do that with Django ORM in a normal way.\nThere is no subquery support and with a normal join it would depend on your database if a distinct could help you. If you are using Postgres than you could do it with this patch: http://code.djangoproject.com/ticket/6422\n... | [
1,
1
] | [] | [] | [
"django",
"gtfs",
"orm",
"python",
"sql"
] | stackoverflow_0004039711_django_gtfs_orm_python_sql.txt |
Q:
Return a range of elements of each list inside a list of lists
From a list mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] how can I get a new list of lists composed of the first two elements of each "inside" list e.i. newlist = [[1, 2], [4, 5], [7, 8]]? Is there a one-liner that can do this efficiently (for large list... | Return a range of elements of each list inside a list of lists | From a list mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] how can I get a new list of lists composed of the first two elements of each "inside" list e.i. newlist = [[1, 2], [4, 5], [7, 8]]? Is there a one-liner that can do this efficiently (for large lists of lists)?
| [
"The easiest way is probably to use a list comprehension:\nnewlist = [sublist[:2] for sublist in mylist]\n\n",
"Quick answer:\nfirst_two = [sublist[:2] for sublist in mylist]\n\nIf having a list of tuples is ok, then a faster answer (2x by my measurements):\nimport operator\nmap(operator.itemgetter(0, 1), mylist)... | [
7,
3,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0004053594_list_comprehension_python.txt |
Q:
How to call Wine dll from python on Linux?
I'm writing a python script in Linux, and need to call some Windows functions available in Wine. Specifically, AllocateAndInitializeSid and LookupAccountSidW, to determine who is logged in to a remote Windows computer. These functions are part of advapi32.dll in Wine (e... | How to call Wine dll from python on Linux? | I'm writing a python script in Linux, and need to call some Windows functions available in Wine. Specifically, AllocateAndInitializeSid and LookupAccountSidW, to determine who is logged in to a remote Windows computer. These functions are part of advapi32.dll in Wine (edit: using the answers, I was able to call the f... | [
"Doesn't Wine provide *.so versions of the dlls? I seem to have /usr/lib32/wine/advapi32.dll.so, for example. \nIf you're on a 64-bit machine, keep in mind that you'll need a 32-bit version of Python to load 32-bit libraries.\n",
"Understand that .DLL is the format used by Windows. \nOn linux, such libraries end ... | [
7,
0
] | [] | [] | [
"dll",
"linux",
"python",
"wine"
] | stackoverflow_0004052690_dll_linux_python_wine.txt |
Q:
Open file in universal-newline mode when using pkg_resources?
I am processing a CSV file and have the following working code:
reader = csv.reader(open(filename, 'rU'), dialect='excel')
header = reader.next()
However, to be compatible with elsewhere in the codebase, I need to use a file object using pkg_resources.... | Open file in universal-newline mode when using pkg_resources? | I am processing a CSV file and have the following working code:
reader = csv.reader(open(filename, 'rU'), dialect='excel')
header = reader.next()
However, to be compatible with elsewhere in the codebase, I need to use a file object using pkg_resources.resource_stream, as follows:
fileobj = pkg_resources.resource_strea... | [
"If the stream always has an fd (e.g. because it's a normal opened file on the filesystem), you can use os.fdopen(fileobj.fileno(), 'rU') to open it with the right mode.\n"
] | [
6
] | [] | [] | [
"csv",
"pkg_resources",
"python"
] | stackoverflow_0004052489_csv_pkg_resources_python.txt |
Q:
using float('nan') to represent missing values - safe?
Python 3.1
I am doing some calculations on a data that has missing values. Any calculation that involves a missing value should result in a missing value.
I am thinking of using float('nan') to represent missing values. Is it safe? At the end I'll just check
d... | using float('nan') to represent missing values - safe? | Python 3.1
I am doing some calculations on a data that has missing values. Any calculation that involves a missing value should result in a missing value.
I am thinking of using float('nan') to represent missing values. Is it safe? At the end I'll just check
def is_missing(x):
return x!=x # I hope it's safe to use to... | [
"It's safe-ish, but if the FPU ever has to touch x it can be insanely slow (as some hardware treats NaN as a special case): Is it a good idea to use IEEE754 floating point NaN for values which are not set?\n"
] | [
1
] | [] | [] | [
"floating_point",
"python",
"python_3.x"
] | stackoverflow_0004054005_floating_point_python_python_3.x.txt |
Q:
Pull data from one couchdb doc via ids in another (Python)
I have two databases in CouchDB - DB1's documents are user data - name, email address, username, password but within one field that I store a list of the ID's saved in DB2 where user projects are saved (containing a username field and some Textfields.
... | Pull data from one couchdb doc via ids in another (Python) | I have two databases in CouchDB - DB1's documents are user data - name, email address, username, password but within one field that I store a list of the ID's saved in DB2 where user projects are saved (containing a username field and some Textfields.
Example DB1 Document (Users)
{
"_id": "bobsmith1000"... | [
"Unless you have great reasons to split your docs in different dbs, that seems like is not the case according to your question, them you should keep them all on the same database and have some property on the docs to identify their type (like a \"type: user\" and \"type: project\").\nThat way you can get the desire... | [
1
] | [] | [] | [
"couchdb",
"flask",
"python"
] | stackoverflow_0004052220_couchdb_flask_python.txt |
Q:
How can I create a TABLE if and only if it does not exist?
I'm trying
conn = MySQLdb.connect (host = "localhost",
user = "username",
passwd = "password",
db = "my_db")
cursor = conn.cursor ()
q = """IF NOT EXISTS CREATE TABLE %s (
... | How can I create a TABLE if and only if it does not exist? | I'm trying
conn = MySQLdb.connect (host = "localhost",
user = "username",
passwd = "password",
db = "my_db")
cursor = conn.cursor ()
q = """IF NOT EXISTS CREATE TABLE %s (
course VARCHAR(15),
student VARCHAR(15),
... | [
"Wrong syntax: IF NOT EXISTS CREATE TABLE is not valid SQL in MySQL. \nYou want \nCREATE TABLE IF NOT EXISTS [tablename]\n\nper the MySQL documentation.\n"
] | [
14
] | [] | [] | [
"mysql",
"mysql_error_1064",
"python"
] | stackoverflow_0004054649_mysql_mysql_error_1064_python.txt |
Q:
Does anyone see why the first part of my regex isn't working in Python?
I tested this regex out in RegexBuddy
,[A-Z\s]+?,(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?
and it seems to be able to do what I need it to do - capture a piece of data that looks like one of the following:
,POWDER,RO,ML,8/19/200... | Does anyone see why the first part of my regex isn't working in Python? | I tested this regex out in RegexBuddy
,[A-Z\s]+?,(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?
and it seems to be able to do what I need it to do - capture a piece of data that looks like one of the following:
,POWDER,RO,ML,8/19/2002
,POWDER,RO,,,
,POWDER,RO,,8/19/2002
,POWDER,RO,ML,,
When I use it in a pyth... | [
"Yes. You did not capture the first group.\nr\",([A-Z\\s]+),(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\\d+/\\d+/\\d{4})?\"\n# ^ ^ \n\nBTW, it seems that you are parsing a CSV file with regex. In Python, there is already a csv module.\n",
"The first part of your regex doesn't have capturing parentheses around... | [
5,
3,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004054690_python_regex.txt |
Q:
Python XML Parse (using schema to generate dataset)
I'm looking to parse a xml file using Python and I was wondering if there was any way of automating the task over manually walking through all xml nodes/attributes using xml.dom.minidom library.
Essentially what would be sweet is if I could load a xml schema for ... | Python XML Parse (using schema to generate dataset) | I'm looking to parse a xml file using Python and I was wondering if there was any way of automating the task over manually walking through all xml nodes/attributes using xml.dom.minidom library.
Essentially what would be sweet is if I could load a xml schema for the xml file I am reading then have that automatically ge... | [
"lxml is a super-robust xml parsing package. It includes a subpackage, lxml.objectify, that will make an object tree from your xml.\nIt doesn't generate a class from the schema -- that's probably more a C#/Java thing -- but it does do schema validation so you know what kind of object you're getting back (see \"asse... | [
3,
0
] | [
"hey dude - take beautifulSoup - it is a super library. HEAD over to the site scraperwiki.com\nthe can help you! \n"
] | [
-1
] | [
"c#",
"dataset",
"python",
"schema",
"xml"
] | stackoverflow_0004054205_c#_dataset_python_schema_xml.txt |
Q:
django error ,about django-sphinx
from django.db import models
from djangosphinx.models import SphinxSearch
class MyModel(models.Model):
search = SphinxSearch() # optional: defaults to db_table
# If your index name does not match MyModel._meta.db_table
# Note: You can only generate automatic configura... | django error ,about django-sphinx | from django.db import models
from djangosphinx.models import SphinxSearch
class MyModel(models.Model):
search = SphinxSearch() # optional: defaults to db_table
# If your index name does not match MyModel._meta.db_table
# Note: You can only generate automatic configurations from the ./manage.py script
#... | [
"I know what the problem is :)\nYou are trying to run this script as stand-alone. But since you use django models. all of them have to be imported in your namespace. This is what is the error. It clearly days ImportError.\nTo solve - go to your django-project directory & then type python manage.py shell. This impor... | [
1,
0
] | [] | [] | [
"django",
"django_sphinx",
"python"
] | stackoverflow_0002174400_django_django_sphinx_python.txt |
Q:
How to use Python re module to replace \n with nothing in a single file
Regards to all.
I'm developing a Image compression system using Python Image Library. The basic workflow is:
Read all images of a certain directory with : find /opt/images -name *.jpg > /opt/rs/images.txt
Read this file and storage the result... | How to use Python re module to replace \n with nothing in a single file | Regards to all.
I'm developing a Image compression system using Python Image Library. The basic workflow is:
Read all images of a certain directory with : find /opt/images -name *.jpg > /opt/rs/images.txt
Read this file and storage the result in a Python list
Iterate the list, create a Image object and passing like a ... | [
"Assuming s is the string with the carriage return, you may use s.strip(\"\\n\") to remove carriage returns at the corners of the string. No need for regular expressions there.\n",
"I guess the relevant code lines are these:\nfor line in f:\n images.append(line)\n\nto remove the \\n, you can simply call strip(... | [
2,
1,
0
] | [] | [] | [
"python",
"python_imaging_library",
"regex",
"resize"
] | stackoverflow_0004054043_python_python_imaging_library_regex_resize.txt |
Q:
Python std methods hierarchy calls documented?
just encountered a problem at dict "type" subclassing. I did override __iter__ method and expected it will affect other methods like iterkeys, keys etc. because I believed they call __iter__ method to get values but it seems they are implemented independently and I ha... | Python std methods hierarchy calls documented? | just encountered a problem at dict "type" subclassing. I did override __iter__ method and expected it will affect other methods like iterkeys, keys etc. because I believed they call __iter__ method to get values but it seems they are implemented independently and I have to override all of them.
Is this a bug or intenti... | [
"Subclass Mapping or MuteableMapping from the collections module instead of dict and you get all those methods for free.\nHere is a example of a minimal mapping and some of the methods you get for free:\nimport collections\nclass MinimalMapping(collections.Mapping):\n def __init__(self, *items ):\n self.e... | [
5,
2,
1,
0
] | [] | [] | [
"python",
"python_datamodel"
] | stackoverflow_0004053662_python_python_datamodel.txt |
Q:
How to deal with utf-8 encoded String and BeautifulSoup?
How can I replace HTML-entities in unicode-Strings with proper unicode?
u'"HAUS Kleider" - Über das Bekleiden und Entkleiden, das VerhŸllen und Veredeln'
to
u'"HAUS-Kleider" - Über das Bekleiden und Entkleiden, das Verhüllen und Veredeln... | How to deal with utf-8 encoded String and BeautifulSoup? | How can I replace HTML-entities in unicode-Strings with proper unicode?
u'"HAUS Kleider" - Über das Bekleiden und Entkleiden, das VerhŸllen und Veredeln'
to
u'"HAUS-Kleider" - Über das Bekleiden und Entkleiden, das Verhüllen und Veredeln'
edit
Actually the entities are wrong. At it seems like Beau... | [
"I think what you need are ICU transliterators. I think there is a way to transliterate HTML entities into Unicode. \nTry the transliterator id Hex/XML-Any that should to what you want. On the Demo page you can choose \"Insert Sample: Compound\" and then enter Hex/XML-Any into the \"Compound 1\" box, add some input... | [
1,
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004054551_beautifulsoup_python.txt |
Q:
Text in Text Widget as a variable
so I've got this little Text widget with a scroll bar and I've got a question. How do I make text in this Text widget a variable ? If I made this text a variable I would be able to open a text file and edit it's text or save the text I've written, etc or maybe it's a wrong way tha... | Text in Text Widget as a variable | so I've got this little Text widget with a scroll bar and I've got a question. How do I make text in this Text widget a variable ? If I made this text a variable I would be able to open a text file and edit it's text or save the text I've written, etc or maybe it's a wrong way that I'm approaching this, is there a bett... | [
"There is no option to associate a variable with a text widget. You can achieve the same thing by using variable traces and widget bindings but it's rarely worth the effort.\nThe typical way to interact with the text widget is to read a file into a variable then use the insert method of the widget to put the text i... | [
5
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004055017_python_tkinter_user_interface.txt |
Q:
wx.ProgressDialog not updating bar or newmsg
The update method of wx.ProgressDialog has a newmsg argument that is supposed to give a textual update on what is happening in each step of the process, but my code is not doing this properly.
Here is the link to the documentation for wx.ProgressDialog http://www.wxpyth... | wx.ProgressDialog not updating bar or newmsg | The update method of wx.ProgressDialog has a newmsg argument that is supposed to give a textual update on what is happening in each step of the process, but my code is not doing this properly.
Here is the link to the documentation for wx.ProgressDialog http://www.wxpython.org/docs/api/wx.ProgressDialog-class.html
Also,... | [
"Python identifiers are case sensitive, so newstep is different from newStep.\nAs for the bar itself, that works properly when I run your code. Although I had to change (keepGoing, skip) to keepGoing everywhere, probably a version difference (I have wx.VERSION_STRING == '2.6.3.2').\n",
"Your problem is wx.PD_AUTO... | [
1,
1,
0
] | [] | [] | [
"progress_bar",
"progressdialog",
"python",
"wxpython"
] | stackoverflow_0004046040_progress_bar_progressdialog_python_wxpython.txt |
Q:
How do I write this to a file? I already implemented the Twitter streaming API (Python)...but it just prints to console
from getpass import getpass
from textwrap import TextWrapper
import tweepy
import time
class StreamWatcherListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_inde... | How do I write this to a file? I already implemented the Twitter streaming API (Python)...but it just prints to console | from getpass import getpass
from textwrap import TextWrapper
import tweepy
import time
class StreamWatcherListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')
def on_status(self, status):
try:
print self.status_wrapper.fill... | [
"You are using print statements.\nOpen a file and write the string that you are printing to console.\nIn your code\nclass StreamWatcherListener(tweepy.StreamListener):\n status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')\n\n def __init__(self, api=None):\n self.file... | [
2,
0,
0,
0
] | [] | [] | [
"api",
"logging",
"python",
"twitter"
] | stackoverflow_0004050184_api_logging_python_twitter.txt |
Q:
Lists in pgu/pygame
I'm searching for help about lists in pgu gui for pygame. I need to know which methods and properties they have, so I can include them in my programs
A:
My first suggestion
Use python's builtins to introspect on
import pgu.gui.List
import inspect
help(pgu.gui.List) # to read out the doc stri... | Lists in pgu/pygame | I'm searching for help about lists in pgu gui for pygame. I need to know which methods and properties they have, so I can include them in my programs
| [
"My first suggestion\nUse python's builtins to introspect on \nimport pgu.gui.List\nimport inspect\nhelp(pgu.gui.List) # to read out the doc strings\nprint dir(pgu.gui.List) # to get the namespace of List class\n# to get all methods of that class\nall_functions = inspect.getmembers(pgu.gui.List, inspect.isfunction)... | [
0
] | [] | [] | [
"pgu",
"pygame",
"python"
] | stackoverflow_0004055347_pgu_pygame_python.txt |
Q:
How to set defualt python library path
I'm using FreeBSD 7.2. I upgraded to Python 2.6. However when I run any python app, it is still using /usr/local/lib/pytho25 as the library path. How do I change it? I cannot modify the python app. Basically I need to change the default lib path to python26.
A:
Are you sure... | How to set defualt python library path | I'm using FreeBSD 7.2. I upgraded to Python 2.6. However when I run any python app, it is still using /usr/local/lib/pytho25 as the library path. How do I change it? I cannot modify the python app. Basically I need to change the default lib path to python26.
| [
"Are you sure you're using the new binary? I'm not familiar with FreeBSD, but with OpenBSD you have to do a ln -s /usr/local/bin/python2.6 /usr/local/bin/python if you want to start it as python. Perhaps it still points the old way? Also there is PYTHONPATH\n",
"You can creat a softlink to your desiered python ex... | [
3,
0,
0
] | [] | [] | [
"freebsd",
"linux",
"python"
] | stackoverflow_0003749658_freebsd_linux_python.txt |
Q:
Adding Album Art using python in mp3 metadata
The code below doesnt seem to update the artwork of the mp3 file.
Code:-
#Editing the MetaData
tag = eyeD3.Tag()
print tag.link('location') //Returns 1
tag.setVersion([2,3,0])
print tag.addImage(0x08,'artwork.jpg') //Return None (Its sure that file is present)
print ta... | Adding Album Art using python in mp3 metadata | The code below doesnt seem to update the artwork of the mp3 file.
Code:-
#Editing the MetaData
tag = eyeD3.Tag()
print tag.link('location') //Returns 1
tag.setVersion([2,3,0])
print tag.addImage(0x08,'artwork.jpg') //Return None (Its sure that file is present)
print tag.update() //Returns 1
The values returned by the... | [
"It looks like you're specifically referring to adding images to an MP3 using the eyeD3 module. I've only used the CLI version of eyeD3 so I may be wrong, but you don't seem to be passing a type parameter to the addImage method. I don't remember being able to get it to work without passing a type.\n--add-image=IMG_... | [
0
] | [] | [] | [
"artwork",
"id3",
"metadata",
"mp3",
"python"
] | stackoverflow_0002336911_artwork_id3_metadata_mp3_python.txt |
Q:
Python: How do I promote an object from a base class to a derived class?
Hope this isn't too basic, but...
Suppose I have a base class pa(), and I have derived classes pai(), paj(), etc, that inherit from the base class.
I would like to instantiate an object from base class pa():
>>> from pamod import *
>>> mypa =... | Python: How do I promote an object from a base class to a derived class? | Hope this isn't too basic, but...
Suppose I have a base class pa(), and I have derived classes pai(), paj(), etc, that inherit from the base class.
I would like to instantiate an object from base class pa():
>>> from pamod import *
>>> mypa = pa()
>>> mypa
<pamod.pa object at 0x28d4fd0>
>>>
... and then promote it (ca... | [
"It's a terrible approach, since you have to handle initialization of the new attributes yourself. Write a class method in the child that returns a new instance with the appropriate attributes copied over.\n",
"I don't get it. Seems like reassigning __class__ keeps me from having to copy everything over, which is... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004047935_python.txt |
Q:
What is the canonical way of handling different types in Python?
I have a function where I need to generate different output strings for another program I invoke, depending on which type it wants.
Basically, the called program needs a command line argument telling it which type it was called with.
Happily I found ... | What is the canonical way of handling different types in Python? | I have a function where I need to generate different output strings for another program I invoke, depending on which type it wants.
Basically, the called program needs a command line argument telling it which type it was called with.
Happily I found this answer on SO on how to check a variable for type. But I noticed h... | [
"You could use Double Dispatch or Multimethods.\n",
" But I noticed how people also raised objections, \nthat checking for types betrays a \"not object oriented\" design\n\nActually it's called Duck typing style (\"If it looks like a duck and quacks like a duck, it must be a duck.\"), and it's the python langu... | [
5,
3,
3,
1
] | [] | [] | [
"oop",
"paradigms",
"python"
] | stackoverflow_0004051847_oop_paradigms_python.txt |
Q:
Assigning a value to an element of a slice in Python
This is a simple question about how Python handles data and variables. I've done a lot of experimenting and have Python mostly figured out, except this keeps tripping me up:
[edit: I separated and rearranged the examples for clarity]
Example 1:
>>> a = [[1], 2]
... | Assigning a value to an element of a slice in Python | This is a simple question about how Python handles data and variables. I've done a lot of experimenting and have Python mostly figured out, except this keeps tripping me up:
[edit: I separated and rearranged the examples for clarity]
Example 1:
>>> a = [[1], 2]
>>> a[0:1]
[[1]]
>>> a[0:1] = [[5]]
>>> a
[[5], 2] # The a... | [
"a[0:1] is returning a new array which contains a reference to the array [1], thus you end up modifying the inner array via a reference call.\nThe reason the first case doesn't modify the [1] array is that you're assigning the copied outer array a new inner array value.\nBottom line - a[0:1] returns a copy of the d... | [
7,
3,
1
] | [] | [] | [
"list",
"python",
"slice",
"variable_assignment"
] | stackoverflow_0004055515_list_python_slice_variable_assignment.txt |
Q:
SQLAlchemy equivalent to Django's annotate() method
I'm doing a join like this in SQLAlchemy:
items = Item.query\
.outerjoin((ItemInfo, ItemInfo.item_id==Item.id))
items.add_columns(ItemInfo.count)
This causes SQLAlchemy to return tuples:
>>> items.first()
(<Item ...>, 2)
I'd much prefer it if the "count... | SQLAlchemy equivalent to Django's annotate() method | I'm doing a join like this in SQLAlchemy:
items = Item.query\
.outerjoin((ItemInfo, ItemInfo.item_id==Item.id))
items.add_columns(ItemInfo.count)
This causes SQLAlchemy to return tuples:
>>> items.first()
(<Item ...>, 2)
I'd much prefer it if the "count" value would instead be returned as an attribute of the ... | [
"Actually, \"items.first().count\" would work, since the tuple you get back is a named tuple...but guessing you don't want to see items.first().item.foo.\nThe second way you could do this would be just to run the result of your query() through a function that constructs the kind of result you want:\ndef process(q):... | [
6
] | [] | [] | [
"django",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0004052724_django_orm_python_sqlalchemy.txt |
Q:
Strange newline when attempting unbuffered reading in python
I have this code:
def getch(self):
if os.name == 'posix':
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcs... | Strange newline when attempting unbuffered reading in python | I have this code:
def getch(self):
if os.name == 'posix':
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
elif os.name == 'n... | [
"This might be a platform-specific problem. Have you tried the code on different POSIX-based operating systems (e.g. Linux, BSD, Darwin, etc.). Are your results the same? They all handle terminal operations a little differently, so you might need to account for more than just posix vs. nt and go a little deeper. \n... | [
1
] | [] | [] | [
"python",
"python_3.x",
"terminal"
] | stackoverflow_0004055903_python_python_3.x_terminal.txt |
Q:
Httplib2 - AttributeError: 'NoneType' object has no attribute 'makefile'
How do I fix this?
PS: On googling, I found that this is some httplib2 bug but I didn't understand how to use the patches people have provided.
Traceback (most recent call last):
File "alt_func.py", line 18, in <module>
func(code)
... | Httplib2 - AttributeError: 'NoneType' object has no attribute 'makefile' | How do I fix this?
PS: On googling, I found that this is some httplib2 bug but I didn't understand how to use the patches people have provided.
Traceback (most recent call last):
File "alt_func.py", line 18, in <module>
func(code)
File "alt_func.py", line 9, in func
resp, content = h.request(url_string,... | [
"This is a known issue: http://code.google.com/p/httplib2/issues/detail?id=96\nThere appear to be some dupes logged, or perhaps the same symptom arising from different circumstances:\n\nhttp://code.google.com/p/httplib2/issues/detail?id=101\nhttp://code.google.com/p/httplib2/issues/detail?id=102\n\n",
"You will a... | [
5,
5,
0
] | [] | [] | [
"httplib2",
"python"
] | stackoverflow_0003226218_httplib2_python.txt |
Q:
Extracting data from a URL result with special formatting
I have a URL:
http://somewhere.com/relatedqueries?limit=2&query=seedterm
where modifying the inputs, limit and query, will generate wanted data. Limit is the max number of term possible and query is the seed term.
The URL provides text result formatted in t... | Extracting data from a URL result with special formatting | I have a URL:
http://somewhere.com/relatedqueries?limit=2&query=seedterm
where modifying the inputs, limit and query, will generate wanted data. Limit is the max number of term possible and query is the seed term.
The URL provides text result formatted in this way:
oo.visualization.Query.setResponse({version:'0.5',reqI... | [
"It sounds like you can break this problem up into several subproblems.\nSubproblems\nThere are a handful of problems that need to be solved before composing the completed script:\n\nForming the request URL: Creating a configured request URL from a template\nRetrieving data: Actually making the request\nUnwrapping ... | [
12,
1
] | [] | [] | [
"parsing",
"python",
"url"
] | stackoverflow_0004056375_parsing_python_url.txt |
Q:
python getting weekday from an input date
I'm trying to work on a homework problem where I have an input date in the format YYYY-MM-DD
I need to import a couple modules and create a function weekday where it splits up the date and returns the weekday.
So far I imported:
from time import *
from datetime import *
... | python getting weekday from an input date | I'm trying to work on a homework problem where I have an input date in the format YYYY-MM-DD
I need to import a couple modules and create a function weekday where it splits up the date and returns the weekday.
So far I imported:
from time import *
from datetime import *
I need help in my weekday function where I must... | [
"Suppose s is your input string:\ns = '2010-10-29'\n\nAt the prompt, try s.split('-'). What happens?\nCreate a date object:\nd = datetime.date(2010, 10, 29)\n\nThen run d.strftime('%B'). What happens? How would you get the weekday, instead?\nYou can fill in the rest. Look at the Python docs for more information. Py... | [
15,
2
] | [] | [] | [
"date",
"python"
] | stackoverflow_0004056683_date_python.txt |
Q:
python parsing a block of text betwen 2 known lines
I am trying to get a block of lines between 2 known lines using pyparsing. For example:
ABC
....
DEF
My python code:
end = Literal("\n").suppress()
firstLine = Literal("ABC") + SkipTo(end)
secondLine = Literal("DEF") + SkipTo(end)
line = SkipTo(end)
test = first... | python parsing a block of text betwen 2 known lines | I am trying to get a block of lines between 2 known lines using pyparsing. For example:
ABC
....
DEF
My python code:
end = Literal("\n").suppress()
firstLine = Literal("ABC") + SkipTo(end)
secondLine = Literal("DEF") + SkipTo(end)
line = SkipTo(end)
test = firstLine + OneOrMore(line) + secondLine
test.searchString(my... | [
"Add this debugging code to your program:\nfirstLine.setName(\"firstLine\").setDebug()\nline.setName(\"line\").setDebug()\nsecondLine.setName(\"secondLine\").setDebug()\n\nand change searchString to parseString. setDebug() will print out every time an expression is about to be attempted to match, and if matched, w... | [
1,
0
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0004040762_pyparsing_python.txt |
Q:
Python ctypes.create_string_buffer Problem
The ReadProcessMemory function of kernel32.dll appears to be returning Unicode.
kernel32 = ctypes.windll.kernel32
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
pid = int(raw_input("Enter PID: "))
hproc = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION |PROCE... | Python ctypes.create_string_buffer Problem | The ReadProcessMemory function of kernel32.dll appears to be returning Unicode.
kernel32 = ctypes.windll.kernel32
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
pid = int(raw_input("Enter PID: "))
hproc = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION |PROCESS_VM_READ, False, pid)
lpbaseaddr = 16799644
re... | [
"It is not returning Unicode, but four bytes as a string (probably '\\x80\\x00\\x00\\x00') Pass a pointer to an integer not a string buffer:\nread_buff = ctypes.c_uint()\nkernel32.ReadProcessMemory(hproc, lpbaseaddr, ctypes.byref(read_buff),\n ctypes.sizeof(read_buff), ctypes.byref(bytrea... | [
5
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0004056609_ctypes_python.txt |
Q:
App Engine Namespaces
App Engine provides a way to set the current "namespace". Is this a way to be able to easily reference variables, and thus not always have to insert database lookups in one's code?
A:
Not quite.
Namespacing is useful when you have an appengine app that you want to deploy to serve discrete ... | App Engine Namespaces | App Engine provides a way to set the current "namespace". Is this a way to be able to easily reference variables, and thus not always have to insert database lookups in one's code?
| [
"Not quite.\nNamespacing is useful when you have an appengine app that you want to deploy to serve discrete groups data. You can read more about it here.\nWith namespacing, you partition your appengine app's stuff (datastore, memcache, and taskqueue) into a bunch of separate groups where data, row keys, tasks, etc... | [
5,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004057140_google_app_engine_python.txt |
Q:
Border around string python
Write a function spaced(s) that outputs spaces and a dashdot border around a string s.
The sample code, which calls spaced("Hello") would output:
--.-.-.-.-
. .
- Hello -
. .
-.-.-.-.-.
Please help me out with this :D. Im new to programming and im trying ... | Border around string python | Write a function spaced(s) that outputs spaces and a dashdot border around a string s.
The sample code, which calls spaced("Hello") would output:
--.-.-.-.-
. .
- Hello -
. .
-.-.-.-.-.
Please help me out with this :D. Im new to programming and im trying to learn this stuff. I dont have ... | [
"the key to programming is looking for patterns, and then implementing them.\ndefine your requirements:\n• must have fixed-space fonts\n• border at the top/bottom needs to be the length of text + margin (white space) + border\n• text must have two spaces in all directions (vertical and horizontal)\n• you want alter... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004057129_python.txt |
Q:
Oauth + Aeoid +Python + Google App Engine + Google documents
I am trying to complete a story assignment system for my school newspaper in Google App Engine. It'll track deadlines for writers, allow writers to pick up stories, and give an "at a glance" view of the weeks stories. My partner and I are trying to ful... | Oauth + Aeoid +Python + Google App Engine + Google documents | I am trying to complete a story assignment system for my school newspaper in Google App Engine. It'll track deadlines for writers, allow writers to pick up stories, and give an "at a glance" view of the weeks stories. My partner and I are trying to fully integrate it with our newspapers Google Apps installation. Oh,... | [
"I have a working python App Engine app that uses OpenID, and OAuth to get your google contacts:\nhttp://github.com/sje397/Chess\nIt is running at:\nhttp://your-move.appspot.com\nNote that Aeoid is not needed anymore, since App Engine has built-in OpenID support.\n",
"I just found out wasting a couple of hours, t... | [
3,
1,
0
] | [] | [] | [
"google_app_engine",
"google_docs",
"oauth",
"python"
] | stackoverflow_0002835908_google_app_engine_google_docs_oauth_python.txt |
Q:
Why is Loan undefined when type(self) works just fine?
The following code is being used by the admin to save a Loan object
import uuid
from django.db import models
from django.contrib.auth.models import User
from apps.partners.models import Agent
# Create your models here.
class Loan(models.Model):
""" This ... | Why is Loan undefined when type(self) works just fine? | The following code is being used by the admin to save a Loan object
import uuid
from django.db import models
from django.contrib.auth.models import User
from apps.partners.models import Agent
# Create your models here.
class Loan(models.Model):
""" This is our local info about the loan from the LOS """
guid =... | [
"The Django developers offer a pattern for overriding the model save() method. Using that pattern, the implementation for your save() method should be:\ndef save(self, *args, **kwargs):\n if self.guid == None:\n self.guid = uuid.uuid4().hex\n super(Blog, self).save(*args, **kwargs) # Call the \"real\"... | [
1,
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004047535_django_django_admin_django_models_python.txt |
Q:
Relational database design - Two Relations 1:1 or one 1:2?
This question is about how to design a SQL relationship. I am pretty newbie in this matter and I'd like to know the answers of (way) more experts guys...
I am currently migrating a ZopeDB (Object oriented) database to MySQL (relational) using MeGrok and Sq... | Relational database design - Two Relations 1:1 or one 1:2? | This question is about how to design a SQL relationship. I am pretty newbie in this matter and I'd like to know the answers of (way) more experts guys...
I am currently migrating a ZopeDB (Object oriented) database to MySQL (relational) using MeGrok and SqlAlchemy (although I don't think that's really too relevant, sin... | [
"Expanded in Response to Comments\nThe issue is, you are thinking in the terms that you know (understandable), and you have the limitations of an OO database ... which would not be good to carry over into the Relational db. So for many reasons, it is best to simply identify the Entities and Relations, and to Norma... | [
4,
1,
1
] | [] | [] | [
"database_design",
"modeling",
"python",
"relational_database",
"sqlalchemy"
] | stackoverflow_0004055332_database_design_modeling_python_relational_database_sqlalchemy.txt |
Q:
Any framework for PHP, as effective as Django for Python?
I am using python with django. There I can simply make form from models and also it had builtin Admin.
I am eager to know corresponding framework for PHP with all this facilities.
I have encountered lot some similar questions like this, but they had not com... | Any framework for PHP, as effective as Django for Python? | I am using python with django. There I can simply make form from models and also it had builtin Admin.
I am eager to know corresponding framework for PHP with all this facilities.
I have encountered lot some similar questions like this, but they had not compared the frameworks with django. Experts Please Suggest.
| [
"I'd try Symfony.\nWhat you're referring to sounds like \"scaffolding\"\n",
"I've had good success with Zend in the past. It has a lot of functionality in its libraries and it is all completely decoupled, so you can use whichever parts best fit your task, leaving out other things all together.\n",
"It doesn't ... | [
3,
2,
2,
2,
0
] | [] | [] | [
"django",
"frameworks",
"php",
"python"
] | stackoverflow_0004030026_django_frameworks_php_python.txt |
Q:
Why is this C method segfaulting?
I'm writing an immutable linked list class in C, but one method is mysteriously segfaulting. The code is intended to be roughly equivalent to this:
class PList(object):
def __init__(self, first, rest=None):
self.first = first
self.rest = rest
def cons(sel... | Why is this C method segfaulting? | I'm writing an immutable linked list class in C, but one method is mysteriously segfaulting. The code is intended to be roughly equivalent to this:
class PList(object):
def __init__(self, first, rest=None):
self.first = first
self.rest = rest
def cons(self, item):
return PList(item, se... | [
"I am reading from the documentation:\n\nPyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL)\n Return value: New reference.\n\nCall a callable Python object callable, with a variable number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by NULL. R... | [
4
] | [] | [] | [
"c",
"python",
"python_c_extension",
"segmentation_fault"
] | stackoverflow_0004057611_c_python_python_c_extension_segmentation_fault.txt |
Q:
confused about python subprocess inside for loop
I am trying to automate some big data file processing using python.
A lop of the processing is chained , i.e script1 writes a file , that is then processed by script2 , then script2's output by script3 etc.
I am using the subprocess module in a threaded context.
I h... | confused about python subprocess inside for loop | I am trying to automate some big data file processing using python.
A lop of the processing is chained , i.e script1 writes a file , that is then processed by script2 , then script2's output by script3 etc.
I am using the subprocess module in a threaded context.
I have one class that creates tuples of chained scripts
... | [
"The loop will serially call each script, wait until it completes, and then call the next one regardless of success or failure of the previous call. You probably want to say:\ntry:\n map(subprocess.check_call, script_list)\nexcept Exception, e:\n # failed script\n\nA new thread will start with each call to run, ... | [
2
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0004029782_multithreading_python_queue.txt |
Q:
Pylons app deployment with privately developed dependencies
In my organization, we have a couple of internally developed Python packages. For sake of example, let's call them Foo and Bar. Both are developed in separate Git repositories. Foo is a Pylons application that uses certain library functions from Bar. Neit... | Pylons app deployment with privately developed dependencies | In my organization, we have a couple of internally developed Python packages. For sake of example, let's call them Foo and Bar. Both are developed in separate Git repositories. Foo is a Pylons application that uses certain library functions from Bar. Neither is publicly distributed.
When we deploy Foo, we typically exp... | [
"You can create a package repository. The steps are basically:\n\nCreate an egg with setup.py bdist_egg\nCopy the created egg from dist to a directory served by Apache\nAdd the url to the directory exposed by Apache to the easy_install command with the -f switch\n\nNote that Apache is not necessarily required, but ... | [
2,
1,
0
] | [] | [] | [
"deployment",
"distutils",
"python",
"setuptools"
] | stackoverflow_0004005009_deployment_distutils_python_setuptools.txt |
Q:
Why store sessions on the server instead of inside a cookie?
I have been using Flask for some time now and I am really enjoying the framework. One thing that I fail to understand is that in almost all other places they talk about storing the session on the server and the session id on the client, which would then ... | Why store sessions on the server instead of inside a cookie? | I have been using Flask for some time now and I am really enjoying the framework. One thing that I fail to understand is that in almost all other places they talk about storing the session on the server and the session id on the client, which would then identify the session. However after using flask, I dont feel the ... | [
"Even if your data is encrypted, the user could still roll back their cookie to a previous state (unless you start encoding one-time IDs etc)\ne.g. cookie says the user has 100 credits, user spends 100 credits, they get a new cookie saying they have 0 credits. They could then restore their previous cookie (with 100... | [
19,
8,
7,
2
] | [] | [] | [
"cookies",
"flask",
"python",
"session"
] | stackoverflow_0003948975_cookies_flask_python_session.txt |
Q:
In Python, how would you write a regex that matches the following?
The string contains one or more "@" symbols. One or more of those symbols must have a character after it (not a space).
A:
import re
my_regex = re.compile(r'@\S+')
The \S class matches any non-whitespace character. If you'd prefer only alphanum... | In Python, how would you write a regex that matches the following? | The string contains one or more "@" symbols. One or more of those symbols must have a character after it (not a space).
| [
"import re\nmy_regex = re.compile(r'@\\S+')\n\nThe \\S class matches any non-whitespace character. If you'd prefer only alphanumeric characters, you might want to use \\w instead.\nThen, if you wanted to get all of the instances where it matched:\nfor match in my_regex.finditer(string_to_search):\n # Do somethin... | [
5,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0004057089_python_regex_string.txt |
Q:
Check if string contains one value or another, syntax error?
I'm coming from a javascript backend to Python and I'm running into a basic but confusing problem
I have a string that can contain a value of either 'left', 'center', or 'right'. I'm trying to test if the variable contains either 'left' or 'right'.
In js... | Check if string contains one value or another, syntax error? | I'm coming from a javascript backend to Python and I'm running into a basic but confusing problem
I have a string that can contain a value of either 'left', 'center', or 'right'. I'm trying to test if the variable contains either 'left' or 'right'.
In js its easy:
if( str === 'left' || str === 'right' ){}
However, in ... | [
"Python's logical OR operator is called or. There is no ||.\nif string == 'left' or string == 'right':\n## ^^\n\nBTW, in Python this kind of test is usually written as:\nif string in ('left', 'right'):\n\n## in Python ≥3.1, also possible with set literal\n## if string in {'left', 'right'}:\n\nAlso... | [
13
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0004058085_if_statement_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.