content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: how to create regular expression in python Regular expression for removing all lines between #if X and #endif //#if X Note the C style comment is important and needs to be taken into account #if X .... ..... #endif //#if X The following is not giving desired o/p: So is the re right ? re.compile("#if.*?#endif //#...
how to create regular expression in python
Regular expression for removing all lines between #if X and #endif //#if X Note the C style comment is important and needs to be taken into account #if X .... ..... #endif //#if X The following is not giving desired o/p: So is the re right ? re.compile("#if.*?#endif //#if X", re.MULTILINE + re.DOTALL)
[ "So far, you have just compiled your regex, you haven't done anything with it yet.\nYou need to do this:\nmyregex = re.compile(r\"#if.*?#endif //#if X\", re.DOTALL)\nresult = myregex.sub(\"\", subject)\n\nwhere subject is the string you want to work on (and \"\" is the replacement string).\nYou don't need the re.MU...
[ 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005457995_python_regex.txt
Q: Python find closest decimal match I have a list as follows: CHOICES = ( ('8.25', '0'), ('7.35', '1'), [...] ) The model I use stores the first value in the tuple (e.g. 8.25 -incidentally, in mm). I need a function that takes any given decimal value (potentially not in the list) and matches it with the...
Python find closest decimal match
I have a list as follows: CHOICES = ( ('8.25', '0'), ('7.35', '1'), [...] ) The model I use stores the first value in the tuple (e.g. 8.25 -incidentally, in mm). I need a function that takes any given decimal value (potentially not in the list) and matches it with the closest value on the CHOICES list, to ...
[ "Unless your values are sorted and assuming the number of the choices is not huge:\nresult = sorted([(math.abs(k - input_val),v) for (k,v) in choices])[0]\n\nOtherwise sort the choices once and use binary search (bisect), as suggested in other answer. It'd look like:\n#do this part only once\nchoices_dict = dict(ch...
[ 4, 2, 0 ]
[]
[]
[ "decimal", "django", "django_models", "python" ]
stackoverflow_0005457523_decimal_django_django_models_python.txt
Q: stdin seems much slower than stdout (python). Why? I have two python programs (one is a subprocess) that need to communicate with each other. Currently I am doing that through stdin and stdout. However, writing to the subprocess's stdin seems painfully slow. a.py, a program that takes an arbitrary line of input ...
stdin seems much slower than stdout (python). Why?
I have two python programs (one is a subprocess) that need to communicate with each other. Currently I am doing that through stdin and stdout. However, writing to the subprocess's stdin seems painfully slow. a.py, a program that takes an arbitrary line of input and prints the time: from time import time, sleep from s...
[ "I'd see if you can reproduce this when disabling buffering on both input and output. I have a hunch that output is being (line) buffered by default (as it is in most languages: perl, .NET, C++ iostreams)\n", "If I try this a few times, the variance of the numbers is very high.\nMaybe you should set up a more san...
[ 1, 0 ]
[]
[]
[ "io", "python", "stdio" ]
stackoverflow_0005387979_io_python_stdio.txt
Q: how to get the value of json data using python this is my code : a = '''{"title":"sss","body":"wwww:aaa&nbsp;&nbsp;&nbsp; <a href='#' onclick='logout()' >fff</a> ","data":{"status":0,"userName":"www","userId":"433"}}''' a = eval(a) print a.title but it show error : so what can i do , thanks A: You sh...
how to get the value of json data using python
this is my code : a = '''{"title":"sss","body":"wwww:aaa&nbsp;&nbsp;&nbsp; <a href='#' onclick='logout()' >fff</a> ","data":{"status":0,"userName":"www","userId":"433"}}''' a = eval(a) print a.title but it show error : so what can i do , thanks
[ "You should use a JSON parser such as the simplejson module rather than using eval:\n>>> a = '''{\"title\":\"sss\",\n\"body\":\"wwww:aaa&nbsp;&nbsp;&nbsp;<a href='#' onclick='logout()' >fff</a>\",\n\"data\":{\"status\":0,\"userName\":\"www\",\"userId\":\"433\"}}'''\n>>> import simplejson\n>>> parsed_data = simplejs...
[ 6, 0, 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0005458873_json_python.txt
Q: Run custom Python script before appcfg.py update runs Is that possible to run some Python script every time I run deployment process with appcfg.py? I need that to copy some files from external source to my app folder before uploading it to GAE. Thanks! A: I checked briefly the sources of appcfg.py, the script t...
Run custom Python script before appcfg.py update runs
Is that possible to run some Python script every time I run deployment process with appcfg.py? I need that to copy some files from external source to my app folder before uploading it to GAE. Thanks!
[ "I checked briefly the sources of appcfg.py, the script that deploys the application to Google App Engine, but I didn't find a place where a pre-deploy hook can be defined.\nI believe that modifying appcfg.py itself would me not mantainable and a bit overkill.\nYou should create a simple deployment script and call ...
[ 3 ]
[]
[]
[ "deployment", "google_app_engine", "python" ]
stackoverflow_0005457434_deployment_google_app_engine_python.txt
Q: Django query question I have a view & template which displays a list of types of items. This is ok, but instead of displaying all different the types of items for that client. What I want to do is display the list of types individually. For example, if an Item has a type stored say "General". I want to display all...
Django query question
I have a view & template which displays a list of types of items. This is ok, but instead of displaying all different the types of items for that client. What I want to do is display the list of types individually. For example, if an Item has a type stored say "General". I want to display all items that has a type only...
[ "Sounds like you want to regroup on type.\n", "You can try `client.storageitem_set.filter(type=YOUR_TYPE):\ndef client_summary(request, client_id):\n client = None\n items = None\n try:\n client = models.Client.objects.get(pk = client_id)\n items = client.storageitem_set.filter(type=\"Gener...
[ 8, 1 ]
[]
[]
[ "django", "html", "models", "python" ]
stackoverflow_0005459051_django_html_models_python.txt
Q: Python: Clustering Search Engine Keywords Python: Clustering Search Engine Keywords Hi, I have a CSV, up to 20,000 rows (I have had 100,000+ for different websites), each row containing a referring keyword (i.e. a keyword someone typed into a search engine to find the website in question), and a number of visits...
Python: Clustering Search Engine Keywords
Python: Clustering Search Engine Keywords Hi, I have a CSV, up to 20,000 rows (I have had 100,000+ for different websites), each row containing a referring keyword (i.e. a keyword someone typed into a search engine to find the website in question), and a number of visits. What I'm looking to do is cluster these keywo...
[ "I like Woosh a lot. It is a pure python search engine that provides, among other things, that kind of functionality. Check it out.\nhttp://packages.python.org/Whoosh/index.html\nThe feature that you are looking is call \"faceted search results\"\nhttp://packages.python.org/Whoosh/facets.html\nHernan\n", "Well I ...
[ 2, 0 ]
[]
[]
[ "cluster_analysis", "keyword", "nlp", "python", "text" ]
stackoverflow_0005457993_cluster_analysis_keyword_nlp_python_text.txt
Q: How to make a module accessible for all applications including GAE deployment process I have a Python module containing some utils that all my GAE applications may use. I created it myself. It is n a separate folder and I sometimes want to update its code, make refactorings etc. Every application I create, can tak...
How to make a module accessible for all applications including GAE deployment process
I have a Python module containing some utils that all my GAE applications may use. I created it myself. It is n a separate folder and I sometimes want to update its code, make refactorings etc. Every application I create, can take use functions from this module. Now I need to copy the module folder somewhere inside an ...
[ "You can store your module in a directory outside all your GAE apps and then create a symbolic link to that directory inside all the GAE apps directories. appcfg.py will follow the symbolic link. Quoting from the Python SDK docs:\n\nIf you make a symbolic link to a module's directory in your application directory, ...
[ 4 ]
[]
[]
[ "deployment", "gae_module", "google_app_engine", "module", "python" ]
stackoverflow_0005456564_deployment_gae_module_google_app_engine_module_python.txt
Q: Django/Python How should this cronjob be executed I created a simple python script that allows me to update a chosen animal to be displayed on the sites frontpage. when I am in my ssh, I run it like this. cd /www/site/mydirectory python perform_daily_action.py How do I run this in my crontab as a cronjob. I tried...
Django/Python How should this cronjob be executed
I created a simple python script that allows me to update a chosen animal to be displayed on the sites frontpage. when I am in my ssh, I run it like this. cd /www/site/mydirectory python perform_daily_action.py How do I run this in my crontab as a cronjob. I tried to do 30 09 * * * cd /www/site/mydirect...
[ "The other answers are great, I would only suggest using full path also for Python interpreter, because cron environment might be different than the regular one and also at some point you might want to switch to virtualenv and then you will definitely need Python interpreter from virtualenv folder.\n", "Try use t...
[ 3, 2, 1 ]
[]
[]
[ "apache2", "cron", "crontab", "django", "python" ]
stackoverflow_0005455425_apache2_cron_crontab_django_python.txt
Q: how to print this number in a shortest time using thread in python this is my code : import thread k=0 b=0 def a(n): i = 0 while i<n: print i i += 1 j = 5000 while k < 5000: a(k) k+=1 for n in range(2,5): thread.start_new_thread(a,(j*n,)) and i want to Run three threads and ...
how to print this number in a shortest time using thread in python
this is my code : import thread k=0 b=0 def a(n): i = 0 while i<n: print i i += 1 j = 5000 while k < 5000: a(k) k+=1 for n in range(2,5): thread.start_new_thread(a,(j*n,)) and i want to Run three threads and a main thread, the main thread print 1,2,3,4,5,....5000 and the thread1 ...
[ "You should use threading instead of thread, since it's easier to implement and it works in almost every case. Now your code will be like:\nimport threading \n\nclass PrintNumber(Thread):\n def __init__(self, n):\n self.n = n\n\n def run(self):\n for i in range(n, n+5000):\n print i\n\n# create your th...
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005459220_multithreading_python.txt
Q: fastest way to arrange data in python numpy based on list I have problem in arrange data in numpy example a have list of data range : numpy.array([1,3,5,4,6]) and I have data : numpy.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]) and I need the data to be arrange to numpy.array([ [1,9999,9999,9999,99...
fastest way to arrange data in python numpy based on list
I have problem in arrange data in numpy example a have list of data range : numpy.array([1,3,5,4,6]) and I have data : numpy.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]) and I need the data to be arrange to numpy.array([ [1,9999,9999,9999,9999,9999,9999] [2,3,4,9999,9999,9999] [5,6,7,8,9,9999] [10,11...
[ "Here are some ways to arrange the data:\nfrom numpy import arange, array, ones, r_, zeros\nfrom numpy.random import randint\n\ndef gen_tst(m, n):\n a= randint(1, n, m)\n b, c= arange(a.sum()), ones((m, n), dtype= int)* 999\n return a, b, c\n\ndef basic_1(a, b, c):\n # some assumed basic iteration based...
[ 3, 1, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0005456194_arrays_numpy_python.txt
Q: ImportError on only one of my two identical sites I have two websites, that are "almost" clones of one another. Well, in fact, they're supposed to be full clones (both have the same source code & config, point to the same database). I am able to work with one of these sites without any problems, yet I'm getting th...
ImportError on only one of my two identical sites
I have two websites, that are "almost" clones of one another. Well, in fact, they're supposed to be full clones (both have the same source code & config, point to the same database). I am able to work with one of these sites without any problems, yet I'm getting this error when accessing the other one. There must be so...
[ "Looks like you are missing a settings_local.py that must be being imported by your settings.\n" ]
[ 3 ]
[]
[]
[ "apache", "django", "python", "ubuntu" ]
stackoverflow_0005458938_apache_django_python_ubuntu.txt
Q: Python - Parse a string with custom price units What is fastest way to parse a string to int in Python? The string may include custom units, such as "k" (kilo), "m" (million), or "b" (billion). For example: 100 -> 100 100k -> 100000 100m -> 100000000 100b -> 100000000000 Thanks. A: def convert(val): lookup...
Python - Parse a string with custom price units
What is fastest way to parse a string to int in Python? The string may include custom units, such as "k" (kilo), "m" (million), or "b" (billion). For example: 100 -> 100 100k -> 100000 100m -> 100000000 100b -> 100000000000 Thanks.
[ "def convert(val):\n lookup = {'k': 1000, 'm': 1000000, 'b': 1000000000}\n unit = val[-1]\n try:\n number = int(val[:-1])\n except ValueError:\n # do something\n if unit in lookup:\n return lookup[unit] * number\n return int(val)\n\n>>> print convert(\"100m\")\n>>> 100000000\n...
[ 7, 2, 1, 0 ]
[]
[]
[ "parsing", "python", "string" ]
stackoverflow_0005459256_parsing_python_string.txt
Q: Dendrogram generated by scipy-cluster customisation This is a follow up to Dendrogram generated by scipy-cluster does not show. from matplotlib.pyplot import show from scipy.spatial.distance import pdist from scipy.cluster.hierarchy import linkage, dendrogram from numpy.random import rand X = rand( 5, 3 ) X[0:5,...
Dendrogram generated by scipy-cluster customisation
This is a follow up to Dendrogram generated by scipy-cluster does not show. from matplotlib.pyplot import show from scipy.spatial.distance import pdist from scipy.cluster.hierarchy import linkage, dendrogram from numpy.random import rand X = rand( 5, 3 ) X[0:5, :] *= 2 Y = pdist( X ) Z = linkage( Y ) dendrogram( Z ) ...
[ "According the dendrogram documentation, you should be able to define labels when you are calling it (either via labels or leaf_label_func args). So there is no need to try to tamper afterwards with labels.\n" ]
[ 3 ]
[]
[]
[ "dendrogram", "matplotlib", "python", "scipy" ]
stackoverflow_0005459341_dendrogram_matplotlib_python_scipy.txt
Q: How can I get virtualenv to produce Python executables with the correct sys.path using the Enthought Python Distribution? I installed the Enthought Python Distribution version 7.0 on a Mac, then easy_installed pip, then did pip install virtualenv. When I try to create a virtual environment, I get: > virtualenv tes...
How can I get virtualenv to produce Python executables with the correct sys.path using the Enthought Python Distribution?
I installed the Enthought Python Distribution version 7.0 on a Mac, then easy_installed pip, then did pip install virtualenv. When I try to create a virtual environment, I get: > virtualenv test New python executable in test/bin/python ERROR: The executable test/bin/python is not functioning ERROR: It thinks sys.prefix...
[ "This question was discussed on the EPD developers mailing list.\nAmong others it was mentioned that EPD was not put together with virtualenv in mind and that it has it's bugs sometimes.\nHowever, somebody posted a link to a summarized solution which I'm trying out myself now:\nhttps://gist.github.com/845545\nHTH,\...
[ 6 ]
[]
[]
[ "enthought", "python", "virtualenv" ]
stackoverflow_0005044601_enthought_python_virtualenv.txt
Q: Inject the revision number in sourcecode (TortoiseSvn or SVN Shell) I would like to inject the revision number in source code on commit. I found out that I could do it through svn shell by doing something like: find . -name *.php -exec svn propset svn:keywords "Rev" However someone else said that that would not w...
Inject the revision number in sourcecode (TortoiseSvn or SVN Shell)
I would like to inject the revision number in source code on commit. I found out that I could do it through svn shell by doing something like: find . -name *.php -exec svn propset svn:keywords "Rev" However someone else said that that would not work as there are no files in the repository (as they files are encrypted)...
[ "Don't write your own method for injecting version numbers. Instead,\n\nonly introduce the replaced tags $Revision$, etc.) in the files you want the replacement to happen for\nonly enable replacement (using svn propset svn:keywords Revision or some such) for those files\n\n" ]
[ 4 ]
[]
[]
[ "perl", "python", "svn", "tortoisesvn", "version_control" ]
stackoverflow_0005459391_perl_python_svn_tortoisesvn_version_control.txt
Q: Low volume Open source Message Board suggestions? Looking for a low volume, probably no more that 20-30 users, Open Source message/bulletin board. Obviously must be written in something which our web server supports, PHP/Python/Ruby etc. Any suggestions? Thanks, Nick A: FUDForum phpBB and lots more. The abo...
Low volume Open source Message Board suggestions?
Looking for a low volume, probably no more that 20-30 users, Open Source message/bulletin board. Obviously must be written in something which our web server supports, PHP/Python/Ruby etc. Any suggestions? Thanks, Nick
[ "\nFUDForum\nphpBB\n\nand lots more. The above are designed to handle very large boards, but can be used with low traffic websites. All PHP\n", "PhpBB http://en.wikipedia.org/wiki/PhpBB free and open Source, requires MySQL. Great for running on run-of-the-mill LAMP configurations. \n", "I would use Vanilla foru...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "html", "php", "python", "ruby" ]
stackoverflow_0005459896_html_php_python_ruby.txt
Q: Segmentation fault in Prime Number generator I am aware the following isn't the fastest way of generating a list of primes however I posed myself the problem and before googling wrote the following program. It works fine for numbers < ~ 44,000 but then gives a segmentation fault when ran on my 2Ghz Core 2 Duo Macb...
Segmentation fault in Prime Number generator
I am aware the following isn't the fastest way of generating a list of primes however I posed myself the problem and before googling wrote the following program. It works fine for numbers < ~ 44,000 but then gives a segmentation fault when ran on my 2Ghz Core 2 Duo Macbook. I am not really interested in alternative met...
[ "You might be getting stack overflow from too many recusive calls on the stack. At 42751 you would have a 21375 depth function call stack. In such case, refining your method might actually be needed.\nA handy little routine which will check primeness can be written like this (pseudocode):\nif n < 2 return false;\ni...
[ 4, 0, 0, 0, 0, 0 ]
[]
[]
[ "primes", "python", "segmentation_fault" ]
stackoverflow_0003885793_primes_python_segmentation_fault.txt
Q: Does Python use NFAs for regular expression evaluation in the re module? Does anybody know if Python (any version) used NFAs (Non-Deterministic Finite Automata) to evaluate regular expressions or does it use some other mechanism? Please provide links/reference if available. A: This should take less than a ms on...
Does Python use NFAs for regular expression evaluation in the re module?
Does anybody know if Python (any version) used NFAs (Non-Deterministic Finite Automata) to evaluate regular expressions or does it use some other mechanism? Please provide links/reference if available.
[ "This should take less than a ms on a DFA:\n$ time python3 -c 'import re; re.match(\"a?\"*25+\"a\"*25, \"a\"*25)'\nreal 0m7.273s\n\nChange 25 with 100 and it won't terminate for a lifetime.\nHere is how it looks on a DFA (grep):\n$ time echo \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
[ 8, 6 ]
[]
[]
[ "nfa", "python", "regex" ]
stackoverflow_0001748853_nfa_python_regex.txt
Q: Getting command line arguments as tuples in python Here is an example of how I would like to call my script: python script.py -f file1.txt "string1" "string2" -f file2.txt "string3" "string4" Every file that goes as input will have 2 strings associated with that file. There can be any number of files. To simplify...
Getting command line arguments as tuples in python
Here is an example of how I would like to call my script: python script.py -f file1.txt "string1" "string2" -f file2.txt "string3" "string4" Every file that goes as input will have 2 strings associated with that file. There can be any number of files. To simplify, I am trying to get a print like this: ('file1.txt', 's...
[ "I think you want to use the action=append argument of the add_argument method\nimport argparse\n\nparser= argparse.ArgumentParser()\nparser.add_argument ('-f', '--file', nargs=3, action='append')\n\nfiles = parser.parse_args('-f file1 string1 string2 -f file2 string3 string4 -f file3 string5 string6'.split()).file...
[ 13, 1, 0, 0, 0 ]
[]
[]
[ "command_line_arguments", "optparse", "python" ]
stackoverflow_0005372697_command_line_arguments_optparse_python.txt
Q: Pywin - Initialize pvarResult by calling the VariantInit() I'm using Pywin32 to communicate with Bloomberg through its COM-library. This works rather good! However, I have stumbeled upona a problem which I consider pretty complex. If I set the property QueueEvents of the Com object to True I the program fails. ...
Pywin - Initialize pvarResult by calling the VariantInit()
I'm using Pywin32 to communicate with Bloomberg through its COM-library. This works rather good! However, I have stumbeled upona a problem which I consider pretty complex. If I set the property QueueEvents of the Com object to True I the program fails. In the documentation they have a section regarding this, If yo...
[ "I'm not sure if this will help for your issue, but to have working COM events in Python you shouldn't forget about:\n\nsetting COM apartment to free\nthreaded at the beginning of script\nfile. This could be done using\nfollowing lines\nimport sys\nsys.coinit_flags = 0\n\ngenerating wrapper for com library before c...
[ 1 ]
[]
[]
[ "bloomberg", "com", "python", "pywin32" ]
stackoverflow_0005456458_bloomberg_com_python_pywin32.txt
Q: python: check if IP or DNS how can one check if variable contains DNS name or IP address in python ? A: This will work. import socket host = "localhost" if socket.gethostbyname(host) == host: print "It's an IP" else: print "It's a host name" A: You can use re module of Python to check if the contents o...
python: check if IP or DNS
how can one check if variable contains DNS name or IP address in python ?
[ "This will work.\nimport socket\nhost = \"localhost\"\nif socket.gethostbyname(host) == host:\n print \"It's an IP\"\nelse:\n print \"It's a host name\"\n\n", "You can use re module of Python to check if the contents of the variable is a ip address.\nExample for the ip address :\nimport re\n\nmy_ip = \"192....
[ 11, 8, 2, 0 ]
[]
[]
[ "dns", "ip", "python", "regex" ]
stackoverflow_0005461322_dns_ip_python_regex.txt
Q: Create client/server with Twisted I'm trying to create a client/server using Twisted. I'd like to create a daemon, which will be connected to another server as a client and act as a server for other clients. I've writen something like that which I think describes my problem: server = sys.argv[1] control_port = 800...
Create client/server with Twisted
I'm trying to create a client/server using Twisted. I'd like to create a daemon, which will be connected to another server as a client and act as a server for other clients. I've writen something like that which I think describes my problem: server = sys.argv[1] control_port = 8001 class ControlClient(protocol.Protoco...
[ "The only thing you seem to be missing is that you can keep a list of your client connections and make that list available to the code that's trying to send out data to all the clients.\nThere's an example of this in the Twisted FAQ: http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeco...
[ 3 ]
[]
[]
[ "client", "python", "twisted" ]
stackoverflow_0005459998_client_python_twisted.txt
Q: wxPython panel redraw in windows I am trying to make several different pages where I need to show different texts and buttons. What I did was I created a panel, and then several sizers on it, and then in the next page, I destroyed the panel and recreated the panel again with different contents/sizers. It worked we...
wxPython panel redraw in windows
I am trying to make several different pages where I need to show different texts and buttons. What I did was I created a panel, and then several sizers on it, and then in the next page, I destroyed the panel and recreated the panel again with different contents/sizers. It worked well in Linux, but when I tried the same...
[ "Calling Layout on the widget's parent is the best way to do this is you are adding or destroying widgets. Sometimes you also need to call Refresh() to make it redraw too, although that might only be required when you're using Freeze/Thaw.\n", "It seems there are better ways to do this, but panel.Layout() solved ...
[ 4, 2, 1 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0005457644_python_user_interface_wxpython.txt
Q: python: iterate using a class method I'm still digging in python, and there are a few things that my C++ background is getting in the way. For example, I have a class class crack(object): def __init__(self, sz1,sz2): self.z1 = sz1 self.z2 = sz2 def smallz_Z(self,z,z1,z2): return z - ...
python: iterate using a class method
I'm still digging in python, and there are a few things that my C++ background is getting in the way. For example, I have a class class crack(object): def __init__(self, sz1,sz2): self.z1 = sz1 self.z2 = sz2 def smallz_Z(self,z,z1,z2): return z - 0.5*(z2-z1) def get_pot(self,z): ...
[ "Object to be iterable needs to have __iter__() method, which returns an iterator (or sequence). Iterator should implement method next(), which will yield elements or raise StopIteration is there are no more elements. As simple as that.\n", "First, I don't see that your get_pot method returns anything. It should...
[ 5, 1, 1, 1 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0005460657_matplotlib_numpy_python.txt
Q: returned dictionary value is 'None' python I have a function in a file which I am calling in a separate script (as shown below). Printing directly from the function works correctly, however when I try to return the value to the script it sends 'None'. Any help would be appreciated. Thanks script: import modules.fu...
returned dictionary value is 'None' python
I have a function in a file which I am calling in a separate script (as shown below). Printing directly from the function works correctly, however when I try to return the value to the script it sends 'None'. Any help would be appreciated. Thanks script: import modules.functions as f restype = 'THR' atomtype = 'CA' p...
[ "Here's a guess: AtomType calls threonine, but doesn't return its return value.\n" ]
[ 2 ]
[]
[]
[ "dictionary", "python", "return_value" ]
stackoverflow_0005461840_dictionary_python_return_value.txt
Q: What's so cool about Twisted? I'm increasingly hearing that Python's Twisted framework rocks and other frameworks pale in comparison. Can anybody shed some light on this and possibly compare Twisted with other network programming frameworks. A: There are a lot of different aspects of Twisted that you might find ...
What's so cool about Twisted?
I'm increasingly hearing that Python's Twisted framework rocks and other frameworks pale in comparison. Can anybody shed some light on this and possibly compare Twisted with other network programming frameworks.
[ "There are a lot of different aspects of Twisted that you might find cool.\nTwisted includes lots and lots of protocol implementations, meaning that more likely than not there will be an API you can use to talk to some remote system (either client or server in most cases) - be it HTTP, FTP, SMTP, POP3, IMAP4, DNS, ...
[ 134, 9 ]
[]
[]
[ "comparison", "python", "twisted" ]
stackoverflow_0005458631_comparison_python_twisted.txt
Q: Python Twisted: twisted conch filetransfer verifyHostKey I playing around with the sftp example from here: Stackoverflow: twisted conch filetransfer I am using this here to connect. So I can use a key from a string instead of a password or the keys in ~/.shh. Now I want to deliver a hostkey or a fingerprint from a...
Python Twisted: twisted conch filetransfer verifyHostKey
I playing around with the sftp example from here: Stackoverflow: twisted conch filetransfer I am using this here to connect. So I can use a key from a string instead of a password or the keys in ~/.shh. Now I want to deliver a hostkey or a fingerprint from a hostkey to avoid to prompt the user to verify the hostkey def...
[ "\nI tried to give some arguments to verifyHostkey\n\nAre you saying you tried calling verifyHostKey yourself? It sounds like that's not going to help you avoid prompting the user for unknown host keys. Instead, you want to pass a different function for that parameter to connect. Instead of using the verifyHostK...
[ 3 ]
[]
[]
[ "python", "sftp", "twisted" ]
stackoverflow_0005457422_python_sftp_twisted.txt
Q: How do I delete a foreign key constraint in SQLAlchemy? I'm using SQLAlchemy Migrate to keep track of database changes and I'm running into an issue with removing a foreign key. I have two tables, t_new is a new table, and t_exists is an existing table. I need to add t_new, then add a foreign key to t_exists. T...
How do I delete a foreign key constraint in SQLAlchemy?
I'm using SQLAlchemy Migrate to keep track of database changes and I'm running into an issue with removing a foreign key. I have two tables, t_new is a new table, and t_exists is an existing table. I need to add t_new, then add a foreign key to t_exists. Then I need to be able to reverse the operation (which is wher...
[ "You can do it with sqlalchemy.migrate.\nIn order to make it work, I have had to create the foreign key constraint explicitly rather than implicitely with Column('fk', ForeignKey('fk_table.field')):\nAlas, instead of doing this:\np2 = Table('tablename',\n metadata,\n Column('id', Integer, prim...
[ 7, 3, 0 ]
[ "Well, you can achieve this in sqlalchemy: just drop() the all the constraints before you drop() the column (theoretically, you might have multiple constraints):\ndef drop_column(column):\n for fk in column.table.foreign_keys:\n if fk.column == column:\n print 'deleting fk ', fk\n fk...
[ -1 ]
[ "foreign_keys", "mysql", "mysql_error_1025", "python", "sqlalchemy" ]
stackoverflow_0002427199_foreign_keys_mysql_mysql_error_1025_python_sqlalchemy.txt
Q: Single installation, multiple domains and apps? I am planning to use Django for a multi-site project, where each site is mostly independent, but would share a few models across all the sites. I am wondering if there is a way to make each Django 'app' it's own site, complete with unique domain name, and still allo...
Single installation, multiple domains and apps?
I am planning to use Django for a multi-site project, where each site is mostly independent, but would share a few models across all the sites. I am wondering if there is a way to make each Django 'app' it's own site, complete with unique domain name, and still allow each site to access a common app that contains some...
[ "Re. your update: You don't need to fake the URL structure like that, unless you also want URLs like mainsite.com/secondarysite to be directly available to the user.\nI'll assume you're using name-based virtual hosting. One simple but very flexible approach would be to have each <VirtualHost> directive invoke a di...
[ 6, 0 ]
[]
[]
[ "django", "python", "single_sign_on" ]
stackoverflow_0005275082_django_python_single_sign_on.txt
Q: Adding to a date, checking if past expiration date One part of my program requires that the user enters a date and this date is then checked against each product in the dictionary to see if the date the product arrived plus its shelf life causes the product to expire before or after the date entered by the user. i...
Adding to a date, checking if past expiration date
One part of my program requires that the user enters a date and this date is then checked against each product in the dictionary to see if the date the product arrived plus its shelf life causes the product to expire before or after the date entered by the user. import sys from string import * import pickle import date...
[ "If I understand correctly, you need to transform strings representing dates in the format \"dd/mm/yyyy\" into datetime objects?\nIf so, you should use the datetime.strptime method. For example:\nfrom datetime import datetime\nd = datetime.strptime(\"28/03/2011\", \"%d/%m/%Y\")\nprint repr(d)\n\nThis prints:\ndatet...
[ 1, 1, 0 ]
[]
[]
[ "date", "datetime", "dictionary", "python" ]
stackoverflow_0005453331_date_datetime_dictionary_python.txt
Q: Using Python object exported from DLL in an exe I have a two-part event generator: pyglobalexe (a stub to simulate events): #pragma comment(lib, "pyglobalextension.lib") #include <Python.h> __declspec(dllimport) PyObject* PyInit_pyglobalextension; __declspec(dllimport) PyObject* event_queue; int main() { in...
Using Python object exported from DLL in an exe
I have a two-part event generator: pyglobalexe (a stub to simulate events): #pragma comment(lib, "pyglobalextension.lib") #include <Python.h> __declspec(dllimport) PyObject* PyInit_pyglobalextension; __declspec(dllimport) PyObject* event_queue; int main() { int i; for(i=0; i<10; i++) { PyObject_CallM...
[ "\nevent_queue will be NULL, because nothing has called set_queue before you do CallMethod.\nPyInit_... is a function, not a variable; and you don't call it, so the module and the set_queue don't even exist.\n\nAd. edit:\nAbove still stands. What you're doing requires interprocess communication, simple global varia...
[ 2 ]
[]
[]
[ "c", "python", "python_extensions" ]
stackoverflow_0005462710_c_python_python_extensions.txt
Q: Update Two Related Files On Disk In a "Secure" Way? I have two binary files that are related one to another (meaning, when one file's records are updated, the other file's matching records should be updated as well). both files are binary files stored on disk. The updation will look something like this: UpdateFirs...
Update Two Related Files On Disk In a "Secure" Way?
I have two binary files that are related one to another (meaning, when one file's records are updated, the other file's matching records should be updated as well). both files are binary files stored on disk. The updation will look something like this: UpdateFirstFile() -- first file is updated..... UpdateSecondFile() ...
[ "The generic approach would be to implement transactions with some kind of rollback journal.\nFor example you could use a separate file to record the current contents of each part in each file that will be affected by the update. After your transaction is done, you remove the journal file.\nThe mere presence of the...
[ 4, 2, 0 ]
[]
[]
[ "atomic", "binary", "linux", "python" ]
stackoverflow_0005453101_atomic_binary_linux_python.txt
Q: wxpython: How to fill the inside of a checkbox in a listctrl object with a given rgb color? I have this chart. In this chart I have a bunch of countries. I am trying to create the legends inside a listctrl object by changing the color of a non-functional checkbox. Is there any wxpython function to change such attr...
wxpython: How to fill the inside of a checkbox in a listctrl object with a given rgb color?
I have this chart. In this chart I have a bunch of countries. I am trying to create the legends inside a listctrl object by changing the color of a non-functional checkbox. Is there any wxpython function to change such attribute? Thanks
[ "I don't think CheckBox will work for that. Changing the background color will have a different effect on different platforms, and I'm not sure any of them change only the box part of the widget. ListCtrl is also pretty limited. \nIf there's nothing built-in to do the job, you could try something like this using...
[ 0, 0 ]
[]
[]
[ "listctrl", "python", "wxpython" ]
stackoverflow_0005410273_listctrl_python_wxpython.txt
Q: Control three frames from main menu I created three frames separately. I need to call these child frames from the click events of buttons located in a main frame. And when a child frame is open, I want the main frame to be hidden or disabled until the child frame is closed. How can I do this? Thanks in advance...
Control three frames from main menu
I created three frames separately. I need to call these child frames from the click events of buttons located in a main frame. And when a child frame is open, I want the main frame to be hidden or disabled until the child frame is closed. How can I do this? Thanks in advance.
[ "I use pubsub to do this. Right after I open a child frame, I call the main frame's Hide method. When I close a child frame, I uses pubsub to let the main frame know that it can Show itself. You can see a fairly simple tutorial here:\nhttp://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutoria...
[ 1, 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0005308263_python_wxpython.txt
Q: Twisted + qtreactor: How to cleanup after last window closed? I have a Twisted/PyQt application that (among other things) connects to a bunch of remote resources. When the user closes the window I want to shut down all the connections, cleanly if possible, forcibly if not. The problem is that by the time I go to c...
Twisted + qtreactor: How to cleanup after last window closed?
I have a Twisted/PyQt application that (among other things) connects to a bunch of remote resources. When the user closes the window I want to shut down all the connections, cleanly if possible, forcibly if not. The problem is that by the time I go to close the connections, it appears that the reactor is no longer aliv...
[ "I don't know exactly when that lastWindowClosed() signal fires. However, even if it fires early enough, before the reactor has shut down (preventing you from doing what you want to do), I'm sure that PyQt doesn't know what to do with the Deferred that is returned by your stop function. This means that the shutdo...
[ 2 ]
[]
[]
[ "pyqt", "python", "twisted" ]
stackoverflow_0005461816_pyqt_python_twisted.txt
Q: Supporting PubSubHubbub with PyRSS2Gen? I'm using PyRSS2Gen to generate a RSS feed and I'm trying to support PubSubHubbub, but I need to add link elements that break RSS. Here's what should work without requiring a rewrite as Atom: <atom:link rel="hub" href="http://example.hub.com" xmlns:atom="http://www.w3.org/2...
Supporting PubSubHubbub with PyRSS2Gen?
I'm using PyRSS2Gen to generate a RSS feed and I'm trying to support PubSubHubbub, but I need to add link elements that break RSS. Here's what should work without requiring a rewrite as Atom: <atom:link rel="hub" href="http://example.hub.com" xmlns:atom="http://www.w3.org/2005/Atom"> <atom:link rel="self" href="http:/...
[ "I looked at the PyRSS2Gen source code, and it looks like all you have to do is override the RSS class' publish_extensions() method. Something like this perhaps:\nimport PyRSS2Gen\n\nclass MyRSS2(PyRSS2Gen.RSS2):\n def publish_extensions(self, handler):\n PyRSS2Gen._element(handler, 'atom:link', None, {'e...
[ 0 ]
[]
[]
[ "python", "rss", "websub" ]
stackoverflow_0002360641_python_rss_websub.txt
Q: Numpy NdArray Memoization I'm working on some fairly computational intensive calculations that deal with numpy matrices and ndarrays, and from some digging around, there are about a dozen ways not to implement memoization, generally full of collisions, and issues with ndarrays being mutable objects. Has anyone co...
Numpy NdArray Memoization
I'm working on some fairly computational intensive calculations that deal with numpy matrices and ndarrays, and from some digging around, there are about a dozen ways not to implement memoization, generally full of collisions, and issues with ndarrays being mutable objects. Has anyone come across a fairly general memo...
[ "How about this package:\nhttp://packages.python.org/joblib/memory.html\n2021 update\nhttps://joblib.readthedocs.io/en/latest/generated/joblib.Memory.html\n", "An alternative is my package jug:\nhttp://packages.python.org/Jug\nIt is similar to joblib, but with a slightly different approach.\n" ]
[ 9, 1 ]
[]
[]
[ "matrix", "memoization", "multidimensional_array", "numpy", "python" ]
stackoverflow_0005362781_matrix_memoization_multidimensional_array_numpy_python.txt
Q: Moving the point downwards in a floating point number First off all, thanks for the attention, I'm new to this site ^^ so excuse me if I do something wrong... I have a huge problem with my Python code... I'm new to programming, and I'm new to Python as well. I need to take a floating point number and move the poin...
Moving the point downwards in a floating point number
First off all, thanks for the attention, I'm new to this site ^^ so excuse me if I do something wrong... I have a huge problem with my Python code... I'm new to programming, and I'm new to Python as well. I need to take a floating point number and move the point right so it becomes an integer, like taking 60.27 and get...
[ "Floating point representations have that issue.\nAre you looking to change:\n1.2345\n12.345\n123.45\n1234.5\n\nall to 12345?\nFor floats which have no exact representation (you mention 6024.70), do you expect to get 6024700000000001, since that's the output of the closest thing to 6024.70 which can be stored in fl...
[ 2, 2, 1, 1, 1, 1 ]
[]
[]
[ "floating_point", "integer", "python", "recursion" ]
stackoverflow_0005463541_floating_point_integer_python_recursion.txt
Q: python universal feedparser crashing on unicode error I am using OSX 10.6 and python 2.7.1 with BeautifulSoup 3.0 and feedparser 5.01. I am trying to parse the New York Times RSS Feed, which validates, and which Beautiful Soup on its own will parse happily. The minimum code to produce the error is: import feedpar...
python universal feedparser crashing on unicode error
I am using OSX 10.6 and python 2.7.1 with BeautifulSoup 3.0 and feedparser 5.01. I am trying to parse the New York Times RSS Feed, which validates, and which Beautiful Soup on its own will parse happily. The minimum code to produce the error is: import feedparser from BeautifulSoup import BeautifulSoup feed = feedpa...
[ "I tested using Python 2.7.1, feedparser 5.0.1, and BeautifulSoup 3.2.0, but the feed didn't cause a traceback. Try upgrading to BeautifulSoup 3.2.0.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "feedparser", "python", "unicode" ]
stackoverflow_0005236978_beautifulsoup_feedparser_python_unicode.txt
Q: How can I access relative paths in Python 2.7 when imported by different modules The Goal: Access / Write to the same temp files when using a common utility function called from various python modules. Background: I am using the python Unittest module to run sets of custom tests that interface with instrumentation...
How can I access relative paths in Python 2.7 when imported by different modules
The Goal: Access / Write to the same temp files when using a common utility function called from various python modules. Background: I am using the python Unittest module to run sets of custom tests that interface with instrumentation via pySerial. Because I am using the unittest module, I am unable to pass required v...
[ "Probably you know this, but here the basics first:\n## file one: main.py, main program in your working directory\n# this code must run directly, not inside IDLE to get right directory name\nimport os, mytest\ncurdir=os.path.dirname(__file__) \nprint '-'*10,'program','-'*10\nprint 'Program in',curdir\nprint 'Module...
[ 5 ]
[]
[]
[ "path", "python", "unit_testing" ]
stackoverflow_0005464176_path_python_unit_testing.txt
Q: Django query works from the shell, but not the dev server? Raises FieldError in dev server I've been having a wtf moment with Django's ORM (django 1.3). In the development server: # in x.modules.training.models class Training(x.models.Base): trainers = models.ManyToManyField(staff_models.Staff, related_name='t...
Django query works from the shell, but not the dev server? Raises FieldError in dev server
I've been having a wtf moment with Django's ORM (django 1.3). In the development server: # in x.modules.training.models class Training(x.models.Base): trainers = models.ManyToManyField(staff_models.Staff, related_name='trainings_taught') people = models.ManyToManyField(x.models.Person, related_name='trainings_a...
[ "If you have any class inheriting from Training Class, you must guarantee all related_name's are different. So you should declare it as:\npeople = models.ManyToManyField(x.models.Person, related_name='%(app_label)s_%(class)s_trainings_attended')\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005464089_django_django_models_python.txt
Q: NumPy linalg.eig I have this annoying problem and I haven't figured it out yet. I have a matrix and I want to find the eigenvectors, so I write: val,vec = np.linalg.eig(mymatrix) and then I got vec . My problem is when others from my group do the same with the same matrix (mymatrix) we dont get the same eigenvect...
NumPy linalg.eig
I have this annoying problem and I haven't figured it out yet. I have a matrix and I want to find the eigenvectors, so I write: val,vec = np.linalg.eig(mymatrix) and then I got vec . My problem is when others from my group do the same with the same matrix (mymatrix) we dont get the same eigenvectors !! Someone who can...
[ "The fundamental property of an eigenvector x is\nA x = lambda x\n\nfor some constant lambda.\nIf x is an eigenvector, so is -x:\nA (-x) = - A x = - lambda x = lambda (-x)\n\n\nNote also that the set of eigenvectors may not be unique. For example, any vector (of the appropriate dimension) can be an eigenvector of t...
[ 6 ]
[]
[]
[ "eigenvector", "numpy", "python" ]
stackoverflow_0005464081_eigenvector_numpy_python.txt
Q: Problems stopping a thread when signaled from a menu event? This samplet is from a project I am working on. My client uses software which uses his webcam to take snapshots if motion is detected within it's view. The problem is that the software is unable to email the images to his account as they are taken. I wrot...
Problems stopping a thread when signaled from a menu event?
This samplet is from a project I am working on. My client uses software which uses his webcam to take snapshots if motion is detected within it's view. The problem is that the software is unable to email the images to his account as they are taken. I wrote this project to monitor the folder where the snapshots are save...
[ "Just figured it out.. Why are my biggest problems always one line fixes?? :P\nApparently I overlooked the fact that I was recreating the variable mon each time self.OnConnect was called, I kinda clued in on this mistake when I got frustrated enough to furiously click connect/disconnect a billion times and watched ...
[ 0 ]
[]
[]
[ "events", "multithreading", "python", "wxpython" ]
stackoverflow_0005446300_events_multithreading_python_wxpython.txt
Q: How to convert mpeg-4 to mp3 or wave format using pure python on Google App Engine? I'm working on a project, using Python running on Google App Engine. The project must allow users to upload mpeg-4 audio file for others to playback. Is there a way to convert mpeg-4 to mp3/wav on the server side? Could anyone offe...
How to convert mpeg-4 to mp3 or wave format using pure python on Google App Engine?
I'm working on a project, using Python running on Google App Engine. The project must allow users to upload mpeg-4 audio file for others to playback. Is there a way to convert mpeg-4 to mp3/wav on the server side? Could anyone offer a solution to this? Any help is greatly appreciated.
[ "Google App Engine is designed for lightweight HTTP requests and user-facing Web application.\nVideo/audio transcoding is an Heavy activity that would probably deplete your available CPU quota in no time.\nIf you can, outsource the transcoding Task to some third-party service like Zencoder, Heywatch or Encoding.com...
[ 1 ]
[]
[]
[ "google_app_engine", "mp3", "mpeg_4", "python" ]
stackoverflow_0005463190_google_app_engine_mp3_mpeg_4_python.txt
Q: searching and processing particular directory and files in python In my present directory I have the following files: project1, project5, junk, temp and personal I would like to walk through the sub directories at this level only. For directories other than junk, temp and personal I would like to open and process...
searching and processing particular directory and files in python
In my present directory I have the following files: project1, project5, junk, temp and personal I would like to walk through the sub directories at this level only. For directories other than junk, temp and personal I would like to open and process a particular file present in them say called project.c for dirs in os....
[ "Here's one way:\nimport os\nimport glob\n\nignoreDirs = ['junk', 'temp', 'personal']\n\nfor x in glob.glob('*'):\n if (os.path.isdir(x) == False):\n continue\n\n if (x in ignoreDirs):\n continue\n\n # ... do processing work here ...\n\n", "And here's another, somewhat similar way\nignored=...
[ 1, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0005463351_file_python.txt
Q: Where to Disconnect() the `default_product_search_listener` in Satchmo I don't want to use the Default Satchmo search listener. I've created my own search listener instead. Where is the best place to disconnect the default search listener? # This is what I need to do... from satchmo_store.shop.listeners import d...
Where to Disconnect() the `default_product_search_listener` in Satchmo
I don't want to use the Default Satchmo search listener. I've created my own search listener instead. Where is the best place to disconnect the default search listener? # This is what I need to do... from satchmo_store.shop.listeners import default_product_search_listener application_search.disconnect(default_product...
[ "Try swapping the order of Satchmo and your app in INSTALLED_APPS.\n", "The answer to this question is more generally answered by Where To Put Django Startup Code.\n\nWrite middleware that does this in init and afterwards raise django.core.exceptions.MiddlewareNotUsed from the init, django will remove it for all ...
[ 1, 1 ]
[]
[]
[ "django", "python", "satchmo" ]
stackoverflow_0005439769_django_python_satchmo.txt
Q: Accessing an object created in another module using python How to access an object created in another module using python A: import other_module other_module.some_object.do_something() A: Also you could do from module import object object.function() A: Yeah, Thats right, from module import desired_object ...
Accessing an object created in another module using python
How to access an object created in another module using python
[ "import other_module\n\nother_module.some_object.do_something()\n\n", "Also you could do \nfrom module import object\nobject.function()\n\n", "Yeah, \nThats right,\nfrom module import desired_object\n\nmodule exapmle:\n# Desired Module:\n\ndesired_object = None\ndef my_func():\n global desired_object\n de...
[ 4, 3, 3 ]
[]
[]
[ "class", "module", "oop", "python" ]
stackoverflow_0005464504_class_module_oop_python.txt
Q: Using python to create a data.xml file for fusion charts I am a newbie to python. I just want to know how i can create a code to write an xml file name data.xml for fusioncharts. The xml file follows the format: <?xml version="1.0" encoding="UTF-8" ?> <graph caption="Test graph" xAxisName="X" yAxisName="Y" showAnc...
Using python to create a data.xml file for fusion charts
I am a newbie to python. I just want to know how i can create a code to write an xml file name data.xml for fusioncharts. The xml file follows the format: <?xml version="1.0" encoding="UTF-8" ?> <graph caption="Test graph" xAxisName="X" yAxisName="Y" showAnchors="1" anchorRadius="1" showValues="0"> <set name='2004' val...
[ "You can use the miniDOM library which is built into python 2.0 and later:\nhttp://docs.python.org/library/xml.dom.minidom.html\n", "ElementTree from stdlib might be helpful:\nimport xml.etree.cElementTree as etree\n\nG = etree.Element('graph', dict(caption='Test graph', xAxisName=\"...\"))\n\nfor name, value, co...
[ 2, 0, 0 ]
[]
[]
[ "fusioncharts", "python" ]
stackoverflow_0005463201_fusioncharts_python.txt
Q: Is there any python implement of edonkey/emule I want deploy a project in google appengine to search edonkey/emule, Is there any python implement of edonkey/emule or ed2k protocol library ? A: After 20 minutes of googling all combinations of python and edonkey/emule/ed2k and visiting all sites of all clients lis...
Is there any python implement of edonkey/emule
I want deploy a project in google appengine to search edonkey/emule, Is there any python implement of edonkey/emule or ed2k protocol library ?
[ "After 20 minutes of googling all combinations of python and edonkey/emule/ed2k and visiting all sites of all clients listed under the \"eDonkey network\" Wikipedia page I can say with near certainty that the answer is \"No.\"\n", "I stumbled upon both this question and y-donkey today. Y-donkey looks like it coul...
[ 1, 1 ]
[]
[]
[ "p2p", "python" ]
stackoverflow_0005313513_p2p_python.txt
Q: python django media_root If I use the code below it will find my base.css under the project folder: <link rel="stylesheet" type="text/css" href="{% block stylesheet %}/media/a/admin/css/base.css{% endblock %}" /> MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/a/...
python django media_root
If I use the code below it will find my base.css under the project folder: <link rel="stylesheet" type="text/css" href="{% block stylesheet %}/media/a/admin/css/base.css{% endblock %}" /> MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/a/' (r'^media/(?P<path>.*)$', 'd...
[ "I'm guessing you have your ADMIN_MEDIA_PREFIX = '/a/admin/'\nhttp://docs.djangoproject.com/en/dev/ref/settings/#admin-media-prefix\n\nMake sure to use a trailing slash, and\n to have this be different from the\n MEDIA_URL setting (since the same URL\n cannot be mapped onto two different\n sets of files).\n\n",...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005410086_django_python.txt
Q: Django 1.3 static files and displaying content using custom views A slight problem displaying an image using custom views. I have used the request context as required, however the image doesn't show. My model uses thumbnails creating the image into a folder named "timgs" which lives under static/myapp/timgs The st...
Django 1.3 static files and displaying content using custom views
A slight problem displaying an image using custom views. I have used the request context as required, however the image doesn't show. My model uses thumbnails creating the image into a folder named "timgs" which lives under static/myapp/timgs The static files directory displays css/images fine however when it comes to ...
[ "You must list the absolute paths for every static dir\nSTATICFILES_DIR = (\n os.path.join(PROJECT_DIR, 'static/myapp/'),\n ('timgs',os.path.join(PROJECT_DIR, 'static/myapp/timgs')),\n\n)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0005465052_django_django_templates_django_views_python.txt
Q: Simple way to transcode mp3 to ogg in python (live)? I'm searching for a library / module that can transcode an MP3 (other formats are a plus) to OGG, on the fly. What I need this for: I'm writing a relatively small web app, for personal use, that will allow people to listen their music via a browser. For the list...
Simple way to transcode mp3 to ogg in python (live)?
I'm searching for a library / module that can transcode an MP3 (other formats are a plus) to OGG, on the fly. What I need this for: I'm writing a relatively small web app, for personal use, that will allow people to listen their music via a browser. For the listening part, I intend to use the new and mighty <audio> tag...
[ "You know, there's no shame in using subprocess to call external utilities. For example, you could construct pipes like:\n#!/usr/bin/env python\nimport subprocess\nfrommp3 = subprocess.Popen(['mpg123', '-w', '-', '/tmp/test.mp3'], stdout=subprocess.PIPE)\ntoogg = subprocess.Popen(['oggenc', '-'], stdin=frommp3.stdo...
[ 7 ]
[]
[]
[ "audio", "python", "transcoding" ]
stackoverflow_0005464912_audio_python_transcoding.txt
Q: using python join to join first element of each list I'd like to do this: for qb in qb_data: qb_in += "'" + qb[0] + "'" + "," using a join. Obviously the problem is that join just concatenates each member of the list. But here I have a list of lists and only need to join the first element of each list. A: "...
using python join to join first element of each list
I'd like to do this: for qb in qb_data: qb_in += "'" + qb[0] + "'" + "," using a join. Obviously the problem is that join just concatenates each member of the list. But here I have a list of lists and only need to join the first element of each list.
[ "\",\".join(\"'%s'\" % qb[0] for qb in qb_data)\n\nYou can still selectively pick out stuff in your generator expression/list comprehension, of course!\nFor example:\n>>> qb_data = [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8', '9']]\n>>> \",\".join(\"'%s'\" % qb[0] for qb in qb_data)\n\"'1','3','5','7'\"\n\n" ]
[ 9 ]
[]
[]
[ "join", "python" ]
stackoverflow_0005465317_join_python.txt
Q: How to draw a notification on the screen that doesn't take focus and always stays on top (Windows) I'm trying to find a way to draw something on the screen that will show on top of anything else that is running (even full screen applications), but will not steal focus, or act like a normal application or window. I...
How to draw a notification on the screen that doesn't take focus and always stays on top (Windows)
I'm trying to find a way to draw something on the screen that will show on top of anything else that is running (even full screen applications), but will not steal focus, or act like a normal application or window. It should be purely visual and not interfere in any other way. Python is preferable. What I'm aiming for ...
[ "In general, you cannot write an application which guarantees to stay on top of other applications which want to stay on top of other applications.\n\nhttp://blogs.msdn.com/b/oldnewthing/archive/2011/03/10/10138969.aspx\n\nSince a full-screen application is window which is topmost, there is no way for the OS to kno...
[ 1, 0 ]
[]
[]
[ "notifications", "python", "windows" ]
stackoverflow_0005465164_notifications_python_windows.txt
Q: Adding and removing data to/from iCal I need to add/remove calendar data to/from iCal. I google and found that I can uses python library to create the ics file. With this, I can come up with applescript to run iCal to import the generated ics file to add calendar info to iCal, but for deleting calendar info, I don...
Adding and removing data to/from iCal
I need to add/remove calendar data to/from iCal. I google and found that I can uses python library to create the ics file. With this, I can come up with applescript to run iCal to import the generated ics file to add calendar info to iCal, but for deleting calendar info, I don't know exactly what to do. Q1 : How to de...
[ "To delete the an event within iCal you need to be able to identify it. This can be done via the event's uid property or by some other identifying piece of information. Here's a quick example:\ntell application \"iCal\"\n tell calendar \"Chuck\"\n set evt to make new event at end with properties ¬\n ...
[ 1 ]
[]
[]
[ "applescript", "icalendar", "python" ]
stackoverflow_0005455190_applescript_icalendar_python.txt
Q: Syntax to call random function from a list From this thread: How do I perform a random event in Python by picking a random variable? I learned that it's possible to put some functions into a list, and by using random.choice(), call one of them to generate a random event. I'm interested in doing this because I'm wr...
Syntax to call random function from a list
From this thread: How do I perform a random event in Python by picking a random variable? I learned that it's possible to put some functions into a list, and by using random.choice(), call one of them to generate a random event. I'm interested in doing this because I'm writing a fairly small text based game as part of ...
[ "With the parentheses you call the function. What you want is assigning them to the list and call the choice later:\nmy_list = [func_test_1, func_test_2, func_test_3]\nrandom.choice(my_list)()\n\n", "Firstly, when you do my_list = [func_test_1(), func_test_2(), func_test_3()] you store function results, not funct...
[ 57, 13, 11 ]
[]
[]
[ "python" ]
stackoverflow_0005465455_python.txt
Q: Trying to convert MSWord 2007 document to an XML format I'm hoping I can forgo the history, but trust me on the following: I have several people who have immediate access to MSWord 2007 We are trying to prep a generic Word document that can be passed from person to person over the course of several months and the...
Trying to convert MSWord 2007 document to an XML format
I'm hoping I can forgo the history, but trust me on the following: I have several people who have immediate access to MSWord 2007 We are trying to prep a generic Word document that can be passed from person to person over the course of several months and they can "add" new content to it. Regardless of the answers bel...
[ "If the data will be as uniform as the example you provided (i.e. just note elements, with a fixed number of fields) You might be able to get away with having one big table in the Word document, with columns for to, from, heading, body, etc. Then, you could parse it out in Python using one of the methods described ...
[ 1 ]
[]
[]
[ "ms_word", "python", "schema_design", "xml", "xsd" ]
stackoverflow_0005456959_ms_word_python_schema_design_xml_xsd.txt
Q: Optimising `__getitem__` and `__setitem__` for a sparse array in Python I'm writing my own sparse (one-dimensional) array class but I'm running into some performance issues. Profiling suggests that one of the bottlenecks is my __getitem__ and __setitem__ implementations, and in particular, it seems like one of the...
Optimising `__getitem__` and `__setitem__` for a sparse array in Python
I'm writing my own sparse (one-dimensional) array class but I'm running into some performance issues. Profiling suggests that one of the bottlenecks is my __getitem__ and __setitem__ implementations, and in particular, it seems like one of the culprits might be my use of isinstance. At the moment I have 5 calls to isin...
[ "To answer your immediate question, isinstance() is a slow call because the name is global. You can speed it up significantly simply by adding isinstance=isinstance to __setitem__()'s signature, like so:\ndef __setitem__(self, key, value, isinstance=isinstance):\n # und so weiter\n\nThis converts the global name...
[ 5, 2, 0 ]
[ "Use assert instead:\nif not isinstance(key, int):\n raise TypeError('list indices must be be integers')\n\nit's more faster than \"if ....: raise exception\"\n" ]
[ -1 ]
[ "optimization", "python" ]
stackoverflow_0005464422_optimization_python.txt
Q: Reusing the same SVG in a PDF with wkhtmltopdf I have the following HTML for conversion to PDF using wkhtmltopdf: <html> <head> </head> <body> <object data="first.svg" width="100" height="100" type="image/svg+xml"></object> <object data="second.svg" width="100" height="100" type="image/svg+xml"></object> <object ...
Reusing the same SVG in a PDF with wkhtmltopdf
I have the following HTML for conversion to PDF using wkhtmltopdf: <html> <head> </head> <body> <object data="first.svg" width="100" height="100" type="image/svg+xml"></object> <object data="second.svg" width="100" height="100" type="image/svg+xml"></object> <object data="third.svg" width="100" height="100" type="imag...
[ "I am not familiar with wkhtmltopdf, but the structure of a PDF file is that it contains a library of \"glyphs\" (corresponding to letters, symbols, digraphs, etc) that are reused over and over at different coordinates.\nIt seems very likely that you could turn the final svg image into a glyph, but I'm afraid I don...
[ 0, 0 ]
[]
[]
[ "html", "python", "svg", "webkit", "wkhtmltopdf" ]
stackoverflow_0003352019_html_python_svg_webkit_wkhtmltopdf.txt
Q: Is there an implementation of silverlight's policy file server in twisted? Is there an implementation for silverlight's xml policy file server in twisted python? If not, what should I know to implement one myself? A: Not in Twisted itself, no. But all you need to know is how to include static content on your si...
Is there an implementation of silverlight's policy file server in twisted?
Is there an implementation for silverlight's xml policy file server in twisted python? If not, what should I know to implement one myself?
[ "Not in Twisted itself, no. But all you need to know is how to include static content on your site. If you're using a command like twistd web --path foo, just create a foo/clientaccesspolicy.xml (or foo/crossdomain.xml) and you are done.\n" ]
[ 1 ]
[]
[]
[ ".net", "python", "silverlight", "twisted" ]
stackoverflow_0005458460_.net_python_silverlight_twisted.txt
Q: Smart Querying in Django, ManyToMany relationships with User I'm working on an app that currently has a lot of ManyToMany relationships (and will eventually have even more), and I'm trying to think of clever ways (read: the right ways) to accurately query the ORM for JOINed data. Here's a sample of what I have and...
Smart Querying in Django, ManyToMany relationships with User
I'm working on an app that currently has a lot of ManyToMany relationships (and will eventually have even more), and I'm trying to think of clever ways (read: the right ways) to accurately query the ORM for JOINed data. Here's a sample of what I have and what I need to do. I apologize for the pseudocode. ProjectModel: ...
[ "# users in projects owned by request.user \nusers = User.objects.filter(projectmodel__owner=request.user).distinct()\n\nIf there are a lot of m2ms, and you had defined a related_name in your people field, that's what you would use in your reverse lookup instead of projectmodel. \n" ]
[ 7 ]
[]
[]
[ "django", "django_orm", "orm", "python" ]
stackoverflow_0005465837_django_django_orm_orm_python.txt
Q: Learning Perl from Python perspective I am fairly familiar with python, from a system automation and tool building prospective; I am a sysadm by trade. I recently started a new job at a company that wants to standardise on perl, for which I know none. So I need to get up to speed on perl pretty quickly and was h...
Learning Perl from Python perspective
I am fairly familiar with python, from a system automation and tool building prospective; I am a sysadm by trade. I recently started a new job at a company that wants to standardise on perl, for which I know none. So I need to get up to speed on perl pretty quickly and was hoping someone could point to some helpful r...
[ "Crank through the Llama (it will be easy) and when you're done with that check out Effective Perl Programming and/or Modern Perl. They'll help you avoid the mistakes encouraged by all the crappy tutorials written in 1994 that still seem to reverberate around the net.\nTake the time to check out Moose and in parti...
[ 17, 8, 8, 6, 2 ]
[]
[]
[ "perl", "python", "scripting" ]
stackoverflow_0005460418_perl_python_scripting.txt
Q: select.select() does not catch exceptional condition on socket? Python 2.7, Windows XP. I have a server that sends messages to client(s). I use select module to check for sockets ready to receive, as well as to catch exceptional conditions. I was under the impression that if a client closed a socket, select() woul...
select.select() does not catch exceptional condition on socket?
Python 2.7, Windows XP. I have a server that sends messages to client(s). I use select module to check for sockets ready to receive, as well as to catch exceptional conditions. I was under the impression that if a client closed a socket, select() would return said socket in the socket list of exceptional conditions, bu...
[ "A closed socket is not an exception (error) condition. What will happen is the socket will be in the read list (lin) and when you read you will get 0 bytes. This means the other end has closed the socket.\nUpdate:\nIn normal practice you will never see anything in the except list and can safely ignore it. It is fo...
[ 7, 3, 1 ]
[]
[]
[ "python", "select", "sockets" ]
stackoverflow_0005466137_python_select_sockets.txt
Q: Python Twisted does not work on Eclipse I installed Twisted for Python and I am trying to build a simple server on Eclipse and I am getting the following error: ImportError: No module named zope.interface I'm not sure how to correct this. Doesn't Twisted install all of the dependencies first? A: Make sure you: ...
Python Twisted does not work on Eclipse
I installed Twisted for Python and I am trying to build a simple server on Eclipse and I am getting the following error: ImportError: No module named zope.interface I'm not sure how to correct this. Doesn't Twisted install all of the dependencies first?
[ "Make sure you:\n\nHave PyDev installed\nHave twisted / zope.interface installed and in your PYTHONPATH.\nHave configured your eclipse project as a python/pydev project.\nHave configured the interpreter in the Eclipse environment (Pydev settings).\n\n" ]
[ 2 ]
[]
[]
[ "eclipse", "pydev", "python", "twisted" ]
stackoverflow_0005463782_eclipse_pydev_python_twisted.txt
Q: Run Fortran command line program within Python So I am in a bit of a pickle. I am trying to write plotting and fitting extensions to a Fortran77 (why this program was rewritten in F77 is a mystery too me, btw) code that requires command line input, i.e. it prompts the user for input. Currently the program uses GNU...
Run Fortran command line program within Python
So I am in a bit of a pickle. I am trying to write plotting and fitting extensions to a Fortran77 (why this program was rewritten in F77 is a mystery too me, btw) code that requires command line input, i.e. it prompts the user for input. Currently the program uses GNUplot to plot, but the GNUplot fitting routine is les...
[ "Can't you just dump the data generated by the Fortran program to a file and then read it from python ?\nNumpy can read a binary file and treat it as a array.\nGoing from here to matplotlib then should be a breeeze. \n", "It sounds like all you want to do is run the F77 program and then parse the output files, al...
[ 2, 1 ]
[]
[]
[ "fortran77", "numpy", "python", "scipy" ]
stackoverflow_0005465982_fortran77_numpy_python_scipy.txt
Q: Why is this python while loop missing the logical operator? I'm working through learn python the hard way, and in exercise 33 extra credit 2 I'm trying to utilize either raw_input or argv to set a variable that will be used in a while loop: # from sys import argv # script, my_num = argv def all_the_numbers(n): ...
Why is this python while loop missing the logical operator?
I'm working through learn python the hard way, and in exercise 33 extra credit 2 I'm trying to utilize either raw_input or argv to set a variable that will be used in a while loop: # from sys import argv # script, my_num = argv def all_the_numbers(n): """increment by 1 up to limit n""" i = 0 numbers = [] w...
[ "The raw_input() function returns a string, not an integer. Try:\nn = int(raw_input(\"#\"))\n\nor\nn = int(my_num)\n\nThis converts the string returned by raw_input() into an integer, which your all_the_numbers() function expects.\nHere's the relevant passage from the Python docs (emphasis mine):\n\nThe operators <...
[ 5 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0005466346_python_while_loop.txt
Q: Does Boost/Python have a make_array method? I'd like to return to Python the results of my computations in a ndarray object. I know there is a make_tuple method so I figure there might be something similar for arrays though I can't find it. Edit - I guess I can create the array in python, pass it as an extra param...
Does Boost/Python have a make_array method?
I'd like to return to Python the results of my computations in a ndarray object. I know there is a make_tuple method so I figure there might be something similar for arrays though I can't find it. Edit - I guess I can create the array in python, pass it as an extra parameter and modify it to hold the values. Would be b...
[ "Try boost::python::numeric::array:\n http://www.boost.org/doc/libs/1_46_1/libs/python/doc/v2/numeric.html#array-spec\nNumeric is the former name of NumPy. It's possible that this wrapper still works with NumPy. Boost::Python seems to be notorious for having out of date documentation. \n" ]
[ 1 ]
[]
[]
[ "arrays", "boost", "c++", "python" ]
stackoverflow_0005466442_arrays_boost_c++_python.txt
Q: 3 Models Entity Joins in AppEngine Python I've read a lot about how I need to rethink implementing entities and joins when developing for AppEngine, and I still can't figure out how to do this: I've 3 entities. Tag has many Tweets and User Follow many Tags. I would like to get all Tweets that is Tagged with tags ...
3 Models Entity Joins in AppEngine Python
I've read a lot about how I need to rethink implementing entities and joins when developing for AppEngine, and I still can't figure out how to do this: I've 3 entities. Tag has many Tweets and User Follow many Tags. I would like to get all Tweets that is Tagged with tags that a User follows. I thought eliminating Tag...
[ "You're not trying to compare two lists - you're checking for intersection. The query you list will do that, with one major caveat: IN filters are split up into multiple sub-queries, which are executed independently by the backend, with a maximum of 30 sub-queries.\nThat is, if your user follows 3 tags ['foo', 'bar...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005465854_google_app_engine_python.txt
Q: Is there a way to annotate Python source code with the profiler results? I'm currently using cProfile and pstats to profile some Python code. Is there a way to annotate the source code with the time taken on each line? Ideally this would be a coloured (HTML) version of the source with expensive lines highlighted i...
Is there a way to annotate Python source code with the profiler results?
I'm currently using cProfile and pstats to profile some Python code. Is there a way to annotate the source code with the time taken on each line? Ideally this would be a coloured (HTML) version of the source with expensive lines highlighted in red or something.
[ "yes, look at line profiler or profilehooks\nI think is so simple to render the output to html, with your own codes.\nand for graph, take a look at gprof2dot\n", "Not quite what you ask for but might be helpful:\nhttp://code.google.com/p/jrfonseca/wiki/Gprof2Dot\nIt draws a graph which makes it really easy to see...
[ 4, 1 ]
[]
[]
[ "profiler", "python" ]
stackoverflow_0005466700_profiler_python.txt
Q: how to use the b = [[1]*3]*3 in a proper way? All, code: #=A=================== >>> b = [[1]*3]*3 >>> b [[1, 1, 1], [1, 1, 1], [1, 1, 1]] >>> b[0][0] = 0 >>> b [[0, 1, 1], [0, 1, 1], [0, 1, 1]] >>> #=B=================== >>> b = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] >>> b[0][0] = 0 >>> b [[0, 1, 1]...
how to use the b = [[1]*3]*3 in a proper way?
All, code: #=A=================== >>> b = [[1]*3]*3 >>> b [[1, 1, 1], [1, 1, 1], [1, 1, 1]] >>> b[0][0] = 0 >>> b [[0, 1, 1], [0, 1, 1], [0, 1, 1]] >>> #=B=================== >>> b = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] >>> b[0][0] = 0 >>> b [[0, 1, 1], [1, 1, 1], [1, 1, 1]] Can I use the format may ...
[ "The problem with your code is that it references the same list, so when you do b[0][0] = 0, you are really updating the value at the reference(in which all three arrays point to).\nTo get the desired results, I would do(using list comprehension):\n>>> b = [[1]*3 for _ in range(3)]\n>>> b\n[[1, 1, 1], [1, 1, 1], [1...
[ 1, 1, 1, 0 ]
[]
[]
[ "evaluation", "python", "variables" ]
stackoverflow_0005466920_evaluation_python_variables.txt
Q: Python nonlocal statement in a class definition I'm trying to perform some analysis of scope in Python 3 source code and I'm stuck with how the nonlocal statement statement works inside a class definition. As I understand it, the class definition executes its body inside a new namespace (call it dict) and binds th...
Python nonlocal statement in a class definition
I'm trying to perform some analysis of scope in Python 3 source code and I'm stuck with how the nonlocal statement statement works inside a class definition. As I understand it, the class definition executes its body inside a new namespace (call it dict) and binds the class name to the result of type(name, bases, dict)...
[ "Lexical scoping applies only to function namespaces, otherwise methods defined inside a class would be able to \"see\" the class level attributes (which is by design - those attributes must instead be accessed as attributes of self inside the method).\nThe same limitations that cause the class level variables to b...
[ 13, 5 ]
[]
[]
[ "class", "python", "python_3.x", "python_nonlocal" ]
stackoverflow_0005466238_class_python_python_3.x_python_nonlocal.txt
Q: How to clean up after subprocess.Popen? I have a long-running python script with a perl worker subprocess. Data is sent in and out of the child proc through its stdin and stdout. Periodically, the child must be restarted. Unfortunately, after a while of running, it runs out of files ('too many open files'). ls...
How to clean up after subprocess.Popen?
I have a long-running python script with a perl worker subprocess. Data is sent in and out of the child proc through its stdin and stdout. Periodically, the child must be restarted. Unfortunately, after a while of running, it runs out of files ('too many open files'). lsof shows many remaining open pipes. What's th...
[ "I think that's all you need:\ndef restart_helper(self):\n # kill the process if open\n try:\n self.subp.kill()\n except OSError:\n # can't kill a dead proc\n pass\n\n self.start_helper()\n # the wait comes after you opened the process\n # if you want to know how the process e...
[ 7, 1 ]
[]
[]
[ "lsof", "pipe", "popen", "python", "subprocess" ]
stackoverflow_0005033532_lsof_pipe_popen_python_subprocess.txt
Q: Python- Prime summands to an even number This is the assignment my professor gave me. I have no idea where to start or what to do! The point is to use loops to figure this out and I can do the loops, but this is blowing my mind. Even numbers and primes. A prime number is one that has 1 and itself as its only div...
Python- Prime summands to an even number
This is the assignment my professor gave me. I have no idea where to start or what to do! The point is to use loops to figure this out and I can do the loops, but this is blowing my mind. Even numbers and primes. A prime number is one that has 1 and itself as its only divisors. 2, 3, 5, 7 and 11 are the first several...
[ "Don't worry about the big picture of the assignment being difficult. Just go step by step as the prof has broken it down.\n" ]
[ 2 ]
[ "Prime Number\n\nA prime number (or a prime) is a\n natural number that has exactly two\n distinct natural number divisors: 1\n and itself.\n\nA)\ndef is_prime(n): # Write a is_prime(n) function.\n if n <= 1: # It should accept a positive integer n>1 \n return False\n ...
[ -1 ]
[ "primes", "python" ]
stackoverflow_0005466977_primes_python.txt
Q: How does one use the built-in math module in Python 3.X? I'm a beginner programmer, starting in Python. I'm attempting to use math.log10(x) in my program, but keep getting the error "NameError: name 'math' is not defined". The intellisense pops up while I'm typing, so it seems like I should be able to use it. The ...
How does one use the built-in math module in Python 3.X?
I'm a beginner programmer, starting in Python. I'm attempting to use math.log10(x) in my program, but keep getting the error "NameError: name 'math' is not defined". The intellisense pops up while I'm typing, so it seems like I should be able to use it. The guides I've read so far have said little about how to properly...
[ "type \"import math\" at the top of the program.\n" ]
[ 2 ]
[]
[]
[ "math", "module", "python" ]
stackoverflow_0005467083_math_module_python.txt
Q: How come my python import doesn't work? This works: from story.apps.document import core print core.submit() This doesn't work: from story import apps print apps.document.core.submit() "story" is a directory. Inside it, there is "apps" directory. Inside it, there is "document" directory. "core.py" is a file. Th...
How come my python import doesn't work?
This works: from story.apps.document import core print core.submit() This doesn't work: from story import apps print apps.document.core.submit() "story" is a directory. Inside it, there is "apps" directory. Inside it, there is "document" directory. "core.py" is a file. There is a __init__.py in every directory.
[ "The __init__.py file tells python to interpret the directory as a package, but it does not necessarily tell python to import sub-packages or other files from the directory (although it may, if you add the appropriate import statements). \nWith large package hierarchies, it is often preferable to require sub-packag...
[ 8, 7, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005467041_python.txt
Q: Get bbox in data coordinates in matplotlib I have the bbox of a matplotlib.patches.Rectangle object (a bar from a bar graph) in display coordinates, like this: Bbox(array([[ 0., 0.],[ 1., 1.]]) But I would like that not in display coordinates but data coordinates. I'm pretty sure this requires a transform. Wha...
Get bbox in data coordinates in matplotlib
I have the bbox of a matplotlib.patches.Rectangle object (a bar from a bar graph) in display coordinates, like this: Bbox(array([[ 0., 0.],[ 1., 1.]]) But I would like that not in display coordinates but data coordinates. I'm pretty sure this requires a transform. What's the method for doing this?
[ "I'm not sure how you got the Bbox in display coordinates. Almost everything the user interacts with is in data coordinates (those look like axis or data coordinates to me, not display pixels). The following should fully explain the transforms as they apply to Bboxes:\nfrom matplotlib import pyplot as plt\nbars =...
[ 18 ]
[]
[]
[ "matplotlib", "python", "transformation" ]
stackoverflow_0005466539_matplotlib_python_transformation.txt
Q: Cython interface with other extensions Is it possible to use both Cython and pure python extensions together? Say I'd like to have a wrapper for a C function, returning GdkPixbuf pointer. The ultimate goal would be to have that function available in python, returning gtk.gdk.Pixbuf object. A: Yes it is possible ...
Cython interface with other extensions
Is it possible to use both Cython and pure python extensions together? Say I'd like to have a wrapper for a C function, returning GdkPixbuf pointer. The ultimate goal would be to have that function available in python, returning gtk.gdk.Pixbuf object.
[ "Yes it is possible because most of the things that can be done with python can also be done in cython. However, using python extensions or doing anything with python objects (as opposed to statically declared C datatypes) will incur a performance penalty, so Cython will be less of an advantage.\nLook into cdef cla...
[ 0 ]
[]
[]
[ "cython", "gtk", "pygtk", "python" ]
stackoverflow_0005287207_cython_gtk_pygtk_python.txt
Q: Modelform not printing fields of one to many relationships Summary: I have 1 to many hierarchical relationships between models Country (1) --> City (Many) City (1) --> Status (Many) I have a form that is suppose to print the fields belonging to all these models, but when I print I only see the “city” field and th...
Modelform not printing fields of one to many relationships
Summary: I have 1 to many hierarchical relationships between models Country (1) --> City (Many) City (1) --> Status (Many) I have a form that is suppose to print the fields belonging to all these models, but when I print I only see the “city” field and that too appears as a drop-down list instead of appearing as a tex...
[ "Your form is outputting correctly.\nYou have a one to many relations between cities and statuses.\n country\n __ __ __ __ __ __ __ __ | __ __ __ __ __ __ __ \n / | | \\ \n city city city c...
[ 1 ]
[]
[]
[ "django", "django_forms", "google_app_engine", "python" ]
stackoverflow_0005467062_django_django_forms_google_app_engine_python.txt
Q: how to get 30 if a is 25 using python this is my code: from math import ceil a = 25 a = float(a/10) a = int(ceil(a))*10 print a i get 20, but i want get 30 , the next is what i want get: if the a is 22 , i want get 20 if the a is 25 , i want get 30 if the a is 27 , i want get 30 if the a is 21 , i want get 20 so...
how to get 30 if a is 25 using python
this is my code: from math import ceil a = 25 a = float(a/10) a = int(ceil(a))*10 print a i get 20, but i want get 30 , the next is what i want get: if the a is 22 , i want get 20 if the a is 25 , i want get 30 if the a is 27 , i want get 30 if the a is 21 , i want get 20 so what can i do , thanks
[ "You're looking for the round() function:\nprint int(round(25, -1))\n\n", "You can use the round() method\n>>> num = 25\n>>> round_num = int(round(num, -1))\n>>> round_num\n30\n\n>>> num = 22\n>>> round_num = int(round(num, -1))\n>>> round_num\n20\n\nand so on.\n" ]
[ 7, 2 ]
[]
[]
[ "math", "python" ]
stackoverflow_0005467545_math_python.txt
Q: pyspatialite symbol not found for _iconv I am trying to compile pyspatialite 2.6.1 using the command sudo python setup.py install It compiles successfully but the resulting binary is missing a symbol. When I import the dbapi2 module from it I get the following error. Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:...
pyspatialite symbol not found for _iconv
I am trying to compile pyspatialite 2.6.1 using the command sudo python setup.py install It compiles successfully but the resulting binary is missing a symbol. When I import the dbapi2 module from it I get the following error. Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. build 5664)] on dar...
[ "I have found the answer on my own. In setup.py look for a line that says:\nlibraries = ['geos','geos_c','proj']\n\nAdd 'iconv' to the end of that list so that it looks like this:\nlibraries = ['geos','geos_c','proj','iconv']\n\n" ]
[ 5 ]
[]
[]
[ "iconv", "macos", "python", "spatialite" ]
stackoverflow_0005467612_iconv_macos_python_spatialite.txt
Q: How to extract string with regular expressions in python I am trying to extract a sub string from a string in python. My data file contains line of the Quran where each one is marked with verse and chapter number at the beginning of the string. I want to try to extract the first number and second number and writ...
How to extract string with regular expressions in python
I am trying to extract a sub string from a string in python. My data file contains line of the Quran where each one is marked with verse and chapter number at the beginning of the string. I want to try to extract the first number and second number and write these to a line in another text file Here is an example of a...
[ "If all your lines are formatted like A|B|C, then you don't need any regex, just split it.\nfor line in fp:\n parts = line.split('|') # or line.split('|', 2) if the last part can contain |\n # use parts[0], parts[1]\n\n", "I think the easiest way would be to use a re.split() to get the verses text\nand a re...
[ 4, 0 ]
[ "With parenthesis? Isn't that how all regular expressions work?\n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0005462659_python_regex.txt
Q: call list of function using list comprehension can I call a list of functions and use list comprehension? def func1():return 1 def func2():return 2 def func3():return 3 fl = [func1,func2,func3] fl[0]() fl[1]() fl[2]() I know I can do for f in fl: f() but can I do below ? [f() for f in fl] A additional qu...
call list of function using list comprehension
can I call a list of functions and use list comprehension? def func1():return 1 def func2():return 2 def func3():return 3 fl = [func1,func2,func3] fl[0]() fl[1]() fl[2]() I know I can do for f in fl: f() but can I do below ? [f() for f in fl] A additional question for those kind people, if my list of function...
[ ">>> [f() for f in fl]\n[1, 2, 3]\n\nAbsolutely :)\n", "Of course you can as Fábio Diniz said :),\nHowever for the class method when used as a callable, an object must be given as an argument:\nfobj= F()\n\nfor f in fobj.fl:\n f(fobj)\n\nThe object must be given as an argument to the callable because when you ...
[ 29, 19, 1, 0 ]
[]
[]
[ "function", "list", "list_comprehension", "python" ]
stackoverflow_0005461571_function_list_list_comprehension_python.txt
Q: Uploading images using Django Admin? Is there an easy way to include file upload capabilities to the admin interface in Django? I saw this question but I'm not well versed in Javascript. Is there any magick I can add to the models.py or admin.py files that will allow me to easily do this with Django's built in CM...
Uploading images using Django Admin?
Is there an easy way to include file upload capabilities to the admin interface in Django? I saw this question but I'm not well versed in Javascript. Is there any magick I can add to the models.py or admin.py files that will allow me to easily do this with Django's built in CMS system? Background: I'm trying to create...
[ "Forgive me if I'm wrong, but it sounds like you don't need anything more than the default admin widget for an ImageField.\nThis satisfies:\n\nUploading images using Django Admin\nIncluding a profile picture (singular) to go with a celebrity.\n\nAlso, the link you point to is pretty old. The django admin ships with...
[ 30 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0005467691_django_django_admin_django_models_python.txt
Q: Python, version fragmentation and graphics...advice? I've been working on learning python (mostly 3.1) for the last month or two. I'm currently working on a multiplayer network enabled boardgame (Spacehulk if anyone cares) as a learning exercise and to play with my friends. But I feel like I'm banging my head a...
Python, version fragmentation and graphics...advice?
I've been working on learning python (mostly 3.1) for the last month or two. I'm currently working on a multiplayer network enabled boardgame (Spacehulk if anyone cares) as a learning exercise and to play with my friends. But I feel like I'm banging my head against a wall trying to find a graphics package that meets...
[ "Downgrading to Python 2.7 seems to be a good option: many libraries are still not available on Python 3.\nPythonbrew can help you manage those two Python versions.\n" ]
[ 2 ]
[]
[]
[ "graphics", "python", "version" ]
stackoverflow_0005464175_graphics_python_version.txt
Q: Linking a @username in Django Template Variables I'm using the twitter API and am displaying a list of tweets. I'd like to link the usernames and hashtags in my app to the approperiate place, but all I have is a string with an @ and # symbol in them. Is there a way through django templates I can say "if the variab...
Linking a @username in Django Template Variables
I'm using the twitter API and am displaying a list of tweets. I'd like to link the usernames and hashtags in my app to the approperiate place, but all I have is a string with an @ and # symbol in them. Is there a way through django templates I can say "if the variable contains a word starting with #, surround it with "...
[ "I'm not sure about handling within the template itself without creating your own filter, but can you handle it in the controller using python? In basic form with a regular expression:\nimport re\n\nuser_pattern = re.compile('(\\s|^)(@)(\\w+)(\\s|$)')\ntweet = 'Hey @pssdbt, thats not what I wanted!'\ntweet = user_...
[ 5 ]
[]
[]
[ "django", "jquery", "python", "twitter" ]
stackoverflow_0005468449_django_jquery_python_twitter.txt
Q: Writing a Python wrapper for difficult C header file using Cython A while back I wrote an thin wrapper around a commercial DAQ library using ctypes. Since then I've come across Cython and wanted to give it a go, thinking it might make it better/cleaner all around than what I had before. Most of the Cython docume...
Writing a Python wrapper for difficult C header file using Cython
A while back I wrote an thin wrapper around a commercial DAQ library using ctypes. Since then I've come across Cython and wanted to give it a go, thinking it might make it better/cleaner all around than what I had before. Most of the Cython documentation makes sense, and I've found most of what I know but the library...
[ "Create a cython typedef with the return type. In this way cython will use the same Macros of original library. \ncdef extern from \"header.h\":\n\n ctypedef void * win_api_t \"DAQAPI DaqHandleT WINAPI\"\n win_api_t daqOpen( char* ) \n\ncpdef pyDaqOpen( pystr ):\n daqOpen(pystr)\n\n" ]
[ 1 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0005438302_cython_python.txt
Q: Python pyodbc settings I am looking at a system that is using PyODBC and FreeTDS with a connection similar to the following: cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=srv;DATABASE=dbtable;UID=uid;PWD=pwd') I was wondering if after this connection is made, if it is possible to view the settings that are ac...
Python pyodbc settings
I am looking at a system that is using PyODBC and FreeTDS with a connection similar to the following: cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=srv;DATABASE=dbtable;UID=uid;PWD=pwd') I was wondering if after this connection is made, if it is possible to view the settings that are actually used. We dont current...
[ "What information do you need?\nYou can get many information using getinfo() (wrapper for SQLGetInfo()):\ndb = pyodbc.connect('DSN=northwind')\nisolation = db.getinfo(pyodbc.SQL_DEFAULT_TXN_ISOLATION)\nprint('isolation=%s' % isolation)\n\nHave a look at pgtests.py for more getinfo() usage examples.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005467383_python.txt
Q: offset/limit programmatically with python mysqldb Im trying to process data from a database table. Loading them all simultaneously will hog most of computer resource. Heres my current code cursor.execute("SELECT * from sometable") rs = cursor.fetchall() . # process 1: set operation . for a in rs: # process 2: ...
offset/limit programmatically with python mysqldb
Im trying to process data from a database table. Loading them all simultaneously will hog most of computer resource. Heres my current code cursor.execute("SELECT * from sometable") rs = cursor.fetchall() . # process 1: set operation . for a in rs: # process 2: put data in another db Is there a way to reduce resour...
[ "You can use cursor.fetchone(). Read about it here. Example usage:\ncursor.execute(query)\nnumrows = int(cursor.rowcount)\nfor x in range(0,numrows):\n row = cursor.fetchone()\n\nYou can also consider using LIMIT in the mysql query:\ncursor.execute(\"SELECT * from sometable LIMIT 0, 100\")\n\nFinally, avoid usin...
[ 1, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004364129_mysql_python.txt
Q: Reading and graphing data read from huge files We have pretty large files, the order of 1-1.5 GB combined (mostly log files) with raw data that is easily parseable to a csv, which is subsequently supposed to be graphed to generate a set of graph images. Currently, we are using bash scripts to turn the raw data int...
Reading and graphing data read from huge files
We have pretty large files, the order of 1-1.5 GB combined (mostly log files) with raw data that is easily parseable to a csv, which is subsequently supposed to be graphed to generate a set of graph images. Currently, we are using bash scripts to turn the raw data into a csv file, with just the numbers that need to be ...
[ "python sounds to be a good choice because it has a good threading API (the implementation is questionable though), matplotlib and pylab. I miss some more specs from your end but maybe this could be a good starting point for you: matplotlib: async plotting with threads.\nI would go for a single thread for handling ...
[ 4, 1 ]
[]
[]
[ "graphing", "large_files", "numpy", "python", "r" ]
stackoverflow_0005468921_graphing_large_files_numpy_python_r.txt
Q: Global variables in Python Hi I tried the following example (i don't have im in the global) and found that the program actually runs and outputs 10. Is Python dynamic scoped? def useGlobal(): def inSide(): print 'inside', print b b = 5 print im inSide() if __name__ == '__main__':...
Global variables in Python
Hi I tried the following example (i don't have im in the global) and found that the program actually runs and outputs 10. Is Python dynamic scoped? def useGlobal(): def inSide(): print 'inside', print b b = 5 print im inSide() if __name__ == '__main__': im = 10 useGlobal()
[ "The if statement doesn't create another scope in Python, therefore, the \"im\" is in the module level, namely, the global scope. \n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0005469630_python.txt
Q: How to generate an index for a file? For instance if a file has xxx|12 yyy|13 zzz|14 I need the output to be 1 xxx|12 2 yyy|13 3 zzz|14 How can I achieve that? A: import fileinput f=fileinput.FileInput("file",inplace=1) for line in f: print f.lineno(), line there are many other ways to do it. If y...
How to generate an index for a file?
For instance if a file has xxx|12 yyy|13 zzz|14 I need the output to be 1 xxx|12 2 yyy|13 3 zzz|14 How can I achieve that?
[ "import fileinput\nf=fileinput.FileInput(\"file\",inplace=1)\nfor line in f:\n print f.lineno(), line\n\nthere are many other ways to do it. If you are on a linux/unix system\nawk '{print NR,$0}' file\ncat -n file\nsed '=' file\nnl file\n\nAlso Ruby(1.9+)\nruby -ne 'print \"#{$.} #{$_}\"' file\n\n", "Use enu...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005469621_python.txt
Q: Truncating division in Python 3.2 Is integer floor division // faster than float division / in Python 3.2? If I know I'm going to be working with integers only, should I favour // instead of defaulting to /? How do I get integer truncation behaviour in Python 3.2? 1/2 = 0 -1/2 = 0 Thanks. A: from math import (f...
Truncating division in Python 3.2
Is integer floor division // faster than float division / in Python 3.2? If I know I'm going to be working with integers only, should I favour // instead of defaulting to /? How do I get integer truncation behaviour in Python 3.2? 1/2 = 0 -1/2 = 0 Thanks.
[ "from math import (floor, ceil)\ndef trunc_div(a, b):\n c = a / b\n return floor(c) if c > 0 else ceil(c)\n\nTest it to make sure it's right. It's late and I'm doing math while sleepy.\nActually, don't do that. While seeing if I could subclass int to do truncated division (don't do that either (also, it didn'...
[ 3 ]
[]
[]
[ "division", "python" ]
stackoverflow_0005469740_division_python.txt
Q: ZMQ failing when sending larger chunks of data over LAN well basically i have a single master system and 3 slave systems . I have used Request/Response phase to send the content to 3 of my client systems , since it inherently solves my problem of data splitting . After sending the content to 3 of my client system...
ZMQ failing when sending larger chunks of data over LAN
well basically i have a single master system and 3 slave systems . I have used Request/Response phase to send the content to 3 of my client systems , since it inherently solves my problem of data splitting . After sending the content to 3 of my client systems , i close the socket which was responsible to REQ/REP topo...
[ "PAIR sockets don't automatically reconnect, so they're not recommended for LAN use. \n" ]
[ 2 ]
[]
[]
[ "python", "sockets", "zeromq" ]
stackoverflow_0005461814_python_sockets_zeromq.txt
Q: Can't seem to load images in Django? This ought to be quite straight forward but I have a feeling one of the pathnames is screwing the whole thing up. Basically, my images are displaying as 404. Here are the relevant parts to my Django app: models.py class MemeDetails(models.Model): datecreated = models.DateT...
Can't seem to load images in Django?
This ought to be quite straight forward but I have a feeling one of the pathnames is screwing the whole thing up. Basically, my images are displaying as 404. Here are the relevant parts to my Django app: models.py class MemeDetails(models.Model): datecreated = models.DateTimeField(default=datetime.datetime.now) ...
[ "Your ADMIN_MEDIA_PREFIX is probably also /media/. Change one of them.\n", "change the MEDIA_URL\nMEDIA_URL = 'http://127.0.0.1:8000/media/' \n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python", "url" ]
stackoverflow_0005469783_django_django_admin_django_models_python_url.txt
Q: Line by line comparison of large text files with python I am working on some large (several million line) bioinformatics data sets with the general format: chromosomeNumber locusStart locusStop sequence moreData I have other files in this format: chromosomeNumber locusStart locusStop moreData What I need to be a...
Line by line comparison of large text files with python
I am working on some large (several million line) bioinformatics data sets with the general format: chromosomeNumber locusStart locusStop sequence moreData I have other files in this format: chromosomeNumber locusStart locusStop moreData What I need to be able to do is read one of each type of file into memory and if...
[ "It seems that for the lower file (which I assuming has the second format), the only field you are concerned about is 'locusStart'. Since, from your description, you do not necessarily care about the other data, you could make a set of all of the locusStart:\nlocusStart_list = set()\nwith open(upper_file, 'r') as f...
[ 0, 0, 0 ]
[]
[]
[ "performance", "python", "text_parsing" ]
stackoverflow_0005464649_performance_python_text_parsing.txt
Q: Parsing XML with Python xml.sax: How does one "keep track" of where in the tree you are? I need to regularly export XML files from our Administration software. This is the first time I'm using XML Parsing in Python. The XML with xml.sax isn't terribly difficult, but what is the best way to "keep track" of where in...
Parsing XML with Python xml.sax: How does one "keep track" of where in the tree you are?
I need to regularly export XML files from our Administration software. This is the first time I'm using XML Parsing in Python. The XML with xml.sax isn't terribly difficult, but what is the best way to "keep track" of where in the XML tree you are? For example, I have a list of our customers. I want to extract the Tele...
[ "I used sax too, but then I found a better tool: iterparse from ElementTree.\nIt is similar to sax, but you can retrieve elements with contents, to free the memory you just have to clear element once retrieved.\n", "Is there a specific reason you need to use SAX for this?\nBecause, if loading the entire XML file ...
[ 4, 2, 2, 1 ]
[]
[]
[ "python", "sax", "xml" ]
stackoverflow_0005418924_python_sax_xml.txt
Q: python can load modules from remote server? in python,can i load a module from remote server to local? what i do this is want to protect my source code. what should i do ,thanks A: it can be done via python import hooks. see knockout for an implementation that you can either use directly or as a starting point t...
python can load modules from remote server?
in python,can i load a module from remote server to local? what i do this is want to protect my source code. what should i do ,thanks
[ "it can be done via python import hooks. see knockout for an implementation that you can either use directly or as a starting point to add further code-protection logic\n", "A bit off topic but if source protection is what you need C-compile your python source with cython and distribute .pyd files.\nYou'll have t...
[ 2, 1, 0 ]
[]
[]
[ "load", "module", "python" ]
stackoverflow_0005470161_load_module_python.txt
Q: Why is shutil.rmtree() so slow? I went to check how to remove a directory in Python, and was led to use shutil.rmtree(). It's speed surprised me, as compared to what I'd expect from a rm --recursive. Are there faster alternatives, short of using subprocess module? A: The implementation does a lot of extra proces...
Why is shutil.rmtree() so slow?
I went to check how to remove a directory in Python, and was led to use shutil.rmtree(). It's speed surprised me, as compared to what I'd expect from a rm --recursive. Are there faster alternatives, short of using subprocess module?
[ "The implementation does a lot of extra processing:\ndef rmtree(path, ignore_errors=False, onerror=None):\n \"\"\"Recursively delete a directory tree.\n\n If ignore_errors is set, errors are ignored; otherwise, if onerror\n is set, it is called to handle the error with arguments (func,\n path, exc_info)...
[ 10, 3, 1 ]
[]
[]
[ "python", "rm" ]
stackoverflow_0005470939_python_rm.txt
Q: How can I speed up an animation? I'm trying to create a Matplotlib animation of my paw data, where you can see the pressure distribution on the entire pressure plate over time (256x64 sensors for 250 frames). I found a working example on Matplotlib's own site and managed to get it working on my own data. However t...
How can I speed up an animation?
I'm trying to create a Matplotlib animation of my paw data, where you can see the pressure distribution on the entire pressure plate over time (256x64 sensors for 250 frames). I found a working example on Matplotlib's own site and managed to get it working on my own data. However the 'animation' is awfully slow and I h...
[ "I found Joe Kington's answer that mentioned using Glumpy instead. At first I couldn't get it to work on my own data, but with some help on chat we managed to figure out how to adapt one of the Matplotlib examples that come with Glumpy to work on my data.\nimport numpy, glumpy\nfrom glumpy.pylab import *\n\nwindow ...
[ 10, 4, 1 ]
[]
[]
[ "animation", "python" ]
stackoverflow_0005003094_animation_python.txt