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: Non sorted eigenvalues for finding features in Python I am now trying some stuff with PCA but it's very important for me to know which are the features responsible for each eigenvalue. numpy.linalg.eig gives us the diagonal matrix already sorted but I wanted this matrix with them at the original positions. Does a...
Non sorted eigenvalues for finding features in Python
I am now trying some stuff with PCA but it's very important for me to know which are the features responsible for each eigenvalue. numpy.linalg.eig gives us the diagonal matrix already sorted but I wanted this matrix with them at the original positions. Does anybody know how I can make it?
[ "What Sven mentioned in his comments is correct. There is no \"default\" ordering of the eigenvalues. Each eigenvalue is associated with an eigenvector, and it is important is that the eigenvalue-eigenvector pair is matched correctly. You'll find that all languages and packages will do so. \nSo if R gives you eigen...
[ 1, 0 ]
[]
[]
[ "pca", "python" ]
stackoverflow_0006227589_pca_python.txt
Q: Performing many means in numpy Good Morning, I am implimenting a Cressman filter for doing distance weighted averages in Numpy.. I use a Ball Tree implimentation (thanks to Jake VanderPlas) to return a list of locatations for each point in a request array.. the query array (q) is shape [n,3] and at each point has ...
Performing many means in numpy
Good Morning, I am implimenting a Cressman filter for doing distance weighted averages in Numpy.. I use a Ball Tree implimentation (thanks to Jake VanderPlas) to return a list of locatations for each point in a request array.. the query array (q) is shape [n,3] and at each point has the x,y,z at point I want to do a we...
[ "You can find a discussion about the relative merits of the Cressman scheme vs using a Gaussian weight function at:\nhttp://www.flame.org/~cdoswell/publications/radar_oa_00.pdf\nThe key is to match the smoothing parameter to the data (I recommend using a value close to the average spacing between data points). Onc...
[ 0 ]
[]
[]
[ "interpolation", "mean", "numpy", "performance", "python" ]
stackoverflow_0006229080_interpolation_mean_numpy_performance_python.txt
Q: accessing two or more list in a single for-loop provided that I have two lists in same length, list_a, list_b. I can print they items in a single for loop as follows: for i in range(0, len(list_a)): print "%s %s" % (list_a[i], list_b[i]) is there any alternative and elegant way to do above mentioned task ? I ...
accessing two or more list in a single for-loop
provided that I have two lists in same length, list_a, list_b. I can print they items in a single for loop as follows: for i in range(0, len(list_a)): print "%s %s" % (list_a[i], list_b[i]) is there any alternative and elegant way to do above mentioned task ? I have tried for a, b in list_a, list_b: print ""
[ "You need zip():\nfor a, b in zip(list_a, list_b):\n # whatever\n\nWhen the lists are long and you are using Python 2.x, you might prefer itertools.izip() to save some memory.\n", "Or you also able to use the following statement to combine lists: \nmap(lambda x,y,z: (x,y,z), list_a, list_b, list_c)\n\n" ]
[ 11, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006229299_python_python_3.x.txt
Q: Running commands from within python that need root access I have been playing around with subprocess lately. As I do more and more; I find myself needing root access. I was wondering if there is an easy way to enter the root password for a command that needs it with subprocess module. So when I am prompted for the...
Running commands from within python that need root access
I have been playing around with subprocess lately. As I do more and more; I find myself needing root access. I was wondering if there is an easy way to enter the root password for a command that needs it with subprocess module. So when I am prompted for the password my script and provide it and run the command. I know ...
[ "It would probably be best to leverage sudo for the user running the Python program. You can specify specific commands and arguments that can be run from sudo without requiring a password. Here is an example:\nThere are many approaches but I prefer the one that assigns command sets to groups. So let's say we wan...
[ 10 ]
[]
[]
[ "python", "subprocess", "sudo" ]
stackoverflow_0006229358_python_subprocess_sudo.txt
Q: Checking compatible total orders given by a Python list I'm using the IPython shell here. Suppose I have two lists In [1]: L1 = [1,3,4,5,2] In [2]: L2 = [1,3,5,5,1] I'd like to say that L1 and L2 are compatible in the sense that the ordering generated by the indices of the increasing order of the elements are co...
Checking compatible total orders given by a Python list
I'm using the IPython shell here. Suppose I have two lists In [1]: L1 = [1,3,4,5,2] In [2]: L2 = [1,3,5,5,1] I'd like to say that L1 and L2 are compatible in the sense that the ordering generated by the indices of the increasing order of the elements are compatible. That is, L1 gives 0<4<1<2<3 while L2 gives {0,4}<...
[ "Part of the way there would be to generate a list of tuples of list-elements and indexes, I think. This can then be sorted by list-element value and the index extracted.\nSomething like:\nL1order = [t[1] for t in sorted(zip(L1, range(len(L1))))]\nL2order = [t[1] for t in sorted(zip(L2, range(len(L2))))]\nL1order =...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "compatibility", "list", "python" ]
stackoverflow_0006228375_compatibility_list_python.txt
Q: Scope of Objects Passed as Arguments - Python I want to send a session object of sqlalchemy to a function of another class . From class OraDialog's function oraconnect to class oraconn's assign function . Actually My need is to use the session object in oraconn's another function map I can't send the session objec...
Scope of Objects Passed as Arguments - Python
I want to send a session object of sqlalchemy to a function of another class . From class OraDialog's function oraconnect to class oraconn's assign function . Actually My need is to use the session object in oraconn's another function map I can't send the session object directly to map function because it is a slot - i...
[ "If you're using Qt, then this is likely a GUI app. Maybe there are threading issues; maybe self refers to different objects. It's hard to tell with only what you've given us. Before you go any further, add:\nprint self\n\nnear the top of each method. At least then you can confirm whether both are operating on the ...
[ 2, 0 ]
[]
[]
[ "object", "pyqt4", "python", "sqlalchemy" ]
stackoverflow_0006229393_object_pyqt4_python_sqlalchemy.txt
Q: How to manage string memory with python ctypes My python code is calling a C function in a native library (also written by me). The function takes two strings as arguments and returns its response as a string. The two argument strings that python passes to C library are only read by the C library, so I am not worr...
How to manage string memory with python ctypes
My python code is calling a C function in a native library (also written by me). The function takes two strings as arguments and returns its response as a string. The two argument strings that python passes to C library are only read by the C library, so I am not worried about their memory management. AFAIK, their memo...
[ "I'd recommend strongly against memory allocation in a foreign function called via ctypes and freeing this memory from Python. Whenever possible, allocate the memory in Python.\nIn your case, if you know in advance an upper limit for the length of the returned string, use\nbuf = ctypes.create_string_buffer(upper_l...
[ 4, 3 ]
[]
[]
[ "ctypes", "memory_management", "python" ]
stackoverflow_0006229610_ctypes_memory_management_python.txt
Q: How to convert 32digit long info hash to 40 digit long info hash in python? Some websites such as Sumotorrent.com use the magnet link with the 32 digit long hash, but my code is designed to store and work with 40 digit long hash? A: Luckily 32 is smaller than 40, so you can just pad with 8 zeroes without losing ...
How to convert 32digit long info hash to 40 digit long info hash in python?
Some websites such as Sumotorrent.com use the magnet link with the 32 digit long hash, but my code is designed to store and work with 40 digit long hash?
[ "Luckily 32 is smaller than 40, so you can just pad with 8 zeroes without losing information.\n", "The info hash in those magnet links appear to be encoded in Base32, while the info hash used in bittorrent is in hexadecimal (i.e. Base16). This appears to give consistent results:\nimport base64\nbase64.b16encode(b...
[ 1, 1 ]
[]
[]
[ "bittorrent", "hash", "python" ]
stackoverflow_0006227618_bittorrent_hash_python.txt
Q: Python subprocess fails, depending on how IDLE is opened On a MacBook Pro with Mac OS X version 10.6.7, I have a simple python script 'test.py': import subprocess subprocess.Popen(['xterm']) If I run this script by opening it in IDLE using the mouse, it crashes. If I run the same script in an IDLE that I launch b...
Python subprocess fails, depending on how IDLE is opened
On a MacBook Pro with Mac OS X version 10.6.7, I have a simple python script 'test.py': import subprocess subprocess.Popen(['xterm']) If I run this script by opening it in IDLE using the mouse, it crashes. If I run the same script in an IDLE that I launch by typing 'idle' in a terminal, it doesn't crash. What's going ...
[ "The difference in behavior you are seeing does indeed have to do with the PATH environment variable. When you start IDLE via a terminal shell, it inherits the PATH value from your shell environment. path_helper(8) sets the default value for a login shell PATH by consulting the entries in /etc/paths.d/. On OS X 1...
[ 2, 1 ]
[]
[]
[ "macos", "python", "python_idle", "subprocess" ]
stackoverflow_0006130042_macos_python_python_idle_subprocess.txt
Q: Will Python open a file before it's finished writing? I am writing a script that will be polling a directory looking for new files. In this scenario, is it necessary to do some sort of error checking to make sure the files are completely written prior to accessing them? I don't want to work with a file before i...
Will Python open a file before it's finished writing?
I am writing a script that will be polling a directory looking for new files. In this scenario, is it necessary to do some sort of error checking to make sure the files are completely written prior to accessing them? I don't want to work with a file before it has been written completely to disk, but because the info...
[ "Typically on Linux, unless you're using locking of some kind, two processes can quite happily have the same file open at once, even for writing. There are three ways of avoiding problems with this:\n\nLocking\nBy having the writer apply a lock to the file, it is possible to prevent the reader from reading the file...
[ 7, 4, 0, 0 ]
[]
[]
[ "file", "linux", "python" ]
stackoverflow_0006215324_file_linux_python.txt
Q: Getting PSP and Publisher handler working together in Apache2 mod-python I could just have mod-python working on apache2 for the first time and I could play with PSP and Publisher handler a little by adding either AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On Or AddHandler mod_pytho...
Getting PSP and Publisher handler working together in Apache2 mod-python
I could just have mod-python working on apache2 for the first time and I could play with PSP and Publisher handler a little by adding either AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On Or AddHandler mod_python .psp PythonHandler mod_python.psp PythonDebug On to /etc/apache2/sites-avai...
[ "This one works for me:\n<Directory /var/www>\n Options Indexes FollowSymLinks MultiViews\n AllowOverride All\n Order allow,deny\n allow from all\n AddHandler mod_python .py\n PythonHandler mod_python.publisher | .py\n AddHandler mod_python .psp .psp_\n Python...
[ 3 ]
[]
[]
[ "apache2", "mod_python", "python" ]
stackoverflow_0003860957_apache2_mod_python_python.txt
Q: Understanding Python Class Initialization Suppose I have two classes: class A(): pass class B(): pass I have another class class C(object): def __init__(self, cond): if cond ==True: # class C initialize with class A else: # class C initialize with class B If I ...
Understanding Python Class Initialization
Suppose I have two classes: class A(): pass class B(): pass I have another class class C(object): def __init__(self, cond): if cond ==True: # class C initialize with class A else: # class C initialize with class B If I inherit from A or B, by this implementation is ...
[ "If you want to set the class use the __class__ variable.\nclass C(object):\n def __init__(self, cond):\n if cond ==True:\n self.__class__ = A\n else:\n self.__class__ = B\n self.__class__.__init__(self)\n\n", "Since you didn't give a very good example why that could ev...
[ 4, 3, 1, 1 ]
[]
[]
[ "python", "superclass" ]
stackoverflow_0006229890_python_superclass.txt
Q: Reading lines from text file in python (windows) I am working on a simple import routine that translates a text file to a json file format for our system in python. import json # Open text file for reading txtFile = open('Boating.Make.txt', 'r') # Create picklist obj picklistObj = dict() picklistObj['name'] = '...
Reading lines from text file in python (windows)
I am working on a simple import routine that translates a text file to a json file format for our system in python. import json # Open text file for reading txtFile = open('Boating.Make.txt', 'r') # Create picklist obj picklistObj = dict() picklistObj['name'] = 'Boating.Make' picklistObj['items'] = list() i = 0 # I...
[ "Python keeps the new line characters while enumerating lines. For example, when enumerating a text file such as\nfoo\nbar\n\nyou get two strings: \"foo\\n\" and \"bar\\n\". If you don't want the terminal new line characters, you call strip().\nI am not a fan of this behavior by the way.\n", "See this. \n\nPython...
[ 3, 1, 0, 0 ]
[]
[]
[ "io", "json", "python", "windows" ]
stackoverflow_0006229910_io_json_python_windows.txt
Q: Python - reduce function and | operator I am looking at some Web2py code. The variable tokens is some kind of a list of strings. To be more precise, it is defined as tokens = form.vars.name.split() where form.vars.name is a string. My question deals with the following instruction : query = reduce(lambda a,b:a&b,[U...
Python - reduce function and | operator
I am looking at some Web2py code. The variable tokens is some kind of a list of strings. To be more precise, it is defined as tokens = form.vars.name.split() where form.vars.name is a string. My question deals with the following instruction : query = reduce(lambda a,b:a&b,[User.first_name.contains(k)|User.last_name.con...
[ "\nIn Web2Py & and | are not bitwise and/or here, but are used to build a special object that represents a database query! They correspond to AND and OR in SQL statements\ncontains is part of Web2Pys DAL\nSee 1.\nreduce is fold, a very fundamental higher order function that essentially reduces a list to a result, u...
[ 7, 0, 0 ]
[]
[]
[ "python", "reduce", "web2py" ]
stackoverflow_0006230117_python_reduce_web2py.txt
Q: Creating short tinyurls for Django model objects while maintaining clean code I'm using this code https://github.com/kylebragger/tiny/blob/master/tiny.py to transform integer primary keys into shortened URLs. For example, instead of using the url /articles/1000/title-of-article for article id 1000, the url might...
Creating short tinyurls for Django model objects while maintaining clean code
I'm using this code https://github.com/kylebragger/tiny/blob/master/tiny.py to transform integer primary keys into shortened URLs. For example, instead of using the url /articles/1000/title-of-article for article id 1000, the url might be transformed to /articles/a1b2c3/title-of-article. The problem with doing this i...
[ "If you store the shortened url in the database as a slug field of sorts then you can use it like any other slug field and filter on it directly, without having to convert it.\nAlternatively:\nYou may consider writing a custom manager for any model that uses this technique, that allows you to search the table for r...
[ 1 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0006230174_django_django_urls_python.txt
Q: How to parse list of dictionaries string returned by facebook api with python? Using django-social-auth to grab user data from facebook, it is returning a list of dicts in a unicode string. For example, response.get('education') for a user is returning: u"[{u'school': {u'id': u'12345', u'name': u'Joe Thiesman ...
How to parse list of dictionaries string returned by facebook api with python?
Using django-social-auth to grab user data from facebook, it is returning a list of dicts in a unicode string. For example, response.get('education') for a user is returning: u"[{u'school': {u'id': u'12345', u'name': u'Joe Thiesman High'}, u'type': u'High School'}, {u'school': {u'id': u'23456', u'name': u'Joe ...
[ "Take a look at the answer to this question :\nConvert a String representation of a Dictionary to a dictionary?\nThe use of python's ast.literal_eval might be very useful to you. It is also a lot safer to use than eval because it only will evaluate python data literals (strings, tuples, etc...) but not executable ...
[ 3, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006230164_django_python.txt
Q: 100% CPU usage with a regexp depending on input length I'm trying to come up with a regexp in Python that has to match any character but avoiding three or more consecutive commas or semicolons. In other words, only up to two consecutive commas or semicolons are allowed. So this is what I currently have: ^(,|;){,2}...
100% CPU usage with a regexp depending on input length
I'm trying to come up with a regexp in Python that has to match any character but avoiding three or more consecutive commas or semicolons. In other words, only up to two consecutive commas or semicolons are allowed. So this is what I currently have: ^(,|;){,2}([^,;]+(,|;){,2})*$ And it seems to work as expected: >>> r...
[ "You're running into catastrophic backtracking.\nThe reason for this is that you have made the separators optional, and therefore the [^,;]+ part (which is itself in a repeating group) of your regex will try loads of permutations (of baaaaaaaz) before finally having to admit failure when confronted with more than t...
[ 24, 11, 4, 1 ]
[]
[]
[ "cpu_usage", "python", "regex" ]
stackoverflow_0006230489_cpu_usage_python_regex.txt
Q: Is there a way to tell matplotlib to loosen the zoom on the plotted data? I have some data plotted which includes some limits on each subplot: Both axes have the limits, but since the data fits so nicely within the limits on the second plot, the limits themselves set the boudaries for the y-axis, making them invi...
Is there a way to tell matplotlib to loosen the zoom on the plotted data?
I have some data plotted which includes some limits on each subplot: Both axes have the limits, but since the data fits so nicely within the limits on the second plot, the limits themselves set the boudaries for the y-axis, making them invisible. To make them visible, I could do something like this: axes.set_ylim(1.1*...
[ "In regards to your request for a function to change the y-axis limits, would this suit your purposes?:\ndef larger_axlim( axlim ):\n \"\"\" argument axlim expects 2-tuple \n returns slightly larger 2-tuple \"\"\"\n axmin,axmax = axlim\n axrng = axmax - axmin\n new_min = axmin - 0.1 * axrng\n ...
[ 5 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006230627_matplotlib_python.txt
Q: Django aggregate count on ForeignKey returning multiple records for same ID The model structure is Question has one Video, and Question has many Answers. The problem query is: questions = Question.objects\ .values('id', 'answer', 'section__title', 'title', 'created_at','user__username')\ .filter(video=v).annot...
Django aggregate count on ForeignKey returning multiple records for same ID
The model structure is Question has one Video, and Question has many Answers. The problem query is: questions = Question.objects\ .values('id', 'answer', 'section__title', 'title', 'created_at','user__username')\ .filter(video=v).annotate(answer_count=Count('answer')) I'm using the Count aggregate function to add ...
[ "I'm not sure what your model definition is. I assume you have something like this:\nclass Answer(models.Models):\n question = models.ForeignKey(Question, related_name='answer')\n\nWhen you query the way you described, you will retrieve one row per answer. If you leave out 'answer', from the values call, you sho...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006230679_django_python.txt
Q: XPath predicate with sub-paths with lxml? I'm trying to understand and XPath that was sent to me for use with ACORD XML forms (common format in insurance). The XPath they sent me is (truncated for brevity): ./PersApplicationInfo/InsuredOrPrincipal[InsuredOrPrincipalInfo/InsuredOrPrincipalRoleCd="AN"]/GeneralParty...
XPath predicate with sub-paths with lxml?
I'm trying to understand and XPath that was sent to me for use with ACORD XML forms (common format in insurance). The XPath they sent me is (truncated for brevity): ./PersApplicationInfo/InsuredOrPrincipal[InsuredOrPrincipalInfo/InsuredOrPrincipalRoleCd="AN"]/GeneralPartyInfo Where I'm running into trouble is that Py...
[ "Change tree.find to tree.xpath. find and findall are present in lxml to provide compatibility with other implementations of ElementTree. These methods do not implement the entire XPath language. To employ XPath expressions containing more advanced features, use the xpath method, the XPath class, or XPathEvaluator....
[ 18, 3, 1, 0 ]
[]
[]
[ "lxml", "python", "xml", "xpath" ]
stackoverflow_0006218126_lxml_python_xml_xpath.txt
Q: Poplib not working correctly? I want to get all the messages from my gmail inbox, but I am facing 2 problems. It does not get all the emails, (as per the count in stat function) The order of emails it get is random. I am unsure if its the problem with poplib or gmail pop server. What am I missing here? A: What...
Poplib not working correctly?
I want to get all the messages from my gmail inbox, but I am facing 2 problems. It does not get all the emails, (as per the count in stat function) The order of emails it get is random. I am unsure if its the problem with poplib or gmail pop server. What am I missing here?
[ "What does your code look like? Using poplib, you're able to decide on the order and number of the messages downloaded. The code from the poplib documentation should work:\nimport getpass, poplib\n\nM = poplib.POP3('localhost')\nM.user(getpass.getuser())\nM.pass_(getpass.getpass())\nnumMessages = len(M.list()[1])\n...
[ 2, 2, 1, 0 ]
[]
[]
[ "poplib", "python", "python_2.5" ]
stackoverflow_0000617892_poplib_python_python_2.5.txt
Q: How to convert HTML CSS class into style in pure python - what kind of library could be used on GAE Is there any pure python library to use on Google App Engine which allow to convert HTML with CSS class into HTML with styles only for emailing purpose on gmail. Want to make such conversion on google app engine. X...
How to convert HTML CSS class into style in pure python - what kind of library could be used on GAE
Is there any pure python library to use on Google App Engine which allow to convert HTML with CSS class into HTML with styles only for emailing purpose on gmail. Want to make such conversion on google app engine. XHTML with CSS class: <p class="xx">xxx</p> <p class="yy">yyy</p> Considering that CSS is such: p.xx, p.yy...
[ "Take a look at xhtml2pdf (under Apache License) for the code that combines the HTML and CSS together and then change the output from PDF to HTML.\n" ]
[ 0 ]
[]
[]
[ "css", "email", "google_app_engine", "python" ]
stackoverflow_0005670684_css_email_google_app_engine_python.txt
Q: How do I build a web crawler that can extract particular information from any site? So I'm trying to build a web crawler that I can turn on any review site and have it fairly reliably scrape user reviews from the text. That is, rather than building a scraper for say Amazon and Overstocked, I just want a single scr...
How do I build a web crawler that can extract particular information from any site?
So I'm trying to build a web crawler that I can turn on any review site and have it fairly reliably scrape user reviews from the text. That is, rather than building a scraper for say Amazon and Overstocked, I just want a single scraper that can scrape the reviews for a product off of both them even if were to sacrifice...
[ "There isn't really an 'answer' to this question, but for the benefit of anyone coming across this question:\nThe concept of a 'generic' scraper is - at best - an interesting academic exercise. It is not likely to be possible in any useful way.\nTwo useful projects to look at are Scrapy, a python web scraping frame...
[ 4, 3, 0 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0006142475_python_web_crawler.txt
Q: python function-converting texting language to english? I'm having trouble creating a function that uses a dictionary of texting abbreviations, and using the dictionary to write functions that translate to and from English. For example: “y r u l8?” translates to “Why are you late?” So I have this so far: (I don't ...
python function-converting texting language to english?
I'm having trouble creating a function that uses a dictionary of texting abbreviations, and using the dictionary to write functions that translate to and from English. For example: “y r u l8?” translates to “Why are you late?” So I have this so far: (I don't need every single texting phrase) def text(string): tex...
[ "If you have a dictionary of replacements you can do this:\nreplacements = {\n 'lol': 'laugh out loud',\n 'y': 'why',\n 'l8': 'late',\n 'u': 'you',\n 'r': 'are'\n}\n\ns1 = 'y r u l8'\n\ns2 = ' '.join([replacements.get(w, w) for w in s1.split()])\n\n", "\nstring needs to be split into words\nthen loop through...
[ 6, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006230684_dictionary_python.txt
Q: Importing rpy module into python I'm trying to import the rpy1.0.3 module for python2.6.6 using: from rpy import * and getting this error: File "C:\Python26\lib\site-packages\rpy.py", line 58, in <module> RVERSION = rpy_tools.get_R_VERSION(RHOME) File "C:\Python26\lib\site-packages\rpy_tools.py", line 103, i...
Importing rpy module into python
I'm trying to import the rpy1.0.3 module for python2.6.6 using: from rpy import * and getting this error: File "C:\Python26\lib\site-packages\rpy.py", line 58, in <module> RVERSION = rpy_tools.get_R_VERSION(RHOME) File "C:\Python26\lib\site-packages\rpy_tools.py", line 103, in get_R_VERSION raise RuntimeError...
[ "The setup.py script is calling upon the rpy_tools.py script to gain access to the version number. It searches the output of R --version for a regular expression:\nversion = re.search(\" +([0-9]\\.[0-9]\\.[0-9])\", output)\n\nHowever, R is now in version 2.13.0, so it won't be able to find a two-digit version numbe...
[ 1 ]
[]
[]
[ "python", "r" ]
stackoverflow_0005890706_python_r.txt
Q: Setting bar spacing in a matplotlib bar plot I have a matplotlib.bar plot and I can't figure out how to space the bars further apart so the labels are readable. Here is my code import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def makePlot(self, data, labels, title, fileName): plt...
Setting bar spacing in a matplotlib bar plot
I have a matplotlib.bar plot and I can't figure out how to space the bars further apart so the labels are readable. Here is my code import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def makePlot(self, data, labels, title, fileName): plt.bar(range(1,len(data)+1), data, align="center") ...
[ "You can change the size of the figure by calling plt.figure(figsize=(x,y)) where x and y are the width and height in inches. That line must be before you call plt.bar. \nAlternatively, you can make the label font smaller. You would do that by changing your call to xticks to plt.xticks(range(1, len(labels)+1), l...
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006230457_matplotlib_python.txt
Q: Check if Cheetah Template Dict has key I am trying to come up with a base template for an application and one of the goals would be to remove any unnecessary js/css from pages so I want to do something in the cheetah template like #if $dict.has_key('datepicker'): <link rel="stylesheet" href="$datepicker" type="t...
Check if Cheetah Template Dict has key
I am trying to come up with a base template for an application and one of the goals would be to remove any unnecessary js/css from pages so I want to do something in the cheetah template like #if $dict.has_key('datepicker'): <link rel="stylesheet" href="$datepicker" type="text/css" /> #end if I think this would also...
[ "The bug is this:\ndict.has_key('datepicker')\n\n\"dict\" is a class, so it expects the first argument of \"dict.has_key\" to be an instance of \"dict\".\nYou're passing a string instead of the dict object.\nBasically, \"d.has_key(k)\" is equivalent to \"dict.has_key(d, k)\", and you have the latter.\n" ]
[ 1 ]
[]
[]
[ "cheetah", "python", "templates" ]
stackoverflow_0006230070_cheetah_python_templates.txt
Q: Rewriting 2D array of integers to bitmap in Python using PyQT I want to do convert array of integers into some sort of 'picture' using PyQt (I've decided to do my app in Qt). I have array like this: Array = [ [0,0,1,0,0], [0,1,0,1,0], [1,0,0,0,1], [0,1,0,1,0], [0,0,1,0,0]] Now I want to rewrite it into picture, b...
Rewriting 2D array of integers to bitmap in Python using PyQT
I want to do convert array of integers into some sort of 'picture' using PyQt (I've decided to do my app in Qt). I have array like this: Array = [ [0,0,1,0,0], [0,1,0,1,0], [1,0,0,0,1], [0,1,0,1,0], [0,0,1,0,0]] Now I want to rewrite it into picture, by replacing each integer by for example square 10x10 pixels. I have...
[ "You could easily do the above with QGraphicsScene and QGraphicsView. In order to get good performance, you'll want to call setViewport(QGLWidget()) on your QGraphicsView instance. Create a subclass of QGraphicsItem to represent an element in your array. You'll then even be able to animate the changes if you want.\...
[ 1, 1 ]
[]
[]
[ "arrays", "pyqt", "python", "qt" ]
stackoverflow_0006228106_arrays_pyqt_python_qt.txt
Q: Python: Making a GUI in nokia phone I am writing one of the Mobile monitoring program in my phone which I almost finished it. My program has a pedometer which counts human's steps in a real time manner. My question is that I am now writing GUI for phone which will show let's say some picture after they accomplish ...
Python: Making a GUI in nokia phone
I am writing one of the Mobile monitoring program in my phone which I almost finished it. My program has a pedometer which counts human's steps in a real time manner. My question is that I am now writing GUI for phone which will show let's say some picture after they accomplish 1000 steps(like an award) and so on. I am...
[ "Which phone model and OS are we talking about? Is it running Android?\nI believe pre-Android Nokia phones used Qt GUI framework\nPython has Qt wrappers, look into PyQt4 for all your UI needs.\n" ]
[ 0 ]
[]
[]
[ "mobile_phones", "python" ]
stackoverflow_0006230525_mobile_phones_python.txt
Q: Recommendations for a noSQL database for use with Python I'm writing a small Python CGI script that captures the User-Agent, parses the OS, browser name and version, maps it to a database, and returns a device grade (integer). Since this is only one table, it's a pretty simple operation, but I will likely have su...
Recommendations for a noSQL database for use with Python
I'm writing a small Python CGI script that captures the User-Agent, parses the OS, browser name and version, maps it to a database, and returns a device grade (integer). Since this is only one table, it's a pretty simple operation, but I will likely have substantial traffic (10,000+ hits a day, potentially scaling muc...
[ "I suggest Redis. It probably fits well for what you want to do. And it is fast but still simple to set up and use.\n", "It depends on your use-case. Are you planning on caching the records temporarily or do you want the records to persist? If the former, Redis would be the best choice because of its speed. If th...
[ 3, 2, 1 ]
[]
[]
[ "nosql", "python" ]
stackoverflow_0006230793_nosql_python.txt
Q: Nesting classes in order to imitate static members I am trying to imitate "static" member by nesting a class inside another class in order to define the classes constants. f.e. class foo: class NoAuthActions: Action1, Action2, Action3 = ["action1", "action2", "action3"] class AuthActions: Action4, Action5, Act...
Nesting classes in order to imitate static members
I am trying to imitate "static" member by nesting a class inside another class in order to define the classes constants. f.e. class foo: class NoAuthActions: Action1, Action2, Action3 = ["action1", "action2", "action3"] class AuthActions: Action4, Action5, Action6 = ["action4", "action5", "action6"] Is there a bet...
[ "Why the inner class?\nclass Foo:\n action1, action2, action3 = [\"action1\", \"action2\", \"action3\"]\n\nwill create a class Foo with three class attributes action1, action2 and action3. You can access them via Foo.action1 or foo.action1 for a Foo instance foo. To change the value of a class variable, use\nF...
[ 3, 0 ]
[]
[]
[ "api", "class_design", "python" ]
stackoverflow_0006230315_api_class_design_python.txt
Q: How to start mapreduce job from cron on GAE Python I have mapreduce job defined in mapreduce.yaml: mapreduce: - name: JobName mapper: input_reader: google.appengine.ext.mapreduce.input_readers.DatastoreInputReader handler: handler_name params: - name: entity_kind default: KindName How to ...
How to start mapreduce job from cron on GAE Python
I have mapreduce job defined in mapreduce.yaml: mapreduce: - name: JobName mapper: input_reader: google.appengine.ext.mapreduce.input_readers.DatastoreInputReader handler: handler_name params: - name: entity_kind default: KindName How to start it from cron? Is there some url that can run it?
[ "You can start a mapreduce task from any kind of AppEngine handler using control.py\nfrom mapreduce import control\n\nmapreduce_id = control.start_map(\n \"My Mapper\",\n \"main.my_mapper\",\n \"mapreduce.input_readers.DatastoreInputReader\",\n {\"entity_kind\": \"models.MyEntity\"},\n shard_count=10...
[ 10 ]
[ "Yes, if you look at the Getting Started page, it shows that you set the URL in your app.yaml:\nhandlers:\n- url: /mapreduce(/.*)?\n script: mapreduce/main.py\n login: admin\n\nYou then can just cron it in the usual App Engine fashion, which in this example would be writing a cron.yaml like this:\ncron:\n- descri...
[ -6 ]
[ "cron", "google_app_engine", "mapreduce", "python" ]
stackoverflow_0006228802_cron_google_app_engine_mapreduce_python.txt
Q: Is django-piston mature enough? I'm developing an advertising site and want to use web services for the requests. I mean, a publisher site will put a JavaScript snippet and it will pull a banner through a REST GET. Is the django-piston framework mature enough to implement this functionality? A: I've been looking...
Is django-piston mature enough?
I'm developing an advertising site and want to use web services for the requests. I mean, a publisher site will put a JavaScript snippet and it will pull a banner through a REST GET. Is the django-piston framework mature enough to implement this functionality?
[ "I've been looking into finding the \"best\" Django REST package and came across this table, which is useful: \nhttp://www.djangopackages.com/grids/g/api/\nAt this point (mid-2011) Django-Tastypie is the clear winner for number of authors, updated codebase, documentation, and overall activity.\nEDIT, Jan.2012: I th...
[ 13, 6, 1, 0 ]
[]
[]
[ "django", "django_piston", "python", "rest", "web_services" ]
stackoverflow_0003752607_django_django_piston_python_rest_web_services.txt
Q: how to smartly rewrite a python script that used to use XSLT? I have an old python app that used to use XSLT to transform some XML data (two types of xml files with their respective xslt ones) to produce html output. I'd like to port this app to appengine, but, sadly, appengine's python version doesn't support xs...
how to smartly rewrite a python script that used to use XSLT?
I have an old python app that used to use XSLT to transform some XML data (two types of xml files with their respective xslt ones) to produce html output. I'd like to port this app to appengine, but, sadly, appengine's python version doesn't support xslt. Is there an easy way to rewrite my code without manually pars...
[ "Unfortunately there is no working XSLT implementation in pure python. You may be able to adapt your python code to run on jython, which would give you access to java's XSLT implementation. This is described in this blog post.\nYou will have to decide if porting/testing your existing code to jython is a better opti...
[ 2, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "xml", "xslt" ]
stackoverflow_0006221518_google_app_engine_python_xml_xslt.txt
Q: User flow after registration I have the following user flow: 1) user registers. 2) user has a 'getting_started' page where he fills out some basic info and adds a picture. 3) user activates his email and logs in After a user has finished filling out his info on the getting started page, if he goes back to the page...
User flow after registration
I have the following user flow: 1) user registers. 2) user has a 'getting_started' page where he fills out some basic info and adds a picture. 3) user activates his email and logs in After a user has finished filling out his info on the getting started page, if he goes back to the page getting_started/, I want the user...
[ "Is it just the getting_started view/page that you want to redirect on? Don't think in terms of global variables, think in terms of database fields!\nOnce your user has signed up, they will be a registered user (if you are using djangos auth app) and they will have an entry in the database. Therefore you simply hav...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006232140_django_python.txt
Q: Save raw_post_data to FileField using Django I need to save some Raw Post Data (request.raw_post_data) straight to a FileField using Python/Django. All the information I have found so far is not helpful for saving RAW data. More specifically, the raw data is the wave data recorded from a Mic using Flash. Can someo...
Save raw_post_data to FileField using Django
I need to save some Raw Post Data (request.raw_post_data) straight to a FileField using Python/Django. All the information I have found so far is not helpful for saving RAW data. More specifically, the raw data is the wave data recorded from a Mic using Flash. Can someone please show me how this is done? Thanks!
[ "Ok. I figured it out. You can use SimpleUploadedFile like this:\nif request.method == 'POST':\n from django.core.files.uploadedfile import SimpleUploadedFile\n object = Model.objects.get(pk=1)\n file_contents = SimpleUploadedFile(\"%s.mp3\" % \"myfile\", request.raw_post_data, \"audio/mp3\")\n object.a...
[ 7 ]
[]
[]
[ "django", "python", "raw_post" ]
stackoverflow_0006232089_django_python_raw_post.txt
Q: Python: tell X to reserve screen space for application I am trying to solve the issue of reserving space on the screen for an application with X Window Manager (i.e. Linux platforms). I have seen this issue addressed and solved for Gtk and I asked the prompted the same question using Qt. Since no one reacted to th...
Python: tell X to reserve screen space for application
I am trying to solve the issue of reserving space on the screen for an application with X Window Manager (i.e. Linux platforms). I have seen this issue addressed and solved for Gtk and I asked the prompted the same question using Qt. Since no one reacted to the Qt-specific question (which I also addressed in other foru...
[ "After some research i found the solution using Python-Xlib.\nIn the code that generates the window, it is possible to get the window ID, which is the reference for the window on X. Depending on the GUI kit used, the method to get this ID may vary. Qt4 provides QWidget.winId(), Gtk+2 has its own means to reserve sp...
[ 6, 0 ]
[]
[]
[ "python", "x11" ]
stackoverflow_0005949230_python_x11.txt
Q: Django query across many-to-many relationship I'm trying to retrieve the following data in a view: user_profile has a one-to-one join to users user_profile has a many-to-many join to store, via the stores field store has a one-to-many join to targets, via targets.store I can retrieve all stores associated with a u...
Django query across many-to-many relationship
I'm trying to retrieve the following data in a view: user_profile has a one-to-one join to users user_profile has a many-to-many join to store, via the stores field store has a one-to-many join to targets, via targets.store I can retrieve all stores associated with a user by doing: user_profile = request.user.get_profi...
[ "Target.objects.filter( store__user_profile__user=request.user )\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0006232187_django_django_queryset_python.txt
Q: What is wrong with this Regular Expression? I am trying to create a test to verify that a link is rendered on a webpage. I'm not understanding what I'm doing wrong on this assertion test: self.assertRegexpMatches( response.content, r'<a href="/questions/?sort=elite" class="on" title="Staff Selected Questions">el...
What is wrong with this Regular Expression?
I am trying to create a test to verify that a link is rendered on a webpage. I'm not understanding what I'm doing wrong on this assertion test: self.assertRegexpMatches( response.content, r'<a href="/questions/?sort=elite" class="on" title="Staff Selected Questions">elite</a>') I know that the markup is on the page ...
[ "Why are you using a regex here? There's absolutely no reason to. You're just matching a simple string. Use:\nself.assertContains(response, '<a href=\"/questions/?sort=elite\" class=\"on\" title=\"Staff Selected Questions\">elite</a>')\n\n", "The ? in your regex is getting interpreted as a ? quantifier (end of th...
[ 8, 4, 1, 0 ]
[ "It's probably the \"<\" and \">\" characters. In some regular expression syntaxes they are special characters that indicate beginning and end of line.\nYou might look at a regular expression tester tool to help you learn them.\n" ]
[ -1 ]
[ "django", "python", "unit_testing" ]
stackoverflow_0006232218_django_python_unit_testing.txt
Q: problems importing python module I'm trying to use python's bitstring module in a script and am getting an import error. This error does not happen when running from interactive mode. Here's the code: import bitstring b = bitstring.BitArray(bin='001001111') When run like this: python test.py I get this: Attribu...
problems importing python module
I'm trying to use python's bitstring module in a script and am getting an import error. This error does not happen when running from interactive mode. Here's the code: import bitstring b = bitstring.BitArray(bin='001001111') When run like this: python test.py I get this: AttributeError: 'module' object has no attrib...
[ "I predict you have created a bitstring.py in your current directory.\n", "The problem is caused by a bitstring.py file in sys.path of test.py, but not in that of the interactive python shell. Most likely, there's a bitstring.py file in the directory test.py is in, and you started your shell from another working ...
[ 7, 1, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0006231853_import_module_python.txt
Q: Capturing CAPTCHA image with Python I tried using mechanize to see the URL of the image, but its a dynamic page generating a different image each time. I was wondering if there was any way to "capture" this image for viewing/saving. Thanks! A: The only way to save the image would be to make a single call to the ...
Capturing CAPTCHA image with Python
I tried using mechanize to see the URL of the image, but its a dynamic page generating a different image each time. I was wondering if there was any way to "capture" this image for viewing/saving. Thanks!
[ "The only way to save the image would be to make a single call to the CATPCHA URL programatically, save the result, and then present that saved result to the user. The whole point of CAPTCHA is that each request generates a unique/different reponse/image.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006232780_python.txt
Q: Configurable URLs in Django I have an app where I want the urls to have certain level of configuration, for example there's an url /jobs/programming/ and I want the 'jobs' part to be configured via settings.py: JOBS_URL = 'positions' So my urls.py looks something like this: ... #job listing + category url(r'^'+JO...
Configurable URLs in Django
I have an app where I want the urls to have certain level of configuration, for example there's an url /jobs/programming/ and I want the 'jobs' part to be configured via settings.py: JOBS_URL = 'positions' So my urls.py looks something like this: ... #job listing + category url(r'^'+JOBS_URL+'/(?P<cvar_name>[-\w]+)/$'...
[ "Instead of using a variable in your URL pattern, call a function to calculate the URL. That way you can do a sanity check on JOBS_URL and fall back to a reasonable default.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006233187_django_python.txt
Q: What are the advantages of "yield item" vs return iter(items)? In the examples below, resp.results is an iterator. Version1 : items = [] for result in resp.results: item = process(result) items.append(item) return iter(items) Version 2: for result in resp.results: yield process(result) Is returnin...
What are the advantages of "yield item" vs return iter(items)?
In the examples below, resp.results is an iterator. Version1 : items = [] for result in resp.results: item = process(result) items.append(item) return iter(items) Version 2: for result in resp.results: yield process(result) Is returning iter(items) in Version 1 any better/worse in terms of performance/...
[ "The first causes all the results to be calculated and stored while the second is a lazy load, whereby the results are calculated only when requested. That is, one will store and create a list of N items, while the other will store and create 0 items until you begin iterating through them.\nA better way of thinkin...
[ 4, 4, 3, 2, 1 ]
[]
[]
[ "iterator", "python", "unit_testing", "yield" ]
stackoverflow_0006231607_iterator_python_unit_testing_yield.txt
Q: Mocks or Stubs? I have a method that calls two other methods in it. def main_method(self, query): result = self.method_one(query) count = self.method_two(result) return count def method_one(self, query): #Do some stuff based on results. #This method hits the database. return result def method_two(sel...
Mocks or Stubs?
I have a method that calls two other methods in it. def main_method(self, query): result = self.method_one(query) count = self.method_two(result) return count def method_one(self, query): #Do some stuff based on results. #This method hits the database. return result def method_two(self, result): #Do som...
[ "Before worrying about testing main_method(), first test the smaller methods. Consider method_one(). For the purpose of discussion, let's say it exists in a class like this:\nclass Foo(object):\n def method_one(self, query):\n # Big nasty query that hits the database really hard!!\n return query.al...
[ 5 ]
[]
[]
[ "mocking", "mox", "python", "stubs", "unit_testing" ]
stackoverflow_0006233499_mocking_mox_python_stubs_unit_testing.txt
Q: Django Combine a Variable Number of QuerySets Is there a way to concatenate a unknown number of querysets into a list? Here are my models: class Item(models.Model): name = models.CharField(max_length=200) brand = models.ForeignKey(User, related_name='brand') tags = models.ManyToManyField(Tag, blank=Tr...
Django Combine a Variable Number of QuerySets
Is there a way to concatenate a unknown number of querysets into a list? Here are my models: class Item(models.Model): name = models.CharField(max_length=200) brand = models.ForeignKey(User, related_name='brand') tags = models.ManyToManyField(Tag, blank=True, null=True) def __unicode__(self): r...
[ "Slightly unorthodox, but you could use recursion. So in your example:\ndef recursive_search(tags, results_queryset):\n if len(tags) > 0:\n result_qs = result_queryset.filter(tags_name=tags[0])\n if result_queryset.exists():\n return filter_recursion(tags[1:],result_queryset)\n el...
[ 3 ]
[]
[]
[ "django", "django_queryset", "python", "python_itertools" ]
stackoverflow_0006233493_django_django_queryset_python_python_itertools.txt
Q: UnicodeEncodeError in django app I'm trying to create an app using Django on webfaction. I basically was messing around with the Amazon API, and when one of the search results has a trademark symbol, which is passed to my template...the error is thrown. I'm getting the error Caught UnicodeEncodeError while renderi...
UnicodeEncodeError in django app
I'm trying to create an app using Django on webfaction. I basically was messing around with the Amazon API, and when one of the search results has a trademark symbol, which is passed to my template...the error is thrown. I'm getting the error Caught UnicodeEncodeError while rendering: 'ascii' codec can't encode charact...
[ "It probably means you are calling str() on a a peice of unicode data - the str function could be called ascii to better describe what it does! Your templates will be totally happy with unicode data so given that you are using Django I suspect the problem is in a __unicode__ method or some such.\nUnicode is a trick...
[ 3, 1 ]
[]
[]
[ "django", "python", "unicode", "webfaction" ]
stackoverflow_0006233230_django_python_unicode_webfaction.txt
Q: Is there a field in django that can have multiple foreign key fields? Is there a field in django that can have multiple foreign key fields? I have the following code: from django.db import models from django.auth.models import * class Wish(Model): name = CharField(max_length=128) cost = IntegerField() ...
Is there a field in django that can have multiple foreign key fields?
Is there a field in django that can have multiple foreign key fields? I have the following code: from django.db import models from django.auth.models import * class Wish(Model): name = CharField(max_length=128) cost = IntegerField() person = ForeignKey(Person) date = DateField('Date Wished') comment...
[ "Try using the ManyToMany field. \nNote that ManyToMany to the same model, is assumed to be symmetrical - if Person A is a friend of Person B, then Person B will also be a friend of Person A. You can specify symmetrical=False to avoid that.\n", "I think you want a ManyToMany field. In this example you would be sa...
[ 4, 1 ]
[]
[]
[ "django", "foreign_keys", "models", "python" ]
stackoverflow_0006233847_django_foreign_keys_models_python.txt
Q: Python extented slicing with lists: is the documentation correct? The docs at http://docs.python.org/reference/expressions.html#slicings say (with some excerpts): 5.3.3. Slicings A slicing selects a range of items in a sequence object (e.g., a string, tuple or list). slicing ::= simple_slicing | exten...
Python extented slicing with lists: is the documentation correct?
The docs at http://docs.python.org/reference/expressions.html#slicings say (with some excerpts): 5.3.3. Slicings A slicing selects a range of items in a sequence object (e.g., a string, tuple or list). slicing ::= simple_slicing | extended_slicing simple_slicing ::= primary "[" short_slice "]" extended_...
[ "The language about a mapping is broken; it should say 'sequence or mapping' in all cases to match the behaviour of the interpreter. Both protocols can accept slice objects, and the interpreter will do the conversion in all cases. However, for the built-in types, only the sequences actually support it: \n >>> a = {...
[ 2, 1 ]
[]
[]
[ "list", "python", "slice" ]
stackoverflow_0006191765_list_python_slice.txt
Q: GAE Models: How to list child nodes in parent Using Google App Engine in Python and references, you automatically get a back reference from the referenced object to the one you're dealing with. This is described very well in the answer found here. What I'd like to do is create a (simpler) one-to-many relationship...
GAE Models: How to list child nodes in parent
Using Google App Engine in Python and references, you automatically get a back reference from the referenced object to the one you're dealing with. This is described very well in the answer found here. What I'd like to do is create a (simpler) one-to-many relationship, with each Group having a list of Tags, and each T...
[ "How are you going to query your tags, will you be concerned only with tags from a particular entity group? If that is the case, since you're going to put your Tag entities in a Group entity's entity group, the ReferenceProperty provides no real value. You could instead use tag_entity.key().parent() to get the Gr...
[ 1, 1, 0 ]
[]
[]
[ "database", "google_app_engine", "python" ]
stackoverflow_0006232092_database_google_app_engine_python.txt
Q: .NET array is slower than list in IronPython? I did the following matrix multiplication benchmark in IronPython based on code here: from System import Random from System.Diagnostics import Stopwatch def zero(m,n): # Create zero matrix new_matrix = [[0 for row in range(n)] for col in range(m)] return n...
.NET array is slower than list in IronPython?
I did the following matrix multiplication benchmark in IronPython based on code here: from System import Random from System.Diagnostics import Stopwatch def zero(m,n): # Create zero matrix new_matrix = [[0 for row in range(n)] for col in range(m)] return new_matrix def rand(m,n): # Create random matri...
[ "For your particular question, I think the problem is boxing - in IronPython, list items (and all other variables) are stored boxed, so only boxed values are operated on. CLR Array elements are not boxed, however, and thus IronPython will have to box them when they are extracted from the array, and then unbox them ...
[ 2, 1, 0, 0 ]
[]
[]
[ ".net", "ironpython", "python" ]
stackoverflow_0006199657_.net_ironpython_python.txt
Q: Passing static JSON to Django Template - best practices? I have a JSON data file that is part of my application (version controlled, etc.), and several of our templates need the data in this file to render properly. What are the pros and cons of various ways of making this JSON data available to the templates? Let...
Passing static JSON to Django Template - best practices?
I have a JSON data file that is part of my application (version controlled, etc.), and several of our templates need the data in this file to render properly. What are the pros and cons of various ways of making this JSON data available to the templates? Let's start with the fairly simple option of storing the JSON dat...
[ "If the data should be available on many/all pages, than a context_processor might be your best solution: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATE_CONTEXT_PROCESSORS\nIf you only need it on a couple of specific pages, than you can simply pass it to the template like you are doing now...
[ 1, 1 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0006234242_django_json_python.txt
Q: How to print password combination (but with custom constraints for each index) I am trying to build a dynamic password recovery tool. You can specify a password, and an unknown character list which correspond to unknown password indexes. So, if you remember 90% of your password, and can't remember a few letters, t...
How to print password combination (but with custom constraints for each index)
I am trying to build a dynamic password recovery tool. You can specify a password, and an unknown character list which correspond to unknown password indexes. So, if you remember 90% of your password, and can't remember a few letters, this will do a light weight brute force for you. I am able to combine the user suppli...
[ "Do you mean something like this?\n>>> import itertools\n>>> \n>>> password = 'Dude123' \n>>> charList = ['d8','vV','','D8','','',''] \n>>> \n>>> finalString = [''.join(set((a, b))) for a, b in zip(password, charList)] \n>>> \n>>> possibles = list(''.join(poss) for poss in itertools.product(*finalString))\n>>> poss...
[ 3 ]
[]
[]
[ "combinations", "loops", "passwords", "python", "string" ]
stackoverflow_0006234395_combinations_loops_passwords_python_string.txt
Q: Accesing PyQt Gui elements from another file I am learning PyQt and coming from webdesign, so excuse this question that must have very obvious answer.So I am building a PyQt application and I would like to spread methods to several files to correspond different parts of GUI. How can I access textbox locating in fi...
Accesing PyQt Gui elements from another file
I am learning PyQt and coming from webdesign, so excuse this question that must have very obvious answer.So I am building a PyQt application and I would like to spread methods to several files to correspond different parts of GUI. How can I access textbox locating in fileA.py from fileB.py. : #fileA.py import sys from ...
[ "You can take advantage of Python's class inheritance, like so:\nfileA.py:\nimport sys\nfrom PyQt4 import QtGui, QtCore\nfrom gui1 import Ui_MainWindow\nimport fileB\n\nclass MyApp(fileB.MyApp, QtGui.QMainWindow):\n def __init__(self):\n self.MyMethod()\n # Should print 'foo'\n\nfileB.py:\nimport sys\nfrom...
[ 2, 1 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006234263_pyqt_python.txt
Q: Comet protocol and Django - I know some options but I can't seem to make them WORK I'm very interested in making real-time web apps with Django. Unfortunately, I'm having more than a little bit of problem with setting things up. Some options I'm considering: Orbited: Seems to be the choice for Django. Unfortun...
Comet protocol and Django - I know some options but I can't seem to make them WORK
I'm very interested in making real-time web apps with Django. Unfortunately, I'm having more than a little bit of problem with setting things up. Some options I'm considering: Orbited: Seems to be the choice for Django. Unfortunately, their domains have seemingly expired, and with it pretty much all of the document...
[ "To do real-time web apps using comet techniques (or websocket) you need a server that can handle long-lived connections and a javascript client. Most of the comet libraries give you both (APE, orbited, etc). Working with websockets seems preferable to me, it's part of HTML5, the client code is really simple to imp...
[ 5, 0 ]
[]
[]
[ "comet", "django", "python" ]
stackoverflow_0006233762_comet_django_python.txt
Q: We need to pickle any sort of callable Recently a question was posed regarding some Python code attempting to facilitate distributed computing through the use of pickled processes. Apparently, that functionality has historically been possible, but for security reasons the same functionality is disabled. On the sec...
We need to pickle any sort of callable
Recently a question was posed regarding some Python code attempting to facilitate distributed computing through the use of pickled processes. Apparently, that functionality has historically been possible, but for security reasons the same functionality is disabled. On the second attempted at transmitting a function obj...
[ "You could marshal the bytecode and pickle the other function things:\nimport marshal\nimport pickle\n\nmarshaled_bytecode = marshal.dumps(your_function.func_code)\n# In this process, other function things are lost, so they have to be sent separated.\npickled_name = pickle.dumps(your_function.func_name)\npickled_ar...
[ 14 ]
[]
[]
[ "distributed_computing", "python" ]
stackoverflow_0006234586_distributed_computing_python.txt
Q: How to embed Lua inside Python? This sounds like a weird question, so I'll explain circumstances surrounding first. Basically, I have a 3D game development kit, written in Python, that works excellently by itself. However, most of my users will be used to using Lua as a scripting language, so I started to look at ...
How to embed Lua inside Python?
This sounds like a weird question, so I'll explain circumstances surrounding first. Basically, I have a 3D game development kit, written in Python, that works excellently by itself. However, most of my users will be used to using Lua as a scripting language, so I started to look at Lua-Python bindings. I settled with S...
[ "you should look into lunatic-python it is a 2 way bridge between python and lua. \nan example off the site shows how natural and easy it is:\n>>> import lua\n>>> lg = lua.globals()\n>>> lg.string\n<Lua table at 0x81c6a10>\n>>> lg.string.lower\n<Lua function at 0x81c6b30>\n>>> lg.string.lower(\"Hello world!\")\n'h...
[ 4 ]
[]
[]
[ "embedding", "lua", "python" ]
stackoverflow_0006234252_embedding_lua_python.txt
Q: Can I use Scrapy functions inside Django classes I have build a website in Django. I need to use the web crawling features. So I installed Scrapy. Scrapy is working, as stated in their tutorial, by using scrapy startproject dmoz But that works on a diff folder with its own files. Is it possible to use Scrapy func...
Can I use Scrapy functions inside Django classes
I have build a website in Django. I need to use the web crawling features. So I installed Scrapy. Scrapy is working, as stated in their tutorial, by using scrapy startproject dmoz But that works on a diff folder with its own files. Is it possible to use Scrapy functions in Django classes and put data in Django variabl...
[ "Crawling is a long, time consuming task. It doesn't mix well with short HTTP requests. Therefore, you should use a user interface (presumably written in Django) to fire off Scrapy crawls, and a shared storage to monitor the state of the crawl. \nBut you wouldn't want to crawl during the lifetime of a HTTP requests...
[ 1 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0006229932_python_scrapy.txt
Q: chain the function as shell pipe command in python In Unix/linux shell we can: seq 0 100 | head -10 | awk 'NF%2==0' | awk 'NF%2==1' | rev Now I defined: seqsrc = list(range(0,100)) def all(src): return src def head(src, count, offset = 0): return src[:count] def tail(src, count, offset = 0): return src[-count:] ...
chain the function as shell pipe command in python
In Unix/linux shell we can: seq 0 100 | head -10 | awk 'NF%2==0' | awk 'NF%2==1' | rev Now I defined: seqsrc = list(range(0,100)) def all(src): return src def head(src, count, offset = 0): return src[:count] def tail(src, count, offset = 0): return src[-count:] def odd(src): return [x for x in src if x % 2 != 0] def ...
[ "There are many questions in your post and I'm not certain to understand them all. However, here is a starting point.\nChainable methods are usually implemented by designing classes with methods that return new instances of the class itself. This allows to call further methods from the return value of previous meth...
[ 4 ]
[]
[]
[ "function", "pipe", "python", "shell" ]
stackoverflow_0006235051_function_pipe_python_shell.txt
Q: comparing contents of two files using python I have a file name exclusionlist.txt and i have contents in it like import os import re import subprocess ......and many more I have another file named libraries.txt and the contents of this file are import mymodule ...
comparing contents of two files using python
I have a file name exclusionlist.txt and i have contents in it like import os import re import subprocess ......and many more I have another file named libraries.txt and the contents of this file are import mymodule import empmodule,os import subproces...
[ "Use set intersection:\ndef readImports(path):\n with open(path) as f:\n for line in f:\n # lines of form \"import ___,___\"\n # assuming not of form \"from ___ import ___ [as ___]\"\n if 'import' in line:\n modules = line.split('import')[1]\n ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006235126_python.txt
Q: Converting separate functions into class-based I have several function that need to have a 'redirect' filter. The redirect filter goes something like this -- 1) if a user is not logged in and has no session data, redirect to login page. 2) if a user is logged in and has already filled out the page, redirect to use...
Converting separate functions into class-based
I have several function that need to have a 'redirect' filter. The redirect filter goes something like this -- 1) if a user is not logged in and has no session data, redirect to login page. 2) if a user is logged in and has already filled out the page, redirect to user home. 3) if a user is logged in and has not alread...
[ "Django actually already includes a login_required decorator that makes handling user authentication trivial. Just include the following at the top of your view.py page:\nfrom django.contrib.auth.decorators import login_required\n\nand then add \n@login_required \n\nbefore any views that require a login. It even ha...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006235146_django_python.txt
Q: compare file contents using python Possible Duplicate: comparing contents of two files using python I have a file name globalexclusionlist.txt and i have contents in it like #include <stdio.h> #include <iostream> import subprocess import java.sql.*;import java.io.*; ruby library ...
compare file contents using python
Possible Duplicate: comparing contents of two files using python I have a file name globalexclusionlist.txt and i have contents in it like #include <stdio.h> #include <iostream> import subprocess import java.sql.*;import java.io.*; ruby library show tables; ......and many ...
[ "Check out difflib\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006235377_python.txt
Q: How to stop sqlite from return unicode symbol I could be mistaken but since I backtracked to python 2.7 from 3.2 I've noticed something sqlite3 is doing that I don't like... When I use to use my cursor.fetch method it would return (1, x, x, x) from my table but in 2.7 its returning (1, u'x' ,u'x' ,u'x') How do I g...
How to stop sqlite from return unicode symbol
I could be mistaken but since I backtracked to python 2.7 from 3.2 I've noticed something sqlite3 is doing that I don't like... When I use to use my cursor.fetch method it would return (1, x, x, x) from my table but in 2.7 its returning (1, u'x' ,u'x' ,u'x') How do I get it to stop returning that 'u' in my queries? I n...
[ "Sigh.\n(1, u'x' ,u'x' ,u'x') is a tuple. That tuple contains four elements. One of them is an integer, the other three are unicode strings, as indicated by the u.\nIf you print the entire tuple at once, it will look like the above. But that's a silly thing to do, because presumably you actually want to do somethin...
[ 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006235521_python_sqlite.txt
Q: How to make a chronological list of files, with the file modification date I want to create a list of those files in a directory which have the extension .bas, and which were modified after June 1, 2011. Also, I'd like to know how to optionally have the files in the list appear with the date and time the file was...
How to make a chronological list of files, with the file modification date
I want to create a list of those files in a directory which have the extension .bas, and which were modified after June 1, 2011. Also, I'd like to know how to optionally have the files in the list appear with the date and time the file was last modified, e.g., 'filename.bas 2011-06-04_AM.00.30' I am a python newbie. ...
[ "Collect files and dates in a list of tuples and sort that list by the date element. Here is the example code, the comments in it should be sufficient to understand it:\nfrom stat import S_ISREG, ST_CTIME, ST_MODE\nimport os, sys, time, glob\nsearch_dir = r\"e:\\test\"\nfiles = filter(os.path.isfile, glob.glob(sear...
[ 4 ]
[]
[]
[ "datetime", "directory_listing", "python" ]
stackoverflow_0006235639_datetime_directory_listing_python.txt
Q: Python, iterated list comprehension The class Item has a member function text() that returns a list of strings. The class Dictionary has a member function items() that returns a list of Items. dict is an instance of Dictionary. I want to test if all characters in all strings in all items in dict are ASCII. I tried...
Python, iterated list comprehension
The class Item has a member function text() that returns a list of strings. The class Dictionary has a member function items() that returns a list of Items. dict is an instance of Dictionary. I want to test if all characters in all strings in all items in dict are ASCII. I tried all(ord(ch) < 128 for ch in s for s in i...
[ "The order of the for clauses needs to be the other way around. The innermost loop comes last, the outmost loop comes first.\nall(ord(ch) < 128 for item in dict.items() for s in item.text() for ch in s)\n\n" ]
[ 5 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0006235734_list_comprehension_python.txt
Q: How to get the name of attribute in python object? For example I have next python class class Myclass(): a = int b = int Imagine that I don't know the name this class, so I need to get the names of attributes? ("a" and "b") A: If you want all (including private) attributes, just dir(Myclass) Attribu...
How to get the name of attribute in python object?
For example I have next python class class Myclass(): a = int b = int Imagine that I don't know the name this class, so I need to get the names of attributes? ("a" and "b")
[ "If you want all (including private) attributes, just\ndir(Myclass)\n\nAttributes starting with _ are private/internal, though. For example, even your simple Myclass will have a __module__ and an empty __doc__ attribute. To filter these out, use\nfilter(lambda aname: not aname.startswith('_'), dir(Myclass))\n\n" ]
[ 10 ]
[]
[]
[ "attributes", "object", "python" ]
stackoverflow_0006235779_attributes_object_python.txt
Q: "if var and var2 == getSomeValue()" in python - if the first is false, is the second statement evaluated?' I have some code like this: if var: if var2 == getSomeValue() This could be in a single expression. if var and var2 == getSomeValue(): ...but getSomeValue() can only be called if var is True. So, when c...
"if var and var2 == getSomeValue()" in python - if the first is false, is the second statement evaluated?'
I have some code like this: if var: if var2 == getSomeValue() This could be in a single expression. if var and var2 == getSomeValue(): ...but getSomeValue() can only be called if var is True. So, when calling if var and var2 == getSomeValue(), are both evaluated by the interpreter, or the evaluation stops at var ...
[ "This is called short-circuiting, and Python does it, so you're good.\nUPDATE: Here's a quick example.\n>>> def foo():\n... print \"Yay!\"\n... \n>>> if True and foo() is None:\n... print \"indeed\"\n... \nYay!\nindeed\n>>> if False and foo() is None:\n... print \"nope\"\n... \n\nUPDATE 2: Putting the r...
[ 10, 2, 2, 1, 1, 1 ]
[]
[]
[ "python", "short_circuiting" ]
stackoverflow_0006230701_python_short_circuiting.txt
Q: How does "is" work in python? Can please someone explain how one may use 'is' in an 'if' condition. I am working with the fractions module, and I'm having some trouble: >>> Fraction(0, 1) is 0 False >>> float(Fraction(0, 1)) 0.0 >>> float(Fraction(0,1)) is 0.0 False The only thing I found to work is: >>> F = Frac...
How does "is" work in python?
Can please someone explain how one may use 'is' in an 'if' condition. I am working with the fractions module, and I'm having some trouble: >>> Fraction(0, 1) is 0 False >>> float(Fraction(0, 1)) 0.0 >>> float(Fraction(0,1)) is 0.0 False The only thing I found to work is: >>> F = Fraction(a,b) >>> if F >= 0: ... if...
[ "From the documentation: \n\nThe operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value. \n\nWhat you want here is ==, to test whether two objects are equal or equivalent by comparing the values and not the identities.\n...
[ 6, 6, 5, 3, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0006235684_module_python.txt
Q: xml writer/editor -- use python's version? I need to learn/write XML and I already have python downloaded as I am also learning python. I did notice that there was another question on stackoverflow about xml writers and python but I didn't get the idea that there was real consensus on what's easiest to use? That ...
xml writer/editor -- use python's version?
I need to learn/write XML and I already have python downloaded as I am also learning python. I did notice that there was another question on stackoverflow about xml writers and python but I didn't get the idea that there was real consensus on what's easiest to use? That is, I would ideally like an XML editor that high...
[ "You're asking about two separate things.\nXML Notepad and the NetBeans utility are apps for visually creating and editing XML.\nPython's ElementTree is a library for programmatically creating and parsing XML.\nWhich one you need depends on what you want to do - create XML in an editor, or do it inside your program...
[ 3, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0006235910_python_xml.txt
Q: Any implementations of graph st-ordering or ear-decomposition? I'm in the search for an implementation of an ear-decomposition algorithm (http://www.ics.uci.edu/~eppstein/junkyard/euler/ear.html). I examined networkx and didn't find one. Although the algorithm layout is vaguely in my mind, I'd like to see some ref...
Any implementations of graph st-ordering or ear-decomposition?
I'm in the search for an implementation of an ear-decomposition algorithm (http://www.ics.uci.edu/~eppstein/junkyard/euler/ear.html). I examined networkx and didn't find one. Although the algorithm layout is vaguely in my mind, I'd like to see some reference implementation, too. I'm aware of Ulrik Brandes publication o...
[ "I dug this up, but the credit goes to it's author Minjae Park\n# 20106911 Minjae Park\n# Finding an Ear decomposition of 2(-edge)-connected graph\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\ncolorList = [\"orange\", \"blue\", \"red\", \"green\", \"magenta\", \"purple\", \"yellow\", \"black\"]\nglob...
[ 2 ]
[]
[]
[ "decomposition", "graph", "math", "networkx", "python" ]
stackoverflow_0002716918_decomposition_graph_math_networkx_python.txt
Q: best practice for passing values between functions in Python What is pythonic best practice for allowing one function to use another function's returned values? e.g. Is it better to call one function within another, or better that function1 returns to the class, and class variables are assigned that are then used ...
best practice for passing values between functions in Python
What is pythonic best practice for allowing one function to use another function's returned values? e.g. Is it better to call one function within another, or better that function1 returns to the class, and class variables are assigned that are then used by function2? Secondly, how many different ways could you pass val...
[ "As import this would say, \"explicit is better than implicit\"; so go with the first form.\nIf the number of return values becomes large, let use_value take a sequence argument instead.\n", "All ways are valid and depend completely on your subject domain and the compartmentalisation of functionality, the separat...
[ 9, 4, 1 ]
[]
[]
[ "function", "python", "return_value" ]
stackoverflow_0006236032_function_python_return_value.txt
Q: write lisp dialect Do you have any advice for writing a Lisp dialect/interpreter in Python? I'd like to start off with just several basic commands, like set, print, and define or something. A: There's a fully functional Scheme interpreter in Python here. Its main "eval loop" is just this: def _eval(self, expr, e...
write lisp dialect
Do you have any advice for writing a Lisp dialect/interpreter in Python? I'd like to start off with just several basic commands, like set, print, and define or something.
[ "There's a fully functional Scheme interpreter in Python here. Its main \"eval loop\" is just this:\ndef _eval(self, expr, env):\n if DEBUG: print('~~~~ Eval called on %s [%s]' % (expr_repr(expr), type(expr)))\n if DEBUG: print('Env:')\n if DEBUG: pprint.pprint(env.binding)\n\n # Standard Scheme eval (S...
[ 6, 4 ]
[]
[]
[ "dialect", "interpreter", "lisp", "python" ]
stackoverflow_0006235472_dialect_interpreter_lisp_python.txt
Q: python groupby behaviour? >>from itertools import groupby >>keyfunc = lambda x : x > 500 >>obj = dict(groupby(range(1000), keyfunc)) >>list(obj[True]) [999] >>list(obj[False]) [] range(1000) is obviously sorted by default for the condition (x > 500). I was expecting the numbers from 0 to 999 to be grouped in a di...
python groupby behaviour?
>>from itertools import groupby >>keyfunc = lambda x : x > 500 >>obj = dict(groupby(range(1000), keyfunc)) >>list(obj[True]) [999] >>list(obj[False]) [] range(1000) is obviously sorted by default for the condition (x > 500). I was expecting the numbers from 0 to 999 to be grouped in a dict by the condition (x > 500)...
[ "From the docs:\n\nThe returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list[.]\n\nAnd you are storing iter...
[ 25, 11, 4 ]
[]
[]
[ "dictionary", "group_by", "iterator", "python" ]
stackoverflow_0006236081_dictionary_group_by_iterator_python.txt
Q: How to print Radio Control information I am using mechanize module to retrieve information from a web page. It has a radio control section which I select before moving to the next page. I could easily select the value by assigning value to it. But coulnt retrieve the value of the candidate radio button. RadioSelec...
How to print Radio Control information
I am using mechanize module to retrieve information from a web page. It has a radio control section which I select before moving to the next page. I could easily select the value by assigning value to it. But coulnt retrieve the value of the candidate radio button. RadioSelect part of my form looks like below: <RadioCo...
[ "Instead of:\nprint br.form.possible_items(\"rdoSelect\")\n\nmechanize says to use:\noptions = [item.name for item in form.find_control('rdoSelect').items]\n\nExample use:\n#!/usr/bin/python\nimport re\nimport mechanize\nbr = mechanize.Browser()\nr = br.open(\"http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_RADIO...
[ 3, 0 ]
[]
[]
[ "forms", "mechanize", "python" ]
stackoverflow_0005932443_forms_mechanize_python.txt
Q: Python: from import error I'm running Python 2.6.6 on Ubuntu 10.10. I understand that we can import a module and bind that module to a different name, e.g. import spam as eggs also, from eggs import spam as foo My problem is that when running the PySide examples, the following import code does not run: import Py...
Python: from import error
I'm running Python 2.6.6 on Ubuntu 10.10. I understand that we can import a module and bind that module to a different name, e.g. import spam as eggs also, from eggs import spam as foo My problem is that when running the PySide examples, the following import code does not run: import PySide as PyQt4 from PyQt4 import...
[ "import and from are a special syntax.\nThey look for a module name, which means a file in sys.path which starts with the module name.\nAnd it seems like you don't have PyQt4 installed, so it will fail.\nThe fact that you have a variable called PyQt4 in your namespace after running import PySide as PyQt4 does not c...
[ 4, 2 ]
[]
[]
[ "import", "pyside", "python" ]
stackoverflow_0005099331_import_pyside_python.txt
Q: Python with eclipse import problem I use eclipse as my IDE for python. Recently I encountered a strange problem. A file contains an import from external libraries (such as wx, matplotlib etc.) if I put it inside the src directory, it will run as expected, but in the editor, I get error marks all over the places w...
Python with eclipse import problem
I use eclipse as my IDE for python. Recently I encountered a strange problem. A file contains an import from external libraries (such as wx, matplotlib etc.) if I put it inside the src directory, it will run as expected, but in the editor, I get error marks all over the places where I use the imported libraries. The e...
[ "In my installation I have several other libraries in the system pythonpath dialog including wx. Try setting the interpreter again in order to reload the libraries or load them manually.\n" ]
[ 2 ]
[]
[]
[ "eclipse", "eclipse_plugin", "python" ]
stackoverflow_0006236479_eclipse_eclipse_plugin_python.txt
Q: How much is the difference between html parsing and web crawling in python I need to grab some data from websites in my django website. Now i am confused whether i should use python parsing libraries or web crawling libraries. Does search engine libraries also fall in same category I want to know how much is the d...
How much is the difference between html parsing and web crawling in python
I need to grab some data from websites in my django website. Now i am confused whether i should use python parsing libraries or web crawling libraries. Does search engine libraries also fall in same category I want to know how much is the difference between the two and if i want to use those functions inside my websit...
[ "If you can get away with background web crawling use scrapy. If need to immediately grab something use html5lib (more robust) or lxml (faster). If you are going to be doing the later, use the awesome requests library. I would avoid using BeautifulSoup, mechanize, urllib2, httplib.\n", "HTML parse will parse the ...
[ 9, 1, 1 ]
[]
[]
[ "django", "python", "web_crawler" ]
stackoverflow_0006236794_django_python_web_crawler.txt
Q: Changing image projection using Python Image corner coordinates are known: Top left: (70.20315, 20.92749) Top right: (70.20315, 31.45240) Bottom left: (59.70571, 20.92749) Bottom right: (59.70571, 31.45240) (Basically map over Finland and a little bit of Sweden/Norway/Russia) I couldn't find a way to change imag...
Changing image projection using Python
Image corner coordinates are known: Top left: (70.20315, 20.92749) Top right: (70.20315, 31.45240) Bottom left: (59.70571, 20.92749) Bottom right: (59.70571, 31.45240) (Basically map over Finland and a little bit of Sweden/Norway/Russia) I couldn't find a way to change image projection to Google maps overlay image, p...
[ "(Copy-paste from gis answer)\nExtensive trial-and-error showed it worked fine without specifying source projection. Same can be achieved using only GDAL Python API. Steps to reproduce:\nAdding control points to TIF (of course, first convert mapimage.png mapimage.tif):\ngdal_translate mapimage.tif mapimage_georeffe...
[ 0 ]
[]
[]
[ "dictionary", "google_maps", "map_projections", "python" ]
stackoverflow_0006186268_dictionary_google_maps_map_projections_python.txt
Q: Using matplotlib, how do I whiten the background of the axis label? Is there a way to whiten out the background of the axis label so that when it crosses the axis line itself, the latter does not run through it? For example, this script (the best I managed so far) #!/usr/bin/python import matplotlib.pyplot as pl...
Using matplotlib, how do I whiten the background of the axis label?
Is there a way to whiten out the background of the axis label so that when it crosses the axis line itself, the latter does not run through it? For example, this script (the best I managed so far) #!/usr/bin/python import matplotlib.pyplot as plt xx=[1,2,3] yy=[2,3,4] dy=[0.1,0.2,0.05] fig=plt.figure() ax=fig.add_s...
[ "By default, the left spine has a zorder of 2.5. For some reason this seems to cause problems; maybe there's something in the code which only works if they're integral? Anyway, if you add\nax.spines['left'].set_zorder(2)\n\nor more generally\nax.spines['left'].set_zorder(ax.yaxis.get_label().get_zorder()-1)\n\nbe...
[ 2, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006236238_matplotlib_python.txt
Q: Django objects.filter() values_list() vs python list comprehension for __in query I have a quirk(?) with Django queryset filtering: ipdb> MagazineIssue.objects.filter(id__in=l_magazines.values_list('id')) Out[0]: [] or ipdb> MagazineIssue.objects.filter(id__in=[l_magazine.id for l_magazine in l_magazines]) Out[0]...
Django objects.filter() values_list() vs python list comprehension for __in query
I have a quirk(?) with Django queryset filtering: ipdb> MagazineIssue.objects.filter(id__in=l_magazines.values_list('id')) Out[0]: [] or ipdb> MagazineIssue.objects.filter(id__in=[l_magazine.id for l_magazine in l_magazines]) Out[0]: [<MagazineIssue: Architecture Australia, Jan 1995 (#1)>] and ipdb> l_magazines.value...
[ "Try l_magazines.values_list('id', flat=True). That returns a list of ids instead of a list of single id tuples.\n", "One thing to note is that there is a difference in the behaviour of values/values_list from a list comprehension: \n\nvalues/values_list will yield the actual value stored in the field, that is, ...
[ 59, 2 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0004812035_django_django_models_django_queryset_python.txt
Q: Why does MyClass.__class__ return a different value than MyClass().__class__? I want to be able to call 'person.Person.class' and get back 'class person.Person', like it does for a person object: >>> p = person.Person() >>> p.__class__ <class 'person.Person'> >>> person.Person.__class__ <class 'perframe.datatype.T...
Why does MyClass.__class__ return a different value than MyClass().__class__?
I want to be able to call 'person.Person.class' and get back 'class person.Person', like it does for a person object: >>> p = person.Person() >>> p.__class__ <class 'person.Person'> >>> person.Person.__class__ <class 'perframe.datatype.TypeSystemMeta'> Here is the Person inheritance tree... class TypeSystem(object): ...
[ "In Python, even classes are objects and every object is an instance of a class. Person refers to the \"class object\", which is an instance of type. In this case, there's a metaclass in the play - highly confusing metaprogramming magic, but if you want an introduction, see What is a metaclass in Python?. If you de...
[ 5, 2, 1 ]
[]
[]
[ "inheritance", "method_resolution_order", "multiple_inheritance", "python", "reflection" ]
stackoverflow_0006237356_inheritance_method_resolution_order_multiple_inheritance_python_reflection.txt
Q: insert into sqlite table with unique column I'm inserting values into my table (from python code) as follows: cur.execute("insert into t(a, b, c) values (?, ?, ?)", (a, b, c)) There is a unique constraint on column c. What is a common way of insert if I want to cover the case when we're inserting duplicate value ...
insert into sqlite table with unique column
I'm inserting values into my table (from python code) as follows: cur.execute("insert into t(a, b, c) values (?, ?, ?)", (a, b, c)) There is a unique constraint on column c. What is a common way of insert if I want to cover the case when we're inserting duplicate value for c column? I have some ideas select everythin...
[ "You could use INSERT OR REPLACE to update rows with a unique constraint,\nor INSERT OR IGNORE to ignore inserts which conflict with a unique constraint:\nimport sqlite3\n\ndef insert_or_replace():\n # https://sqlite.org/lang_insert.html\n connection=sqlite3.connect(':memory:')\n cursor=connection.cursor()...
[ 14, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006237378_python_sqlite.txt
Q: Python socket.send() can only send once, then socket.error: [Errno 32] Broken pipe occurred I'm a newbie in network programming, so please forgive me if this is a dumb question :) I created 1 client and 1 SocketServer.ThreadingMixIn server on Ubuntu 10.04.2 using Python2.7, but it seems like I can only call sock.s...
Python socket.send() can only send once, then socket.error: [Errno 32] Broken pipe occurred
I'm a newbie in network programming, so please forgive me if this is a dumb question :) I created 1 client and 1 SocketServer.ThreadingMixIn server on Ubuntu 10.04.2 using Python2.7, but it seems like I can only call sock.send() once in client, then I'll get a: Traceback (most recent call last): File "testClient1.py...
[ "handle() is called in the SocketServer.StreamRequestHandler once for each connection. If you return from handle the connection is closed.\nIf you want the server to handle more than one send/recv, you must loop until recv() returns 0, indicating the client closed the connection (or at least called shutdown() on s...
[ 17 ]
[]
[]
[ "broken_pipe", "python", "socketserver" ]
stackoverflow_0006237569_broken_pipe_python_socketserver.txt
Q: fast parsing links out of a page in python I need to parse a large number of pages (say 1000) and replace the links with tinyurl links. right now i am doing this using a regex href_link_re = re.compile(r"<a[^>]+?href\s*=\s*(\"|')(.*?)\1[^>]*>", re.S) but its not fast enough. i am thinking so far state machine ...
fast parsing links out of a page in python
I need to parse a large number of pages (say 1000) and replace the links with tinyurl links. right now i am doing this using a regex href_link_re = re.compile(r"<a[^>]+?href\s*=\s*(\"|')(.*?)\1[^>]*>", re.S) but its not fast enough. i am thinking so far state machine (the success of this will depend on my ability t...
[ "LXML is probably your best bet for this task. See Beautiful Soup vs LXML Performance. Parsing links is easy in LXML and it's fast.\nroot = lxml.html.fromstring(s)\nanchors = root.cssselect(\"a\")\nlinks = [a.get(\"href\") for a in anchors]\n\n", "Parsing using regexp's very bad idea, because of speed and regexp ...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "parsing", "python" ]
stackoverflow_0006219980_beautifulsoup_parsing_python.txt
Q: How do I check HTTP headers of an incoming request to Google Appengine in Python? I have an app installed on Google Appengine running on Python code. It has a request handler and a built-in database, which I update via something like this: http://appname.appspot.com/?type=update&service=test_name&url=.......... I ...
How do I check HTTP headers of an incoming request to Google Appengine in Python?
I have an app installed on Google Appengine running on Python code. It has a request handler and a built-in database, which I update via something like this: http://appname.appspot.com/?type=update&service=test_name&url=.......... I only want the database to update, if the client accessing the python app has a certain ...
[ "See http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_headers\nBasically\nself.request.headers\n\nis a dictionary-like object that holds the request headers.\n", "within your handler self.request holds all the request info, including headers.\n" ]
[ 6, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006237251_google_app_engine_python.txt
Q: Crawling youtube user info I'm trying to crawl Youtube to retrieve information about a group of users (approx. 200 people). I'm interested in looking for relationships between the users: contacts subscribers subscriptions what videos they commented on etc I've managed to get contact information with the followi...
Crawling youtube user info
I'm trying to crawl Youtube to retrieve information about a group of users (approx. 200 people). I'm interested in looking for relationships between the users: contacts subscribers subscriptions what videos they commented on etc I've managed to get contact information with the following source: import gdata.youtube ...
[ "In order to access a user's subscriptions feed without the user being logged in, the user must check the \"Subscribe to a channel\" checkbox under his Account Sharing settings.\nCurrently, there is no direct way to get a channel's subscribers through the gdata API. In fact, there has been an outstanding feature re...
[ 2 ]
[]
[]
[ "gdata", "python", "youtube" ]
stackoverflow_0006237530_gdata_python_youtube.txt
Q: How many rows have been inserted to sqlite table? I'm using this code in Python: for ... : cursor.execute('INSERT OR IGNORE INTO foo (bar,baz) VALUES (?, ?)',(1,3)) con.commit() Can I get the value of the number of rows that have been inserted without using if statement and testing if the value existed before i...
How many rows have been inserted to sqlite table?
I'm using this code in Python: for ... : cursor.execute('INSERT OR IGNORE INTO foo (bar,baz) VALUES (?, ?)',(1,3)) con.commit() Can I get the value of the number of rows that have been inserted without using if statement and testing if the value existed before insert?
[ "To get number of rows inserted, cursor.rowcount should return the number of rows affected by the last execute ( in this case, number of inserts). \n" ]
[ 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006238242_python_sqlite.txt
Q: Error for Injected Javascript (Python Web Scraper) I had a similar problem to this earlier, but I can't figure out why it won't let me click the checkbox. I BELIEVE I am making an error checking the checkbox by selecting it the wrong way. Here's my traceback: Traceback (most recent call last): File "C:\Python27\...
Error for Injected Javascript (Python Web Scraper)
I had a similar problem to this earlier, but I can't figure out why it won't let me click the checkbox. I BELIEVE I am making an error checking the checkbox by selecting it the wrong way. Here's my traceback: Traceback (most recent call last): File "C:\Python27\Sample Programs\Spynner Basic.py", line 19, in <module> ...
[ "I believe this has to do with the name being wrong on the selector.\n", "I might be wrong, but I think this is an actual bug. You should report it to Kiorky.\nI copied your html to a local document and ran your code (and variations of it).\nIf you turn on debugging you can see this:\nJavascript console (undefine...
[ 0, 0 ]
[]
[]
[ "css", "html", "javascript", "python", "traceback" ]
stackoverflow_0006169049_css_html_javascript_python_traceback.txt
Q: easy_install extra build arguments I'm trying to install ReportLab, but I have no C compiler available to compile the rl_accel library. Using setup.py, I would add an extra argument like so: python setup.py --rl_accel=no install Is it possible to add extra arguments to easy_install so that I can reproduce the sa...
easy_install extra build arguments
I'm trying to install ReportLab, but I have no C compiler available to compile the rl_accel library. Using setup.py, I would add an extra argument like so: python setup.py --rl_accel=no install Is it possible to add extra arguments to easy_install so that I can reproduce the same effect? easy_install reportlab [somet...
[ "not using the command, but you can write the configuration file:\nhttp://packages.python.org/distribute/easy_install.html#controlling-build-options\n" ]
[ 5 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0003361245_easy_install_python.txt
Q: Python Distributed Computing (works) I'm using an old thread to post new code which attempts to solve the same problem. What constitutes a secure pickle? this? sock.py from socket import socket from socket import AF_INET from socket import SOCK_STREAM from socket import gethostbyname from socket import gethostname...
Python Distributed Computing (works)
I'm using an old thread to post new code which attempts to solve the same problem. What constitutes a secure pickle? this? sock.py from socket import socket from socket import AF_INET from socket import SOCK_STREAM from socket import gethostbyname from socket import gethostname class SocketServer: def __init__(self,...
[ "I don't think Process objects are designed to be sent over the network. Look at line 256 in multiprocessing/process.py. \n# We subclass bytes to avoid accidental transmission of auth keys over network.\n\nSounds like there's a good reason to me. If you want to do distributed computing, maybe you should look into a...
[ 4, 2 ]
[]
[]
[ "distributed_computing", "multiprocessing", "pickle", "python", "sockets" ]
stackoverflow_0006212326_distributed_computing_multiprocessing_pickle_python_sockets.txt
Q: Multivariate spline interpolation in python/scipy? Is there a library module or other straightforward way to implement multivariate spline interpolation in python? Specifically, I have a set of scalar data on a regularly-spaced three-dimensional grid which I need to interpolate at a small number of points scattere...
Multivariate spline interpolation in python/scipy?
Is there a library module or other straightforward way to implement multivariate spline interpolation in python? Specifically, I have a set of scalar data on a regularly-spaced three-dimensional grid which I need to interpolate at a small number of points scattered throughout the domain. For two dimensions, I have bee...
[ "If I'm understanding your question correctly, your input \"observation\" data is regularly gridded?\nIf so, scipy.ndimage.map_coordinates does exactly what you want. \nIt's a bit hard to understand at first pass, but essentially, you just feed it a sequence of coordinates that you want to interpolate the values o...
[ 47, 3 ]
[]
[]
[ "interpolation", "numpy", "python", "scipy" ]
stackoverflow_0006238250_interpolation_numpy_python_scipy.txt
Q: Using integers/dates as terminals in NLTK parser I'm trying to use the Earley parser in NLTK to parse sentences such as: If date is before 12/21/2010 then serial = 10 To do this, I'm trying to write a CFG but the problem is I would need to have a general format of dates and integers as terminals, instead of the sp...
Using integers/dates as terminals in NLTK parser
I'm trying to use the Earley parser in NLTK to parse sentences such as: If date is before 12/21/2010 then serial = 10 To do this, I'm trying to write a CFG but the problem is I would need to have a general format of dates and integers as terminals, instead of the specific values. Is there any ways to specify the right...
[ "For this to work, you'll need to tokenize the date so that each digit and slash is a separate token.\nfrom nltk.parse.earleychart import EarleyChartParser\nimport nltk\n\ngrammar = nltk.parse_cfg(\"\"\"\nDATE -> MONTH SEP DAY SEP YEAR\nSEP -> \"/\"\nMONTH -> DIGIT | DIGIT DIGIT\nDAY -> DIGIT | DIGIT DIGIT\nYEAR ->...
[ 2 ]
[]
[]
[ "earley_parser", "nltk", "parsing", "python", "regex" ]
stackoverflow_0004148171_earley_parser_nltk_parsing_python_regex.txt
Q: How to overload the subscript operator with swig Python I have a class which contains a std::vector<Foo> where Foo is a class containing a key, value, comment, etc. Please note that there is a reason why I am using a vector and not a dictionary. I have overloaded the subscript operator in C++ such that foos["Key N...
How to overload the subscript operator with swig Python
I have a class which contains a std::vector<Foo> where Foo is a class containing a key, value, comment, etc. Please note that there is a reason why I am using a vector and not a dictionary. I have overloaded the subscript operator in C++ such that foos["Key Name"] will search through the vector for a Foo object with ke...
[ "In straight Python, if you want to overload the subscript operator, you would create a __getitem__ and __setitem__ class method. As a simple example:\nclass MyClass(object):\n def __init__(self):\n self.storage = {}\n\n def __getitem__(self, key):\n return self.storage[key]\n\n def __setitem...
[ 5, 2 ]
[]
[]
[ "c++", "operator_keyword", "python", "subscript", "swig" ]
stackoverflow_0006238931_c++_operator_keyword_python_subscript_swig.txt
Q: Reliable / well-supported library to serve as interface to GPS units? I'm preparing to build an application which will have the capability to send / receive waypoints to / from GPS devices. With some Googling I've found a lot of libraries which may be useful for this purpose: Java Chaeron GPS GPSLib4J Python P...
Reliable / well-supported library to serve as interface to GPS units?
I'm preparing to build an application which will have the capability to send / receive waypoints to / from GPS devices. With some Googling I've found a lot of libraries which may be useful for this purpose: Java Chaeron GPS GPSLib4J Python PyGarmin Most of the libraries I've found, it seems, are out of date and h...
[ "Another option is to use gpsbabel. It will handle more formats/recievers than anything else I've come across. (In addition to converting between formats, it allows you to read/write to/from serial and usb gps devices and get real-time position information.)\nThere is a (3rd party) python wrapper for it, but it d...
[ 1 ]
[]
[]
[ "gps", "java", "python" ]
stackoverflow_0006237406_gps_java_python.txt
Q: libusb-1.x VS openUsb Have a few questions about libusb VS openusb I'm the author of a project called Berry4all that allows tethering for Blackberries Via USB. Cuurrently I'm using libusb-0.x but i'd like /need to migrate to either libusb1.x OR libopenusb ... but I'm not sure which to pick Some of the things I nee...
libusb-1.x VS openUsb
Have a few questions about libusb VS openusb I'm the author of a project called Berry4all that allows tethering for Blackberries Via USB. Cuurrently I'm using libusb-0.x but i'd like /need to migrate to either libusb1.x OR libopenusb ... but I'm not sure which to pick Some of the things I need: - Linux support - Mac OS...
[ "I would go for libusb-1 because it seems architecturally simpler, more actively maintained, more portable and more mainstream than OpenUSB. Their webpage lists successful projects based on it, and a small comparison to OpenUSB you might find useful.\n" ]
[ 6 ]
[]
[]
[ "linux", "max", "python", "usb" ]
stackoverflow_0005843296_linux_max_python_usb.txt
Q: How do I set up a localhost in python? The project is to be able to send email from within Python. I can successfully send to, for example, "smtp.gmail.com", but using a localhost or 127.0.0.1 returns an "errno 111, connection was refused." The statement is server = smtplib.SMTP('127.0.0.1', 8025) Notes: I a...
How do I set up a localhost in python?
The project is to be able to send email from within Python. I can successfully send to, for example, "smtp.gmail.com", but using a localhost or 127.0.0.1 returns an "errno 111, connection was refused." The statement is server = smtplib.SMTP('127.0.0.1', 8025) Notes: I am running Ubuntu, Python 3.2 or Python 2.7 d...
[ "First, test your local SMTP connection using Telnet. (Alternate instructions here) This will tell if you can connect to your local SMTP server in the way you think you can. \nYou probably have one of several problems: \n\nNo SMTP server on your machine or;\nYou have SMTP but it requires a password and/or;\nYou hav...
[ 1, 1 ]
[]
[]
[ "localhost", "python", "smtp", "sockets" ]
stackoverflow_0006239304_localhost_python_smtp_sockets.txt
Q: Can we create interactive PDF forms using reportlab? Can we create interactive PDF forms using reportlab? That is, a form that takes in data from readers and save them into the database. A: reportlab.pdfbase.pdfform.py implies that you can, but it doesn't sound like a mature feature. Support for Acrobat Forms i...
Can we create interactive PDF forms using reportlab?
Can we create interactive PDF forms using reportlab? That is, a form that takes in data from readers and save them into the database.
[ "reportlab.pdfbase.pdfform.py implies that you can, but it doesn't sound like a mature feature.\nSupport for Acrobat Forms in ReportLab documents\n\nThis module is somewhat experimental at this time.\n\nIncludes basic support for\n textfields,\n select fields (drop down lists), and\n check buttons.\n\nThe ...
[ 8 ]
[]
[]
[ "django", "pdf", "python", "reportlab" ]
stackoverflow_0003929408_django_pdf_python_reportlab.txt
Q: Writing HTML with Python xlwt module I'm using xlwt to write an Excel formatted file, and I want to include html in a cell. What parameters do I need to provide to hint that Excel should render the content? A: If you can do it manually using the Excel 2003 user interface, then there's some chance of doing it wit...
Writing HTML with Python xlwt module
I'm using xlwt to write an Excel formatted file, and I want to include html in a cell. What parameters do I need to provide to hint that Excel should render the content?
[ "If you can do it manually using the Excel 2003 user interface, then there's some chance of doing it with current xlwt, or making xlwt do it. Please edit your question to show what keyboard/mouse actions are required.\nIf you can't do it manually, then xlwt definitely can't do it either. Have you explored all the c...
[ 3 ]
[]
[]
[ "python", "xlwt" ]
stackoverflow_0006219070_python_xlwt.txt
Q: Changing folder name in Python I need a super simple script that changes the names of the subfolders of the actual folder Here's a little example for better understanding. Im in the folder My Music and I want to change tha name of all the subfolders (This_Is_A_Example_Subpath): C:/My Music/This_Is_A_Example_- Sub...
Changing folder name in Python
I need a super simple script that changes the names of the subfolders of the actual folder Here's a little example for better understanding. Im in the folder My Music and I want to change tha name of all the subfolders (This_Is_A_Example_Subpath): C:/My Music/This_Is_A_Example_- Subpath C:/My Music/This_Is_A_Example_-...
[ "import os\nimport os.path\n\nfor (dirpath, dirnames, filenames) in os.walk('C:/My Music/'):\n for idx in range(len(dirnames)):\n newname = dirnames[idx].replace('_', ' ')\n os.rename(os.path.join(dirpath, dirnames[idx]), os.path.join(dirpath, newname))\n dirnames[idx] = newname\n\nA bit of ...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0006239782_python.txt
Q: Are there any editors that does syntax highlighting for Django templates? Like of I put my cursor on an opening forloop tag the closing forloop tag will be highlighted like most IDEs? Preferably free. A: Off the top of my head I know Vim, Emacs, Textmate and PyCharm all support Django's template syntax, and I'd ...
Are there any editors that does syntax highlighting for Django templates?
Like of I put my cursor on an opening forloop tag the closing forloop tag will be highlighted like most IDEs? Preferably free.
[ "Off the top of my head I know Vim, Emacs, Textmate and PyCharm all support Django's template syntax, and I'd imagine many more do as well. They all support customizable syntax highlighting/completion. I've been particularly impressed with PyCharm's Django support, but there are many good IDEs/Editors out there. Pi...
[ 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006239352_django_python.txt
Q: What's the suitable widget in PyQt to create a floating widget on the desktop? I'd like to create something very alike to Rainlendar with python. Currently I'm using PyQt for GUI, but there doesn't seem to be a widget type that can directly display something like that, specifically I mean: No edge displayed, incu...
What's the suitable widget in PyQt to create a floating widget on the desktop?
I'd like to create something very alike to Rainlendar with python. Currently I'm using PyQt for GUI, but there doesn't seem to be a widget type that can directly display something like that, specifically I mean: No edge displayed, incuding buttons on the top right corner. No corresponding bar in the task bar. Able to ...
[ "\nHave a look at the docs for QWidget.setWindowFlags. In particular, when coupled with Qt.FramelessWindowHint it should be borderless and buttonless.\nAnother task for setWindowFlags — setting it to Qt.Tool stops the task bar entry. So combined with the above, you want window.setWindowFlags(Qt.Tool | Qt.FramelessW...
[ 4 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0006236323_pyqt4_python.txt