content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python: What does _("str") do? I see this in the Django source code: description = _("Comma-separated integers") description = _("Date (without time)") What does it do? I try it in Python 3.1.3 and it fails: >>> foo = _("bar") Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> foo = ...
Python: What does _("str") do?
I see this in the Django source code: description = _("Comma-separated integers") description = _("Date (without time)") What does it do? I try it in Python 3.1.3 and it fails: >>> foo = _("bar") Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> foo = _("bar") NameError: name '_' is not ...
[ "The name _ is an ordinary name like any other. The syntax _(x) is calling the function called _ with the argument x. In this case it is used as an alias for ugettext, which is defined by Django. This function is used for translation of strings. From the documentation:\n\nSpecifying translation strings: In Python c...
[ 19, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0004708595_python_syntax.txt
Q: Detecting unused Django template libraries While rendering a template is there a way to make Django log something when unused tag libraries are loaded? A: I guess you could fold in your own load method into the django template language and add in a logmethod using Django logging, just out of curiosity, is it the...
Detecting unused Django template libraries
While rendering a template is there a way to make Django log something when unused tag libraries are loaded?
[ "I guess you could fold in your own load method into the django template language and add in a logmethod using Django logging, just out of curiosity, is it the complexity of the template variety that a logger makes it more conveinient to keep the helicopter view?\n" ]
[ 1 ]
[ "Here is what I would do, although this may not be the best solution.\n\nWrite a script that goes through all of your urls.py files and builds up a tree of all the urls that exist in your project (I know there is a third-party django plugin to list all urls, but I cant seem to remember what it is)\nBuild a unittest...
[ -1 ]
[ "django", "python" ]
stackoverflow_0007227776_django_python.txt
Q: any way to composite configuration/.ini files in pylons? We're running a pylons app with multiple ini files (production, staging, development, etc). When a new setting is added that can be the same in all environments, it would be great to be able to set it once in some sort of master configuration that gets incl...
any way to composite configuration/.ini files in pylons?
We're running a pylons app with multiple ini files (production, staging, development, etc). When a new setting is added that can be the same in all environments, it would be great to be able to set it once in some sort of master configuration that gets included with all .ini files. Or included via some other way to l...
[ "You can use the ConfigParser module.\n" ]
[ 0 ]
[]
[]
[ "configuration", "ini", "paster", "pylons", "python" ]
stackoverflow_0007233546_configuration_ini_paster_pylons_python.txt
Q: Binding to an Entry in Tkinter When I bind the event <Key> to an entry and read the content, the change somehow lags behind. I want to "dynamically update" another entry that shows the result of a calculation of the contents of various entries as soon as entry 1 is changed. But somehow the change is not recognize...
Binding to an Entry in Tkinter
When I bind the event <Key> to an entry and read the content, the change somehow lags behind. I want to "dynamically update" another entry that shows the result of a calculation of the contents of various entries as soon as entry 1 is changed. But somehow the change is not recognized instantly, only the foregoing one. ...
[ "The reason is due to the order that events are processed. That order is defined by the \"binding tag\" (or bindtag) of the widget. By default the order is widget, class, toplevel, \"all\". For example, if you have a binding on the widget, and on the class, and on the toplevel window that contains the widget, and o...
[ 7 ]
[]
[]
[ "binding", "python", "tkinter" ]
stackoverflow_0007230713_binding_python_tkinter.txt
Q: Find day difference between two datetimes (excluding weekend days) in Python? The same problem to Find day difference between two dates (excluding weekend days) but it is for javascript. How to do that in Python? A: Try it with scikits.timeseries: import scikits.timeseries as ts import datetime a = datetime.dat...
Find day difference between two datetimes (excluding weekend days) in Python?
The same problem to Find day difference between two dates (excluding weekend days) but it is for javascript. How to do that in Python?
[ "Try it with scikits.timeseries:\nimport scikits.timeseries as ts\nimport datetime\n\na = datetime.datetime(2011,8,1)\nb = datetime.datetime(2011,8,29)\n\ndiff_business_days = ts.Date('B', b) - ts.Date('B', a)\n# returns 20\n\nor with dateutil:\nimport datetime\nfrom dateutil import rrule\n\na = datetime.datetime(2...
[ 8, 3, 3 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0007227173_datetime_python.txt
Q: Insert date from wxdatepickerctrl to database self.dateEntry = wx.GenericDatePickerCtrl(self, -1, size=(120,20), pos=(90,185), style = wx.TAB_TRAVERSAL | wx.DP_DROPDOWN | wx.DP_SHOWCENTURY ...
Insert date from wxdatepickerctrl to database
self.dateEntry = wx.GenericDatePickerCtrl(self, -1, size=(120,20), pos=(90,185), style = wx.TAB_TRAVERSAL | wx.DP_DROPDOWN | wx.DP_SHOWCENTURY | wx.DP_A...
[ "That widget returns a wx.DateTime object, so you'll need to convert it to something that your database understands or maybe the Python datetime object. Here's a thread on how to do the latter: http://wxpython-users.1045709.n5.nabble.com/How-to-convert-wx-DateTime-to-python-datetime-td2352965.html\n" ]
[ 1 ]
[]
[]
[ "postgresql", "psycopg2", "python", "wxpython" ]
stackoverflow_0007233215_postgresql_psycopg2_python_wxpython.txt
Q: Why does Python store German and Spanish (and other?) time format strings as %T in the locale module? I'm writing a test for a program that will be used in multiple locales. While running the test in German, i got the error Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local...
Why does Python store German and Spanish (and other?) time format strings as %T in the locale module?
I'm writing a test for a program that will be used in multiple locales. While running the test in German, i got the error Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/_strptime.py", line 454, in _strptime_time return _strptime(data_string, format)[0] Fi...
[ "This is a wholly unsatisfying answer, but this is the answer anyway:\nThe reason locale and time.strptime do not play well together is because the locale formats were not written for time.strptime. They were written for time.strftime, to produce necessary date/time formats, not to parse them. \nBecause time.strpti...
[ 1, 0 ]
[]
[]
[ "locale", "python", "string_formatting", "time" ]
stackoverflow_0007196634_locale_python_string_formatting_time.txt
Q: Problem with creating python executor I have created a FileManager for my personal files. The launcher for this manager is launched by following script. #!/usr/bin/python from ui.MovieManager import MovieManager MovieManager().showView() Movie manager and other modules are situated in the ui and core packages, ...
Problem with creating python executor
I have created a FileManager for my personal files. The launcher for this manager is launched by following script. #!/usr/bin/python from ui.MovieManager import MovieManager MovieManager().showView() Movie manager and other modules are situated in the ui and core packages, but when executing the file as script, I do...
[ "It's not python which generates the error.\nCheck this out:\nblubb@nemo:~$ from ui.MovieManager import MovieManager\nfrom: can't read /var/mail/ui.MovieManager\n\nMind you, this is the console, which is a logical consequence of you calling the script with sh Launcher.py. Instead, use ./Launcher.py. For this to wo...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007233991_python.txt
Q: Which keywords most distinguish two groups of people? I have a database of keywords used in searches by people of different groups. Something like: group1person1: x, y, z group1person2: x, z, d ... group2person1: z, d, l ... and so on I want to see which keywords are most characteristic of a given group. I'm try...
Which keywords most distinguish two groups of people?
I have a database of keywords used in searches by people of different groups. Something like: group1person1: x, y, z group1person2: x, z, d ... group2person1: z, d, l ... and so on I want to see which keywords are most characteristic of a given group. I'm trying to do what OkCupid did in their blog: http://blog.okcup...
[ "Your question more or less recites the core use case for the ID3 algorithm. \nThe output of ID3 is a classifier, which has a binary tree structure (ID3, C4.5, et al. are often referred to as decision trees). The Wikipedia entry for Decision Tree Learning actually has a decent summary (at the algorithm level) of ID...
[ 5, 2, 0 ]
[]
[]
[ "algorithm", "machine_learning", "python", "statistics" ]
stackoverflow_0007211678_algorithm_machine_learning_python_statistics.txt
Q: how to detect navigation (menu) on web page so i'm writing this program that opens the page and one of the things that it should do is detect how many navigations (menus) web page has, how long is the main navigation (how many elements), average text in elements in navigation and so on... anyway i have some proble...
how to detect navigation (menu) on web page
so i'm writing this program that opens the page and one of the things that it should do is detect how many navigations (menus) web page has, how long is the main navigation (how many elements), average text in elements in navigation and so on... anyway i have some problems detecting menus. i'm thinking there is 2 ways ...
[ "There is no universal solution. You need to implement some heuristics. I will try such:\n\nget all site pages with recursion limit=1 (like wget -r -l1 http://example.com/)\nfor each internal page, keep set of internal links on that page\nget intersection of all sets.\n\nThis way you will get the constant set of in...
[ 5, 2, 1, 0 ]
[]
[]
[ "html", "python", "xhtml" ]
stackoverflow_0007233406_html_python_xhtml.txt
Q: csh stdin to Python stdin? How do you redirect the stdin of a csh script to the stdin of a python script? I have a cgi script I'm writing in csh that runs on a Solaris machine. This csh script is a wrapper to a python script that reads from the stdin (I know, scripting in csh is bad but I'm forced to in this case...
csh stdin to Python stdin?
How do you redirect the stdin of a csh script to the stdin of a python script? I have a cgi script I'm writing in csh that runs on a Solaris machine. This csh script is a wrapper to a python script that reads from the stdin (I know, scripting in csh is bad but I'm forced to in this case). Thanks for help! (And sorry ...
[ "test.csh\n#!/bin/env csh\npython test.py\n\ntest.py (see this question)\n#!/bin/env python\nimport fileinput\n\nif __name__ == '__main__':\n print \"Hi. printing stdin\"\n for line in fileinput.input():\n print line\n\n print \"fin\"\n\nThen the stdin to test.csh is passed in to test.py as Henning ...
[ 6, 3 ]
[]
[]
[ "csh", "python", "stdin" ]
stackoverflow_0007234640_csh_python_stdin.txt
Q: How to check if two words are ordered in python what is the bes way tho check if two words are ordered in sentence and how many times it occurs in python. For example: I like to eat maki sushi and the best sushi is in Japan. words are: [maki, sushi] Thanks. The code import re x="I like to eat maki sushi and th...
How to check if two words are ordered in python
what is the bes way tho check if two words are ordered in sentence and how many times it occurs in python. For example: I like to eat maki sushi and the best sushi is in Japan. words are: [maki, sushi] Thanks. The code import re x="I like to eat maki sushi and the best sushi is in Japan" x1 = re.split('\W+',x) l1 =...
[ "According to the added code, you mean that words are adjacent?\nWhy not just put them together:\nprint len(re.findall(r'\\bmaki sushi\\b', sent)) \n\n", "def ordered(string, words):\n pos = [string.index(word) for word in words]\n return pos == sorted(pos)\n\ns = \"I like to eat maki sushi and the best sus...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007234518_python.txt
Q: "cannot find the main class" error calling a java program using subprocess.Popen, whereas the same call just works using os.system I am writing a script that calls another java program, to perform some tasks. It is very important that each task starts, if and only if, the previous one has finished. Each task might...
"cannot find the main class" error calling a java program using subprocess.Popen, whereas the same call just works using os.system
I am writing a script that calls another java program, to perform some tasks. It is very important that each task starts, if and only if, the previous one has finished. Each task might run for several days, producing a huge amount of output. It works on a huge database I noticed that if I run the script using os.system...
[ "Not sure if this is a typo, but in the way \"that does not work\" as you describe it, you have no space between the cmd and the concatenated \"1\", \"2\" and \"3\" strings. With the os.system calls you do have the space. Without the space you are effectively changing the name of the class whose main method you wan...
[ 3 ]
[]
[]
[ "external", "java", "path", "popen", "python" ]
stackoverflow_0007234769_external_java_path_popen_python.txt
Q: Local Variable referenced before assignment I was wondering if you guys could help. I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error: local variable 'form' referenced before assignment Looking at my code, I can't see whats wrong. def add_client(...
Local Variable referenced before assignment
I was wondering if you guys could help. I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error: local variable 'form' referenced before assignment Looking at my code, I can't see whats wrong. def add_client(request): user = request.user if request....
[ "This is what is happening:\n\nThe if block is not being entered.\nThe form variable is not defined.\nYou then attempt to refer to the form variable in the return statement.\n\nAs to how to fix it, that's really for you to decide. What the fix is depends on what you want your code to do in case the request method i...
[ 14, 7 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0007234881_django_django_models_django_views_python.txt
Q: CharField max_length 2^n vs 2^n-1 Why does one use max_length of CharField equal to 2^n whilst others use 2^n-1? For example: in django.contrib.gis.db.backends.postgis.models (django 1.3): class SpatialRefSys(models.Model, SpatialRefSysMixin): srtext = models.CharField(max_length=2048) in django_openid_auth....
CharField max_length 2^n vs 2^n-1
Why does one use max_length of CharField equal to 2^n whilst others use 2^n-1? For example: in django.contrib.gis.db.backends.postgis.models (django 1.3): class SpatialRefSys(models.Model, SpatialRefSysMixin): srtext = models.CharField(max_length=2048) in django_openid_auth.models (djano-openid-auth 0.3): class N...
[ "You've mostly got it. It's not just the unique=True argument for 255, it's also that strings up to 255 long can sometimes be stored more efficiently.\nSo the answer is that there is maybe a point to doing it for 255 vs. 256, but for other lengths it's very likely to be pointless. Picking power-of-two lengths to ...
[ 10 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0007233031_database_django_python.txt
Q: converting a list of unicode character into a Hebrew string in python Following this thread solution, I have managed to get a bunch of lists that each looks like: [u'\u05ea\u05d0\u05de\u05d9\u05df \u05dc\u05d9'] I assume that those are unicode character but for some reason, I can't convert them back into Hebre...
converting a list of unicode character into a Hebrew string in python
Following this thread solution, I have managed to get a bunch of lists that each looks like: [u'\u05ea\u05d0\u05de\u05d9\u05df \u05dc\u05d9'] I assume that those are unicode character but for some reason, I can't convert them back into Hebrew. I tried the suggested solution in the comments in the link. I also trie...
[ "This is a unicode string, it is in Hebrew and you can even print it directly on a Python interactive shell. e.g.:\n>>> print u'\\u05ea\\u05d0\\u05de\\u05d9\\u05df \\u05dc\\u05d9'\nתאמין לי\n\nIf you really need to convert it to a raw string of bytes (a str object) for some reason, you have to specify the encoding ...
[ 3 ]
[]
[]
[ "html_parsing", "python", "unicode" ]
stackoverflow_0007235081_html_parsing_python_unicode.txt
Q: Hadoop pig latin unable to stream through a python script I have a simple python script (moo.py) that i am trying to stream though import sys, os for line in sys.stdin: print 1; and i try to run this pig script DEFINE CMD `python moo.py` ship('moo.py'); data = LOAD 's3://path/to/my/data/*' AS (a:chararray, b...
Hadoop pig latin unable to stream through a python script
I have a simple python script (moo.py) that i am trying to stream though import sys, os for line in sys.stdin: print 1; and i try to run this pig script DEFINE CMD `python moo.py` ship('moo.py'); data = LOAD 's3://path/to/my/data/*' AS (a:chararray, b:chararray, c:int, d:int); res = STREAM data through CMD; dump ...
[ "it's most likely an issue of relative path.\ntry: \nDEFINE CMD `python moo.py` ship('/local/path/to/moo.py');\n\nit can also be an issue of read/write/execute permission.\n", "The problem was that i used ship() function instead of cache()\nwhile ship() works file - passing local files from the master to the slav...
[ 5, 0 ]
[]
[]
[ "apache_pig", "hadoop", "python" ]
stackoverflow_0005650417_apache_pig_hadoop_python.txt
Q: How to exit from a Python program using MacFSEvents using Ctrl-C I'm using MacFSEvents, a Python library that monitors a directory for changes on Mac OS X, like so: # from http://pypi.python.org/packages/source/M/MacFSEvents/ from fsevents import Observer from fsevents import Stream observer = Observer() def call...
How to exit from a Python program using MacFSEvents using Ctrl-C
I'm using MacFSEvents, a Python library that monitors a directory for changes on Mac OS X, like so: # from http://pypi.python.org/packages/source/M/MacFSEvents/ from fsevents import Observer from fsevents import Stream observer = Observer() def callback(event): print event.name stream = Stream(callback, '.', file...
[ "The answer, by the way, is the little known Ctrl-\\, which sends SIGQUIT to the process, and will quit it no matter how hung.\n", "An alternative is to look for KeyboardInterrupt and stop the observer manually (as an alternative to observer.run()):\ndef better_run(observer):\n try:\n observer.start()\n ...
[ 3, 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0005607316_macos_python.txt
Q: How do I iterate over a Python dictionary, ordered by values? I've got a dictionary like: { 'a': 6, 'b': 1, 'c': 2 } I'd like to iterate over it by value, not by key. In other words: (b, 1) (c, 2) (a, 6) What's the most straightforward way? A: sorted(dictionary.items(), key=lambda x: x[1]) for these of you th...
How do I iterate over a Python dictionary, ordered by values?
I've got a dictionary like: { 'a': 6, 'b': 1, 'c': 2 } I'd like to iterate over it by value, not by key. In other words: (b, 1) (c, 2) (a, 6) What's the most straightforward way?
[ "sorted(dictionary.items(), key=lambda x: x[1])\n\nfor these of you that hate lambda :-)\nimport operator\nsorted(dictionary.items(), key=operator.itemgetter(1))\n\nHowever operator version requires CPython 2.5+\n", "For non-Python 3 programs, you'll want to use iteritems to get the performance boost of generator...
[ 44, 7, 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0000674509_python.txt
Q: Tkinter - making a second canvas display the contents of another I'm looking for a way to make one canvas display the contents of another WITHOUT duplicating the objects that are drawn in it. The second canvas needs to be just a display which takes as input what is drawn on the first one. I know that the .postscri...
Tkinter - making a second canvas display the contents of another
I'm looking for a way to make one canvas display the contents of another WITHOUT duplicating the objects that are drawn in it. The second canvas needs to be just a display which takes as input what is drawn on the first one. I know that the .postscript method writes the contents in a file or a variable, but I don't kno...
[ "There is no built-in way to do this. The canvas doesn't support any sort of peering or duplication. However, keeping copies of all the objects in a second canvas is pretty easy and fast if you don't have any embedded widgets. \nA simple way to do this is to subclass the canvas widget, then create new implementatio...
[ 5 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007214054_python_tkinter.txt
Q: Sorting numpy array according to the sum I want to sort an numpy array according to the sum. Something like import numpy as np a = np.array([1,2,3,8], [3,0,2,1]) b = np.sum(a, axis = 0) idx = b.argsort() Now np.take(a, idx) leads to [2, 1, 3, 8]. But I would like an array: result = np.array([2, 1, 3, 8], [0, 3, ...
Sorting numpy array according to the sum
I want to sort an numpy array according to the sum. Something like import numpy as np a = np.array([1,2,3,8], [3,0,2,1]) b = np.sum(a, axis = 0) idx = b.argsort() Now np.take(a, idx) leads to [2, 1, 3, 8]. But I would like an array: result = np.array([2, 1, 3, 8], [0, 3, 2, 1]] What is the most clever and fastest wa...
[ "With the same code from your question, you can just use the optional axis argument for np.take (default the flattened array is used, that's the reason you got only the first row, see documentation):\n>>> np.take(a, idx, axis=1)\narray([[2, 1, 3, 8],\n [0, 3, 2, 1]])\n\nOr you can use fancy indexing:\n>>> a[:...
[ 5 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007235785_numpy_python.txt
Q: Beautifulsoup Parsing- detail info I already asked a question, but it seems my explnation was not clear.. So, I am asking again with more detail info. <h2 class="sectionTitle"> CORPORATE HEADQUARTERS </h2> 277 Park Avenue<br /> New York, New York 10172 <br /><br />United States<br /><br /> I would like to extrac...
Beautifulsoup Parsing- detail info
I already asked a question, but it seems my explnation was not clear.. So, I am asking again with more detail info. <h2 class="sectionTitle"> CORPORATE HEADQUARTERS </h2> 277 Park Avenue<br /> New York, New York 10172 <br /><br />United States<br /><br /> I would like to extract only New York, New York without postal...
[ "You should use a combination of tag.contents with .split('\\n') to split on lines and.rsplit(' ', 1)` to split only the right most space-separated string. \n", "You still need more detail to write a good regex.\nFor example, if you want to extract the second line of \"CORPORATE HEADQUARTERS\" without a postal co...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007235744_beautifulsoup_python.txt
Q: cleaning data with Python (for statement) Edit: Sorry for the confusion everyone. The first version of this question is so confusing I that have decided to delete it. Here is my question again. How do I translate a list of 10,000 student names (text file) to a list that can be iterated through? I initially said di...
cleaning data with Python (for statement)
Edit: Sorry for the confusion everyone. The first version of this question is so confusing I that have decided to delete it. Here is my question again. How do I translate a list of 10,000 student names (text file) to a list that can be iterated through? I initially said dictionary, but I actually meant list, I apologiz...
[ "Assuming that each student's name is on its own line, which is what it sounds like, this is as easy as\nstudents = open('list-of-students.txt').readlines()\n\nwhich will make students be a list of all the students in the file.\n", "It depends strongly on what you want to do.\nBut something like this should work:...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007234504_python.txt
Q: Where is the python mechanize cache/temp folder? How can I clear it? How can I retrieve files from it? I'm on Ubuntu. I'd like to be able to retrieve images saved in my temp folder, and clear it, at will (or does mechanize not actually read images but rather just html?). A: Mechanize doesn't retrieve images unle...
Where is the python mechanize cache/temp folder? How can I clear it? How can I retrieve files from it?
I'm on Ubuntu. I'd like to be able to retrieve images saved in my temp folder, and clear it, at will (or does mechanize not actually read images but rather just html?).
[ "Mechanize doesn't retrieve images unless you specifically tell it to (on a one by one basis).\n" ]
[ 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0007230327_mechanize_python.txt
Q: How to append lists in a dictionary in Python? Hey everyone this code is working fine just one thing to deal with. It overwrites the multiple entries against a key. I need to avoid the overwriting and to save all those entries. Can you help me in this please? #!/usr/bin/python import sys import fileinput #trys ...
How to append lists in a dictionary in Python?
Hey everyone this code is working fine just one thing to deal with. It overwrites the multiple entries against a key. I need to avoid the overwriting and to save all those entries. Can you help me in this please? #!/usr/bin/python import sys import fileinput #trys to create dictionary from african country list dic =...
[ "You've got a number of problems with your code. The simplest way to do what you describe is to use a defaultdict, which gets rid of the explicit if and has_key (which you should replace by new in dic anyway):\n#trys to create dictionary from african country list\nfrom collections import defaultdict\n\ndic = defaul...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007236101_python.txt
Q: Giving parameters into TestCase from Suite in python From python documentation(http://docs.python.org/library/unittest.html): import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() self...
Giving parameters into TestCase from Suite in python
From python documentation(http://docs.python.org/library/unittest.html): import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() self.widget = None def test_default_size(self): s...
[ "What I've done is in test_suite module just added\nWidgetTestCase.CustomParameter=\"some_address\"\n\nThe simplest solutions are the best :)\n", "This is something that has been on my mind recently. Yes it is very possible to do. I called it scenario testing, but I think parameterized may be more accurate. I ...
[ 6, 3, 3, 0, 0 ]
[]
[]
[ "python", "testcase", "unit_testing" ]
stackoverflow_0005336626_python_testcase_unit_testing.txt
Q: Concatenating two variables in Django that are being rendered via a template Semi-brief overview... --- Indices is a Python list of indices that correspond to the total number of rows the HTML table will have. For example if the column has 5 rows the list would be [0, 1, 2, 3, 4]. --- RowNames is a Python list of ...
Concatenating two variables in Django that are being rendered via a template
Semi-brief overview... --- Indices is a Python list of indices that correspond to the total number of rows the HTML table will have. For example if the column has 5 rows the list would be [0, 1, 2, 3, 4]. --- RowNames is a Python list of the individual names of the HTML table rows. For example [Title, Year, Author, Da...
[ "You can access the index of the element via forloop.counter0 (see here).\nOk, I remembered wrong. Basically you should approach the problem like this:\neither create list of objects or a list of tuples. Django does not support this for reason - the programming should not be done in the templates.\nUsing python's z...
[ 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0007236436_django_html_python.txt
Q: python database drivers timeout This is a generic question about all python database drivers but if you an answer for a specific driver (pyodbc, psycopg2, pymysql, mysqldb, etc.) would be useful anyway. Once I have a connection and cursor, is there a way (an API) to check the connection has or has not timeout with...
python database drivers timeout
This is a generic question about all python database drivers but if you an answer for a specific driver (pyodbc, psycopg2, pymysql, mysqldb, etc.) would be useful anyway. Once I have a connection and cursor, is there a way (an API) to check the connection has or has not timeout without attempting to execute a command t...
[ "In psycopg2, there is an attribute in both the cursor and connection objects named \"closed\".\nFor example, to check if your cursor still is open:\n connection = psycopg2.connect (...)\n cursor = connection.cursor()\n if cursor.closed:\n print('the connection is closed')\n else:\n ...\n\...
[ 1 ]
[]
[]
[ "database", "drivers", "python" ]
stackoverflow_0007235928_database_drivers_python.txt
Q: Facebook Graph API doesn't return the latest picture for an event Pretty sure this is a caching (server side not client) issue but no idea how to resolve. Some events when I try and get the image just return the normal "question mark" static image (i.e. no image). But when I check on facebook actual i can see the ...
Facebook Graph API doesn't return the latest picture for an event
Pretty sure this is a caching (server side not client) issue but no idea how to resolve. Some events when I try and get the image just return the normal "question mark" static image (i.e. no image). But when I check on facebook actual i can see the picture. This is on the server side as its my python scripts that are g...
[ "I think the picture does not appear because the event's information is not accessible through the Graph API. Looking at the event page, it seems to have been created for a non-public group. I think it is likely that you need to be a member of the group in order to access information about its events through the Gr...
[ 2 ]
[]
[]
[ "facebook_graph_api", "facebook_opengraph", "python" ]
stackoverflow_0007233002_facebook_graph_api_facebook_opengraph_python.txt
Q: How do I implement a mod_python style authenhandler/authzhandler using mod_wsgi? I have a simple mod_python script that provides authentication and authorization for a large static website. We're migrating from CentOS 4 to Scientific Linux 6 and I discover that mod_python isn't bundled anymore so I need to conver...
How do I implement a mod_python style authenhandler/authzhandler using mod_wsgi?
I have a simple mod_python script that provides authentication and authorization for a large static website. We're migrating from CentOS 4 to Scientific Linux 6 and I discover that mod_python isn't bundled anymore so I need to convert to mod_wsgi. All the examples for mod_wsgi I've found assume either Basic or Digest...
[ "Suggested at:\nhttp://groups.google.com/group/modwsgi/browse_thread/thread/1edd0398206c89a9\nto use mod_auth_tkt instead.\nhttp://www.openfusion.com.au/labs/mod_auth_tkt/ \n" ]
[ 1 ]
[]
[]
[ "apache2", "mod_python", "mod_wsgi", "python" ]
stackoverflow_0007233305_apache2_mod_python_mod_wsgi_python.txt
Q: Drawing sections of a Bezier curve I was writing code to approximate a quarter ellipse to a Bézier curve. Now having done that, I am encountering trouble drawing sections of this curve. I need some help choosing the control points. Initially, I had taken the ratio of distance of control point to distance of star...
Drawing sections of a Bezier curve
I was writing code to approximate a quarter ellipse to a Bézier curve. Now having done that, I am encountering trouble drawing sections of this curve. I need some help choosing the control points. Initially, I had taken the ratio of distance of control point to distance of start of curve as 0.51. Edited: pseudo code ...
[ "To approximate a circle quarter using a single cubic arc what is normally done is making the middle point being exactly on the circle and using tangent starting and ending directions.\nThis is not formally the \"best\" approximation in any reasonable metric but is very easy to compute... for example the magic numb...
[ 5, 1, 0 ]
[]
[]
[ "bezier", "c++", "python" ]
stackoverflow_0006244272_bezier_c++_python.txt
Q: What is the proper way to track indexes in python? Right now I am tracking my index in side the loop like this index = 0 for entry in longList: if entry == 'foo': print index index += 1 is there a better way to do this? A: for index, entry in enumerate(longList): if entry == 'foo': p...
What is the proper way to track indexes in python?
Right now I am tracking my index in side the loop like this index = 0 for entry in longList: if entry == 'foo': print index index += 1 is there a better way to do this?
[ "for index, entry in enumerate(longList):\n if entry == 'foo':\n print index\n\n", "Use the enumerate() built-in function.\nfor index, entry in enumerate(longList):\n if entry == 'foo':\n print index\n\nHowever, in your specific case, you can simply do index = longList.index(\"foo\")\nEDIT: If...
[ 21, 10, 6, 5, 3, 3 ]
[]
[]
[ "indexing", "lookup", "python" ]
stackoverflow_0007233575_indexing_lookup_python.txt
Q: Replace text with HTML tag in LXML text element I have some lxml element: >> lxml_element.text 'hello BREAK world' I need to replace the word BREAK with an HTML break tag—<br />. I've tried to do simple text replacing: lxml_element.text.replace('BREAK', '<br />') but it inserts the tag with escaped symbols, li...
Replace text with HTML tag in LXML text element
I have some lxml element: >> lxml_element.text 'hello BREAK world' I need to replace the word BREAK with an HTML break tag—<br />. I've tried to do simple text replacing: lxml_element.text.replace('BREAK', '<br />') but it inserts the tag with escaped symbols, like &lt;br/&gt;. How do I solve this problem?
[ "Here's how you could do it. Setting up a sample lxml from your question:\n>>> import lxml\n>>> some_data = \"<b>hello BREAK world</b>\"\n>>> root = lxml.etree.fromstring(some_data)\n>>> root\n<Element b at 0x3f35a50>\n>>> root.text\n'hello BREAK world'\n\nNext, create a subelement tag <br>:\n>>> childbr = lxml.etr...
[ 6, 2 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0007236798_lxml_python.txt
Q: Synchronizing Flickr With Django I am trying to synchronize flickr with django. I am using django-syncr app. But i stacked in somewhere. Database syncdb is ok. But how do we sync the images? Where do we write below code. from syncr.app.flickr import FlickrSyncr f = FlickrSyncr(API_KEY, API_SECRET) f.syncRecentPho...
Synchronizing Flickr With Django
I am trying to synchronize flickr with django. I am using django-syncr app. But i stacked in somewhere. Database syncdb is ok. But how do we sync the images? Where do we write below code. from syncr.app.flickr import FlickrSyncr f = FlickrSyncr(API_KEY, API_SECRET) f.syncRecentPhotos('username', days=7) f.syncPublicFa...
[ "If you wanted to manually synchronize photos, you could add that code to a view that could redirect to a template that might show the updated photos.\nIn my opinion, a better solution would be automated background synchronization. You could either write a Python script and have it run through a cron job, or use a ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004000995_django_python.txt
Q: How to implement a long-running, event-driven python program? I have a series of maintenance tasks for a python WSGI application that are a bit too complex for a crontab (jobs need to be run at frequencies derived from the size of the job queue, manage a connection pool to a group of EC2 instances, etc). How shoul...
How to implement a long-running, event-driven python program?
I have a series of maintenance tasks for a python WSGI application that are a bit too complex for a crontab (jobs need to be run at frequencies derived from the size of the job queue, manage a connection pool to a group of EC2 instances, etc). How should I implement a long-running, event-driven python program? I've nev...
[ "Most of the large, modern python sites are using Celery for this type of work. It is a distributed task queue that supports scheduling of tasks as well.\nThough probably a bit heavyweight for a small site, it'll grow with you. I'm looking to implement it myself (sans Rabbit) shortly.\nI recently found another ch...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0007237106_python.txt
Q: Merging 2 very large text files, update each line, without using memory Say I've got 2 text files with around 2 million lines each (~50-80MB file size each). The structure of both files is the same: Column1 Column2 Column3 ... Column 1 never changes, Column 2: the same value may not be in both files, and won't be...
Merging 2 very large text files, update each line, without using memory
Say I've got 2 text files with around 2 million lines each (~50-80MB file size each). The structure of both files is the same: Column1 Column2 Column3 ... Column 1 never changes, Column 2: the same value may not be in both files, and won't be in the same order for both files, Column3 is a number and will be different ...
[ "I'd go with command line sort(1)to merge and sort the files . After that, it should be a simple script to compute the sums. I don't know PHP, so I'll give my example in python:\nsort -k2 <file1> <file2> | python -c \"\n import itertools,sys\n allLines = (x.strip().split(' ') for x in sys.stdin)\n groups = itert...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "file_io", "memory", "merge", "php", "python" ]
stackoverflow_0007236644_file_io_memory_merge_php_python.txt
Q: create_string_buffer throwing error TypeError: str/bytes expected instead of str instance I am trying this simple ctypes example and getting the error mentioned >>> from ctypes import create_string_buffer >>> str = create_string_buffer("hello") Traceback (most recent call last): File "<stdin>", line 1, in <module>...
create_string_buffer throwing error TypeError: str/bytes expected instead of str instance
I am trying this simple ctypes example and getting the error mentioned >>> from ctypes import create_string_buffer >>> str = create_string_buffer("hello") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python32\lib\ctypes\__init__.py", line 59, in create_string_buffer buf.value = init T...
[ "You're using Python 3, and strings (str-type) in Python 3 are Unicode objects. create_string_buffer creates C char arrays, so you are required to pass a bytes object. If you have a str object encode with an appropriate encoding to create a bytes object. Note there is a create_unicode_buffer that creates C wchar...
[ 15, 11, 0 ]
[]
[]
[ "ctypes", "pointers", "python", "string" ]
stackoverflow_0007237133_ctypes_pointers_python_string.txt
Q: How to run Vim shell from script's path? Search results returned tones of Q&As and I don't know how to rephrase this better, so pardon me if it's a duplicate: I'm running a python script with Vim. The script is at ~/path/to/my/script.py and there is a style sheet file in the same path. The code's content opens the...
How to run Vim shell from script's path?
Search results returned tones of Q&As and I don't know how to rephrase this better, so pardon me if it's a duplicate: I'm running a python script with Vim. The script is at ~/path/to/my/script.py and there is a style sheet file in the same path. The code's content opens the file: f = open('./stylesheet.css', 'r') s = f...
[ "You can use this :lcd %:p:h | !python %. \nA brief explanation. lcd changes directory to the current file being edited - http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file\nThen executes the python command on the file.\nThe one problem with this command is that your current directory will now be (...
[ 5, 1, 0 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0007237256_python_vim.txt
Q: Web2py nginx and domains Hello I am running web2py nginx and uwsgi but I am running into an issue deploying 1 or more domains. The issue is the server is always returning the default welcome application and not the folder I specify for a domain Any ideas are greatly appreciated. Here is my nginx.conf file (the rel...
Web2py nginx and domains
Hello I am running web2py nginx and uwsgi but I am running into an issue deploying 1 or more domains. The issue is the server is always returning the default welcome application and not the folder I specify for a domain Any ideas are greatly appreciated. Here is my nginx.conf file (the relevant parts) server { list...
[ "This location:\nlocation /static {\n root /opt/web2py/applications/cheer10s/;\n }\n\nis only a rewrite for static files, not for apps, and I guess it is wrong, must be:\nlocation ~* /(\\w+)/static/ {\n root /opt/web2py/applications/;\n }\n\nThe line above will just server files under /...
[ 3 ]
[]
[]
[ "nginx", "python", "uwsgi", "web2py" ]
stackoverflow_0007236461_nginx_python_uwsgi_web2py.txt
Q: Is there a good way to do this type of mining? I am trying to find points that are closest in space in X and Y directions (sample dataset given at the end) and am looking to see if there are smarter approaches to do this than my trivial (and untested) approach. The plot of these points in space looks something lik...
Is there a good way to do this type of mining?
I am trying to find points that are closest in space in X and Y directions (sample dataset given at the end) and am looking to see if there are smarter approaches to do this than my trivial (and untested) approach. The plot of these points in space looks something like the following and am trying to find sets of points...
[ "This is a little late, but this problem has been worrying me for some time. I\nwas sure it could be solved with mixed integer / linear programming techniques\nand asked for help in this question: Identifying column and row clusters with linear programming\nHowever, after getting a reply there, I had the insight t...
[ 13, 3 ]
[]
[]
[ "algorithm", "data_mining", "python" ]
stackoverflow_0007076349_algorithm_data_mining_python.txt
Q: data loss problem of tcp protocol in twisted I wrote a tcp based server with the twisted.internet module. It's a high concurrency environment. I usually send data by the instance of protocol.Protocol, and I got a problem with that. Some of the tcp connections may be closed caused by timeout, and it seems I cannot...
data loss problem of tcp protocol in twisted
I wrote a tcp based server with the twisted.internet module. It's a high concurrency environment. I usually send data by the instance of protocol.Protocol, and I got a problem with that. Some of the tcp connections may be closed caused by timeout, and it seems I cannot get any notification so that the data I have writ...
[ "This problem is not specific to Twisted. Your protocol must have some acknowledgement that data was received, if you want to know that it was received.\nThe result from send() does not tell you that the data was authoritatively received by the peer; it just says that it was queued by the kernel for transport. Fr...
[ 4 ]
[]
[]
[ "python", "tcp", "twisted" ]
stackoverflow_0007237996_python_tcp_twisted.txt
Q: web2py - test for row with combination of two field values I'm building a web2py controller in which I need to query a table for a combination of value x in one field AND value y in a second field (in the same row). To query on a single field, I would just write db.table.field == x But I don't know how to write ...
web2py - test for row with combination of two field values
I'm building a web2py controller in which I need to query a table for a combination of value x in one field AND value y in a second field (in the same row). To query on a single field, I would just write db.table.field == x But I don't know how to write a query that looks for field==x AND field2==y
[ "(db.table.field1==x)&(db.table.field2==y)\n\nSee the book section on logical operators.\n", "For a more advanced version, you can append a query to a list and use python's reduce function.\nqueries=[]\nif arg1 == \"x\": queries.append(db.table.field == x)\nif arg2 == \"y\": queries.append(db.table.otherfield == ...
[ 5, 1 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0007237774_python_web2py.txt
Q: Program causes OSX (Snow Leopard 10.6.4) window server to spontaneously crash I have a program that uses OpenGL combined with Cocoa and Python using PyObjC. I've recently expanded on my menu making code to show menu selections for maps including map information. When using the new code, the window server will spon...
Program causes OSX (Snow Leopard 10.6.4) window server to spontaneously crash
I have a program that uses OpenGL combined with Cocoa and Python using PyObjC. I've recently expanded on my menu making code to show menu selections for maps including map information. When using the new code, the window server will spontaneously crash at some random point (Not random but it appears that way). The new ...
[ "AFAIK, there's nothing you can do about it unfortunately. It's a crash introduced with 10.6.4 by Apple.\n", "This is NOT a new \"bug\" by any means. Doing a search turns up a number of instances over the years.\nI have two servers, one Panther (10.3.9) & the other Tiger (10.4.11) that present this error when doi...
[ 0, 0 ]
[]
[]
[ "cocoa", "macos", "opengl", "osx_snow_leopard", "python" ]
stackoverflow_0003407073_cocoa_macos_opengl_osx_snow_leopard_python.txt
Q: Why Python for web development? I'm wondering if learning this language or not. I've been 15 years mainly coding with PHP. I know C, C++, Java, Perl … but PHP has solved all of my problems for web development. I've read carefully this: http://wiki.python.org/moin/PythonVsPhp I find Python useful for sysadmin tasks...
Why Python for web development?
I'm wondering if learning this language or not. I've been 15 years mainly coding with PHP. I know C, C++, Java, Perl … but PHP has solved all of my problems for web development. I've read carefully this: http://wiki.python.org/moin/PythonVsPhp I find Python useful for sysadmin tasks for example, or for first programmin...
[ "I wouldn't do Python web dev without a framework. Having moved from Rails to Django, Django is much better. It has great docs, a great community, doesn't try to force architecture (which can lead to hours of googling about where to put things), and doesn't hide things behind unnerving \"magic\" the way Rails does....
[ 22 ]
[]
[]
[ "python" ]
stackoverflow_0007238513_python.txt
Q: Python raw strings and html parsing How do python raw strings and string literals work? I'm trying to make a webscraper to download pdfs from a site. When I search the string it works, but when I try to implement it in python I always get None as my answer import urllib import re url="" //insert url here sock=...
Python raw strings and html parsing
How do python raw strings and string literals work? I'm trying to make a webscraper to download pdfs from a site. When I search the string it works, but when I try to implement it in python I always get None as my answer import urllib import re url="" //insert url here sock=urllib.urlopen(url) htmlSource=sock.read(...
[ "You seem to be very confused.\nA 'string literal' is a string that you type into the program. Because there needs to be a clear beginning and end to your string, certain characters become inconvenient to have within the middle of the string, and escape sequences must be used to represent them.\nPython offers 'raw'...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007238204_python.txt
Q: loop and process items in list, reloop until all items have been processed I've found similar but not identical questions 742371 and 4081217 with great answers, but haven't come to a solution to my problem. I'm trying to process items in a list in place while it's being looped over, and re-loop over what's remaini...
loop and process items in list, reloop until all items have been processed
I've found similar but not identical questions 742371 and 4081217 with great answers, but haven't come to a solution to my problem. I'm trying to process items in a list in place while it's being looped over, and re-loop over what's remaining in the list if it has not met a conditional. The conditional will eventually ...
[ "current = ['it1', 'test', 'blah', 10]\nresults = []\nwhile current:\n remaining = []\n for item in current:\n (results if meets_conditional(item) else remaining).append(item)\n current = remaining\n\n", "How about something like this (just made up a silly condition so I could test it):\nimport ra...
[ 4, 1, 0 ]
[]
[]
[ "list", "python", "tree" ]
stackoverflow_0007238401_list_python_tree.txt
Q: Python: line break in a textfile after specific word I have a textfile and there's just one line with 10.000 words. Now I want to add a line break before a specific word ("Comment") appears and I also want to write this in a new textfile: The textfile looks like: "Comment: Yeah, you're right Comment: That's very ...
Python: line break in a textfile after specific word
I have a textfile and there's just one line with 10.000 words. Now I want to add a line break before a specific word ("Comment") appears and I also want to write this in a new textfile: The textfile looks like: "Comment: Yeah, you're right Comment: That's very interesting Comment: really? And the new file should looks...
[ "You just need to use str.replace:\ne.write(d.read().replace(' Comment:', '\\nComment:'))\n\n", "Here are explanations of what's wrong, in order:\nd = file('test.txt','r')\ntext=d.read() # Ok: now 'text' contains the entire file contents.\ne = file('output.txt','w')\nx=raw_input(\"Insert word:\")\n# -> Comment\nf...
[ 5, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007236424_python.txt
Q: build list of lists using comprehension lists two at a time I am using the following code to build a list of lists: res = [] for i in I: res.append(x) res.append(y[i]) so my final list is [x, y[0], x, y[1],...] where x and y[i] are also lists. Is there a way building this list using list comprehensions, ins...
build list of lists using comprehension lists two at a time
I am using the following code to build a list of lists: res = [] for i in I: res.append(x) res.append(y[i]) so my final list is [x, y[0], x, y[1],...] where x and y[i] are also lists. Is there a way building this list using list comprehensions, instead of for loop?
[ "I ... think ... this might be close to what you want:\nres = [z for z in ((x, y[i]) for i in I)]\n\n", "Itertools can help with this sort of thing:\n>>> y = I = range(5)\n>>> x = 'x'\n>>> res = list(itertools.chain.from_iterable((x, y[i]) for i in I))\n>>> res\n['x', 0, 'x', 1, 'x', 2, 'x', 3, 'x', 4]\n\n", "r...
[ 2, 2, 2, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007233796_python.txt
Q: Using while in list comprehension or generator expressions I can use if and for in list comprehensions/generator expressions as list(i for i in range(100) if i*i < 30) I know this is not the most efficient but bear with me as the condition could be much more complicated and this is just an example. However, this ...
Using while in list comprehension or generator expressions
I can use if and for in list comprehensions/generator expressions as list(i for i in range(100) if i*i < 30) I know this is not the most efficient but bear with me as the condition could be much more complicated and this is just an example. However, this still goes through hundred iterations and only yields a value in...
[ "Because the syntax of takewhile() and dropwhile() is not the clearest, here are the actual examples of your question: \n>>> [i for i in itertools.takewhile(lambda x: x*x<30, range(10))]\n[0, 1, 2, 3, 4, 5]\n>>> [i for i in itertools.dropwhile(lambda x: x*x<30, range(10))]\n[6, 7, 8, 9] \n\nKnow that the author of ...
[ 26, 14 ]
[]
[]
[ "generator_expression", "list_comprehension", "python", "recipe" ]
stackoverflow_0005505891_generator_expression_list_comprehension_python_recipe.txt
Q: Scaling embedded matplotlib widget in qt application written in python problem I am writing a simple digital image processing program. To do this I have embedded a mpl widget in my qt application. The user can perform some simple analysis on the image such as box car filter, FFT etc. Every thing is working fine...
Scaling embedded matplotlib widget in qt application written in python problem
I am writing a simple digital image processing program. To do this I have embedded a mpl widget in my qt application. The user can perform some simple analysis on the image such as box car filter, FFT etc. Every thing is working fine until I would like to switch from displaying an image to displaying a plot. If I di...
[ "you can use aspect parameter of imshow() to adjust the ratio between the height & weight:\nfrom pylab import *\na = np.zeros((100,10)) # height=100, weight=10\nsubplot(211)\nimshow(a) # ratio = 10\nsubplot(212)\nimshow(a, aspect=0.1) # ratio = 1\nshow()\n\nbut it will stretch the image.\nor you can use xlim(), yl...
[ 1 ]
[]
[]
[ "matplotlib", "pyqt", "python", "qt" ]
stackoverflow_0007238570_matplotlib_pyqt_python_qt.txt
Q: AppEngine elegant way to handle similar requests I'm making a server that can let clients upload and download data of different models. Is there some elegant way handle the requests? More precisely, I don't want to do something like this, app = webapp.WSGIApplication([ ('/my_upload_and_download_url/ModelA/(.*)...
AppEngine elegant way to handle similar requests
I'm making a server that can let clients upload and download data of different models. Is there some elegant way handle the requests? More precisely, I don't want to do something like this, app = webapp.WSGIApplication([ ('/my_upload_and_download_url/ModelA/(.*)', MyRequestHandlerForA), ('/my_upload_and_downloa...
[ "How you do this depends largely on the details of your code in the request handler. You can do a fairly generic one like this:\nclass ModelHandler(webapp.RequestHandler):\n def get(self, kind, key):\n model = db.class_for_kind(kind)\n instance = model.get(key)\n # Do something with the instance - eg, pri...
[ 5, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0007232850_google_app_engine_python_web_applications.txt
Q: checking a Python dictionary for specific keys There are several different ways to check if a Python dictionary contains a specific key, i.e. d = {} if key in d: if d.contains(key): if d.has_key(key): it's silly for a language to allow you to do the same thing several different ways, UNLESS, each of the method...
checking a Python dictionary for specific keys
There are several different ways to check if a Python dictionary contains a specific key, i.e. d = {} if key in d: if d.contains(key): if d.has_key(key): it's silly for a language to allow you to do the same thing several different ways, UNLESS, each of the methods was doing something entirely different. Could som...
[ "They're all the same and they're all around for historical reasons, but you should use key in d.\n", "Method #1 is the accepted way to do it. Method #2 doesn't actually exist, at least in any versions of Python that I'm aware of; I'd be interested to see where you found that. Method #3 used to be the accepted ...
[ 12, 7, 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0007234734_python.txt
Q: how to create an excel file in google app engine (python)? I want to create an excel sheet using Google App Engine in python. my application datastore contains the data of company details like name, business, website,..etc.,. i want to put those details in an excel sheet, is it possible to generate excel file in...
how to create an excel file in google app engine (python)?
I want to create an excel sheet using Google App Engine in python. my application datastore contains the data of company details like name, business, website,..etc.,. i want to put those details in an excel sheet, is it possible to generate excel file in Google App Engine using python. can anybody help me!
[ "You can't write to the filesystem in App Engine, so pyexcelerator's save function obviously won't work. \nYou'll want to take the data pyexcelerator's generating, and instead of writing it to a file either save it as a blob in the Datastore or return it directly to the user's browser.\n", "You may like to consi...
[ 4, 4, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001389076_google_app_engine_python.txt
Q: Displaying checkbox with selected element as checked I'm trying to let a user pick hobbies from list of hobbies that is provided in the form of checklist. When they are chosen, chosen hobbies goes into the user table. I would like for my checkbox to display the user's hobbies, as if the hobbies is selected, it i...
Displaying checkbox with selected element as checked
I'm trying to let a user pick hobbies from list of hobbies that is provided in the form of checklist. When they are chosen, chosen hobbies goes into the user table. I would like for my checkbox to display the user's hobbies, as if the hobbies is selected, it is checked and if not its not checked. User can update the...
[ "{% for hobby in hobbies_list %}\n <input type=\"checkbox\" {% if hobby in user.hobbies %}checked=\"yes\"{% endif %} name = \"{{hobby.name}}\"/>{{hobby.name}}<br/>\n{% endfor %}\n\n", "The easiest way to do this is to use a forms library, like Django forms or WTForms. There's no need to write large amounts of fo...
[ 1, 1, 1 ]
[]
[]
[ "google_app_engine", "html", "python" ]
stackoverflow_0007238075_google_app_engine_html_python.txt
Q: Sorting a counted list in Python (I am brand new to any kind of programming so please be as specific as you can when you answer) Problem: I have written a program to solve pythonchallenge.com level 2. The program works but the results are messy. I want to sort the results of the character count into a nice looking...
Sorting a counted list in Python
(I am brand new to any kind of programming so please be as specific as you can when you answer) Problem: I have written a program to solve pythonchallenge.com level 2. The program works but the results are messy. I want to sort the results of the character count into a nice looking list. When I try to sort the results ...
[ "You should really use the Counter class instead of reinventing your own wheel.\ncharcount is a dictionary, and dictionaries have no implicit sort order. Therefore, we'll have to convert it to a list, which can be sorted. Each entry in that list will be a tuple of count and character.\ncharcount.items() already giv...
[ 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "count", "list", "python", "sorting" ]
stackoverflow_0007239363_count_list_python_sorting.txt
Q: Find what percent of a line a point makes up I have two points, x2 and x1. I have their corresponding y's, y2 and y1. I always know that x2>.95>x1 and that y2>y1. so i wrote this code, in the hopes that I can basically find where along y1-y2 that .95 occurs, however I am not sure towards its accurancy, so any sug...
Find what percent of a line a point makes up
I have two points, x2 and x1. I have their corresponding y's, y2 and y1. I always know that x2>.95>x1 and that y2>y1. so i wrote this code, in the hopes that I can basically find where along y1-y2 that .95 occurs, however I am not sure towards its accurancy, so any suggestions or notices would be nice: 3 x1 = float(...
[ "The equation of a line is y = mx + c where m is the slope, and c is the intercept.\nGiven (x1, y1) and (x2, y2), you can find m and c:\nm = (y2-y1)/(x2-x1)\nc = y2 - m * x2\n\nNow that you know those, you can find the value of y when x = 0.95, by:\ny = m * 0.95 + c\n\n", "The equation of a line by two points (x1...
[ 3, 2 ]
[]
[]
[ "geometry", "line", "python" ]
stackoverflow_0007239142_geometry_line_python.txt
Q: How do I use signal handling? I am trying to write a game that does stuff in the background until you hit a key, so it's waiting for input while doing other stuff at the same time. I have never done something like this before but I hear the solution has to do with event handling. I am trying to use either the "a...
How do I use signal handling?
I am trying to write a game that does stuff in the background until you hit a key, so it's waiting for input while doing other stuff at the same time. I have never done something like this before but I hear the solution has to do with event handling. I am trying to use either the "asyncore" library or the "signal" li...
[ "Python's asyncore library is for network communication, and the signal library is used for timers and operating system signals (not related to keyboard input).\nTo get started, you should find a Python game programming library that suits your purposes.\nIf you want to do something as seemingly simple as keyboard i...
[ 1, 1 ]
[]
[]
[ "python", "signals" ]
stackoverflow_0007236719_python_signals.txt
Q: Swig-generated Constants in Python I'm using SWIG to create a Python interface to my C++ class library. I can't work out how to utilise the constants created by SWIG in Python. I can't even print their value. For example, both these print statements in Python fail silently... print CONST1 print rep (CONST1) In...
Swig-generated Constants in Python
I'm using SWIG to create a Python interface to my C++ class library. I can't work out how to utilise the constants created by SWIG in Python. I can't even print their value. For example, both these print statements in Python fail silently... print CONST1 print rep (CONST1) In C++, I have this #define CONST1 0x20000...
[ "After build, you will get a python source file: theCPPlibrary.py, and a pyd file: _theCPPlibrary.pyd. You must import the python module first:\nimport theCPPlibrary\n\nCONST1 is defined by #define, it can be access by:\nprint theCPPlibrary.CONST1\n\nCONST2 is defined by const, is't a global variable, access it by:...
[ 1 ]
[]
[]
[ "python", "swig" ]
stackoverflow_0007239185_python_swig.txt
Q: what is this saying in python map(tuple, map(lambda row: [float(row[0]), int(row[1]), parse(row[2])], res)) Can someone help me with the syntax here? I'm trying to understand specifically what tuple and lambda is referring to. A: tuple() is a constructor for a "tuple" object, that can convert a list (or other se...
what is this saying in python
map(tuple, map(lambda row: [float(row[0]), int(row[1]), parse(row[2])], res)) Can someone help me with the syntax here? I'm trying to understand specifically what tuple and lambda is referring to.
[ "tuple() is a constructor for a \"tuple\" object, that can convert a list (or other sequence object) to a tuple.\nFor example:\n>>> a = [1, 2, 3]\n>>> a\n[1, 2, 3]\n>>> tuple(a)\n(1, 2, 3)\n\nWhen used in your example, it converts the result of each lambda expression from a list to a tuple. It seems a bit redundant...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007239838_python.txt
Q: How to sort dict of dicts by keys? I have a dict, that looks like: channels = { '24': {'type': 'plain', 'table_name': 'channel.items.AuctionChannel'}, '26': {'type': 'plain', 'table_name': 'channel.gm.DeleteAvatarChannel'}, '27': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyChannel'}, '20': {'type': '...
How to sort dict of dicts by keys?
I have a dict, that looks like: channels = { '24': {'type': 'plain', 'table_name': 'channel.items.AuctionChannel'}, '26': {'type': 'plain', 'table_name': 'channel.gm.DeleteAvatarChannel'}, '27': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyChannel'}, '20': {'type': 'plain', 'table_name': 'channel.gm.Avatar...
[ "Dicts are not sorted/ordered. If you are using python 2.7 you can use an OrderedDict though.\n", "Standard dict is not sorted. You can however iterate over its keys and values in a sorted order:\nfor channelName, channelValue in sorted(channels.items()):\n ...\n\n", "a dict is a mapping, keys are not ordere...
[ 6, 5, 2, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "key", "python", "sorting" ]
stackoverflow_0007239869_dictionary_key_python_sorting.txt
Q: Generate values for str.format style template strings from formatted output This might seem like a wierd requirement, but I am looking for a good implementation to do this. I have a dict like vals = dict(red='#F00', green='#0F0', blue='#00F') and a string like tpl = '{red}:{green}:{blue}' and the str.formatted o...
Generate values for str.format style template strings from formatted output
This might seem like a wierd requirement, but I am looking for a good implementation to do this. I have a dict like vals = dict(red='#F00', green='#0F0', blue='#00F') and a string like tpl = '{red}:{green}:{blue}' and the str.formatted output output = tpl.format(**vals) All is well till here. However, I now need to ...
[ "You can use regular expressions. (And maybe then you'll have two problems.)\n>>> import re\n>>> pattern = re.compile('(#[\\da-fA-F]{3})')\n>>> l = pattern.findall(output)\n['#F00', '#0F0', '#00F']\n>>> dict(zip(('red', 'green', 'blue'), l))\n{'blue': '#00F', 'green': '#0F0', 'red': '#F00'}\n>>>\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007240011_python.txt
Q: AppEngine Task Queue API Calls increase on TaskAlreadyExistsError I'm using deferred to put tasks in the default queue in a AppEngine app similar to this approach. Im naming the task with a timestamp that changes every 5 second. During that time a lot of calls are made to the queue with the same name resulting in ...
AppEngine Task Queue API Calls increase on TaskAlreadyExistsError
I'm using deferred to put tasks in the default queue in a AppEngine app similar to this approach. Im naming the task with a timestamp that changes every 5 second. During that time a lot of calls are made to the queue with the same name resulting in a TaskAlreadyExistsError which is fine. The problem is when I check the...
[ "Thanks for pointing out that this is the case, because I didn't realise, but the same problem must be affecting me.\nAs far as I can see yeah, throwing something into memcache comprised of the taskname should work fine, and then if you want to reduce those hits on memcache you can store the flag locally also with...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python", "task_queue" ]
stackoverflow_0007204744_google_app_engine_python_task_queue.txt
Q: Changing input for the Google Map API I'm trying to use Google Map API in my GAE app but having trouble making it the way i want it to be. Im trying to use the code examples from gecoding-simple http://code.google.com/intl/en/apis/maps/documentation/javascript/examples/geocoding-simple.html I'm trying to display ...
Changing input for the Google Map API
I'm trying to use Google Map API in my GAE app but having trouble making it the way i want it to be. Im trying to use the code examples from gecoding-simple http://code.google.com/intl/en/apis/maps/documentation/javascript/examples/geocoding-simple.html I'm trying to display the map of where my event take place which ...
[ "var address = 'London';\ngeocoder.geocode({ 'address': address }, function (results, status)\n\nSeems to be working fine at my side.\nDo you get any errors?\nWhy is your event.location framed with double brackets?\nMaybe thats causeing the Problem?\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_maps_api_3", "javascript", "python" ]
stackoverflow_0007239785_google_app_engine_google_maps_api_3_javascript_python.txt
Q: Debugging python with mod_fastcgi I running apache with mod_fastcgi to run python scripts (using Ubuntu OS). How can I debug python with fastcgi? I put a pdb.set_trace() call in my script, but when loading the page in a browser nothing happens in the console from which I ran the apache start command (/etc/init.d/a...
Debugging python with mod_fastcgi
I running apache with mod_fastcgi to run python scripts (using Ubuntu OS). How can I debug python with fastcgi? I put a pdb.set_trace() call in my script, but when loading the page in a browser nothing happens in the console from which I ran the apache start command (/etc/init.d/apache2 start). Where should the python ...
[ "You have to attach pdb to a running instance of your FCGI script, read this for a How To. \nThis information is also stated in the FCGI FAQ.\n" ]
[ 0 ]
[]
[]
[ "apache", "fastcgi", "mod_fastcgi", "python" ]
stackoverflow_0007239305_apache_fastcgi_mod_fastcgi_python.txt
Q: How to find difference in time from current date and a pre-determined date in python? Possible Duplicate: How do I find the time difference between two datetime objects in python? I am trying to find the difference in the number of days between current time and a given time in python. For example, the time given...
How to find difference in time from current date and a pre-determined date in python?
Possible Duplicate: How do I find the time difference between two datetime objects in python? I am trying to find the difference in the number of days between current time and a given time in python. For example, the time given is 2011-07-20 and the difference in the number of days at the point of posting this quest...
[ "Sure something like this:\nfrom datetime import datetime\n\nd = datetime.now()\nd1 = datetime.strptime('2011-07-20', '%Y-%m-%d')\n\n(d-d1).days\n>>> 42 # number of total days beetween two given dates\n\nFind more on strptime using the following link.\n" ]
[ 5 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0007240377_datetime_python.txt
Q: sqlalchemy: subqueryload with filter on the subquery In sqlalchemy, is it possible to filter the result in the returned by subqueryloading of a relationship? Consider the following (please ignore any syntax/api errors) Relationship: User.address = relationship(Address, secondary = UserA...
sqlalchemy: subqueryload with filter on the subquery
In sqlalchemy, is it possible to filter the result in the returned by subqueryloading of a relationship? Consider the following (please ignore any syntax/api errors) Relationship: User.address = relationship(Address, secondary = UserAddress, primaryjoin = (User.us...
[ "You want addresses, right? Just do a simple query from the other side (user_id is a parameter):\nqry = session.query(Address).join(User).filter(User.id == user_id)\nif user_group == 'guest':\n qry = qry.filter(Address.type != 'home')\naddresses = qry.all()\n\n" ]
[ 0 ]
[]
[]
[ "python", "relationship", "sqlalchemy" ]
stackoverflow_0007236464_python_relationship_sqlalchemy.txt
Q: Is there a Python equivalent for the Perl module Term::VT102? In Perl there is a very handy module, Term::VT102, which allows you to create a screen in memory. This is very handy for scraping purposes since you can keep track of all the changes to portions of the screen and then export the screen as plain-text for...
Is there a Python equivalent for the Perl module Term::VT102?
In Perl there is a very handy module, Term::VT102, which allows you to create a screen in memory. This is very handy for scraping purposes since you can keep track of all the changes to portions of the screen and then export the screen as plain-text for processing. Is there an equivalent module in Python? Followup Ques...
[ "See also ashttp built on top of Pexcept:\n\nashttp can serve any text application over http, like :\n\n$ ashttp 8080 top\nto serve a top on port 8080, or :\n\n$ ashttp 8080 watch -n 1 ls -lah /tmp\nto serve an actualized directory listing of /tmp\n\n\n(Source: https://mdk.fr/blog/ashttp-vt100-screen-scraping-expor...
[ 3, 2 ]
[]
[]
[ "command_line_interface", "perl", "python", "screen_scraping", "vt100" ]
stackoverflow_0002335882_command_line_interface_perl_python_screen_scraping_vt100.txt
Q: How to use the initializer in a Python ThreadPool I am trying to do threaded convolution using PyFFTW, in order to calculate a large number of 2D convolutions simultaneously. (One does not need separate processes, since the GIL is released for Numpy operations). Now here is the canonical model for doing so: http:...
How to use the initializer in a Python ThreadPool
I am trying to do threaded convolution using PyFFTW, in order to calculate a large number of 2D convolutions simultaneously. (One does not need separate processes, since the GIL is released for Numpy operations). Now here is the canonical model for doing so: http://code.activestate.com/recipes/577187-python-thread-poo...
[ "you can wrap the convolver call with a function that uses Thread Local Storage (threading.local()) to initialize PyFFTW and remember the result\n" ]
[ 1 ]
[]
[]
[ "convolution", "fftw", "multithreading", "python" ]
stackoverflow_0007192376_convolution_fftw_multithreading_python.txt
Q: PyLint wrongly says an object missing certain attributes In my code I use object from compiled extensions (in my case, igraph). I use PyLint to analyze the code. PyLint complains about missing attributes (such as igraph's Graph.adjacent), while it clearly exists (the code runs without errors). What might be the ca...
PyLint wrongly says an object missing certain attributes
In my code I use object from compiled extensions (in my case, igraph). I use PyLint to analyze the code. PyLint complains about missing attributes (such as igraph's Graph.adjacent), while it clearly exists (the code runs without errors). What might be the cause for this messages? Here is some test code import igraph gr...
[ "if it is a compiled C extension, there is little Pylint can do, as it cannot analyze the source code. Can you print igraph.Graph.are_connected in an interactive shell ? If not, it means that the library probably does some weird things at instantiation time or that the methods are introspected. \nIn any case this i...
[ 1 ]
[]
[]
[ "code_analysis", "pylint", "python" ]
stackoverflow_0007239879_code_analysis_pylint_python.txt
Q: Python Mongo DB mod_wsgi form action insert I have a web page generated by newreg.py, when i click on Save / submit button, action written in insertNew.py to read the data and insert into MongoDB. In newreg.py html += '<form method=post action="insertNew.py">' state = form.getvalue('state','<font color="#FF...
Python Mongo DB mod_wsgi form action insert
I have a web page generated by newreg.py, when i click on Save / submit button, action written in insertNew.py to read the data and insert into MongoDB. In newreg.py html += '<form method=post action="insertNew.py">' state = form.getvalue('state','<font color="#FF0000">ERROR</font>') district = form.getvalue('d...
[ "Perhaps try a full Apache restart. The error message doesn't match the code snippet you provided.\nProcess restarts are required after code changes because they will not be detected automatically. Read:\nhttp://code.google.com/p/modwsgi/wiki/ReloadingSourceCode\nRecommended you use daemon mode and touch WSGI scrip...
[ 0 ]
[]
[]
[ "forms", "insert", "list", "mongodb", "python" ]
stackoverflow_0007241329_forms_insert_list_mongodb_python.txt
Q: Disposing of objects with circular references My design is as follows: __main__ references a a references b b references a a is created and then disposed of from __main__ Thus a and b have circular references. However upon del a I would prefer both a and b disposed of. I see in many places advice to use Context ...
Disposing of objects with circular references
My design is as follows: __main__ references a a references b b references a a is created and then disposed of from __main__ Thus a and b have circular references. However upon del a I would prefer both a and b disposed of. I see in many places advice to use Context Managers, and specifically the with statement inste...
[ "I recommend either:\n\nUsing weakref - which is sometimes applicable when circular references are involved\nor ... just manually disposing of stuff in the order you need - not in __del__ but in an explicit dispose method you call at the right time(s)\n\nIn general, when you know you have circular references, relyi...
[ 5, 2, 0 ]
[]
[]
[ "circular_reference", "contextmanager", "python", "with_statement" ]
stackoverflow_0007241113_circular_reference_contextmanager_python_with_statement.txt
Q: Django with IronPython and VS2010? I have just checked JetBrains products page and noticed they have a new product - PyCharm that supports Django out of the box for Python development. Is there a plug-in or a native support for Django in Visual Studio 2010 with IronPython? A: Microsoft did open-source release of...
Django with IronPython and VS2010?
I have just checked JetBrains products page and noticed they have a new product - PyCharm that supports Django out of the box for Python development. Is there a plug-in or a native support for Django in Visual Studio 2010 with IronPython?
[ "Microsoft did open-source release of Python tools for Visual Studio.NET\nThe announcement can be found at http://blogs.msdn.com/b/somasegar/archive/2011/08/29/python-tools-for-visual-studio.aspx\nThe Python tools itself could be found at http://pytools.codeplex.com/\nIt supports CPython, IronPython, Jython, and Py...
[ 3, 1 ]
[]
[]
[ "django", "ironpython", "pycharm", "python", "visual_studio_2010" ]
stackoverflow_0004259553_django_ironpython_pycharm_python_visual_studio_2010.txt
Q: Komodo Extension Continuing on with my Python learning, I just installed Komodo edit, are there any recommended add ins/extensions that I should include? Any recommendations on using it or another GUI designer (TkInter base)? A: If you want to use Komodo, integrate it with Pylint as stated here (I do not know i...
Komodo Extension
Continuing on with my Python learning, I just installed Komodo edit, are there any recommended add ins/extensions that I should include? Any recommendations on using it or another GUI designer (TkInter base)?
[ "If you want to use Komodo, integrate it with Pylint as stated here (I do not know if it works with Komodo Edit, I have run it with Komodo then). It is a code checker, very useful for dynamic language like Python.\nAlso, there is GUI Builder, which is not an \"add-in\" but \"add-out\", it was already part of the Ko...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "ide", "komodo", "python" ]
stackoverflow_0000951974_ide_komodo_python.txt
Q: Python data scraping I want to download a couple songs off of http://www.youtube-mp3.org/. I'm using urllib2 and BeautifulSoup. The problem is that when I urllib2 open the site with my video ID plugged in, http://www.youtube-mp3.org/?c#v=lV7r8PiuecQ, I get the site but they are tricky about it and load the info af...
Python data scraping
I want to download a couple songs off of http://www.youtube-mp3.org/. I'm using urllib2 and BeautifulSoup. The problem is that when I urllib2 open the site with my video ID plugged in, http://www.youtube-mp3.org/?c#v=lV7r8PiuecQ, I get the site but they are tricky about it and load the info after the initial pageload w...
[ "The API is JSON-based, so the contents of the html files won't give you any clue on where to find the files. A good idea when exploring web services like this one, is to open the Network tab in Chrome's developer tools and see what pages it loads when interacting with the page. That exercise showed me that two url...
[ 10, 4, 2 ]
[]
[]
[ "python", "scrape", "urllib2", "youtube" ]
stackoverflow_0007240382_python_scrape_urllib2_youtube.txt
Q: selective RECORD using python xlib? I'm trying to implement clickable areas on the root window, using python xlib's RECORD extension. this is what i've got so far: import sys import os from Xlib import X, XK, display from Xlib.ext import record from Xlib.protocol import rq local_dpy = display.Display() record_dp...
selective RECORD using python xlib?
I'm trying to implement clickable areas on the root window, using python xlib's RECORD extension. this is what i've got so far: import sys import os from Xlib import X, XK, display from Xlib.ext import record from Xlib.protocol import rq local_dpy = display.Display() record_dpy = display.Display() buttons={(0,200,0,...
[ "found it out myself:\ndef record_callback(reply):\n if reply.category != record.FromServer:\n return\n if reply.client_swapped:\n print \"* received swapped protocol data, cowardly ignored\"\n return\n if not len(reply.data) or ord(reply.data[0]) < 2:\n # not an event\n ...
[ 2 ]
[]
[]
[ "python", "x11", "xlib", "xorg" ]
stackoverflow_0006609078_python_x11_xlib_xorg.txt
Q: String to datetime variable format Ok, so I'm converting strings to date so far by: datetime.datetime.fromtimestamp(time.mktime(time.strptime(date_string, DB_TIME_FORMAT))) But I'm getting some strange results. For example for: date_string = '2011-08-30 12:52:57.573979' DB_TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f' Th...
String to datetime variable format
Ok, so I'm converting strings to date so far by: datetime.datetime.fromtimestamp(time.mktime(time.strptime(date_string, DB_TIME_FORMAT))) But I'm getting some strange results. For example for: date_string = '2011-08-30 12:52:57.573979' DB_TIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f' The result is: 2011-08-30 12:52:57 So I g...
[ "You're missing the milliseconds because strptime returns a time tuple, which has no milliseconds field, and stores seconds as an integer. From that point forward, your results are missing the milliseconds. The proper way to get milliseconds is to use the datetime module's strptime, like this:\nparsed = datetime....
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007242342_python.txt
Q: Best way to get email id from a string using python In what are the ways we can get 'X-Mailer-recipient:' email id from this below string using python. using re? Received: from localhost6.localdomain6 (unknown [59.92.85.188]) by smtp.webfaction.com (Postfix) with ESMTP id 05B332078BD1 for <rshi...
Best way to get email id from a string using python
In what are the ways we can get 'X-Mailer-recipient:' email id from this below string using python. using re? Received: from localhost6.localdomain6 (unknown [59.92.85.188]) by smtp.webfaction.com (Postfix) with ESMTP id 05B332078BD1 for <rshivaganesh@gmail.com>; Fri, 26 Aug 2011 04:59:36 -0500 (CDT...
[ "Using the email package:\nfrom email import message_from_string\n\nmsg = '''Received: from localhost6.localdomain6 (unknown [59.92.85.188])\n by smtp.webfaction.com (Postfix) with ESMTP id 05B332078BD1\n for <rshivaganesh@gmail.com>; Fri, 26 Aug 2011 04:59:36 -0500 (CDT)\nContent-Type: text/html; charset=\"u...
[ 4, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007242364_python_string.txt
Q: How to get the string out of this html segment using python I am using python's beautiful stone soup to extract data from this web page. I am using this code segment to get a <li> object: req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Ge...
How to get the string out of this html segment using python
I am using python's beautiful stone soup to extract data from this web page. I am using this code segment to get a <li> object: req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/200809241\ 7 Firefox/3.0.3') response=urllib2.urlopen(re...
[ "I would try\nprint ''.join(map(str, li.contents))\n\n" ]
[ 1 ]
[]
[]
[ "html_parsing", "python" ]
stackoverflow_0007242583_html_parsing_python.txt
Q: How to enumerate all objects and get they attribute? for example: obj1 = ClassName() obj1.name = "name1" obj2 = ClassName() obj2.name = "name2" obj3 = ClassName() obj3.name = "name3" obj4 = ClassName() obj4.name = "name4" and we have static variable that return number of objects: ClassName.counter How i can g...
How to enumerate all objects and get they attribute?
for example: obj1 = ClassName() obj1.name = "name1" obj2 = ClassName() obj2.name = "name2" obj3 = ClassName() obj3.name = "name3" obj4 = ClassName() obj4.name = "name4" and we have static variable that return number of objects: ClassName.counter How i can get obj1.name, obj2.name and other, but if objects count ca...
[ "You can use a Factory class, that's to say an object which handles creation and storing of ClassName objects. Then you can easily access the different ClassNames within an array in Factory class (which must be a Singleton)\n", "Well... it's actually not recommended to do this type of staff, being a little incomp...
[ 2, 1 ]
[]
[]
[ "architecture", "class", "object", "python" ]
stackoverflow_0007242773_architecture_class_object_python.txt
Q: Sort a list of sets I have a list of sets on which I want to perform intersection. Is there an efficient way to sort those sets by length, in order to optimize calculations? A: The key argument of sort allows custom sort keys. Using len will do the trick: l=<list_of_sets> l.sort(key=len) If you want the longes...
Sort a list of sets
I have a list of sets on which I want to perform intersection. Is there an efficient way to sort those sets by length, in order to optimize calculations?
[ "The key argument of sort allows custom sort keys. Using len will do the trick:\nl=<list_of_sets>\nl.sort(key=len)\n\nIf you want the longest set first, use the reverse argument:\nl.sort(key=len, reverse=True)\n\nFor example:\n>>> l=[set((1,2,5,6,7)), set((1,2,3,4,5,6,7)), set((1,)), set((1,2,3))]\n>>> l\n[set([1, ...
[ 11, 7 ]
[]
[]
[ "python" ]
stackoverflow_0007242821_python.txt
Q: instapaper and oauth - 403 "Not logged in" error I am trying to use the instapaper API, but I keep getting a 403 error for my requests. Here's the code: consumer_key='...' consumer_secret='...' access_token_url = 'https://www.instapaper.com/api/1/oauth/access_token' consumer = oauth.Consumer(consumer_key, consume...
instapaper and oauth - 403 "Not logged in" error
I am trying to use the instapaper API, but I keep getting a 403 error for my requests. Here's the code: consumer_key='...' consumer_secret='...' access_token_url = 'https://www.instapaper.com/api/1/oauth/access_token' consumer = oauth.Consumer(consumer_key, consumer_secret) client = oauth.Client(consumer) client.add_c...
[ "You're right about the signature method.\nBut my main problem was that I wasn't handling the token appropriately. Here's the working code:\nconsumer = oauth.Consumer('key', 'secret')\nclient = oauth.Client(consumer)\n\n# Get access token\nresp, content = client.request('https://www.instapaper.com/api/1/oauth/acces...
[ 4, 3 ]
[]
[]
[ "instapaper", "oauth", "python" ]
stackoverflow_0007222071_instapaper_oauth_python.txt
Q: Reading, Adding to and saving a CSV File using Python. I'm having some problems with some python scripting I've been doing. The idea of the whole script is to read a csv document containing 4 coloumns of 'friends'. Being their name, address, phone number and birthday. Now, I've written out some code already, but ...
Reading, Adding to and saving a CSV File using Python.
I'm having some problems with some python scripting I've been doing. The idea of the whole script is to read a csv document containing 4 coloumns of 'friends'. Being their name, address, phone number and birthday. Now, I've written out some code already, but having some issues. I have the code for the load_friends def...
[ "csv assumes newline between each line so the following should do all you need.\nwriter = csv.writer(open('friends.csv', 'ab')) \n..... \ndef add_friend(name, address, ph_number, birthday):\n \"\"\"write a row to the friends.csv file\n \"\"\"\n writer.writerow([name, address, ph_number, birthday])\n\...
[ 1, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007242849_csv_python.txt
Q: Session expire even if expire_on_commit=False when I use pyramid_tm Just as the title said. All I want to do is get the return id (auto generate primary key) from the session after session.add. If I commit the transaction manually without using pyramid_tm all is fine, but when I start using pyramid_tm, it seems to...
Session expire even if expire_on_commit=False when I use pyramid_tm
Just as the title said. All I want to do is get the return id (auto generate primary key) from the session after session.add. If I commit the transaction manually without using pyramid_tm all is fine, but when I start using pyramid_tm, it seems to ignore expire_on_commit. Any suggestions?
[ "It doesn't ignore expire_on_commit, it's just that the transaction isn't committed until after your code has run, so you need to flush and refresh. This is how I do it:\nthing = Thing()\nSession.add(thing)\nSession.flush()\nSession.refresh(thing)\nprint thing.id\n\n" ]
[ 2 ]
[]
[]
[ "pyramid", "python", "transactions" ]
stackoverflow_0007240778_pyramid_python_transactions.txt
Q: How to debug uncalled __del__() I use __del__() to write a warning log in case the object gets deleted while in a wrong internal state (please no wrath about it). I tried to test it but although I use del my_object in the test, the __del__() doesn't seem to be called. __del__()'s reference warns of 3 situations wh...
How to debug uncalled __del__()
I use __del__() to write a warning log in case the object gets deleted while in a wrong internal state (please no wrath about it). I tried to test it but although I use del my_object in the test, the __del__() doesn't seem to be called. __del__()'s reference warns of 3 situations where this might happen, but doesn't gi...
[ "You can change all references between the suspect objects to weakref and watch the output of the callback you provide to weakref.ref\n", "If __del__ is not being called when you invoke del myObject directly, then there is at least one other outstanding reference to myObject. I'm guessing you have stuffed it into...
[ 4, 4, 3 ]
[]
[]
[ "del", "destructor", "python" ]
stackoverflow_0007240171_del_destructor_python.txt
Q: Python decoding works for me but not others I'm sure this question has been answered somewhere, but I have no idea what to search for. My problem is not so much my problem as everyone else's. Long story short, I have a Python script with text decoding, and it decodes fine for me but fails for other users, even wit...
Python decoding works for me but not others
I'm sure this question has been answered somewhere, but I have no idea what to search for. My problem is not so much my problem as everyone else's. Long story short, I have a Python script with text decoding, and it decodes fine for me but fails for other users, even with the same code and input. I've written a script ...
[ "You could start off by giving us a sample of the PIM backup file that you can read and the German user can't read.\nThe fact that you occasionally get a UnicodeEncodeError (note Encode not Decode) is significant. Care to change you code to display the exact error message and traceback that you get, instead of supp...
[ 2 ]
[]
[]
[ "character_encoding", "encoding", "python" ]
stackoverflow_0007242275_character_encoding_encoding_python.txt
Q: Is there a way to create a function that does not need parentheses? Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers. What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:...
Is there a way to create a function that does not need parentheses?
Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers. What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with: >>>my_function arg1, arg2 instead of >>>my_function(arg1, arg2) ? I se...
[ "You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.\n\n>>> import this\n The Zen of Python, by Tim Peters \nBeautiful is better than ugly.\nExplicit is better than implicit.\n Simple is better than complex.\n Complex is better than co...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007243364_python.txt
Q: IntegrityError "Exception: Field is not unique" for a OneToOneField with unique=True in django models I have the following in models.py class Groups(models.Model): name = models.CharField(max_length=20) calls_lim = models.IntegerField(blank=True,null=True,max_length=2,unique=False) time_lim = models.Integer...
IntegrityError "Exception: Field is not unique" for a OneToOneField with unique=True in django models
I have the following in models.py class Groups(models.Model): name = models.CharField(max_length=20) calls_lim = models.IntegerField(blank=True,null=True,max_length=2,unique=False) time_lim = models.IntegerField(max_length=4,blank=True,null=True,unique=False) ivr = models.OneToOneField(ivr,unique=False) def...
[ "Intuitively I would think Groups and Users have a many to many relationship (A user can be part of many groups and a group can consist of many users). If that is the case, use a ManyToManyField instead.\nIf in your case a User can be part of only one group, the group-user relationship is one to many and thus the U...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007217617_django_django_models_python.txt
Q: How to set the parent of an entity as a property? i want to do something like this: e = Employee(key_name = 'john',name='john the first') e.put() a = Address(key_name='addr_john',street='66th street') a.parent = e; a.put(); addr = Address.gql("WHERE ANCESTOR IS :1", e).fetch(1) #len(addr)==0 But it doesn't works...
How to set the parent of an entity as a property?
i want to do something like this: e = Employee(key_name = 'john',name='john the first') e.put() a = Address(key_name='addr_john',street='66th street') a.parent = e; a.put(); addr = Address.gql("WHERE ANCESTOR IS :1", e).fetch(1) #len(addr)==0 But it doesn't works, it just works if i set the parent in the constructor....
[ "Parent for an entity can only be set during its creation, so only in a constructor of db.Model subclass instance. Attempting to assign to parent attribute of db.Model instance would result in its parent() function being overwritten, but the actual parent for corresponding datastore entity will not be changed.\nIf ...
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007243440_google_app_engine_google_cloud_datastore_python.txt
Q: Does Python optimize function calls from loops? Say, I have a code which calls some function millions time from loop and I want the code to be fast: def outer_function(file): for line in file: inner_function(line) def inner_function(line): # do something pass It's not necessarily a file proce...
Does Python optimize function calls from loops?
Say, I have a code which calls some function millions time from loop and I want the code to be fast: def outer_function(file): for line in file: inner_function(line) def inner_function(line): # do something pass It's not necessarily a file processing, it could be for example a function drawing poi...
[ "Python does not inline function calls, because of its dynamic nature. Theoretically, inner_function can do something that re-binds the name inner_function to something else - Python has no way to know at compile time this might happen. For example:\ndef func1():\n global inner_func\n inner_func = func2\n ...
[ 15, 13, 5, 3, 1 ]
[]
[]
[ "compiler_optimization", "optimization", "python" ]
stackoverflow_0007243444_compiler_optimization_optimization_python.txt
Q: Form validation and MultiValueDictKeyError Django framework. Html form. views.py script. I have a form with multiple checkboxes, the user chooses a checkbox in correspondence with what files they would like to download in a zip file. When all boxes are checked, a zip file is created and able to download however w...
Form validation and MultiValueDictKeyError
Django framework. Html form. views.py script. I have a form with multiple checkboxes, the user chooses a checkbox in correspondence with what files they would like to download in a zip file. When all boxes are checked, a zip file is created and able to download however whenever a checkbox is unchecked I get the follow...
[ "This is a standard issue with HTML forms ... on the POST an unchecked checkbox will NOT EXIST in the POST values, not have a value of 'off' as expected. So you need to check for existence:\nlogs = 0\nif request.POST.get and 'logs' in request.POST and request.POST['logs'] == \"on\":\n logs = 1\n\n" ]
[ 3 ]
[]
[]
[ "django", "python", "validation" ]
stackoverflow_0007244107_django_python_validation.txt
Q: python variable sharing between packages/modules trying to understand and learn how to write packages... testing with something i've always used, logging... Can you please help me understand why the 'log' variable is not working... and no logging is working on the screen? Thanks! main.py : #!/opt/local/bin/python ...
python variable sharing between packages/modules
trying to understand and learn how to write packages... testing with something i've always used, logging... Can you please help me understand why the 'log' variable is not working... and no logging is working on the screen? Thanks! main.py : #!/opt/local/bin/python import sys sys.path.append('CLUSTER') impo...
[ "log is a global variable in the differentlogging module. Thus you can access it as\nclusterlogging.differentlogging.log.\nYou could also do something like from clusterlogging.differentlogging import log and then access it as just log.\nEdit: actually, on reviewing your code again I don't know what to make of it. C...
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007237183_python.txt
Q: dropdown menu with sub menu in pyqt4 how to create a drop down menu with sub menus that can execute an action when the element is selected? The data of the menu's are loaded from dictionary. I've tried the menu in qpushbutton but i think there's no sub menus for it. Here is an example of what i want to do, I only ...
dropdown menu with sub menu in pyqt4
how to create a drop down menu with sub menus that can execute an action when the element is selected? The data of the menu's are loaded from dictionary. I've tried the menu in qpushbutton but i think there's no sub menus for it. Here is an example of what i want to do, I only want the sub menus, but its too complicate...
[ "You didn't say what did you do, but here's a simple example:\nfrom PyQt4 import QtGui\n\napp = QtGui.QApplication([])\n\nmenu = QtGui.QMenu()\n\nsub_menu = QtGui.QMenu(\"Sub Menu\")\n\nfor i in [\"a\", \"b\", \"c\"]: #or your dict\n sub_menu.addAction(i) #it is just a regular QMenu\n\nmenu.addMenu(sub_menu)\n\n...
[ 3 ]
[]
[]
[ "drop_down_menu", "pyqt4", "python" ]
stackoverflow_0007244056_drop_down_menu_pyqt4_python.txt
Q: Why does my file get overwritten? When using this code in python: f = open('ping.log', 'r+') f.write("["+time.ctime()+"]"+"Status") f.close() My file always gets overwritten. And only has one line in it, like this: [Fri Sep 02 16:30:56 2011]Status Why is it getting overwritten? A: It's failing because you ...
Why does my file get overwritten?
When using this code in python: f = open('ping.log', 'r+') f.write("["+time.ctime()+"]"+"Status") f.close() My file always gets overwritten. And only has one line in it, like this: [Fri Sep 02 16:30:56 2011]Status Why is it getting overwritten?
[ "It's failing because you are effectively recreating the file each time as you are overwriting the first N bytes every time. If you wrote less bytes you'd see the \"old\" information still there.\nYou need to open the file for \"append\"\n\n'a' opens the file for appending\n\nSource\n", "r+ sets the initial file ...
[ 5, 2, 2, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0007244455_file_io_python.txt
Q: Iterating within a function using for loop doesn't work? When I use for loop within a function (see below), the block of statements below the for loop is not iterated, def F(rho, m, E, v_rho, v_m, v_E): for n in xrange(N): #Update conserved quantities rho = G(Evolve_rho1(rho)) m = mome...
Iterating within a function using for loop doesn't work?
When I use for loop within a function (see below), the block of statements below the for loop is not iterated, def F(rho, m, E, v_rho, v_m, v_E): for n in xrange(N): #Update conserved quantities rho = G(Evolve_rho1(rho)) m = momentum(Evolve_m1(m)) E = Energy(Evolve_E1(E)) v_...
[ "I'm guessing your missing the difference between a global and a local vlue for N. As you've written it, the value of N in the F function will be whatever N is when F is called, not when it's defined. So if at the time F is called N==0, then the loop block will never be executed.\n", "The function was using glo...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007209722_python.txt
Q: python equivalent of perl hmac_sha1_hex i need to reproduce in python what perl does # perl perl -e'use Digest::HMAC_SHA1 qw(hmac_sha1_hex); my $hmac = hmac_sha1_hex("string1", "string2"); print $hmac . "\n";' 25afd2da17e81972b535d15ebae464e291fb3635 #python python -c 'import sha; import hmac; print hm...
python equivalent of perl hmac_sha1_hex
i need to reproduce in python what perl does # perl perl -e'use Digest::HMAC_SHA1 qw(hmac_sha1_hex); my $hmac = hmac_sha1_hex("string1", "string2"); print $hmac . "\n";' 25afd2da17e81972b535d15ebae464e291fb3635 #python python -c 'import sha; import hmac; print hmac.new("string1", "string2", sha).hexdigest(...
[ "Python's HMAC constructor just takes the key and the message in the opposite order -- Python's hmac takes the key first, Perl's Digest::HMAC takes the key second.\npython -c 'import sha; import hmac; print hmac.new(\"string2\", \"string1\", sha).hexdigest()'\n25afd2da17e81972b535d15ebae464e291fb3635\n\nMatches you...
[ 10 ]
[]
[]
[ "hmac", "perl", "python", "sha1" ]
stackoverflow_0007245157_hmac_perl_python_sha1.txt
Q: Cannot call klipper methods in dbus with python I try to call methods from klipper bus with python. But I could not make it. Here is what i try: >>> import dbus >>> bus = dbus.SessionBus() >>> proxy = bus.get_object("org.kde.klipper","/org/kde/klipper") >>> print proxy <ProxyObject wrapping <dbus._dbus.SessionBus ...
Cannot call klipper methods in dbus with python
I try to call methods from klipper bus with python. But I could not make it. Here is what i try: >>> import dbus >>> bus = dbus.SessionBus() >>> proxy = bus.get_object("org.kde.klipper","/org/kde/klipper") >>> print proxy <ProxyObject wrapping <dbus._dbus.SessionBus (session) at 0x7fc249da3bf0> :1.67 /org/kde/klipper a...
[ "After some try, I found the the mistake:\n>>> proxy = bus.get_object(\"org.kde.klipper\",\"/org/kde/klipper\") \nmust be: \n>>> proxy = bus.get_object(\"org.kde.klipper\",\"/klipper\") \nthis solved the problem\n", "Looks quite scarry. It might be simpler to call qdbus through bash:\nimport os\nsystem(\"qdbus or...
[ 1, 0 ]
[]
[]
[ "dbus", "python" ]
stackoverflow_0005156549_dbus_python.txt
Q: tarfile and user,group information problem I am using python tarfile module to extract files from a *.tgz file. Here what I use: import tarfile tar = tarfile.open("some.tar") tar.extractall(".") tar.close() Assume "some.tar" contents as: -a.txt ===> user:usr1 , group: grp1 -b.txt ===> user:usr2 , group: grp2 But...
tarfile and user,group information problem
I am using python tarfile module to extract files from a *.tgz file. Here what I use: import tarfile tar = tarfile.open("some.tar") tar.extractall(".") tar.close() Assume "some.tar" contents as: -a.txt ===> user:usr1 , group: grp1 -b.txt ===> user:usr2 , group: grp2 But after extracting I lose all of user,group,date....
[ "First, your script needs to run as root (on unix like systems). Otherwise, you can't use chown.\nYou need to get the TarInfo object for the files:\nhttp://docs.python.org/library/tarfile.html#tarfile.TarInfo\nThere you get uid (user id) and gid (group id) and (or user name).\nThen you need to use chown.\n", "As ...
[ 0, 0 ]
[]
[]
[ "python", "tarfile" ]
stackoverflow_0007245338_python_tarfile.txt
Q: pyqt gui application packaging for ubuntu I am really new to packaging. I have developed a music player using pyqt in ubuntu. It has a gui and it uses sqlite database. I have looked at distutil. What I understood is how to place modules and scripts in right place. What I don't understand is how to set paths for da...
pyqt gui application packaging for ubuntu
I am really new to packaging. I have developed a music player using pyqt in ubuntu. It has a gui and it uses sqlite database. I have looked at distutil. What I understood is how to place modules and scripts in right place. What I don't understand is how to set paths for database, config files & log files. How do I achi...
[ "You can use QDir.home() to get the absolute path to a user's home path. You can use this path when generating/accessing your database, config files and log files. For example, on first startup you can do something like:\nfilePath = QDir.home() + \"/.application_name\"\nif not QDir.exists(filepath)\n QDir.mkdir(...
[ 1 ]
[]
[]
[ "packaging", "pyqt", "python", "qt", "ubuntu" ]
stackoverflow_0007240844_packaging_pyqt_python_qt_ubuntu.txt
Q: Regular expression capturing entire match consisting of repeated groups I've looked thrould the forums but could not find exactly how exactly to solve my problem. Let's say I have a string like the following: UDK .636.32/38.082.4454.2(575.3) and I would like to match the expression with a regex, capturing the a...
Regular expression capturing entire match consisting of repeated groups
I've looked thrould the forums but could not find exactly how exactly to solve my problem. Let's say I have a string like the following: UDK .636.32/38.082.4454.2(575.3) and I would like to match the expression with a regex, capturing the actual number (in this case the '.636.32/38.082.4454.2(575.3)'). There could ...
[ "First, you need a non-greedy .*?.\nSecond, you don't need to escape some chars in [ ].\nThird, you might just consider it as a sequence of digits AND some allowed characters? Why there is a \\d{1,3} but a 4454?\n>>> re.match(r'UDK.*?([\\d.,()\\[\\]=\\':\"+/-]+)', s).group(1)\n'.636.32/38.082.4454.2(575.3)'\n\n", ...
[ 5, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007244736_python_regex.txt
Q: Delete or remove last column in CSV file using Python I have a CSV file with 5 columns. Using Python, how can I delete the last column (header5 in the example)? Is there an easy way I'm missing, or do I have to loop through all rows in the CSV and remove each value from the last column (which could still leave me ...
Delete or remove last column in CSV file using Python
I have a CSV file with 5 columns. Using Python, how can I delete the last column (header5 in the example)? Is there an easy way I'm missing, or do I have to loop through all rows in the CSV and remove each value from the last column (which could still leave me with the undesired preceding comma)? I'm not seeing anythin...
[ "Use the csv module. When writing out a row, use row[:-1] to chop off the last item:\nimport csv\n\nwith open(filename,\"r\") as fin:\n with open(outname,\"w\") as fout:\n writer=csv.writer(fout)\n for row in csv.reader(fin):\n writer.writerow(row[:-1])\n\n", "Even if you don't use CSV...
[ 16, 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007245738_csv_python.txt