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: MySql Connector (python) and SQLAlchemy Unicode problem I am using the mysql connector (https://launchpad.net/myconnpy) with SQLAlchemy and, though the table is definitely UTF8, any string columns returned are just normal strings not unicode. The documentation doesn't list any specific parameters for UTF8/unicode ...
MySql Connector (python) and SQLAlchemy Unicode problem
I am using the mysql connector (https://launchpad.net/myconnpy) with SQLAlchemy and, though the table is definitely UTF8, any string columns returned are just normal strings not unicode. The documentation doesn't list any specific parameters for UTF8/unicode support for the mysql connector driver so I borrowed from the...
[ "To work with Unicode python objects you should set the optional parameter convert_unicode to True when specifying a character column type:\nusers = Table('users', metadata,\n Column('id', Integer, primary_key=True)\n Column('name', String(100, convert_unicode=True))\n\nYou could also use ...
[ 1 ]
[ "Sorry, i don't know about the connector, i use MySQLDB and it is working quite nicely. I work in UTF8 as well and i didn't have any problem.\n" ]
[ -3 ]
[ "mysql", "python", "sqlalchemy", "unicode" ]
stackoverflow_0004191370_mysql_python_sqlalchemy_unicode.txt
Q: Selecting specific users I have a a model that stores users: class SubItem(models.Model): created = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(User) I have a group in the auth admin section called 'advisors'. How do I only show the advisors in the pulldown that django create...
Selecting specific users
I have a a model that stores users: class SubItem(models.Model): created = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(User) I have a group in the auth admin section called 'advisors'. How do I only show the advisors in the pulldown that django creates. (I have a feeling I have to...
[ "You are looking for the limit_choices_to parameter.\nExample:\nclass SubItem(models.Model):\n created = models.DateTimeField(default=datetime.now)\n created_by = models.ForeignKey(User,\n limit_choices_to={'group': 'advisors'})\n\n", "I found out from this link that only selecting users in a set gro...
[ 2, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0006466628_django_django_forms_python.txt
Q: python super question I have a syntax question about python's super() and multiple inheritance. Say I have class A and B, both of which have a method hello(). I have a class C that inherits from both A and B, in that order. How do I call the hello() method of B explicitly from C? Seems simple enough, but I can't ...
python super question
I have a syntax question about python's super() and multiple inheritance. Say I have class A and B, both of which have a method hello(). I have a class C that inherits from both A and B, in that order. How do I call the hello() method of B explicitly from C? Seems simple enough, but I can't seem to find the syntax for...
[ "To call B's hello method explicitly from C:\nB.hello(self,...)\n\n", ">>> class A(object):\n def hello(self):\n print \"hello from A\"\n\n>>> class B(object):\n def hello(self):\n print \"hello from B\"\n\n>>> class C(A, B):\n def hello(self):\n print \"hello from C\"\n\n>>> c = C()...
[ 5, 4, 3 ]
[ "Remember that Python calls superclass methods from right to left.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0006472481_python.txt
Q: Problems printing searches not found In the code below, the program is getting string data from the user and converting it to ascii and hex and searching all .log and .txt files in a certain directory for the string in plain string, hex, and ascii values. The program prints the line # , the string type found, and ...
Problems printing searches not found
In the code below, the program is getting string data from the user and converting it to ascii and hex and searching all .log and .txt files in a certain directory for the string in plain string, hex, and ascii values. The program prints the line # , the string type found, and the file path if the string is found. Howe...
[ "Folks, I think user706808 wants to search for all occurrences of searchstring in file and:\n\nfor each occurrence if string IS found in file, then on a per-LINE basis, print lineno, file pathname\nif string is NOT found in file, then on a per-FILE basis print file pathname (but not the contents) and searchstring.\...
[ 1 ]
[]
[]
[ "python", "regex", "text_formatting" ]
stackoverflow_0006424949_python_regex_text_formatting.txt
Q: Getting shogun ML library to work with python I was trying to install shogun on Windows: http://www.shogun-toolbox.org/doc/installation.html but evidently it requires python 2.5 to work. I tried with python 3 and it didn't work. But then python 2.5 no longer exists. Does anybody know how to get it working with py...
Getting shogun ML library to work with python
I was trying to install shogun on Windows: http://www.shogun-toolbox.org/doc/installation.html but evidently it requires python 2.5 to work. I tried with python 3 and it didn't work. But then python 2.5 no longer exists. Does anybody know how to get it working with python without using python 2.5?
[ "You won't get very far trying with Python 3 (which is not fully compatible with Python 2.x).\nFurthermore, the installation instructions say:\n\n\"SHOGUN requires the standard linux\n utils like bash, grep, test, sed, cut,\n ldd, uname gcc g++ cat python\"\n\nsounds like you are out of luck on windows, unless yo...
[ 0, 0 ]
[]
[]
[ "c++", "machine_learning", "python", "shogun" ]
stackoverflow_0006419032_c++_machine_learning_python_shogun.txt
Q: Mechanize Error - Python I am attempting to use mechanize to veiw and collect data from various websites. I have run across an error that states No handlers could be found for logger "mechanize" This error does not give a specific location for where it the error occurred which makes it very difficult to debug. I ...
Mechanize Error - Python
I am attempting to use mechanize to veiw and collect data from various websites. I have run across an error that states No handlers could be found for logger "mechanize" This error does not give a specific location for where it the error occurred which makes it very difficult to debug. I have looked online and have se...
[ "mechanize uses the logging module.\nIf your script does not supply a logging handler, then logging calls from within mechanize can result in this error.\nTo supply a generic handler, try adding\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\nto your script. This will show all logging messages of level...
[ 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0006472531_mechanize_python.txt
Q: Getting visible text from a QTextEdit in PyQt This is related to another question I found here that seems to be inactive for a few months, so I think it's worth asking again. I have created a simple QDialog that has a QTextEdit and a QPushButton. This pops up in my application when a user right-clicks and selects ...
Getting visible text from a QTextEdit in PyQt
This is related to another question I found here that seems to be inactive for a few months, so I think it's worth asking again. I have created a simple QDialog that has a QTextEdit and a QPushButton. This pops up in my application when a user right-clicks and selects the option to "add comments". I want them to be abl...
[ "Objects that are being bound to default arguments are evaluated at the definition time. The function is working correctly, it returns whatever was in the text field when it was executed. Your code simply calls it at the wrong moment. If you want to use lambda, then do:\nself.connect(\n accept_button, QtCore.SIG...
[ 5 ]
[]
[]
[ "pyqt", "python", "qtextedit" ]
stackoverflow_0006472445_pyqt_python_qtextedit.txt
Q: ruby/python learning reference for Windows user I am interested in learning python and ruby, but I use Windows 7. Most online articles I have seen out there are not really helpful to me since they are all explaining about python and ruby in UNIX environment. I'd like to know if there are any good articles/books ab...
ruby/python learning reference for Windows user
I am interested in learning python and ruby, but I use Windows 7. Most online articles I have seen out there are not really helpful to me since they are all explaining about python and ruby in UNIX environment. I'd like to know if there are any good articles/books about Ruby/python programming languages that are more f...
[ "http://docs.python.org/using/windows.html This is from Python's documentation. It has a few links in there to some standard Python resources, e.g. Dive Into Python, which I would recommend.\nhttp://rubyonwindows.blogspot.com/ This blog is an alright resource; pay particular attention to the posts tagged 'faq'.\nFo...
[ 2, 2, 0, 0 ]
[]
[]
[ "python", "ruby", "windows", "windows_7" ]
stackoverflow_0006472661_python_ruby_windows_windows_7.txt
Q: How do I get python's pprint to return a string instead of printing? In other words, what's the sprintf equivalent to pprint? A: The pprint module has a function named pformat, for just that purpose. From the documentation: Return the formatted representation of object as a string. indent, width and depth wil...
How do I get python's pprint to return a string instead of printing?
In other words, what's the sprintf equivalent to pprint?
[ "The pprint module has a function named pformat, for just that purpose.\nFrom the documentation:\n\nReturn the formatted representation of object as a string. indent,\nwidth and depth will be passed to the PrettyPrinter constructor as\nformatting parameters.\n\nExample:\n>>> import pprint\n>>> people = [\n... {...
[ 352, 20, 17, 17, 13 ]
[]
[]
[ "pprint", "pretty_print", "python" ]
stackoverflow_0000521532_pprint_pretty_print_python.txt
Q: Django ModelForm with initial data not shown on redisplay I have a Django ModelForm with some initial data passed to it. Which is working fine so far. But, if the user doesn't fill in all data, or makes another mistake the initial value will not be looked up again on redisplaying the form. Here's a piece of code: ...
Django ModelForm with initial data not shown on redisplay
I have a Django ModelForm with some initial data passed to it. Which is working fine so far. But, if the user doesn't fill in all data, or makes another mistake the initial value will not be looked up again on redisplaying the form. Here's a piece of code: class TrainingAddForm(forms.ModelForm): class Meta: model =...
[ "I'm not sure I understand the logic of your form or your view.\nYou've included the task field, yet disabled the field. With the task field disabled, the value isn't going to be in the request.POST collection.\nIn your view, you're passing the form the task_id parameter as the initial data, and if the request.meth...
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0006472269_django_django_forms_python.txt
Q: PyQt (PySide), WebKit and exposing methods from/to Javascript I am planning to use PyQt to control an embedded WebKit browser on the server side. I have some inherit application logic in Javascript in the HTML page running inside WebKit. How could I communicate from the host process (Python, PyQt) with Javascript,...
PyQt (PySide), WebKit and exposing methods from/to Javascript
I am planning to use PyQt to control an embedded WebKit browser on the server side. I have some inherit application logic in Javascript in the HTML page running inside WebKit. How could I communicate from the host process (Python, PyQt) with Javascript, so that I can call Javascript functions inside the page Python m...
[ "The following source code should be helpful:\nimport sys\nfrom PyQt4.QtCore import QObject, pyqtSlot\nfrom PyQt4.QtGui import QApplication\nfrom PyQt4.QtWebKit import QWebView\n\nhtml = \"\"\"\n<html>\n<body>\n <h1>Hello!</h1><br>\n <h2><a href=\"#\" onclick=\"printer.text('Message from QWebView')\">QObject ...
[ 28 ]
[]
[]
[ "javascript", "pyqt", "pyside", "python", "webkit" ]
stackoverflow_0006447011_javascript_pyqt_pyside_python_webkit.txt
Q: Getting multiple matches from regex pattern in Python I'm writing a regular expression to parse arguments in a fashion similar to shell arguments, with spaces and quoted strings as the delimiters, as well as backslash escaping. This seems to work on RegexPal: (?:(["'])(?:\\(?:\\\\)?\1|\\\\|.)*?\1|(?:\\(?:\\\\)?\s|...
Getting multiple matches from regex pattern in Python
I'm writing a regular expression to parse arguments in a fashion similar to shell arguments, with spaces and quoted strings as the delimiters, as well as backslash escaping. This seems to work on RegexPal: (?:(["'])(?:\\(?:\\\\)?\1|\\\\|.)*?\1|(?:\\(?:\\\\)?\s|\\\\|\S)+) Here is a more readable version of that: (?:(["...
[ "It looks like everything is inside a non-capturing group. So you get matches, just no matching content.\n" ]
[ 2 ]
[]
[]
[ "backreference", "backslash", "escaping", "python", "regex" ]
stackoverflow_0006473276_backreference_backslash_escaping_python_regex.txt
Q: Python readline() on the Mac New to python and trying to learn the ropes of file i/o. Working with pulling lines from a large (2 million line) file in this format: 56fr4 4543d 4343d hirh3 I've been reading that readline() is best because it doesn't pull the whole file into memory. But when I try to read the docu...
Python readline() on the Mac
New to python and trying to learn the ropes of file i/o. Working with pulling lines from a large (2 million line) file in this format: 56fr4 4543d 4343d hirh3 I've been reading that readline() is best because it doesn't pull the whole file into memory. But when I try to read the documentation on it, it seems to be Un...
[ "You don't need readline:\nwith open(\"data.txt\") as file:\n for line in file:\n # do stuff with line\n\nThis will read the entire file line-by-line, but not all at once (so you don't need all the memory). If you want to abort reading the file, because you found the line you want, use break to terminate ...
[ 12, 0 ]
[]
[]
[ "file_io", "macos", "python" ]
stackoverflow_0006472856_file_io_macos_python.txt
Q: Basic python file-io variables with enumerate New to python and trying to learn the ropes of file i/o. I am working with pulling lines from a large (2 million line) file in this format: 56fr4 4543d 4343d 5irh3 Here is the function I'm using to return a code: def getCode(i): with open("test.txt") as f: ...
Basic python file-io variables with enumerate
New to python and trying to learn the ropes of file i/o. I am working with pulling lines from a large (2 million line) file in this format: 56fr4 4543d 4343d 5irh3 Here is the function I'm using to return a code: def getCode(i): with open("test.txt") as f: for index, line in enumerate(f): if in...
[ "code = line.strip()\nwill assign code to the line number that is equal to i while removing the trailing new line.\nyou also need to update your code a bit\n def getCode(i):\n with open('temp.txt', 'r') as f:\n for index, line in enumerate(f):\n if index == i:\n ...
[ 13, 8 ]
[]
[]
[ "enumerate", "file_io", "python" ]
stackoverflow_0006473283_enumerate_file_io_python.txt
Q: urllib2.urlopen returning an object with no info() or geturl() methods I am running Python 2.7.1 and am trying to use the urllib2 module to access some webpages. Per the Python documentation, urllib2.urlopen(): This function returns a file-like object with two additional methods, geturl() and info() However, ...
urllib2.urlopen returning an object with no info() or geturl() methods
I am running Python 2.7.1 and am trying to use the urllib2 module to access some webpages. Per the Python documentation, urllib2.urlopen(): This function returns a file-like object with two additional methods, geturl() and info() However, it indicates there are no such methods when I try to access info() in the la...
[ "The issue is with the fact that you have install_opener receive an HTTPNtlmAuthHandler. When that class handles the request, it returns an HTTPResponse instead of the standard 'file like object'.\nTo see the source, go here.\n" ]
[ 1 ]
[]
[]
[ "http", "httpresponse", "python", "urllib2" ]
stackoverflow_0006473409_http_httpresponse_python_urllib2.txt
Q: How do I read the output for a file spawned through subprocess.popen in Python? I've started playing around with writing a GUI for a bitcoin miner and right now I just have a window with a "Start" and "Stop" button and I've got those working so you click start and it uses self.p = subprocess.Popen(args) to open th...
How do I read the output for a file spawned through subprocess.popen in Python?
I've started playing around with writing a GUI for a bitcoin miner and right now I just have a window with a "Start" and "Stop" button and I've got those working so you click start and it uses self.p = subprocess.Popen(args) to open the process and self.p.terminate() to end the process. My next step is to read the spee...
[ "Use Popen.communicate to read the output. For example.\nimport subprocess\n\np = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n# returns a tuple containing the the stdout and stderr of the program\nres, err = p.communicate() \n\n", "you call:\nout, err = p.communicate()\n\n" ]
[ 2, 1 ]
[]
[]
[ "bitcoin", "python", "subprocess" ]
stackoverflow_0006473753_bitcoin_python_subprocess.txt
Q: Turn SSLchecking off in M2Crypto in Python Is there a way to turn off SSL checking so that WrongHost Exceptions are not generated when using SOAPpy in python. A: You can disable all peer certificate checks in M2Crypto like that: from M2Crypto import SSL, httpslib context = SSL.Context("sslv3") # Disable certif...
Turn SSLchecking off in M2Crypto in Python
Is there a way to turn off SSL checking so that WrongHost Exceptions are not generated when using SOAPpy in python.
[ "You can disable all peer certificate checks in M2Crypto like that:\nfrom M2Crypto import SSL, httpslib\n\ncontext = SSL.Context(\"sslv3\")\n\n# Disable certificate checking\ncontext.set_verify(0, depth = 0)\n\nconnection = httpslib.HTTPSConnection(\"somehostname\", 443, ssl_context=context)\n\n# Hack (!!!) for dis...
[ 5, 0 ]
[]
[]
[ "python", "soappy", "ssl" ]
stackoverflow_0002328265_python_soappy_ssl.txt
Q: Reading incoming data from barcode I have to read incoming data from a barcode scanner using pyserial. Then I have to store the contents into a MySQL database. I have the database part but not the serial part. can someone show me examples of how to do this. I'm using a windows machine. A: You will find it easier...
Reading incoming data from barcode
I have to read incoming data from a barcode scanner using pyserial. Then I have to store the contents into a MySQL database. I have the database part but not the serial part. can someone show me examples of how to do this. I'm using a windows machine.
[ "You will find it easier to use a USB scanner. These will decode the scan, and send it as if it were typed on the keyboard, and entered with a trailing return. \nThe barcode is typically written with leading and trailing * characters, but these are not sent with the scan. \nThus you print \"*AB123*\" using a 3 of ...
[ 1 ]
[]
[]
[ "pyserial", "python" ]
stackoverflow_0006471569_pyserial_python.txt
Q: Good patterns or apps to use when writing django code that will serve multiple, subtly different sites I'm heading into working on a project that will be a single codebase that will manage multiple, slightly different sites. I've found a few things, which I'll put in the answers, but I'd like to see if people have...
Good patterns or apps to use when writing django code that will serve multiple, subtly different sites
I'm heading into working on a project that will be a single codebase that will manage multiple, slightly different sites. I've found a few things, which I'll put in the answers, but I'd like to see if people have other ideas, especially for how to manage the minor form, model, and view differences that crop up.
[ "I'm hoping for better answers, but I wanted to put these in here in case I don't get them, or to give people looking for the same info the few links I've found. =)\nhttp://www.huyng.com/archives/franchising-running-multiple-sites-from-one-django-codebase-2/394/\nand \nhttp://blog.uysrc.com/2011/03/23/serving-multi...
[ 0 ]
[]
[]
[ "design_patterns", "django", "python" ]
stackoverflow_0006474075_design_patterns_django_python.txt
Q: thread module question so i have the code: def Listen(filepath): def play(filepath): def play_music(music_file): """ stream music with mixer.music module in blocking manner this will stream the sound from disk while playing """ ...
thread module question
so i have the code: def Listen(filepath): def play(filepath): def play_music(music_file): """ stream music with mixer.music module in blocking manner this will stream the sound from disk while playing """ clock = pygame...
[ "Read the TypeError message: \"2nd arg must be a tuple.\" You have (filepath). This is not a tuple. A tuple of one element should be written: (filepath,) to disambiguate.\n" ]
[ 25 ]
[]
[]
[ "python" ]
stackoverflow_0006474509_python.txt
Q: How to install h5py (+numpy+libhdf5+...) as non-root on a Debian Linux system I need to install the h5py Python module, and all its absent dependencies, on a Debian Linux system. This task is complicated by the following: I don't have any superuser privileges on this system (no sudo, no root password, etc.); the...
How to install h5py (+numpy+libhdf5+...) as non-root on a Debian Linux system
I need to install the h5py Python module, and all its absent dependencies, on a Debian Linux system. This task is complicated by the following: I don't have any superuser privileges on this system (no sudo, no root password, etc.); the rest of the code I am using requires version 2.7 of Python, which is not the defau...
[ "This should be possible using virtualenv. You would create a virtualenv like this (at the command line):\nvirtualenv -p /opt/python-2.7.1 mypythonenv\n\nLast bit is the name of a new folder for the environment to go in.\nThen:\ncd mypythonenv\nsource bin/activate\n\nThen you can install whatever Python modules you...
[ 2, 1 ]
[]
[]
[ "debian", "hdf5", "numpy", "python", "scipy" ]
stackoverflow_0006442754_debian_hdf5_numpy_python_scipy.txt
Q: Inherit another object's methods f = open('bobby_g.txt', 'w') f.write('Hey bobby!') f.close() class BobFile: def __init__(self, x): self = open(x, 'r') a = BobFile('bobby_g.txt') print a.read() a.close() I don't want to subclass the 'file' object, I want to create a BobFile object that then becomes ...
Inherit another object's methods
f = open('bobby_g.txt', 'w') f.write('Hey bobby!') f.close() class BobFile: def __init__(self, x): self = open(x, 'r') a = BobFile('bobby_g.txt') print a.read() a.close() I don't want to subclass the 'file' object, I want to create a BobFile object that then becomes another object(a file object) (and in...
[ "attribute delegation?\nclass BobFile:\n def __init__(self, x):\n self.__file = open(x,'r')\n def __getattr__(self, name):\n return getattr(self.__file, name)\n\na = BobFile('/dev/random')\nprint a.read(20)\na.close()\n\n", "What exactly are you trying to achieve? You can't create an object th...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006474724_python.txt
Q: python socket - how to save stream to file I have a server that sends data out to a port. In python, how can I create a script that connects to that socket, and save the data stream locally? A: By a simple client socket program? import socket HOST = 'yourhost' # The remote host PORT = 101 # The s...
python socket - how to save stream to file
I have a server that sends data out to a port. In python, how can I create a script that connects to that socket, and save the data stream locally?
[ "By a simple client socket program?\nimport socket\n\nHOST = 'yourhost' # The remote host\nPORT = 101 # The same port as used by the server\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((HOST, PORT))\ndata = s.recv(1024)\ns.close()\nwith open('yourfile','w') as f:\n f.write(da...
[ 13 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0006474817_python_sockets.txt
Q: Efficiently re-shaping a numpy ndarray from 2-D to 3-D based on elements from 2-D I'm working with DICOM files that contain image data. I am using pydicom to read the metadata from the .DCM file. Now, the pixel data that is extracted from the .DCM file is returned as a 2 dimensional numpy ndarray. The particular...
Efficiently re-shaping a numpy ndarray from 2-D to 3-D based on elements from 2-D
I'm working with DICOM files that contain image data. I am using pydicom to read the metadata from the .DCM file. Now, the pixel data that is extracted from the .DCM file is returned as a 2 dimensional numpy ndarray. The particular DICOM files I am working with save a single intensity value per pixel. After I perfor...
[ "So what you want, of course, is an array of shape m x n x r, where r is the tuple size. \nOne way to do this, which seems to me the most straightforward, is to: (i) explicitly create a 3D grid array, identical to your original 2D arrayexcept for addition of the last dimension, r, which has been added, and then; (...
[ 2 ]
[]
[]
[ "matrix", "numpy", "pydicom", "python" ]
stackoverflow_0006473630_matrix_numpy_pydicom_python.txt
Q: How to bind the root to call method inside a class This is the basic layout of my program: class App(CheckInfo): def __init__(self, master): CheckInfo.__init__(self) master.title("Example") ..... After that I have i method (inside the class App) that goes like this: def moveIt(self...
How to bind the root to call method inside a class
This is the basic layout of my program: class App(CheckInfo): def __init__(self, master): CheckInfo.__init__(self) master.title("Example") ..... After that I have i method (inside the class App) that goes like this: def moveIt(self): print "It doesnt work" At the bottom (outsid...
[ "Your experiments may not be working because a frame by default does not have the keyboard focus. Try adding root.focus() so that keyboard events are directed to the root window.\nThe other part of your question has to do with how to do the binding. Since moveIt is a method of the class App and 'app' is an instance...
[ 1 ]
[]
[]
[ "bind", "python", "tkinter", "user_interface" ]
stackoverflow_0006473993_bind_python_tkinter_user_interface.txt
Q: How to make Python 2.x Unicode strings not print as u'string'? I'm currently testing a webservice that returns large amounts of JSON data in the form of dictionaries. The keys and values for those dictionaries are all unicode strings, and thus they print like {u'key1':u'value', u'key2':u'value2'} when printed t...
How to make Python 2.x Unicode strings not print as u'string'?
I'm currently testing a webservice that returns large amounts of JSON data in the form of dictionaries. The keys and values for those dictionaries are all unicode strings, and thus they print like {u'key1':u'value', u'key2':u'value2'} when printed to the screen in the interactive interpreter. Now imagine that this i...
[ "if it's json you want, just print json:\n>>> import json\n>>> print json.dumps({u'key1':u'value', u'key2':u'value2'}, indent=4)\n{\n \"key2\": \"value2\", \n \"key1\": \"value\"\n}\n\n", "Why don't you create your own function to print the dictionary? Python's default format is OK for fast, easy debugging,...
[ 19, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0006474365_python_unicode.txt
Q: Save state in file on cleanup using __del__? I have a class that looks like this: class A: def __init__(self, filename, sources): # gather info from file # info is updated during lifetime of the object def close(self): # save info back to file Now, this is in a server program, so ...
Save state in file on cleanup using __del__?
I have a class that looks like this: class A: def __init__(self, filename, sources): # gather info from file # info is updated during lifetime of the object def close(self): # save info back to file Now, this is in a server program, so it might be shutdown without prior notice by a sig...
[ "Waiting until later is just not the strategy to making something reliable. In fact, you have to go the complete opposite direction. As soon as you know something that should be persistent, you need to take action to persist it. In fact, if you want to make it reliable, you need to first write to disk the steps ...
[ 2, 1, 1, 1 ]
[]
[]
[ "del", "python", "resource_cleanup" ]
stackoverflow_0006474415_del_python_resource_cleanup.txt
Q: Global variable Python classes What is the proper way to define a global variable that has class scope in python? Coming from a C/C++/Java background I assume that this is correct: class Shape: lolwut = None def __init__(self, default=0): self.lolwut = default; def a(self): print self...
Global variable Python classes
What is the proper way to define a global variable that has class scope in python? Coming from a C/C++/Java background I assume that this is correct: class Shape: lolwut = None def __init__(self, default=0): self.lolwut = default; def a(self): print self.lolwut def b(self): sel...
[ "What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute\nclass Shape(object):\n lolwut = 1\n\nshape = S...
[ 95 ]
[]
[]
[ "global_variables", "python" ]
stackoverflow_0006475321_global_variables_python.txt
Q: ezyang / git-ftp on Windows I have been trying to install git-ftp from https://github.com/ezyang/git-ftp on my windows. I know most of git-ftp need cygwin or just cant be install on windows but, since its coded in Python and you can install a Python interpreter on windows, i tough i could install it. I installed P...
ezyang / git-ftp on Windows
I have been trying to install git-ftp from https://github.com/ezyang/git-ftp on my windows. I know most of git-ftp need cygwin or just cant be install on windows but, since its coded in Python and you can install a Python interpreter on windows, i tough i could install it. I installed Python 3.2, added it to my path. T...
[ "git-ftp is written Python 2, and is not, as it stands, compatible with Python 3. Install an earlier version of the interpreter.\nEdit. You need to install the git-python library. Since the easiest way to install libraries is easy_install, you should set it up with the instructions here: http://pypi.python.org/pypi...
[ 4 ]
[]
[]
[ "git", "git_ftp", "python", "windows" ]
stackoverflow_0006473443_git_git_ftp_python_windows.txt
Q: Python/Django - initial/default admin page After a user has logged into the admin interface is it possible to redirect them to a specific page? I want to redirect to the list of entries for a particular model. I'm using Django 1.3 Cheers! A: You can set the default redirect url (on login) in your settings.py LOG...
Python/Django - initial/default admin page
After a user has logged into the admin interface is it possible to redirect them to a specific page? I want to redirect to the list of entries for a particular model. I'm using Django 1.3 Cheers!
[ "You can set the default redirect url (on login) in your settings.py\nLOGIN_REDIRECT_URL = \"/admin/mymodel/\"\n\nhttps://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#login-redirect-url\n", "Look at ticket 14510 .\nSeems django admin doesn't support LOGIN_REDIRECT_URL settings and you should subclass ...
[ 4, 3 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006264551_django_django_admin_python.txt
Q: How can I access variable values in a SWF on a running webpage? I've been using a combination of Sikuli and Python to create a very low-level script that automates playing various levels of a Flash game, but I can only do so much through visual image recognition. What I want to do is be able to access variables wi...
How can I access variable values in a SWF on a running webpage?
I've been using a combination of Sikuli and Python to create a very low-level script that automates playing various levels of a Flash game, but I can only do so much through visual image recognition. What I want to do is be able to access variables within the running flash game, as opposed to accessing static data via ...
[ "Without the source of the swf you can't. You can decompile the swf and modify the code to provide you with the data.\n" ]
[ 2 ]
[]
[]
[ "flash", "python" ]
stackoverflow_0006475482_flash_python.txt
Q: Why are some of my html tags following css and others not? So I have a normal html file with tags like and etc. I have this css file: html, body { margin:0; padding:0; backgound-color:blue; } a { /* Note: For whatever reason this does not apply to templates/tags/naviagtion.html */ text-dec...
Why are some of my html tags following css and others not?
So I have a normal html file with tags like and etc. I have this css file: html, body { margin:0; padding:0; backgound-color:blue; } a { /* Note: For whatever reason this does not apply to templates/tags/naviagtion.html */ text-decoration: none; } For whatever reason when this is applied to my...
[ "Spelling error fixed. Also css is case sensitive.\nhtml, body {\n margin:0; \n padding:0;\n background-color:blue; \n}\n\na{\n /* Note: For whatever reason this does not apply to templates/tags/naviagtion.html */\n text-decoration: none;\n}\n\nYou said text-decoration:none is not getting applied.\nD...
[ 2, 1, 0, 0 ]
[]
[]
[ "css", "django", "html", "python" ]
stackoverflow_0006476330_css_django_html_python.txt
Q: Python Dictionary of Dictionary with condition I am working on a function. If "source" is found in "d" then it will be added to it's value of dictionary object, otherwise it will be added. For example in this case. "a" is added twice but "b" is added once. I would like to get output as below(last line) Thank you....
Python Dictionary of Dictionary with condition
I am working on a function. If "source" is found in "d" then it will be added to it's value of dictionary object, otherwise it will be added. For example in this case. "a" is added twice but "b" is added once. I would like to get output as below(last line) Thank you. def adder(source,dest,weight): """""" if __nam...
[ "A dictionary of dictionaries is just a dictionary of tuples. You could implement adder like this:\n#The dictionary we will be adding to\nd = {}\n\ndef adder(source, dest, weight):\n d[(source, dest)] = weight\n\nThe high brow reason for this is that in any category with products, Hom(C, Hom(B, A)) is naturally...
[ 2, 1, 0 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0006476457_python_scripting.txt
Q: stripping inline tags with python's lxml I have to deal with two types of inline tags in xml documents. The first type of tags enclose text that I want to keep in-between. I can deal with this with lxml's etree.tostring(element, method="text", encoding='utf-8') The second type of tags include text that I don't wa...
stripping inline tags with python's lxml
I have to deal with two types of inline tags in xml documents. The first type of tags enclose text that I want to keep in-between. I can deal with this with lxml's etree.tostring(element, method="text", encoding='utf-8') The second type of tags include text that I don't want to keep. How can I get rid of these tags an...
[ "I think that strip_tags and strip_elements are what you want in each case. For example, this script:\nfrom lxml import etree\n\ntext = \"<x>hello, <z>keep me</z> and <y>ignore me</y>, and here's some <y>more</y> text</x>\"\n\ntree = etree.fromstring(text)\n\nprint etree.tostring(tree, pretty_print=True)\n\n# Remo...
[ 13 ]
[]
[]
[ "lxml", "python", "tags", "xml" ]
stackoverflow_0006476548_lxml_python_tags_xml.txt
Q: Returning the function that called this function Ok, so, I am writing a Python(v2.7) code with a function to display an error message. But there are a couple of other functions which rely on this original error-checking function. Now, when this error-checking function is called, and if there is an error, I wish to...
Returning the function that called this function
Ok, so, I am writing a Python(v2.7) code with a function to display an error message. But there are a couple of other functions which rely on this original error-checking function. Now, when this error-checking function is called, and if there is an error, I wish to display an error, and call the function that called t...
[ "Implicitly recalling the calling function is bound to lead to infinite loops, bugs (unless you make absolutely sure all methods calling error are idempotent, even when prematurely aborted), confusion, and utterly unpythonic anyways. What you're looking for is just regular error handling:\ndef f2():\n try:\n ...
[ 4, 3 ]
[]
[]
[ "function", "python", "return" ]
stackoverflow_0006477113_function_python_return.txt
Q: gtk.StatusIcon with double click I'm using python GTK under Gnome (Gnome 3 in Fedora 15). I'd like to catch events when the user double clic on the icon in the tray area. I found that "activate" signals is called when the user do a single clic, but can't find the signal or a proper way to call a method when the us...
gtk.StatusIcon with double click
I'm using python GTK under Gnome (Gnome 3 in Fedora 15). I'd like to catch events when the user double clic on the icon in the tray area. I found that "activate" signals is called when the user do a single clic, but can't find the signal or a proper way to call a method when the user double clic on it. How can I do ? T...
[ "You can't. Gtk+ itself doesn't even know if it was single or double clicked.\nFrom the Gtk+ documentation about the ::activate signal:\n\nGets emitted when the user activates the status icon. If and how status icons can activated is platform-dependent.\n\nInterestingly Qt knows about this (it has Trigger and Doubl...
[ 3 ]
[]
[]
[ "gtk", "icons", "python", "status" ]
stackoverflow_0006370804_gtk_icons_python_status.txt
Q: Creating images with nice tables I have some data that I would like to represent as a table. Is there a python library that will allow easy generation of an image with a nice looking table in it? I know that matplotlib does not have this feature, but maybe some other library has... A: Take a look at Google Chart...
Creating images with nice tables
I have some data that I would like to represent as a table. Is there a python library that will allow easy generation of an image with a nice looking table in it? I know that matplotlib does not have this feature, but maybe some other library has...
[ "Take a look at Google Chart API.\nAlso a python wrapper for it: pygooglechart\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006477272_python.txt
Q: Replacement for for... if array iteration I love list comprehensions in Python, because they concisely represent a transformation of a list. However, in other languages, I frequently find myself writing something along the lines of: foreach (int x in intArray) if (x > 3) //generic condition on x x++ //d...
Replacement for for... if array iteration
I love list comprehensions in Python, because they concisely represent a transformation of a list. However, in other languages, I frequently find myself writing something along the lines of: foreach (int x in intArray) if (x > 3) //generic condition on x x++ //do other processing This example is in C#, wher...
[ "The increment in the original foreach loop will not affect the contents of the array, the only way to do this remains a for loop:\nfor(int i = 0; i < intArray.Length; ++i)\n{\n if(intArray[i] > 3) ++intArray[i];\n}\n\nLinq is not intended to modify existing collections or sequences. It creates new sequences bas...
[ 7, 2, 1, 0, 0 ]
[ "Depends on the language and what you need to do, a \"map\" as it's called in many languages could be what you're looking for. I don't know C#, but according to this page, .NET 2.0 calls map \"ConvertAll\".\nThe meaning of \"map\" is pretty simple - take a list, and apply a function to each element of it, returning...
[ -1 ]
[ ".net", "arrays", "iteration", "loops", "python" ]
stackoverflow_0000013396_.net_arrays_iteration_loops_python.txt
Q: SSL in Python: Why it doesn't send certificate to server? I'm writing some software that is supposed to acquire information from SSL-secured web page. Below there's piece of code I use to connect to server. s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) ssl_sock = ssl.wrap_socket ( s, ca_certs = '/...
SSL in Python: Why it doesn't send certificate to server?
I'm writing some software that is supposed to acquire information from SSL-secured web page. Below there's piece of code I use to connect to server. s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) ssl_sock = ssl.wrap_socket ( s, ca_certs = '/home/stilz/Desktop/Certyfikaty/GLOWNE_CA.cer', cert_reqs = ...
[ "First of all, you need to determine if you need to authenticate yourself on the server (certificate is sent to the server only in this case) or you need to validate server's authenticity (in which case the certificate is not sent to the server).\nNow about issues in your code:\nCase 1: you don't need to authentica...
[ 1, 0 ]
[]
[]
[ "handshake", "python", "ssl", "ssl_certificate", "x509" ]
stackoverflow_0006477586_handshake_python_ssl_ssl_certificate_x509.txt
Q: Data too long Mysql and python MYSQL Error , while sending from android to python the GPS Latitude and longititude enter code here def pacman(self): while True: while True: try: x1=self.sockfd.recv(2048) print x1 print "\n hi" conn.begin() ...
Data too long Mysql and python
MYSQL Error , while sending from android to python the GPS Latitude and longititude enter code here def pacman(self): while True: while True: try: x1=self.sockfd.recv(2048) print x1 print "\n hi" conn.begin() x.execute("UPDATE locatio...
[ "Try with varchar 256 it looks like a mysql error\n", "Change your column definition so all possible values fit in it.\n" ]
[ 3, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006477995_mysql_python.txt
Q: Display special characters when using print statement I would like to display the escape characters when using print statement. E.g. a = "Hello\tWorld\nHello World" print a Hello World Hello World I would like it to display: "Hello\tWorld\nHello\sWorld" A: Use repr: a = "Hello\tWorld\nHello World" print(r...
Display special characters when using print statement
I would like to display the escape characters when using print statement. E.g. a = "Hello\tWorld\nHello World" print a Hello World Hello World I would like it to display: "Hello\tWorld\nHello\sWorld"
[ "Use repr:\na = \"Hello\\tWorld\\nHello World\"\nprint(repr(a))\n# 'Hello\\tWorld\\nHello World'\n\nNote you do not get \\s for a space. I hope that was a typo...?\nBut if you really do want \\s for spaces, you could do this:\nprint(repr(a).replace(' ',r'\\s'))\n\n", "Do you merely want to print the string that w...
[ 198, 19 ]
[]
[]
[ "character", "escaping", "printing", "python" ]
stackoverflow_0006477823_character_escaping_printing_python.txt
Q: django form to add item returning 'NoneType' object is not callable error My add_player view takes a team_season_id parameter and displays an unbound form. def add_player( request, team_season_id ): team_season = get_object_or_404( TeamSeasonConference, pk=team_season_id ) player_form = PlayerForm() ...
django form to add item returning 'NoneType' object is not callable error
My add_player view takes a team_season_id parameter and displays an unbound form. def add_player( request, team_season_id ): team_season = get_object_or_404( TeamSeasonConference, pk=team_season_id ) player_form = PlayerForm() return render_to_response( 'backoffice/organization/add_player.html', { ...
[ "You're using ModelForm with no model associated with it. Create an inner Meta class with model attribute, as per documentation:\nclass PlayerForm(forms.ModelForm):\n class Meta:\n model = models.Player # or whatever\n\nAlso, don't override save if you don't really need it.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006477931_django_python.txt
Q: unable to get sys.argv[1] value I am trying to execute a very simple script. It only prints the first argument passed. The code is import sys def check(argument): '''Open, read, and print a file.''' print argument if __name__ == "__main__": check(sys.argv[1]) however when i execute from command line, i alw...
unable to get sys.argv[1] value
I am trying to execute a very simple script. It only prints the first argument passed. The code is import sys def check(argument): '''Open, read, and print a file.''' print argument if __name__ == "__main__": check(sys.argv[1]) however when i execute from command line, i always get this error C:\>sample.py myna...
[ "Your script is fine, the way you execute it is wrong.\nC:>sample.py myname\n\nThis uses windows file extension detecting to launch it with the python interpreter. Arguments might get lost in this way. Try executing it like this:\nC:>python sample.py myname\n\nAlso, see issue 7936.\n", "This might be a Windows is...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006478120_python.txt
Q: How can I control results returned by Python's re.findall() on an html string? I'm trying to capture all instances of "Catalina 320" SO LONG as they occur before the "These boats" string (see generic sample below). I have the code to capture ALL instances of "Catalina 320" but I can't figure out how to stop it at ...
How can I control results returned by Python's re.findall() on an html string?
I'm trying to capture all instances of "Catalina 320" SO LONG as they occur before the "These boats" string (see generic sample below). I have the code to capture ALL instances of "Catalina 320" but I can't figure out how to stop it at the "These boats" string. resultsArray = re.findall(r'<tag>(Catalina 320)</tag>', st...
[ "You could solve this with a regular expression, but regex isn't required based on the way that you stated problemSee End Note 1.\nYou should use lxml to parse this...\nimport lxml.etree as ET\nfrom lxml.etree import XMLParser\n\nresultsArray = []\nparser = XMLParser(ns_clean=True, recover=True)\ntree = ET.parse('f...
[ 3, 2, 0 ]
[ "With file of name 'foo.html' containing\n <body>\n<tag>Blah blah blah</tag>\n <tag>**Catalina 320**</tag>\n <tag>Blah<tag>\n <td>**Catalina 320**</td>\n </tag>Blah Blah </tag>\n <tag>**These boats** are fully booked for the day</tag>\n <tag>Blah blah blah</tag>\n <tag>Catalina 320</tag>\n <ta...
[ -1 ]
[ "html", "lxml", "python", "regex" ]
stackoverflow_0006476364_html_lxml_python_regex.txt
Q: Get All Domain users in Google App Engine I want to get the list of all the users for the domain on a GAE app (using python). When I hit this URL https://apps-apis.google.com/a/feeds/domain/user/2.0 . I get an authorization error. How can I authenticate for this GET hit. A: You'll need to use the Provisioning AP...
Get All Domain users in Google App Engine
I want to get the list of all the users for the domain on a GAE app (using python). When I hit this URL https://apps-apis.google.com/a/feeds/domain/user/2.0 . I get an authorization error. How can I authenticate for this GET hit.
[ "You'll need to use the Provisioning API, and you'll need to authenticate via OAuth first\n", "To expand on the answer from Chris, prepare for a bit of pain around authentication. You have four options for read-only access, and one if you need read/write: \nMarketplace authorization: if your app is on the Google...
[ 2, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006441575_google_app_engine_python.txt
Q: What is a reasonable timeout for checking if a server is online? I have to query ~10000 gameservers through an UDP protocol to check if they are online on a server every 15 minutes. My code is working, but servers that are offline block threads slowing progress down enormously. I use 20 threads, more will cause th...
What is a reasonable timeout for checking if a server is online?
I have to query ~10000 gameservers through an UDP protocol to check if they are online on a server every 15 minutes. My code is working, but servers that are offline block threads slowing progress down enormously. I use 20 threads, more will cause the UDP sockets of Python to slow down to a crawl. Currently I'm using a...
[ "You don't have to use synchronous communication (i.e. send packet, block and wait for results), especially not if you're using UDP. Just have one thread send out pings, and another one constantly receiving pongs on the same socket. If you have to do complicated processing with the results, you may want to use anot...
[ 1 ]
[]
[]
[ "python", "settimeout", "udp" ]
stackoverflow_0006478288_python_settimeout_udp.txt
Q: Extracting compressed files The following code allows me to extract .tgz files. However, it stops extracting after about two levels down; there are other subfolders that have .tgz files that need extracting. Additionally, when I extract a file, I have to manually move it to another path or it will get overwritten ...
Extracting compressed files
The following code allows me to extract .tgz files. However, it stops extracting after about two levels down; there are other subfolders that have .tgz files that need extracting. Additionally, when I extract a file, I have to manually move it to another path or it will get overwritten by other .tgz files that I extrac...
[ "If I have not wrongly misinterpreted your question, then here is what you want to do - \n\nExtract a .tgz file which may have\nmore .tgz files within it that needs further\nextraction (and so on..) \nWhile extracting, you need to be careful that you are not replacing an already existing directory in the folder.\n...
[ 5 ]
[]
[]
[ "compression", "python", "tar" ]
stackoverflow_0006077222_compression_python_tar.txt
Q: Python. What is the name of this loop I have some code: ... reader.loop(0, callback) ... (from here http://breakingcode.wordpress.com/2010/04/02/using-impacketpcapy-with-python-2-6-on-windows/) How this "loop" named and where i can read about it or how to break that "loop" (how it works at all). Thanx. A: loop ...
Python. What is the name of this loop
I have some code: ... reader.loop(0, callback) ... (from here http://breakingcode.wordpress.com/2010/04/02/using-impacketpcapy-with-python-2-6-on-windows/) How this "loop" named and where i can read about it or how to break that "loop" (how it works at all). Thanx.
[ "loop is not a keyword or other special construct in Python.\nreader simply has a member function called loop that takes two parameters. To find out what this loop member function does, check what kind of object reader is and look for loop in that class' documentation.\n" ]
[ 6 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0006478412_loops_python.txt
Q: Multiple Database calls in an asynchronous request with Tornado I am currently using Tornado and asyncmongo to create a website that accesses a mongodb. Everything is working great except when I need to make multiple requests to mongodb within in a single request to my handler. I would like to keep all my database...
Multiple Database calls in an asynchronous request with Tornado
I am currently using Tornado and asyncmongo to create a website that accesses a mongodb. Everything is working great except when I need to make multiple requests to mongodb within in a single request to my handler. I would like to keep all my database call asynchronous so that there is no blocking on the server. How ca...
[ "Have each request trigger a different callback?\ne.g. (I didn't test this, and I'm not familiar with asyncmongo, so it probably contains errors):\nimport asyncmongo\nimport tornado.web\n\nclass Handler(tornado.web.RequestHandler):\n\n @tornado.web.asynchronous\n def get(self, id):\n self.id = id\n ...
[ 4 ]
[]
[]
[ "asynchronous", "mongodb", "python", "tornado" ]
stackoverflow_0006475825_asynchronous_mongodb_python_tornado.txt
Q: Django, Models, and Apps I'm new to Django and MVT, so I apologize if this is a silly question. I've looked over some similar questions but am looking for a little additional clarity and whether I'm even attempting to do the right thing. Here's a simplified version of what I'm working on. Let's say I'm designing a...
Django, Models, and Apps
I'm new to Django and MVT, so I apologize if this is a silly question. I've looked over some similar questions but am looking for a little additional clarity and whether I'm even attempting to do the right thing. Here's a simplified version of what I'm working on. Let's say I'm designing a Django interface to a pre-exi...
[ "No, you do not need to create a separate app for each model. You should create an application for each distinct set of functionality in your project. Since you're just learning, you should create one application (with the name of your project) and use that to learn. \nAs for the models, they are just a representat...
[ 3 ]
[]
[]
[ "django", "model_view_controller", "python" ]
stackoverflow_0006478532_django_model_view_controller_python.txt
Q: How to apply a logical operator to all elements in a python list I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic. def apply_and(alist): if len(alist) > 1: return alist[0] and apply_and(alist[1:]) else: return a...
How to apply a logical operator to all elements in a python list
I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic. def apply_and(alist): if len(alist) > 1: return alist[0] and apply_and(alist[1:]) else: return alist[0] Any suggestions on how to make it more pythonic appreciated.
[ "Logical and across all elements in a_list:\nall(a_list)\n\nLogical or across all elements in a_list:\nany(a_list)\n\n\nIf you feel creative, you can also do:\nimport operator\ndef my_all(a_list):\n return reduce(operator.and_, a_list, True)\n\ndef my_any(a_list):\n return reduce(operator.or_, a_list, False)\n\nk...
[ 212, 34, 17, 11, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001790520_python.txt
Q: Keeping a process open and communicating with it in Python I am doing some iterations using python script. What I do is something like this. python exec.py variables.in.1 output.out.1 Here 1 is the iteration number. Now what this does is, it calls an executable using the values in the variables file and then the ...
Keeping a process open and communicating with it in Python
I am doing some iterations using python script. What I do is something like this. python exec.py variables.in.1 output.out.1 Here 1 is the iteration number. Now what this does is, it calls an executable using the values in the variables file and then the output of the executable is put into the output file. Unfortunat...
[ "Is there a way for you to augment exec.py to take any number of input/output filename pairs?\nIf so, the invocation will look like so:\n\npython exec.py variables.in.1 output.out.1 ... variables.in.N output.out.N\n\nNow, suppose you have 1000 such pairs. You can partition this range into 20 groups of 50 pairs (fo...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006296514_python.txt
Q: Python memory limit? Clear GC when close to limit? How would I clear garbage collected objects before performing other memory intensive operations? Or is it done automatically when the memory is full? Why does it seem that Python (+Eclipse) throws a Memory Exception at 2 GB (Win32) whereas actually still some memo...
Python memory limit? Clear GC when close to limit?
How would I clear garbage collected objects before performing other memory intensive operations? Or is it done automatically when the memory is full? Why does it seem that Python (+Eclipse) throws a Memory Exception at 2 GB (Win32) whereas actually still some memory is unused on Windows? Are there limits defined anywhe...
[ "You can tweak the performance of the garbage collector with the gc module -- for example, with gc.set_threshold -- or you can \"manually\" collect the garbage: gc.collect. However, I believe that most of the time, objects are collected as soon as their refcount goes to zero.\nSo to be explicit about it, (thanks de...
[ 3, 1 ]
[]
[]
[ "eclipse", "garbage_collection", "memory", "python", "windows" ]
stackoverflow_0006478663_eclipse_garbage_collection_memory_python_windows.txt
Q: global object access across the session in web2py? I'm new to webdev, these days plan for writing a boradgame with web2py. When start to coding, I found that I can't use global variables easily. for demo purpose, I want a python list object access by many players, I use sqlite to make it work. the database, (usin...
global object access across the session in web2py?
I'm new to webdev, these days plan for writing a boradgame with web2py. When start to coding, I found that I can't use global variables easily. for demo purpose, I want a python list object access by many players, I use sqlite to make it work. the database, (using DAL('sqlite:memory:') won't work), so I try the file w...
[ "If you do not need to persist the information, then you can use the session\nsession.myvariable\n\nif you need to persist and you want to speed up things with cache, then you can cache the select:\ndef cache_db_select():\n logs = db().select(db.log.ALL, cache=(cache.ram, 60))\n return dict(logs=logs) \n\n" ]
[ 1 ]
[]
[]
[ "cache_control", "python", "sqlite", "web2py" ]
stackoverflow_0006107918_cache_control_python_sqlite_web2py.txt
Q: Another Python module reload question Here is my code to reload a python module using the reload() build in function. I have looked at some (not all :) ) the other questions and answers in stackoverflow but to get my code to work I still need to do a os.remove('m.pyc'). Can anybody maybe explain it to me or show m...
Another Python module reload question
Here is my code to reload a python module using the reload() build in function. I have looked at some (not all :) ) the other questions and answers in stackoverflow but to get my code to work I still need to do a os.remove('m.pyc'). Can anybody maybe explain it to me or show me how I need to change my code to make the ...
[ "By replacing your remove statement with time.sleep(1) to prevent both files from being created nearly simultaneously, I obtain the correct result. I guess the problem is that both files have the same time stamp which prevents Python from detecting the change and truly reload the module.\n", "I get a different pr...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006477528_python.txt
Q: Setting up orbited development environment on windows I am developing a comet application using python orbited and django. But I don't know how to setup the development environment. Can any one please help me out? I looked at the documentations and tutorials... But I found them confusing... What I am looking is a ...
Setting up orbited development environment on windows
I am developing a comet application using python orbited and django. But I don't know how to setup the development environment. Can any one please help me out? I looked at the documentations and tutorials... But I found them confusing... What I am looking is a walk-through kind of information.
[ "Perhaps this can get you started - Django, Orbited, Stomp and Co.\n" ]
[ 0 ]
[]
[]
[ "orbited", "python" ]
stackoverflow_0003628663_orbited_python.txt
Q: How to collapse consecutive delimiters? The default split method in Python treats consecutive spaces as a single delimiter. But if you specify a delimiter string, consecutive delimiters are not collapsed: >>> 'aaa'.split('a') ['', '', '', ''] What is the most straightforward way to collapse consecutive delimiter...
How to collapse consecutive delimiters?
The default split method in Python treats consecutive spaces as a single delimiter. But if you specify a delimiter string, consecutive delimiters are not collapsed: >>> 'aaa'.split('a') ['', '', '', ''] What is the most straightforward way to collapse consecutive delimiters? I know I could just remove empty strings ...
[ "This is about as concise as you can get:\nstring = 'aaa'\nresult = [s for s in string.split('a') if s]\n\nOr you could switch to regular expressions:\nstring = 'aaa'\nresult = re.split('a+', string)\n\n", "You can use re.split with a regular expression as the delimiter, as in:\nre.split(pattern, string[, maxspli...
[ 26, 14, 2, 1, 0, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0006478845_python_split_string.txt
Q: How is IPython different from Python? I have been trying PyMC these days, and I wrote a very simple mcmceasy.py. Interestingly, the script runs OK in IPython, however, when I use Python directly, it gives the following traceback: Traceback (most recent call last): File "mcmceasy.py", line 2, in <module> from...
How is IPython different from Python?
I have been trying PyMC these days, and I wrote a very simple mcmceasy.py. Interestingly, the script runs OK in IPython, however, when I use Python directly, it gives the following traceback: Traceback (most recent call last): File "mcmceasy.py", line 2, in <module> from pymc import MvNormal, MCMC File "/usr/li...
[ "Of course I don't have your script but I've successfully run the imports in question from Windows, Linux and OSX versions of 2.6 and 2.7 python in both IPython and python. No errors as you report.\nHOWEVER, looking at the \"scipy/misc/init.py\" the name common is not imported. \nfrom common import *\n#...more st...
[ 2, 0 ]
[]
[]
[ "ipython", "python", "scipy" ]
stackoverflow_0006477927_ipython_python_scipy.txt
Q: weird string behavior after reading from text file in python I am reading a text file which I know its 38th line is "Uncalibrated Peaks:", and I know its stored in 38th element of my list. I already check them and there is no indexing problem. I am reading the text file by the following code import os fd = open('...
weird string behavior after reading from text file in python
I am reading a text file which I know its 38th line is "Uncalibrated Peaks:", and I know its stored in 38th element of my list. I already check them and there is no indexing problem. I am reading the text file by the following code import os fd = open('Report.txt') contents = fd.readlines() fd.close() for ind, line i...
[ "Generally, if it seems like the characters in a string are \"too wide\", you probably have a unicode file. Try converting it using the unicode function.\nLooking at your code above it looks more like a simple indexing error though.\n", "Did you try contents[37][0]? The 38th line should be at index 37 since index...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "text_files" ]
stackoverflow_0006478931_python_text_files.txt
Q: Python :: catching exceptions in order to traverse a list Here's the code, part of a solution to problem 11 in Euler Project: sum_d = 0 j = 0 while j < 20: i = 0 while i < 20: try: sum_d = grid[j][i] * grid[j+1][i+1] * grid[j+2][i+2] * grid[j+3][i+3] if sum_d > result: ...
Python :: catching exceptions in order to traverse a list
Here's the code, part of a solution to problem 11 in Euler Project: sum_d = 0 j = 0 while j < 20: i = 0 while i < 20: try: sum_d = grid[j][i] * grid[j+1][i+1] * grid[j+2][i+2] * grid[j+3][i+3] if sum_d > result: result = sum_d except IndexError: ...
[ "Spoiler: Here's part of my solution for problem 11.\nfor x in range(0,16):\n for y in range(0,16):\n prod = p[y][x] * p[y+1][x+1] * p[y+2][x+2] * p[y+3][x+3]\n m = max(m, prod)\n\nUsing exceptions instead of basic control structures is imho always a bad idea. This time you can get away with loopin...
[ 7, 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0006479022_exception_python.txt
Q: Custom Django admin action, remove entries related by ForeignKey I have two models: A(models.Model): field = models.IntegerField() B(models.Model): f = models.ForeignKey(A) And in admin panel I have custom action, which clears(resets) some info in Model A: def clear_something(modeladmin, request, queryse...
Custom Django admin action, remove entries related by ForeignKey
I have two models: A(models.Model): field = models.IntegerField() B(models.Model): f = models.ForeignKey(A) And in admin panel I have custom action, which clears(resets) some info in Model A: def clear_something(modeladmin, request, queryset): queryset.update(field=0) How could I make custom action clea...
[ "Assuming queryset is a set of A's, you should be able to loop over them and delete the 'b_set' (reverse FK lookup) of each, like so:\ndef clear_something(modeladmin, request, queryset):\n queryset.update(field=0)\n for a in queryset:\n a.b_set.all().delete()\n\nAlternatively, use B's model manager:\nd...
[ 2 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006479084_django_django_admin_python.txt
Q: Is there a python REPL for Google App Engine? The Clojure/Compojure people have a drop in repl for Google App Engine, do Python people have anything similar? I use the repl quite a bit in "vanilla" python development, and it would be really useful if I could use it in Google App Engine Python as well. I have seen ...
Is there a python REPL for Google App Engine?
The Clojure/Compojure people have a drop in repl for Google App Engine, do Python people have anything similar? I use the repl quite a bit in "vanilla" python development, and it would be really useful if I could use it in Google App Engine Python as well. I have seen the following http://shell.appspot.com/ demo, and I...
[ "If you're okay with a REPL that works on the dev server, take a look at the bin/python script that Tipfy creates for you. It just loads the Python REPL with your project and the GAE SDK code. I've pasted my version of it here - YMMV, but you can use it as a starting point. \n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "read_eval_print_loop" ]
stackoverflow_0006208683_google_app_engine_python_read_eval_print_loop.txt
Q: Is it normal for python's io.BytesIO.getvalue() to return str instead of bytes? Is it normal for python's io.BytesIO.getvalue() to return str instead of bytes? Python 2.7.1 (r271:86832, Jun 13 2011, 14:28:51) >>> import io >>> a = io.BytesIO() >>> a <_io.BytesIO object at 0x10f9453b0> >>> a.getvalue() '' ...
Is it normal for python's io.BytesIO.getvalue() to return str instead of bytes?
Is it normal for python's io.BytesIO.getvalue() to return str instead of bytes? Python 2.7.1 (r271:86832, Jun 13 2011, 14:28:51) >>> import io >>> a = io.BytesIO() >>> a <_io.BytesIO object at 0x10f9453b0> >>> a.getvalue() '' >>> print type(a.getvalue()) <type 'str'> >>> Should I file a bug?
[ "No, this isn't a bug. This is normal behaviour. See this answer: the bytes type in python 2.7 and PEP-358\nIt basically comes down that the 2.7 bytes is just an alias for str to smoothen the transition to 3.x.\n", "bytes doesn't exist as a separate kind of datastructure in Python 2.X so yes, it is entirely norma...
[ 22, 4 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0006479317_python_python_2.7.txt
Q: In list of dicts, match dict based on one key/value? In Python, I have a list of dictionaries: mylist = [ { 'name': 'James', 'school': 'UCLA', 'date_joined': 2001 }, { 'name': 'Jack', 'school': 'UCLA', 'date_joined': 2001 }, { 'name': 'Fisher', 'school': 'NYU', 'date_joined': 2003 }] How can...
In list of dicts, match dict based on one key/value?
In Python, I have a list of dictionaries: mylist = [ { 'name': 'James', 'school': 'UCLA', 'date_joined': 2001 }, { 'name': 'Jack', 'school': 'UCLA', 'date_joined': 2001 }, { 'name': 'Fisher', 'school': 'NYU', 'date_joined': 2003 }] How can I check whether a certain dictionary matches existing rec...
[ "fields = ('name', 'school')\nmatch_found = any(all(x[f]==example[f] for f in fields) for x in myList)\n\n", "Not knowing anything more about the structure of your program, my approach might be somewhat different:\nfrom collections import namedtuple\nimport datetime\n\nStudentRecord = namedtuple('StudentRecord', ...
[ 5, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006479377_python.txt
Q: MySql Python Adapter Installation Problem on Windows 7 Machine C:\Users\Me>easy_install MySQL-python Searching for MySQL-python Reading [http://pypi.python.org/simple/MySQL-python/ Reading [http://sourceforge.net/projects/mysql-python/ Reading [http://sourceforge.net/projects/mysql-python Best match: MySQL-python...
MySql Python Adapter Installation Problem on Windows 7 Machine
C:\Users\Me>easy_install MySQL-python Searching for MySQL-python Reading [http://pypi.python.org/simple/MySQL-python/ Reading [http://sourceforge.net/projects/mysql-python/ Reading [http://sourceforge.net/projects/mysql-python Best match: MySQL-python 1.2.3 Downloading [http://download.sourceforge.net/sourceforge/mysq...
[ "You can download the binaries from here, http://www.codegood.com/archives/129, which will bypass easy_install all together. Plus, stop using easy_install, use pip, it's much better.\n" ]
[ 2 ]
[]
[]
[ "mysql", "python", "windows_7" ]
stackoverflow_0006479378_mysql_python_windows_7.txt
Q: Getting empty form in Django with MetaForm I have this as template account_form.html <form action="/contact/" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input typ...
Getting empty form in Django with MetaForm
I have this as template account_form.html <form action="/contact/" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Send message" /></p> </form> ...
[ "I think you forgot to actually create your form:\nShould read something like this:\nforms.py:\nfrom django.forms import ModelForm\nfrom yourapp.models import Account\n\nclass AccountForm(ModelForm):\n class Meta:\n model = Order\n\nThis will give you all fields from Account.\nHTH\n" ]
[ 1 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0006479504_django_forms_python.txt
Q: select_related-like function doesn't work in RawQuerySet I have a problem with raw sql query in Django 1.3. When I use select_related() from ORM I get whole needed data in one query. activities = UserActivity.objects.filter(Q(user__in=friends_list),Q(activity_type = UserActivity.TYPE_POST, post__status=Post.PUBLIC...
select_related-like function doesn't work in RawQuerySet
I have a problem with raw sql query in Django 1.3. When I use select_related() from ORM I get whole needed data in one query. activities = UserActivity.objects.filter(Q(user__in=friends_list),Q(activity_type = UserActivity.TYPE_POST, post__status=Post.PUBLIC_STATUS)|Q(activity_type = UserActivity.TYPE_SHORT_REVIEW)|Q(a...
[ "OK. Problem wasn't in my query. It was connected to printing result. Function tried to print user instead of username, so every user had to be fetch from database.\nWas\ndef __unicode__(self):\n return \"%s\" % self.user\n\nShould be \ndef __unicode__(self):\n return self.username\n\n" ]
[ 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0006474422_django_postgresql_python.txt
Q: Assigning a function to an object attribute Based on my understanding of Python's data model, and specifically the subsection "Instance Methods", whenever you read an attribute whose value is of type "user-defined function", some magic kicks in and you get a bound instance method instead of the actual, original fu...
Assigning a function to an object attribute
Based on my understanding of Python's data model, and specifically the subsection "Instance Methods", whenever you read an attribute whose value is of type "user-defined function", some magic kicks in and you get a bound instance method instead of the actual, original function. That magic is why you don't explicitly pa...
[ "Here is how you do it:\nimport types\nclass Scriptable:\n def __init__(self, script = None):\n if script is not None:\n self.script = types.MethodType(script, self) # replace the method\n def script(self):\n print(\"greetings from the default script\")\n\nAs ba__friend noted in the...
[ 18, 11, 7, 1 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0006478371_methods_python.txt
Q: Mac Python pointing to different site-packages after python upgrade - How do i point all site-packages to correct python version? I am trying to upgrade my Mac from 2.6 to 2.7 and everything went fine except for some libraries are being used from 2.6 now instead of 2.7, any idea how I can point all the new librari...
Mac Python pointing to different site-packages after python upgrade - How do i point all site-packages to correct python version?
I am trying to upgrade my Mac from 2.6 to 2.7 and everything went fine except for some libraries are being used from 2.6 now instead of 2.7, any idea how I can point all the new libraries to 2.7? Basically I am trying to install yolk for 2.7 but it says that its already installed (under 2.6). $ python Python 2.7 (r27:...
[ "From the evidence you present, it appears you have both of the framework bin directories of Python 2.6 and Python 2.7 on your shell search path, $PATH. If you used the python.org installers to install both 2.6 and 2.7, each installer by default modifies your shell startup files to include the bin directory it ins...
[ 2, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0006479054_macos_python.txt
Q: Searching for area code in txt-file in Python I have a textfile that looks like this: Thomas Edgarson, Berliner Str 4, 13359 Berlin Madeleine Jones, Müller Str 5, 15992 Karlsruhe etc... It's always two words, followed by a comma, then two words and number, comma, area code and city. There are no exceptions. I use...
Searching for area code in txt-file in Python
I have a textfile that looks like this: Thomas Edgarson, Berliner Str 4, 13359 Berlin Madeleine Jones, Müller Str 5, 15992 Karlsruhe etc... It's always two words, followed by a comma, then two words and number, comma, area code and city. There are no exceptions. I used f=open("C:\\Users\\xxxxxx\\Desktop\\useradresses....
[ "Loop through the file, reading lines, and split by comma. Then, process each part by splitting by space. Then, add the values to a dictionary.\n", "d={}\n\nfor line in open('useradresses.txt','r'):\n if line.strip()=='':\n continue\n (name,strasse,plzort) = line.split(',')\n nachname,vorname=name...
[ 1, 1, 1 ]
[ "Python has a lot of libraries dealing with string manipulation, which is what this is. You'll be wanting the re library and the shlex library. I'd suggest the following code:\nwith open(\"C:\\\\Users\\\\xxxxxx\\\\Desktop\\\\useradresses.txt\", \"r\") as f:\n for line in f.readlines():\n split = shlex.spl...
[ -1 ]
[ "python", "search", "text_files" ]
stackoverflow_0006479905_python_search_text_files.txt
Q: Is there a way to capture URL parameters with django in urls.py? I am trying to write something elegant where I am not relying on Request object in my code. All the examples are using: (r'^hello/(?P.*)$', 'foobar.views.hello') but it doesn't seem like you can post to a URL like that very easily with a form. ...
Is there a way to capture URL parameters with django in urls.py?
I am trying to write something elegant where I am not relying on Request object in my code. All the examples are using: (r'^hello/(?P.*)$', 'foobar.views.hello') but it doesn't seem like you can post to a URL like that very easily with a form. Is there a way to make that URL respond to ..../hello?name=smith
[ "Absolutely. If your url is mapped to a function, in this case foobar.views.hello, then that function might look like this for a GET request:\ndef hello(request):\n if request.method == \"GET\":\n name_detail = request.GET.get(\"name\", None)\n\n if name_detail:\n # got details\n ...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006479916_django_python.txt
Q: Django Python noob - how do I get the NUMBER out of a Aggregate sum? I have a simple Aggregate: tot=PurchaseOrderLine.objects.aggregate(total=Sum('price')) return HttpResponse(tot) This returns "total". If I do: return HttpResponse(str(tot)) It displays "{'total': Decimal('321.60')}" How do I get the...
Django Python noob - how do I get the NUMBER out of a Aggregate sum?
I have a simple Aggregate: tot=PurchaseOrderLine.objects.aggregate(total=Sum('price')) return HttpResponse(tot) This returns "total". If I do: return HttpResponse(str(tot)) It displays "{'total': Decimal('321.60')}" How do I get the NUMERIC var out of this!
[ "tot=PurchaseOrderLine.objects.aggregate(total=Sum('price'))['total'] \nreturn HttpResponse(tot)\n\n" ]
[ 1 ]
[]
[]
[ "aggregate", "annotate", "django", "python" ]
stackoverflow_0006480189_aggregate_annotate_django_python.txt
Q: Threading and Conditions I'm new to threading and I don't really understand how to use conditions. At the moment, I have a thread class like this: class MusicThread(threading.Thread): def __init__(self, song): threading.Thread.__init__(self) self.song = song def run(self): self.outp...
Threading and Conditions
I'm new to threading and I don't really understand how to use conditions. At the moment, I have a thread class like this: class MusicThread(threading.Thread): def __init__(self, song): threading.Thread.__init__(self) self.song = song def run(self): self.output = audiere.open_device() ...
[ "There is a much simpler solution here. You're using the Audiere library, which already plays audio in its own thread. Therefore, there is no need to spawn a second thread of your own just to play audio. Instead, use Audiere directly from the main thread, and stop it from the main thread.\n", "Matt Campbell's ...
[ 3, 2 ]
[]
[]
[ "conditional_statements", "multithreading", "python" ]
stackoverflow_0006480132_conditional_statements_multithreading_python.txt
Q: Python property() returning unlisted field? The code I'm looking at is from django.contrib.auth.models.User def _get_message_set(self): import warnings warnings.warn('The user messaging API is deprecated. Please update' ' your code to use the new messages framework.', ca...
Python property() returning unlisted field?
The code I'm looking at is from django.contrib.auth.models.User def _get_message_set(self): import warnings warnings.warn('The user messaging API is deprecated. Please update' ' your code to use the new messages framework.', category=DeprecationWarning) return self.**_mes...
[ "In Python, an attribute of an object does not need to be declared. In your case, it's set up in the constructor of the superclass models.Model.\nNote that the internal attribute is prefixed with an underscore, whereas the external one (which happens to be a property) lacks one.\n", "from django.contrib.auth.mode...
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006480211_django_python.txt
Q: ctypes pointer into the middle of a numpy array I know how to get a ctypes pointer to the beginning of a numpy array: a = np.arange(10000, dtype=np.double) p = a.ctypes.data_as(POINTER(c_double)) p.contents c_double(0.0) however, I need to pass the pointer to, let's say, element 100, without copying the array. Th...
ctypes pointer into the middle of a numpy array
I know how to get a ctypes pointer to the beginning of a numpy array: a = np.arange(10000, dtype=np.double) p = a.ctypes.data_as(POINTER(c_double)) p.contents c_double(0.0) however, I need to pass the pointer to, let's say, element 100, without copying the array. There must be an easy way to do it but cannot find it. ...
[ "Slicing a numpy array creates a view, not a copy:\n>>> a = numpy.arange(10000, dtype=numpy.double)\n>>> p = a[100:].ctypes.data_as(ctypes.POINTER(ctypes.c_double))\n>>> p.contents\nc_double(100.0)\n>>> a[100] = 55\n>>> p.contents\nc_double(55.0)\n\n" ]
[ 11 ]
[]
[]
[ "ctypes", "numpy", "pointers", "python" ]
stackoverflow_0006480310_ctypes_numpy_pointers_python.txt
Q: Python ctypes: SetWindowsHookEx callback function never called I'm trying to write a program in Python that is aware of when alert boxes/dialogues are shown. It's dealing with multiple monitors, and I want it to display a visualization on the secondary monitor when a taskbar icon flashes, an error/notification pop...
Python ctypes: SetWindowsHookEx callback function never called
I'm trying to write a program in Python that is aware of when alert boxes/dialogues are shown. It's dealing with multiple monitors, and I want it to display a visualization on the secondary monitor when a taskbar icon flashes, an error/notification pops up, etc. As far as I can tell, the way to do detect these events i...
[ "With the exception of WH_KEYBOARD_LL and WH_MOUSE_LL, the Windows hooks must be implemented in a DLL that Windows injects into each application process. Therefore, you can't simply implement a callback in your program and expect Windows to run it.\nI can think of two ways to solve this problem:\n\nWrite a DLL in ...
[ 2 ]
[]
[]
[ "events", "python", "pywin32", "winapi", "windows" ]
stackoverflow_0006458812_events_python_pywin32_winapi_windows.txt
Q: Django, Model with "Def Self" value, SUM aggregate not working I have the following model: class PurchaseOrderLine(models.Model): productcode = models.ForeignKey(OurProduct, on_delete=models.PROTECT) price = models.DecimalField (max_digits=6, decimal_places=2) qty = models.IntegerField() def linetotal(self)...
Django, Model with "Def Self" value, SUM aggregate not working
I have the following model: class PurchaseOrderLine(models.Model): productcode = models.ForeignKey(OurProduct, on_delete=models.PROTECT) price = models.DecimalField (max_digits=6, decimal_places=2) qty = models.IntegerField() def linetotal(self): from decimal import * total = (self.price * self.qty) ...
[ "The linetotal property doesn't exist at the database level, so how would the ORM handle it? You need to implement the query using extra:\nfor purchase_order_line in PurchaseOrderLine.objects.extra(select={'total': 'price * qty'}):\n print purchase_order.total\n\n" ]
[ 1 ]
[]
[]
[ "aggregate", "django", "python", "sum" ]
stackoverflow_0006480682_aggregate_django_python_sum.txt
Q: Download MongoKit "devel" branch from Git using Buildout? Any solid examples of using buildout to download a tarball from a specific branch in Git into my eggs directory? All the answers i've tried seem to keep grabbing the version from PyPi instead. I'm trying to grab the development branch of MongoKit... ( ...
Download MongoKit "devel" branch from Git using Buildout?
Any solid examples of using buildout to download a tarball from a specific branch in Git into my eggs directory? All the answers i've tried seem to keep grabbing the version from PyPi instead. I'm trying to grab the development branch of MongoKit... ( http://github.com/namlook/mongokit/tarball/devel#egg=m...
[ "You can add any python package hosted on git-hub by adding a find-links url pointing to the project tarball URL plus a #egg=packagename postfix. As you already discovered, for mongokit that is:\nhttp://github.com/namlook/mongokit/tarball/devel#egg=mongokit\n\nYou can add a version number to that URL to provide bui...
[ 2, 0 ]
[]
[]
[ "buildout", "mongokit", "pypi", "python" ]
stackoverflow_0006478973_buildout_mongokit_pypi_python.txt
Q: Formula to convert ISO A series paper sizes to C series (envelopes) Based on the Wikipedia article, the best I've been able to come up with so far is this, which works for 9/11 sizes: A_SERIES = [ [841, 1189], [594, 841], [420, 594], [297, 420], [210, 297], [148, 210], [105, 148], [...
Formula to convert ISO A series paper sizes to C series (envelopes)
Based on the Wikipedia article, the best I've been able to come up with so far is this, which works for 9/11 sizes: A_SERIES = [ [841, 1189], [594, 841], [420, 594], [297, 420], [210, 297], [148, 210], [105, 148], [74, 105], [52, 74], [37, 52], [26, 37]] C_SERIES = [ [91...
[ "I really dont know how they come to that formula, but I would say it is just wrong.\nThere is a reasons how it and why it was developed as it is. \nThe ratio of A is 1:sqrt(2). So when you half a side you got the next smaller one.\n(The beginning has 1 m^2 - thats why it easy to calc the weight when you got the we...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006480724_python.txt
Q: Python error: List assignment index out of range I am attempting to initialize a list and keep getting the index out of range: self.nodes = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] When I run this code: for i in range(self.rows): for j in range(self.columns): if self.GRID[i][j...
Python error: List assignment index out of range
I am attempting to initialize a list and keep getting the index out of range: self.nodes = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] When I run this code: for i in range(self.rows): for j in range(self.columns): if self.GRID[i][j] == 0: self.walkable.append(Node(...
[ "Assignment to a non-existent index in a list fails. In your case, you are attempting to assign to index j of an empty list:\nself.nodes = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\n# assume i == 0 and j == 0\nself.nodes[i] # refers to the first empty list []\nself.nodes[i][j] ## does not exist\n\nConsider ...
[ 2, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006480908_list_python.txt
Q: StringIO replacement that works with bytes instead of strings? Is there any replacement for python StringIO class, one that will work with bytes instead of strings? It may not be obvious but if you used StringIO for processing binary data you are out of luck with Python 2.7 or newer. A: Try io.BytesIO. As other...
StringIO replacement that works with bytes instead of strings?
Is there any replacement for python StringIO class, one that will work with bytes instead of strings? It may not be obvious but if you used StringIO for processing binary data you are out of luck with Python 2.7 or newer.
[ "Try io.BytesIO.\nAs others have pointed out, you can indeed use StringIO in 2.7, but BytesIO is a good choice for forward-compatibility. \n", "In Python 2.6/2.7, the io module is intended to be used for compatibility with Python 3.X. From the docs:\n\nNew in version 2.6.\nThe io module provides the Python\n in...
[ 118, 12, 8 ]
[]
[]
[ "python", "python_2.7", "stringio", "unicode" ]
stackoverflow_0006479100_python_python_2.7_stringio_unicode.txt
Q: Gzip problem,traceback and IOError: [Errno 2] No such file or directory I'm new to python and bioinformatics field. I'm using python-2.6. Now I'm trying to select all fastq.gz files, then gzip.open(just a few lines because it's too huge and time-wasting), then count 'J' , then pick out those files with 'J' count N...
Gzip problem,traceback and IOError: [Errno 2] No such file or directory
I'm new to python and bioinformatics field. I'm using python-2.6. Now I'm trying to select all fastq.gz files, then gzip.open(just a few lines because it's too huge and time-wasting), then count 'J' , then pick out those files with 'J' count NOT equal to 0. The following is my code: #!/usr/bin/python import os,sys,re,...
[ "on this line:\ntext = gzip.open(file,'r').read()\n\nfile is a filename not a full path so\nfullpath = os.path.join(path, file)\ntext = gzip.open(fullpath,'r').read()\n\n\nabout F.readlines()[:10] will read the whole file in to a list of lines and then take the first 10\nimport itertools\nlist(itertools.islice(F.xr...
[ 4, 1, 0 ]
[]
[]
[ "gzip", "python" ]
stackoverflow_0006481001_gzip_python.txt
Q: Django SUM Query? I have a query akin to the following: SELECT SUM(ISNULL(table.name)) FROM table How does that SUM translate into a QuerySet in Django? i.e. What operation xyz does it translate to, in something like MyModel.objects.xyz()? A: Update: The following incorporates the ISNULL aspect of the original ...
Django SUM Query?
I have a query akin to the following: SELECT SUM(ISNULL(table.name)) FROM table How does that SUM translate into a QuerySet in Django? i.e. What operation xyz does it translate to, in something like MyModel.objects.xyz()?
[ "Update: The following incorporates the ISNULL aspect of the original query:\nfrom django.db.models import Sum\n\nModelName.objects.filter(field_name__isnull=True).aggregate(Sum('field_name'))\n# returns {'field_name__sum': 1000} for example\n\nYou're looking for the Sum aggregation function, which works as follows...
[ 197 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0006481279_django_django_queryset_python.txt
Q: Django Database Routers error: "need more than 1 value to unpack" When I did this in my code: DATABASE_ROUTERS = [ 'some_value_here' ] I got: ValueError at / need more than 1 value to unpack <some-path>/django/v1_2/core/handlers/base.py in get_response # Setup default url resolver for this thread. urlconf = ...
Django Database Routers error: "need more than 1 value to unpack"
When I did this in my code: DATABASE_ROUTERS = [ 'some_value_here' ] I got: ValueError at / need more than 1 value to unpack <some-path>/django/v1_2/core/handlers/base.py in get_response # Setup default url resolver for this thread. urlconf = settings.ROOT_URLCONF urlresolvers.set_urlconf(urlconf) resolver = urlr...
[ "Try:\nDATABASE_ROUTERS = [\n 'some_value_here',\n]\n\n", "Scratch that, I just the error myself: I need the module name, not just the class name.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006481373_django_python.txt
Q: Quick question about separating the return values of this function ## velocity def get_velocity(self): return ( (self.dx, self.dy) ) def set_velocity (self, new_velocity): self.dx, self.dy = new_velocity velocity = property(get_velocity, set_velocity) The above is from the source code...
Quick question about separating the return values of this function
## velocity def get_velocity(self): return ( (self.dx, self.dy) ) def set_velocity (self, new_velocity): self.dx, self.dy = new_velocity velocity = property(get_velocity, set_velocity) The above is from the source code of a module I am using. So to get the velocity values individually (dx ...
[ "No, because when you want to assign the return value of a function to a variable, you have to have the variable on the left and the function on the right:\nlala = self.get_velocity()\n\nWith that one change, it should work. But note that you can do the same thing with less typing like so:\ndx, dy = self.get_veloci...
[ 4, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0006481455_function_python.txt
Q: Python Unicode Conversions How to do the following conversions in Python? "杭州" to "%BA%BC%D6%DD" "大连" to "%B4%F3%C1%AC" A: To convert u'杭州' to '%BA%BC%D6%DD': In [24]: ''.join('%{0:X}'.format(ord(c)) for c in u"杭州".encode('gbk')) Out[24]: '%BA%BC%D6%DD' In [25]: ''.join('%{0:X}'.format(ord(c)) for c in u"大连".en...
Python Unicode Conversions
How to do the following conversions in Python? "杭州" to "%BA%BC%D6%DD" "大连" to "%B4%F3%C1%AC"
[ "To convert u'杭州' to '%BA%BC%D6%DD':\nIn [24]: ''.join('%{0:X}'.format(ord(c)) for c in u\"杭州\".encode('gbk'))\nOut[24]: '%BA%BC%D6%DD'\n\nIn [25]: ''.join('%{0:X}'.format(ord(c)) for c in u\"大连\".encode('gbk'))\nOut[25]: '%B4%F3%C1%AC'\n\n\nTo convert '%BA%BC%D6%DD' to u'杭州':\nIn [54]: import binascii \nIn [55]...
[ 3, 3 ]
[]
[]
[ "encoding", "python", "python_unicode", "string", "unicode" ]
stackoverflow_0006481523_encoding_python_python_unicode_string_unicode.txt
Q: List Compherension with sublist Suppose I have a list of sublist: lst = [ ['A', 'is', 'from', 'B,', '2', 'm', 'from', 'C', '1.2', 'm', 'from', 'D.'], ['0.3', 'm', 'from', 'D.'] ] and I wanted to organize the letters after the word "from" so I want to have new_lst = [ [B,C,D], [D] ] A: As you're talkin...
List Compherension with sublist
Suppose I have a list of sublist: lst = [ ['A', 'is', 'from', 'B,', '2', 'm', 'from', 'C', '1.2', 'm', 'from', 'D.'], ['0.3', 'm', 'from', 'D.'] ] and I wanted to organize the letters after the word "from" so I want to have new_lst = [ [B,C,D], [D] ]
[ "As you're talking about list comprehensions, you're probably writing in Python.\nSo I wrote the most awesome comprehension you may find to solve that problem.\n>>> [[next(i) for j in i if j == 'from'] for i in (iter(x) for x in lst)]\n[['B,', 'C', 'D.'], ['D.']]\n\n\n" ]
[ 6 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0006479405_list_list_comprehension_python.txt
Q: Problems with IMAP in Gmail with Python I have a problem with IMAP in Python 2.7 For testing purposes, I have created foobar306@gmail.com with the password testing123testing I am following this tutorial and typed this into my Python Iteractive Shell: Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 3...
Problems with IMAP in Gmail with Python
I have a problem with IMAP in Python 2.7 For testing purposes, I have created foobar306@gmail.com with the password testing123testing I am following this tutorial and typed this into my Python Iteractive Shell: Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "cr...
[ "It seems to work for me; I created a sarnoldwashere folder via the python API:\n>>> mail.create(\"sarnoldwashere\")\n('OK', ['Success'])\n>>> mail.list()\n('OK', ['(\\\\HasNoChildren) \"/\" \"INBOX\"',\n'(\\\\HasNoChildren) \"/\" \"Personal\"',\n'(\\\\HasNoChildren) \"/\" \"Receipts\"',\n'(\\\\HasNoChildren) \"/\"...
[ 3 ]
[]
[]
[ "gmail", "imap", "imaplib", "python" ]
stackoverflow_0006481771_gmail_imap_imaplib_python.txt
Q: Property decorator I have a property decorator so: def Property(f): """ Allow readable properties without voodoo. """ fget, fset, fdel = f() fdoc = f.__doc__ return property(fget, fset, fdel, fdoc) Used (for example) so: @Property def method(): """""" def fget(sel...
Property decorator
I have a property decorator so: def Property(f): """ Allow readable properties without voodoo. """ fget, fset, fdel = f() fdoc = f.__doc__ return property(fget, fset, fdel, fdoc) Used (for example) so: @Property def method(): """""" def fget(self): return s...
[ "You could use @staticmethod to create a method which does not receive an implicit first argument. Doesn't Python's @property decorator already do what you want?\nclass Foo(object):\n @property\n def bar(self):\n return 'foobar'\n\n>>> foo = Foo()\n\n>>> foo.bar\n<<< 'foobar'\n\n" ]
[ 10 ]
[]
[]
[ "decorator", "pydev", "pylint", "python", "python_3.x" ]
stackoverflow_0006481733_decorator_pydev_pylint_python_python_3.x.txt
Q: Should we use Pylons or PHP for our webapp? My friend and I are planning on building a sort of a forum type of webapp. We've used the major PHP frameworks but we're really thinking about using Python specifically the Pylons framework for our app. Although we're competent PHP programmers, we're somewhat noobs at Py...
Should we use Pylons or PHP for our webapp?
My friend and I are planning on building a sort of a forum type of webapp. We've used the major PHP frameworks but we're really thinking about using Python specifically the Pylons framework for our app. Although we're competent PHP programmers, we're somewhat noobs at Python (We could create practical scripts and such)...
[ "Decide what you want to put your focus on, being productive or learning a new language:\n\nIf you want to learn Pylons and Python, use Pylon and Python. \nIf you want to deliver a stable forum software, use PHP, because that's what you're competent at. \n\nNote: I should add that this is not meant to imply that ...
[ 9, 5, 4, 0 ]
[]
[]
[ "php", "pylons", "python" ]
stackoverflow_0002409812_php_pylons_python.txt
Q: Jython Optimizations Are their any ways to optimize Jython without resorting to profiling or significantly changing the code? Specifically are there any flags that can be passed to the compiler, or code hints in tight loops. A: No flags, no code hints. You can optimize by tweaking your code much as you would for...
Jython Optimizations
Are their any ways to optimize Jython without resorting to profiling or significantly changing the code? Specifically are there any flags that can be passed to the compiler, or code hints in tight loops.
[ "No flags, no code hints. You can optimize by tweaking your code much as you would for any other Python implementation (hoisting, etc), but profiling helps by telling you where it's worth your while to expend such effort -- so, sure, you can optimize \"without resorting to profiling\" (and the code changes to do so...
[ 6, 1, 0 ]
[]
[]
[ "java", "jython", "optimization", "python" ]
stackoverflow_0001978139_java_jython_optimization_python.txt
Q: ConfigParser Get Key on given Value Using ConfigParser I can read value of key easily as shown in the example below- #config.cfg [NODE] 192.168.31.22 = node22 192.168.31.23 = node23 192.168.31.26 = node26 #PYTHON CODE config = ConfigParser.RawConfigParser() config.readfp(open("config.cfg")) print config.get("NOD...
ConfigParser Get Key on given Value
Using ConfigParser I can read value of key easily as shown in the example below- #config.cfg [NODE] 192.168.31.22 = node22 192.168.31.23 = node23 192.168.31.26 = node26 #PYTHON CODE config = ConfigParser.RawConfigParser() config.readfp(open("config.cfg")) print config.get("NODE", "192.168.31.22") >>>node22 Sometime ...
[ "No, there is no direct way. Internally, ConfigParser reads the configuration file into a nested dictionary, and in each sections keys are mapped to values, not the other way around. Frankly, I'm not sure why you want this, but I suspect it's not a common request :)\nImplementing your own is very easy, however:\n# ...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006481939_python.txt
Q: Debugging ping pong game in Python I'm tired, and I've tried to run this all day. IT's a game of pong where the ball bounces off the wall and comes into contact with the user's "Slab" or paddle. I've treid to debug for a while, and turns out my iCollide and the iGet_Velocity parts have been causing a lot of issues...
Debugging ping pong game in Python
I'm tired, and I've tried to run this all day. IT's a game of pong where the ball bounces off the wall and comes into contact with the user's "Slab" or paddle. I've treid to debug for a while, and turns out my iCollide and the iGet_Velocity parts have been causing a lot of issues. from livewires import games, color gam...
[ "These two lines look sketchy:\n self.dx += self.dx + new_dx\n self.dy += self.dy + new_dy\n\nTry:\n self.dx += new_dx\n self.dy += new_dy\n\n", "Well, without having some more data, I can't say for certain what is wrong. But it looks like your collision response code is a bit screwy. For example, i...
[ 3, 3 ]
[]
[]
[ "pong", "pygame", "python" ]
stackoverflow_0006481993_pong_pygame_python.txt
Q: What's the problem of my prime test code? I implemented the Miller-Rabin prime test algorithm found on wikipedia with Python 3. It seems to be working correctly with most numbers but occasionaly fail on certain numbers. For example, the prime number 99999999999999997 is judged to be NOT prime. I implemented the al...
What's the problem of my prime test code?
I implemented the Miller-Rabin prime test algorithm found on wikipedia with Python 3. It seems to be working correctly with most numbers but occasionaly fail on certain numbers. For example, the prime number 99999999999999997 is judged to be NOT prime. I implemented the algorithm line by line and I have no clue where t...
[ "This is an implementation of Miller-Rabin I wrote a while ago. It has never given me an unexpected result -- though that doesn't mean it won't! It is substantially identical to the one you pasted, and it declares 99999999999999997 to be prime. Yours did too, when I tested it -- so that's a second to Mikola's opini...
[ 4, 2, 0 ]
[]
[]
[ "algorithm", "primes", "python" ]
stackoverflow_0006481727_algorithm_primes_python.txt
Q: Intersection between text files How can I compute the intersection between two text files in terms of raw text? It doesn't matter whether the solution uses a shell command or is expressed in Python, Elisp, or other common scripting languages. I know comm and grep -Fxv -f file1 file2. Both assume that I am interest...
Intersection between text files
How can I compute the intersection between two text files in terms of raw text? It doesn't matter whether the solution uses a shell command or is expressed in Python, Elisp, or other common scripting languages. I know comm and grep -Fxv -f file1 file2. Both assume that I am interested in the intersection of lines, wher...
[ "You're looking for Python's difflib module (in the standard library), and in particular difflib.SequenceMatcher.\n", "okay here is a very simple python scripit to accomplish this\nit can be imporved upon, but should do the job.\ntemp.txt\n\nxx yy xyz zz aa xx yy xyz zz\n aa xx yy xyz zz aa xx yy 111\n aa cc\n\...
[ 8, 2, 0 ]
[]
[]
[ "bash", "emacs", "grep", "python", "text" ]
stackoverflow_0006481953_bash_emacs_grep_python_text.txt
Q: Python: how to share an object instance across multiple invocations of a script I'm use a library which provides a python interface to an external program. This allows me to create: foo = Foo() The code above starts a new instance of the Foo program that I can control from within python. I have a python scripts w...
Python: how to share an object instance across multiple invocations of a script
I'm use a library which provides a python interface to an external program. This allows me to create: foo = Foo() The code above starts a new instance of the Foo program that I can control from within python. I have a python scripts which needs to be invoked multiple times and depending on external parameters, tell a ...
[ "This can be done if you follow an approach similar to that given in this answer. Or you can use Pyro, which is compared to multiprocessing in this answer.\n", "You might be able to use pickle. Here's a simple example:\nimport os, pickle\n\nclass Foo(object):\n def __init__(self, bar):\n self.bar = bar\...
[ 3, 0, 0 ]
[]
[]
[ "object_persistence", "object_sharing", "python" ]
stackoverflow_0006481602_object_persistence_object_sharing_python.txt
Q: MySQLdb connection problems I'm having trouble with the MySQLdb module. db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) (I'm using a custom port) the error I get is: Error 2002: Can't connect to local MySQL server through socket '/var/lib/m...
MySQLdb connection problems
I'm having trouble with the MySQLdb module. db = MySQLdb.connect( host = 'localhost', user = 'root', passwd = '', db = 'testdb', port = 3000) (I'm using a custom port) the error I get is: Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) Which doesn'...
[ "Changing localhost to 127.0.0.1 solved my problem using MySQLdb:\ndb = MySQLdb.connect(\n host = '127.0.0.1', \n user = 'root', \n passwd = '', \n db = 'testdb', \n port = 3000)\n\nUsing 127.0.0.1 forces the client to use TCP/IP, so that the server listening to the TCP port can pickle it up. If host...
[ 54, 12, 3, 3, 2, 0 ]
[ "Maybe try adding the keyword parameter unix_socket = None to connect()?\n" ]
[ -2 ]
[ "connection", "mysql", "python" ]
stackoverflow_0000758819_connection_mysql_python.txt
Q: Python+MySQL - Bulk Insert I'm working with the MySQLdb module in Python to interact with a database. I have a situation where there is a very large list (tens of thousands of elements) which I need to insert as rows into a table. My solution right now is to generate a large INSERT statement as a string and execut...
Python+MySQL - Bulk Insert
I'm working with the MySQLdb module in Python to interact with a database. I have a situation where there is a very large list (tens of thousands of elements) which I need to insert as rows into a table. My solution right now is to generate a large INSERT statement as a string and execute it. Is there a smarter way?
[ "There is a smarter way. \nThe problem with bulk insertions is that by default autocommit is enabled thus causing each insert statement to be saved to stable store before the next insert can initiate.\nAs the manual page notes:\n\nBy default, MySQL runs with autocommit\n mode enabled. This means that as soon\n as...
[ 20, 14, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006482004_mysql_python.txt
Q: How to slice a list that is sliced in python? I have a list of let's say [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]] and its name is somelist. I want to do somelist[:2][:2] and have that return [[1,2], [1,2]]. So it slices the list and then slices that list and returns that. Is it even possible to do this in one ...
How to slice a list that is sliced in python?
I have a list of let's say [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]] and its name is somelist. I want to do somelist[:2][:2] and have that return [[1,2], [1,2]]. So it slices the list and then slices that list and returns that. Is it even possible to do this in one line in python?
[ "You can do this using list comprehension. I changed your sample input to make it clearer what is being selected:\n>>> l = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]\n>>> print [x[:2] for x in l[:2]]\n[[1, 2], [5, 6]]\n\n", "Multidimensional slicing is easy with numpy:\nimport numpy\na = nump...
[ 8, 1, 0 ]
[]
[]
[ "python", "slice" ]
stackoverflow_0006482699_python_slice.txt
Q: Changing formatting string from % to alternate character? In python 2.6, is there a way to specify an alternate character other than % for string formatting operations? Or is the % char hardcoded in the python interpreter? For example, to generate a string that looks like this: param1%02param2%03param3... I curre...
Changing formatting string from % to alternate character?
In python 2.6, is there a way to specify an alternate character other than % for string formatting operations? Or is the % char hardcoded in the python interpreter? For example, to generate a string that looks like this: param1%02param2%03param3... I currently have to do this: str = "%s%%02%s%%03%s" % (param1, param2,...
[ "You can use the new str.format method. It offers more formatting options and is more readable.\n>>> '{0}%02{1}%03{2}'.format('a', 'b', 'c')\n'a%02b%03c'\n\n>>> '{param1} is also {param2}'.format(param1='foo', param2='bar')\n'foo is also bar'\n\n>>> '{0[name]} is {0[age]} years old'.format({'name': 'Bob', 'age': 42...
[ 3, 2, 2 ]
[ "You can't - its not even hard-coded in python, its hard-coded somewhere in libc (a level below the interpreter). You could write a function that will the string with the ^ and convert them to % and take the existing % and convert them to %% and then pass it to formatting.\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0006481193_python.txt