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: Iterating through model fields - Django I'm trying to iterate through fields as they are written down within my model: currently I'm using this: def attrs(self): for attr, value in self.__dict__.iteritems(): yield attr, value but the order seems pretty much random :( Any ideas? A: The _meta attribute on ...
Iterating through model fields - Django
I'm trying to iterate through fields as they are written down within my model: currently I'm using this: def attrs(self): for attr, value in self.__dict__.iteritems(): yield attr, value but the order seems pretty much random :( Any ideas?
[ "The _meta attribute on Model classes and instances is a django.db.models.options.Options which provides access to all sorts of useful information about the Model in question.\nFor fields, it will give you them in the order they were created (i.e. the same order they were declared).\ndef attrs(self):\n for field...
[ 24 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003159614_django_django_models_python.txt
Q: Problem with scraping data using BeautifulSoup I have written the following trial code to retreive the title of legislative acts from the European parliament. import urllib2 from BeautifulSoup import BeautifulSoup search_url = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-%...
Problem with scraping data using BeautifulSoup
I have written the following trial code to retreive the title of legislative acts from the European parliament. import urllib2 from BeautifulSoup import BeautifulSoup search_url = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-%.4d&language=EN" for number in xrange(1,10): ...
[ "BeautifulSoup works in Unicode, so it's not responsible for that decoding error. More likely, your problem comes with the print statement -- your standard output seems to be in ascii (i.e., sys.stdout.encoding = 'ascii' or absent) and therefore you would indeed get such errors if trying to print a string containi...
[ 4, 1, 0 ]
[]
[]
[ "beautifulsoup", "loops", "python", "web_scraping" ]
stackoverflow_0003158433_beautifulsoup_loops_python_web_scraping.txt
Q: Parsing JSON with Python I'm getting an error while parsing a JSON response in Python. Ex: { "oneliners": [ "she\'s the one", "who opened the gates" ] } The JSON decoder coughs up on the invalid escape on the single quote. Typically do people apply a REGEX to remove the escape slash charac...
Parsing JSON with Python
I'm getting an error while parsing a JSON response in Python. Ex: { "oneliners": [ "she\'s the one", "who opened the gates" ] } The JSON decoder coughs up on the invalid escape on the single quote. Typically do people apply a REGEX to remove the escape slash character prior to decoding a respon...
[ "Pyparsing ships with a JSON parsing example (or you can get it online here):\n>>> text = r\"\"\"{\n... \"oneliners\": [\n... \"she\\'s the one\",\n... \"who opened the gates\"\n... ]\n... } \"\"\"\n>>> text\n'{ \\n \"oneliners\": [ \\n \"she\\\\\\'s the one\", \\...
[ 1, 1 ]
[ "import json\ns = \"\"\"{\n \"oneliners\": [\n \"she\\'s the one\",\n \"who opened the gates\"\n ]\n}\"\"\"\n\nprint \"%r\" % json.loads(s)\n\nThis appears to work just fine, in Python 2.6 and upwards anyway.\n" ]
[ -1 ]
[ "json", "python" ]
stackoverflow_0003155758_json_python.txt
Q: python open() how to change set files name/title If I open a file (image) in python with f = open('/path/to/file.jpg', 'r+') I have a function f.title() and I get the full path of the file back. How can I change the opened files name/repr/title to something else? A: You don't change filenames using open, that'...
python open() how to change set files name/title
If I open a file (image) in python with f = open('/path/to/file.jpg', 'r+') I have a function f.title() and I get the full path of the file back. How can I change the opened files name/repr/title to something else?
[ "You don't change filenames using open, that's for sure. You'll want to use os.rename.\nBut if you're trying to change the name the file has within your program but NOT the actual filename, why are you trying to do that/what would be the point in that? I guess you could detach the buffer from the file object and as...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003159652_python.txt
Q: How to determine if we are in the first week of the current month I am writing a little utility function in Python which returns a boolean, indicating whether today is in the first week of the month. This is what I have so far: import calendar import time y, m = time.localtime(time.time())[:2] data = calendar.mont...
How to determine if we are in the first week of the current month
I am writing a little utility function in Python which returns a boolean, indicating whether today is in the first week of the month. This is what I have so far: import calendar import time y, m = time.localtime(time.time())[:2] data = calendar.month(y, m) In [24]: type(temp) Out[24]: <type 'str'> In [25]: print temp...
[ "Here's a simple function which will tell you whether today is in the first week of the month:\nfrom datetime import date\n\ndef first_week():\n today = date.today()\n return today.weekday() - today.day >= -1\n\nThis is simpler than processing the output of a call into the calendar library; simply take the da...
[ 5, 3, 2 ]
[]
[]
[ "calendar", "python" ]
stackoverflow_0003159908_calendar_python.txt
Q: What kind of regex would I use to match this? I have several strings which look like the following: <some_text> TAG[<some_text>@11.22.33.44] <some_text> I want to get the ip_address and only the ip_address from this line. (For the sake of this example, assume that the ip address will always be in this format xx.x...
What kind of regex would I use to match this?
I have several strings which look like the following: <some_text> TAG[<some_text>@11.22.33.44] <some_text> I want to get the ip_address and only the ip_address from this line. (For the sake of this example, assume that the ip address will always be in this format xx.xx.xx.xx) Edit: I'm afraid I wasn't clear. The stri...
[ "Try re.search('(?<=@)\\d\\d\\.\\d\\d\\.\\d\\d\\.\\d\\d(?=\\])', line).\nIn fact, re.search('\\d\\d\\.\\d\\d\\.\\d\\d\\.\\d\\d', line) may get you what you need if the only occurrence of the xx.xx.xx.xx format in the strings being checked is in those IP address sections.\nEDIT: As stated in my comment, to find all ...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003152151_python_regex.txt
Q: python random.shuffle's randomness Following is from python website, about random.shuffle(x[, random]) Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). Note that for even rather small len(x), t...
python random.shuffle's randomness
Following is from python website, about random.shuffle(x[, random]) Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). Note that for even rather small len(x), the total number of permutations of x is ...
[ "You don't have anything to worry about. While under len(x) is under 2000, random.shuffle should work just fine.\n", "For a sequence of length 11, there are 11! or 39,916,800 (~ 225.3) possible permutations. For the Mersienne Twister (Python's random algorithm) the period is 219937 − 1. In other words, you'll b...
[ 6, 6 ]
[]
[]
[ "python", "random", "shuffle" ]
stackoverflow_0003160214_python_random_shuffle.txt
Q: Could you recommend a python library or source code for reading barcodes? I would like some help finding a python module that can identify a barcode within a scanned document. If anyone can help me at least come closer to finding an example of this I would be greatly appreciative. A: http://pypi.python.org/pypi/...
Could you recommend a python library or source code for reading barcodes?
I would like some help finding a python module that can identify a barcode within a scanned document. If anyone can help me at least come closer to finding an example of this I would be greatly appreciative.
[ "http://pypi.python.org/pypi/zbar\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003160320_python.txt
Q: header filtering using python i want to filter some headers in a wireshark capture (converted to text format) so i can analyse these set of headers.i need a python script to do this. any help would be appreciated A: You might want to look at dpkt. It's a Python library to simplify reading (or generating) netwo...
header filtering using python
i want to filter some headers in a wireshark capture (converted to text format) so i can analyse these set of headers.i need a python script to do this. any help would be appreciated
[ "You might want to look at dpkt. It's a Python library to simplify reading (or generating) network data. Just save your Wireshark data as a Pcap stream and it can easily be opened from within Python.\nI don't know exactly which headers you want or how you need them filtered and formatted, but here's an example of...
[ 1 ]
[]
[]
[ "python", "python_2.5" ]
stackoverflow_0003160307_python_python_2.5.txt
Q: running BLAST (bl2seq) without creating sequence files I have a script that performs BLAST queries (bl2seq) The script works like this: Get sequence a, sequence b write sequence a to filea write sequence b to fileb run command 'bl2seq -i filea -j fileb -n blastn' get output from STDOUT, parse repeat 20 million ti...
running BLAST (bl2seq) without creating sequence files
I have a script that performs BLAST queries (bl2seq) The script works like this: Get sequence a, sequence b write sequence a to filea write sequence b to fileb run command 'bl2seq -i filea -j fileb -n blastn' get output from STDOUT, parse repeat 20 million times The program bl2seq does not support piping. Is there ...
[ "Depending on what OS you're running on, you may be able to use something like bash's process substitution. I'm not sure how you'd set that up in Python, but you're basically using a named pipe (or named file descriptor). That won't work if bl2seq tries to seek within the files, but it should work if it just read...
[ 4, 1, 1, 1, 1 ]
[]
[]
[ "bioinformatics", "perl", "python", "shell", "unix" ]
stackoverflow_0002248016_bioinformatics_perl_python_shell_unix.txt
Q: Mutagen's OggFileType producing 'Type Error: NoneType' exception Ive just started using mutagen and have succefully used it with m4a, mp3, ape, afs, and flac. However Im having difficulty with the OggFileType class, when I try to create an instance of OggFileType Im presented with a "TypeError: 'NoneType' object i...
Mutagen's OggFileType producing 'Type Error: NoneType' exception
Ive just started using mutagen and have succefully used it with m4a, mp3, ape, afs, and flac. However Im having difficulty with the OggFileType class, when I try to create an instance of OggFileType Im presented with a "TypeError: 'NoneType' object is not callable" exception. Iv searched and searched for solutions but ...
[ "You're not supposed to use OggFileType directly. It's a base class for the other Ogg format classes -- OggVorbis, OggTheora, etc. Those all properly set _Info, _Tags, _Error appropriately. This is noted in the documentation for the ogg.py module:\n\nRead and write Ogg bitstreams and pages.\nThis module reads an...
[ 1 ]
[]
[]
[ "metadata", "mutagen", "ogg", "python" ]
stackoverflow_0003160471_metadata_mutagen_ogg_python.txt
Q: Python: Help with new line character I read in a text file that is tab delimited, i then have a list for each line, i then index out the first entry of each list, i then write this to a file. code below: import csv z = csv.reader(open('output.blast'), delimiter='\t') k = open('output.fasta', 'w') for row in z: ...
Python: Help with new line character
I read in a text file that is tab delimited, i then have a list for each line, i then index out the first entry of each list, i then write this to a file. code below: import csv z = csv.reader(open('output.blast'), delimiter='\t') k = open('output.fasta', 'w') for row in z: print row[1:12] for i in row[1:12]: ...
[ "It sounds like you just want it after each row, so put it at the end of the for loop that iterates over the rows:\nfor row in z:\n print row[1:12]\n for i in row[1:12]:\n k.write(i+'\\t')\n k.write('\\n')\n\n", "If you're writing it back out to a tab separated format why not use the csv package a...
[ 6, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003160508_python.txt
Q: How can I achieve layout similar to Google Image search in QT (PyQT)? I'm new to QT. I'm using PyQT for GUI development in my project. I want to achieve this layout in my application. This application searches images from an image database. Google image search layout is ideal for my purpose. I'm following the boo...
How can I achieve layout similar to Google Image search in QT (PyQT)?
I'm new to QT. I'm using PyQT for GUI development in my project. I want to achieve this layout in my application. This application searches images from an image database. Google image search layout is ideal for my purpose. I'm following the book "Rapid GUI Programming with Python and Qt" and I'm familiar with layouts...
[ "1/2.\nFor displaying the images and labels use a QListWidget with view mode set to QListView::IconMode. However, if you need to customize the display beyond what the QListWidget/QListWidgetItem api can provide you will need to create your own QAbstractListModel and use a standard QListView with it.\nMake sure and ...
[ 14, 3 ]
[]
[]
[ "pyqt", "python", "qt", "qt4" ]
stackoverflow_0003157766_pyqt_python_qt_qt4.txt
Q: None value returned The code below is used in a function: def print_query(x): h = open('/home/rv/data.txt', 'r') read = h.readlines() for line in read: return line When the value "line" is retunred it should print but instead i get the value "None" A: Try this: with open('/home/rv/data.txt',...
None value returned
The code below is used in a function: def print_query(x): h = open('/home/rv/data.txt', 'r') read = h.readlines() for line in read: return line When the value "line" is retunred it should print but instead i get the value "None"
[ "Try this:\nwith open('/home/rv/data.txt','r') as fh:\n for line in fh:\n print line\n\nIf you're on Python 2.5 you might need a from __future__ import with_statement on top.\nAlso: why do you return the line when you want to print it?\n", "You are not checking if the \"read\" variable actually contains...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003160863_python.txt
Q: Accessing outer class methods from an inner class I want a python class that has a nested class where the inner class can access the members of the outer class. I understand that normal nesting doesn't even require that the outer class has an instance. I have some code that seems to generate the results I desire a...
Accessing outer class methods from an inner class
I want a python class that has a nested class where the inner class can access the members of the outer class. I understand that normal nesting doesn't even require that the outer class has an instance. I have some code that seems to generate the results I desire and I want feedback on style and unforeseen complication...
[ "This doesn't look very good to me. classBdef is a class factory method. Usually (and seldomly) you would use these to create custom classes e.g. a class with a custom super class:\ndef class_factory(superclass):\n class CustomClass(superclass):\n def custom_method(self):\n pass\n return Cus...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003160809_python.txt
Q: Running Python scripts on a server? How would I run a python script on my site? I wrote a script that takes values (the values should come from a form that the end user fills out) and then returns a string. What would I need to add to the submit form to make the script run with the values? Is this possible or sho...
Running Python scripts on a server?
How would I run a python script on my site? I wrote a script that takes values (the values should come from a form that the end user fills out) and then returns a string. What would I need to add to the submit form to make the script run with the values? Is this possible or should I be using PHP? (The script involved ...
[ "Your site needs to allow python cgi scripting. \nSee this for more info, especially this.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003160906_python.txt
Q: String or list substitution in Python How would I go about taking a string: ("h1", "h2", "h3, "h4") And substituting these values with numbers 1, 2, 3, 4? Correspondingly, how I would I preform the same operation but on a list instead? A: to_replace = ["h1","h2","h3","h4"] replaced = [ int(s.replace("h","")) ...
String or list substitution in Python
How would I go about taking a string: ("h1", "h2", "h3, "h4") And substituting these values with numbers 1, 2, 3, 4? Correspondingly, how I would I preform the same operation but on a list instead?
[ " to_replace = [\"h1\",\"h2\",\"h3\",\"h4\"]\n replaced = [ int(s.replace(\"h\",\"\")) for s in to_replace ]\n\nIf this is what you want.\nIt's not exactly clear; I'm assuming that your input is not literally a string \"(\\\"h1\\\", \\\"h2\\\", \\\"h3\\\", \\\"h4\\\")\", but a list of strings.\nAnd I'm not sure wha...
[ 5, 3 ]
[]
[]
[ "list", "python", "string", "substitution" ]
stackoverflow_0003160791_list_python_string_substitution.txt
Q: Python threads in embedded Python: How? While experimenting with Python's (python.org) C API, I found myself wondering how to properly spawn threads via Python's threading package when Python itself is embedded in a C program. Functions PyEval_EvalCode and kin appear to terminate threads it "owns" as soon as the C...
Python threads in embedded Python: How?
While experimenting with Python's (python.org) C API, I found myself wondering how to properly spawn threads via Python's threading package when Python itself is embedded in a C program. Functions PyEval_EvalCode and kin appear to terminate threads it "owns" as soon as the C function finishes evaluating a block of Pyth...
[ "Have you included the pthread library? Python will fall back to dummy threads if it detects that real threads are not available\n" ]
[ 2 ]
[]
[]
[ "c", "embed", "multithreading", "python" ]
stackoverflow_0003159256_c_embed_multithreading_python.txt
Q: adding a trailing comma to a print command makes threads executions "serialized" without dumping tones of code here is the symptom having a threads which all run various methods of the same type of object. within the methods i have a print line which reads: print self.args, self.foo everything works just fine. How...
adding a trailing comma to a print command makes threads executions "serialized"
without dumping tones of code here is the symptom having a threads which all run various methods of the same type of object. within the methods i have a print line which reads: print self.args, self.foo everything works just fine. However, if i turn that line into: # remain in the same line print self.args, self.foo, ...
[ "Try flushing stdout after the print\nsys.stdout.flush()\n\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003161412_multithreading_python.txt
Q: Beginner needing experienced advice for important choices I've never written a program, (although I've dabbled in Access and am familiar with OOP concepts), and have decided to undertake the challenge of writing myself a database program for home use. (It'll keep track of our finances and be customized to our way...
Beginner needing experienced advice for important choices
I've never written a program, (although I've dabbled in Access and am familiar with OOP concepts), and have decided to undertake the challenge of writing myself a database program for home use. (It'll keep track of our finances and be customized to our way of doing things.) I've pretty much decided to use Python and ...
[ "Tkinter is a *great** UI framework for beginners. I highly recommend using that, if it seems powerful enough to fill your needs.\nSince it sounds like you're pretty inexperienced as far as programming goes, here's what I recommend:\n1) Learn how to do basic IO, and especially learn Python's string formatting. It's...
[ 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003159878_python.txt
Q: How to model this in django (inherited model, where each inherited model has a unique method) How to model this in django: 1) have a base network of manufacturers 2) under each network their might be several distributors 3) a user of the system can access items through the distributor 4) if a user access the item ...
How to model this in django (inherited model, where each inherited model has a unique method)
How to model this in django: 1) have a base network of manufacturers 2) under each network their might be several distributors 3) a user of the system can access items through the distributor 4) if a user access the item through the distributor we want that item to be translated where each manufacturer will have their ...
[ "If dist is an instance of Distributor, then you can do dist.man to get the Manufacturer instance. Due to the way multi-table inheritance works in Django, you'll need to access the OneToOneField that exists on the Manufacturer to the subclass instance. The problem lies in figuring out which subclass instance exists...
[ 0 ]
[]
[]
[ "django", "inheritance", "model", "proxy", "python" ]
stackoverflow_0003160762_django_inheritance_model_proxy_python.txt
Q: Retain formatting Im using a function to return a text file that is tab delimited and read in, the format of the text file is: 1_0 NP_250397 100.00 140 0 0 1 140 1 140 6e-54 198 1_0 NP_250378 60.00 140 0 0 1 140 1 140 6e...
Retain formatting
Im using a function to return a text file that is tab delimited and read in, the format of the text file is: 1_0 NP_250397 100.00 140 0 0 1 140 1 140 6e-54 198 1_0 NP_250378 60.00 140 0 0 1 140 1 140 6e-54 198 1_0 NP_2...
[ "If you want print_file to actually print the file as the function name suggests\ndef print_file(x):\n with open('/home/me/data/db/test.blast', 'r') as h:\n for line in h:\n print line\n\nIf you want to return the contents of the file as a single string\ndef print_file(x):\n with open('/home...
[ 2, 0, 0 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0003161413_formatting_python.txt
Q: How do i print the script line number in IronPython? I am running an IronPython script inside a c# application, i am catching exceptions within the script and i wish to find out the script line at which the exception is thrown. This has to be done while the script is running ie. i do not wish the script to termina...
How do i print the script line number in IronPython?
I am running an IronPython script inside a c# application, i am catching exceptions within the script and i wish to find out the script line at which the exception is thrown. This has to be done while the script is running ie. i do not wish the script to terminate in order to print the exception. Is this even possible?...
[ "If inspect is working as expected under IronPython (not really sure) this could do the trick:\nimport inspect\n\nfilename, linenum, funcname = inspect.getframeinfo(inspect.currentframe())[:3]\nprint linenum\n\nEdit: alternate solution:\nimport sys\n\nframe = sys._getframe()\nprint frame.f_lineno\n\n", "Haven't t...
[ 1, 0 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0003161177_ironpython_python.txt
Q: What am I doing wrong? Python object instantiation keeping data from previous instantiation? Can someone point out to me what I'm doing wrong or where my understanding is wrong? To me, it seems like the code below which instantiates two objects should have separate data for each instantiation. class Node: def ...
What am I doing wrong? Python object instantiation keeping data from previous instantiation?
Can someone point out to me what I'm doing wrong or where my understanding is wrong? To me, it seems like the code below which instantiates two objects should have separate data for each instantiation. class Node: def __init__(self, data = []): self.data = data def main(): a = Node() a.data.append(...
[ "You can't use an mutable object as a default value. All objects will share the same mutable object.\nDo this.\nclass Node:\n def __init__(self, data = None):\n self.data = data if data is not None else []\n\nWhen you create the class definition, it creates the [] list object. Every time you create an i...
[ 16, 6, 3 ]
[]
[]
[ "instantiation", "python" ]
stackoverflow_0003161827_instantiation_python.txt
Q: How can I access another server with Python? I have two servers, and one updates with a DNSBL of 100k domains every 15 minutes. I want to process these domains through a Python script with information from Safebrowsing, Siteadvisor, and other services. Unfortunately, the server with the DNSBL is rather slow. Is th...
How can I access another server with Python?
I have two servers, and one updates with a DNSBL of 100k domains every 15 minutes. I want to process these domains through a Python script with information from Safebrowsing, Siteadvisor, and other services. Unfortunately, the server with the DNSBL is rather slow. Is there a way I can transfer the files over from the o...
[ "If it's just files (and directories) you are transferring, why not just use rsync over ssh (in a bash script perhaps). A proven, mature method.\nOr you could mount the remote filesystem (over ssh) into your own filesystem using sshfs (fuse) and then use something like pyrobocopy (implementing a basic version of rs...
[ 0, 0 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0003161884_python_ssh.txt
Q: How can I fix this bug? BadKeyError: Name must be string type Hey everyone. I am using Appengine/Python and I haven't been able to fix a BadKeyError bug for the last 5 hours. I'm wondering if someone can help me figure it out. The part of the app that is causing the bug is a controller that processes votes done by...
How can I fix this bug? BadKeyError: Name must be string type
Hey everyone. I am using Appengine/Python and I haven't been able to fix a BadKeyError bug for the last 5 hours. I'm wondering if someone can help me figure it out. The part of the app that is causing the bug is a controller that processes votes done by users. Actor_id is the key of the user and object_id is the key of...
[ "object is always a poor choice of name and could well be causing the exception.\n", "The constructor for PolyModel is like so: class PolyModel(parent=None, key_name=None, **kwds): So you're passing in the headline object as the key_name, which looks like it must be a string from the stacktrace.\nFrom reading th...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003161919_google_app_engine_python.txt
Q: PyQt4 dropdownlist with actions I want to create a drop down list in PyQt4, that executes an action when an element is selected. Also, some options may not be available at some time. They should still be in the list, but greyed out. I tried attaching a menu to a QToolButton, but I can not even see the menu. How is...
PyQt4 dropdownlist with actions
I want to create a drop down list in PyQt4, that executes an action when an element is selected. Also, some options may not be available at some time. They should still be in the list, but greyed out. I tried attaching a menu to a QToolButton, but I can not even see the menu. How is it done? Thanks! Nathan
[ "Use a popup. You can trigger a popup anywhere, using the QMenu.exec_ method and passing the point at which you want the menu to appear.\nI created a button that remembered where it was clicked, and connected that to the method to create and display the popup.\nclass MemoryButton(QPushButton):\n def __init__(se...
[ 2, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0003161519_pyqt4_python.txt
Q: Python encoding function can't be decoded I wrote this python code in an attempt to convert objects to a string of ones and zeros, but the decoding fails because the data can't be unpickled. This is the code: def encode(obj): 'convert an object to ones and zeros' def tobin(str): rstr = '' f...
Python encoding function can't be decoded
I wrote this python code in an attempt to convert objects to a string of ones and zeros, but the decoding fails because the data can't be unpickled. This is the code: def encode(obj): 'convert an object to ones and zeros' def tobin(str): rstr = '' for f in str: if f == "0": rstr += "...
[ "I think there are several problems, but one is that when you decode, you need to iterate through groups of 4 characters in you unbin() function, not single characters like you are currently doing.\n", "I think I have a better solution for you. This should be even more secure, since it \"encrypts\" everything, no...
[ 2, 1, 0, 0 ]
[]
[]
[ "decoding", "encoding", "pickle", "python" ]
stackoverflow_0003160919_decoding_encoding_pickle_python.txt
Q: Python's subprocess module returning different results from Unix shell I'm trying to get a list of the CSV files in a directory with python. This is really easy within unix: ls -l *.csv And, predictably, I get a list of the files that end with .csv in my directory. However, when I attempt the Python equivalent us...
Python's subprocess module returning different results from Unix shell
I'm trying to get a list of the CSV files in a directory with python. This is really easy within unix: ls -l *.csv And, predictably, I get a list of the files that end with .csv in my directory. However, when I attempt the Python equivalent using the Subprocess module: >>> import subprocess as sp >>> sp.Popen(["ls", "...
[ "If you want it to behave as it does at the shell, you need to pass shell=True (your mileage may vary here, depending on your system and shell). In your case the problem is that when you do ls -l *.csv, the shell is evaluating what * means, not ls. (ls is merely formatting your results, but the shell has done the ...
[ 4, 4, 1, 1 ]
[]
[]
[ "python", "unix" ]
stackoverflow_0003162153_python_unix.txt
Q: Add headers to a file I have a file containing data like below: 88_NPDJ 565 789 3434 54454 98HGJDN 945 453 3453 23423 ... ... ... whats the best way to add headers to the file? After data has been entered into the file. The data is tab delimited. A: Best way to get the effect of altering a f...
Add headers to a file
I have a file containing data like below: 88_NPDJ 565 789 3434 54454 98HGJDN 945 453 3453 23423 ... ... ... whats the best way to add headers to the file? After data has been entered into the file. The data is tab delimited.
[ "Best way to get the effect of altering a file in place is with fileinput:\nimport fileinput\n\nheaders = 'a b c d e'.split()\nfor line in fileinput.input(['thefile.blah'], inplace=True):\n if fileinput.isfirstline():\n print '\\t'.join(headers)\n print line,\n\n", "Which kind of headers? Something l...
[ 9, 1, 0 ]
[]
[]
[ "file_io", "header", "python" ]
stackoverflow_0003162314_file_io_header_python.txt
Q: Python binary file reading problem I'm trying to read a binary file (which represents a matrix in Matlab) in Python. But I am having trouble reading the file and converting the bytes to the correct values. The binary file consists of a sequence of 4-byte numbers. The first two numbers are the number of rows and co...
Python binary file reading problem
I'm trying to read a binary file (which represents a matrix in Matlab) in Python. But I am having trouble reading the file and converting the bytes to the correct values. The binary file consists of a sequence of 4-byte numbers. The first two numbers are the number of rows and columns respectively. My friend gave me a ...
[ "rows = f.read(4)\ncols = f.read(4)\n\nboth names are now bound to 4-byte strings. To turn them into integers instead,\nimport struct\n\nrowsandcols = f.read(8)\nrows, cols = struct.unpack('=ii', rowsandcols)\n\nSee the docs for struct.unpack.\n", "I looked a bit more in your problem, since I had never used stru...
[ 7, 2 ]
[]
[]
[ "binary", "file_io", "matlab", "python" ]
stackoverflow_0003162191_binary_file_io_matlab_python.txt
Q: Python: Looping over One Dictionary and Creating Key/Value Pairs in a New Dictionary if Conditions Are Met I want to compare the values of one dictionary to the values of a second dictionary. If the values meet certain criteria, I want to create a third dictionary with keys and value pairs that will vary dependin...
Python: Looping over One Dictionary and Creating Key/Value Pairs in a New Dictionary if Conditions Are Met
I want to compare the values of one dictionary to the values of a second dictionary. If the values meet certain criteria, I want to create a third dictionary with keys and value pairs that will vary depending on the matches. Here is a contrived example that shows my problem. edit: sorry about all the returns, but stac...
[ "Simplest fix (and answer to your first question): key is not properly defined in your latest snippets, the assignment must be inside the for though outside the ifs:\nfor key in school_districts:\n jobs_in_school_district[key] = {}\n if ... etc etc ...\n\n if ... other etc etc ...\n\nSimplest may actually ...
[ 3, 0, 0 ]
[]
[]
[ "conditional", "dictionary", "iteration", "key", "python" ]
stackoverflow_0003162166_conditional_dictionary_iteration_key_python.txt
Q: Flicker-free drawable ScrolledWindow I'm trying to build a ScrolledWindow that you can draw on using the mouse, and it's working too, but I'm getting a nasty flicker when the user is drawing on the window while the scrollbars aren't in the "home" position.. To reproduce, run the attached program, scroll a bit down...
Flicker-free drawable ScrolledWindow
I'm trying to build a ScrolledWindow that you can draw on using the mouse, and it's working too, but I'm getting a nasty flicker when the user is drawing on the window while the scrollbars aren't in the "home" position.. To reproduce, run the attached program, scroll a bit down (or to the right) and "doodle" a bit by k...
[ "From Robin Dunn himself:\n\nFirst, a Refresh() by default will\n erase the background before sending\n the paint event (although setting the\n BG style or catching the erase event\n would have taken care of that.) The\n second and probably most visible\n problem in this case is that in your\n on_motion han...
[ 5, 2 ]
[]
[]
[ "flicker", "python", "scrolledwindow", "wxpython" ]
stackoverflow_0003147613_flicker_python_scrolledwindow_wxpython.txt
Q: Displaying and refreshing my picture every 5 seconds Ok, I've got the GUI in tkinter working, and I'm trying to grab and image every 5 seconds and display it in a Label named Picturelabel. from Tkinter import * from PIL import ImageGrab import cStringIO, base64, time, threading class PictureThread(threading.Threa...
Displaying and refreshing my picture every 5 seconds
Ok, I've got the GUI in tkinter working, and I'm trying to grab and image every 5 seconds and display it in a Label named Picturelabel. from Tkinter import * from PIL import ImageGrab import cStringIO, base64, time, threading class PictureThread(threading.Thread): def run(self): print "test" box = ...
[ "The problem is that you return the new image from the PictureThread().run() in the method, but you never save it.\nHow about:\nfrom Tkinter import *\nfrom PIL import ImageGrab\nimport cStringIO, base64, time, threading\n\nbox = (0,0,500,500) #x,x,width,height\nMyImage = ImageGrab.grab(box)\n\nfp = cStringIO.String...
[ 0, 0 ]
[]
[]
[ "multithreading", "python", "tkinter" ]
stackoverflow_0003162564_multithreading_python_tkinter.txt
Q: Python "List" object is not callable I'm writing a program that looks through CSVs in a directory and appends the contents of each CSV to a list. Here's a snippet of the offending code: import glob import re c = glob.glob("*.csv") print c archive = [] for element in c: look = open(element, "r").read() o...
Python "List" object is not callable
I'm writing a program that looks through CSVs in a directory and appends the contents of each CSV to a list. Here's a snippet of the offending code: import glob import re c = glob.glob("*.csv") print c archive = [] for element in c: look = open(element, "r").read() open = re.split("\n+", look) for n in ...
[ "I think it's because you redefine open as a list and call it in the next loop iteration.\nJust give the list another name.\nNote that strings have a split() method for when you don't need a regex.\n", "The fact that open is a builtin function is irrelevant. It could have been a function defined in the same modul...
[ 10, 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003162588_python.txt
Q: What does [[]]*2 do in python? A = [[]]*2 A[0].append("a") A[1].append("b") B = [[], []] B[0].append("a") B[1].append("b") print "A: "+ str(A) print "B: "+ str(B) Yields: A: [['a', 'b'], ['a', 'b']] B: [['a'], ['b']] One would expect that the A list would be the same as the B list, this is not the case, both...
What does [[]]*2 do in python?
A = [[]]*2 A[0].append("a") A[1].append("b") B = [[], []] B[0].append("a") B[1].append("b") print "A: "+ str(A) print "B: "+ str(B) Yields: A: [['a', 'b'], ['a', 'b']] B: [['a'], ['b']] One would expect that the A list would be the same as the B list, this is not the case, both append statements were applied to A...
[ "A = [[]]*2 creates a list with 2 identical elements: [[],[]].\nThe elements are the same exact list.\nSo\nA[0].append(\"a\")\nA[1].append(\"b\")\n\nappends both \"a\" and \"b\" to the same list.\nB = [[], []] creates a list with 2 distinct elements. \nIn [220]: A=[[]]*2\n\nIn [221]: A\nOut[221]: [[], []]\n\nThis s...
[ 17 ]
[]
[]
[ "python" ]
stackoverflow_0003162698_python.txt
Q: Scraping Ajax - Using python I'm trying to scrap a page in youtube with python which has lot of ajax in it I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated. A: Youtube (and everything else ...
Scraping Ajax - Using python
I'm trying to scrap a page in youtube with python which has lot of ajax in it I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated.
[ "Youtube (and everything else Google makes) have EXTENSIVE APIs already in place for giving you access to just about any and all data you could possibly want.\nTake a look at The Youtube Data API for more information.\nI use urllib to make the API requests and ElementTree to parse the returned XML.\n", "Main prob...
[ 6, 6, 2, 0, 0 ]
[]
[]
[ "ajax", "python", "screen_scraping" ]
stackoverflow_0001281075_ajax_python_screen_scraping.txt
Q: Python regex confused by brackets ([])? Is python confused, or is the programmer? I've got a lot of lines of this: some_dict[0x2a] = blah some_dict[0xab] = blah, blah What I'd like to do is to convert the hex codes into all uppercase to look like this: some_dict[0x2A] = blah some_dict[0xAB] = blah, blah So I dec...
Python regex confused by brackets ([])?
Is python confused, or is the programmer? I've got a lot of lines of this: some_dict[0x2a] = blah some_dict[0xab] = blah, blah What I'd like to do is to convert the hex codes into all uppercase to look like this: some_dict[0x2A] = blah some_dict[0xAB] = blah, blah So I decided to call in the regular expressions. Nor...
[ "re.match matches from the start of the string. Use re.search instead to \"match the first occurrence anywhere in the string\". The key bit about this in the docs is here.\n", "I don't think you need the comma within the brackets. i.e.:\nfound = re.match(\"0x([0-9,a-f]{2})\", line)\n\ntells python to look for c...
[ 7, 4, 4, 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003160590_python_regex.txt
Q: Can someone show me the "hello world" of Paypal IPN? I'd like to set up a PayPal donation box, and use their IPN protocol to monitor when donations come in. The documentation is enormously complex and full of features I'm not interested in. Is there a short snippet -- ideally in Python -- that shows how to, say, c...
Can someone show me the "hello world" of Paypal IPN?
I'd like to set up a PayPal donation box, and use their IPN protocol to monitor when donations come in. The documentation is enormously complex and full of features I'm not interested in. Is there a short snippet -- ideally in Python -- that shows how to, say, connect to Paypal, loop forever, and print "Just got $5" ev...
[ "Actually, with IPNs it's the other way around. PayPal posts a notification to your server via HTTP POST when a payment is made. You therefore need to make a CGI script or server that receives these posts, checks their validity, and processes them.\nProbably the easiest sample code to look at for setting up an IPN ...
[ 4 ]
[]
[]
[ "paypal", "paypal_ipn", "python" ]
stackoverflow_0003162758_paypal_paypal_ipn_python.txt
Q: Python search and replace in binary file I am trying to search and replace some of the text (eg 'Smith, John') in this pdf form file (header.fdf, I presumed this is treated as binary file): '%FDF-1.2\n%\xe2\xe3\xcf\xd3\n1 0 obj\n<</FDF<</Fields[<</V(M)/T(PatientSexLabel)>><</V(24-09-1956 53)/T(PatientDateOfBirth)...
Python search and replace in binary file
I am trying to search and replace some of the text (eg 'Smith, John') in this pdf form file (header.fdf, I presumed this is treated as binary file): '%FDF-1.2\n%\xe2\xe3\xcf\xd3\n1 0 obj\n<</FDF<</Fields[<</V(M)/T(PatientSexLabel)>><</V(24-09-1956 53)/T(PatientDateOfBirth)>><</V(Fisher)/T(PatientLastNameLabel)>><</V(C...
[ "f=open(\"header.fdf\",\"rb\")\ns=str(f.read())\nf.close()\ns=s.replace(b'PatientName',name)\n\nor\nf=open(\"header.fdf\",\"rb\")\ns=f.read()\nf.close()\ns=s.replace(b'PatientName',bytes(name))\n\nprobably the latter, as I don't think you are going to be able to use unicode names with this type of substitution anyw...
[ 32, 11 ]
[]
[]
[ "binary_data", "python", "replace" ]
stackoverflow_0003162614_binary_data_python_replace.txt
Q: Python2.6 XML reading I want to migrate my system from Active Python 2.4 to Python 2.6.5. However I face some problem in parsing XML files. The I/O is very slow. My sample xml file <config><dicts><dictName>EnvDict</dictName><dictElems><key>AppServerIP</key> <value>localhost</value><key>DBServerIP</key> <value>l...
Python2.6 XML reading
I want to migrate my system from Active Python 2.4 to Python 2.6.5. However I face some problem in parsing XML files. The I/O is very slow. My sample xml file <config><dicts><dictName>EnvDict</dictName><dictElems><key>AppServerIP</key> <value>localhost</value><key>DBServerIP</key> <value>localhost</value><key>DBServ...
[ "I'm very perplexed...:\n$ py26 -mtimeit -s'import rex' 'rex.t()'\n10000 loops, best of 3: 103 usec per loop\n\n100 microseconds seems more reasonable than 25 seconds to read in, and parse, such a small XML file as you're giving (even on the old laptop I'm using for the timing!) -- but how to explain the fact that ...
[ 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003163133_python_xml.txt
Q: Better Way to Write This List Comprehension? I'm parsing a string that doesn't have a delimiter but does have specific indexes where fields start and stop. Here's my list comprehension to generate a list from the string: field_breaks = [(0,2), (2,10), (10,13), (13, 21), (21, 32), (32, 43), (43, 51), (51, 54), (54,...
Better Way to Write This List Comprehension?
I'm parsing a string that doesn't have a delimiter but does have specific indexes where fields start and stop. Here's my list comprehension to generate a list from the string: field_breaks = [(0,2), (2,10), (10,13), (13, 21), (21, 32), (32, 43), (43, 51), (51, 54), (54, 55), (55, 57), (57, 61), (61, 63), (63, 113), (11...
[ "You can cut your field_breaks list in half by doing:\nfield_breaks = [0, 2, 10, 13, 21, 32, 43, ..., 250, 300]\ns = ...\ndata = [s[x[0]:x[1]].strip() for x in zip(field_breaks[:-1], field_breaks[1:])]\n\n", "You can use tuple unpacking for cleaner code:\ndata = [s[a:b].strip() for a,b in field_breaks]\n\n", "T...
[ 7, 7, 3, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003163391_list_comprehension_python.txt
Q: Can't build readline when trying to install Python 2.6.5 in Debian 4.3.2 I am trying to install Python 2.6.5 on my web server running Debian 4.3.2.1-1. I unpacked the tarball, ran "./configure --prefix /usr/", then ran "make". I saw this message. Failed to find the necessary bits to build these modules: _bsddb ...
Can't build readline when trying to install Python 2.6.5 in Debian 4.3.2
I am trying to install Python 2.6.5 on my web server running Debian 4.3.2.1-1. I unpacked the tarball, ran "./configure --prefix /usr/", then ran "make". I saw this message. Failed to find the necessary bits to build these modules: _bsddb _hashlib _ssl _tkinter bsddb185 ...
[ "You'll probably need to install the libreadline-dev virtual package for Debian 4 (etch) to be able to build python with libreadline support. Check the package dependencies for the Debian python2.6 source package here. It's for a newer version of Debian so not all of the same versions will be available in etch bu...
[ 7 ]
[]
[]
[ "debian", "linux", "python", "readline" ]
stackoverflow_0003163573_debian_linux_python_readline.txt
Q: Storing Application Sensitive Data I am implementing a python application that will connect to our different servers and computers. They all have different logins and passwords. I want to store all these information in the app directly and ask for one master login/password only. How can I store all these sensitive...
Storing Application Sensitive Data
I am implementing a python application that will connect to our different servers and computers. They all have different logins and passwords. I want to store all these information in the app directly and ask for one master login/password only. How can I store all these sensitive data in the application so that someone...
[ "This sounds like a very bad idea. You could encrypt the logins and passwords, but anyone who has access to the master password will then have access to all of the individual logins. That means you can guarantee the individual logins won't remain a secret for long and if they do leak out you'll have to change them ...
[ 1 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0003163903_encryption_python.txt
Q: python application development resources (as in books/online guides) can anyone recommend a resource (book,tutorial,etc.) that focuses on application development in python? something similar to Practical Django Projects, but for stand alone applications instead of web apps (for now). A: Assuming you want a GUI ...
python application development resources (as in books/online guides)
can anyone recommend a resource (book,tutorial,etc.) that focuses on application development in python? something similar to Practical Django Projects, but for stand alone applications instead of web apps (for now).
[ "Assuming you want a GUI on your standalone application, you could try Rapid GUI Programming with Python and Qt. There are other Python reference books of course, but I don't know of any that focus solely on application development without focusing on a particular toolkit (web or otherwise).\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003163814_python.txt
Q: How can I manage these subprocesses efficiently? I've got a script that downloads and then converts videos. I'm trying to do all of the downloads at once(a lot of wgets) and then when they're done, convert them. Right now I have to wait while each file downloads individually and then convert when done. I want all ...
How can I manage these subprocesses efficiently?
I've got a script that downloads and then converts videos. I'm trying to do all of the downloads at once(a lot of wgets) and then when they're done, convert them. Right now I have to wait while each file downloads individually and then convert when done. I want all the download requests to run concurrently. Here's the ...
[ "you could use\nprocess_list = [] \nfor id in ids:\n process_list.append(subprocess.Popen(cmd, shell=True))\nfor process in process_list:\n process.wait()\n\nas such you will wait just at the end of simultaneous jobs.\n", "You could use xargs as a simple solution, if that is availabe for your platform. ...
[ 1, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003164086_python_subprocess.txt
Q: Thread safety in Python (Question how it works) I've read through the documentation on threading for python and as I've pereceived it the following should hold true: You can access (read) any PoD or python specific object (such as an array) without causing failure in a multi-threaded program trying the same thing ...
Thread safety in Python (Question how it works)
I've read through the documentation on threading for python and as I've pereceived it the following should hold true: You can access (read) any PoD or python specific object (such as an array) without causing failure in a multi-threaded program trying the same thing at the same time, but you can not change them and acc...
[ "Locals are thread-safe as they are not shared between threads. All constants (variables you never write to from any thread) are thread-safe. If that's all you have, then yes, that's fine. Ensure the class members you are talking about are really not written from any other thread.\nCheck there are no underlying sha...
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003164241_multithreading_python.txt
Q: How to handle post request in python how can I handle post request in python script? Somewhere I want to send it from ajax to the python script with given params. What's correct way to handle that data in python? A: you probably use a cgi and you can handle it with form = cgi.FieldStorage() as described into ht...
How to handle post request in python
how can I handle post request in python script? Somewhere I want to send it from ajax to the python script with given params. What's correct way to handle that data in python?
[ "you probably use a cgi and you can handle it with form = cgi.FieldStorage() as described into http://docs.python.org/library/cgi.html\n" ]
[ 1 ]
[]
[]
[ "post", "python", "request" ]
stackoverflow_0003164503_post_python_request.txt
Q: How to bypass url mapping in django & make url directly point to file I'm new to web development using python. I've good amount of experience in building dynamic websites using PHP. Also, I've never used MVC on PHP. For the first time I'm using MVC (or MTV to be more correct). I'm following One thing different fr...
How to bypass url mapping in django & make url directly point to file
I'm new to web development using python. I've good amount of experience in building dynamic websites using PHP. Also, I've never used MVC on PHP. For the first time I'm using MVC (or MTV to be more correct). I'm following One thing different from PHP world is that. URLs doesn't point to files but to functions. This si...
[ "You can configure your HTTP server to serve your files directly.\nYou can read about static files in Django here:\nhttp://docs.djangoproject.com/en/dev/howto/static-files/\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003164699_django_python.txt
Q: How to properly use PyDev with two different Python versions with scripts that are recalling other python scripts? The story began with a very strange error while I was running my script from PyDev. Running the same script from outside will not encounter the same problem. Fatal Python error: Py_Initialize: can't ...
How to properly use PyDev with two different Python versions with scripts that are recalling other python scripts?
The story began with a very strange error while I was running my script from PyDev. Running the same script from outside will not encounter the same problem. Fatal Python error: Py_Initialize: can't initialize sys standard streams File "C:\Python26\lib\encodings\__init__.py", line 123 raise CodecRegistryError,\ ...
[ "I found a solution that seams acceptable specially because it will not interfere with running the scripts on other systems, just to run python -E second.py - this will force Python to ignore PYTHON* environment variables.\n", "I may not be understanding this quite right, but I think you're invoking a script from...
[ 2, 0, 0 ]
[]
[]
[ "environment_variables", "python", "windows" ]
stackoverflow_0003133690_environment_variables_python_windows.txt
Q: Why the id(string) does not return the address of string import ctypes a = 'abc' b = ctypes.string_at(id(a), 3) c = ctypes.string_at(id(a) + 20, 3) I expect the result of b to be 'abc', but it is not; and the result of c is 'abc'. I don't know why. Anyone can explain me? A: In Python, a str is an object, so th...
Why the id(string) does not return the address of string
import ctypes a = 'abc' b = ctypes.string_at(id(a), 3) c = ctypes.string_at(id(a) + 20, 3) I expect the result of b to be 'abc', but it is not; and the result of c is 'abc'. I don't know why. Anyone can explain me?
[ "In Python, a str is an object, so there is no guarantee about what it looks like in memory. Probably, it contains some more information, like the length of the string. In your case, the size of this \"metadata\" is apparently 20 bytes.\nPossibly, the object itself does not even contain the actual string, but rathe...
[ 6 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003165213_ctypes_python.txt
Q: Storing 'struct' data to binary file I need to store a binary file with a 12 byte header composed of 4 fields. They are namely: sSamples (4-bytes integer), sSampPeriod (4-bytes integer), sSampSize (2-bytes integer), and finally sParmKind (2-bytes integer). I'm using 'struct' to my variables to the desired fields. ...
Storing 'struct' data to binary file
I need to store a binary file with a 12 byte header composed of 4 fields. They are namely: sSamples (4-bytes integer), sSampPeriod (4-bytes integer), sSampSize (2-bytes integer), and finally sParmKind (2-bytes integer). I'm using 'struct' to my variables to the desired fields. Now that I have them defined separately, h...
[ "As Cody Brocious wrote, you can pack your entire header at once:\nheader = struct.pack('<iiHH', nSamples, nSampPeriod, nSampSize, nParmKind)\n\nHe also mentioned endianness, which is important if you want to pack your data so as to reliably unpack it on machines with different architectures. The < at the beginning...
[ 2, 1 ]
[]
[]
[ "binaryfiles", "header_files", "python" ]
stackoverflow_0003164957_binaryfiles_header_files_python.txt
Q: Optimizing a Partition Function Here is the code, in python: # function for pentagonal numbers def pent (n): return int((0.5*n)*((3*n)-1)) # function for generalized pentagonal numbers def gen_pent (n): return pent(int(((-1)**(n+1))*(round((n+1)/2)))) # array for storing partitions - first ten already stored...
Optimizing a Partition Function
Here is the code, in python: # function for pentagonal numbers def pent (n): return int((0.5*n)*((3*n)-1)) # function for generalized pentagonal numbers def gen_pent (n): return pent(int(((-1)**(n+1))*(round((n+1)/2)))) # array for storing partitions - first ten already stored partitions = [1, 1, 2, 3, 5, 7, 11, ...
[ "Here are some comments. Note that I am no expert on this stuff, by I too like messing about with maths (and Project Euler).\nI have redefined the pentagonal number functions as follows:\ndef pent_new(n):\n return (n*(3*n - 1))/2\n\ndef gen_pent_new(n):\n if n%2:\n i = (n + 1)/2\n else:\n i =...
[ 6 ]
[]
[]
[ "optimization", "partitioning", "python" ]
stackoverflow_0003164305_optimization_partitioning_python.txt
Q: python/matplotlib - parasite twin axis scaling Trying to plot a spectrum, ie, velocity versus intensity, with lower x axis = velocity, on the upper twin axis = frequency The relationship between them (doppler formula) is f = (1-v/c)*f_0 where f is the resulting frequency, v the velocity, c the speed of light, ...
python/matplotlib - parasite twin axis scaling
Trying to plot a spectrum, ie, velocity versus intensity, with lower x axis = velocity, on the upper twin axis = frequency The relationship between them (doppler formula) is f = (1-v/c)*f_0 where f is the resulting frequency, v the velocity, c the speed of light, and f_0 the frequency at v=0, ie. the v_lsr. I have ...
[ "The solution I ended up using was:\nax_hz = ax_kms.twiny()\nx_1, x_2 = ax_kms.get_xlim()\n# i want the frequency in GHz so, divide by 1e9\nax_hz.set_xlim(calc_frequency(x_1,data.restfreq/1e9),calc_frequency(x_2,data.restfreq/1e9))\n\nThis works perfect, and much less complicated solution.\nEDIT : Found a very fanc...
[ 5, 0 ]
[]
[]
[ "axes", "matplotlib", "python" ]
stackoverflow_0003148808_axes_matplotlib_python.txt
Q: Is there any way to make Tkinter look less windows 95ish? I was wondering if there was a way to make tkinter more aesthetically pleasing. A: The ttk module is in the upcoming Python 2.7 release. A: You can try PyGtk or PyQt, both have very nice python bindings from what i have heard. There's also the possibil...
Is there any way to make Tkinter look less windows 95ish?
I was wondering if there was a way to make tkinter more aesthetically pleasing.
[ "The ttk module is in the upcoming Python 2.7 release.\n", "You can try PyGtk or PyQt, both have very nice python bindings from what i have heard. There's also the possibility of Tile, which is getting integrated into tkinter in the (near?) future.\nSo, choose another GUI toolkit, or wait :). \n", "If you don't...
[ 3, 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003162662_python_tkinter.txt
Q: import statement mess in python I want to have a number of files imported in a general python file and then include that file when I need the imported modules in the current module. This of course will lead to errors and re-imports if using the from x import y, however when using the "normal" import statement I en...
import statement mess in python
I want to have a number of files imported in a general python file and then include that file when I need the imported modules in the current module. This of course will lead to errors and re-imports if using the from x import y, however when using the "normal" import statement I end up with long instruction statements...
[ "It sounds like you've got recursive imports (importModule refers to moduleName, and moduleName refers to importModule. If you refactor, you should be able to use \nfrom importModule.directoryName1.directoryName2.moduleName import ClassName\n\nTo refactor, you can change the order in which things are imported in m...
[ 3, 2 ]
[]
[]
[ "import", "python", "using_statement" ]
stackoverflow_0003165881_import_python_using_statement.txt
Q: Having PyQt app controlling all. How use reactor? I've a django application, served via Twisted, which also serves ohter services (three sockets, mainly). I need to have it working under windows, and I decide to write a PyQt4 application which acts quite like Apache Service Monitor for windows. I was not able to c...
Having PyQt app controlling all. How use reactor?
I've a django application, served via Twisted, which also serves ohter services (three sockets, mainly). I need to have it working under windows, and I decide to write a PyQt4 application which acts quite like Apache Service Monitor for windows. I was not able to connect twisted reactor to pyqt application reactor, so ...
[ "I'm not sure I totally understand your design but what I can say is that you need to use only one reactor in an application. The reactor is the main (event) loop of the application. And, I think, this reactor should be the QTReactor in your case.\n" ]
[ 1 ]
[]
[]
[ "django", "pyqt4", "python", "reactor", "twisted" ]
stackoverflow_0003165742_django_pyqt4_python_reactor_twisted.txt
Q: how to display a numpy array with pyglet? I have a label matrix with dimension (100*100), stored as a numpy array, and I would like to display the matrix with pyglet. My original idea is to use this matrix to form a new pyglet image using function pyglet.image.ImageData(). It requres a buffer of the imagedata as a...
how to display a numpy array with pyglet?
I have a label matrix with dimension (100*100), stored as a numpy array, and I would like to display the matrix with pyglet. My original idea is to use this matrix to form a new pyglet image using function pyglet.image.ImageData(). It requres a buffer of the imagedata as an input, however I have no idea how to get a ri...
[ "I think what you are looking for is np.dstack (or more generally, np.concatenate):\nlabel255=label*255\nlabel3=numpy.dstack((label255,label255,label255))\n\nThis shows dstack produces the same array (label3) as your construction for label_3d:\nimport numpy as np\n\nlabel=np.random.random((100,100))\nlabel255=label...
[ 5, 1 ]
[]
[]
[ "numpy", "pyglet", "python" ]
stackoverflow_0003165379_numpy_pyglet_python.txt
Q: Can ( s is "" ) and ( s == "" ) ever give different results in Python 2.6.2? As any Python programmer knows, you should use == instead of is to compare two strings for equality. However, are there actually any cases where ( s is "" ) and ( s == "" ) will give different results in Python 2.6.2? I recently came acro...
Can ( s is "" ) and ( s == "" ) ever give different results in Python 2.6.2?
As any Python programmer knows, you should use == instead of is to compare two strings for equality. However, are there actually any cases where ( s is "" ) and ( s == "" ) will give different results in Python 2.6.2? I recently came across code that used ( s is "" ) in code review, and while pointing out that this was...
[ "Python is tests the objects identity and not equality. Here is an example where using is and == gives a different result:\n>>> s=u\"\"\n>>> print s is \"\"\nFalse\n>>> print s==\"\"\nTrue\n\n", "As everyone else has said, don't rely on undefined behaviour. However, since you asked for a specific counterexample f...
[ 12, 11, 7, 3, 1, 0, 0 ]
[]
[]
[ "equality", "identity", "python", "string" ]
stackoverflow_0003165300_equality_identity_python_string.txt
Q: How to use OR using Django's model filter system? It seems that Django's object model filter method automatically uses the AND SQL keyword. For example: >>> Publisher.objects.filter(name__contains="press", country__contains="U.S.A") will automatically translate into something like: SELECT ... FROM publisher WHE...
How to use OR using Django's model filter system?
It seems that Django's object model filter method automatically uses the AND SQL keyword. For example: >>> Publisher.objects.filter(name__contains="press", country__contains="U.S.A") will automatically translate into something like: SELECT ... FROM publisher WHERE name LIKE '%press%' AND country LIKE '%U.S.A.%' How...
[ "You can use Q objects to do what you want, by bitwise OR-ing them together:\nfrom django.db.models import Q\nPublisher.objects.filter(Q(name__contains=\"press\") | Q(country__contains=\"U.S.A\"))\n\n" ]
[ 82 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0003166361_django_python_sql.txt
Q: Python project architecture I'm a java developer new to python. In java, you can access all classes in the same directory without having to import them. I am trying to achieve the same behavior in python. Is this possible? I've tried various solutions, for example by importing everything in a file which I import e...
Python project architecture
I'm a java developer new to python. In java, you can access all classes in the same directory without having to import them. I am trying to achieve the same behavior in python. Is this possible? I've tried various solutions, for example by importing everything in a file which I import everywhere. That works, but I have...
[ "Put everything into a folder (doesn't matter the name), and make sure that that folder has a file named __init__.py (the file can be empty).\nThen you can add the following line to the top of your code:\nfrom myfolder import *\n\nThat should give you access to everything defined in that folder without needing to g...
[ 2 ]
[]
[]
[ "architecture", "python" ]
stackoverflow_0003166347_architecture_python.txt
Q: Overriding Django Admin's main page? - Django I'm trying to add features to Django 1.2 admin's main page. I've been playing with index.html, but features added to this page affect all app pages. Any ideas on what template I'm supposed to use? Thanks loads!! A: You can use template hierarchy like: index.html .....
Overriding Django Admin's main page? - Django
I'm trying to add features to Django 1.2 admin's main page. I've been playing with index.html, but features added to this page affect all app pages. Any ideas on what template I'm supposed to use? Thanks loads!!
[ "You can use template hierarchy like:\nindex.html\n\n...\n{% block content %}\n...\n{% block mycontent %}My custom text{% endblock %}\n...\n{% endblock %}\n\napp_index.html\n\n...\n {% block mycontent %}{% endblock %}\n..\n\n", "I have done this by modifying the admin/index.html template. You may also need to ...
[ 4, 3, 3 ]
[]
[]
[ "admin", "django", "overriding", "python" ]
stackoverflow_0002896490_admin_django_overriding_python.txt
Q: Is safe to use the shove module to store data in a non blocking program? I'm writing a simple crawler with eventlet and I want to store all the url I retrieve in a simple datastore like shove. Is safe to use it in a non blocking enviroment? A: Since most modules are written in the traditional synchronous/blocki...
Is safe to use the shove module to store data in a non blocking program?
I'm writing a simple crawler with eventlet and I want to store all the url I retrieve in a simple datastore like shove. Is safe to use it in a non blocking enviroment?
[ "Since most modules are written in the traditional synchronous/blocking module, unless your module explicitly touts that it is asynchronous, you need to handle it with a callback in your eventlet program. The shove home page doesn't mention anything about the issue, which means its probably going to block on file...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003156175_python.txt
Q: python regex: match a string with only one instance of a character Suppose there are two strings: $1 off delicious ham. $1 off delicious $5 ham. In Python, can I have a regex that matches when there is only one $ in the string? I.e., I want the RE to match on the first phrase, but not on the second. I tried som...
python regex: match a string with only one instance of a character
Suppose there are two strings: $1 off delicious ham. $1 off delicious $5 ham. In Python, can I have a regex that matches when there is only one $ in the string? I.e., I want the RE to match on the first phrase, but not on the second. I tried something like: re.search(r"\$[0-9]+.*!(\$)","$1 off delicious $5 ham.") ....
[ ">>> import re\n>>> onedollar = re.compile(r'^[^\\$]*\\$[^\\$]*$')\n>>> onedollar.match('$1 off delicious ham.')\n<_sre.SRE_Match object at 0x7fe253c9c4a8>\n>>> onedollar.match('$1 off delicious $5 ham.')\n>>>\n\nBreakdown of regexp:\n^ Anchor at start of string\n[^\\$]* Zero or more characters that are not $\n\\$ ...
[ 11, 7, 2, 1, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0003166619_python_regex_string.txt
Q: Why does this simple Python script reveal the incorrect answer? I'm again working on Project Euler, this time problem #4. The point of this script is to find the largest palindromic product of two three digit numbers. I thought it was fairly straightforward to solve, but I'm getting an answer that is too low. More...
Why does this simple Python script reveal the incorrect answer?
I'm again working on Project Euler, this time problem #4. The point of this script is to find the largest palindromic product of two three digit numbers. I thought it was fairly straightforward to solve, but I'm getting an answer that is too low. More specifically, I am getting 580085, and the answer is 906609. Could ...
[ "Your code doesn't make sure it prints the largest product, since there could later be a smaller product which replaces it. To fix it, initialize t to zero, and replace your condition with\nif z==s and int(z)>t:\n t = int(z)\n\nOr equivalently,\nif z==s:\n t = max(t,int(z))\n\nEdit: Fixed int/string issues ab...
[ 6, 6, 3, 2, 1, 0 ]
[]
[]
[ "palindrome", "python" ]
stackoverflow_0003145897_palindrome_python.txt
Q: Use 2 sound cards I need to play a sound with sound card "A", while recording another sound using sound card "B". I know how to play or record a sound (using PyAudio), but I don't know how to choose which sound card to use for it. I have the impression that PyAudio doesn't allow choosing the sound card, but I migh...
Use 2 sound cards
I need to play a sound with sound card "A", while recording another sound using sound card "B". I know how to play or record a sound (using PyAudio), but I don't know how to choose which sound card to use for it. I have the impression that PyAudio doesn't allow choosing the sound card, but I might be wrong (I'm a begin...
[ "It appears that PortAudio, the C package that PyAudio wraps, has the ability to choose a sound card.\nPortAudio has the parameters / methods PaDeviceIndex, Pa_getdeviceCount(), and PaUseHostAPISpecificDeviceSpecification.\nFor some reason, PyAudio does not wrap those parameters / methods.\n" ]
[ 0 ]
[]
[]
[ "python", "soundcard" ]
stackoverflow_0003165200_python_soundcard.txt
Q: Python: How to make object attribute refer call a method I'd like for an attribute call like object.x to return the results of some method, say object.other.other_method(). How can I do this? Edit: I asked a bit soon: it looks like I can do this with object.__dict__['x']=object.other.other_method() Is this an OK...
Python: How to make object attribute refer call a method
I'd like for an attribute call like object.x to return the results of some method, say object.other.other_method(). How can I do this? Edit: I asked a bit soon: it looks like I can do this with object.__dict__['x']=object.other.other_method() Is this an OK way to do this?
[ "Use the property decorator\nclass Test(object): # make sure you inherit from object\n @property\n def x(self):\n return 4\n\np = Test()\np.x # returns 4\n\nMucking with the __dict__ is dirty, especially when @property is available.\n", "Have a look at the built-in property function.\n", "Use a pro...
[ 50, 11, 6, 4 ]
[]
[]
[ "attributes", "python" ]
stackoverflow_0003166773_attributes_python.txt
Q: Python images display How can I create a python script that runs through the images (1.jpeg-n.jpeg) in a directory on a mac and displays them in a browser OR via another python program? Do I import a file to python and than display in browser? Do I extract the file names 1,2,3,4,5 and add that to a list, which I g...
Python images display
How can I create a python script that runs through the images (1.jpeg-n.jpeg) in a directory on a mac and displays them in a browser OR via another python program? Do I import a file to python and than display in browser? Do I extract the file names 1,2,3,4,5 and add that to a list, which I give to another function tha...
[ "Using Tkinter and PIL for this purpose is pretty trivial. Add muskies example to the information from this thread that contains this example:\n# use a Tkinter label as a panel/frame with a background image\n# note that Tkinter only reads gif and ppm images\n# use the Python Image Library (PIL) for other image form...
[ 5, 4, 1, 0 ]
[]
[]
[ "image", "python" ]
stackoverflow_0003166221_image_python.txt
Q: Py-appscript: How can I make message with Mail.app I'm trying to create mail with py-appscript (AppleScript interface for python). I tried following code, from appscript import * mail = app('Mail') msg = mail.make(new=k.outgoing_message, with_properties={'visible':True, ...
Py-appscript: How can I make message with Mail.app
I'm trying to create mail with py-appscript (AppleScript interface for python). I tried following code, from appscript import * mail = app('Mail') msg = mail.make(new=k.outgoing_message, with_properties={'visible':True, 'content':"hello", ...
[ "Problem solved by myself, following code works fine.\nfrom appscript import *\n\nmail = app('Mail')\nmsg = mail.make(new=k.outgoing_message)\nmsg.subject.set(\"hello\"),\nmsg.content.set(\"appscript\")\nmsg.to_recipients.end.make(\n new=k.to_recipient,\n with_properties={k.address: 'taichino@gmail.com'}\n)\n...
[ 0 ]
[]
[]
[ "applescript", "python" ]
stackoverflow_0003166175_applescript_python.txt
Q: Cherrypy multithreading example I do know that cherrypy is a multithreaded and also has a threadpool implementation. So I wanted to try an example showing multithreaded behaviour. Now lets say I've my some function in the root class and rest all things are configured def testPage(self, *args, **kwargs): curren...
Cherrypy multithreading example
I do know that cherrypy is a multithreaded and also has a threadpool implementation. So I wanted to try an example showing multithreaded behaviour. Now lets say I've my some function in the root class and rest all things are configured def testPage(self, *args, **kwargs): current = threading.currentThread() pri...
[ "This is almost certainly a limitation of your browser and not of CherryPy. Firefox 2, for example, will make no more than 2 concurrent requests to the same domain, even with multiple tabs. And if each tab is also fetching a favicon...that leaves one hit at a time on your handler.\nSee http://www.cherrypy.org/ticke...
[ 2 ]
[]
[]
[ "cherrypy", "multithreading", "python" ]
stackoverflow_0003164560_cherrypy_multithreading_python.txt
Q: Storing XML/HTML files inside a SQLite database - Possible? Is it possible to directly store a XML/HTML file inside a SQLite database? I'm writing a program in python which is supposed to parse XML/HTML files and store the values inside the database. However, the fields inside the XML/HTML files may vary and I tho...
Storing XML/HTML files inside a SQLite database - Possible?
Is it possible to directly store a XML/HTML file inside a SQLite database? I'm writing a program in python which is supposed to parse XML/HTML files and store the values inside the database. However, the fields inside the XML/HTML files may vary and I thought it would be easier to simply store the entire XML/HTML file ...
[ "You can store your XML/HTML file as text without problems in a text column.\nThe obvious downside is that you can't really query for the values in your XML.\nEdit: \nHere is an example. Just read your XML file into a variable and store it in the DB like you would store any string, alongside with any other values y...
[ 7 ]
[]
[]
[ "python", "sqlite", "xml" ]
stackoverflow_0003167139_python_sqlite_xml.txt
Q: Python dictionaries: changing the order of nesting I have a dictionary, with 300 key value pairs, where each of the keys are integers and the values are dictionaries with three key value pairs. The inner dictionaries all have the same keys, but different values. The whole thing looks pretty much like this: nested_...
Python dictionaries: changing the order of nesting
I have a dictionary, with 300 key value pairs, where each of the keys are integers and the values are dictionaries with three key value pairs. The inner dictionaries all have the same keys, but different values. The whole thing looks pretty much like this: nested_dicts = {1: {'name1':88.4, 'name2':22.1, 'nam...
[ "After adjusting your input dict to be:\n>>> nested_dicts\n{0: {'name2': 22.1, 'name3': 115.7, 'name1': 88.4},\n 1: {'name2': 23.7, 'name3': 117.9, 'name1': 89.4},\n 2: {'name2': 36.6, 'name3': 122.4, 'name1': 110.1}}\n>>> for i in sorted(nested_dicts):\n for k, v in nested_dicts[i].items():\n if k not in...
[ 4, 3 ]
[]
[]
[ "dictionary", "list_comprehension", "python", "sorting" ]
stackoverflow_0003167143_dictionary_list_comprehension_python_sorting.txt
Q: Using Beautiful Soup Python module to replace tags with plain text I am using Beautiful Soup to extract 'content' from web pages. I know some people have asked this question before and they were all pointed to Beautiful Soup and that's how I got started with it. I was able to successfully get most of the content ...
Using Beautiful Soup Python module to replace tags with plain text
I am using Beautiful Soup to extract 'content' from web pages. I know some people have asked this question before and they were all pointed to Beautiful Soup and that's how I got started with it. I was able to successfully get most of the content but I am running into some challenges with tags that are part of the con...
[ "An approach that works for your specific example is:\nfrom BeautifulSoup import BeautifulSoup\n\nht = '''\n<div id=\"abc\">\n some long text goes <a href=\"/\"> here </a> and hopefully it \n will get picked up by the parser as content\n</div>\n'''\nsoup = BeautifulSoup(ht)\n\nanchors = soup.findAll('a')\nfor...
[ 4, 1 ]
[]
[]
[ "html_content_extraction", "python" ]
stackoverflow_0002061718_html_content_extraction_python.txt
Q: Fast lookup for dictionary vector to a given vector. High dimensions I'm looking for an answer that scales, but for my specific purpose, I have a 48th dimension vector. This could be represented as an array of 48 integers all between 0 and 255. I have a large dictionary of these vectors, approximately 25 thousand...
Fast lookup for dictionary vector to a given vector. High dimensions
I'm looking for an answer that scales, but for my specific purpose, I have a 48th dimension vector. This could be represented as an array of 48 integers all between 0 and 255. I have a large dictionary of these vectors, approximately 25 thousand of them. I need to be able to take a vector that may or may not be in my ...
[ "I would suggest implementing a kd-tree on which you can perform Nearest neighbour search. The worst case search time for N points in k dimensions is O(k.N^(1-1/k)) so it should scale sublinearly in N.\nIf I have time I will come back to this answer and provide a less terse explanation that Wikipedia's. \nSince y...
[ 8, 4 ]
[]
[]
[ "algorithm", "math", "python", "vector" ]
stackoverflow_0003163854_algorithm_math_python_vector.txt
Q: django ORM: make query Possible Duplicate: Django equivalent for count and group by I'm studying django. In my project I'm having trouble with making a query with django ORM: SELECT MIN( id ) AS id, domain, COUNT( * ) AS cnt FROM app_competition WHERE word_id = 1545 GROUP BY domain Help me please make this que...
django ORM: make query
Possible Duplicate: Django equivalent for count and group by I'm studying django. In my project I'm having trouble with making a query with django ORM: SELECT MIN( id ) AS id, domain, COUNT( * ) AS cnt FROM app_competition WHERE word_id = 1545 GROUP BY domain Help me please make this query
[ "You need some Aggregation for this!\nWhat you need to do in your case is two things: First, use values to force GROUPBY on your query, then annotate your query using the built-in functions Min and Count\nIf my django-orm fu is correct, your query should look something like this:\nfrom django.db.models import Min, ...
[ 2 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0003167516_django_orm_python.txt
Q: Rename a computer programmatically I need to automate the changing of the hostname of a computer, but I can't figure out how to do it inside a program. My options are open; I would be happy with a solution in any of the following: Command line Java Python C# (would prefer one of the other 3, but this is ok) It wou...
Rename a computer programmatically
I need to automate the changing of the hostname of a computer, but I can't figure out how to do it inside a program. My options are open; I would be happy with a solution in any of the following: Command line Java Python C# (would prefer one of the other 3, but this is ok) It would be helpful to learn how to do this on...
[ "For Unix-based systems:\nCommand line:\n$ hostname \"host.domain.com\"\n\nPython (sort of):\nimport os\nos.system('hostname \"host.domain.com\"')\n\n", "You could also do this in powershell on windows. Seems safer to me than changing registry keys by hand :\n$computer = Get-WmiObject Win32_ComputerSystem -Origin...
[ 3, 2, 0 ]
[]
[]
[ "c#", "hostname", "java", "python" ]
stackoverflow_0003167469_c#_hostname_java_python.txt
Q: Scraping a table using BeautifulSoup I have a question which i suspect is fairly straight forward. I have the following type of page from which I want to collect the information in the last table (if you scroll all the way down it is the one in the box labelled "Procedure"): http://www.europarl.europa.eu/sides/get...
Scraping a table using BeautifulSoup
I have a question which i suspect is fairly straight forward. I have the following type of page from which I want to collect the information in the last table (if you scroll all the way down it is the one in the box labelled "Procedure"): http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2...
[ "You can find elements by other attributes if you're a bit clever. I took this shot at scraping your data, and it probably isn't the best – but, it gets you close.\nThe first thing I noticed was you definitely wanted data after the second appearance of the word \"PROCEDURE\" (first being the link, second being the ...
[ 3 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping" ]
stackoverflow_0003167106_beautifulsoup_python_screen_scraping.txt
Q: importing files residing in an unrelated path Consider I have a directory called root that has two directories: x and y. I have a module file that resides in x, let us call that test.py. Now in y, I have a module that needs to call test.py I am doing a simple: from x import test And it works. I was wondering, how ...
importing files residing in an unrelated path
Consider I have a directory called root that has two directories: x and y. I have a module file that resides in x, let us call that test.py. Now in y, I have a module that needs to call test.py I am doing a simple: from x import test And it works. I was wondering, how this works? EDIT: How it works, as in there was no...
[ "It doesn't. You, or your operating system, or your Python site startup scripts, have modified PYTHONPATH.\n14:59 jsmith@upsidedown pwd\n/Users/jsmith/Test/Test2/root\n\n14:59 jsmith@upsidedown cat x/test.py\ndef hello():\n print \"hello\"\n\n14:59 jsmith@upsidedown cat y/real.py\n#!/usr/bin/python\nfrom x impo...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003168378_python.txt
Q: Library to render Directed Graphs (similar to graphviz) on Google App Engine I am looking for a Java or Python library that can render graphs in the Dot language as image file. The problem is that I need a library that I can use on Google App Engine. Basically I am looking for a library that can convert the text ...
Library to render Directed Graphs (similar to graphviz) on Google App Engine
I am looking for a Java or Python library that can render graphs in the Dot language as image file. The problem is that I need a library that I can use on Google App Engine. Basically I am looking for a library that can convert the text description of a directed graph into an image of the graph. For example: Covert th...
[ "Canviz is what you are looking for: it is a JavaScript library for drawing Graphviz graphs to a web browser canvas. It works with most browsers.\n\nUsing Canviz has advantages for your web application over generating and sending bitmapped images and imagemaps to the browser:\n\nThe server only needs to have Graphv...
[ 19, 12, 0, 0 ]
[]
[]
[ "google_app_engine", "graph", "graphviz", "java", "python" ]
stackoverflow_0002264157_google_app_engine_graph_graphviz_java_python.txt
Q: how to extends the parent html page on google app engine templates | ....a.html |.....admin |..... index.html |..... b.html in google app engine templates, i can use this to extends b.html in index.html: {% extends 'b.html' %} but how to extends a.html in index.html. thanks A: Y...
how to extends the parent html page on google app engine
templates | ....a.html |.....admin |..... index.html |..... b.html in google app engine templates, i can use this to extends b.html in index.html: {% extends 'b.html' %} but how to extends a.html in index.html. thanks
[ "You can only have one extends per template. It's like single inheritance in OOP languages like C# and Java. \nThis question has an answer that will give you some good ideas for laying out your templates and having a good template inheritence scheme\n" ]
[ 1 ]
[]
[]
[ "extends", "google_app_engine", "python", "templates" ]
stackoverflow_0003168532_extends_google_app_engine_python_templates.txt
Q: Possible to retrieve steam server list in python? I wanted to hear whether it was possible to find a way to retrieve steam servers in python? If so, how could one go about it? A: Valve has documented the Master Server Query Protocol rather well. There is also a Python library called SourceLib that provides an i...
Possible to retrieve steam server list in python?
I wanted to hear whether it was possible to find a way to retrieve steam servers in python? If so, how could one go about it?
[ "Valve has documented the Master Server Query Protocol rather well. There is also a Python library called SourceLib that provides an interface to the server list.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003148231_python.txt
Q: Django Custom Template Tags In Google App Engine I am trying to include the following Tag In Google App Engine Web Application: http://www.djangosnippets.org/snippets/1357/ Is there any configuration of this file to make it work with Google App Engine? Cause I followed the Django Template tutorials: http://docs.dj...
Django Custom Template Tags In Google App Engine
I am trying to include the following Tag In Google App Engine Web Application: http://www.djangosnippets.org/snippets/1357/ Is there any configuration of this file to make it work with Google App Engine? Cause I followed the Django Template tutorials: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ and...
[ "try doing the following:\n$ python ./manage.py startapp foo\n\nAdd foo to installed apps:\nINSTALLED_APPS += ('foo',)\n\nAnd move your templatetags directory into your foo app. Something like:\n./djangoproject\n __init__.py\n settings.py\n urls.py\n etc..\n foo/\n __init__.py\n templat...
[ 4, 4, 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0000770854_django_google_app_engine_python.txt
Q: how to show a html page in a js file on google app engine $('#upload').click(function(){ $('#main .right').html("{% extends 'a.html' %}") }) but this is error , how to make this code running . thanks A: Let me guess -- your element ends up containing "{% extends 'a.html' %}"? If so, it's because yo...
how to show a html page in a js file on google app engine
$('#upload').click(function(){ $('#main .right').html("{% extends 'a.html' %}") }) but this is error , how to make this code running . thanks
[ "Let me guess -- your element ends up containing \"{% extends 'a.html' %}\"? If so, it's because your js file is not being parsed by the template engine. In any case, you might be better served by making this an AJAX request, like the following:\n$('#upload').click(function() {\n $.get(\"a.html\", function(data)...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "jquery", "python" ]
stackoverflow_0003168498_google_app_engine_jquery_python.txt
Q: Python parsing files I need to know the best approach for the following scenario lets say we have some huge file which logs the output of the compilation and there are couple of error patterns which I want to test against this file, for eg. error patterns could be - : error: - : error [A-Z]*[\d ]* - [A-Z]*[\d]*...
Python parsing files
I need to know the best approach for the following scenario lets say we have some huge file which logs the output of the compilation and there are couple of error patterns which I want to test against this file, for eg. error patterns could be - : error: - : error [A-Z]*[\d ]* - [A-Z]*[\d]* [E\e|rror: - " Cannot o...
[ "If the log file is large, it may not be a good idea to load it to memory. Instead, you may precompile all regular expressions and test against them line by line, e.g.:\ndef has_error(filename):\n with file(filename, 'r') as logfile:\n for line in logfile:\n for regexp in MY_REGEXPS:\n ...
[ 2, 0, 0 ]
[]
[]
[ "grep", "parsing", "python", "regex" ]
stackoverflow_0003168759_grep_parsing_python_regex.txt
Q: Complex HTML parsing with Python I am already aware of tag based HTML parsing in Python using BeautifulSoup, htmllib etc. However, I want a powerful engine which can do complex tasks like read html tables, lists etc. and present these as simple to use objects within code. Does python have such powerful libraries?...
Complex HTML parsing with Python
I am already aware of tag based HTML parsing in Python using BeautifulSoup, htmllib etc. However, I want a powerful engine which can do complex tasks like read html tables, lists etc. and present these as simple to use objects within code. Does python have such powerful libraries?
[ "BeautifulSoup is a nice library and provides a good way to parse HTML with some handy ways to parse the data very easily. \nWhat you are trying to do, can easily be done using some simple regular expressions. You can write regular expressions to search for a particular pattern of data and extract the data you need...
[ 2, 2, 0 ]
[]
[]
[ "html_parsing", "python" ]
stackoverflow_0003167679_html_parsing_python.txt
Q: Finding the intersection of two vector equations I've been trying to solve this and I found an equation that gives the possibility of zero division errors. Not the best thing: v1 = (a,b) v2 = (c,d) d1 = (e,f) d2 = (h,i) l1: v1 + λd1 l2: v2 + µd2 Equation to find vector intersection of l1 and l2 programatically b...
Finding the intersection of two vector equations
I've been trying to solve this and I found an equation that gives the possibility of zero division errors. Not the best thing: v1 = (a,b) v2 = (c,d) d1 = (e,f) d2 = (h,i) l1: v1 + λd1 l2: v2 + µd2 Equation to find vector intersection of l1 and l2 programatically by re-arranging for lambda. (a,b) + λ(e,f) = (c,d) + µ...
[ "If you do a Google search for intersection of lines you'll find lots of formulas that don't involve division by one of the coordinates. The sputsoft one referenced from wikipedia has a good explanation of the algorithm. \nRegarding your math, you are too quick to divide by h and i. A solution can be arrived at by ...
[ 1, 0, 0 ]
[]
[]
[ "c++", "graphics", "math", "python" ]
stackoverflow_0003066635_c++_graphics_math_python.txt
Q: Help with cPickle in Python 2.6 I tried the following code I python. This is my first attempt at pickling. import Tkinter import cPickle root = Tkinter.Tk() root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) root.sclX.pack(ipadx=75) root.resizable(False,False) root.title('Scal...
Help with cPickle in Python 2.6
I tried the following code I python. This is my first attempt at pickling. import Tkinter import cPickle root = Tkinter.Tk() root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) root.sclX.pack(ipadx=75) root.resizable(False,False) root.title('Scale') with open('myconfig.pk', 'wb...
[ "Try switching the order of the arguments:\ncPickle.dump(root.config(), f, -1)\ncPickle.dump(root.sclX.config(), f, -1)\n\nAccording to the documentation, the file should be the second argument, and the object to be pickled should be the first.\n", "I think you have the parameters in the wrong order. See the docs...
[ 2, 1 ]
[]
[]
[ "pickle", "python", "python_2.6", "tkinter" ]
stackoverflow_0003168894_pickle_python_python_2.6_tkinter.txt
Q: Programmatically interrupting raw_input Is there a way to programmatically interrupt Python's raw_input? Specifically, I would like to present a prompt to the user, but also listen on a socket descriptor (using select, for instance) and interrupt the prompt, output something, and redisplay the prompt if data comes...
Programmatically interrupting raw_input
Is there a way to programmatically interrupt Python's raw_input? Specifically, I would like to present a prompt to the user, but also listen on a socket descriptor (using select, for instance) and interrupt the prompt, output something, and redisplay the prompt if data comes in on the socket. The reason for using raw_i...
[ "As far as I know... \"Sort of\".\nraw_input is blocking so the only way I can think of is spawning a subprocess/thread to retrieve the input, and then simply communicate with the thread/subprocess. It's a pretty dirty hack (at least it seems that way to me), but it should work cross platform. The other alternative...
[ 2 ]
[]
[]
[ "input", "python", "readline" ]
stackoverflow_0003167956_input_python_readline.txt
Q: Python fast string parsing, manipulation I am using python to parse the incoming comma separated string. I want to do some calculation afterwards on the data. The length of the string is: 800 characters with 120 comma separated fields. There such 1.2 million strings to process. for v in item.values(): l...
Python fast string parsing, manipulation
I am using python to parse the incoming comma separated string. I want to do some calculation afterwards on the data. The length of the string is: 800 characters with 120 comma separated fields. There such 1.2 million strings to process. for v in item.values(): l.extend(get_fields(v.split(','))) #process l...
[ "Are you loading a dict with your file records? Probably better to process the data directly:\ndatafile = file(\"file_with_1point2million_records.dat\")\n# uncomment next to skip over a header record\n# file.next()\n\nl = sum(get_fields(v.split(',')) for v in file, [])\n\nThis avoids creating any overall data stru...
[ 3, 2 ]
[]
[]
[ "parsing", "performance", "python", "string" ]
stackoverflow_0003168560_parsing_performance_python_string.txt
Q: How should I organize a list of items by their category in Django? I have a "Category" model, and a "Project" model, which contains a ForeignKey to "Category." So each Project can only belong to one Category. I want to create a list that ends up looking like the following: Category 1 Project 1 Project 2 Category 2...
How should I organize a list of items by their category in Django?
I have a "Category" model, and a "Project" model, which contains a ForeignKey to "Category." So each Project can only belong to one Category. I want to create a list that ends up looking like the following: Category 1 Project 1 Project 2 Category 2 Project 3 Project 4 etc. I think the following psuedocode will work: <u...
[ "{% for p in c.project_set.all %}\n\nLook in the Django documentation for following relationships backwards. \n", "You can do this by using the regroup tag http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#regroup\n" ]
[ 3, 2 ]
[]
[]
[ "django", "loops", "python", "templates" ]
stackoverflow_0003169027_django_loops_python_templates.txt
Q: Google App Engine Python Authentication from API I'm currently building a Python webapp on the Google App Engine and I want to expose various parts of my application via a JSON API. This API may be used in the form of a mobile client, or (for the purposes of testing) a headless Python script. I need to be able to ...
Google App Engine Python Authentication from API
I'm currently building a Python webapp on the Google App Engine and I want to expose various parts of my application via a JSON API. This API may be used in the form of a mobile client, or (for the purposes of testing) a headless Python script. I need to be able to authenticate users before they perform operations on t...
[ "You might want to check out the recently released oauth support. Failing that, you can implement your own authentication, for example by using simple or digest authentication.\n", "Just for the record, I ended up going with the wonderful Tipfy framework in the end.\n" ]
[ 0, 0 ]
[]
[]
[ "api", "google_app_engine", "python", "web_applications" ]
stackoverflow_0003074889_api_google_app_engine_python_web_applications.txt
Q: What data type should my widgets accept/return? I'm building a form class in python for producing and validating HTML forms. Each field has an associated widget which defines how the field is rendered. When the widget is created, it is passed in a (default) value so that it knows what to display the first time it ...
What data type should my widgets accept/return?
I'm building a form class in python for producing and validating HTML forms. Each field has an associated widget which defines how the field is rendered. When the widget is created, it is passed in a (default) value so that it knows what to display the first time it is rendered. After the form is submitted, the widget ...
[ "While simply passing strings around seems like a useful idea, I think you're going to discover it doesn't work as well as you might hope.\nThink about the date example—instead of passing around a date object, instead you pass around a str of the format \"2010-01-01\". In order to work with that data, every user o...
[ 2, 1 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0003169096_design_patterns_python.txt
Q: Sequence file name being used as key in Hadoop output? I'm trying to use Dumbo/Hadoop to calculate TF-IDF for a bunch of small text files using this example http://dumbotics.com/2009/05/17/tf-idf-revisited/ To improve efficiency, I've packaged the text files into a sequence file using Stuart Sierra's tool -- http:...
Sequence file name being used as key in Hadoop output?
I'm trying to use Dumbo/Hadoop to calculate TF-IDF for a bunch of small text files using this example http://dumbotics.com/2009/05/17/tf-idf-revisited/ To improve efficiency, I've packaged the text files into a sequence file using Stuart Sierra's tool -- http://stuartsierra.com/2008/04/24/a-million-little-files The seq...
[ "I made the following tweaks to the first mapper and everything started working.\n#Original version\n@opt(\"addpath\", \"yes\")\ndef mapper1(key, value):\n for word in value.split():\n yield (key[0], word), 1\n\n#Edits version\ndef mapper1(key, value):\n for word in value.split():\n yield (key, ...
[ 1 ]
[]
[]
[ "hadoop", "mapreduce", "python" ]
stackoverflow_0003151811_hadoop_mapreduce_python.txt
Q: Where can I get some proxy list good for use it with Python? Where? I'm trying google and any of the proxys I've tried worked... I'm trying urllib.open with it... I don't know if urllib need some special proxy type or something like that... Thank you ps: I need some proxies to ping a certain website and not got ba...
Where can I get some proxy list good for use it with Python?
Where? I'm trying google and any of the proxys I've tried worked... I'm trying urllib.open with it... I don't know if urllib need some special proxy type or something like that... Thank you ps: I need some proxies to ping a certain website and not got banned from my ip
[ "Try setting up your own proxy and connecting to it...\n", "You probably don't even need to use a proxy. The urllib module knows how to contact web servers directly. \nYou may need to use a proxy if you're behind certain kinds of corporate firewalls, but in that case you can't just choose any proxy to use, you ha...
[ 0, 0 ]
[]
[]
[ "proxy", "python" ]
stackoverflow_0003169425_proxy_python.txt
Q: Py GTK Drawing area and Rich Text Editor I would like to include a rich text editor in a pygtk drawing area for an application i am developing. The editor ( a small resizable widget ) should be able to move around the drawing area like a rectangle. I am not sure how to start as I am pretty new to PyGTK. thank you ...
Py GTK Drawing area and Rich Text Editor
I would like to include a rich text editor in a pygtk drawing area for an application i am developing. The editor ( a small resizable widget ) should be able to move around the drawing area like a rectangle. I am not sure how to start as I am pretty new to PyGTK. thank you !
[ "BloGTK seems to use an HTML widget for rich text. Those aren't quite as flexible for plain text.\nHere's a link that should be helpful:\nhttp://www.kksou.com/php-gtk2/articles/apply-styles-to-GtkTextView-using-GtkTextTag---Part-1.php\n", "gtk.TextView is \"rich\", in that it can display all types of formatting a...
[ 1, 0, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0002650591_pygtk_python.txt
Q: python: c# binary datetime encoding I need to extract financial price data from a binary file. This price data is normally extracted by a piece of C# code. The biggest problem I'm having is getting a meaningful datetime. The binary data looks like this: '\x14\x11\x00\x00{\x14\xaeG\xe1z(@\x9a\x99\x99\x99\x99\x99(...
python: c# binary datetime encoding
I need to extract financial price data from a binary file. This price data is normally extracted by a piece of C# code. The biggest problem I'm having is getting a meaningful datetime. The binary data looks like this: '\x14\x11\x00\x00{\x14\xaeG\xe1z(@\x9a\x99\x99\x99\x99\x99(@q=\n\xd7\xa3p(@\x9a\x99\x99\x99\x99\x99(...
[ "As far as I know, .net timestamps are ticks since 0001-01-01T00:00:00Z where a tick is 100 nanoseconds. So:\n>>> x = 634124502600000000\n>>> secs = x / 10.0 ** 7\n>>> secs\n63412450260.0\n>>> import datetime\n>>> delta = datetime.timedelta(seconds=secs)\n>>> delta\ndatetime.timedelta(733940, 34260)\n>>> ts = datet...
[ 3, 0 ]
[]
[]
[ "binary", "c#", "python" ]
stackoverflow_0003169517_binary_c#_python.txt
Q: Python Error Catching & FTP Trying to get a handle on the FTP library in Python. :) Got this so far. from ftplib import FTP server = '127.0.0.1' port = '57422' print 'FTP Client (' + server + ') port: ' + port try: ftp = FTP() ftp.connect(server, port, 3) print 'Connected! Welcome msg is \"' + ftp.g...
Python Error Catching & FTP
Trying to get a handle on the FTP library in Python. :) Got this so far. from ftplib import FTP server = '127.0.0.1' port = '57422' print 'FTP Client (' + server + ') port: ' + port try: ftp = FTP() ftp.connect(server, port, 3) print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"' ftp.cwd('...
[ "\nI can't do\n\nexcept: ftplib.all_errors\n\nOf course not, that's simply bad syntax! But of course you can do it with proper syntax:\nexcept ftplib.all_errors:\n\ni.e., the colon after the tuple of exceptions.\n\nHow can I retrieve more specific\n information on the error? Perhaps the\n error code?\n\nexcept f...
[ 24, 2, 1 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0003169725_ftp_python.txt
Q: Generating Combinations in python I am not sure how to go about this in Python, if its even possible. What I need to do is create an array (or a matrix, or vector?) from 3 separate arrays. Each array as 4 elements as such, they return this: Class1 = [1,2,3,4] Class2 = [1,2,3,4] Class3 = [1,2,3,4] Now what I woul...
Generating Combinations in python
I am not sure how to go about this in Python, if its even possible. What I need to do is create an array (or a matrix, or vector?) from 3 separate arrays. Each array as 4 elements as such, they return this: Class1 = [1,2,3,4] Class2 = [1,2,3,4] Class3 = [1,2,3,4] Now what I would like to do is return all possible com...
[ "What you want is called a Cartesian product:\nimport itertools\n\niterables = [ [1,2,3,4], [88,99], ['a','b'] ]\n\nfor t in itertools.product(*iterables):\n print t\n\n", "The simplest way:\nfor i in Class1:\n for j in Class2:\n for k in Class3:\n print (i,j,k)\n\n", "Check the Python i...
[ 43, 8, 2 ]
[]
[]
[ "arrays", "combinations", "matrix", "multidimensional_array", "python" ]
stackoverflow_0003169825_arrays_combinations_matrix_multidimensional_array_python.txt
Q: how do i take advantage of sqlite manifest typing / type affinity using sqlalchemy? I like the idea of sqlite's manifest typing / type affinity: http://www.sqlite.org/datatype3.html Essentially, if I set a column's affinity as 'numeric', it will duck type integers or floats to store them as such, but still allow m...
how do i take advantage of sqlite manifest typing / type affinity using sqlalchemy?
I like the idea of sqlite's manifest typing / type affinity: http://www.sqlite.org/datatype3.html Essentially, if I set a column's affinity as 'numeric', it will duck type integers or floats to store them as such, but still allow me to store strings if I want to. Seems to me this is the best 'default' type for a colum...
[ "OK, here's what I've come up with:\nDefine a custom column type, as per\nhttp://www.sqlalchemy.org/docs/reference/sqlalchemy/types.html#custom-types\na combination of the documentation and some trial & error have given me this:\nclass MyDuckType(sqlalchemy.types.TypeDecorator):\n \"\"\"\n SQLALchemy custom c...
[ 1, 0 ]
[]
[]
[ "python", "sqlalchemy", "sqlite", "typing" ]
stackoverflow_0003044518_python_sqlalchemy_sqlite_typing.txt
Q: why my code stop in secound while loop? #hello , i wounder why my code keep stoping at the secound while loop and doesn't do anything print"*******************************" a = 0 deg_list =[] deg_list_a=[] deg_list_b=[] deg_list_c=[] degree=input("Enter the students Degree:") while a<=degree: deg_list.append(d...
why my code stop in secound while loop?
#hello , i wounder why my code keep stoping at the secound while loop and doesn't do anything print"*******************************" a = 0 deg_list =[] deg_list_a=[] deg_list_b=[] deg_list_c=[] degree=input("Enter the students Degree:") while a<=degree: deg_list.append(degree); degree=input("Enter the students ...
[ "Your code enters an endless loop. \nBoth of your while loops have problems with the condition which allows them to terminate. Since your code never changes the value of a, the first loop becomes while 0<=degree, and so the first loop terminates when the user inputs a negative value. But the variable a can be re...
[ 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003169919_python.txt