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:
Django Formset without instance
In this Django Doc explain how to create a formset that allows you to edit books belonging to a particular author.
What I want to do is: Create a formset that allows you to ADD new book belonging to a NEW author... Add the Book and their Authors in the same formset.
Can you gime a l... | Django Formset without instance | In this Django Doc explain how to create a formset that allows you to edit books belonging to a particular author.
What I want to do is: Create a formset that allows you to ADD new book belonging to a NEW author... Add the Book and their Authors in the same formset.
Can you gime a light? thanks.
| [
"When you're instantiating the form and formset for the initial display, you don't need to provide an instance - so you will just get blank forms.\nWhen you pass in the data on POST, you can do the form first, save it, and get an instance. Then you can pass that instance into the formset, so that it correctly saves... | [
13,
0
] | [] | [] | [
"django",
"forms",
"formset",
"inline_formset",
"python"
] | stackoverflow_0001267810_django_forms_formset_inline_formset_python.txt |
Q:
Python http proxy library based on libevent or comparable technology?
I'm looking to build an intelligent reverse http proxy capable of routing, header examination and enrichment (eg. examine and build cookies and http headers), and various other fanciness. For a general idea of what I'm looking to build see Ruby ... | Python http proxy library based on libevent or comparable technology? | I'm looking to build an intelligent reverse http proxy capable of routing, header examination and enrichment (eg. examine and build cookies and http headers), and various other fanciness. For a general idea of what I'm looking to build see Ruby Proxies for Scale and Monitoring - except in Python.
I realize that Twiste... | [
"Not sure if meets all your needs, but proxylet is a reverse proxy based on Linden Lab's eventlet.\n"
] | [
3
] | [] | [] | [
"http",
"libevent",
"proxy",
"python"
] | stackoverflow_0001268984_http_libevent_proxy_python.txt |
Q:
How can I change the font size in GTK?
Is there an easy way to change the font size of text elements in GTK? Right now the best I can do is do set_markup on a label, with something silly like:
lbl.set_markup("<span font_desc='Tahoma 5.4'>%s</span>" % text)
This 1) requires me to set the font , 2) seems like a lot... | How can I change the font size in GTK? | Is there an easy way to change the font size of text elements in GTK? Right now the best I can do is do set_markup on a label, with something silly like:
lbl.set_markup("<span font_desc='Tahoma 5.4'>%s</span>" % text)
This 1) requires me to set the font , 2) seems like a lot of overhead (having to parse the markup), a... | [
"If you want to change font overall in your app(s), I'd leave this job to gtkrc (then becomes a google question, and \"gtkrc font\" query brings us to this ubuntu forums link which has the following snippet of the the gtkrc file):\nstyle \"font\"\n{\nfont_name = \"Corbel 8\"\n}\nwidget_class \"*\" style \"font\"\ng... | [
9,
3
] | [] | [] | [
"fonts",
"gtk",
"gtk2",
"pygtk",
"python"
] | stackoverflow_0001269326_fonts_gtk_gtk2_pygtk_python.txt |
Q:
Python threading question - returning control to parent
Basically, I have a python program which listens for DeviceAdded DBus events (e.g. when someone plugs in a USB drive), and when an event occurs, I want to create a thread which collects metadata on that newly connected device. However, I want to do this async... | Python threading question - returning control to parent | Basically, I have a python program which listens for DeviceAdded DBus events (e.g. when someone plugs in a USB drive), and when an event occurs, I want to create a thread which collects metadata on that newly connected device. However, I want to do this asynchronously - that is, allow one thread to keep collecting meta... | [
"Try spawning a thread just for the capture stuff, by changing the following lines in your _filter() function to this:\nif device.QueryCapability(\"volume\"):\n threading.start_new_thread(self.capture, (device))\n\nThis is assuming that the bulk of the work is happening in the capture() function. If not, then j... | [
2
] | [] | [] | [
"dbus",
"multithreading",
"python"
] | stackoverflow_0001269466_dbus_multithreading_python.txt |
Q:
Get information from related object in generic list view
So, I've been noodling about with Django's generic views, specifically the object_list view. I have this in my urls.py:
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from diplomacy.engine.models import Game
game_info ... | Get information from related object in generic list view | So, I've been noodling about with Django's generic views, specifically the object_list view. I have this in my urls.py:
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from diplomacy.engine.models import Game
game_info = {
"queryset": Game.objects.filter(state__in=('A', 'P')),... | [
"If Turn.game points to the associated Game object, then {{game.turn_set.all}} should return the set of Turn objects for that game. \nYou may need to add a Meta class to the Turn model to order from newest to oldest.\nClass Meta:\n ordering = ['-generated']\n\nThen, {{game.turn_set.all.0}} should return the unic... | [
0
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0001269625_django_django_templates_django_views_python.txt |
Q:
How to print Python installation directory to the output?
Let's say Python is installed in the location
C:\TOOLS\COMMON\python\python252
I want to print this location in the output of my program. Please let me know can I do this.
A:
you can use
import sys, os
os.path.dirname(sys.executable)
but remember than... | How to print Python installation directory to the output? | Let's say Python is installed in the location
C:\TOOLS\COMMON\python\python252
I want to print this location in the output of my program. Please let me know can I do this.
| [
"you can use\nimport sys, os\nos.path.dirname(sys.executable)\n\nbut remember than in Unix systems the \"installation\" of a program is usually distributed along the following folders:\n\n/usr/bin (this is what you'll probably get)\n/usr/lib\n/usr/share\netc.\n\n",
"Maybe either of these will satisfy you:\n>>> im... | [
36,
6,
4
] | [] | [] | [
"path",
"python"
] | stackoverflow_0001270537_path_python.txt |
Q:
About Python's Mixed Numeric Data Types converting results up to the most complicated operand
A little background: I'm in the process of learning Python through O'Reilly's, "Learning Python" book, I've had some experience in Java.
Anyway, upon reading Chapter 5 (I'm still in the middle of it, actually) I have come... | About Python's Mixed Numeric Data Types converting results up to the most complicated operand | A little background: I'm in the process of learning Python through O'Reilly's, "Learning Python" book, I've had some experience in Java.
Anyway, upon reading Chapter 5 (I'm still in the middle of it, actually) I have come across a question with the way Python treats results of Mixed Numeric expressions. In the book, t... | [
"\n\"If you have a decimal place in your expression, you know it's going to be a floating point number, if you have something like 3+4j, you know it's going to be a complex number.\"\n\nThat is the \"hierarchy of Numeric Literals\". I'm not really sure what more you want. Furthermore, the result will always be a su... | [
5,
2,
0
] | [] | [] | [
"numeric",
"python"
] | stackoverflow_0001270403_numeric_python.txt |
Q:
Print out the line with the longest length, the line with the highest sum of ASCII values, or the line with the greatest number of words
I need some help to print out the line with the longest length, the line with the highest sum of ASCII values, or the line with the greatest number of words from a text file. Thi... | Print out the line with the longest length, the line with the highest sum of ASCII values, or the line with the greatest number of words | I need some help to print out the line with the longest length, the line with the highest sum of ASCII values, or the line with the greatest number of words from a text file. This is my first time programming and I'm really struggling with python and don't know how to calculate want is required for my lab this week. I ... | [
"First work out how to open the file and read a line of text from the file to a string.\nRead one line inside a loop and each time you loop work out the length of the string (easy), the number of words (split the string by the ' ' (space) character and count how many words you get) and the sum of the ASCII values (... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0001270652_python.txt |
Q:
Why does import of ctypes raise ImportError?
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\li... | Why does import of ctypes raise ImportError? | Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\ctypes\__init__.py", line 17, in <module>
fr... | [
"It seems you have another struct.py in your path somewhere.\nTry this to see where python finds your struct module:\n>>> import inspect\n>>> import struct\n>>> inspect.getabsfile(struct)\n'c:\\\\python26\\\\lib\\\\struct.py'\n\n"
] | [
11
] | [] | [] | [
"ctypes",
"importerror",
"python",
"python_2.6"
] | stackoverflow_0001270738_ctypes_importerror_python_python_2.6.txt |
Q:
Most concise way to check whether a list is empty or contains only None?
Most concise way to check whether a list is empty or contains only None?
I understand that I can test:
if MyList:
pass
and:
if not MyList:
pass
but what if the list has an item (or multiple items), but those item/s are None:
MyList ... | Most concise way to check whether a list is empty or contains only None? | Most concise way to check whether a list is empty or contains only None?
I understand that I can test:
if MyList:
pass
and:
if not MyList:
pass
but what if the list has an item (or multiple items), but those item/s are None:
MyList = [None, None, None]
if ???:
pass
| [
"One way is to use all and a list comprehension:\nif all(e is None for e in myList):\n print('all empty or None')\n\nThis works for empty lists as well. More generally, to test whether the list only contains things that evaluate to False, you can use any:\nif not any(myList):\n print('all empty or evaluating ... | [
15,
9,
4,
2
] | [] | [] | [
"list",
"python",
"types"
] | stackoverflow_0001270920_list_python_types.txt |
Q:
How to change the "Event" portlet in Plone 3
I am trying to customize the "Event" portlet in Plone 3 that shows the upcoming events. The "view" link in the footer of that portlet goes to the /events URL. But my site is multi-lingual so that URL is not always correct. For example, the correct URL for Dutch events s... | How to change the "Event" portlet in Plone 3 | I am trying to customize the "Event" portlet in Plone 3 that shows the upcoming events. The "view" link in the footer of that portlet goes to the /events URL. But my site is multi-lingual so that URL is not always correct. For example, the correct URL for Dutch events should be /evenementen.
In my setup I use one folde... | [
"The events portlet uses a view to provide it with data, and the expression 'view/all_events_link' calls a method on that view to provide it with a link. You have 2 options to replace that link:\n\nRegister your own event portlet that subclasses the old one, and replaces the all_events_link method. This in the heav... | [
1
] | [] | [] | [
"plone",
"portlet",
"python",
"zope"
] | stackoverflow_0001271057_plone_portlet_python_zope.txt |
Q:
python db insert
I am in facing a performance problem in my code.I am making db connection a making a select query and then inserting in a table.Around 500 rows in one select query ids populated .Before inserting i am running select query around 8-9 times first and then inserting then all using cursor.executemany... | python db insert | I am in facing a performance problem in my code.I am making db connection a making a select query and then inserting in a table.Around 500 rows in one select query ids populated .Before inserting i am running select query around 8-9 times first and then inserting then all using cursor.executemany.But it is taking 2 mi... | [
"I don't really understand why you're doing this.\nIt seems that you want to insert a subset of rows from \"assd\" into one table, and another subset into another table?\nWhy not just do it with two SQL statements, structured like this:\ninsert into tab1 select * from assd where asd_id = 42 and cond1 = 'set';\ninse... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0001271502_python.txt |
Q:
accessing remote url's in Google App Engine
I don't know the correct terminology to do a google search.
What I want is to make a POST http request to other url, for example
twitter, from within mi app in google app engine.
If the question is unclear please comment.
Thanks!
Manuel
A:
Google provides urlfetch for ... | accessing remote url's in Google App Engine | I don't know the correct terminology to do a google search.
What I want is to make a POST http request to other url, for example
twitter, from within mi app in google app engine.
If the question is unclear please comment.
Thanks!
Manuel
| [
"Google provides urlfetch for this.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"httprequest",
"python",
"twitter"
] | stackoverflow_0001271908_google_app_engine_httprequest_python_twitter.txt |
Q:
parsing CSV files backwards
I have csv files with the following format:
CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
The problem is that the first field has commas "," in it. I have no control over file... | parsing CSV files backwards | I have csv files with the following format:
CSV FILE
"a" , "b" , "c" , "d"
hello, world , 1 , 2 , 3
1,2,3,4,5,6,7 , 2 , 456 , 87
h,1231232,3 , 3 , 45 , 44
The problem is that the first field has commas "," in it. I have no control over file generation, as that's the format... | [
"The rsplit string method splits a string starting from the right instead of the left, and so it's probably what you're looking for (it takes an argument specifying the max number of times to split):\nline = \"hello, world , 1 , 2 , 3\"\nparts = line.rsplit(\",\", 3)\nprint parts # prints ['hello, world... | [
16,
4,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"csv",
"parsing",
"python",
"readline"
] | stackoverflow_0001272315_csv_parsing_python_readline.txt |
Q:
Alternatives to mod_python's CGI handler
I'm looking for the simplest way of using python and SQLAlchemy to produce some XML for a jQuery based HTTP client. Right now I'm using mod_python's CGI handler but I'm unhappy with the fact that I can't persist stuff like the SQLAlchemy session.
The mod_python publisher ha... | Alternatives to mod_python's CGI handler | I'm looking for the simplest way of using python and SQLAlchemy to produce some XML for a jQuery based HTTP client. Right now I'm using mod_python's CGI handler but I'm unhappy with the fact that I can't persist stuff like the SQLAlchemy session.
The mod_python publisher handler that is apparently capable of persisting... | [
"You could always write your own handler, which is the way mod_python is normally intended to be used. You would have to set some HTTP headers (and you could have a look at the publisher handler's source code for inspiration on that), but otherwise I don't think it's much more complicated than what you've been tryi... | [
2
] | [] | [] | [
"cgi",
"mod_python",
"python"
] | stackoverflow_0001272325_cgi_mod_python_python.txt |
Q:
wxPython: Changing the color scheme of a wx.stc.StyledTextCtrl
I have a PyShell, which is supposed to be derived from wx.stc.StyledTextCtrl. How do I change the color scheme that it currently uses?
A:
You can use
styledTextCtrl.StyleSetSpec(wx.stc.STC_STYLE_INDENTGUIDE, "fore:#CDCDCD")
(Bunch of .StyleSetSpec p... | wxPython: Changing the color scheme of a wx.stc.StyledTextCtrl | I have a PyShell, which is supposed to be derived from wx.stc.StyledTextCtrl. How do I change the color scheme that it currently uses?
| [
"You can use \nstyledTextCtrl.StyleSetSpec(wx.stc.STC_STYLE_INDENTGUIDE, \"fore:#CDCDCD\")\n(Bunch of .StyleSetSpec properties)\n...\n...\n...\nstyCtrl.SetCaretForeground(\"BLUE\")\nstyCtrl.SetSelBackground(True, wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT))\nstyCtrl.SetSelForeground(True, wx.SystemSettings... | [
0
] | [] | [] | [
"color_scheme",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0001211380_color_scheme_python_user_interface_wxpython.txt |
Q:
Using Python (Bash?) to get OS-level system information (CPU Speed)
I want to repeat this question using python. Reason is I have access to 10 nodes in a cluster and each node is not identical. They range in performance and I want to find which is the best computer to use remotely based on memory and cpu-speed/cor... | Using Python (Bash?) to get OS-level system information (CPU Speed) | I want to repeat this question using python. Reason is I have access to 10 nodes in a cluster and each node is not identical. They range in performance and I want to find which is the best computer to use remotely based on memory and cpu-speed/cores available.
EDIT: Heck, even just a command line interface would be use... | [
"Take a look at the SIGAR library which has an extensive API for collecting system data cross-platform. It also has libraries available in many languages (Python, Java, Erlang, Ruby, etc).\n"
] | [
1
] | [] | [] | [
"cpu_speed",
"performance",
"python"
] | stackoverflow_0001272903_cpu_speed_performance_python.txt |
Q:
django problem uploading and saving documents
I am working on a django app. One part would involve uploading files (e.g. spreadsheet or whatever). I am getting this error:
IOError at /fileupload/
[Errno 13] Permission denied: 'fyi.xml'
Where 'fileupload' was the django app name and 'fyi.xml' was the test docum... | django problem uploading and saving documents | I am working on a django app. One part would involve uploading files (e.g. spreadsheet or whatever). I am getting this error:
IOError at /fileupload/
[Errno 13] Permission denied: 'fyi.xml'
Where 'fileupload' was the django app name and 'fyi.xml' was the test document I was uploading.
So, I used chmod and chown to ... | [
"Maybe try changing:\ndestination = open('fyi.xml', 'wb+')\n\nto something like:\nupload_dir = settings.MEDIA_ROOT # or wherever\ndestination = open(os.path.join(upload_dir, 'fyi.xml'), 'wb+')\n\nIf it is an SELinux issue, perhaps this page would help:\n\nhttp://blog.chrisramsay.co.uk/2009/05/22/writing-files-with-... | [
0
] | [] | [] | [
"django",
"file",
"permissions",
"python"
] | stackoverflow_0001273285_django_file_permissions_python.txt |
Q:
What is the importance of an IDE when programming in Python?
I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to... | What is the importance of an IDE when programming in Python? | I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool.
However, much of the documentatio... | [
"IDEs arent very useful in Python; powerful editors such as Emacs and Vim seem very popular among Python programmers.\nThis may confuse e.g. Java programmers, because in Java each file generally requires boilerplate code, such as a package statement, getters and setters.\nPython is much more lightweight in comparis... | [
9,
4,
3,
1,
1,
0
] | [] | [] | [
"ide",
"python"
] | stackoverflow_0001250295_ide_python.txt |
Q:
Porting a Python app that uses Psyco to Mac
I'm trying to port my Python app from Windows to Mac. My app uses Psyco. How exactly do I install Psyco on Mac?
Keep in mind I'm a Mac newbie.
A:
First, you need Apple's XCode installed (well, specifically you only need the gcc compiler that comes with it, but installi... | Porting a Python app that uses Psyco to Mac | I'm trying to port my Python app from Windows to Mac. My app uses Psyco. How exactly do I install Psyco on Mac?
Keep in mind I'm a Mac newbie.
| [
"First, you need Apple's XCode installed (well, specifically you only need the gcc compiler that comes with it, but installing the whole thing is simpler;-). If you want the latest and greatest, sign up for ADC at the lowest (free!-) level and download from there; otherwise it should be in your OSX DVD (or, dependi... | [
2
] | [
"The News page shows that a Mac port is still being written. Learn how to install from source code using Make. Apply that patch, compile, and install.\n"
] | [
-1
] | [
"macos",
"psyco",
"python"
] | stackoverflow_0001273546_macos_psyco_python.txt |
Q:
What is the correct way to generate a json from file in GoogleAppEngine?
I'm quite new to python and GAE, can anyone please provide some help/sample code for doing the following simple task? I managed to read a simple file and output it as a webpage but I need some slightly more complicated logic. Here is the pseu... | What is the correct way to generate a json from file in GoogleAppEngine? | I'm quite new to python and GAE, can anyone please provide some help/sample code for doing the following simple task? I managed to read a simple file and output it as a webpage but I need some slightly more complicated logic. Here is the pseudo code:
open file;
for each line in file {
store first line as album ... | [
"Here's a generator-based solution with a few nice features:\n\nTolerates multiple blank lines between albums in text file \nTolerates leading/trailing blank lines in text file \nUses only an album's worth of memory at a time \nDemonstrates a lot of neato things you can do with Python :) \n\nalbums.txt\nAlbum... | [
3,
1
] | [] | [] | [
"file_io",
"google_app_engine",
"python"
] | stackoverflow_0001274035_file_io_google_app_engine_python.txt |
Q:
How to create new folder?
I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know how.
Suppose I have given folder path like "C:\Program Files\alex"... | How to create new folder? | I want to put output information of my program to a folder. if given folder does not exist, then the program should create a new folder with folder name as given in the program. Is this possible? If yes, please let me know how.
Suppose I have given folder path like "C:\Program Files\alex" and alex folder doesn't exist ... | [
"You can create a folder with os.makedirs()\nand use os.path.exists() to see if it already exists:\nnewpath = r'C:\\Program Files\\arbitrary' \nif not os.path.exists(newpath):\n os.makedirs(newpath)\n\nIf you're trying to make an installer: Windows Installer does a lot of work for you.\n",
"Have you tried os.m... | [
432,
57,
40
] | [] | [] | [
"mkdir",
"python"
] | stackoverflow_0001274405_mkdir_python.txt |
Q:
How can I create a list of files in the current directory and its subdirectories with a given extension?
I'm trying to generate a text file that has a list of all files in the current directory and all of its sub-directories with the extension ".asp". What would be the best way to do this?
A:
You'll want to use ... | How can I create a list of files in the current directory and its subdirectories with a given extension? | I'm trying to generate a text file that has a list of all files in the current directory and all of its sub-directories with the extension ".asp". What would be the best way to do this?
| [
"You'll want to use os.walk which will make that trivial.\nimport os\n\nasps = []\nfor root, dirs, files in os.walk(r'C:\\web'):\n for file in files:\n if file.endswith('.asp'):\n asps.append(file)\n\n",
"walk the tree with os.walk and filter content with glob:\nimport os\nimport glob\n\nasps... | [
20,
4
] | [] | [] | [
"python"
] | stackoverflow_0001274506_python.txt |
Q:
How can I write 'n <<= 1' (Python) in PHP?
I have the Python expression n <<= 1
How do you express this in PHP?
A:
That statement is short for
n = n << 1;
the << operator is means a bitwise shift left, by n positions. Its counterpart is >>, which means shift right by n. To visualize, say you have the value 5, ... | How can I write 'n <<= 1' (Python) in PHP? | I have the Python expression n <<= 1
How do you express this in PHP?
| [
"That statement is short for\nn = n << 1;\n\nthe << operator is means a bitwise shift left, by n positions. Its counterpart is >>, which means shift right by n. To visualize, say you have the value 5, and you want to shift it left by 2 positions. In binary:\n0000 0101 -> 5\nshift left by 2:\n0001 0100 -> 20\n\nBasi... | [
6,
5,
2
] | [] | [] | [
"bitwise_operators",
"operators",
"php",
"python"
] | stackoverflow_0001274493_bitwise_operators_operators_php_python.txt |
Q:
Python: remove lots of items from a list
I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.
I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary ... | Python: remove lots of items from a list | I am in the final stretch of a project I have been working on. Everything is running smoothly but I have a bottleneck that I am having trouble working around.
I have a list of tuples. The list ranges in length from say 40,000 - 1,000,000 records. Now I have a dictionary where each and every (value, key) is a tuple i... | [
"You'll have to measure, but I can imagine this to be more performant:\nmyList = filter(lambda x: myDict.get(x[1], None) != x[0], myList)\n\nbecause the lookup happens in the dict, which is more suited for this kind of thing. Note, though, that this will create a new list before removing the old one; so there's a m... | [
20,
9,
5,
2,
2,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001267260_python.txt |
Q:
Would Like Open Source RSS / News Reader Code or Widget Python or Javascript
I would like to be able to massage certain categories of news feeds to make their entries more consistent. For example, when a job seeker subscribes to two different job sites the feeds s/he gets will differ markedly. One would like to be... | Would Like Open Source RSS / News Reader Code or Widget Python or Javascript | I would like to be able to massage certain categories of news feeds to make their entries more consistent. For example, when a job seeker subscribes to two different job sites the feeds s/he gets will differ markedly. One would like to be able to perform lookups and other work in the news reader, process the incoming f... | [
"You might have a look at the Planet Venus software, which has a filter system that might be useful for what you want.\n",
"I don't know if this is quite what you want, but you could look into Yahoo Pipes. You could also parse the feeds with PyRSS2Gen.\n",
"I'd still be interested in any responses that people m... | [
2,
1,
0
] | [] | [] | [
"javascript",
"open_source",
"python",
"rss"
] | stackoverflow_0001080149_javascript_open_source_python_rss.txt |
Q:
Python looping to read and parse all in a directory
class __init__:
path = "articles/"
files = os.listdir(path)
files.reverse()
def iterate(Files, Path):
def handleXml(content):
months = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September... | Python looping to read and parse all in a directory | class __init__:
path = "articles/"
files = os.listdir(path)
files.reverse()
def iterate(Files, Path):
def handleXml(content):
months = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
parse ... | [
"Could it be because of:\ndel Files[5:]\n\nIt deletes the last 5 entries from the original list as well. Instead of using del, you can try:\nfor file in Files[:5]:\n #...\n\n",
"As stated in the comments, the actual recursion is missing.\nEven if it is there in some other place of the code, the recursion call is... | [
1,
0
] | [] | [] | [
"blogs",
"file_io",
"python",
"xml"
] | stackoverflow_0001272405_blogs_file_io_python_xml.txt |
Q:
Eliminate part of a file in python
In the below file I have 3 occurrences of '.1'. I want to eliminate the last one and write the rest of file to a new file. Kindly suggest some way to do it in PYTHON and thank you all.
d1dlwa_ a.1.1.1 (A:) Protozoan/bacterial hemoglobin {Ciliate (Paramecium caudatum) [TaxId: 588... | Eliminate part of a file in python | In the below file I have 3 occurrences of '.1'. I want to eliminate the last one and write the rest of file to a new file. Kindly suggest some way to do it in PYTHON and thank you all.
d1dlwa_ a.1.1.1 (A:) Protozoan/bacterial hemoglobin {Ciliate (Paramecium caudatum) [TaxId: 5885]}
slfeqlggqaavqavtaqfyaniqadatvatffn... | [
"If the file's not too horrendously huge, by far the simplest approach is:\nf = open('oldfile', 'r')\ndata = f.read()\nf.close()\n\ndata = data.replace('.1.1.1', '.1.1')\n\nf = open('newfile', 'w')\nf.write(data)\nf.close()\n\nIf the file IS horrendously huge, you'll need to read it and write it by pieces. For exam... | [
7,
4,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0001274941_file_python.txt |
Q:
technology recommendation for LAN Dashboard
I'm about to start a fairly large project for a mid-sized business
with a lot of integration with other systems (POS, accounting,
website, inventory, purchasing, etc.) The purpose of the system is to
try to reduce current data siloing and give employees role-based
access... | technology recommendation for LAN Dashboard | I'm about to start a fairly large project for a mid-sized business
with a lot of integration with other systems (POS, accounting,
website, inventory, purchasing, etc.) The purpose of the system is to
try to reduce current data siloing and give employees role-based
access to the specific data entry and reports they need... | [
"If you're comfortable with a LAMP-style stack with PHP, then there's no reason you can't use either Django or Rails. Both are mature, well documented platforms with active, helpful communities. \nBased on what you've described, there's no reason that you can't use either technology. \n",
"Both of these technol... | [
1,
0,
0,
0
] | [] | [] | [
"dashboard",
"django",
"filemaker",
"python",
"ruby_on_rails"
] | stackoverflow_0001263756_dashboard_django_filemaker_python_ruby_on_rails.txt |
Q:
JQuery "get" failure (using Google App Engine on the back-end)
What I am trying to do is pretty simple: yet something has clearly gone awry.
On the Front-End:
function eval() {
var x = 'Unchanged X'
$.get("/", { entry: document.getElementById('entry').value },
function(data){
x = dat... | JQuery "get" failure (using Google App Engine on the back-end) | What I am trying to do is pretty simple: yet something has clearly gone awry.
On the Front-End:
function eval() {
var x = 'Unchanged X'
$.get("/", { entry: document.getElementById('entry').value },
function(data){
x = data;
}
);
$("#result").html(x);
}
On the ... | [
"$(\"#result\").html(x); goes in the get() callback\n",
"If the callback is not running you can try changing the $.get into a $.ajax() call, and adding an error callback, to see if the server is returning an error.\nOr better yet, check in the \"net\" panel in firebug to see what the server response is, which mig... | [
2,
2,
1
] | [] | [] | [
"google_app_engine",
"javascript",
"jquery",
"python"
] | stackoverflow_0001275708_google_app_engine_javascript_jquery_python.txt |
Q:
Take screenshots **quickly** from python
A PIL.Image.grab() takes about 0.5 seconds. That's just to get data from the screen to my app, without any processing on my part. FRAPS, on the other hand, can take screenshots up to 30 FPS. Is there any way for me to do the same from a Python program? If not, how about fro... | Take screenshots **quickly** from python | A PIL.Image.grab() takes about 0.5 seconds. That's just to get data from the screen to my app, without any processing on my part. FRAPS, on the other hand, can take screenshots up to 30 FPS. Is there any way for me to do the same from a Python program? If not, how about from a C program? (I could interface it w/ the P... | [
"If you want fast screenshots, you must use a lower level API, like DirectX or GTK. There are Python wrappers for those, like DirectPython and PyGTK. Some samples I've found follow:\n\nPyGTK sample \nWindows and DirectX samples\n\n"
] | [
7
] | [] | [] | [
"image",
"optimization",
"performance",
"python",
"screen_scraping"
] | stackoverflow_0001276616_image_optimization_performance_python_screen_scraping.txt |
Q:
Batch output redirection when using start command for GUI app
This is the scenario:
We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:
os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
In the batch.b... | Batch output redirection when using start command for GUI app | This is the scenario:
We have a Python script that starts a Windows batch file and redirects its output to a file. Afterwards it reads the file and then tries to delete it:
os.system(C:\batch.bat >C:\temp.txt 2>&1)
os.remove(C:\temp.txt)
In the batch.bat we start a Windows GUI programm like this:
start c:\the_programm... | [
"This is a bit hacky, but you could try it. It uses the AT command to run the_programm.exe up to a minute in the future (which it computes using the %TIME% environment variable and SET arithmetic).\nbatch.bat:\n@echo off\nsetlocal\n:: store the current time so it does not change while parsing\nset t=%time%\n:: pars... | [
2,
0,
0,
0,
0,
0
] | [] | [] | [
"batch_file",
"output_redirect",
"python",
"windows"
] | stackoverflow_0001272309_batch_file_output_redirect_python_windows.txt |
Q:
python subprocess module: looping over stdout of child process
I have some commands which I am running using the subprocess module. I then want to loop over the lines of the output. The documentation says do not do data_stream.stdout.read which I am not but I may be doing something which calls that. I am loopin... | python subprocess module: looping over stdout of child process | I have some commands which I am running using the subprocess module. I then want to loop over the lines of the output. The documentation says do not do data_stream.stdout.read which I am not but I may be doing something which calls that. I am looping over the output like this:
for line in data_stream.stdout:
#do ... | [
"You have to worry about deadlocks if you're communicating with your subprocess, i.e. if you're writing to stdin as well as reading from stdout. Because these pipes may be cached, doing this kind of two-way communication is very much a no-no:\ndata_stream = Popen(mycmd, stdin=PIPE, stdout=PIPE)\ndata_stream.stdin.w... | [
9,
6,
4,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0001277866_python_subprocess.txt |
Q:
How do I detect missing fields in a CSV file in a Pythonic way?
I'm trying to parse a CSV file using Python's csv module (specifically, the DictReader class). Is there a Pythonic way to detect empty or missing fields and throw an error?
Here's a sample file using the following headers: NAME, LABEL, VALUE
foo,bar,... | How do I detect missing fields in a CSV file in a Pythonic way? | I'm trying to parse a CSV file using Python's csv module (specifically, the DictReader class). Is there a Pythonic way to detect empty or missing fields and throw an error?
Here's a sample file using the following headers: NAME, LABEL, VALUE
foo,bar,baz
yes,no
x,y,z
When parsing, I'd like the second line to throw an ... | [
"if any(row[key] in (None, \"\") for key in row):\n # raise error\n\nEdit: Even better:\nif any(val in (None, \"\") for val in row.itervalues()):\n # raise error\n\n",
"Since None and empty strings both evaluate to False, you should consider this:\nfor row in reader:\n for header in HEADERS:\n if ... | [
21,
2,
1,
1,
0
] | [] | [] | [
"csv",
"error_handling",
"python"
] | stackoverflow_0001278749_csv_error_handling_python.txt |
Q:
How to eliminate last digit from each of the top lines
Sequence 1.1.1 ATGCGCGCGATAAGGCGCTA
ATATTATAGCGCGCGCGCGGATATATATATATATATATATT
Sequence 1.2.2 ATATGCGCGCGCGCGCGGCG
ACCCCGCGCGCGCGCGGCGCGATATATATATATATATATATT
Sequence 2.1.1 ATTCGCGCGAGTATAGCGGCG
NOW,I would like to remove the last digit from... | How to eliminate last digit from each of the top lines |
Sequence 1.1.1 ATGCGCGCGATAAGGCGCTA
ATATTATAGCGCGCGCGCGGATATATATATATATATATATT
Sequence 1.2.2 ATATGCGCGCGCGCGCGGCG
ACCCCGCGCGCGCGCGGCGCGATATATATATATATATATATT
Sequence 2.1.1 ATTCGCGCGAGTATAGCGGCG
NOW,I would like to remove the last digit from each of the line that starts with '>'. For example, in thi... | [
"import fileinput\nimport re\n\nfor line in fileinput.input(inplace=True, backup='.bak'):\n line = line.rstrip()\n if line.startswith('>'):\n line = re.sub(r'\\.\\d$', '', line)\n print line\n\nmany details can be changed depending on details of the processing you want, which you have not clearly communicated... | [
7,
4,
4,
2,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0001278664_file_python.txt |
Q:
example for using streamhtmlparser
Can anyone give me an example on how to use http://code.google.com/p/streamhtmlparser to parse out all the A tag href's from an html document? (either C++ code or python code is ok, but I would prefer an example using the python bindings)
I can see how it works in the python test... | example for using streamhtmlparser | Can anyone give me an example on how to use http://code.google.com/p/streamhtmlparser to parse out all the A tag href's from an html document? (either C++ code or python code is ok, but I would prefer an example using the python bindings)
I can see how it works in the python tests, but they expect special tokens alread... | [
"import py_streamhtmlparser\nparser = py_streamhtmlparser.HtmlParser()\nhtml = \"\"\"<html><body><a href='http://google.com' id=100>\n link</a><p><a href=heise.de/></body></html>\"\"\"\ncur_attr = cur_value = None\nfor index, character in enumerate(html):\n parser.Parse(character)\n if parser.State() == ... | [
1
] | [] | [] | [
"c++",
"html",
"parsing",
"python"
] | stackoverflow_0001261264_c++_html_parsing_python.txt |
Q:
Python and regex
i have to parse need string.
Here is command I execute in Linux console:
amixer get Master |grep Mono:
And get, for example,
Mono: Playback 61 [95%] [-3.00dB] [on]
Then i test it from python-console:
import re,os
print re.search( ur"(?<=\[)[0-9]{1,3}", u" Mono: Playback 61 [95%] [-3.00dB] [on]... | Python and regex | i have to parse need string.
Here is command I execute in Linux console:
amixer get Master |grep Mono:
And get, for example,
Mono: Playback 61 [95%] [-3.00dB] [on]
Then i test it from python-console:
import re,os
print re.search( ur"(?<=\[)[0-9]{1,3}", u" Mono: Playback 61 [95%] [-3.00dB] [on]" ).group()[0]
And ge... | [
"os.system() returns the exit code from the application, not the text output of the application.\nYou should read up on the subprocess Python module; it will do what you need.\n",
"Instead of using os.system(), use the subprocess module:\nfrom subprocess import Popen, PIPE\np = Popen(\"amixer get Master | grep Mo... | [
7,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001279087_python_regex.txt |
Q:
BytesIO with python v2.5
Question:
How do I get a byte stream that works like StringIO for Python 2.5?
Application:
I'm converting a PDF to text, but don't want to save a file to the hard disk.
Other Thoughts:
I figured I could use StringIO, but there's no mode parameter (I guess "String" implies text mode).
Appa... | BytesIO with python v2.5 | Question:
How do I get a byte stream that works like StringIO for Python 2.5?
Application:
I'm converting a PDF to text, but don't want to save a file to the hard disk.
Other Thoughts:
I figured I could use StringIO, but there's no mode parameter (I guess "String" implies text mode).
Apparently the io.BytesIO class is... | [
"In Python 2.x, \"string\" means \"bytes\", and \"unicode\" means \"string\". You should use the StringIO or cStringIO modules. The mode will depend on which kind of data you pass in as the buffer parameter.\n",
"If you're working with PDF, then StringIO should be fine as long as you pay heed to the docs:\n\nThe ... | [
4,
2
] | [] | [] | [
"bytesio",
"python",
"stringio"
] | stackoverflow_0001279244_bytesio_python_stringio.txt |
Q:
Multiple Datacenters
I am finding a lack of information regarding handling multiple datacenters. What tools and techniques are available for taking advantage of multiple datacenters? A requirement is that the databases become consistent very quickly.
A:
http://dev.mysql.com/doc/refman/5.0/en/mysql-cluster.html... | Multiple Datacenters | I am finding a lack of information regarding handling multiple datacenters. What tools and techniques are available for taking advantage of multiple datacenters? A requirement is that the databases become consistent very quickly.
| [
"http://dev.mysql.com/doc/refman/5.0/en/mysql-cluster.html\n\n"
] | [
1
] | [] | [] | [
"mysql",
"python",
"replication",
"scaling"
] | stackoverflow_0001279358_mysql_python_replication_scaling.txt |
Q:
sqlalchemy - grouping items and iterating over the sub-lists
Consider a table like this:
| Name | Version | Other |
| ---------------------|-------|
| Foo | 1 | 'a' |
| Foo | 2 | 'b' |
| Bar | 5 | 'c' |
| Baz | 3 | 'd' |
| Baz | 4 | 'e'... | sqlalchemy - grouping items and iterating over the sub-lists | Consider a table like this:
| Name | Version | Other |
| ---------------------|-------|
| Foo | 1 | 'a' |
| Foo | 2 | 'b' |
| Bar | 5 | 'c' |
| Baz | 3 | 'd' |
| Baz | 4 | 'e' |
| Baz | 5 | 'f' |
----------------------------... | [
"If you need full objects you'll need to select maximum versions by name in a subquery and join to that:\nmax_versions = session.query(Cls.name, func.max(Cls.version).label('max_version'))\\\n .group_by(Cls.name).subquery()\nobjs = session.query(Cls).join((max_versions,\n and_(Cls.nam... | [
6
] | [
"Here's the SQL you can call with the engine.execute command:\nselect\n t1.*\nfrom\n table t1\n inner join \n (select\n Name,\n max(version) as Version\n from\n table\n group by\n name) s on\n s.name = t1.name\n and s.version ... | [
-2
] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0001279356_python_sql_sqlalchemy.txt |
Q:
SQLAlchemy - Trying Eager loading.. Attribute Error
I access a a postgres table using SQLAlchemy. I want a query to have eagerloading.
from sqlalchemy.orm import sessionmaker, scoped_session, eagerload
from settings import DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME
from sqlalchem... | SQLAlchemy - Trying Eager loading.. Attribute Error | I access a a postgres table using SQLAlchemy. I want a query to have eagerloading.
from sqlalchemy.orm import sessionmaker, scoped_session, eagerload
from settings import DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME
from sqlalchemy import create_engine
from sqlalchemy import Table, Colu... | [
"You can only eager load on a relation property. Not on the table itself. Eager loading is meant for loading objects from other tables at the same time as getting a particular object. The way you load all the objects for a query will be simply adding all().\nquery = session.query(Zipcode).options(eagerload('zipco... | [
2
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0001279583_postgresql_python_sqlalchemy.txt |
Q:
Default route doesn't work
I'm using the standard routing module with pylons to try and setup a default route for the home page of my website.
I've followed the instructions in the docs and here http://routes.groovie.org/recipes.html but when I try http://127.0.0.1:5000/ I just get the 'Welcome to Pylons' default... | Default route doesn't work | I'm using the standard routing module with pylons to try and setup a default route for the home page of my website.
I've followed the instructions in the docs and here http://routes.groovie.org/recipes.html but when I try http://127.0.0.1:5000/ I just get the 'Welcome to Pylons' default page.
My config/routing.py fil... | [
"You have to delete the static page (myapp/public/index.html). Static\nfiles take priority due to the Cascade configuration at the end of\nmiddleware.py. \n"
] | [
9
] | [] | [] | [
"pylons",
"python",
"routes"
] | stackoverflow_0001279403_pylons_python_routes.txt |
Q:
How to classify users into different countries, based on the Location field
Most web applications have a Location field, in which uses may enter a Location of their choice.
How would you classify users into different countries, based on the location entered.
For eg, I used the Stack Overflow dump of users.xml and ... | How to classify users into different countries, based on the Location field | Most web applications have a Location field, in which uses may enter a Location of their choice.
How would you classify users into different countries, based on the location entered.
For eg, I used the Stack Overflow dump of users.xml and extracted users' names, reputation and location:
['Jeff Atwood', '12853', 'El Cer... | [
"You best bet is to use a Geocoding API like geopy (some Examples).\nThe Google Geocoding API, for example, will return the country in the CountryNameCode-field of the response.\nWith just this one location field the number of false matches will probably be relatively high, but maybe it is good enough.\nIf you had ... | [
2,
1
] | [] | [] | [
"elementtree",
"geolocation",
"python",
"xml"
] | stackoverflow_0001280266_elementtree_geolocation_python_xml.txt |
Q:
Executes Fine In Jail Shell but not in Browser
My python script executes fine in Jail shell, putting out html which I can pipe to an html file. When I look at the file, it's exactly what I want. However when I try to run the file from a browser I get a 500 error. According to the instructions at http://imgseekw... | Executes Fine In Jail Shell but not in Browser | My python script executes fine in Jail shell, putting out html which I can pipe to an html file. When I look at the file, it's exactly what I want. However when I try to run the file from a browser I get a 500 error. According to the instructions at http://imgseekweb.sourceforge.net/install.html the cgi-bin should b... | [
"My hoster resolved the issue. It turns out I'm working in a Windows environment with Microsoft Expression 2.0 HTML editor. The code needed to be converted to a UNIX environment with dos2unix which is installed in the hoster environment and can be accessed from the shell...Thanks for reading this thread to any wh... | [
0
] | [] | [] | [
"browser",
"python",
"scripting"
] | stackoverflow_0001276497_browser_python_scripting.txt |
Q:
Controlling Django ModelForm output
I've got a Model in Django, example code below (not my actual code):
class Department(models.Model):
name = models.CharField(max_length=100)
abbreviation = models.CharField(max_length=4)
Let's say I do the following in the Django shell:
>>> Department(name='Computer Sci... | Controlling Django ModelForm output | I've got a Model in Django, example code below (not my actual code):
class Department(models.Model):
name = models.CharField(max_length=100)
abbreviation = models.CharField(max_length=4)
Let's say I do the following in the Django shell:
>>> Department(name='Computer Science',abbreviation='C S ').save()
>>> Dep... | [
"\nHow can I change the way these items are sorted in the ModelForm code, or in the Model code, rather than in the template?\n\nOne thing you can do is add an ordering meta option. You do this by adding a Meta inner class to a class, with the ordering attribute specified:\nclass Department(models.Model):\n name ... | [
9,
1
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0001279221_django_django_forms_django_templates_python.txt |
Q:
remove duplicates from nested dictionaries in list
quick and very basic newbie question.
If i have list of dictionaries looking like this:
L = []
L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4})
Let's say there exists multiple entries where value3 and value4 are identical to othe... | remove duplicates from nested dictionaries in list | quick and very basic newbie question.
If i have list of dictionaries looking like this:
L = []
L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4})
Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and... | [
"Here's one way:\nkeyfunc = lambda d: (d['value3'], d['value4'])\n\nfrom itertools import groupby\ngiter = groupby(sorted(L, key=keyfunc), keyfunc)\n\nL2 = [g[1].next() for g in giter]\nprint L2\n\n",
"In Python 2.6 or 3.*:\nimport itertools\nimport pprint\n\nL = [{\"value1\": \"fssd\", \"value2\": \"dsfds\", \"v... | [
7,
7,
2,
1,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0001279805_dictionary_python.txt |
Q:
Ruby to python one-liner conversion
I have a little one-liner in my Rails app that returns a range of copyright dates with an optional parameter, e.g.:
def copyright_dates(start_year = Date.today().year)
[start_year, Date.today().year].sort.uniq.join(" - ")
end
I'm moving the app over to Django, and while I l... | Ruby to python one-liner conversion | I have a little one-liner in my Rails app that returns a range of copyright dates with an optional parameter, e.g.:
def copyright_dates(start_year = Date.today().year)
[start_year, Date.today().year].sort.uniq.join(" - ")
end
I'm moving the app over to Django, and while I love it, I miss a bit of the conciseness. ... | [
"from datetime import datetime\n\ndef copyright_dates(start_year = datetime.now().year):\n return \" - \".join(str(y) for y in sorted(set([start_year, datetime.now().year])))\n\n",
"Watch out for the default parameter which is evaluated once. So if your web application runs over 12/31/09 without a restart, yo... | [
5,
5,
2
] | [] | [] | [
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0001280379_django_python_ruby_ruby_on_rails.txt |
Q:
detecting two simultaneous keys in pyglet (python)
I wanted to know how to detect when two keys are simultaneously pressed using pyglet.
I currently have
def on_text_motion(self, motion):
(dx,dy) = ARROW_KEY_TO_VERSOR[motion]
self.window.move_dx_dy((dx,dy))
But this only gets arrow keys one at a time..... | detecting two simultaneous keys in pyglet (python) | I wanted to know how to detect when two keys are simultaneously pressed using pyglet.
I currently have
def on_text_motion(self, motion):
(dx,dy) = ARROW_KEY_TO_VERSOR[motion]
self.window.move_dx_dy((dx,dy))
But this only gets arrow keys one at a time...
I'd like to distinguish between the combination UP+LEF... | [
"Try pyglet.window.key.KeyStateHandler:\nimport pyglet\n\nkey = pyglet.window.key\n\nwin = pyglet.window.Window()\nkeyboard = key.KeyStateHandler()\nwin.push_handlers(keyboard)\n\nprint keyboard[key.UP] and keyboard[key.LEFT]\n\n"
] | [
5
] | [] | [] | [
"keyboard",
"pyglet",
"python"
] | stackoverflow_0001280616_keyboard_pyglet_python.txt |
Q:
What's the regex for removing dots in acronyms but not in domain names?
I want to remove dots in acronyms but not in domain names in a python string. For example,
I want the string
'a.b.c. test@test.com http://www.test.com'
to become
'abc test@test.com http://www.test.com'
The closest regex I made so far is
re.... | What's the regex for removing dots in acronyms but not in domain names? | I want to remove dots in acronyms but not in domain names in a python string. For example,
I want the string
'a.b.c. test@test.com http://www.test.com'
to become
'abc test@test.com http://www.test.com'
The closest regex I made so far is
re.sub('(?:\s|\A).{1}\.',lambda s: s.group()[0:2], s)
which results to
'ab.c. t... | [
"If your data is always formatted like this then why not split your data into 3 parts by splitting on the space.\nThen it's pretty trivial to remove the periods from the first element and use join to remerge the parts.\n",
"I suggest you split the string at '@' (or whatever character makes sense), do the substitu... | [
5,
2,
2,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001279110_python_regex.txt |
Q:
How can I list the methods in a Python 2.5 module?
I'm trying to use a Python library written in C that has no documentation of any kind. I want to use introspection to at least see what methods and classes are in the modules. Does somebody have a function or library I can use to list the functions (with argument ... | How can I list the methods in a Python 2.5 module? | I'm trying to use a Python library written in C that has no documentation of any kind. I want to use introspection to at least see what methods and classes are in the modules. Does somebody have a function or library I can use to list the functions (with argument lists) and classes (with methods and member variables) w... | [
"Here are some things you can do at least:\nimport module\n\nprint dir(module) # Find functions of interest.\n\n# For each function of interest:\nhelp(module.interesting_function)\nprint module.interesting_function.func_defaults\n\n",
"Mark Pilgrim's chapter 4, which you mention, does actually apply just fine to ... | [
58,
12,
8,
4
] | [] | [] | [
"introspection",
"python",
"python_2.5"
] | stackoverflow_0001280787_introspection_python_python_2.5.txt |
Q:
In python is there an easier way to write 6 nested for loops?
This problem has been getting at me for a while now. Is there an easier way to write nested for loops in python? For example if my code went something like this:
for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
... | In python is there an easier way to write 6 nested for loops? | This problem has been getting at me for a while now. Is there an easier way to write nested for loops in python? For example if my code went something like this:
for y in range(3):
for x in range(3):
do_something()
for y1 in range(3):
for x1 in range(3):
do_something_else()
would th... | [
"If you're frequently iterating over a Cartesian product like in your example, you might want to investigate Python 2.6's itertools.product -- or write your own if you're in an earlier Python.\nfrom itertools import product\nfor y, x in product(range(3), repeat=2):\n do_something()\n for y1, x1 in product(range(3... | [
60,
14,
10,
8,
6,
4,
3,
3,
2,
2,
1
] | [] | [] | [
"for_loop",
"nested_loops",
"python"
] | stackoverflow_0001280667_for_loop_nested_loops_python.txt |
Q:
wxPython: Items in BoxSizer don't expand horizontally, only vertically
I have several buttons in various sizers and they expand in the way that I want them to. However, when I add the parent to a new wx.BoxSizer that is used to add a border around all the elements in the frame, the sizer that has been added functi... | wxPython: Items in BoxSizer don't expand horizontally, only vertically | I have several buttons in various sizers and they expand in the way that I want them to. However, when I add the parent to a new wx.BoxSizer that is used to add a border around all the elements in the frame, the sizer that has been added functions correctly vertically, but not horizontally.
The following code demonstra... | [
"First of all, you're passing some flags incorrectly. BoxSizer takes wxHORIZONTAL or wxVERTICAL, not wxEXPAND. sizer.Add does not take wxHORIZONTAL.\nIf you have a VERTICAL BoxSizer, wxEXPAND will make the control fill horizontally, while a proportion of 1 or more (second argument to Add) will make the control fi... | [
28
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0001280600_python_wxpython_wxwidgets.txt |
Q:
Why can't I set a global variable in Python?
How do global variables work in Python? I know global variables are evil, I'm just experimenting.
This does not work in python:
G = None
def foo():
if G is None:
G = 1
foo()
I get an error:
UnboundLocalError: local variable 'G' referenced before assignme... | Why can't I set a global variable in Python? | How do global variables work in Python? I know global variables are evil, I'm just experimenting.
This does not work in python:
G = None
def foo():
if G is None:
G = 1
foo()
I get an error:
UnboundLocalError: local variable 'G' referenced before assignment
What am I doing wrong?
| [
"You need the global statement:\ndef foo():\n global G\n if G is None:\n G = 1\n\nIn Python, variables that you assign to become local variables by default. You need to use global to declare them as global variables. On the other hand, variables that you refer to but do not assign to do not automatical... | [
71,
10,
9,
2
] | [] | [] | [
"global_variables",
"python"
] | stackoverflow_0001281184_global_variables_python.txt |
Q:
Accessing elements with offsets in Python's for .. in loops
I've been mucking around a bit with Python, and I've gathered that it's usually better (or 'pythonic') to use
for x in SomeArray:
rather than the more C-style
for i in range(0, len(SomeArray)):
I do see the benefits in this, mainly cleaner code, and the... | Accessing elements with offsets in Python's for .. in loops | I've been mucking around a bit with Python, and I've gathered that it's usually better (or 'pythonic') to use
for x in SomeArray:
rather than the more C-style
for i in range(0, len(SomeArray)):
I do see the benefits in this, mainly cleaner code, and the ability to use the nice map() and related functions. However, I ... | [
"The way to do this in Python is:\nfor i, x in enumerate(SomeArray):\n print i, x\n\nThe enumerate generator produces a sequence of 2-tuples, each containing the array index and the element.\n",
"List indexing and zip() are your friends.\nHere's my answer for your more specific question:\n\nI might want to add... | [
15,
6
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0001281752_loops_python.txt |
Q:
Copying files to directories as specified in a file list with python
I have a bunch of files in a single directory that I would like to organize in sub-directories.
This directory structure (which file would go in which directory) is specified in a file list that looks like this:
Directory: Music\
-> 01-some_song1... | Copying files to directories as specified in a file list with python | I have a bunch of files in a single directory that I would like to organize in sub-directories.
This directory structure (which file would go in which directory) is specified in a file list that looks like this:
Directory: Music\
-> 01-some_song1.mp3
-> 02-some_song2.mp3
-> 03-some_song3.mp3
Directory: Images\
-> 01-so... | [
"I think that the cause is that you are reusing always the same list. \ndel tmp[:] clears the list and doesn't create a new instance. In your case, you need to create a new list by calling tmp = []\nFollowing fix should work (I didn't test it)\n\ndef get_values(file):\n values = []\n tmp = []\n pattern = r... | [
1,
1,
0
] | [] | [] | [
"copy",
"directory",
"file",
"python"
] | stackoverflow_0001281944_copy_directory_file_python.txt |
Q:
Handling both SSL and non-SSL connections when inheriting from httplib.HTTP(s)Connection
I have a class that inherits from httplib.HTTPSConnection.
class MyConnection(httplib.HTTPSConnection):
def __init__(self, *args, **kw):
httplib.HTTPSConnection.__init__(self,*args, **kw)
...
Is it possible to turn... | Handling both SSL and non-SSL connections when inheriting from httplib.HTTP(s)Connection | I have a class that inherits from httplib.HTTPSConnection.
class MyConnection(httplib.HTTPSConnection):
def __init__(self, *args, **kw):
httplib.HTTPSConnection.__init__(self,*args, **kw)
...
Is it possible to turn off the SSL layer when the class is instantiatied so I can also use it to communicate with no... | [
"Per your last paragraph, in Python you can use something like a factory pattern:\nclass Foo:\n def doit(self):\n print \"I'm a foo\"\nclass Bar:\n def doit(self):\n print \"I'm a bar\"\n\ndef MakeClass(isSecure):\n if isSecure:\n base = Foo\n else:\n base = Bar\n\n class ... | [
2,
1,
0
] | [] | [] | [
"http",
"https",
"python"
] | stackoverflow_0001282368_http_https_python.txt |
Q:
How to prevent Satchmo forms from displaying asterisk after required fields?
I'm customizing my Satchmo store forms and have an icon that appears before any required fields. The problem is, Satchmo seems to want to render a text asterisk after the required fields. I'm using field.label to get this label, should ... | How to prevent Satchmo forms from displaying asterisk after required fields? | I'm customizing my Satchmo store forms and have an icon that appears before any required fields. The problem is, Satchmo seems to want to render a text asterisk after the required fields. I'm using field.label to get this label, should I be using something else?
EDIT: All my form templates are hard coded. I have an ... | [
"What happens if you do the following?\n\nCopy some or all of Satchmo's form templates to a new location and modify them to remove the asterisks\nArrange it so that your copies of those templates are seen before Satchmo's copies (by configuring the template loader settings appropriately, say by placing the app with... | [
1
] | [] | [] | [
"django",
"field",
"forms",
"python",
"satchmo"
] | stackoverflow_0001267874_django_field_forms_python_satchmo.txt |
Q:
Explain socket buffers please
I was trying to find examples about socket programming and came upon this script:
http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py
When reading through this script i found this line:
listenSocket.listen(5)
As i understand it - it reads 5 bytes from the buff... | Explain socket buffers please | I was trying to find examples about socket programming and came upon this script:
http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py
When reading through this script i found this line:
listenSocket.listen(5)
As i understand it - it reads 5 bytes from the buffer and then does stuff with it...
... | [
"The following is applicable to sockets in general, but it should help answer your specific question about using sockets from Python.\nsocket.listen() is used on a server socket to listen for incoming connection requests.\nThe parameter passed to listen is called the backlog and it means how many connections should... | [
13,
0,
0
] | [] | [] | [
"python",
"python_stackless",
"sockets",
"stackless"
] | stackoverflow_0001282656_python_python_stackless_sockets_stackless.txt |
Q:
What's the Ruby equivalent of Python's os.walk?
Does anyone know if there's an existing module/function inside Ruby to traverse file system directories and files? I'm looking for something similar to Python's os.walk. The closest module I've found is Find but requires some extra work to do the traversal.
The Pyth... | What's the Ruby equivalent of Python's os.walk? | Does anyone know if there's an existing module/function inside Ruby to traverse file system directories and files? I'm looking for something similar to Python's os.walk. The closest module I've found is Find but requires some extra work to do the traversal.
The Python code looks like the following:
for root, dirs, fil... | [
"The following will print all files recursively. Then you can use File.directory? to see if the it is a directory or a file.\nDir['**/*'].each { |f| print f }\n\n",
"Find seems pretty simple to me:\nrequire \"find\"\nFind.find('mydir'){|f| puts f}\n\n",
"require 'pathname'\n\ndef os_walk(dir)\n root = Pathname... | [
27,
10,
5
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0001281090_python_ruby.txt |
Q:
aap - python trouble
i'm trying to run aap-application. Version is 1.076 (tried higher). All commands send me an error like:
> Traceback (most recent call last):
> File "/usr/bin/aap", line 10, in
> <module>
> import Main File "/usr/share/aap/Main.py", line 14, in
> <module>
> from DoAddDef import doa... | aap - python trouble | i'm trying to run aap-application. Version is 1.076 (tried higher). All commands send me an error like:
> Traceback (most recent call last):
> File "/usr/bin/aap", line 10, in
> <module>
> import Main File "/usr/share/aap/Main.py", line 14, in
> <module>
> from DoAddDef import doadddef File "/usr/share/a... | [
"Well, as is a reserved word in Python. So, that can't be used in FileType.py as a variable name.\nTry updating your installation of aap or writing in to the aap authors/forums.\n",
"as is a reserved word in Python.\nSeems aap-application was written for Python 2.5 and bellow:\n\nChanged in version 2.5: Both as ... | [
6,
3
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0001282828_linux_python.txt |
Q:
How are nested dictionaries handled by DictWriter?
Using the CSV module in python, I was experimenting with the DictWriter class to convert dictionaries to rows in a csv. Is there any way to handle nested dictionaries? Specifically, I'm exporting Disqus comments that have a structure like this:
{
u'status': u'app... | How are nested dictionaries handled by DictWriter? | Using the CSV module in python, I was experimenting with the DictWriter class to convert dictionaries to rows in a csv. Is there any way to handle nested dictionaries? Specifically, I'm exporting Disqus comments that have a structure like this:
{
u'status': u'approved',
u'forum': {u'id': u'', u'': u'', u'shortname': ... | [
"I think the main problem your going to have is how to represent a nested data structure in one flat row of csv data.\nYou could use some form of name mangeling to flatten the keys from the sub dict's into the top level dict.\neg thread': {u'allow_comments': \nwould become thread_allows_comments. \n"
] | [
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0001282920_csv_python.txt |
Q:
Auto-tab between fields on Django admin site
I have an inline on a model with data with a fixed length, that has to be entered very fast, so I was thinking about a way of "tabbing" through fields automatically when the field is filled...
Could that be possible?
A:
Sure it's possible, but it will need some javasc... | Auto-tab between fields on Django admin site | I have an inline on a model with data with a fixed length, that has to be entered very fast, so I was thinking about a way of "tabbing" through fields automatically when the field is filled...
Could that be possible?
| [
"Sure it's possible, but it will need some javascript. You'd want to bind an event to the keypress event on each field, and when it fires test the length of the text entered so far - if it matches, move the focus onto the next field.\n",
"I can recommend the following links:\n\nJQuery AutoTab\n\n"
] | [
1,
1
] | [] | [] | [
"django",
"django_admin",
"field",
"python"
] | stackoverflow_0000881536_django_django_admin_field_python.txt |
Q:
Using Python to read the screen and controlling keyboard/mouse on OSX
I'm looking for or trying to write a testing suite in Python which will control the mouse/keyboard and watch the screen for changes.
The obvious parts I need are (1) screen watcher, (2) keyboard/mouse control.
The latter is explained here, but w... | Using Python to read the screen and controlling keyboard/mouse on OSX | I'm looking for or trying to write a testing suite in Python which will control the mouse/keyboard and watch the screen for changes.
The obvious parts I need are (1) screen watcher, (2) keyboard/mouse control.
The latter is explained here, but what is the best way to go about doing the former on OSX?
| [
"I can't think of a smart way to \"watch the screen for changes\" in any OS nor with any language. On MacOSX, you can take screenshots programmatically at any time, e.g. with code like the one Apple shows at this sample (translating the Objective C into Python + PyObjC if you want), or more simply by executing the ... | [
2
] | [] | [] | [
"macos",
"python",
"user_interface"
] | stackoverflow_0001282860_macos_python_user_interface.txt |
Q:
Recursive generation + filtering. Better non-recursive?
I have the following need (in python):
generate all possible tuples of length 12 (could be more) containing either 0, 1 or 2 (basically, a ternary number with 12 digits)
filter these tuples according to specific criteria, culling those not good, and keeping... | Recursive generation + filtering. Better non-recursive? | I have the following need (in python):
generate all possible tuples of length 12 (could be more) containing either 0, 1 or 2 (basically, a ternary number with 12 digits)
filter these tuples according to specific criteria, culling those not good, and keeping the ones I need.
As I had to deal with small lengths until ... | [
"How about\nimport itertools\n\nresults = []\nfor x in itertools.product(range(3), repeat=12):\n if myfilter(x):\n results.append(x)\n\nwhere myfilter does the selection. Here, for example, only allowing result with 10 or more 1's,\ndef myfilter(x): # example filter, only take lists with 10 or more 1s\n... | [
4,
1,
0
] | [] | [] | [
"functional_programming",
"python",
"recursion"
] | stackoverflow_0001283266_functional_programming_python_recursion.txt |
Q:
How do unit tests work in django-tagging, because I want mine to run like that?
Few times while browsing tests dir in various Django apps I stumbled across models.py and settings.py files (in django-tagging for example).
But there's no code to be found that syncs test models or applies custom test settings - but ... | How do unit tests work in django-tagging, because I want mine to run like that? | Few times while browsing tests dir in various Django apps I stumbled across models.py and settings.py files (in django-tagging for example).
But there's no code to be found that syncs test models or applies custom test settings - but tests make use of them just as if django would auto-magically load them. However if I... | [
"If you want to run the tests in django-tagging, you can try:\n\ndjango-admin.py test --settings=tagging.tests.settings\n\nBasically, it uses doctests which are in the tests.py file inside the tests package/directory. The tests use the settings file in that same directory (and specified in the command line to djan... | [
1,
0
] | [] | [] | [
"django",
"python",
"unit_testing"
] | stackoverflow_0001279032_django_python_unit_testing.txt |
Q:
In GTK, how do I make a window unable to be closed?
For example, graying out the "X" on windows systems.
A:
If Gtk can't convince the window manager you can always connect the "delete-event" signal and return True from the callback. Doing this Gtk assumes that the callback handle that signal and does nothing.
im... | In GTK, how do I make a window unable to be closed? | For example, graying out the "X" on windows systems.
| [
"If Gtk can't convince the window manager you can always connect the \"delete-event\" signal and return True from the callback. Doing this Gtk assumes that the callback handle that signal and does nothing.\nimport gtk\n\nwindow = gtk.Window()\nwindow.connect('delete-event',lambda widget, event: True)\n\n",
"Just ... | [
5,
4
] | [] | [] | [
"gtk",
"pygtk",
"python",
"windows"
] | stackoverflow_0001235417_gtk_pygtk_python_windows.txt |
Q:
Python Data Descriptor With Pass-through __set__ command
I'm having a bit of an issue solving a problem I'm looking at. I have a specialized set of functions which are going to be in use across a program, which are basically dynamic callables which can replace functions and methods. Due to the need to have them ... | Python Data Descriptor With Pass-through __set__ command | I'm having a bit of an issue solving a problem I'm looking at. I have a specialized set of functions which are going to be in use across a program, which are basically dynamic callables which can replace functions and methods. Due to the need to have them work properly to emulate the functionality of methods, these f... | [
"I think the cleanest solution is to leave __set__ alone, and set the descriptor on the class -- wrapping the original class if needed. I.e., instead of x.a = Descriptor(), do setdesc(x, 'a', Descriptor() where:\nclass Wrapper(object): pass\n\ndef setdesc(x, name, desc):\n t = type(x)\n if not issubclass(t, wrap... | [
1,
0
] | [] | [] | [
"descriptor",
"function",
"methods",
"python",
"set"
] | stackoverflow_0001283435_descriptor_function_methods_python_set.txt |
Q:
URLconfs in Django
I am going through the Django sample application and come across the URLConf.
I thought the import statement on the top resolves the url location, but for 'mysite.polls.urls' I couldn't remove the quotes by including in the import statement.
Why should I use quotes for 'mysite.polls.urls' and no... | URLconfs in Django | I am going through the Django sample application and come across the URLConf.
I thought the import statement on the top resolves the url location, but for 'mysite.polls.urls' I couldn't remove the quotes by including in the import statement.
Why should I use quotes for 'mysite.polls.urls' and not for admin url? and wha... | [
"You've elided a bunch of stuff, but do you have the following statement in there?\nfrom django.contrib import admin\n\nIf so, that would explain why you don't need to quote the latter. See the django documentation for AdminSite.urls for more information.\nIf you want to remove the quotes from the former, then:\ni... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001283811_django_python.txt |
Q:
How does mercurial work without Python installed?
I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that.
How does it work?
Also, is it possible to force Mercurial run on IronPython and will it be compatible?
Thank you.
A:
The Mercurial wind... | How does mercurial work without Python installed? | I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that.
How does it work?
Also, is it possible to force Mercurial run on IronPython and will it be compatible?
Thank you.
| [
"The Mercurial windows installer is packaged using py2exe. This places the python interpreter as a DLL inside of a file called \"library.zip\". \nOn my machine, it is placed in \"C:\\Program Files\\TortoiseHg\\library.zip\"\nThis zip file also contains the python libraries that are required by mercurial. \nFor a ... | [
17,
7,
6,
3
] | [] | [] | [
"ironpython",
"mercurial",
"python"
] | stackoverflow_0001231853_ironpython_mercurial_python.txt |
Q:
Django - SQL Query - Timestamp
Can anyone turn me to a tutorial, code or some kind of resource that will help me out with the following problem.
I have a table in a mySQL database. It contains an ID, Timestamp, another ID and a value. I'm passing it the 'main' ID which can uniquely identify a piece of data. Howeve... | Django - SQL Query - Timestamp | Can anyone turn me to a tutorial, code or some kind of resource that will help me out with the following problem.
I have a table in a mySQL database. It contains an ID, Timestamp, another ID and a value. I'm passing it the 'main' ID which can uniquely identify a piece of data. However, I want to do a time search on thi... | [
"If the table in question maps to a Django model MyModel, e.g.\nclass MyModel(models.Model):\n ...\n primaryid = ...\n timestamp = ...\n secondaryid = ...\n valuefield = ...\n\nthen you can use\nMyModel.objects.filter(\n primaryid=1987\n ).exclude(\n ... | [
3,
2
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0001279490_django_mysql_python.txt |
Q:
Does django's Form class maintain state?
I'm building my first form with django, and I'm seeing some behavior that I really did not expect at all. I defined a form class:
class AssignmentFilterForm(forms.Form):
filters = []
filter = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(forms.Form, se... | Does django's Form class maintain state? | I'm building my first form with django, and I'm seeing some behavior that I really did not expect at all. I defined a form class:
class AssignmentFilterForm(forms.Form):
filters = []
filter = forms.ChoiceField()
def __init__(self, *args, **kwargs):
super(forms.Form, self).__init__(*args, **kwargs)
self.filters... | [
"This is actually a feature of Python that catches a lot of people.\nWhen you define variables on the class as you have with filters = [] the right half of the expression is evaluated when the class is initially defined. So when your code is first run it will create a new list in memory and return a reference to th... | [
7,
2,
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001275009_django_python.txt |
Q:
Stackless python stopped mod_python/apache from working
I installed stackless pyton 2.6.2 after reading several sites that said its fully compatible with vanilla python. After installing i found that my django applications do not work any more.
I did reinstall django (1.1) again and now im kind of lost. The error ... | Stackless python stopped mod_python/apache from working | I installed stackless pyton 2.6.2 after reading several sites that said its fully compatible with vanilla python. After installing i found that my django applications do not work any more.
I did reinstall django (1.1) again and now im kind of lost. The error that i get is 500:
Internal Server Error
The server encounter... | [
"When you install a new version of Python (whether stackless or not) you also need to reinstall all of the third party modules you need -- either from sources, which you say you don't want to do, or from packages built for the new version of Python you've just installed. \nSo, check the repository from which you in... | [
2
] | [] | [] | [
"mod_python",
"mod_wsgi",
"python",
"python_stackless",
"stackless"
] | stackoverflow_0001283856_mod_python_mod_wsgi_python_python_stackless_stackless.txt |
Q:
Does one often use libraries outside the standard ones?
I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3... | Does one often use libraries outside the standard ones? | I am trying to learn Python and referencing the documentation for the standard Python library from the Python website, and I was wondering if this was really the only library and documentation I will need or is there more? I do not plan to program advanced 3d graphics or anything advanced at the moment.
Edit:
Thanks v... | [
"For the basics, yes, the standard Python library is probably all you'll need. But as you continue programming in Python, eventually you will need some other library for some task -- for instance, I recently needed to generate a tone at a specific, but differing, frequency for an application, and pyAudiere did the... | [
2,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"libraries",
"python"
] | stackoverflow_0001283922_libraries_python.txt |
Q:
django auto entry generation
I am trying to make an automated database entry generation with Django, whenever I trigger it to happen.
For instance, assume I have a such model:
class status_entry(models.Model):
name = models.TextField()
date = models.DateField()
status = models.BooleanField()
and I hav... | django auto entry generation | I am trying to make an automated database entry generation with Django, whenever I trigger it to happen.
For instance, assume I have a such model:
class status_entry(models.Model):
name = models.TextField()
date = models.DateField()
status = models.BooleanField()
and I have several entries to the model suc... | [
"You can overwrite save and do the autofill there (daterange function taken from here):\nfrom datetime import timedelta\n\ndef daterange(start_date, end_date):\n for n in range((end_date - start_date).days):\n yield start_date + timedelta(n)\n\n\nclass StatusEntry(models.Model):\n name = models.TextFie... | [
0
] | [] | [] | [
"django",
"django_models",
"python",
"scripting"
] | stackoverflow_0001284814_django_django_models_python_scripting.txt |
Q:
Programmatically change font color of text in PDF
I'm not familiar with the PDF specification at all. I was wondering if it's possible to directly manipulate a PDF file so that certain blocks of text that I've identified as important are highlighted in colors of my choice. Language of choice would be python.
A:
... | Programmatically change font color of text in PDF | I'm not familiar with the PDF specification at all. I was wondering if it's possible to directly manipulate a PDF file so that certain blocks of text that I've identified as important are highlighted in colors of my choice. Language of choice would be python.
| [
"It's possible, but not necessarily easy, because the PDF format is so rich. You can find a document describing it in detail here. The first elementary example it gives about how PDFs display text is:\nBT\n/F13 12 Tf\n288 720 Td\n(ABC) Tj\nET\n\nBT and ET are commands to begin and end a text object; Tf is a command... | [
16,
0
] | [] | [] | [
"fonts",
"pdf",
"python"
] | stackoverflow_0001283065_fonts_pdf_python.txt |
Q:
Why can't you add attributes to object in python?
(Written in Python shell)
>>> o = object()
>>> o.test = 1
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass
>>> t = test1()
>>> t.test
Tr... | Why can't you add attributes to object in python? | (Written in Python shell)
>>> o = object()
>>> o.test = 1
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass
>>> t = test1()
>>> t.test
Traceback (most recent call last):
File "<pyshell#50>",... | [
"Notice that an object instance has no __dict__ attribute:\n>>> dir(object())\n['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']\n\nAn example to illustrate this behavior in a derived class:\n>>> class ... | [
57,
4
] | [] | [] | [
"attributes",
"instances",
"python"
] | stackoverflow_0001285269_attributes_instances_python.txt |
Q:
DOCTEST==argv[0] as a convention?
In a bit of Python I'm writing (a command line and filter testing tool: claft) I wanted a simple way to invoke the built-in test suite (doctest) and I decided on the following:
if 'DOCTEST' in os.environ and os.environ['DOCTEST']==sys.argv[0]:
_runDocTests()
sys.exit()
Th... | DOCTEST==argv[0] as a convention? | In a bit of Python I'm writing (a command line and filter testing tool: claft) I wanted a simple way to invoke the built-in test suite (doctest) and I decided on the following:
if 'DOCTEST' in os.environ and os.environ['DOCTEST']==sys.argv[0]:
_runDocTests()
sys.exit()
Thus if the DOCTEST variable is set for s... | [
"Since you're already doing command-line parsing, why not just add a --selftest option? You won't have to worry about any conflicts that way, and invocation will be easier.\n",
"Another hackish way to avoid namespace conflicts with the environment: looks for myprogname_DEBUG or the like. \n"
] | [
3,
0
] | [] | [] | [
"doctest",
"python",
"testing",
"unit_testing"
] | stackoverflow_0001281385_doctest_python_testing_unit_testing.txt |
Q:
How will Python and Ruby applications be affected by .NET?
I'm curious about how .NET will affect Python and Ruby applications.
Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific?
If they don't use any of the .NET features,... | How will Python and Ruby applications be affected by .NET? | I'm curious about how .NET will affect Python and Ruby applications.
Will applications written in IronPython/IronRuby be so specific to the .NET environment, that they will essentially become platform specific?
If they don't use any of the .NET features, then what is the advantage of IronPython/IronRuby over their no... | [
"I can't say anything about IronRuby, but most python implementations (like IronPython, Jython and PyPy) try to be as true to the CPython implementation as possible. IronPython is quickly becoming one of the best in this respect though, and there is a lot of traffic on Planet Python about it.\nThe main thing that w... | [
5,
2,
1,
1,
1,
0,
0
] | [] | [] | [
".net",
"ironpython",
"ironruby",
"python",
"ruby"
] | stackoverflow_0000466897_.net_ironpython_ironruby_python_ruby.txt |
Q:
What would you call a non-persistent data structure that allows persistent operations?
I've got a class that is essentially mutable, but allows for some "persistent-like" operations. For example, I can mutate the object like this (in Python):
# create an object with y equal to 3 and z equal to "foobar"
x = MyData... | What would you call a non-persistent data structure that allows persistent operations? | I've got a class that is essentially mutable, but allows for some "persistent-like" operations. For example, I can mutate the object like this (in Python):
# create an object with y equal to 3 and z equal to "foobar"
x = MyDataStructure(y = 3, z = "foobar")
x.y = 4
However, in lieu of doing things this way, there ar... | [
"I call this kind of data Persistable but not sure if it's a word\n.\n",
"It's just a optimized copy, I'd rather rename the operation to reflect that. \na = x.copy_with(y=4)\n\n"
] | [
2,
2
] | [] | [] | [
"data_structures",
"functional_programming",
"naming",
"persistence",
"python"
] | stackoverflow_0001285657_data_structures_functional_programming_naming_persistence_python.txt |
Q:
How To Clone/Mutate A Model In Django Without Subclassing
'Ello, all. I'm trying to create a model in Django based on - but not subclassing or having a DB relation to - another model. My original model looks something like this: it stores some data with a date/time stamp.
class Entry(Model):
data1 = FloatFi... | How To Clone/Mutate A Model In Django Without Subclassing | 'Ello, all. I'm trying to create a model in Django based on - but not subclassing or having a DB relation to - another model. My original model looks something like this: it stores some data with a date/time stamp.
class Entry(Model):
data1 = FloatField()
data2 = FloatField()
entered = DateTimeField(... | [
"What if you create a AbstractEntry class with all the data1 stuff and then, two subclasses: Entry and EntryDailyAvg.\nCheck the docs for info on how to tell django that one class is abstract.\n"
] | [
2
] | [] | [] | [
"aggregation",
"django",
"django_models",
"dry",
"python"
] | stackoverflow_0001285977_aggregation_django_django_models_dry_python.txt |
Q:
Using Python Mechanize like "Tamper Data"
I'm writing a web testing script with python (2.6) and mechanize (0.1.11). The page I'm working with has an html form with a select field like this:
<select name="field1" size="1">
<option value="A" selected>A</option>
<option value="B">B</option>
<option valu... | Using Python Mechanize like "Tamper Data" | I'm writing a web testing script with python (2.6) and mechanize (0.1.11). The page I'm working with has an html form with a select field like this:
<select name="field1" size="1">
<option value="A" selected>A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</optio... | [
"After poking around with the guts of ClientForm, it looks like you can trick it into adding another item.\nFor a select field, something like this seems to work:\nxitem = ClientForm.Item(browser.form.find_control(name=\"field1\"), \n {'contents':'E', 'value':'E', 'label':'E'})\n\nSimilarly, for a radio butt... | [
7
] | [] | [] | [
"forms",
"mechanize",
"python",
"tampering"
] | stackoverflow_0001285895_forms_mechanize_python_tampering.txt |
Q:
How can I check to see if a Python script was started interactively?
I'd like for a script of mine to have 2 behaviours, one when started as a scheduled task, and another if started manually. How could I test for interactiveness?
EDIT: this could either be a cron job, or started by a windows batch file, through th... | How can I check to see if a Python script was started interactively? | I'd like for a script of mine to have 2 behaviours, one when started as a scheduled task, and another if started manually. How could I test for interactiveness?
EDIT: this could either be a cron job, or started by a windows batch file, through the scheduled tasks.
| [
"You should simply add a command-line switch in the scheduled task, and check for it in your script, modifying the behavior as appropriate. Explicit is better than implicit.\nOne benefit to this design: you'll be able to test both behaviors, regardless of how you actually invoked the script.\n",
"If you want to ... | [
11,
7,
0
] | [] | [] | [
"interactive",
"python"
] | stackoverflow_0001285024_interactive_python.txt |
Q:
Why does this python method gives an error saying global name not defined?
I have a single code file for my Google App Engine project. This simple file has one class, and inside it a few methods.
Why does this python method gives an error saying global name not defined?
Erro NameError: global name 'gen_groups' is ... | Why does this python method gives an error saying global name not defined? | I have a single code file for my Google App Engine project. This simple file has one class, and inside it a few methods.
Why does this python method gives an error saying global name not defined?
Erro NameError: global name 'gen_groups' is not defined
import wsgiref.handlers
from google.appengine.ext import webapp
fr... | [
"It's an instance method, you need to use self.gen_groups(...) and self.gen_albums(...).\nEdit: I'm guessing the TypeError you are getting now is because you removed the 'self' argument from gen_groups(). You'll need to put it back in:\ndef get_groups(self, lines):\n ...\n\n",
"You need to call it explicitly w... | [
5,
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001286235_google_app_engine_python.txt |
Q:
Django - String to Date - Date to UNIX Timestamp
I need to convert a date from a string (entered into a url) in the form of 12/09/2008-12:40:49. Obviously, I'll need a UNIX Timestamp at the end of it, but before I get that I need the Date object first.
How do I do this? I can't find any resources that show the da... | Django - String to Date - Date to UNIX Timestamp | I need to convert a date from a string (entered into a url) in the form of 12/09/2008-12:40:49. Obviously, I'll need a UNIX Timestamp at the end of it, but before I get that I need the Date object first.
How do I do this? I can't find any resources that show the date in that format? Thank you.
| [
"You need the strptime method. If you're on Python 2.5 or higher, this is a method on datetime, otherwise you have to use a combination of the time and datetime modules to achieve this.\nPython 2.5 up:\nfrom datetime import datetime\ndt = datetime.strptime(s, \"%d/%m/%Y-%H:%M:%S\")\n\nbelow 2.5:\nfrom datetime impo... | [
12,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001286619_django_python.txt |
Q:
What is the fastest way to draw an image in Gtk+?
I have an image/pixbuf that I want to draw into a gtk.DrawingArea and refresh frequently, so the blitting operation has to be fast. Doing it the easy way:
def __init__(self):
self.drawing_area = gtk.DrawingArea()
self.image = gtk.gdk.pixbuf_new_from_file("image... | What is the fastest way to draw an image in Gtk+? | I have an image/pixbuf that I want to draw into a gtk.DrawingArea and refresh frequently, so the blitting operation has to be fast. Doing it the easy way:
def __init__(self):
self.drawing_area = gtk.DrawingArea()
self.image = gtk.gdk.pixbuf_new_from_file("image.png")
def area_expose_cb(self, area, event):
self.d... | [
"Try creating Pixmap that uses the same colormap as your drawing area.\ndr_area.realize()\nself.gc = dr_area.get_style().fg_gc[gtk.STATE_NORMAL]\nimg = gtk.gdk.pixbuf_new_from_file(\"image.png\")\nself.image = gtk.gdk.Pixmap(dr_area.window, img.get_width(), img.get_height())\nself.image.draw_pixbuf(self.gc, img, 0,... | [
7,
2,
0
] | [] | [] | [
"cairo",
"gtk",
"pygtk",
"python"
] | stackoverflow_0000959675_cairo_gtk_pygtk_python.txt |
Q:
What is the correct way to clean up when using PyOpenAL?
I'm looking at PyOpenAL for some sound needs with Python (obviously). Documentation is sparse (consisting of a demo script, which doesn't work unmodified) but as far as I can tell, there are two layers. Direct wrapping of OpenAL calls and a lightweight 'pyth... | What is the correct way to clean up when using PyOpenAL? | I'm looking at PyOpenAL for some sound needs with Python (obviously). Documentation is sparse (consisting of a demo script, which doesn't work unmodified) but as far as I can tell, there are two layers. Direct wrapping of OpenAL calls and a lightweight 'pythonic' wrapper - it is the latter I'm concerned with. Specifica... | [
"#relese reference to l b and s\ndel l\ndel b\ndel s \n#now the WaveBuffer and Source should be destroyed, so we could:\npyopenal.quit()\n\nProbably de destructor of pyopenal calls quit() before exit so you dont need to call it yourself.\n"
] | [
1
] | [] | [] | [
"openal",
"python"
] | stackoverflow_0000787850_openal_python.txt |
Q:
Where can i get technical information on how the internals of Django works?
Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client;
which django function receives it?
what middleware get called?
how is the request object create... | Where can i get technical information on how the internals of Django works? | Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client;
which django function receives it?
what middleware get called?
how is the request object created? and what class/function creates it?
What function maps the request to the nece... | [
"Besides reading the source, here's a few articles I've tagged and bookmarked from a little while ago:\n\nHow Django processes a request\nDjango Request Response processing\nDjango internals: authentication\nHow the Heck do Django Models Work\n\nI've found James Bennet's blog to be a a great source for information ... | [
13,
12,
10,
6,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001286176_django_python.txt |
Q:
OCR Playing Cards
I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be a... | OCR Playing Cards | I decided to do a project for fun where I want to take as input the image of a playing card and return its rank and suit. I figure that I only need look at the upper-left corner, since that has all the information. It should be robust - if I have a large image of an Ace of Diamonds, I should be able to scale it anywher... | [
"I don't think there's something already written for what you are trying to accomplish (at least open source and in Python).\nAs for your second question, it depends on what you are trying to recognize. If the inputs can come from different sources -- e.g., different brands of playing cards with distinctive styles ... | [
3,
1,
1,
1
] | [] | [] | [
"artificial_intelligence",
"computer_vision",
"ocr",
"python"
] | stackoverflow_0001279768_artificial_intelligence_computer_vision_ocr_python.txt |
Q:
python scooping and recursion
I am struck in a small recursive code. I have printed output and it prints fine but when I try to put a counter to actually count my answers, it gives me scooping errors.
total = 0
def foo(me, t):
if t<0:
return
if t==0:
total = total+1
return
for i... | python scooping and recursion | I am struck in a small recursive code. I have printed output and it prints fine but when I try to put a counter to actually count my answers, it gives me scooping errors.
total = 0
def foo(me, t):
if t<0:
return
if t==0:
total = total+1
return
for i in range(1, me+1):
total =... | [
"As mentioned by others, you need the global statement for total. Also, as noted by Svante, the for loop is unnecessary as coded since i is always 1. So, with an equivalent version of your code:\ntotal = 0\ndef foo(me, t):\n global total\n if t < 0:\n return\n total = total + 1\n if t == 0:\n ... | [
2,
1,
1,
1,
0
] | [] | [] | [
"python",
"recursion",
"scope"
] | stackoverflow_0001286626_python_recursion_scope.txt |
Q:
Python vs. C# Twitter API libraries
I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users ... | Python vs. C# Twitter API libraries | I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short dea... | [
"The best advice is to use whatever language you are most comfortable with.\nMyself and a colleague have recently re-written our Twitter web-app's entire back-end with a C# service, and the decision for us came down to which library best suited the purpose. A number of the libraries have varying 'features', some a... | [
4,
4,
3,
0,
0,
0,
0
] | [] | [] | [
"api",
"c#",
"python",
"twitter"
] | stackoverflow_0000872054_api_c#_python_twitter.txt |
Q:
Any efficient way to read datas from large binary file?
I need to handle tens of Gigabytes data in one binary file. Each record in the data file is variable length.
So the file is like:
<len1><data1><len2><data2>..........<lenN><dataN>
The data contains integer, pointer, double value and so on.
I found python ca... | Any efficient way to read datas from large binary file? | I need to handle tens of Gigabytes data in one binary file. Each record in the data file is variable length.
So the file is like:
<len1><data1><len2><data2>..........<lenN><dataN>
The data contains integer, pointer, double value and so on.
I found python can not even handle this situation. There is no problem if I re... | [
"struct and array, which other answers recommend, are fine for the details of the implementation, and might be all you need if your needs are always to sequentially read all of the file or a prefix of it. Other options include buffer, mmap, even ctypes, depending on many details you don't mention regarding your exa... | [
5,
2,
2,
2,
1,
1
] | [] | [] | [
"binary",
"file",
"python"
] | stackoverflow_0001287747_binary_file_python.txt |
Q:
Python equivalent of Jstack?
Is there a python equivalent of jstack? I've got a hung process and I really want to see what it's up to because I have yet to reproduce the defect in development.
A:
Python GDB
| Python equivalent of Jstack? | Is there a python equivalent of jstack? I've got a hung process and I really want to see what it's up to because I have yet to reproduce the defect in development.
| [
"Python GDB\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0001289124_python.txt |
Q:
Server Logging - in Database or Logfile?
I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.
I'm planning on logging some basic information for every request (what type of request, ip address of request, sess... | Server Logging - in Database or Logfile? | I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.
I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will b... | [
"First, use a logging library like SLF4J/Logback that allows you to make this decision dynamically. Then you can tweak a configuration file and route some or all of your log messages to each of several different destinations.\nBe very careful before logging to your application database, you can easily overwhelm it... | [
10,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0001055917_logging_python.txt |
Q:
how fast is python's slice
In order to save space and the complexity of having to maintain the consistency of data between different sources, I'm considering storing start/end indices for some substrings instead of storing the substrings themselves. The trick is that if I do so, it's possible I'll be creating sli... | how fast is python's slice | In order to save space and the complexity of having to maintain the consistency of data between different sources, I'm considering storing start/end indices for some substrings instead of storing the substrings themselves. The trick is that if I do so, it's possible I'll be creating slices ALL the time. Is this somet... | [
"\nFast enough as opposed to what? How do you do it right now? What exactly are you storing, what exactly are you retrieving? The answer probably highly depends on this. Which brings us to ...\nMeasure! Don't discuss and analyze theoretically; try and measure what is the more performant way. Then decide whether the... | [
9,
3,
1,
1
] | [
"premature optimization is the rool of all evil.\nProve to yourself that you really have a need to optimize code, then act.\n"
] | [
-2
] | [
"optimization",
"python"
] | stackoverflow_0001286757_optimization_python.txt |
Q:
How do I split different applications across multiple tcp ports on one site?
I have a series of applications which use one model and are all under one site. Essentially a mix of the main website, and public and private api's. Is there a way to make different DJango apps use a different tcp port? I have not been ... | How do I split different applications across multiple tcp ports on one site? | I have a series of applications which use one model and are all under one site. Essentially a mix of the main website, and public and private api's. Is there a way to make different DJango apps use a different tcp port? I have not been able to find anything in the documentation about it.
| [
"Django docs. Optionally, use Apache to setup a subdomain for each application so you don't have to remember all the ports.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001289953_django_python.txt |
Q:
Paypal NVP API with Django
I am looking into using the paypal NVP API to allow users to pay on my website for a recurring subscription.
I have a few questions about the requirements. Will my site have to meet the "PCI Compliance" stuff. I guess I will have to get an SSL certificate and is there anything else th... | Paypal NVP API with Django | I am looking into using the paypal NVP API to allow users to pay on my website for a recurring subscription.
I have a few questions about the requirements. Will my site have to meet the "PCI Compliance" stuff. I guess I will have to get an SSL certificate and is there anything else that is required or that I need to... | [
"There is nothing forcing you to meet PCI Compliance and use SSL, but you should anyway to limit your liability and inspire a little customer trust. \nI thought I read something on the Satchmo Developer's Google group about a person implementing PayPal NVP and having a patch.\n",
"I know this question is a bit ou... | [
0,
0
] | [] | [] | [
"django",
"paypal",
"python"
] | stackoverflow_0000717911_django_paypal_python.txt |
Q:
converting django ForeignKey to a usable directory name
I'm working on a django app where the user will be able to upload documents of various kinds. The relevant part of my models.py is this:
class Materials(models.Model):
id = models.AutoField(primary_key=True)
id_presentations = models.ForeignKey(Prese... | converting django ForeignKey to a usable directory name | I'm working on a django app where the user will be able to upload documents of various kinds. The relevant part of my models.py is this:
class Materials(models.Model):
id = models.AutoField(primary_key=True)
id_presentations = models.ForeignKey(Presentations, db_column='id_Presentations', related_name = "mater... | [
"As of Django 1.0, the upload_to argument to FileFields can be a callable. If I'm understanding your intentions correctly, something like this should do the trick:\ndef material_path(instance, filename):\n return 'documents/%d' % instance.id_presentations.id\n\nclass Materials(models.Model):\n id_presentatio... | [
2,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001290202_django_django_models_python.txt |
Q:
Python Win32 - equivalent function to DriveInfo.IsReady
I'm trying to find an equivalent Python function to the Windows function DriveInfo.IsReady. I've spent a while searching through the functions provided by win32api and win32file but I can't find anything (though perhaps that's because I didn't manage to find... | Python Win32 - equivalent function to DriveInfo.IsReady | I'm trying to find an equivalent Python function to the Windows function DriveInfo.IsReady. I've spent a while searching through the functions provided by win32api and win32file but I can't find anything (though perhaps that's because I didn't manage to find much useful documentation online, so was simply searching th... | [
"I've used GetVolumeInformation in the past to determine this. For example, something like:\ndef is_drive_ready(drive_name):\n try:\n win32api.GetVolumeInformation(drive_name)\n return True\n except:\n return False\n\nprint 'ready:', is_drive_ready('c:\\\\') # true\nprint 'ready:', is_dr... | [
2
] | [] | [] | [
"python",
"winapi"
] | stackoverflow_0001290515_python_winapi.txt |
Q:
list of duplicate dictionaries copy single entry to another list
newbie question again.
Let's say i have a list of nested dictionaries.
a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie},
{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
{"value1"... | list of duplicate dictionaries copy single entry to another list | newbie question again.
Let's say i have a list of nested dictionaries.
a = [{"value1": 1234, "value2": 23423423421, "value3": norway, "value4": charlie},
{"value1": 1398, "value2": 23423412221, "value3": england, "value4": alpha},
{"value1": 1234, "value2": 23234231221, "value3": norway, "value4": charlie},
... | [
"There was a similar question on this recently. Try this entry.\nIn fact, you asked that question: \"Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and easy find and remove those duplicate dictionaries.\"\nIt sounds like the same thing, ri... | [
2
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0001290717_dictionary_list_python.txt |
Q:
How can I capture the error output from the ipython shell?
I'm writing an ipython macro that processes the output of a program. The thing is, the program can sometimes write to stderr , so if I do something like this :
out = !my_program
the out variable will not contain the output. I think it will contain the ex... | How can I capture the error output from the ipython shell? | I'm writing an ipython macro that processes the output of a program. The thing is, the program can sometimes write to stderr , so if I do something like this :
out = !my_program
the out variable will not contain the output. I think it will contain the exit code ( correct me if I'm wrong ).
How can I capture both stdo... | [
"foo 2>&1 means redirect all of the output, including handle 2 (that is, STDERR), from the foo command to handle 1 (that is, STDOUT)\nso here out = !foo 2>&1 maybe good enough. below is the demo:\negg.py: \n#!/usr/bin/env python\n# -*- coding: utf8 -*-\ndef main():\n print 'hello'\n print 3/0\nif __name__ ==... | [
4
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0001289971_ipython_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.