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: What kind of methods should be method of model class? It is design problem. Let's assume that we have this kind of model in Django: class Payment(models.Model): purchase = ForeignKeyField(Purchase) net_price = DecimalField() is_accepted = BooleanField() def set_accept(self): # there will be some logic...
What kind of methods should be method of model class?
It is design problem. Let's assume that we have this kind of model in Django: class Payment(models.Model): purchase = ForeignKeyField(Purchase) net_price = DecimalField() is_accepted = BooleanField() def set_accept(self): # there will be some logic, which touch purchase, send emails etc. def price_with_...
[ "The overall convention in MVC frameworks (like Django) is to place as much logic as possible into your models. This serves a lot of purposes:\n\nIt binds your logic to your data (good thing).\nMakes it easy to look to one place in the code for all data manipulation methods.\nAllows you to run the methods on your m...
[ 6, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007464311_django_python.txt
Q: Python to Mat-file: export list of string to ordinar matrix of chars (not a cell-array!) This code on Python creates cell "STRINGS" in .mat-file: data = {"STRINGS": numpy.empty((0),dtype=numpy.object)} data["STRINGS"] = numpy.append( data["STRINGS"], "Some string" ) scipy.io.savemat( output_mat_file, data ) In ma...
Python to Mat-file: export list of string to ordinar matrix of chars (not a cell-array!)
This code on Python creates cell "STRINGS" in .mat-file: data = {"STRINGS": numpy.empty((0),dtype=numpy.object)} data["STRINGS"] = numpy.append( data["STRINGS"], "Some string" ) scipy.io.savemat( output_mat_file, data ) In matlab I get cell STRINGS: >> STRINGS{1} ans = Some string How could I get ordinary matrix? F...
[ "In MATLAB, cell arrays are containers for heterogeneous data types, while matrices are not, and all their elements must be of the same type (be it numeric doubles or characters)\nMatrices are of rectangular shapes (thus if you store strings in each 2D matrix row, they all must be of the same length, or padded with...
[ 3 ]
[]
[]
[ "mat_file", "matlab", "python", "scipy" ]
stackoverflow_0007464632_mat_file_matlab_python_scipy.txt
Q: Convert loop and if statemnt to a list comprehension Is it possible to convert the following to a python list comprehension: values = [a,b,c,d,...] converted_values = [] for item in values: if type(item) == datetime.date: converted_values.append(item) else: converted_values.append(item.dec...
Convert loop and if statemnt to a list comprehension
Is it possible to convert the following to a python list comprehension: values = [a,b,c,d,...] converted_values = [] for item in values: if type(item) == datetime.date: converted_values.append(item) else: converted_values.append(item.decode('utf-8'))
[ "You can use Conditional Expressions to make this work.\nconverted_values = [item if type(item) == datetime.data\n else item.decode('utf-8')\n for item in values]\n\nPython conditionals are fairly readable. Here's some examples to show how they work:\nprint(\"yes\" if True else...
[ 9, 5 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007464911_list_python.txt
Q: How would you answer this django interview question? I recently did a programming question for a pre-interview for a certain company. The questions was: Create a django app, test driven of course, to display Fibonacci's sequence to the world. The app should take an index number and display the resulting Fibonacci ...
How would you answer this django interview question?
I recently did a programming question for a pre-interview for a certain company. The questions was: Create a django app, test driven of course, to display Fibonacci's sequence to the world. The app should take an index number and display the resulting Fibonacci sequence. Additionally, there should be a page that shows ...
[ "Every linear reccurence equation can be solve directly.\nIn fibonacci's case the equation is \nf_n+2 = f_n+1 + f_n\nf_1 = 1\nf_2 = 1\n\nThe solution to this is:\nf_n = 1/sqrt(5) * ((1+sqrt(5))/2)^n - 1/sqrt(5) * ((1-sqrt(5))/2)^n\n\nUse this direct formula.\nFor how to get to it look for linear reccurence equation...
[ 4, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007464233_django_python.txt
Q: Extract passwords from settings.py file I would like to extract any sensitive information from my settings.py file, for example, db name/password, amazon key/password, api keys/passwords. What is the suggested way to go about doing this. A: Move all the keys, passwords, etc. to a file secrets.py, then add import...
Extract passwords from settings.py file
I would like to extract any sensitive information from my settings.py file, for example, db name/password, amazon key/password, api keys/passwords. What is the suggested way to go about doing this.
[ "Move all the keys, passwords, etc. to a file secrets.py, then add import secrets to settings.py.\n" ]
[ 6 ]
[]
[]
[ "django", "python", "settings" ]
stackoverflow_0007464941_django_python_settings.txt
Q: How to get the content of textarea I have this textarea form: self.response.out.write(""" <form name="title" action="/edittitlepitchhandler" method="post"> ... pitch: <br /> <textarea name="new_pitch" rows="13" cols="75"> "%s" </textarea><br /><br /> ... <input type="...
How to get the content of textarea
I have this textarea form: self.response.out.write(""" <form name="title" action="/edittitlepitchhandler" method="post"> ... pitch: <br /> <textarea name="new_pitch" rows="13" cols="75"> "%s" </textarea><br /><br /> ... <input type="submit" value="submit"> </form>""" % (....
[ "The textarea displays all the text inside it, so if you put <textarea>\"%s\"</textarea>, it'll put the quotes in as well. Scrap the quotes and it'll just show the expanded %s.\n" ]
[ 3 ]
[]
[]
[ "html", "python", "textarea" ]
stackoverflow_0007455456_html_python_textarea.txt
Q: Multilinear Regression using OLS in Python not working with my own data Possible Duplicate: Python Multiple Linear Regression using OLS code with specific data? Alright, I'm working with ols.py from scipy.org. When I input my own variables and try to initiate a multilinear regression, I'm getting an error. Eve...
Multilinear Regression using OLS in Python not working with my own data
Possible Duplicate: Python Multiple Linear Regression using OLS code with specific data? Alright, I'm working with ols.py from scipy.org. When I input my own variables and try to initiate a multilinear regression, I'm getting an error. Every time I try to put my variables in place of the random variables that came...
[ "The code is right except for the indentation in the methods of the class.\n" ]
[ 2 ]
[]
[]
[ "python", "regression", "scipy", "statistics" ]
stackoverflow_0007463173_python_regression_scipy_statistics.txt
Q: Help with a guess my number program in python I'm trying to write a python program in which the program guesses the users number. I fel like an idiot, the part i am getting caught up on is the math, i feel like its one of those things where I've been working on it for a few hours and someone else would be able to ...
Help with a guess my number program in python
I'm trying to write a python program in which the program guesses the users number. I fel like an idiot, the part i am getting caught up on is the math, i feel like its one of those things where I've been working on it for a few hours and someone else would be able to bring a fresh perspective and solve it easily. I fi...
[ "Okay so 1) I don't know python and 2) I have no idea what your code does and can't be bothered figuring it out. Why? Because I think you're overcomplicating it.\nI believe you can solve this with a simple binary search. In pseudocode:\nlow = 0 // lowest possible value of user's number\nhigh ...
[ 2, 1 ]
[]
[]
[ "logic", "python" ]
stackoverflow_0007465174_logic_python.txt
Q: Issue with python/pytz Converting from local timezone to UTC then back I have a requirement to convert a date from a local time stamp to UTC then back to the local time stamp. Strangely, when converting back to the local from UTC python decides it is PDT instead of the original PST so the post converted date has ...
Issue with python/pytz Converting from local timezone to UTC then back
I have a requirement to convert a date from a local time stamp to UTC then back to the local time stamp. Strangely, when converting back to the local from UTC python decides it is PDT instead of the original PST so the post converted date has gained an hour. Can someone explain to me what is going on or what I am doin...
[ "Change\ndate = date.replace(tzinfo=users_timezone)\n\nto \ndate = users_timezone.localize(date)\n\nlocalize adjusts for Daylight Savings Time, replace does not. See the docs for more info.\n" ]
[ 6 ]
[]
[]
[ "python", "pytz", "timezone" ]
stackoverflow_0007465181_python_pytz_timezone.txt
Q: question on karatsuba multiplication I want to implement Karatsuba's 2-split multiplication in Python. However, writing numbers in the form A=c*x+d where x is a power of the base (let x=b^m) close to sqrt(A). How am I supposed to find x, if I can't even use division and multiplication? Should I count the number o...
question on karatsuba multiplication
I want to implement Karatsuba's 2-split multiplication in Python. However, writing numbers in the form A=c*x+d where x is a power of the base (let x=b^m) close to sqrt(A). How am I supposed to find x, if I can't even use division and multiplication? Should I count the number of digits and shift A to the left by half t...
[ "Almost. You don't shift A by half the number of digits; you shift 1. Of course, this is only efficient if the base is a power of 2, since \"shifting\" in base 10 (for example) has to be done with multiplications. (Edit: well, ok, you can multiply with shifts and additions. But it's ever so much simpler with a powe...
[ 4, 3, 2 ]
[]
[]
[ "algorithm", "math", "python" ]
stackoverflow_0007461496_algorithm_math_python.txt
Q: How to read root XML tag in python My question follows on from another stackoverflow question:- "How to get the root node of an xml file in Python?" from xml.etree import ElementTree as ET path = 'C:\cool.xml' et = ET.parse ( path ) root = et.getroot() When I extract and print the root tag, I receive:- <Element ...
How to read root XML tag in python
My question follows on from another stackoverflow question:- "How to get the root node of an xml file in Python?" from xml.etree import ElementTree as ET path = 'C:\cool.xml' et = ET.parse ( path ) root = et.getroot() When I extract and print the root tag, I receive:- <Element 'root' at 0x1234abcd> I then want to ch...
[ "You should be able to use the tag function to get the name of the node.\nfrom xml.etree import ElementTree as ET\npath = 'C:\\cool.xml'\net = ET.parse ( path )\nroot = et.getroot()\n\nif root.tag == \"root\":\n print \"I'm the root\"\n\n", "root is an instance of the Element class. Any such object will have a t...
[ 8, 3 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0007465455_elementtree_python_xml.txt
Q: Is there any XOR bit reduction operand or function? Is there any XOR bit reduction operand or function in python? I have no problem to write it by yourself, but there's no reason to write it in every script if there's already built-in. r=x&1 for i in xrange(1,63): r=r^((x>>i)&1) A: this doesn't answer your q...
Is there any XOR bit reduction operand or function?
Is there any XOR bit reduction operand or function in python? I have no problem to write it by yourself, but there's no reason to write it in every script if there's already built-in. r=x&1 for i in xrange(1,63): r=r^((x>>i)&1)
[ "this doesn't answer your question but that code is the same as:\ndef parity(x):\n k = 0\n d = x\n while d != 0:\n k = k + 1\n d = d & (d - 1)\n return k % 2\n\nwhich has the benefit of not depending on the bit length of the number; and is faster (e.g. on 2**62 yours takes 46.6 usec and th...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "binary_operators", "python" ]
stackoverflow_0007463656_binary_operators_python.txt
Q: perl to python...how do I? I am trying to learn python but don't quite understand the syntax. What is the equivalent of: my $string='this one this that this here '; while($string=~/this\s+(.*?)\s+/g){ print $1."\n"; } prints: one that here A: Try the re module. I think this is equivalent, modulo some of ...
perl to python...how do I?
I am trying to learn python but don't quite understand the syntax. What is the equivalent of: my $string='this one this that this here '; while($string=~/this\s+(.*?)\s+/g){ print $1."\n"; } prints: one that here
[ "Try the re module. I think this is equivalent, modulo some of the side-effects on string:\nimport re\nstring = \"this one this that this here \"\nfor match in re.finditer(r\"this\\s+(.*?)\\s+\", string):\n print match.group(1)\n\n" ]
[ 7 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0007465695_perl_python.txt
Q: Store images temporary in Google App Engine? I'm writing an app with Python, which will check for updates on a website(let's call it A) every 2 hours, if there are new posts, it will download the images in the post and post them to another website(call it B), then delete those images. Site B provide API for upload...
Store images temporary in Google App Engine?
I'm writing an app with Python, which will check for updates on a website(let's call it A) every 2 hours, if there are new posts, it will download the images in the post and post them to another website(call it B), then delete those images. Site B provide API for upload images with description, which is like: upload(im...
[ "GAE has a BlobStore API, which can work pretty much as a file storage, but probably it's not what you whant. Actually, the right answer depends on what kind of API you're using - it may support file-like objects, so you could pass urllib response object, or accept URLs, or tons of other interesting features\n", ...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "hosting", "python" ]
stackoverflow_0007461111_google_app_engine_hosting_python.txt
Q: Trouble iterating in python Working in Python 2.7. I would like to be able to input a number, and return all the sets of values for x and y that complete the equation win_percentage = observed. def Rlog5(observed): z = float(observed)/1000 for x in range(350, 650, 1): y = 1000 - x win_perce...
Trouble iterating in python
Working in Python 2.7. I would like to be able to input a number, and return all the sets of values for x and y that complete the equation win_percentage = observed. def Rlog5(observed): z = float(observed)/1000 for x in range(350, 650, 1): y = 1000 - x win_percentage = (float(x)-(float(x)*float...
[ "As others have noted, you have = where you should have ==, but I assume that's a typo here, since you would get a syntax error. But you are testing floats for equality, and floats are almost never equal because of their imprecision. Generally, you test to see if two floats are within a small difference of each o...
[ 7, 0, 0 ]
[]
[]
[ "floating_point", "iteration", "python" ]
stackoverflow_0007465824_floating_point_iteration_python.txt
Q: NameError: name 're' is not defined I am very new to python. Very new. I copied the following from a tutorial #!/usr/bin/python from urllib import urlopen from BeautifulSoup import BeautifulSoup webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read patFinderTitle = re.compile('<tit...
NameError: name 're' is not defined
I am very new to python. Very new. I copied the following from a tutorial #!/usr/bin/python from urllib import urlopen from BeautifulSoup import BeautifulSoup webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read patFinderTitle = re.compile('<title>(.*)</title>') patFinderLink = re.com...
[ "You need to import regular expression module in your code\nimport re\nre.compile('<title>(.*)</title>')\n\n", "As well as the missing import re, your program has another error. In\nwebpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read\n\nYou left the () off after read at the end of ...
[ 55, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007465590_python.txt
Q: urllib2.urlopen can't look up a hostname using my normal DNS server; dig etc. can I'm trying to troubleshoot a problem with urllib2.urlopen. It can't seem to make use of my regular DNS server. Below is the result of several attempts to open various URLs, first using Google public DNS (8.8.8.8) and second using my ...
urllib2.urlopen can't look up a hostname using my normal DNS server; dig etc. can
I'm trying to troubleshoot a problem with urllib2.urlopen. It can't seem to make use of my regular DNS server. Below is the result of several attempts to open various URLs, first using Google public DNS (8.8.8.8) and second using my router. gridley is defined in my /etc/hosts file. Python 2.7.2 (default, Jun 29 2011, 1...
[ "This isn't exactly an answer...but note that using dig does not look up hostnames the same way as, say, urlopen does. dig is strictly a DNS query tool, whereas your system may be configured to look for host information in multiple source (a local hosts file, NIS, LDAP, etc).\nWhen you type:\nurllib2.urlopen(\"htt...
[ 1 ]
[]
[]
[ "dns", "python" ]
stackoverflow_0007465474_dns_python.txt
Q: heapify returns NoneType I have b = heapify([5,4,9,1]) and if I do a type(b) It says it's NoneType instead of list type, anyone know what I'm doing wrong?? A: The heapify() method transforms the list in-place. This means that it alters the list, but does not returned the modified list. As agf mentions below...
heapify returns NoneType
I have b = heapify([5,4,9,1]) and if I do a type(b) It says it's NoneType instead of list type, anyone know what I'm doing wrong??
[ "The heapify() method transforms the list in-place. This means that it alters the list, but does not returned the modified list. As agf mentions below, heapify() returns None to protect you from this mistake. Therefore, if you do\nlst = [5,4,9,1]\nheapify(lst)\ntype(lst)\n\nyou will see that lst is now heapified. ...
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007465896_python.txt
Q: Python + XPath: Is it possible to select the next element after the one I actually want? Suppose I have something like this: <span class="filesize">File<a href="http://example.com/image.jpg" target="_blank">image.jpg</a>-(1.61 MB, 1000x1542, <span title="what the file is actually called.jpg">what the file is act...
Python + XPath: Is it possible to select the next element after the one I actually want?
Suppose I have something like this: <span class="filesize">File<a href="http://example.com/image.jpg" target="_blank">image.jpg</a>-(1.61 MB, 1000x1542, <span title="what the file is actually called.jpg">what the file is actually called.jpg</span>)</span><br><a href="http://example.com /image.jpg" target="_blank"> W...
[ "You can use the following-sibling and preceding-sibling xpath \"axes\" to do the navigation you need.\nYou can get detains here.\nEDIT:\nHere's an example that gets me the result you want using only xpath. However it may not work for you depending on what the surrounding XML is like: (I've also had to complete som...
[ 2 ]
[]
[]
[ "python", "xpath" ]
stackoverflow_0007466013_python_xpath.txt
Q: how can I display models data in django I am new to django, I've got models with data that I want to display in a table format. I'm used to using gridviews in asp.net and I am looking for an alternative. Is the best way to do this using template iteration tags and is there some sort of tutorials online showing exa...
how can I display models data in django
I am new to django, I've got models with data that I want to display in a table format. I'm used to using gridviews in asp.net and I am looking for an alternative. Is the best way to do this using template iteration tags and is there some sort of tutorials online showing examples on how to do this?
[ "Django explicitly avoids providing front end widgets (like ASP.NET gridviews or Rails scaffolding). \nIf you want this in a regular template you gotta roll your own:\n{% if list %}\n<table>\n<tr>\n<th> Foo </th>\n<th> Bar </th>\n</tr>\n{% for item in list %}\n <td>{{item.foo}}</td>\n <td>{{item.bar}}</td>\n{% ...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007466158_django_python.txt
Q: Python: Question about multiprocessing / multithreading and shared resources Here's the simplest multi threading example I found so far: import multiprocessing import subprocess def calculate(value): return value * 10 if __name__ == '__main__': pool = multiprocessing.Pool(None) tasks = range(10000) ...
Python: Question about multiprocessing / multithreading and shared resources
Here's the simplest multi threading example I found so far: import multiprocessing import subprocess def calculate(value): return value * 10 if __name__ == '__main__': pool = multiprocessing.Pool(None) tasks = range(10000) results = [] r = pool.map_async(calculate, tasks, callback=results.append) ...
[ "First off, it might be beneficial to make one list of tuples, for example\nnew_list[i] = (first_list[i], second_list[i])\n\nThat way, as you change i, you ensure that you are always operating on the same items from first_list and second_list.\nSecondly, assuming there are no relations between the i and i-1 entries...
[ 1 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0007466270_multiprocessing_multithreading_python.txt
Q: Are python object functions singletons? In Java, objects are instantiated with a complete copy of the functions from the class linked to them. This is one of the reasons that the Spring Framework has been so successful. Spring helps you cut down on the memory that the Java VM uses if you create many temporary da...
Are python object functions singletons?
In Java, objects are instantiated with a complete copy of the functions from the class linked to them. This is one of the reasons that the Spring Framework has been so successful. Spring helps you cut down on the memory that the Java VM uses if you create many temporary data objects, and other service objects that ar...
[ "There is just one instance of the function, which is stored inside the class. The function gets called with a reference to a class instance as the first argument, which is traditionally called self.\nSo, here are three equivalent ways to call the .__add__() method function:\n>>> x = MyObj(2)\n>>> MyObj.__add__(x, ...
[ 6, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007465070_python.txt
Q: GAE Lookup Table Incompatible with Transactions? My Python High Replication Datastore application requires a large lookup table of between 100,000 and 1,000,000 entries. I need to be able to supply a code to some method that will return the value associated with that code (or None if there is no association). For ...
GAE Lookup Table Incompatible with Transactions?
My Python High Replication Datastore application requires a large lookup table of between 100,000 and 1,000,000 entries. I need to be able to supply a code to some method that will return the value associated with that code (or None if there is no association). For example, if my table held acceptable English words the...
[ "First, if you're under the belief that a namespace is going to help avoid key collisions, it's time to take a step back. A key consists of an entity kind, a namespace, a name or id, and any parents that the entity might have. It's perfectly valid for two different entity kinds to have the same name or id. So if yo...
[ 1, 1 ]
[]
[]
[ "entity_groups", "google_app_engine", "google_cloud_datastore", "python", "transactions" ]
stackoverflow_0007451163_entity_groups_google_app_engine_google_cloud_datastore_python_transactions.txt
Q: Queries by key and iterating over objects in AppEngine AppEngine docs note that "Queries that return keys are faster and cost less CPU than queries that return full entities." Which of these two is the more desired way to fetch and iterate over a number of objects from the data store? query_keys = Person.all(keys_...
Queries by key and iterating over objects in AppEngine
AppEngine docs note that "Queries that return keys are faster and cost less CPU than queries that return full entities." Which of these two is the more desired way to fetch and iterate over a number of objects from the data store? query_keys = Person.all(keys_only=True) query_keys.filter('name = ', person_name) query_k...
[ "A regular query performs essentially the operations that your first snippet does, only inside a single RPC. If you need the entities, it's more efficient to just ask for them, than to ask for just the keys and fetch the entities yourself.\nOne thing you should watch out for efficiency-wise is iterating over Query ...
[ 2, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007451819_google_app_engine_python.txt
Q: Increase retrieving perf python appengine with memcache Hello I want to know if in the appengine env the things I did is usefull Because I don't know why this page is very slow. class Foo(db.Model): id = db.StringProperty(multiline=True) name = db.StringProperty(multiline=True) date = db.DateTimeProper...
Increase retrieving perf python appengine with memcache
Hello I want to know if in the appengine env the things I did is usefull Because I don't know why this page is very slow. class Foo(db.Model): id = db.StringProperty(multiline=True) name = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) description = db.TextProperty() ...
[ "You have the memcache.set() inside the loop. That's a lot of unnecessary traffic to the memcache service. Do it once, after the loop.\nFurther, the way you have that coded, there's no need for establishing size.\nfoosTab = []\nfor foo in foos:\n foosTab.append(foo)\n\nor, more idiomatically\nfoosTab = [foo for ...
[ 5, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007448151_google_app_engine_python.txt
Q: why and how to use Python's super(type1, type2)? super has 2 args, super(type, obj_of_type-or-subclass_of_type) I understand how and why to use super with the 2nd arg being obj_of_type. But I don't understand the matter for the 2nd arg being subclass. Anyone can show why and how? A: You pass an object if you w...
why and how to use Python's super(type1, type2)?
super has 2 args, super(type, obj_of_type-or-subclass_of_type) I understand how and why to use super with the 2nd arg being obj_of_type. But I don't understand the matter for the 2nd arg being subclass. Anyone can show why and how?
[ "You pass an object if you want to invoke an instance method. You pass a class if you want to invoke a class method.\nThe classic example for using super() for class methods is with factory methods, where you want all the superclass factory methods to be called.\nclass Base(object):\n @classmethod\n def make(...
[ 3 ]
[]
[]
[ "python", "super" ]
stackoverflow_0007466463_python_super.txt
Q: Lock down a program so it has no access to outside files, like a virus scanner does I would like to launch an untrusted application programmatically, so I want to remove the program's ability to access files, network, etc. Essentially, I want to restrict it so its only interface to the rest of the computer is stdi...
Lock down a program so it has no access to outside files, like a virus scanner does
I would like to launch an untrusted application programmatically, so I want to remove the program's ability to access files, network, etc. Essentially, I want to restrict it so its only interface to the rest of the computer is stdin and stdout. Can I do that? Preferably in a cross-platform way but I sort of expect to h...
[ "The short answer is no.\nThe long answer is not really. Consider a C program, in which the program opens a log file by grabbing the next available file descriptor. Your program, in order to stop this, would need to somehow monitor this, and block it. Depending on the robustness of the untrusted program, this co...
[ 4, 2, 0 ]
[]
[]
[ "linux", "macos", "permissions", "python", "windows" ]
stackoverflow_0007460592_linux_macos_permissions_python_windows.txt
Q: Why isn't there a Spring DI (component lifecycle) framework for python? This question is not focused on the DAO, MVC, Messaging and other component frameworks that Spring is known for, but just the Core. As I understand it, Spring's earlier advantage was that it managed the component lifecycle, providing a Singl...
Why isn't there a Spring DI (component lifecycle) framework for python?
This question is not focused on the DAO, MVC, Messaging and other component frameworks that Spring is known for, but just the Core. As I understand it, Spring's earlier advantage was that it managed the component lifecycle, providing a Singleton Factory that creates the objects in the configuration file read on start...
[ "Python has a different relative cost of operations. Instead of garbage collection, it uses reference counting, which means that releasing objects is not as expensive as in Java. Using singletons just for the speedup is not very good design in my opinion, as it makes more interdependencies between different parts o...
[ 1, 0 ]
[]
[]
[ "dependency_injection", "python" ]
stackoverflow_0007466532_dependency_injection_python.txt
Q: Methodology: how to change URL without reloading page and index whole URL (with anchor # part)? I need Google indexes full URL with anchor part (http://example.com#!/1234). User enters on http://example.com/. Then he click a reference and the address of the page changes to http://example.com#!/1234 (something happ...
Methodology: how to change URL without reloading page and index whole URL (with anchor # part)?
I need Google indexes full URL with anchor part (http://example.com#!/1234). User enters on http://example.com/. Then he click a reference and the address of the page changes to http://example.com#!/1234 (something happens, page does not reload). If user types the address (http://example.com#!/1234) directly to address...
[ "See the documentation here: http://code.google.com/web/ajaxcrawling/docs/getting-started.html\nAnd specifically the parts relating to _escaped_fragment_.\n" ]
[ 1 ]
[]
[]
[ "backend", "html", "javascript", "php", "python" ]
stackoverflow_0007467160_backend_html_javascript_php_python.txt
Q: Crash when showing a PyQt4 Window after importing a python extension that uses OpenMP I'm developing a python application that uses a C-extension module I also developed myself. The extension module does some heavy number crunching and makes use of OpenMP. I was recently adding some GUI components to my Python app...
Crash when showing a PyQt4 Window after importing a python extension that uses OpenMP
I'm developing a python application that uses a C-extension module I also developed myself. The extension module does some heavy number crunching and makes use of OpenMP. I was recently adding some GUI components to my Python application using PyQt4. However, when I show a window, the application crashes before the win...
[ "As a workaround, you can create a stand alone program using openmp, and a Qt frontend program. and make them communicate by using tcp socket or something you familiar (dll is another option?).\nthe point is, isolate different modules, if one module fails, you know which part fails.\nas one whole big program, it is...
[ 1, 1, 1 ]
[]
[]
[ "openmp", "pyqt", "python", "python_c_extension", "qt" ]
stackoverflow_0007273779_openmp_pyqt_python_python_c_extension_qt.txt
Q: python regex - last occurance before EOL I have a set of strings from a log file that I need to parse: timestamp - user not found : user1 timestamp - exception in xyz.security.plugin: global error : low memory I want to capture the text between "-" and the last ":". Currently I am using r' -(.*?)\n' which...
python regex - last occurance before EOL
I have a set of strings from a log file that I need to parse: timestamp - user not found : user1 timestamp - exception in xyz.security.plugin: global error : low memory I want to capture the text between "-" and the last ":". Currently I am using r' -(.*?)\n' which captures the string till the EOL. Please bear...
[ "import re\n\nfor line in open('logfile.log'):\n match = re.search(r'-(.*):', line)\n if match:\n print match.group(1)\n else:\n match = re.search(r'-(.*)', line)\n if match:\n print match.group(1)\n else:\n print 'No match in line', line.strip()\n\n", "T...
[ 2, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007467279_python_regex.txt
Q: How to force old versions of eog to run in a new instance? I have a little python script where I display images by writing them to a temp file, calling eog on the temp file, and then calling rm on the temp file after the eog process closes. The relevant code looks basically like this: os.popen('(eog --new-instance...
How to force old versions of eog to run in a new instance?
I have a little python script where I display images by writing them to a temp file, calling eog on the temp file, and then calling rm on the temp file after the eog process closes. The relevant code looks basically like this: os.popen('(eog --new-instance tmp.jpg; rm tmp.jpg)&') The --new-instance flag is important; ...
[ "There might be a better way to do this overall, but if you would like to make sure rm doesn't run before eog is finished, you can use wait() on a Popen object. This will solve your crashing issues, but you'll also need to check if an existing eog process is running.\nimport subprocess as subp\nimport os, signal\n...
[ 0, 0 ]
[]
[]
[ "image", "popen", "python", "sh" ]
stackoverflow_0007464852_image_popen_python_sh.txt
Q: Chameleon i18n and pluralization How does pluralization in Chameleon templates? I didn't manage to find examples in the documentation. For, example could be having output <span>1 car</span> and <span>2 cars</span> A: Chameleon takes its i18n syntax from Zope pagetemplates, which does unfortunately not sup...
Chameleon i18n and pluralization
How does pluralization in Chameleon templates? I didn't manage to find examples in the documentation. For, example could be having output <span>1 car</span> and <span>2 cars</span>
[ "Chameleon takes its i18n syntax from Zope pagetemplates, which does unfortunately not support pluralization.\n" ]
[ 1 ]
[]
[]
[ "chameleon", "internationalization", "pyramid", "python" ]
stackoverflow_0007339708_chameleon_internationalization_pyramid_python.txt
Q: Finding installation directory of a program on windows from python A python program needs to find the installation location of openoffice.org, which is installed on a Windows XP computer. What is the best way to do this? A: You can use the _winreg module on windows: First find out the path in the registry (eg st...
Finding installation directory of a program on windows from python
A python program needs to find the installation location of openoffice.org, which is installed on a Windows XP computer. What is the best way to do this?
[ "You can use the _winreg module on windows: First find out the path in the registry (eg starting regedit.exe and using its find function). Then you can query this path as I did it once to find the home directory of R:\nkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \"Software\\\\R-core\\\\R\")\nvalue = _winreg....
[ 7 ]
[]
[]
[ "path", "python", "windows" ]
stackoverflow_0007468061_path_python_windows.txt
Q: Optimize memory usage, code selection I am working on a quite big project: The program has to do multiple tasks at the same time and each of them does hundreds of complicated calculations each second. The program has to be working 24/7. As I am not a proffessionnal programmer and I don't know how memory and CPU is...
Optimize memory usage, code selection
I am working on a quite big project: The program has to do multiple tasks at the same time and each of them does hundreds of complicated calculations each second. The program has to be working 24/7. As I am not a proffessionnal programmer and I don't know how memory and CPU is handled by this kind of program, I request...
[ "If you need speed, numpy can help you, it's really fast (it's based on atlas, blas, lapack).\nI don't know if you can use it in C#.\nIf you have a lot of calculations to do, you should find a way to store results in case something crash. Moreover maybe you can find a way to optimize using cache. Otherwise you can ...
[ 1 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0007468317_c#_python.txt
Q: Run-Install python-meep Error I am new in python meep. I try to use python-meep on Ubuntu 10.04 64 bit (virtual machine). I install all the necessary things like PCRE swig and python meep, but when I try to run the samples it gives me the same error as in the beginning: ~/Desktop/Python/python-meep/samples/bent...
Run-Install python-meep Error
I am new in python meep. I try to use python-meep on Ubuntu 10.04 64 bit (virtual machine). I install all the necessary things like PCRE swig and python meep, but when I try to run the samples it gives me the same error as in the beginning: ~/Desktop/Python/python-meep/samples/bent_waveguide$ python python_meep_bent...
[ "Try to use the python-setuptools, so you install the stuff with pip or easy_install.\n" ]
[ 0 ]
[]
[]
[ "meep", "python" ]
stackoverflow_0007467897_meep_python.txt
Q: bash's who command I'm trying to capture&analyze the IDLE time for users in a python script, as obtained by the who command. My problem is that who's time output is a mess - some examples given: 1.00s 47:49 - 9days ... and I possibly left out some of them. There is some way of converting it to something that can...
bash's who command
I'm trying to capture&analyze the IDLE time for users in a python script, as obtained by the who command. My problem is that who's time output is a mess - some examples given: 1.00s 47:49 - 9days ... and I possibly left out some of them. There is some way of converting it to something that can be analysed easier? Or ...
[ "Python's os module really has such a function. It's called getlogin(), see here: http://docs.python.org/library/os.html#os.getlogin\nRegarding your update:\nThere is also a getcwd() available: http://docs.python.org/library/os.html#os.getcwd\nBut I'm not fully understanding what you are really trying to do, so I c...
[ 2 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0007467748_bash_python.txt
Q: how to use django admin Many-to-many field in forms This is my models: class Affiliation(models.Model): submission = models.ForeignKey(Submission, related_name='submission_affiliations') name = models.CharField(max_length=255) department = models.CharField(max_length=255) city = models.CharField(ma...
how to use django admin Many-to-many field in forms
This is my models: class Affiliation(models.Model): submission = models.ForeignKey(Submission, related_name='submission_affiliations') name = models.CharField(max_length=255) department = models.CharField(max_length=255) city = models.CharField(max_length=255) country = models.CharField(max_length=2...
[ "Have you tried inline formsets ?\n", "I don't know if you would consider using ajax, but if, django-ajax-selects should help you, I have been using it several times.\n", "you can do some like how G-mail does for its \"To\" field in email composer\nthere is a text area or text field which has auto complete, and...
[ 1, 0, 0 ]
[]
[]
[ "django", "many_to_many", "python" ]
stackoverflow_0007466377_django_many_to_many_python.txt
Q: what's the difference between two Python imports Python has two ways to import something from a module: from mymodule import ClassOne, ClassTwo, ClassThree and from mymodule import (ClassOne, ClassTwo, ClassThree) I cannot find any note (probably, I'm just not trying hard enough) on this in Python's documentatio...
what's the difference between two Python imports
Python has two ways to import something from a module: from mymodule import ClassOne, ClassTwo, ClassThree and from mymodule import (ClassOne, ClassTwo, ClassThree) I cannot find any note (probably, I'm just not trying hard enough) on this in Python's documentation. I want to know the significant difference between t...
[ "If you put the items to import between brackets, you can use more than one line for everything you want to import, without escaping newlines.\n" ]
[ 11 ]
[]
[]
[ "import", "python" ]
stackoverflow_0007468774_import_python.txt
Q: How do I load a Django template outside of the web app? I am trying to use Django template library outside of the web app. I can pass contextual variables to construct a html document. I have python code that loads the template and constructs the html data. When I try to run the script, I get the following error: ...
How do I load a Django template outside of the web app?
I am trying to use Django template library outside of the web app. I can pass contextual variables to construct a html document. I have python code that loads the template and constructs the html data. When I try to run the script, I get the following error: raise InvalidTemplateLibrary("Template library %s does not ha...
[ "I've tried to reproduce your error, with no luck. Here's (http://pastebin.com/k116mbXC) the simple script (based on your code) that renders template outside of django application. Works on Django 1.3.\n" ]
[ 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0006092455_django_django_templates_python.txt
Q: How can I prevent closing of tags in bad HTML using BeautifulSoup (python)? I automatically translate content of HTML pages to different language, so I have to extract all text nodes from different HTML pages that are sometimes badly written (I have no possibility to edit these HTMLs). By using BeautifulSoup i can...
How can I prevent closing of tags in bad HTML using BeautifulSoup (python)?
I automatically translate content of HTML pages to different language, so I have to extract all text nodes from different HTML pages that are sometimes badly written (I have no possibility to edit these HTMLs). By using BeautifulSoup i can extract those texts easily and replace it with translation, but when I display H...
[ "BeautifulSoup excels in parsing and extracting data from badly formatted HTML/XML, but if the broken HTML is ambiguous then it uses a set of rules to interpret the tags (which may not be what you want). See the section on Parsing HTML in the docs which ends with an example that sounds very similar to your situatio...
[ 4 ]
[]
[]
[ "beautifulsoup", "html_parsing", "parsing", "python" ]
stackoverflow_0007468416_beautifulsoup_html_parsing_parsing_python.txt
Q: Python equivalent of C struct (porting app form C to python) I'm porting a simple bluetooth app, which sends "magic" packet on L2Cap protocol to bluetooth device.. I have a problem with converting struct object in C to python equivalent.. In c: /* command types */ #define CFGBT_TYPE_SETREQ 0x00 #define ...
Python equivalent of C struct (porting app form C to python)
I'm porting a simple bluetooth app, which sends "magic" packet on L2Cap protocol to bluetooth device.. I have a problem with converting struct object in C to python equivalent.. In c: /* command types */ #define CFGBT_TYPE_SETREQ 0x00 #define CFGBT_TYPE_SETRES 0x01 #define CFGBT_TYPE_GETREQ ...
[ "You can go about it with the struct module to pack values into a byte string, for example:\n>>> import struct\n>>> type, status, varid, value = 1, 0, 16, b'Hello'\n>>> buffer = struct.pack('>BBH16s', type, status, varid, value)\n>>> buffer\nb'\\x01\\x00\\x00\\x10Hello\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\...
[ 3, 0 ]
[]
[]
[ "python", "struct" ]
stackoverflow_0007468168_python_struct.txt
Q: Python dictionary, adding a new value to key if present multiple times in list Im trying to split a string of letters into a dictionary which automatically adds the value +1 for every letter present more than once. The only problem is that my code adds the value +1 for every key...For example if i input: "aasf" th...
Python dictionary, adding a new value to key if present multiple times in list
Im trying to split a string of letters into a dictionary which automatically adds the value +1 for every letter present more than once. The only problem is that my code adds the value +1 for every key...For example if i input: "aasf" the dict will be: a:2, s:2, f:2... Whats wrong?? word = raw_input("Write letters: ") c...
[ "Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) \n>>> from collections import Counter\n>>> Counter('count letters in this sentence')\nCounter({'e': 5, 't': 5, ' ': 4, 'n': 4, 's': 3, 'c': 2, 'i': 2, 'h': 1, 'l': 1, 'o': 1, 'r': 1, 'u': 1})\n>>> \n\n", "you must use either \nchars[c] = words.count(c)\n\nOR \nch...
[ 3, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007468541_dictionary_python.txt
Q: How to show a route visually in Google Maps I need to create a google maps web application, where I can import a GPX file to show the route visually as an overlay on the map. After the import I want the result to look like this! How do I do this. I'am using python django Hope someone can help A: I can't help wi...
How to show a route visually in Google Maps
I need to create a google maps web application, where I can import a GPX file to show the route visually as an overlay on the map. After the import I want the result to look like this! How do I do this. I'am using python django Hope someone can help
[ "I can't help with the GPX/python/django side of things. However if you can presumably get a set of data with latitude and longitudes for all the points along your route, this code will create the route for you.\n<!DOCTYPE html>\n<html>\n<head>\n<title>Draw a polyline given many coordinates</title>\n\n<meta name=\...
[ 4 ]
[]
[]
[ "django", "google_maps", "python", "web" ]
stackoverflow_0007469114_django_google_maps_python_web.txt
Q: Format int as int, but float as %.3f I have a function that expects two cutoff values, called min_df and max_df. Either may be an int to denote an absolute frequency cutoff, or a float to denote a relative frequency. Now, I want to add some checks and give appropriate warning messages, but without too much clutter...
Format int as int, but float as %.3f
I have a function that expects two cutoff values, called min_df and max_df. Either may be an int to denote an absolute frequency cutoff, or a float to denote a relative frequency. Now, I want to add some checks and give appropriate warning messages, but without too much clutter. This works: if max_df < 0 or min_df < 0:...
[ "Keep it simple\ndef format_df(df):\n if isinstance(df, (int, long)):\n return \"%d\" % df\n elif isinstance(df, float):\n return \"%.3f\" % df\n else:\n return str(df) # fallback just in case\n\nraise ValueError, \"neither max_df (%s) nor min_df (%s) may be <0\" %\n (...
[ 9, 6 ]
[]
[]
[ "python", "python_2.5", "string_formatting" ]
stackoverflow_0007469301_python_python_2.5_string_formatting.txt
Q: Renaming file names containing spaces I am writing a simple Python script to rename all files in a directory to replace all spaces in the file name with hyphens. I have the following which is crashing on os.rename import os path = os.getcwd() filenames = os.listdir(path) for filename in filenames: os.renam...
Renaming file names containing spaces
I am writing a simple Python script to rename all files in a directory to replace all spaces in the file name with hyphens. I have the following which is crashing on os.rename import os path = os.getcwd() filenames = os.listdir(path) for filename in filenames: os.rename(os.path.join(path + filename), os.path.jo...
[ "I think it's just because you have the syntax wrong in your call to os.path.join, the items you're joining should be supplied as two distinct arguments, separated by a comma. This works fine for me:\nPython 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \...
[ 30, 14 ]
[]
[]
[ "file", "operating_system", "python", "rename" ]
stackoverflow_0007469374_file_operating_system_python_rename.txt
Q: Reshape for array multiplication/division in python I'm encountering an annoying shape mismatch issue when I'm working with arrays that are the same length, but one is only width one. For example: import numpy as np x = np.ones(80) y = np.ones([80, 100]) x*y ValueError: shape mismatch: objects cannot be broadca...
Reshape for array multiplication/division in python
I'm encountering an annoying shape mismatch issue when I'm working with arrays that are the same length, but one is only width one. For example: import numpy as np x = np.ones(80) y = np.ones([80, 100]) x*y ValueError: shape mismatch: objects cannot be broadcast to a single shape The simple solution is y*x.reshape(...
[ "Two somewhat easy ways are:\n(x * y.T).T\n\nor \nx.reshape((-1,1)) * y\n\nNumpy's broadcasting is a very powerful feature, and will do exactly what you want automatically, but it expects the last axis (or axes) of the arrays to have the same shape, not the first axes. Thus, you need to transpose y for it to work....
[ 5, 4 ]
[]
[]
[ "numpy", "python", "shapes" ]
stackoverflow_0007463941_numpy_python_shapes.txt
Q: Converting old function-based generic CRUD views to the new style class-based generic CRUD views I've been using Django's generic CRUD views for quite a few things in my project. I'd now like to begin migrating to new style class-based generic CRUD views in DJango 1.3. I didn't finds the docs to be very help and c...
Converting old function-based generic CRUD views to the new style class-based generic CRUD views
I've been using Django's generic CRUD views for quite a few things in my project. I'd now like to begin migrating to new style class-based generic CRUD views in DJango 1.3. I didn't finds the docs to be very help and could use a little help with converting some of my function-based views. Here's a snippet of my views: ...
[ "After digging through the Django sources I found out how to do it.\nclass DomainCreateView(CreateView):\n \"\"\"\n Creates a Domain\n \"\"\"\n form_class = DomainForm\n template_name = 'customer/create_domains.html'\n success_url = reverse_lazy('manage_domains')\n\n @method_decorator(login_req...
[ 3 ]
[]
[]
[ "django", "django_class_based_views", "django_generic_views", "python" ]
stackoverflow_0007460695_django_django_class_based_views_django_generic_views_python.txt
Q: Multiple python web applications running on multiple domains (virtualhost)? I am stuck and desperate. Is it possible to serve multiple python web applications on multiple different domains using virtualhost on cherrypy? Hmm wait... I will answer myself: Yes, it is possible. With virtual host dispatcher it is poss...
Multiple python web applications running on multiple domains (virtualhost)?
I am stuck and desperate. Is it possible to serve multiple python web applications on multiple different domains using virtualhost on cherrypy? Hmm wait... I will answer myself: Yes, it is possible. With virtual host dispatcher it is possible, until i require this: I need to use more instances of same application but ...
[ "Apache/mod_wsgi can do what is required. Each mounted web application under mod_wsgi will run in a distinct sub interpreter in the same process so can be using different code bases. Better still, you use daemon mode of mod_wsgi and delegate each web application to distinct process so not risk of them interfering w...
[ 1, 0 ]
[]
[]
[ "cherrypy", "hosting", "python", "python_3.x", "web_hosting" ]
stackoverflow_0007468544_cherrypy_hosting_python_python_3.x_web_hosting.txt
Q: how to get correct order of the image when converted to numpy array? I am reading the image from the disk and I am converting it to a numpy array im=Image.open(infile) imdata = scipy.misc.fromimage(im) but the image is mirrored like it is stored on the disk. How to read it in a correct order. Thanks a lot. A: ...
how to get correct order of the image when converted to numpy array?
I am reading the image from the disk and I am converting it to a numpy array im=Image.open(infile) imdata = scipy.misc.fromimage(im) but the image is mirrored like it is stored on the disk. How to read it in a correct order. Thanks a lot.
[ "If it is upside down:\nimagedata = imagedata[::-1, :]\n\nIf it is swapped left to right:\nimagedata = imagedata[:, ::-1]\n\nAnd if it is transposed (flipped at the diagonal):\nimagedata = imagedata.T\n\nIf you have more dimensions more (color, alpha, ...) flipping can be done by\nimagedata = imagedata[::-1, ... ]\...
[ 2 ]
[]
[]
[ "image", "numpy", "python" ]
stackoverflow_0007469803_image_numpy_python.txt
Q: CPU Utilization on UNIX I'm trying to calculate the percentage of CPU% used for a particular process using Python/Shell, but so far nothing. I have looked at a lot of questions here, but none could help me. Any suggestions? A: $ ps o "pid cp" PID CP 1609 0 1813 0 1851 0 1885 0 1896 0 3164 ...
CPU Utilization on UNIX
I'm trying to calculate the percentage of CPU% used for a particular process using Python/Shell, but so far nothing. I have looked at a lot of questions here, but none could help me. Any suggestions?
[ "$ ps o \"pid cp\"\n PID CP\n 1609 0\n 1813 0\n 1851 0\n 1885 0\n 1896 0\n 3164 0\n21679 0\n24019 2\n\nIf the process you're looking for might not be running as the same user etc, you can use ps -eo \"pid cp\" to show all processes on the system instead of just the default self-owned ones.\nIf you...
[ 3, 1, 0 ]
[]
[]
[ "cpu", "python", "shell", "unix" ]
stackoverflow_0007470045_cpu_python_shell_unix.txt
Q: Multiple file upload tracking in Cherrypy 3.2 I have a simplistic CherryPy 3.2 web application, running on Windows 7, that successfully allows me to upload multiple files. The application doesn't save or do anything special with the uploaded files at the moment, however. I just want to do some testing first. An...
Multiple file upload tracking in Cherrypy 3.2
I have a simplistic CherryPy 3.2 web application, running on Windows 7, that successfully allows me to upload multiple files. The application doesn't save or do anything special with the uploaded files at the moment, however. I just want to do some testing first. Anyways, the HTML snippet includes these lines <form ...
[ "Use yield and return a streaming with the actual uploaded file size.\nYou can check yield with cherrypy here: http://www.cherrypy.org/wiki/ReturnVsYield\nThis is one of the cases where yield fits.\n" ]
[ 2 ]
[]
[]
[ "cherrypy", "progress", "python", "statistics", "upload" ]
stackoverflow_0005813969_cherrypy_progress_python_statistics_upload.txt
Q: Interpreting Strings as Variable Names (Classes involved) - Python I have some strings of variables names, that must initially be strings (due to file IO). The variables these correspond to are variable names of PyQt4 widgets, embed in two classes. I need these strings able to be converted to the actual variable n...
Interpreting Strings as Variable Names (Classes involved) - Python
I have some strings of variables names, that must initially be strings (due to file IO). The variables these correspond to are variable names of PyQt4 widgets, embed in two classes. I need these strings able to be converted to the actual variable names to use them in functions. (Kind of like how you 'int' a string of a...
[ "Try\ngetattr(self.ui, VariableName).Function()\n\nSee here for more info on getattr.\n" ]
[ 6 ]
[]
[]
[ "class", "eval", "pyqt4", "python", "variables" ]
stackoverflow_0007470151_class_eval_pyqt4_python_variables.txt
Q: How to Integrate Pyramid 1.1 and Mongo DB - as few lines as possible Goal: I try to integrate Mongo DB with Pyramid 1.1 basic application. Background: Appliation is created by the book (https://docs.pylonsproject.org/projects/pyramid/1.1/narr/project.html#creating-the-project) using basic command "paste create -...
How to Integrate Pyramid 1.1 and Mongo DB - as few lines as possible
Goal: I try to integrate Mongo DB with Pyramid 1.1 basic application. Background: Appliation is created by the book (https://docs.pylonsproject.org/projects/pyramid/1.1/narr/project.html#creating-the-project) using basic command "paste create -t pyramid_starter" I followed this cookbook article: https://docs.pylonspr...
[ "Another possible solution is to use the 'debugtoolbar.panels' setting in your config file to disable the request_vars panel (which is what is causing the issue):\n[app:main]\n.. other stuff ...\ndebugtoolbar.panels =\n pyramid_debugtoolbar.panels.versions.VersionDebugPanel\n pyramid_debugtoolbar.panels.setti...
[ 2, 0, 0 ]
[]
[]
[ "mongodb", "pyramid", "python" ]
stackoverflow_0007201969_mongodb_pyramid_python.txt
Q: Problem loading local files with webkit in python Every time I need to load a local file using webkit in python I need to start with "file://" which I need to include in all files I am working with. How can I eliminate the need to do that? I want to load files like webview.load_uri('file.html') instead of webview....
Problem loading local files with webkit in python
Every time I need to load a local file using webkit in python I need to start with "file://" which I need to include in all files I am working with. How can I eliminate the need to do that? I want to load files like webview.load_uri('file.html') instead of webview.load_uri('file://file.html')?
[ "You can't. webview.load_uri() takes a string containing a URI. 'file.html' isn't a URI, 'file://file.html' is.\n", "webview.load_string() takes the text of an html file. you can load the file into a file object without the file:// and read it into the load_string function.\n" ]
[ 3, 1 ]
[]
[]
[ "gtk", "python", "webkit" ]
stackoverflow_0004416570_gtk_python_webkit.txt
Q: process started by python's subprocess doesn't exist I run a 'mstsc' program in win7 using python's subprocess: >>> import subprocess >>> p=subprocess.Popen('mstsc') >>> p.pid 8884 However, the '8884' process doesn't exist when I check Windows' process moniter, and another 'mstsc' does exist. So I wonder if ...
process started by python's subprocess doesn't exist
I run a 'mstsc' program in win7 using python's subprocess: >>> import subprocess >>> p=subprocess.Popen('mstsc') >>> p.pid 8884 However, the '8884' process doesn't exist when I check Windows' process moniter, and another 'mstsc' does exist. So I wonder if the 'mstsc' create another subprocess when calling subproc...
[ "Well i m still a newbie on python, but still you can go through this.\nThe Popen class uses CreateProcess function in windows to execute the child program.\nCreateProcess function Creates a new process and its primary thread. This new process runs in the security context of the calling process.\nInternally it use ...
[ 6 ]
[]
[]
[ "python", "subprocess", "windows" ]
stackoverflow_0007467835_python_subprocess_windows.txt
Q: Python wordlist I would like to compare the input letters(dictionary) with the list(textfile with words) and print the words matching the inputed letters. What have I done wrong?(I know i only have a print YES or NO-function if it finds a matching word at the moment. What's the best way to create this function by ...
Python wordlist
I would like to compare the input letters(dictionary) with the list(textfile with words) and print the words matching the inputed letters. What have I done wrong?(I know i only have a print YES or NO-function if it finds a matching word at the moment. What's the best way to create this function by the way?). def ordlis...
[ "You are checking for the presence of the entire list of keys in your character list, rather than checking for each key individually. You must iterate over your keys individually, and then check for their presence.\nfor k in chars:\n if k in ordlista(list):\n print \"YES\"\n else:\n print \"NO\...
[ 2, 2, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007470189_dictionary_python.txt
Q: how to explain this loop result in python? x=range(1,4) y=range(1,4) [(xi,yi) for xi in x for yi in y if xi is yi] #output # [(1, 1), (2, 2), (3, 3)] [(xi,yi) for xi in x if xi is yi for yi in y ] #output, I am confused about this one #[(3, 1), (3, 2), (3, 3)] Can any one explain why the second loop results...
how to explain this loop result in python?
x=range(1,4) y=range(1,4) [(xi,yi) for xi in x for yi in y if xi is yi] #output # [(1, 1), (2, 2), (3, 3)] [(xi,yi) for xi in x if xi is yi for yi in y ] #output, I am confused about this one #[(3, 1), (3, 2), (3, 3)] Can any one explain why the second loop results like this? I am quite confused about how multi...
[ "The second construct isn't valid code on its own:\nIn [1]: x=range(1,4)\n\nIn [2]: y=range(1,4)\n\nIn [3]: [(xi,yi) for xi in x if xi is yi for yi in y ]\n---------------------------------------------------------------------------\nNameError Traceback (most recent call last)\n\n/hom...
[ 7, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0007470988_loops_python.txt
Q: Binary Phase Shift Keying in Python I'm currently working on some code to transmit messages/files/and other data over lasers using audio transformation. My current code uses the hexlify function from the binascii module in python to convert the data to binary, and then emits a tone for a 1 and a different tone for...
Binary Phase Shift Keying in Python
I'm currently working on some code to transmit messages/files/and other data over lasers using audio transformation. My current code uses the hexlify function from the binascii module in python to convert the data to binary, and then emits a tone for a 1 and a different tone for a 0. This in theory works, albeit not th...
[ "Take a look at GNU Radio!\nhttp://gnuradio.org/redmine/projects/gnuradio/wiki\nGNU Radio is a project to do, in software, as much possible of radio signal transmission or reception. Because radio already uses phase shift keying, the GNU Radio guys have already solved the problem for you, and GNU Radio is already ...
[ 7, 4 ]
[]
[]
[ "audio", "binary", "python" ]
stackoverflow_0007466715_audio_binary_python.txt
Q: Python: converting a nested list into a simple list with coord positions I am learning python and panda3d currently. I have a nested list which i need to convert into a list of coordinates. my input is [['g,g', 'g,g'], ['d,d', 'd,d,d', 'd,d], ['s,s', 's,s']] The Output that I need is another list: [(0,0,...
Python: converting a nested list into a simple list with coord positions
I am learning python and panda3d currently. I have a nested list which i need to convert into a list of coordinates. my input is [['g,g', 'g,g'], ['d,d', 'd,d,d', 'd,d], ['s,s', 's,s']] The Output that I need is another list: [(0,0,0,'s'),(0,1,0,'s'),(1,0,0,'s'),(1,1,0,'s'),(0,0,1,'d'),(0,1,1,'d'),(1,0,1,'d')...
[ "It might be this:\nl = [['g,g', 'g,g'], ['d,d', 'd,d,d', 'd,d'], ['s,s', 's,s']]\noutput = [ (x, y, z, v) for z, l1 in enumerate(l[::-1]) for y, l2 in enumerate(l1) for x, v in enumerate(l2.split(',')) ]\n\n... but as it has been written, it is not clear what the rule is exactly. In nested loops:\noutput = []\nfor...
[ 3 ]
[]
[]
[ "list", "nested_lists", "python" ]
stackoverflow_0007471055_list_nested_lists_python.txt
Q: How do I generate a multipart/mime message with correct CRLF in Python? I need to generate a multipart/mime message to send as a response to a HTTP request but am hitting either a bug or limitation in the Python email.* package. The problem is that using Python 2.6, the message.as_string() call below generates a s...
How do I generate a multipart/mime message with correct CRLF in Python?
I need to generate a multipart/mime message to send as a response to a HTTP request but am hitting either a bug or limitation in the Python email.* package. The problem is that using Python 2.6, the message.as_string() call below generates a string with \n rather that CRLF as the line endings: message = MIMEMultipart()...
[ "This was a bug in Python that has now been fixed: http://hg.python.org/lookup/r85811\nIt should now be possible to use the MIME libraries over non-email transports and have sensible things happen.\n", "What about a simple hack\nmessage.as_string().replace('\\n', '\\r\\n')\n\n? Inelegant, but should work (and a ...
[ 3, 2 ]
[]
[]
[ "mime", "python" ]
stackoverflow_0003086860_mime_python.txt
Q: super and __new__ confusion As what I just learned, I can use super() this way: super(class, obj_of_class-or-_subclass_of_class) Code goes below: #Case 1 class A(object): def __init__(self): print "A init" class B(A): def __init__(self): print "B init" super(B, self).__init__() #o...
super and __new__ confusion
As what I just learned, I can use super() this way: super(class, obj_of_class-or-_subclass_of_class) Code goes below: #Case 1 class A(object): def __init__(self): print "A init" class B(A): def __init__(self): print "B init" super(B, self).__init__() #ok, I can invoke A's __init__ succ...
[ "From the Python release notes on overriding the __new__ method:\n\n__new__ is a static method, not a class method. I initially thought it\n would have to be a class method, and that's why I added the\n classmethod primitive. Unfortunately, with class methods, upcalls\n don't work right in this case, so I had to...
[ 34 ]
[]
[]
[ "class_method", "python" ]
stackoverflow_0007471255_class_method_python.txt
Q: Python script started by Task Scheduler can't edit file I made this python script: # -*- coding: utf-8 -*- from datetime import datetime date = datetime.now() file = open('myfile.dat', 'a+') file.write(str(date)+'\n') It works fine. But when I schedule it in the Task Scheduler on Windows Server 2008 the script ...
Python script started by Task Scheduler can't edit file
I made this python script: # -*- coding: utf-8 -*- from datetime import datetime date = datetime.now() file = open('myfile.dat', 'a+') file.write(str(date)+'\n') It works fine. But when I schedule it in the Task Scheduler on Windows Server 2008 the script runs, but it doesn't write to the file. Task Scheduler uses m...
[ "Have you tried using an absolute path to the file?\nI think there is also an option in task scheduler to specify where the script should be run, have you set that to the location of the file you want to write to?\n" ]
[ 6 ]
[]
[]
[ "permissions", "python", "scheduled_tasks", "windows_server_2008" ]
stackoverflow_0007471489_permissions_python_scheduled_tasks_windows_server_2008.txt
Q: How to convert this Python 2 code to Python 3? This Python code gives a two-dimensional table in version 2. However, in Python 3, it doesn't work: i = 1 while (i <= 10): print (2*i, ' ',) i += 1 print () The output is: 2 4 6 8 10 12 14 16 18 20 Although I have made modifications in print statements a...
How to convert this Python 2 code to Python 3?
This Python code gives a two-dimensional table in version 2. However, in Python 3, it doesn't work: i = 1 while (i <= 10): print (2*i, ' ',) i += 1 print () The output is: 2 4 6 8 10 12 14 16 18 20 Although I have made modifications in print statements as required in Python 3, it still does not work. How...
[ "Move the second print call out of the loop. Inside the loop, a newline is added between every number.\ni = 1\nwhile (i <= 10):\n print (2*i, ' ',end='')\n i += 1\nprint()\n\nOr, you could replace the while loop (and the print() call) with a generator expression:\nprint(*(2*i for i in range(1,11)),sep=' ')\n...
[ 2, 2, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007470615_python_python_3.x.txt
Q: Can "soft references" exist in Python? In other languages (e.g. Java), object references can be Strong, Weak, Soft or Phantom (http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html). In Python, references are Strong by default and the WeakRef module allows weak references. Is it possible to h...
Can "soft references" exist in Python?
In other languages (e.g. Java), object references can be Strong, Weak, Soft or Phantom (http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html). In Python, references are Strong by default and the WeakRef module allows weak references. Is it possible to have "soft references" in Python? In my parti...
[ "Python doesn't natively offer any flavors of references besides hard (aka strong) & weak. \nThat said, here is a softref implementation I whipped up a year or so ago which I've been using in a few places I needed one. What it provides aren't quite actual soft references, but it comes close for most use cases. It's...
[ 6, 0 ]
[]
[]
[ "python", "reference", "soft_references" ]
stackoverflow_0007331389_python_reference_soft_references.txt
Q: Design problem with a component that should automatically create a database record when another one is saved I have a situation where I want to create a menu item in the database whenever a record is created. I need to design a component that will create the mentioned menu item. I am using django-sitetree as the b...
Design problem with a component that should automatically create a database record when another one is saved
I have a situation where I want to create a menu item in the database whenever a record is created. I need to design a component that will create the mentioned menu item. I am using django-sitetree as the basic app for the menu. It has the following model: class TreeItem(models.Model): PERM_TYPE_ANY = 1 PERM_...
[ "You can use Signals.\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom myapp.models import Record, TreeItem\n\n@receiver(post_save, sender=Record)\ndef my_handler(sender, instance, created, raw):\n if created:\n item = TreeItem() # ..\n\nWhenever new record is crea...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007463771_django_django_models_python.txt
Q: Hierarchical checked tree control with tri-state checkboxes in wxPython? As per the title, is this possible? By tri-state, I mean the parent node is: Checked if all children are checked Unchecked if all children are unchecked Grey/Filled if some children are checked I have used them previously in C# but cannot f...
Hierarchical checked tree control with tri-state checkboxes in wxPython?
As per the title, is this possible? By tri-state, I mean the parent node is: Checked if all children are checked Unchecked if all children are unchecked Grey/Filled if some children are checked I have used them previously in C# but cannot find an equivalent control/implementation for wxPython.
[ "I was trying to do the same thing with the CustomTreeCtrl and it does support tri-state check boxes.\nWhen you create the root,\nself.root= self.tree.AddRoot(\"root node\",ct_type=1)\n\nor a child node,\nchild= self.tree.AppendItem(parent,\"child\",ct_type=1)\n\nit returns a GenericTreeItem object which you can ch...
[ 3, 2 ]
[]
[]
[ "python", "treeview", "wxpython", "wxwidgets" ]
stackoverflow_0002552349_python_treeview_wxpython_wxwidgets.txt
Q: remove certain attributes from HTML tags How can I remove certain attributes such as id, style, class, etc. from HTML code? I thought I could use the lxml.html.clean module, but as it turned out I can only remove style attributes with Clean(style=True).clean_html(code). I'd prefer not to use regular expressions fo...
remove certain attributes from HTML tags
How can I remove certain attributes such as id, style, class, etc. from HTML code? I thought I could use the lxml.html.clean module, but as it turned out I can only remove style attributes with Clean(style=True).clean_html(code). I'd prefer not to use regular expressions for this task (attributes could change). What I ...
[ "cleaner.Cleaner.__call__ has a safe_attrs_only parameter. When set to True, only attributes in clean.defs.safe_attrs are preserved. You can remove any or all attributes by changing clean.defs.safe_attrs. Just be sure to change it back when you are done.\nimport lxml.html.clean as clean\n\ncode = '<tr id=\"ctl00_Co...
[ 12 ]
[]
[]
[ "beautifulsoup", "html_parsing", "lxml", "python" ]
stackoverflow_0007470333_beautifulsoup_html_parsing_lxml_python.txt
Q: How to convert Python dictionary object to numpy array I have python dict object with key as datetime.date object and values as tuple objects: >>> data_dict {datetime.date(2006, 1, 1): (5, 3), datetime.date(2006, 1, 2): (8, 8), datetime.date(2006, 1, 3): (8, 5), datetime.date(2006, 1, 4): (3, 3), datetime.date...
How to convert Python dictionary object to numpy array
I have python dict object with key as datetime.date object and values as tuple objects: >>> data_dict {datetime.date(2006, 1, 1): (5, 3), datetime.date(2006, 1, 2): (8, 8), datetime.date(2006, 1, 3): (8, 5), datetime.date(2006, 1, 4): (3, 3), datetime.date(2006, 1, 5): (3, 3), datetime.date(2006, 1, 6): (4, 3), .....
[ "The following will do it:\narr = np.array([(k,)+v for k,v in data_dict.iteritems()], \\\n dtype=[('date', '|O4'), ('high', '<f8'), ('low', '<f8')])\n\nIf you then wish to use arr as a recarray, you could use:\narr = arr.view(np.recarray)\n\nThis will enable you to reference fields by name, e.g. arr.date.\n...
[ 8 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007471872_numpy_python.txt
Q: Better way to initialize multidimensional array with mutable object I want to create a multidimensional array and initialize it with copies of a mutable object. This is what I have so far: import copy def create_array(dimensions): dimensions = copy.deepcopy(dimensions) dimensions.reverse() a = [0] * d...
Better way to initialize multidimensional array with mutable object
I want to create a multidimensional array and initialize it with copies of a mutable object. This is what I have so far: import copy def create_array(dimensions): dimensions = copy.deepcopy(dimensions) dimensions.reverse() a = [0] * dimensions[0] del dimensions[0] for d in dimensions: a = [...
[ "How about:\nimport copy\n\ndef create_array_mutable(dims, obj):\n if len(dims) == 0:\n return copy.deepcopy(obj)\n else:\n return [create_array_mutable(dims[1:], obj) for i in xrange(dims[0])]\n\nclass C(object): pass\n\nprint create_array_mutable((2,3,4), C())\n\nThis creates a 2x3x4 array of unique insta...
[ 2 ]
[]
[]
[ "multidimensional_array", "python" ]
stackoverflow_0007040134_multidimensional_array_python.txt
Q: Why cannot pass print function to dir() in python? Is print a built-in function? If it is, why I cannot run dir(print)? dir is a built-in function and dir(dir) works well. So it looks very strange to me that dir(print) could not work. A: In python 2 print is a statement and not a function and you can't put a sta...
Why cannot pass print function to dir() in python?
Is print a built-in function? If it is, why I cannot run dir(print)? dir is a built-in function and dir(dir) works well. So it looks very strange to me that dir(print) could not work.
[ "In python 2 print is a statement and not a function and you can't put a statement as a function argument, in the other hand in python3 print is a function so you can do dir(print).\n" ]
[ 16 ]
[]
[]
[ "python" ]
stackoverflow_0007472218_python.txt
Q: c++ loop through registry recursively is slow Have an annoying problem with my code, probably I am doing something wrong because my Python implementation is much faster! C++ implementation problems: Iterating over "HKEY_CLASSES_ROOT" takes a lot of ram, I assume it's because c++ implementation uses lots of variab...
c++ loop through registry recursively is slow
Have an annoying problem with my code, probably I am doing something wrong because my Python implementation is much faster! C++ implementation problems: Iterating over "HKEY_CLASSES_ROOT" takes a lot of ram, I assume it's because c++ implementation uses lots of variables. Fixed It's also slow, much slower than python ...
[ "There is leak of resource in your code. You open hkey but you close hKey (note the difference in case of k and K).\nOn a side note, you store the opened registry key into hkey itself. And it happens that hkey is the passed in parameter, shared among all calls to RecurseOpenRegEx. That is why \"somehow i need to re...
[ 4, 1 ]
[]
[]
[ "c++", "python", "registry" ]
stackoverflow_0007472181_c++_python_registry.txt
Q: Ensuring Unique Fields when Randomly Generating MySQL rows I'm generating somewhere around 100,000 rows of random data, with around 10 columns, and I need to have all of values to be unique. The only solid way I could think of doing this would be doing a query on each random generation to make sure that it does no...
Ensuring Unique Fields when Randomly Generating MySQL rows
I'm generating somewhere around 100,000 rows of random data, with around 10 columns, and I need to have all of values to be unique. The only solid way I could think of doing this would be doing a query on each random generation to make sure that it does not exist yet, but that adds hundreds of thousands of queries. The...
[ "I should generate random numbers in python, in a list.\nThen, use set to get uniques.\nl = [1,5,5,4,5,4,8,9,2]\n\nset(l)\n\nset([1, 2, 4, 5, 8, 9])\n\nNow, you may generate 200.000 numbers to get at least 100.000 unique ones, and truncate the list, or so.\n\nI tried this :\nimport random\nl = []\nfor i in range (2...
[ 2, 0 ]
[]
[]
[ "mysql", "mysql_python", "python", "unique_constraint" ]
stackoverflow_0007472450_mysql_mysql_python_python_unique_constraint.txt
Q: Python urllib and urllib2 not opening localhost URLs? In Python I can use urllib2 (and urllib) to open external URLs such as Google. However, I am hitting issues when opening localhost URLs. I have a python SimpleHTTPServer running on port 8280 which I can browse to successfully using http://localhost:8280/. pytho...
Python urllib and urllib2 not opening localhost URLs?
In Python I can use urllib2 (and urllib) to open external URLs such as Google. However, I am hitting issues when opening localhost URLs. I have a python SimpleHTTPServer running on port 8280 which I can browse to successfully using http://localhost:8280/. python -m SimpleHTTPServer 8280 It's also worth noting that I'm...
[ "Check whether the problem is really in opening localhost, or whether JBoss gives invalid response (that the browser somehow works around):\n\ntry using http://127.0.0.1:8280/ instead of \"localhost:8280\" (if that works, it's a DNS problem)\nuse curl or wget to test JBoss works: wget http://localhost:8280/\nyou ca...
[ 5, 3, 1 ]
[]
[]
[ "python", "urllib", "urllib2" ]
stackoverflow_0007012227_python_urllib_urllib2.txt
Q: Cherrypy 3.2 virtual host - application configuration I am trying to use cherrypy virtualhost dispatcher for serving multiple different applications. My idea was to have separate configuration file for each application, but I am kinda lost. If I use virtualhost dispatcher, all applications are in same namespace, ...
Cherrypy 3.2 virtual host - application configuration
I am trying to use cherrypy virtualhost dispatcher for serving multiple different applications. My idea was to have separate configuration file for each application, but I am kinda lost. If I use virtualhost dispatcher, all applications are in same namespace, so for example section for database connection can occur on...
[ "For my current purposes, I am satisfied with this solution:\nI create separate config file for a cherrypy application and I am using the same class as cherrypy for parsing the file. \nfrom cherrypy.lib.reprconf import Config\nsettings = Config(os.path.join(confPath, \"settings.cfg\"))\nAlso, there is python standa...
[ 1 ]
[]
[]
[ "cherrypy", "python", "python_3.x", "virtualhost" ]
stackoverflow_0006650943_cherrypy_python_python_3.x_virtualhost.txt
Q: Django form errors printed I've got a dictionary containing form errors, namely: [u'PHONE_ALREADY_REGISTERED', u'EMAIL_ALREADY_REGISTERED!'] How can I access the values from the dictionary and print them as strings on the screen? This is the piece of HTML code I'm using up until now: {% if errors %} {{ errors....
Django form errors printed
I've got a dictionary containing form errors, namely: [u'PHONE_ALREADY_REGISTERED', u'EMAIL_ALREADY_REGISTERED!'] How can I access the values from the dictionary and print them as strings on the screen? This is the piece of HTML code I'm using up until now: {% if errors %} {{ errors.values }} {% endif %}
[ "First, that's not a dictionary. It's a list.\nSecond the way to print the values of any iterable (dictionaries and lists, included) is with a for loop.\n{% if errors %}\n {% for error in errors %}\n {{ error }}\n {% endfor %}\n{% endif %}\n\nIn your view you could use something like u', '.join(errors)...
[ 1 ]
[]
[]
[ "django", "error_handling", "forms", "python" ]
stackoverflow_0007472183_django_error_handling_forms_python.txt
Q: How do you debug pythonic GUI programs? I want to debug a pythonic program, such as calibre. Normally, I was using pdb to debug from the console, but when I use pdb with pythonic GUI programs, the GUI part (canvas or what the heck it is) freezes and it's really very hard to debug in that way. Any suggestions for d...
How do you debug pythonic GUI programs?
I want to debug a pythonic program, such as calibre. Normally, I was using pdb to debug from the console, but when I use pdb with pythonic GUI programs, the GUI part (canvas or what the heck it is) freezes and it's really very hard to debug in that way. Any suggestions for debugging pythonic GUI programs? How do you do...
[ "I would place calls to logging.debug at the top of each event handler function/method in my GUI code that represents a \"user action\", i.e. mouse clicks, enter key. Also any high-level function that updates the view would have a logging.debug call at the beginning. These log messages would report any important ...
[ 0 ]
[]
[]
[ "debugging", "pdb", "python", "user_interface" ]
stackoverflow_0006705176_debugging_pdb_python_user_interface.txt
Q: Django run admin inteface with custom template In django how to run /admin interface as well as customized admin index page. My template dirs is followed below. TEMPLATE_DIRS = ( PROJECT_PATH + '/templates/', ) And... ADMIN_MEDIA_PREFIX = '//admin/' If i will comment this line my other functions would not work...
Django run admin inteface with custom template
In django how to run /admin interface as well as customized admin index page. My template dirs is followed below. TEMPLATE_DIRS = ( PROJECT_PATH + '/templates/', ) And... ADMIN_MEDIA_PREFIX = '//admin/' If i will comment this line my other functions would not work, if i put it uncommented then ma admin interface sh...
[ "Leave TEMPLATE_DIRS alone, that affects more than just the admin, and that's not your problem anyways.\nThe way to override any admin page is to include the associated template from the default Django admin templates in your own 'yourproject/templates/admin' directory, and make the necessary modifications.\nSee th...
[ 2 ]
[]
[]
[ "django", "django_admin", "django_templates", "python" ]
stackoverflow_0007473002_django_django_admin_django_templates_python.txt
Q: Telnet and SSH calling in main file, Telnet works but ssh fails I am new to python, I am writing a script to 'telenet' device IP in some cases and SSH username@deviceIp if telnet faiils.. For all Telnet IP's it work perfectly.. But when i am doing "ssh admin@153.88.127.21" the below code fails and I get error in t...
Telnet and SSH calling in main file, Telnet works but ssh fails
I am new to python, I am writing a script to 'telenet' device IP in some cases and SSH username@deviceIp if telnet faiils.. For all Telnet IP's it work perfectly.. But when i am doing "ssh admin@153.88.127.21" the below code fails and I get error in try bloc itself like "socket.error" for ssh device's. I want ssh devic...
[ "Did you forgot the client.load_system_host_keys()? This is an example from the docs:\nclient = SSHClient()\nclient.load_system_host_keys()\nclient.connect('ssh.example.com')\nstdin, stdout, stderr = client.exec_command('ls -l')\n\nAnd you should use the try block like this:\ntry:\n telnet()\nexcept:\n telnet...
[ 1 ]
[]
[]
[ "paramiko", "python", "ssh", "telnetlib" ]
stackoverflow_0007472871_paramiko_python_ssh_telnetlib.txt
Q: Force commit of nested save() within a transaction I have a function where I save a large number of models, (thousands at a time), this takes several minutes so I have written a progress bar to display progress to the user. The progress bar works by polling a URL (from Javascript) and looking a request.session val...
Force commit of nested save() within a transaction
I have a function where I save a large number of models, (thousands at a time), this takes several minutes so I have written a progress bar to display progress to the user. The progress bar works by polling a URL (from Javascript) and looking a request.session value to see the state of the first call (the one that is s...
[ "No, both your main saves and the status bar updates will be conducted using the same database connection so they will be part of the same transaction.\nI can see two options to avoid this.\n\nYou can either create your own, separate database connection and save the status bar updates using that. \nDon't save the s...
[ 1 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0007472348_django_python_sql.txt
Q: Connection resets on (large) file upload So I'm having a rather vexing issue with file uploads in Pylons that I'm hoping someone might be able to assist me with. Originally I posted the issue here thinking this was an issue with Pylons, but I've since come to conclude that the issue is due to the server, i.e., pas...
Connection resets on (large) file upload
So I'm having a rather vexing issue with file uploads in Pylons that I'm hoping someone might be able to assist me with. Originally I posted the issue here thinking this was an issue with Pylons, but I've since come to conclude that the issue is due to the server, i.e., paste, and I've tracked down exactly where the is...
[ "Two ideas come to mind ...\n\nTest with another more robust webserver, such as nginx. It can be run concurrently if need be. See if the problem persists. While paste can handle web apps it isn't meant to handle huge file transfers as far as I know.\nAre you using Chunked Transfer Encoding during the upload?\n\...
[ 1, 0 ]
[]
[]
[ "paste", "paster", "pylons", "python" ]
stackoverflow_0007258245_paste_paster_pylons_python.txt
Q: Use Class and Class methods from another class in python I have couple of classes in jira.py, providing 2 for sample class JiraCommand: name = "<default>" aliases = [] summary = "<--- no summary --->" usage = "" mandatory = "" commands = None def __init__(self, commands): sel...
Use Class and Class methods from another class in python
I have couple of classes in jira.py, providing 2 for sample class JiraCommand: name = "<default>" aliases = [] summary = "<--- no summary --->" usage = "" mandatory = "" commands = None def __init__(self, commands): self.commands = commands def dispatch(self, logger, jira_env...
[ "DonCallisto has got it right.\nJiraCat's run method takes three arguments (logger, jira_env, args); the first one is supposed to be a logger object but you're passing a string (\"-s\").\nSo the error that reports a string (logger=\"-s\") has no \"error\" attribute means just that.\nYour comment about the command l...
[ 2 ]
[]
[]
[ "jira", "jira_plugin", "python" ]
stackoverflow_0007471874_jira_jira_plugin_python.txt
Q: Get system date/time in Python after changing time zone On my system, I have set the current time zone for my clock to "Kuala Lumpur, Singapore (UTC+08:00)", which puts my clock forward by eight hours (of course). In python, I'm using the code to get the current time/date: from datetime import datetime dateTimeTup...
Get system date/time in Python after changing time zone
On my system, I have set the current time zone for my clock to "Kuala Lumpur, Singapore (UTC+08:00)", which puts my clock forward by eight hours (of course). In python, I'm using the code to get the current time/date: from datetime import datetime dateTimeTuple = datetime.now() I'm using this method as I need the indi...
[ "datetime.now() returns a naive local datetime. To convert that to Kuala Lumpur time, you first need to make it a timezone-aware datetime, and then convert it to the Kuala Lumpur timezone:\nThe easiest way to do timezone conversions is to use pytz.\nimport pytz\nimport datetime as dt\nkuala_lumpur=pytz.timezone('As...
[ 3 ]
[]
[]
[ "python", "system", "time", "zone" ]
stackoverflow_0007473456_python_system_time_zone.txt
Q: How to raise StopIteration from swig C++ code? I'm trying to extend a C++ library by implementing the python iteration protocol on a class. The problem is that trying to raise a StopIteration exception from the next() method makes the program SegFault. The method I've used for raising the exception from the C++ co...
How to raise StopIteration from swig C++ code?
I'm trying to extend a C++ library by implementing the python iteration protocol on a class. The problem is that trying to raise a StopIteration exception from the next() method makes the program SegFault. The method I've used for raising the exception from the C++ code (in python.i) is the one described here: http://w...
[ "So the right answer seems to be that the next() method must return a PyObject* and also use SetNone. So it would look like this:\nPyObject* next(PyObject* self) {\n if (i < n) {\n \\\\ go on iterating\n } else {\n PyErr_SetNone(PyExc_StopIteration);\n return NULL;\n }\n}\n\nThanks to aix...
[ 5, 1 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0007473079_c++_python_swig.txt
Q: A* Algorithm does not find shortest path I am trying to implement the A* algorithm in python but have hit a problem when trying to find the path of this map: X X X X X X X S = Start 0 0 0 X 0 0 0 E = End 0 S 0 X 0 E 0 X = Wall 0 0 0 X 0 0 0 0 0 0 0 0 0 0 I am using the Manhattan method. My implementat...
A* Algorithm does not find shortest path
I am trying to implement the A* algorithm in python but have hit a problem when trying to find the path of this map: X X X X X X X S = Start 0 0 0 X 0 0 0 E = End 0 S 0 X 0 E 0 X = Wall 0 0 0 X 0 0 0 0 0 0 0 0 0 0 I am using the Manhattan method. My implementation does find a path, but not the shortest one...
[ "You seem to be constructing a new open list for each node, which contains only that node's neighbors. This essentially makes your search a form of a depth-first search, while A* should be a best-first search.\nYou need to use one open list which will be updated with each node's neighbors as you visit that node. Th...
[ 8 ]
[]
[]
[ "a_star", "algorithm", "python" ]
stackoverflow_0007473441_a_star_algorithm_python.txt
Q: Celery tasks profiling As I can see in top utility celery procecess consume a lot of CPU time. So I want to profile it. I can do it manually on developer machine like so: python -m cProfile -o test-`date +%Y-%m-%d-%T`.prof ./manage.py celeryd -B But to have accurate timings I need to profile it on production mach...
Celery tasks profiling
As I can see in top utility celery procecess consume a lot of CPU time. So I want to profile it. I can do it manually on developer machine like so: python -m cProfile -o test-`date +%Y-%m-%d-%T`.prof ./manage.py celeryd -B But to have accurate timings I need to profile it on production machine. On that machine (Fedora...
[ "I think you're confusing two separate issues. You could be processing too many individual tasks or an individual task could be inefficient.\nYou may know which of these is the problem, but it's not clear from your question which it is.\nTo track how many tasks are being processed I suggest you look at celerymon. I...
[ 17 ]
[]
[]
[ "celery", "django_celery", "profiling", "python" ]
stackoverflow_0007473537_celery_django_celery_profiling_python.txt
Q: Python decorators: how to use parent class decorators in a child class Note: The accepted answer on the other question shows how to use the parent decorater. The accepted answer on this question shows moving the decorator to the module scope. EDIT: Using the previous example was a bad idea. Hopefully this is more...
Python decorators: how to use parent class decorators in a child class
Note: The accepted answer on the other question shows how to use the parent decorater. The accepted answer on this question shows moving the decorator to the module scope. EDIT: Using the previous example was a bad idea. Hopefully this is more clear: class A: def deco( func ): print repr(func) def ...
[ "The problem is that inheritance works for instance attribute lookup, not for class definitions. So when you try to decorate with A.deco in B, it can't find it. The solution is to move deco out to module scope, and because there is nothing magic about the name self, you can keep using it. You also need to explic...
[ 9, 2 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0007473096_decorator_python.txt
Q: Distributing python on Mac, Linux, and Windows using cx_freeze: can I generate all apps from one platform? I'm setting up a scripted build of a cross-platform python app (Python 3) and I'd like to create all the distributables from linux. Is that possible? A: Short answer: no I've been doing something similiar r...
Distributing python on Mac, Linux, and Windows using cx_freeze: can I generate all apps from one platform?
I'm setting up a scripted build of a cross-platform python app (Python 3) and I'd like to create all the distributables from linux. Is that possible?
[ "Short answer: no\nI've been doing something similiar recently (using cx_Freeze with Python 3). If you set up Python inside Wine, you can generate a Windows build, but I had to copy some DLLs in before it worked properly (cx_Freeze calls a Windows API function that's not implemented in Wine). I've not run into any ...
[ 6 ]
[]
[]
[ "cx_freeze", "python", "python_3.x" ]
stackoverflow_0007466375_cx_freeze_python_python_3.x.txt
Q: How to redirect data to a "getpass" like password input? I'm wring a python script for running some command. Some of those commands require user to input password, I did try to input data in their stdin, but it doesn't work, here is two simple python program represent the problem input.py import getpass print r...
How to redirect data to a "getpass" like password input?
I'm wring a python script for running some command. Some of those commands require user to input password, I did try to input data in their stdin, but it doesn't work, here is two simple python program represent the problem input.py import getpass print raw_input('text1:') print getpass.getpass('pass1:') print getpa...
[ "You need the pexpect module for such cases.\n\nPexpect is a Python module for\n spawning child applications and\n controlling them automatically.\n Pexpect can be used for automating\n interactive applications such as ssh,\n ftp, passwd, telnet, etc.\n\n", "There's definitely no need for two classes to make...
[ 2, 0 ]
[]
[]
[ "getpasswd", "passwords", "python", "stdin" ]
stackoverflow_0004826732_getpasswd_passwords_python_stdin.txt
Q: Failed to build PIL on Mac OS X 10.7 Lion I am tying to build PIL 1.1.7 on Mac OS X 10.7, I am getting this error: running build running build_py running build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -arch ppc -arch i386...
Failed to build PIL on Mac OS X 10.7 Lion
I am tying to build PIL 1.1.7 on Mac OS X 10.7, I am getting this error: running build running build_py running build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -arch ppc -arch i386 -g -O2 -DNDEBUG -g -O3 -DHAVE_LIBZ -I/System/L...
[ "You appear to be using a 32-bit-only Python possibly one downloaded from python.org. They are built with gcc-4.0 and for the i386 and ppc archs for compatibility with multiple OS X versions. When building a C extension module, Python's Distutils will attempt to use the same compiler version and options that Pyth...
[ 2 ]
[]
[]
[ "macos", "operating_system", "osx_lion", "python", "python_imaging_library" ]
stackoverflow_0007473896_macos_operating_system_osx_lion_python_python_imaging_library.txt
Q: How to get the socket FD from MySQLdb connection I use MySQLdb to fetch data from mysql and I need the connected socket to do someting else。 Is there some way to get it ? Thanks ! A: From the documentation: import MySQLdb db=MySQLdb.connect(passwd="moonpie",db="thangs") db is what you call your "connected sock...
How to get the socket FD from MySQLdb connection
I use MySQLdb to fetch data from mysql and I need the connected socket to do someting else。 Is there some way to get it ? Thanks !
[ "From the documentation:\nimport MySQLdb\ndb=MySQLdb.connect(passwd=\"moonpie\",db=\"thangs\")\n\ndb is what you call your \"connected socket\"\n" ]
[ 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0007467879_mysql_mysql_python_python.txt
Q: How do I achieve the effect of the === operator in Python? How do I achieve the effect of the === operator in Python? For example, I don't want False == 0 to be True. A: If you want to check that the value and type are the same use: x == y and type(x) == type(y) In Python, explicit type comparisons like this ar...
How do I achieve the effect of the === operator in Python?
How do I achieve the effect of the === operator in Python? For example, I don't want False == 0 to be True.
[ "If you want to check that the value and type are the same use:\nx == y and type(x) == type(y)\n\nIn Python, explicit type comparisons like this are usually avoided, but because booleans are a subclass of integers it's the only choice here.\n\nx is y compares identity—whether two names refer to the same object in m...
[ 40, 16, 2, 0 ]
[]
[]
[ "comparison", "identity_operator", "python" ]
stackoverflow_0006725559_comparison_identity_operator_python.txt
Q: Find value of input field in html doc using python I am trying to get input values from an HTML doc and want to parse out the values of hidden input fields. For example how can I parse out only the value from the snippet below, using python. <input type="hidden" autocomplete="off" id="post_form_id" name="post_...
Find value of input field in html doc using python
I am trying to get input values from an HTML doc and want to parse out the values of hidden input fields. For example how can I parse out only the value from the snippet below, using python. <input type="hidden" autocomplete="off" id="post_form_id" name="post_form_id" value="d619a1eb3becdc05a3ebea530396782f" /> ...
[ "You could use BeautifulSoup:\n>>> htmlstr = \"\"\" <input type=\"hidden\" autocomplete=\"off\" id=\"post_form_id\" name=\"post_form_id\" value=\"d619a1eb3becdc05a3ebea530396782f\" />\n... <input type=\"hidden\" name=\"fb_dtsg\" value=\"AQCYsohu\" autocomplete=\"off\" />\"\"\"\n>>> from BeautifulSoup import ...
[ 7, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007474146_python.txt
Q: Why is large integer division faster than slicing (numeric) strings, for accessing individual digits? I am doing a (typical) assignment of finding primes. I thought I'd be clever and, for large numbers, skip the division process with this trick: def div5(candidate): return str(candidate)[-1] == "5" Adding 5 t...
Why is large integer division faster than slicing (numeric) strings, for accessing individual digits?
I am doing a (typical) assignment of finding primes. I thought I'd be clever and, for large numbers, skip the division process with this trick: def div5(candidate): return str(candidate)[-1] == "5" Adding 5 to itself a few thousand times seems like a waste (I only need the last member), but I wanted to be sure. cr...
[ "% python -mtimeit \"str(2147483645)\"\n1000000 loops, best of 3: 0.321 usec per loop\n\n% python -mtimeit \"2147483645 % 5\"\n10000000 loops, best of 3: 0.0351 usec per loop\n\n% python -mtimeit \"'2147483645'[-1]\"\n10000000 loops, best of 3: 0.0349 usec per loop\n\nI'd say the bottleneck is converting to a strin...
[ 10, 5, 0 ]
[]
[]
[ "computer_science", "python" ]
stackoverflow_0007474628_computer_science_python.txt
Q: Application access its own version in mercurial repository I have application I want to print out (in "about" box) its revision/version from mercurial. Suppose it is revision deadbeef so it will know that. In old times in CVS could use something like $Revision$ to substitute automatically. What is best practice wi...
Application access its own version in mercurial repository
I have application I want to print out (in "about" box) its revision/version from mercurial. Suppose it is revision deadbeef so it will know that. In old times in CVS could use something like $Revision$ to substitute automatically. What is best practice with Mercurial for this?
[ "The best approach is probably to use precommit hook to replace a designated file with the output of hg log -r tip, possibly with a --template arg to format it in a particular way.\nUnfortunately, there's a bit of a chicken and egg problem. The revision is a checksum of the commited data, but the checksum is not a...
[ 5, 2, 1 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0006471412_mercurial_python.txt
Q: How to zip two lists of lists in Python? I have two lists of lists that have equivalent numbers of items. The two lists look like this: L1 = [[1, 2], [3, 4], [5, 6]] L2 =[[a, b], [c, d], [e, f]] I am looking to create one list that looks like this: Lmerge = [[1, 2, a, b], [3, 4, c, d], [5, 6, e, f]] I was attem...
How to zip two lists of lists in Python?
I have two lists of lists that have equivalent numbers of items. The two lists look like this: L1 = [[1, 2], [3, 4], [5, 6]] L2 =[[a, b], [c, d], [e, f]] I am looking to create one list that looks like this: Lmerge = [[1, 2, a, b], [3, 4, c, d], [5, 6, e, f]] I was attempting to use zip() something like this: for li...
[ ">>> map(list.__add__, L1, L2)\n[[1, 2, 'a', 'b'], [3, 4, 'c', 'd'], [5, 6, 'e', 'f']]\n\n", ">>> L1 = [[1, 2], [3, 4], [5, 6]]\n>>> L2 =[[\"a\", \"b\"], [\"c\", \"d\"], [\"e\", \"f\"]]\n>>> [x + y for x,y in zip(L1,L2)]\n[[1, 2, 'a', 'b'], [3, 4, 'c', 'd'], [5, 6, 'e', 'f']]\n\nOr,\n>>> [sum(x,[]) for x in zip(L...
[ 24, 13, 4, 1, 1 ]
[]
[]
[ "list", "merge", "nested", "python", "zip" ]
stackoverflow_0007474717_list_merge_nested_python_zip.txt
Q: Python: Reference to a class generically in an instance method? This question is similar, but it pertains to static methods: In Python, how do I reference a class generically in a static way, like PHP's "self" keyword? How do you refer to a class generically in an instance method? e.g. #!/usr/bin/python class a: ...
Python: Reference to a class generically in an instance method?
This question is similar, but it pertains to static methods: In Python, how do I reference a class generically in a static way, like PHP's "self" keyword? How do you refer to a class generically in an instance method? e.g. #!/usr/bin/python class a: b = 'c' def __init__(self): print(a.b) # <--- not gene...
[ "For old-style classes (if your code is Python 2.x code, and your class in not inheriting from object), use the __class__ property.\ndef __init__(self):\n print(self.__class__.b) # Python 2.x and old-style class\n\nFor new-style classes (if your code is Python 3 code), use type:\ndef __init__(self):\n print(s...
[ 2 ]
[]
[]
[ "programming_languages", "python", "syntax" ]
stackoverflow_0007474836_programming_languages_python_syntax.txt
Q: Filename tricks in python I have a folder containing my books that are in various formats (.pdf, .djvu, .dvi). and they all follow the format: [Name of the Book] - [Author].[an identifier indicating if it searchable or not].[filetype] I want to make a list of my books that is of the format (x,y,z,t) where x is the...
Filename tricks in python
I have a folder containing my books that are in various formats (.pdf, .djvu, .dvi). and they all follow the format: [Name of the Book] - [Author].[an identifier indicating if it searchable or not].[filetype] I want to make a list of my books that is of the format (x,y,z,t) where x is the name of the book, y is the aut...
[ "Strings are immutable, but that doesn't mean you can't create the tuple you need from the string.\nSomething like this should work:\ndef file_to_tuple(file):\n title_author, searchable, ext = file.rsplit('.', 2)\n title, author = title_author.rsplit(' - ', 1)\n return (title, author, searchable, ext)\n\nY...
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007474739_python.txt
Q: issues with python range() I have the following code: def steps(low, hi, n): rn = range(n) newrn = rn print rn #print 1 for x in rn[:]: print x newrn[x] = float(x)/n diff = hi - low print newrn print rn #print 2 for y in rn[:]: print y rn.insert(y, (newrn[y] * diff) + low) return rn for some ...
issues with python range()
I have the following code: def steps(low, hi, n): rn = range(n) newrn = rn print rn #print 1 for x in rn[:]: print x newrn[x] = float(x)/n diff = hi - low print newrn print rn #print 2 for y in rn[:]: print y rn.insert(y, (newrn[y] * diff) + low) return rn for some reason, my first print of rn ret...
[ "The problem is when you made this assignment: newrn = rn. Now both newrn and rn point to the same list, so when you modify one, you modify both.\nUse newrn = rn[:] instead.\n", "This is how variables work in python. In there:\nnewrn = rn\n\nYou're assigning a reference, not a value (which is good sometimes, sin...
[ 5, 3 ]
[]
[]
[ "list", "python", "range" ]
stackoverflow_0007475101_list_python_range.txt
Q: python: fast lightweight persistence I'm writing a python program that runs on a rather slow phone (as well as other platforms). Reading in data on the phone with pickle takes about 2 seconds and simplejson is significantly slower. The phone runs python 2.5.4 The data are in various lists and dictionaries in a gr...
python: fast lightweight persistence
I'm writing a python program that runs on a rather slow phone (as well as other platforms). Reading in data on the phone with pickle takes about 2 seconds and simplejson is significantly slower. The phone runs python 2.5.4 The data are in various lists and dictionaries in a group of classes. I can convert to and from...
[ "What about the marshal module? According to these benchmarks it is significantly faster than pickle. However, make very sure to read and understand the warnings at the top of the documentation.\nAlso, just to make sure: did you use cPickle? If not, try that — it's significantly faster than pickle.\nAlternatively, ...
[ 4 ]
[]
[]
[ "persistence", "python" ]
stackoverflow_0007475207_persistence_python.txt