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:
Python File Search Line And Return Specific Number of Lines after Match
I have a text file that has lines representing some data sets. The file itself is fairly long but it contains certain sections of the following format:
Series_Name INFO Number of teams : n1
| Team ... | Python File Search Line And Return Specific Number of Lines after Match | I have a text file that has lines representing some data sets. The file itself is fairly long but it contains certain sections of the following format:
Series_Name INFO Number of teams : n1
| Team | # | wins |
| TeamName1 ... | [
"Try something like this instead (slightly pseudocode).\nwith open('myfile') as fh:\n for line in fh:\n if line == match: # Some actual code here in your conditional:\n for i in range(5):\n additionalData = next(fh)\n\nBy calling next(fh) you can retrieve the next line in the file without screwing u... | [
3
] | [] | [] | [
"file",
"lines",
"match",
"python"
] | stackoverflow_0006431366_file_lines_match_python.txt |
Q:
Zombie process in python multiprocessing daemon
After researching python daemons, this walk through seemed to be the most robust: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
Now I am trying to implement a pool of workers inside the daemon class which I believe is working (I have not... | Zombie process in python multiprocessing daemon | After researching python daemons, this walk through seemed to be the most robust: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
Now I am trying to implement a pool of workers inside the daemon class which I believe is working (I have not thoroughly tested the code) except that on the close... | [
"It is not possible to have 100% confidence in an answer without knowing what is going on in the child/daemon process, but consider if this could be it. Since you have worker threads in your child process, you actually need to build in some logic to join all of those threads once you receive the SIGTERM. Otherwis... | [
5
] | [] | [] | [
"daemon",
"multiprocessing",
"python",
"zombie_process"
] | stackoverflow_0006428842_daemon_multiprocessing_python_zombie_process.txt |
Q:
How do I know if my code is running deployed on GAE or running local?
I have a few imports and statements needed to get some crypto modules from gdata to load into my GAE Python SDK:
from google.appengine.tools.dev_appserver import HardenedModulesHook
HardenedModulesHook._WHITE_LIST_C_MODULES += ['_counter']
But ... | How do I know if my code is running deployed on GAE or running local? | I have a few imports and statements needed to get some crypto modules from gdata to load into my GAE Python SDK:
from google.appengine.tools.dev_appserver import HardenedModulesHook
HardenedModulesHook._WHITE_LIST_C_MODULES += ['_counter']
But this import does not work (nor is it needed) while deployed on GAE, only lo... | [
"I use this on some of my pet projects. Can't remember where I got it.\nimport os\nif 'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Dev'):\n\n",
"If the import actually doesn't work because it throws an ImportError then your best choice it to just try/except the error.\ntry:\n f... | [
2,
2,
0
] | [] | [] | [
"google_app_engine",
"import",
"python"
] | stackoverflow_0006431495_google_app_engine_import_python.txt |
Q:
Django POST data problem in Firefox and IE9 but not Chrome
I'm creating a website with Django and am getting the following error when I try to submit POST data from a form (input has name 'bsubmit') in Firefox and IE9:
"Key 'bsubmit' not found in '<'QueryDict: {u'bsubmit.y': [u'63'], u'bsubmit.x': [u'81'], u'cs... | Django POST data problem in Firefox and IE9 but not Chrome | I'm creating a website with Django and am getting the following error when I try to submit POST data from a form (input has name 'bsubmit') in Firefox and IE9:
"Key 'bsubmit' not found in '<'QueryDict: {u'bsubmit.y': [u'63'], u'bsubmit.x': [u'81'], u'csrfmiddlewaretoken':[u'bunchofnumbers']}>"
This works fine in Ch... | [
"Are you doing anything with the submit button with JavaScript? The inclusion of 'bsubmit.x' and 'bsubmit.y' in the request is very curious on its own.\nThat aside, what are you actually using 'bsubmit' for?\nIn general, you shouldn't be accessing post variables directly anyways. Use this instead:\nbsubmit = reques... | [
1
] | [] | [] | [
"django",
"firefox",
"internet_explorer",
"post",
"python"
] | stackoverflow_0006431042_django_firefox_internet_explorer_post_python.txt |
Q:
Tarring files together as iterable in Python?
I'm running a WSGI server and part of the API I'm writing returns some (rather large) files along with meta-data about them. I'd like to tar/gzip the files together both to conserve bandwidth and so only one file has to be downloaded. Since WSGI lets you return an it... | Tarring files together as iterable in Python? | I'm running a WSGI server and part of the API I'm writing returns some (rather large) files along with meta-data about them. I'd like to tar/gzip the files together both to conserve bandwidth and so only one file has to be downloaded. Since WSGI lets you return an iterable object, I'd like to return an iterable that ... | [
"The bz2 module provides sequential compressing. And it seems the zlib package can compress data sequentially too. So with these modules you could:\n\ntar your files (shouldn't take that long),\nread the archive iteratively in binary mode,\npass read chunks to a sequential compression function, and\nyield the compr... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006431165_python.txt |
Q:
create rdf files based on SKOS data model in python
I want to create a .rdf file containing data in the form of SKOS model and written in RDF/XML format. I prefer using Python language. Can you suggest any good python libraries? If possible, a simple example would be of great help.
thanks
A:
Have a look at RDFLi... | create rdf files based on SKOS data model in python | I want to create a .rdf file containing data in the form of SKOS model and written in RDF/XML format. I prefer using Python language. Can you suggest any good python libraries? If possible, a simple example would be of great help.
thanks
| [
"Have a look at RDFLib:\n\nRDFLib is a Python library for working\nwith RDF, a simple yet powerful\nlanguage for representing information.\nThe library contains parsers and\nserializers for RDF/XML, N3, NTriples,\nTurtle, TriX and RDFa. The library\npresents a Graph interface which can\nbe backed by any one of a nu... | [
9,
1
] | [] | [] | [
"python",
"rdf"
] | stackoverflow_0006422205_python_rdf.txt |
Q:
write array starting from specific column to new workbook using xlwt
I am trying to write an array (data = [][]) to a worksheet I will create using xlwt.
My question is can I specify a column to start from? I am planning to use a for loop to iterate through the array retrieving the values row by row starting a ne... | write array starting from specific column to new workbook using xlwt | I am trying to write an array (data = [][]) to a worksheet I will create using xlwt.
My question is can I specify a column to start from? I am planning to use a for loop to iterate through the array retrieving the values row by row starting a new line with each row ex: first row starts at C1, next row starts at C2 etc... | [
"Something like:\nwb = xlwt.Workbook()\nws = wb.add_sheet('Sheet1')\nfor r, row in enumerate(data):\n for c, col in enumerate(row):\n ws.write(r, 2 + c, label=col)\n\n"
] | [
5
] | [] | [] | [
"python",
"xlwt"
] | stackoverflow_0006431790_python_xlwt.txt |
Q:
Python (or C) library for creating XLSX documents that can handle millions of rows
I'm looking for a library to create XLSX files which can contain upwards of a million rows, and several dozen columns. So far all the libraries I have found in Python consume too much memory, and I haven't found a suitable library t... | Python (or C) library for creating XLSX documents that can handle millions of rows | I'm looking for a library to create XLSX files which can contain upwards of a million rows, and several dozen columns. So far all the libraries I have found in Python consume too much memory, and I haven't found a suitable library to wrap in C. I'd prefer open source so I can modify the code if need be.
EDIT: I have fo... | [
"have you tried ElementTree? if that uses too much memory, use SAX and just process a row at a time. XML parsing - ElementTree vs SAX and DOM\n",
"The XLSX format consists of a number of XML files that have been zipped. If the format of the output will not be changing, it would be trivial to use an existing file ... | [
1,
0
] | [] | [] | [
"c",
"excel",
"openpyxl",
"python",
"xlsx"
] | stackoverflow_0006431719_c_excel_openpyxl_python_xlsx.txt |
Q:
Can I do math inside Python's string formatting "language"?
I would like to do some simple math while I'm doing string formatting. For example
N = {'number':3}
four = '{number:d + 1}'.format(**N)
This doesn't work (of course). Is there a way to accomplish this that I'm not aware of?
Thanks!
A:
"Is there a way t... | Can I do math inside Python's string formatting "language"? | I would like to do some simple math while I'm doing string formatting. For example
N = {'number':3}
four = '{number:d + 1}'.format(**N)
This doesn't work (of course). Is there a way to accomplish this that I'm not aware of?
Thanks!
| [
"\"Is there a way to accomplish this that I'm not aware of?\" If by \"this\" you mean encoding some mathematical logic in the format string using str.format, then no -- not that I'm aware of. However if you use a templating language you can express all kinds of stuff like this.\nThere are a billion different opti... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0006431817_python.txt |
Q:
How can I scrape data from the Israeli Bureau of Statistics web query tool?
The following url:
http://www.cbs.gov.il/ts/ID40d250e0710c2f/databank/series_func_e_v1.html?level_1=31&level_2=1&level_3=7
Gives a data generator of information from the Israeli government which limits the number of data points extracted t... | How can I scrape data from the Israeli Bureau of Statistics web query tool? | The following url:
http://www.cbs.gov.il/ts/ID40d250e0710c2f/databank/series_func_e_v1.html?level_1=31&level_2=1&level_3=7
Gives a data generator of information from the Israeli government which limits the number of data points extracted to a maximum of 50 series at a time. I wonder, is it possible (and if so, how) to... | [
"Take a look at WWW::Mechanize and WWW::HtmlUnit.\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse WWW::Mechanize;\n\nmy $m = WWW::Mechanize->new;\n\n#get page\n$m->get(\"http://www.cbs.gov.il/ts/ID40d250e0710c2f/databank/series_func_e_v1.html?level_1=31&level_2=1&level_3=7\");\n\n#submit the form on the first... | [
8,
3,
1
] | [] | [] | [
"perl",
"python",
"r",
"screen_scraping",
"security"
] | stackoverflow_0006429618_perl_python_r_screen_scraping_security.txt |
Q:
Access a dictionary as a list
I have a data source which is best modeled with a dictionary (it is a collection of key=value pairs). For a specific visualization purpose, I need to provide a list-like data access interface (in addition to the regular dictionary interface), meaning that you should be able to do the ... | Access a dictionary as a list | I have a data source which is best modeled with a dictionary (it is a collection of key=value pairs). For a specific visualization purpose, I need to provide a list-like data access interface (in addition to the regular dictionary interface), meaning that you should be able to do the following:
data["mykey"] # returns ... | [
"I have to do the same thing to represent data in a ListCtrl that needs to be accessible by a key rather than by index at times (so that it does not have to be searched if I get an arbitrary value to locate). If you have a list of dictionaries, the best I found was to create another dictionary with references to t... | [
3,
1,
0,
0
] | [] | [] | [
"data_structures",
"pyqt4",
"python"
] | stackoverflow_0006430973_data_structures_pyqt4_python.txt |
Q:
str.replace adding back slash
I have this interactive session:
>>> str = '192.168.1.1'
>>> str = str.replace('.','\.')
>>> str
'192\\.168\\.1\\.1'
I want the out put to be: 192\.168\.1\.1 instead of 192\\.168\\.1\\.1
How can I achieve this? Why is it behaving this way?
A:
Use print str instead of str:
>> str = ... | str.replace adding back slash | I have this interactive session:
>>> str = '192.168.1.1'
>>> str = str.replace('.','\.')
>>> str
'192\\.168\\.1\\.1'
I want the out put to be: 192\.168\.1\.1 instead of 192\\.168\\.1\\.1
How can I achieve this? Why is it behaving this way?
| [
"Use print str instead of str:\n>> str = '192.168.1.1'\n>>> str = str.replace('.','\\.')\n>>> str\n'192\\\\.168\\\\.1\\\\.1'\n>>> print str\n192\\.168\\.1\\.1\n\nYour string is the one you expect it to be, but when you just dump the object, python is showing it to you in a form you could use to assign to another st... | [
8,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006432294_python.txt |
Q:
Size limitations of Tkinter grid manager
I'm writing a Python application to parse a list of binary files, aggregate statistics on the data in them, and output results. I can easily output these results as a .tsv file, but this program is being written for the convenience of my coworkers, so I'm trying to have it ... | Size limitations of Tkinter grid manager | I'm writing a Python application to parse a list of binary files, aggregate statistics on the data in them, and output results. I can easily output these results as a .tsv file, but this program is being written for the convenience of my coworkers, so I'm trying to have it display the results in a new window to sometim... | [
"I wrote a test program to display the data two ways, once using a frame and grid and once drawing text directly on the canvas.\nUsing the frame+grid technique, the performance of 100 rows times 10 columns was quite acceptable. When I bumped that up to 200 rows the performance was more than 2x worse, and by the tim... | [
2,
1
] | [] | [] | [
"grid",
"performance",
"python",
"tkinter"
] | stackoverflow_0006431487_grid_performance_python_tkinter.txt |
Q:
How to write an extended gtk.CellRendererText() to have an image beside the text
I am doing a simple file browser in python and GtkBuilder. I am using a Treeview that has one TreeViewColumn with cells that are rendered like:
self.cell = gtk.CellRendererText()
As I mentioned I am creating a file browser. So I want... | How to write an extended gtk.CellRendererText() to have an image beside the text | I am doing a simple file browser in python and GtkBuilder. I am using a Treeview that has one TreeViewColumn with cells that are rendered like:
self.cell = gtk.CellRendererText()
As I mentioned I am creating a file browser. So I want to have a small icon before the text in each cell, that icon will be the folder,file ... | [
"You don't need to extend CellRendererText, you can insert more than one CellRenderer per column using gtk.TreeViewColumn.pack_start().\nYou will want to have a CellRendererPixbuf to the left of your CellRendererText.\n"
] | [
6
] | [] | [] | [
"gtk",
"gtkbuilder",
"pygtk",
"python"
] | stackoverflow_0006431525_gtk_gtkbuilder_pygtk_python.txt |
Q:
How expensive it is to load the environment to run a Python script?
I have a background python script that gets ran several thousand times a day. I'm simply running it with python foo.py. The script itself does some imports (a parsing library and sqlalchemy) and then makes a database connection, makes the parsing ... | How expensive it is to load the environment to run a Python script? | I have a background python script that gets ran several thousand times a day. I'm simply running it with python foo.py. The script itself does some imports (a parsing library and sqlalchemy) and then makes a database connection, makes the parsing and saves the data to db.
I'm wondering if it adds a lot of overhead to l... | [
"of course it adds a lot of overhead, and it would be (however negligibly) more eco-friendly to use a built-in poll or select(); but then you'd have to have a watchdog to see if it crashed, or use respawn from inittab. as long as the server load is fine, it might not be worth the effort.\n\nforgot to mention, memor... | [
4
] | [] | [] | [
"environment",
"overhead",
"python"
] | stackoverflow_0006432377_environment_overhead_python.txt |
Q:
How to add an app to django admin site which do not required model?
How to add an app to django admin site which do not required model?
I mean I need to make inteface for my app. But i dont want to create any tables in databas. Actually it going to work with solr items.
Or maybe someone knows any dummy model whic... | How to add an app to django admin site which do not required model? | How to add an app to django admin site which do not required model?
I mean I need to make inteface for my app. But i dont want to create any tables in databas. Actually it going to work with solr items.
Or maybe someone knows any dummy model which acts like a real model.. but is not related with database table?
So th... | [
"Maybe you can define a model for your app and set the managed Meta option to False so that I won't create a db for you? \nFrom documentation: https://docs.djangoproject.com/en/1.3/ref/models/options/#django.db.models.Options.managed\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006428400_django_python.txt |
Q:
UnitTest in Python
Possible Duplicate:
ValueError: no such test method in <class 'myapp.tests.SessionTestCase'>: runTest
import unittest
class BzTestSe(unittest.TestCase):
DEFAULTUSERNAME = 'username-a2'
DEFAULTPASSWORD = 'pass'
DEFAULTHOST = 'localhots'
def __init__(self,username=DEFAULTUSERNA... | UnitTest in Python |
Possible Duplicate:
ValueError: no such test method in <class 'myapp.tests.SessionTestCase'>: runTest
import unittest
class BzTestSe(unittest.TestCase):
DEFAULTUSERNAME = 'username-a2'
DEFAULTPASSWORD = 'pass'
DEFAULTHOST = 'localhots'
def __init__(self,username=DEFAULTUSERNAME, password=DEFAULTPAS... | [
"Lets try and go back to something simple. In using unittest you have a couple of ways to execute your test cases but the simplest way is to have a main function in the file that contains your unittests.\nFor example:\nimport unittest\n\nclass TestSomething(unittest.TestCase):\n\n def setUp(self):\n self.... | [
2
] | [] | [] | [
"python",
"subclass",
"testing"
] | stackoverflow_0006432374_python_subclass_testing.txt |
Q:
Creating multiple dictionary variables with loop commands?
This is my first time working with python. I'm trying to create a dictionary for each county (23 in total) with year as the key for population and income values. Strong arming the code seems to work, but I'm sure there is an easier way to do it using loop... | Creating multiple dictionary variables with loop commands? | This is my first time working with python. I'm trying to create a dictionary for each county (23 in total) with year as the key for population and income values. Strong arming the code seems to work, but I'm sure there is an easier way to do it using loops or classes...any suggestions?? Thanks!!!!!
import xlrd
wb= x... | [
"popdict = {}\nincdict = {}\nfor ix, city in enumerate(WyomingCnty):\n popdict[city] = dict(zip(Years, popdata.col_values(colx=ix + 1,start_rowx=1,end_rowx=None)\n incdict[city] = dict(zip(Years, incomedata.col_values(colx=ix + 1,start_rowx=1,end_rowx=None)\n\n",
"I would just use another dictionary. As in:\nim... | [
3,
1
] | [] | [] | [
"dictionary",
"python",
"xlrd"
] | stackoverflow_0006432778_dictionary_python_xlrd.txt |
Q:
Jython- using variables in function calls syntax
I am working with Jython to automate deployments in WebSphere. I am wrapping my py script with a shell script to pass needed variables for WAS's built-in functions.
The stock call with hardcoded values looks like this:
appManager=AdminControl.queryNames('cell=wsapp2... | Jython- using variables in function calls syntax | I am working with Jython to automate deployments in WebSphere. I am wrapping my py script with a shell script to pass needed variables for WAS's built-in functions.
The stock call with hardcoded values looks like this:
appManager=AdminControl.queryNames('cell=wsapp2Node01Cell,node=TARGETNODE,type=
... | [
"It looks like the answer is as simple as the following:\nAdminControl.invoke(appManager, 'stopApplication', MyAppVariable)\n\nDoes that work? If not, what does it do?\n"
] | [
1
] | [] | [] | [
"jython",
"python",
"websphere"
] | stackoverflow_0006427298_jython_python_websphere.txt |
Q:
Python nested generators
I was trying to implement the reverse function of itertools.izip on Python 2.7.1. The thing is that I find a problem, and I don't have an explantion.
Solution 1, iunzip_v1 works perfectly. But solution 2. iunzip_v2, doesn't works as expected. Til now, I haven't found any relevant informat... | Python nested generators | I was trying to implement the reverse function of itertools.izip on Python 2.7.1. The thing is that I find a problem, and I don't have an explantion.
Solution 1, iunzip_v1 works perfectly. But solution 2. iunzip_v2, doesn't works as expected. Til now, I haven't found any relevant information about this problem, and re... | [
"You're reinventing the wheel in a crazy way. izip is its own inverse:\n>>> list(izip(*izip(range(10), range(10))))\n[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)]\n\nBut that doesn't quite answer your question, does it?\nThe problem with your nested generators is a scoping problem that happens be... | [
8,
5
] | [] | [] | [
"generator",
"python",
"recursion"
] | stackoverflow_0006432782_generator_python_recursion.txt |
Q:
matplotlib: is a changing background color possible?
matplotlib python:
How do you change the background color of a line plot according to a given column?
Say I have the following data file
1. 0
4. 0
2. 0
1. 1
2. 1
3. 1
3. 2
1. 2
2. 2
The first column represents the y-values, and the 2nd column should control the... | matplotlib: is a changing background color possible? | matplotlib python:
How do you change the background color of a line plot according to a given column?
Say I have the following data file
1. 0
4. 0
2. 0
1. 1
2. 1
3. 1
3. 2
1. 2
2. 2
The first column represents the y-values, and the 2nd column should control the background color. Say, it plots the (black) line on a whi... | [
"This one works:\n plt.axvspan(x, x2, facecolor='g', alpha=0.5)\n\nwhere facecolor is the foreground color \n"
] | [
3
] | [] | [] | [
"background",
"matplotlib",
"plot",
"python"
] | stackoverflow_0006427341_background_matplotlib_plot_python.txt |
Q:
Is there a faster way to convert an arbitrary large integer to a big endian sequence of bytes?
I have this Python code to do this:
from struct import pack as _pack
def packl(lnum, pad = 1):
if lnum < 0:
raise RangeError("Cannot use packl to convert a negative integer "
"to a s... | Is there a faster way to convert an arbitrary large integer to a big endian sequence of bytes? | I have this Python code to do this:
from struct import pack as _pack
def packl(lnum, pad = 1):
if lnum < 0:
raise RangeError("Cannot use packl to convert a negative integer "
"to a string.")
count = 0
l = []
while lnum > 0:
l.append(lnum & 0xffffffffffffffffL)
... | [
"Here is a solution calling the Python/C API via ctypes. Currently, it uses NumPy, but if NumPy is not an option, it could be done purely with ctypes.\nimport numpy\nimport ctypes\nPyLong_AsByteArray = ctypes.pythonapi._PyLong_AsByteArray\nPyLong_AsByteArray.argtypes = [ctypes.py_object,\n ... | [
10,
5,
3,
3
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0004358285_optimization_python.txt |
Q:
Preferred Python XML processor
What is the preferred XML processor to use with Python?
Some choices are
minidom
PyXML
ElementTree
...
EDIT: I will need to be able to read in documents and manipulate them. I also require pretty print functionality.
A:
lxml is where it's at.
Here's some example code:
import te... | Preferred Python XML processor | What is the preferred XML processor to use with Python?
Some choices are
minidom
PyXML
ElementTree
...
EDIT: I will need to be able to read in documents and manipulate them. I also require pretty print functionality.
| [
"lxml is where it's at.\nHere's some example code:\nimport textwrap\nfrom os.path import join\n\nfrom lxml import etree\n\n# string to Element\ntree = etree.XML(textwrap.dedent('''\n <foo_tag>\n foo text\n <bar_tag some_attr='ok'>bar text</bar_tag>\n </foo_tag>\n '''))\nprint 'root text: ' , tree.text\npri... | [
9,
0
] | [
"I'm a big fan of BeautifulSoup ... I find its the easiest parser to use!\n",
"If you are simply parsing a document and not manipulating it. I would suggest using the SAX Parser for Python\nhttp://docs.python.org/library/xml.sax.reader.html\n"
] | [
-1,
-2
] | [
"python",
"xml"
] | stackoverflow_0006432826_python_xml.txt |
Q:
Variable defined with with-statement available outside of with-block?
Consider the following example:
with open('a.txt') as f:
pass
# Is f supposed to be defined here?
I have read the language docs (2.7) for with-statement as well as PEP-343, but as far as I can tell they don't say anything on this matter.
In... | Variable defined with with-statement available outside of with-block? | Consider the following example:
with open('a.txt') as f:
pass
# Is f supposed to be defined here?
I have read the language docs (2.7) for with-statement as well as PEP-343, but as far as I can tell they don't say anything on this matter.
In CPython 2.6.5 f does seem to be defined outside of the with-block, but I'd... | [
"Yes, the context manager will be available outside the with statement and that is not implementation or version dependent. with statements do not create a new execution scope.\n",
"the with syntax:\nwith foo as bar:\n baz()\n\nis approximately sugar for:\ntry:\n bar = foo.__enter__()\n baz()\nfinally:\n... | [
175,
32,
18,
13
] | [] | [] | [
"python"
] | stackoverflow_0006432355_python.txt |
Q:
Elegant way to skip processing script tag for shpaml
I have started using excellent shpaml. But soon hit problem that my js code inside script tags is also processed. Is there a way to configure/extend python shpaml, so that it will skip script or any tag for that matter which is configured for exclusion.
I know I... | Elegant way to skip processing script tag for shpaml | I have started using excellent shpaml. But soon hit problem that my js code inside script tags is also processed. Is there a way to configure/extend python shpaml, so that it will skip script or any tag for that matter which is configured for exclusion.
I know I can prefix pipe but that is not acceptable within my team... | [
"Use the verbatim tag like so\nscript type=\"text/javascript\" VERBATIM\n $(function() {\n alert(\"hello world!);\n });\n\n",
"You can look for alternate template languages such as Is there a HAML implementation for use with Python and Django\n",
"Try: \nscript type=\"text/javascript\" src='/path/t... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"shpaml"
] | stackoverflow_0005595492_python_shpaml.txt |
Q:
Passing data from intent to other using python server
I have an application with an Android client and a Python server. The android package has three Activities, which access GPS and google maps. I send the GPS coordinates from the second activity to the (python) server using a socket. I want to receive the [chang... | Passing data from intent to other using python server | I have an application with an Android client and a Python server. The android package has three Activities, which access GPS and google maps. I send the GPS coordinates from the second activity to the (python) server using a socket. I want to receive the [changed] value back from the server and pass it to the third Act... | [
"The easiest way to do this would be to cut out your custom socket solution and replace it with a tiny web server. Obviously the task isn't going to have serious latency if the user is going to be seeing the result on a map in the near future, so HTTP is fine. Just make an http post request to the server, with long... | [
0
] | [] | [] | [
"android",
"python"
] | stackoverflow_0006430703_android_python.txt |
Q:
Efficient Shift Scheduling in Python
I'm currently working on doing some shift scheduling simulations for a model taxicab company. The company operates 350 cabs, and all are in use on any given day. Drivers each work 5 shifts of 12 hours each, and the there are four overlapping shifts a day. There are shifts from ... | Efficient Shift Scheduling in Python | I'm currently working on doing some shift scheduling simulations for a model taxicab company. The company operates 350 cabs, and all are in use on any given day. Drivers each work 5 shifts of 12 hours each, and the there are four overlapping shifts a day. There are shifts from 3:00-15:00, 15:00-3:00, 16:00-4:00, and 4:... | [
"There's nothing that would obviously slow these functions down, and indeed they aren't slow. They just get called a lot. You say you're using a brute force algorithm - can you write an algorithm that doesn't try every possible combination? Or is there a more efficient way of doing it, like storing the data by driv... | [
4,
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0006431261_python.txt |
Q:
In CherryPy, is it possible to alias a folder name?
I'm using CherryPy. I have a folder named "zh-cn" -- which means that I'm using Mainland China's version of written Chinese - Simplified Chinese.
Here is my code. Notice how I used an underscore? This works.
class ChineseFlashcards:
zh_cn = ChineseFlashcards... | In CherryPy, is it possible to alias a folder name? | I'm using CherryPy. I have a folder named "zh-cn" -- which means that I'm using Mainland China's version of written Chinese - Simplified Chinese.
Here is my code. Notice how I used an underscore? This works.
class ChineseFlashcards:
zh_cn = ChineseFlashcards_zh_cn()
en = ChineseFlashcards_en()
My problem is t... | [
"Solution 1: If you're using CherryPy 3.2 or better, just call it 'zh_cn'. See http://docs.cherrypy.org/dev/concepts/dispatching.html#special-characters\nSolution 2: you can use setattr to bind attribute names which are not legal Python identifiers:\nclass ChineseFlashcards:\n en = ChineseFlashcards_en()\n\nseta... | [
3,
0
] | [] | [] | [
"cherrypy",
"cjk",
"localization",
"python"
] | stackoverflow_0006432219_cherrypy_cjk_localization_python.txt |
Q:
how to create a dynamically-created radio buttons form in django
hello .
im new to django and
i want to create a form that looks like the image above in html.
the form should save the data when the user chose a radio button.
how to implement such a form in django ( please note that user cannot chose more than ... | how to create a dynamically-created radio buttons form in django |
hello .
im new to django and
i want to create a form that looks like the image above in html.
the form should save the data when the user chose a radio button.
how to implement such a form in django ( please note that user cannot chose more than one answer)
| [
"You want to use ChoiceField and RadioSelect:\nfrom django import forms\n\nclass GenderForm(forms.Form):\n CHOICES = (\n ('M', 'Male'),\n ('F', 'Female'),\n )\n choice = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())\n\nRemember, Django documentation is your friend!\nDynamical... | [
7,
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005907193_django_python.txt |
Q:
Record audio in Google App Engine using rtmplite?
I am in the process of building a Google App Engine application which requires audio to be recorded and saved in our database. I have found no alternative to using some form of RTMP server for recording audio through flash, so [rtmplite] (http://code.google.com/p/r... | Record audio in Google App Engine using rtmplite? | I am in the process of building a Google App Engine application which requires audio to be recorded and saved in our database. I have found no alternative to using some form of RTMP server for recording audio through flash, so [rtmplite] (http://code.google.com/p/rtmplite/) came into our horizon.
Since I have no experi... | [
"Google App Engine is tricky for RTMP because it does not support sockets. You would have to use something like RTMPT which is tunneled over HTTP, however, this tunneling incurs latency so if you are looking to do anything realtime this could become an issue.\nCurrently rtmplite does not support RTMPT so this would... | [
5,
0
] | [] | [] | [
"google_app_engine",
"python",
"rtmp"
] | stackoverflow_0005447631_google_app_engine_python_rtmp.txt |
Q:
How can I reload objects in my namespace in ipython
After import functions into ipython, how do I reload them when I have modified them outside of ipython ?
A:
Python 2:
reload(module)
Python 3:
from importlib import reload
reload(module)
Where module is the file with your functions.
A:
you can also use aut... | How can I reload objects in my namespace in ipython | After import functions into ipython, how do I reload them when I have modified them outside of ipython ?
| [
"Python 2:\nreload(module)\n\nPython 3: \nfrom importlib import reload\nreload(module)\n\nWhere module is the file with your functions.\n",
"you can also use autoreload, so that the modules you are working on are automatically reloaded at each statement, pretty handy for debugging, see:\nAutoreload of modules in ... | [
31,
6,
1
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0006420361_ipython_python.txt |
Q:
Accessing file meta-data within Python/wxPython
I would like to write a Python/wxPython app that implements wx.FileDropTarget. This part is easy. I would also like to show the file icon as it is dragged over the app window and then display a proxy with file icon (and other meta-data, perhaps, like size) within the... | Accessing file meta-data within Python/wxPython | I would like to write a Python/wxPython app that implements wx.FileDropTarget. This part is easy. I would also like to show the file icon as it is dragged over the app window and then display a proxy with file icon (and other meta-data, perhaps, like size) within the app window.
I would like to implement this on Window... | [
"I think there's not only one portable way to accomplish this ... on windows platforms, default icons for file types associations are stored on the system registry (except for executables where the icon is in the exe resources) and on linux platforms it depends on the desktop environment, each one has its own stand... | [
1,
1
] | [] | [] | [
"filesystems",
"icons",
"python",
"windows",
"wxpython"
] | stackoverflow_0006433574_filesystems_icons_python_windows_wxpython.txt |
Q:
SQLAlchemy: 'Model' object is not callable
I'm using Flask framework with sqlalchemy and I can't query some related table of a result.
Users > have many > orders
So I have the order and I want to query the user that order belongs to.
order = Order.query.get( id )
return order.user()
When I call this I get that th... | SQLAlchemy: 'Model' object is not callable | I'm using Flask framework with sqlalchemy and I can't query some related table of a result.
Users > have many > orders
So I have the order and I want to query the user that order belongs to.
order = Order.query.get( id )
return order.user()
When I call this I get that the 'User' object is not callable. Here's how my r... | [
"order is the order object, and you've defined the \"user\" relationship as a property. Therefore, the property \"user\" will represent the user object. This may be unlike other ORMs you've used where order.user is actually some function that needs to get called to retrieve the user, or perhaps a query object that ... | [
3
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python",
"sqlalchemy"
] | stackoverflow_0006433809_flask_flask_sqlalchemy_python_sqlalchemy.txt |
Q:
XML and Django problems (unicode related?)
I made this app that is supposed to give an xml document with 5 items. My view sends a dictionary 'rsscontent' with these five items to the file rss.xml:
#views.py
return render_to_response("rss.xml", {"rsscontent":rsscontent})
Then the rss.xml file looks like thi... | XML and Django problems (unicode related?) | I made this app that is supposed to give an xml document with 5 items. My view sends a dictionary 'rsscontent' with these five items to the file rss.xml:
#views.py
return render_to_response("rss.xml", {"rsscontent":rsscontent})
Then the rss.xml file looks like this:
#rss.xml
<?xml version="1.0" encoding="UTF-8"... | [
"Don't use the |safe filter. Additionally, it looks like your object values are lists, so you'll need to get the first element of those, rather than just printing the items themselves. \nYou want to modify your input rsscontent variable to look like this:\n{'item1':'itemtext',\n 'item2':'item2text',\n etc.\n}\n\nr... | [
2
] | [] | [] | [
"django",
"python",
"unicode",
"xml"
] | stackoverflow_0006433845_django_python_unicode_xml.txt |
Q:
search and replace: convert square brackets to xml tags
I will try and keep this short and to the point.
Given the following
#!/usr/bin/python
from lxml import etree
root = etree.Element('root')
sect = etree.SubElement(root,'sect')
para = etree.SubElement(sect,'para')
para.text = 'this is a [b]long[/b] block of t... | search and replace: convert square brackets to xml tags | I will try and keep this short and to the point.
Given the following
#!/usr/bin/python
from lxml import etree
root = etree.Element('root')
sect = etree.SubElement(root,'sect')
para = etree.SubElement(sect,'para')
para.text = 'this is a [b]long[/b] block of text. Much longer than this example makes it out to be.'
how ... | [
"The postmarkup library seems to come closest to what you want to do.\nhttp://pypi.python.org/pypi/postmarkup/1.1.4\nUnfortunately it hasn't seen a lot of development recently, but I don't see any other libraries that look tons better.\nStarting from there and modifying the existing elements to fit your syntax is p... | [
2
] | [] | [] | [
"lxml",
"python",
"regex",
"text_processing",
"xml"
] | stackoverflow_0006433355_lxml_python_regex_text_processing_xml.txt |
Q:
Converting from JSON to SQL with Python: Suggested libraries/techniques to look into?
Yeah, I've seen a bit of SQL-to-JSON but not much talk about going the other way. I guess my question is threefold:
Would I be reinventing the wheel to make a tool which does this?
Are there good libraries that I should look into... | Converting from JSON to SQL with Python: Suggested libraries/techniques to look into? | Yeah, I've seen a bit of SQL-to-JSON but not much talk about going the other way. I guess my question is threefold:
Would I be reinventing the wheel to make a tool which does this?
Are there good libraries that I should look into for making this?
Are there any particular techniques or idioms involved in efficiently and... | [
"The fact that the JSON contains some SQL is pretty irrelevant. \nIt sounds like you just want to read the files containing JSON strings. You can use the json module from the standard python library ( http://docs.python.org/library/json.html ) to read a string into a python variable. \nimport json\nvar = json.lo... | [
1,
0
] | [] | [] | [
"json",
"python",
"sql"
] | stackoverflow_0006433904_json_python_sql.txt |
Q:
Cross database join in sqlalchemy
Is there a way in SQLAlchemy to do cross-database joins. To be specific, here is my use case:
Schema
db1.entity1
entity1_id: Primary Key
entity2_id: Foreign Key to db2.entity2.entity2_id
db2.entity2
entity2_id: Primary Key
Model
I'm using declarative style for models.
class E... | Cross database join in sqlalchemy | Is there a way in SQLAlchemy to do cross-database joins. To be specific, here is my use case:
Schema
db1.entity1
entity1_id: Primary Key
entity2_id: Foreign Key to db2.entity2.entity2_id
db2.entity2
entity2_id: Primary Key
Model
I'm using declarative style for models.
class Entity1(Base):
__tablename__ = 'entit... | [
"You probably need to pass the schema parameter to sqlalchemy.schema.Table. When using declarative base for ORM mapping, you can provide this extra parameter through the __table_args__ property on your classes. \nclass Entity2(Base):\n __tablename__ = 'entity2' ## I tried combination of <db>.<table> with no suc... | [
25
] | [] | [] | [
"flask_sqlalchemy",
"python",
"sqlalchemy"
] | stackoverflow_0006433592_flask_sqlalchemy_python_sqlalchemy.txt |
Q:
Is there an implementation of Hadley's ddply for python?
I find Hadley's plyr package for R extremely helpful, its a great DSL for transforming data. The problem that is solves is so common, that I face it other use cases, when not manipulating data in R, but in other programming languages.
Does anyone know if the... | Is there an implementation of Hadley's ddply for python? | I find Hadley's plyr package for R extremely helpful, its a great DSL for transforming data. The problem that is solves is so common, that I face it other use cases, when not manipulating data in R, but in other programming languages.
Does anyone know if there exists an a module that does a similar thing for python? So... | [
"This is the implementation I drafted up:\ndef ddply(rows, cols, op=lambda group_rows: group_rows): \n \"\"\"group rows by cols, then apply the function op to each group \n rows is list of values or dict with col names (like read from \n csv.reader or csv.DictReader)\"\"\"\n def group_key(row): ... | [
8
] | [] | [] | [
"plyr",
"python",
"r"
] | stackoverflow_0006434048_plyr_python_r.txt |
Q:
What is usage of the last comma in this code?
for x in range(1, 11):
print repr(x).rjust(2), repr(x*x).rjust(3),
# Note trailing comma on previous line
print repr(x*x*x).rjust(4)
result:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 1... | What is usage of the last comma in this code? | for x in range(1, 11):
print repr(x).rjust(2), repr(x*x).rjust(3),
# Note trailing comma on previous line
print repr(x*x*x).rjust(4)
result:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
If it is a line continuation symbol, why c... | [
"It stops print from printing a newline at the end of the text.\nAs Dave pointed out, the documentation in python 2.x says: …. \"A '\\n' character is written at the end, unless the print statement ends with a comma.\"\nUPDATE:\nThe documentation of python 3.x states that print() is a function that accepts the keywo... | [
20,
3
] | [] | [] | [
"python"
] | stackoverflow_0006434308_python.txt |
Q:
Using numpy and pil to convert 565(16bit-color) to 888(24bit-color)
I must preface this, with the fact that I have a working method using bitshift and putpixel, but it is incredibly slow, and I am looking to leverage numpy to speed up the process. I believe I am close, but not quite there. Having timed what I th... | Using numpy and pil to convert 565(16bit-color) to 888(24bit-color) | I must preface this, with the fact that I have a working method using bitshift and putpixel, but it is incredibly slow, and I am looking to leverage numpy to speed up the process. I believe I am close, but not quite there. Having timed what I think should work, I'm seeing a 0.3 second improvement in time, hence my mo... | [
"Warning: the following code hasn't been checked, but I think that this will do what you want (if I'm understanding everything correctly):\nimport numpy as np\narr = np.fromstring(buff,dtype=np.uint16).astype(np.uint32)\narr = ((arr & 0xF800) << 16) + ((arr & 0x07E0) << 13) + ((arr & 0x001F) << 11) + 0xFF\nreturn I... | [
3,
1
] | [] | [] | [
"numpy",
"python",
"python_imaging_library",
"rgb"
] | stackoverflow_0005414638_numpy_python_python_imaging_library_rgb.txt |
Q:
how to use PyV8 and httplib to interpret javascript
I would like to write my own web test engine that will request (get/post) my wsgi application and i would like my client to interpret the return page that contains some javascript code.
Basically it is how to use a PyV8 to make a headless browser.
Thx
A:
Unles... | how to use PyV8 and httplib to interpret javascript | I would like to write my own web test engine that will request (get/post) my wsgi application and i would like my client to interpret the return page that contains some javascript code.
Basically it is how to use a PyV8 to make a headless browser.
Thx
| [
"Unless you really want to do this project yourself, have you considered using PhantomJS (home page)? It's a headless WebKit with support for scripting in Javascript, and has both C++ and Python implementations (though the Python version seems slightly less well-supported than the C++ version, and there was some ch... | [
2
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0006432558_javascript_python.txt |
Q:
Any way to detect mistyped urls in python?
My python program involves going to a user-supplied url and then doing stuff on the page. Ideally, mistyped urls would be recognized and pop up an error. But if they have the right syntax and just don't point anywhere, then either an ISP error page or an ad site is loaded... | Any way to detect mistyped urls in python? | My python program involves going to a user-supplied url and then doing stuff on the page. Ideally, mistyped urls would be recognized and pop up an error. But if they have the right syntax and just don't point anywhere, then either an ISP error page or an ad site is loaded instead.
For example:
"http://washingtonn.edu" ... | [
"Unless I am misunderstanding your question, what you ask for is impossible, doesn't make sense, or is far far from trivial.\nIf you think about it, other than a 404 error, where you detect that a page does not exist, if a page does exist there is not way of knowing whether the page is \"good\" or \"bad\" as this i... | [
3,
1,
1,
0
] | [] | [] | [
"error_handling",
"python",
"web"
] | stackoverflow_0006434667_error_handling_python_web.txt |
Q:
Sever Side convert SVG to PNG or JPG image with Python on Google Application Engine
How to convert SVG to PNG or JPG image with Python on Google Application Engine?
Any idea?
Google Application Engine has PIL support. However, PIL doesn't support SVG.
A:
When working with Google App Engine you will need a pure P... | Sever Side convert SVG to PNG or JPG image with Python on Google Application Engine | How to convert SVG to PNG or JPG image with Python on Google Application Engine?
Any idea?
Google Application Engine has PIL support. However, PIL doesn't support SVG.
| [
"When working with Google App Engine you will need a pure Python library because you can't install anything that's compiled (eg. Cairo). While there are pure Python libraries for creating SVG files (eg. pySVG) I don't think there are any for rasterizing SVG images.\n",
"If you manage to find (or write) a pure Pyt... | [
2,
-1
] | [] | [] | [
"google_app_engine",
"python",
"svg"
] | stackoverflow_0006434530_google_app_engine_python_svg.txt |
Q:
Django--Form validation (Why can't I manually clean an Integer Form Field)
This should be pretty straightforward but I'm not figuring it out from the Django documentation. I have an IntegerField Model Field from which I've created a ModelForm Field. The field in question contains $ values (price) and it would be... | Django--Form validation (Why can't I manually clean an Integer Form Field) | This should be pretty straightforward but I'm not figuring it out from the Django documentation. I have an IntegerField Model Field from which I've created a ModelForm Field. The field in question contains $ values (price) and it would be preferable from a UX standpoint if the user did not receive a error message ('e... | [
"Create an IntegerField in the model, and a CharField in the form.\nYou can still use modelform to do this but you'll have to:\n\n'exclude' the model field from the form, \nwrite a clean_bill method in the form\nset the value of the model's field to the parsed integer value\n\ntry this and/or this\n",
"Yes, you a... | [
4,
1
] | [] | [] | [
"django",
"django_models",
"django_validation",
"python"
] | stackoverflow_0006434245_django_django_models_django_validation_python.txt |
Q:
Tunneling TCP ports through ssh without blocking
I'm trying setup a ssh tunnel via pexpect with following code:
#!/bin/env python2.4
import pexpect, sys
child = pexpect.spawn('ssh -CfNL 0.0.0.0:3306:127.0.0.1:3306 user@server.com')
child.logfile = sys.stdout
while True:
code = child.expect([
'Are you ... | Tunneling TCP ports through ssh without blocking | I'm trying setup a ssh tunnel via pexpect with following code:
#!/bin/env python2.4
import pexpect, sys
child = pexpect.spawn('ssh -CfNL 0.0.0.0:3306:127.0.0.1:3306 user@server.com')
child.logfile = sys.stdout
while True:
code = child.expect([
'Are you sure you want to continue connecting \(yes/no\)\?',
... | [
"I think the simplest solution is to use ssh host-key authentication, combined with backgrounding ssh with &... this is a very basic implementation, but you could enhance it to kill the process after you're done... also, note that I added -n to your ssh args, since we're backgrounding the process.\nimport subproce... | [
3
] | [] | [] | [
"pexpect",
"python",
"ssh_tunnel"
] | stackoverflow_0006434508_pexpect_python_ssh_tunnel.txt |
Q:
python, list everything between two tags
I'm looking for the shortest neatest way to code the folloing.
say I have a string containing: 'the f<ox jumpe>d over the l<azy> dog <and the >fence'
Using < as the opening tag and > as the closing tag, I would like to save everything inbetween into a list.
if saved into li... | python, list everything between two tags | I'm looking for the shortest neatest way to code the folloing.
say I have a string containing: 'the f<ox jumpe>d over the l<azy> dog <and the >fence'
Using < as the opening tag and > as the closing tag, I would like to save everything inbetween into a list.
if saved into list1, list1 would equal ['ox jumpe', 'azy', 'an... | [
"Regular expressions should do the trick here:\nimport re\n\ntext = 'the f<ox jumpe>d over the l<azy> dog <and the >fence'\nlist = re.findall('.*?\\<(.*?)\\>.*?', text)\n\nprint list\n\nEdit:\nYou can read more about regex here\nMainly, what the regex from above does is:\n.*? - non greedy match of all the character... | [
5,
1
] | [] | [] | [
"python",
"string",
"tags"
] | stackoverflow_0006434823_python_string_tags.txt |
Q:
What is the location of the loaded theme icons?
I am creating a simple file browser in python, gtk. I need to find a way to load the icons of the current theme (ie. folder icons) and use them in my code. Is there a location that always holds the current icons?
A:
I found the answer to be in GTK Stock icons.
http... | What is the location of the loaded theme icons? | I am creating a simple file browser in python, gtk. I need to find a way to load the icons of the current theme (ie. folder icons) and use them in my code. Is there a location that always holds the current icons?
| [
"I found the answer to be in GTK Stock icons.\nhttp://www.pygtk.org/docs/pygtk/gtk-stock-items.html\n"
] | [
0
] | [] | [] | [
"gnome",
"gtk",
"linux",
"python",
"ubuntu"
] | stackoverflow_0006434697_gnome_gtk_linux_python_ubuntu.txt |
Q:
intersect two lists of words in python
i want to find the intersection of two lists in python. i have something that looks like this:
>>> q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
>>> w = ['pineapple', 'peach', 'watermelon', 'kiwi']
and i want to find something that looks like this:
t = ['peach',... | intersect two lists of words in python | i want to find the intersection of two lists in python. i have something that looks like this:
>>> q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']
>>> w = ['pineapple', 'peach', 'watermelon', 'kiwi']
and i want to find something that looks like this:
t = ['peach', 'watermelon']
i know its a simple, questio... | [
"The intersection() method is available for sets, which can be easily made from lists. \nETA: if you want a list out of it... \nq = ['apple', 'peach', 'pear', 'watermelon', 'strawberry']\nw = ['pineapple', 'peach', 'watermelon', 'kiwi']\nt = list(set(q) & set(w))\n\nNow t is: \n['watermelon', 'peach']\n\n",
"The ... | [
11,
4,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006431033_list_python.txt |
Q:
Not a valid choice: Can't select ReferenceProperty value at SelectField wtform
i try to use ReferenceProperty at form for create/edit Entry but nothing happen.
i have:
class Type(db.Model):
name = db.StringProperty()
class Entry(db.Model):
type = db.ReferenceProperty(Type, required=False... | Not a valid choice: Can't select ReferenceProperty value at SelectField wtform | i try to use ReferenceProperty at form for create/edit Entry but nothing happen.
i have:
class Type(db.Model):
name = db.StringProperty()
class Entry(db.Model):
type = db.ReferenceProperty(Type, required=False)
class EntryForm(Form):
_type_list = []
for type in Type.all():
... | [
"I solve my problem with this changes at Form class: \nclass EntryForm(Form):\n _type_list = []\n for type in Type.all():\n _type_list.append((type.key().id(),type.name))\n type = fields.SelectField(u'Type of entry', choices = _type_list, coerce=int)\n\nand edit handler:\ndef post(self, *... | [
1
] | [] | [] | [
"google_app_engine",
"python",
"tipfy",
"wtforms"
] | stackoverflow_0006426196_google_app_engine_python_tipfy_wtforms.txt |
Q:
What is the Python convention **kwargs vs **kwds vs **kw?
Is there a python naming convention for key word arguments?
A:
Nope, but normally it is named as **kwargs, but you can name it anything you want. Only thing is it should come at the last following any position args and named args.
A:
The most popular c... | What is the Python convention **kwargs vs **kwds vs **kw? | Is there a python naming convention for key word arguments?
| [
"Nope, but normally it is named as **kwargs, but you can name it anything you want. Only thing is it should come at the last following any position args and named args.\n",
"The most popular convention is **kwargs, as seen in documentation and PEPs.\n",
"The key is consistency. In your personal code and in the ... | [
17,
11,
10
] | [] | [] | [
"keyword_argument",
"python"
] | stackoverflow_0006435319_keyword_argument_python.txt |
Q:
Optional parameters in functions and their mutable default values
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm kind of confused about how optional parameters work in Python functions/methods.
I have the following code block:
>>> def F(a, b=[]):
... b.append(a)
... ... | Optional parameters in functions and their mutable default values |
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm kind of confused about how optional parameters work in Python functions/methods.
I have the following code block:
>>> def F(a, b=[]):
... b.append(a)
... return b
...
>>> F(0)
[0]
>>> F(1)
[0, 1]
>>>
Why F(1) returns [0, 1]... | [
"Good doc from PyCon a couple years back - Default parameter values explained. But basically, since lists are mutable objects, and keyword arguments are evaluated at function definition time, every time you call the function, you get the same default value.\nThe right way to do this would be:\ndef F(a, b=None):\n ... | [
51,
10
] | [] | [] | [
"optional_parameters",
"parameter_passing",
"parameters",
"python"
] | stackoverflow_0006435793_optional_parameters_parameter_passing_parameters_python.txt |
Q:
cannot debug python GAE Django
I have a simple test app that seem to run fine. I'm trying to debug by placing the following in the code:
import pdb; pdb.set_trace()
When I run the app I get the following fatal error that I don't understand:
ERROR:root:Exception in request:
Traceback (most recent call last):
F... | cannot debug python GAE Django | I have a simple test app that seem to run fine. I'm trying to debug by placing the following in the code:
import pdb; pdb.set_trace()
When I run the app I get the following fatal error that I don't understand:
ERROR:root:Exception in request:
Traceback (most recent call last):
File "C:\Documents and Settings\Admin... | [
"Yes, the GAE runtime doesn't support pdb. Hard Luck.\nIf you want a similar runtime, you should check out Apphosted\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006433646_django_python.txt |
Q:
Trouble running python script
I'm trying to run a proof-of-concept script that demonstrates a man-in-the-middle TLS negotiation exploit. The trouble is, the script is written in Python and I have zero experience with Python.
The script is here: http://www.redteam-pentesting.de/files/tls-renegotiation-poc.py
The f... | Trouble running python script | I'm trying to run a proof-of-concept script that demonstrates a man-in-the-middle TLS negotiation exploit. The trouble is, the script is written in Python and I have zero experience with Python.
The script is here: http://www.redteam-pentesting.de/files/tls-renegotiation-poc.py
The first error I received was about imp... | [
"Try printing other.minVersion in filter: It looks like the input is not what you expect (i.e. you are expecting one of three tuples `[(3, 0), (3, 1), (3, 2)] - but that isn't what you're recieving.\nI often find that when throwing an error about a value outside a range like you are doing, that it is a good idea to... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006436093_python.txt |
Q:
handling caching of images in render_to_response
The brief version:
I wish to strip image urls out of the oiutput of a render_to_response call and replace them with a locally cached copy (creating it if it doesn't exist). I have an idea of an implementation, but it seems like every man and his wife has done this b... | handling caching of images in render_to_response | The brief version:
I wish to strip image urls out of the oiutput of a render_to_response call and replace them with a locally cached copy (creating it if it doesn't exist). I have an idea of an implementation, but it seems like every man and his wife has done this before, so I don't want to waste my time when I could b... | [
"How about creating a custom template tag/filter that checks if the url is cached and decides which url to use?\n",
"Since you are serving crawled html, you should probably filter it using a parser like lxml. While doing this, you can try to find the img tags, fetch the images and change the urls. I suggest doi... | [
1,
1,
1
] | [] | [] | [
"django",
"image",
"python",
"qt"
] | stackoverflow_0006435789_django_image_python_qt.txt |
Q:
Outer or inner link url
I want to know if a href="url" attribute is an outer or inner URL. How can I do it in django. Please help.
May be like this
if URL.find("www.sameurl.com") == -1 and URL.find("sameurl.com")==-1:
do
else:
do
A:
MY_DOMAIN = "sameurl.com"
import urlparse
parsed = urlparse.urlparse(url)... | Outer or inner link url | I want to know if a href="url" attribute is an outer or inner URL. How can I do it in django. Please help.
May be like this
if URL.find("www.sameurl.com") == -1 and URL.find("sameurl.com")==-1:
do
else:
do
| [
"MY_DOMAIN = \"sameurl.com\"\n\nimport urlparse\nparsed = urlparse.urlparse(url)\nif parsed.netloc=='' or parsed.netloc.endswith(MY_DOMAIN):\n # internal\nelse:\n # external\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006436075_django_python.txt |
Q:
Get DOM from webpage in python
hello guys i'm wondering how to get DOM from web page !
so check out this
Example.com>Get Dom>Get Document from Dom > Get Cookie Values from Document
i tried this code but not working
response.urllib2.urlopen('http://Example.com')
print response.info().getheader("cookie")
also i tr... | Get DOM from webpage in python | hello guys i'm wondering how to get DOM from web page !
so check out this
Example.com>Get Dom>Get Document from Dom > Get Cookie Values from Document
i tried this code but not working
response.urllib2.urlopen('http://Example.com')
print response.info().getheader("cookie")
also i tried print response.read()
but it's o... | [
"There is something here about HTTP Cookies with Python. You might actually be better off using / learning about python's httplib / http.client documented here, that would allow you to simulate / build an http client. Or even use the more generic urllib documented here, that handle more protocols / arbitrary resour... | [
0
] | [] | [] | [
"cookies",
"dom",
"python",
"setcookie"
] | stackoverflow_0006436375_cookies_dom_python_setcookie.txt |
Q:
python system call
having a difficult time understanding how to get python to call a system function...
the_file = ('logs/consolidated.log.gz')
webstuff = subprocess.Popen(['/usr/bin/zgrep', '/meatsauce/', the_file ],stdout=subprocess.PIPE) % dpt_search
for line in webstuff.stdout:
print line
... | python system call | having a difficult time understanding how to get python to call a system function...
the_file = ('logs/consolidated.log.gz')
webstuff = subprocess.Popen(['/usr/bin/zgrep', '/meatsauce/', the_file ],stdout=subprocess.PIPE) % dpt_search
for line in webstuff.stdout:
print line
Trying to get python to... | [
"I recommend the PyMotW Subprocess page from Doug Hellmann who (quoted) \"Reads the docs so you don't have to\"\nApart from that:\nf = file('sourcefile')\nfor line in f:\n if 'pattern' in line:\n # mind the , at the end,\n # since there's no stripping involved\n # and print adds ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006436740_python.txt |
Q:
In Python epoll can I avoid the errno.EWOULDBLOCK, errno.EAGAIN?
I wrote a epoll wrapper in python, It works fine but recently I found the performance is not not ideal for large package sending. I look down into the code and found there's actually a LOT of error
Traceback (most recent call last):
File "/Users/da... | In Python epoll can I avoid the errno.EWOULDBLOCK, errno.EAGAIN? | I wrote a epoll wrapper in python, It works fine but recently I found the performance is not not ideal for large package sending. I look down into the code and found there's actually a LOT of error
Traceback (most recent call last):
File "/Users/dawn/Documents/workspace/work/dev/server/sandbox/single_point/tcp_epoll.... | [
"Use select to see if a socket is ready for reading or writing.\n"
] | [
1
] | [] | [] | [
"epoll",
"networking",
"python"
] | stackoverflow_0006436754_epoll_networking_python.txt |
Q:
How can I modify this regex to match all three cases?
I want to test if a method appears in a header file. These are the three cases I have:
void aMethod(params ...)
//void aMethod(params
// void aMethod(params
^ can have any number of spaces here
Here's what I have so far:
re.search("(?<!\/\/)\s*void aMethod",... | How can I modify this regex to match all three cases? | I want to test if a method appears in a header file. These are the three cases I have:
void aMethod(params ...)
//void aMethod(params
// void aMethod(params
^ can have any number of spaces here
Here's what I have so far:
re.search("(?<!\/\/)\s*void aMethod",buffer)
Buf this will only match the first case, and the s... | [
"EDIT: Ok, after your edit, Geo, it is this:\n^(?<!\\/\\/)\\s*void aMethod\n\n",
"If you simply want to find all appearances for 'void aMethod(params' then you can use the following:\na = \"\"\"void aMethod(params ...)\n//void aMethod(params\n// void aMethod(params\n ^ can have any number of spaces here\"\"\"\nf... | [
7,
2,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006436837_python_regex.txt |
Q:
Why python module not found on apache
I have a problem with python and Django.
I have the error "Error was: No module named httplib2", so i installed httplib2. When i go on my console and type "import httplib2" it works!
But when i try to do that on my web page, it fails.
Any idea?
Thank you!
A:
HTTPd using a di... | Why python module not found on apache | I have a problem with python and Django.
I have the error "Error was: No module named httplib2", so i installed httplib2. When i go on my console and type "import httplib2" it works!
But when i try to do that on my web page, it fails.
Any idea?
Thank you!
| [
"HTTPd using a different version/install of Python than your REPL.\n"
] | [
2
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0006436979_apache_django_python.txt |
Q:
How can I find a method name not within a comment?
I asked this question earlier but I didn't express myself correctly. If I have these three cases:
void aMethod(params ...)
//void aMethod(params
// void aMethod(params
^ can have any number of spaces here
How could I tweak my regex to match only if the string i... | How can I find a method name not within a comment? | I asked this question earlier but I didn't express myself correctly. If I have these three cases:
void aMethod(params ...)
//void aMethod(params
// void aMethod(params
^ can have any number of spaces here
How could I tweak my regex to match only if the string is not found in a comment? This is my regex:
re.search("... | [
"This should do the stuff for your examples : \nre.search(\"^(?!\\/\\/)\\s*void aMethod\",line)\n\n",
"Is there any particular need to use regex? If not you can also try to use the following:\na = \"\"\"void aMethod(params ...)\n//void aMethod(params\n// void aMethod(params\n ^ can have any number of spaces here... | [
3,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006437063_python_regex.txt |
Q:
I use Jinja2 "recursive" tag in my code,but how can I get the depth of current loop?
I use the tag "recursive" as the documentation:
<ul class="sitemap">
{%- for item in sitemap recursive %}
<li><a href="{{ item.href|e }}">{{ item.title }}</a>
{%- if item.children -%}
<ul class="submenu">{{ loop(it... | I use Jinja2 "recursive" tag in my code,but how can I get the depth of current loop? | I use the tag "recursive" as the documentation:
<ul class="sitemap">
{%- for item in sitemap recursive %}
<li><a href="{{ item.href|e }}">{{ item.title }}</a>
{%- if item.children -%}
<ul class="submenu">{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
</ul>
but I want to know the dep... | [
"Try an array of loop.index values where the parent index is saved before each call to loop() and popped immediately after. To modify an array without rendering text, enable {% do ... %} statements.\nExample:\ntemplate = \"\"\"\n{%- set idxs = [0] -%}\n{%- for item in sitemap recursive %}\n depth={{idxs|length}... | [
4
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0006401912_jinja2_python.txt |
Q:
trying to use code_swarm but Im having some python scripting problems with perforce on osx
I am having issues running this:
link-mbp:codeswarm-0.1 benb$ python convert_logs/convert_logs.py -perforce-path
Traceback (most recent call last):
File “convert_logs/convert_logs.py”, line 408, in
main()
File “convert_logs/... | trying to use code_swarm but Im having some python scripting problems with perforce on osx | I am having issues running this:
link-mbp:codeswarm-0.1 benb$ python convert_logs/convert_logs.py -perforce-path
Traceback (most recent call last):
File “convert_logs/convert_logs.py”, line 408, in
main()
File “convert_logs/convert_logs.py”, line 350, in main
files = run_marshal(’p4 -G describe -s “‘ + changelist['chan... | [
"I had the exact same problem. Not being an expert on python I debugged the script using a print-statement on line 350 like this:\nfor changelist in changelists:\n print changelist # <-- here\n files = run_marshal('p4 -G describe -s \"' + changelist['change'] + '\"')\n\nThis revealed my problem - I had used a... | [
0
] | [] | [] | [
"code_swarm",
"macos",
"perforce",
"python"
] | stackoverflow_0002555481_code_swarm_macos_perforce_python.txt |
Q:
How to include autocomplete in a python web form with MongoDB
I wrote a web page in Python as follows:
#!/usr/bin/env python
import os, re, sys
from datetime import datetime
from pymongo import Connection
import cgi
class Handler:
def do(self, environ, start_response):
html = "<html><head><title>C ... | How to include autocomplete in a python web form with MongoDB | I wrote a web page in Python as follows:
#!/usr/bin/env python
import os, re, sys
from datetime import datetime
from pymongo import Connection
import cgi
class Handler:
def do(self, environ, start_response):
html = "<html><head><title>C Informatics</title></head><body>"
html += "<h1><center>Na... | [
"This question has neither to do with Python nor with MongoDB. What you are trying is some auto-complete functionality through Javascript.\nhttp://docs.jquery.com/Plugins/autocomplete\nis a good start.\n"
] | [
3
] | [] | [] | [
"autocomplete",
"forms",
"python"
] | stackoverflow_0006437260_autocomplete_forms_python.txt |
Q:
mysqldb environment
root@dicksonxavier-desktop:/home/dicksonxavier/Downloads/MySQL-python-1.2.3# python setup.py build
sh: mysql_config: not found
Traceback (most recent call last):
File "setup.py", line 15, in <module>
metadata, options = get_config()
File "/home/dicksonxavier/Downloads/MySQL-python-1.2.3... | mysqldb environment | root@dicksonxavier-desktop:/home/dicksonxavier/Downloads/MySQL-python-1.2.3# python setup.py build
sh: mysql_config: not found
Traceback (most recent call last):
File "setup.py", line 15, in <module>
metadata, options = get_config()
File "/home/dicksonxavier/Downloads/MySQL-python-1.2.3/setup_posix.py", line 43... | [
"Install the mysql-devel package or whatever your distro calls it.\n"
] | [
2
] | [] | [] | [
"django",
"mysql_python",
"python"
] | stackoverflow_0006437474_django_mysql_python_python.txt |
Q:
Python dictionary to sorted tuples, can this be done better?
I have an dictonary for my input with the following characteristics:
Each value will be either an integer, string or iterable (other than a string).
If the element is an iterable, each element in that iterable will only be a string or integer.
ex:
myd... | Python dictionary to sorted tuples, can this be done better? | I have an dictonary for my input with the following characteristics:
Each value will be either an integer, string or iterable (other than a string).
If the element is an iterable, each element in that iterable will only be a string or integer.
ex:
mydict = {
'one': 1,
'two': '23',
'three': 3,
'four':... | [
">>> sorted((i,k) for i,j in mydict.items() for k in ([j] if isinstance(j, str) or isinstance(j, int) else j))\n[('four', 5), ('four', 7), ('four', 8), ('four', '6'), ('nine', 9), ('one', 1), ('three', 3), ('two', '2')]\n\nThe idea here is that if the value is an int or a str, you put it in a list. Now the problem ... | [
5,
1,
0
] | [] | [] | [
"dictionary",
"generator",
"iterable",
"python",
"sorting"
] | stackoverflow_0006435083_dictionary_generator_iterable_python_sorting.txt |
Q:
problem: throwing exception in re.match function
I have one simple question about throwing exeptions in re.match function
Is there a way to 'match' function threw an exception? Maybe some flag. If this is not possible maybe there is some other function in RE library which throw an exception when the list will be e... | problem: throwing exception in re.match function | I have one simple question about throwing exeptions in re.match function
Is there a way to 'match' function threw an exception? Maybe some flag. If this is not possible maybe there is some other function in RE library which throw an exception when the list will be empty for example.
Example:
verify_link=re.match(".*"+s... | [
"There is no such function(s) in Python re module. See the doc:\n\nexception re.error\nException raised when a string passed to one of the functions here is\n not a valid regular expression (for\n example, it might contain unmatched\n parentheses) or when some other error\n occurs during compilation or matchin... | [
4,
2,
1,
0
] | [] | [] | [
"exception",
"python",
"regex"
] | stackoverflow_0006437422_exception_python_regex.txt |
Q:
Django: I cannot form a table
I have a model in which there are two fields, one characterized by the element position on the X coordinate of the second Y
class Task(models.Model):
posx = models.IntegerField(blank = True, null = True, verbose_name='X coordinate')
posy = models.IntegerField(blank = True, nul... | Django: I cannot form a table | I have a model in which there are two fields, one characterized by the element position on the X coordinate of the second Y
class Task(models.Model):
posx = models.IntegerField(blank = True, null = True, verbose_name='X coordinate')
posy = models.IntegerField(blank = True, null = True, verbose_name='Y coordinat... | [
"Use this to generate the table as a list of lists (two dimensional array), then pass it to your template:\ndef get_table(proj, max_x, max_y):\n table = [[False for x in xrange(max_x)] for y in xrange(max_y)]\n tasks = Task.objects.filter(proj=proj)\n for task in tasks:\n table[task.posy-1][task.posx-1] ... | [
0
] | [] | [] | [
"coordinates",
"django",
"python"
] | stackoverflow_0006436923_coordinates_django_python.txt |
Q:
How to encrypt files in twisted?
I'm using twisted to create a server.
Problem is, I must protect my code. Since I don't want to publish it, I'm not really interess into obfuscation or compilation of the python code.
My problem is, my twisted application must run with root uid and a lot of people have root access ... | How to encrypt files in twisted? | I'm using twisted to create a server.
Problem is, I must protect my code. Since I don't want to publish it, I'm not really interess into obfuscation or compilation of the python code.
My problem is, my twisted application must run with root uid and a lot of people have root access to this server.
I don't care if they c... | [
"You have a number of problems here.\n\nmy twisted application must run with root uid\n\nThis is bad. If there are vulnerabilities in your application, then they will be made more serious by running as root. You should consider finding a way to not run as root. For example, if you only run as root so you can bin... | [
4,
0
] | [] | [] | [
"encryption",
"obfuscation",
"python",
"twisted"
] | stackoverflow_0006438124_encryption_obfuscation_python_twisted.txt |
Q:
How to get around the need for multiple reactors in twisted
I am running a Qt application on Linux using the qt4reactor
The application sends and receives bytes on the serial port.
This works very well on Linux with the QtReactor
However when I port the application to windows then I have a problem.
On windows I us... | How to get around the need for multiple reactors in twisted | I am running a Qt application on Linux using the qt4reactor
The application sends and receives bytes on the serial port.
This works very well on Linux with the QtReactor
However when I port the application to windows then I have a problem.
On windows I use the SerialPort class from _win32SerialPort.
The doc string in _... | [
"I recently added serial port supported to selectreactor, iocpreactor, and gtkreactor on Windows. This approach can be extended to support them in the Qt reactor as well, I expect.\n",
"Call the Qt message checking/handling functions in the idle event of the Win32 reactor.\n"
] | [
2,
0
] | [] | [] | [
"python",
"reactor",
"twisted"
] | stackoverflow_0006436935_python_reactor_twisted.txt |
Q:
twisted handle_quit() the way to disconnect?
so I'm implementing a log server with twisted (python-loggingserver) and I added simple authentication to the server. If the authentication fails, I wanna close the connection to the client. The class in the log server code already has a function called handle_quit(). I... | twisted handle_quit() the way to disconnect? | so I'm implementing a log server with twisted (python-loggingserver) and I added simple authentication to the server. If the authentication fails, I wanna close the connection to the client. The class in the log server code already has a function called handle_quit(). Is that the right way to close the connection? Here... | [
"If the handle_quit message you're referring to is this one, then that should work fine. The only thing the method does is self.transport.loseConnection(), which closes the connection. You could also just do self.transport.loseConnection() yourself, which will accomplish the same thing (since it is, of course, th... | [
2
] | [] | [] | [
"logging",
"python",
"twisted"
] | stackoverflow_0006434668_logging_python_twisted.txt |
Q:
mod_wsgi python2.5 ubuntu 11.04 problem
I have such cfg on my amd64 platform with ubuntu 11.04:
build python2.5 from source to /usr/local/python2.5
virtualenv at /home/se7en/.virtualenvs/e-py25
alsp i recompile mod_wsgi.so to custom python:
se7en@se7en-System-Product-Name:~$ ldd /usr/lib/apache2/modules/mod_wsgi... | mod_wsgi python2.5 ubuntu 11.04 problem | I have such cfg on my amd64 platform with ubuntu 11.04:
build python2.5 from source to /usr/local/python2.5
virtualenv at /home/se7en/.virtualenvs/e-py25
alsp i recompile mod_wsgi.so to custom python:
se7en@se7en-System-Product-Name:~$ ldd /usr/lib/apache2/modules/mod_wsgi.so
linux-vdso.so.1 => (0x00007fff5af6c0... | [
"The operating system supplied Python versions on Linux boxes are compiled for UCS4 Unicode character width. If you build from source code, if you don't explicitly say otherwise it will default to UCS2. The result is that your system Python 2.5 and local version under /usr/local are expecting different widths for U... | [
2,
1
] | [] | [] | [
"mod_wsgi",
"python"
] | stackoverflow_0006438260_mod_wsgi_python.txt |
Q:
self parameter and metaprogramming
Well, code speaks more (I have hard-coded some things, to isolate the problem and make the question shorter):
class wrapper:
def __init__( self, func ):
self.func = func
def __call__( self, *args ):
print( "okay, arg = ", args[0] )
self.func( self,... | self parameter and metaprogramming | Well, code speaks more (I have hard-coded some things, to isolate the problem and make the question shorter):
class wrapper:
def __init__( self, func ):
self.func = func
def __call__( self, *args ):
print( "okay, arg = ", args[0] )
self.func( self, args )
class M( type ):
def __new_... | [
"Use function wrapper, instead of class one. Closure will take care of the rest:\n>>> def wrapper(meth):\n... def _wrapped_meth(self, *args):\n... print('okay, arg = ', args)\n... meth(self, *args)\n... return _wrapped_meth\n...\n>>> class M(type):\n... def __new__(klass, name, b... | [
6,
3,
1
] | [] | [] | [
"metaprogramming",
"python"
] | stackoverflow_0006429708_metaprogramming_python.txt |
Q:
how to call to method A of class A from method B of class A
there seems to be a lot of answers on how to call method A of class A from class B but none on how to call to method A of class A from method B of class A. this probably easy but am new to oop in python. here is a quick illustration of what am trying to ... | how to call to method A of class A from method B of class A | there seems to be a lot of answers on how to call method A of class A from class B but none on how to call to method A of class A from method B of class A. this probably easy but am new to oop in python. here is a quick illustration of what am trying to do
class A:
def __init__():
def method_A(self):
... | [
"ans = self.method_A()\n\nself is an instance of A, and methods on instances are called using instance.method().\n",
"Attributes need to be referenced off the object.\nans = self.method_A()\n\n",
"Members of a class are accessed as attributes of self, so you just use this:\nself.method_A()\n\nAlso, you do not n... | [
5,
1,
0
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0006439188_class_methods_python.txt |
Q:
int((0.1+0.7)*10) = 7 in several languages. How to prevent this?
Recently I came across a bug/feature in several languages. I have a very basic knowledge about how it's caused (and I'd like some detailed explanation), but when I think of all the bugs I must have made over the years, the question is how can I deter... | int((0.1+0.7)*10) = 7 in several languages. How to prevent this? | Recently I came across a bug/feature in several languages. I have a very basic knowledge about how it's caused (and I'd like some detailed explanation), but when I think of all the bugs I must have made over the years, the question is how can I determine "Hey, this might cause a riddiculous bug, I'd better use arbitrar... | [
"What Every Computer Scientist Should Know About Floating-Point Arithmetic\n",
"It's not a language issue. It's general issue with float point arithmetic. \n",
"Stop using floats. No, really.\n",
"The floating point representation of numbers is not exact.\nIn Python, int truncates floats towards zero to the n... | [
33,
7,
5,
3,
1,
1,
0
] | [] | [] | [
"internal_representation",
"javascript",
"php",
"python",
"ruby"
] | stackoverflow_0006439140_internal_representation_javascript_php_python_ruby.txt |
Q:
resources on eventlet
hi
i am actually working on a project which needs realtime updates so we are using eventlet for that so can u guys refer to resources to read about eventlet given the fact that i have no
previous experience of using eventlet or any realtime library for that matter
A:
Their patterns page cou... | resources on eventlet | hi
i am actually working on a project which needs realtime updates so we are using eventlet for that so can u guys refer to resources to read about eventlet given the fact that i have no
previous experience of using eventlet or any realtime library for that matter
| [
"Their patterns page could be a good start.\n",
"There's definitely a lack of good documentation for Eventlet. Here are some resources I've found helpful:\nhttp://eventlet.net/doc/examples.html\nhttps://convore.com/django-community/why-dont-more-people-use-eventlet/\nhttps://github.com/ckreutzer/eventlet-django-w... | [
0,
0
] | [] | [] | [
"eventlet",
"python"
] | stackoverflow_0005555559_eventlet_python.txt |
Q:
how to create a sparse matrix from lists of numbers
I have three lists namely A , B , C
All these lists contain 97510 items . I need to create a sparse matrix like this
matrix[A[0]][B[0]] = C[0]
For example ,
A=[1,2,3,4,5]
B=[7,8,9,10,11]
C=[14,15,16,17,18]
I need to create a sparse matrix with
matrix[1][7... | how to create a sparse matrix from lists of numbers | I have three lists namely A , B , C
All these lists contain 97510 items . I need to create a sparse matrix like this
matrix[A[0]][B[0]] = C[0]
For example ,
A=[1,2,3,4,5]
B=[7,8,9,10,11]
C=[14,15,16,17,18]
I need to create a sparse matrix with
matrix[1][7] = 14 #(which is C[1])
matrix[2][8] = 15 #and so on ..
... | [
"I suggest you have a look at the SciPy sparse matrices. E.g. a COO sparse matrix:\nmatrix = sparse.coo_matrix((C,(A,B)),shape=(5,5))\n\nNote: I just took the COO matrix because it was in the example, you can take any other. You probably have to try which one is most suitable for your situation. They all differ in ... | [
8,
4,
2,
0
] | [] | [] | [
"list",
"python",
"sparse_matrix"
] | stackoverflow_0006438318_list_python_sparse_matrix.txt |
Q:
Assignment to discontinuous slices in python
In Matlab I can do this:
s1 = 'abcdef'
s2 = 'uvwxyz'
s1(1:2:end) = s2(1:2:end)
s1 is now 'ubwdyf'
This is just an example of the general:
A(I) = B
Where A,B are vectors, I a vector of indices and B is the same length as I. (Im ignoring matrices for the moment).
What... | Assignment to discontinuous slices in python | In Matlab I can do this:
s1 = 'abcdef'
s2 = 'uvwxyz'
s1(1:2:end) = s2(1:2:end)
s1 is now 'ubwdyf'
This is just an example of the general:
A(I) = B
Where A,B are vectors, I a vector of indices and B is the same length as I. (Im ignoring matrices for the moment).
What would be the pythonic equivalent of the general c... | [
">>> s1 = list('abcdef')\n>>> s2 = list('uvwxyz')\n>>> s1[0::2] = s2[0::2]\n>>> s1\n['u', 'b', 'w', 'd', 'y', 'f']\n>>> ''.join(s1)\n'ubwdyf'\n\nThe main differences are:\n\nStrings are immutable in Python. You can use lists of characters instead though.\nIndexing is 0-based in Python.\nThe slicing syntax is [start... | [
6,
1,
0
] | [] | [] | [
"indexing",
"matlab",
"python",
"slice",
"variable_assignment"
] | stackoverflow_0006439076_indexing_matlab_python_slice_variable_assignment.txt |
Q:
Using Webhelpers in mako template in Pyramid
How do I use Webhelpers in a Mako template in my Pyramid app?
In Pylons I had global helper variable h to use in my templates so I could simply do:
${h.stylesheet_link("/css/default.css")}
given I import stylesheet_link from webhelpers.html.tags in Pylons lib/helpers.... | Using Webhelpers in mako template in Pyramid | How do I use Webhelpers in a Mako template in my Pyramid app?
In Pylons I had global helper variable h to use in my templates so I could simply do:
${h.stylesheet_link("/css/default.css")}
given I import stylesheet_link from webhelpers.html.tags in Pylons lib/helpers.py
I don't want to go with Akhet and replicate ful... | [
"The cookbook in the docs refers to this here\nhttp://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/templates/templates.html\nYou basically inject the helpers using a before-render event so that it's available in your templates. Hope that helps.\n"
] | [
6
] | [] | [] | [
"akhet",
"mako",
"pyramid",
"python"
] | stackoverflow_0006438618_akhet_mako_pyramid_python.txt |
Q:
How to stop a coroutines / thread in Python eventlet
When I use the eventlet package to run a multi-coroutines task, even when the coroutines pool is empty, the program won't continue to run, but will get stuck in a loop. Following is my code and the last row never get executed.
import eventlet
global count
post_... | How to stop a coroutines / thread in Python eventlet | When I use the eventlet package to run a multi-coroutines task, even when the coroutines pool is empty, the program won't continue to run, but will get stuck in a loop. Following is my code and the last row never get executed.
import eventlet
global count
post_id=[]
last_id=0
def download(post_id):
global count
... | [
"The last row never gets executed because your final call to q.get() blocks forever, waiting for something to be added to the queue. There are a few ways you could fix this, including passing a timeout value to get. I think the cleanest solution is to wait for the current tasks to finish if the queue is empty befor... | [
1
] | [] | [] | [
"coroutine",
"eventlet",
"multithreading",
"python",
"threadpool"
] | stackoverflow_0006133633_coroutine_eventlet_multithreading_python_threadpool.txt |
Q:
Downloading from a dynamic list of files in Django Admin
I currently have a django app which generates PDFs and saves them to a specific directory. From the admin interface I want to have some way to view the list of files within that directory (similar to models.FilePathField()), but also be able to download the... | Downloading from a dynamic list of files in Django Admin | I currently have a django app which generates PDFs and saves them to a specific directory. From the admin interface I want to have some way to view the list of files within that directory (similar to models.FilePathField()), but also be able to download them. I realize that django was never intended to actually serve... | [
"Would this project fit your needs? http://code.google.com/p/django-filebrowser/\n",
"I ended up realizing that I was going about the problem in a more complicated manner than was necessary. Using two separate views trivializes the issue. I was just under the impression that the admin interface would include su... | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006416835_django_python.txt |
Q:
How to handle special characters in comments and hard coded strings in python file?
This question aims at the following two scenarios:
You want to add a string with special characters to a variable:
special_char_string = "äöüáèô"
You want to allow special characters in comments.
# This a comment with special char... | How to handle special characters in comments and hard coded strings in python file? | This question aims at the following two scenarios:
You want to add a string with special characters to a variable:
special_char_string = "äöüáèô"
You want to allow special characters in comments.
# This a comment with special characters in it: äöà etc.
At the moment I handle this this way:
# -*- encoding: utf-8 -*-
s... | [
"Python will check the first or second line for an emacs/vim-like encoding specification.\n\nMore precisely, the first or second\n line must match the regular\n expression \"coding[:=]\\s*([-\\w.]+)\". The first\n group of this\n expression is then interpreted as encoding name. If the encoding\n is... | [
4,
2
] | [] | [] | [
"comments",
"encoding",
"python",
"special_characters",
"string"
] | stackoverflow_0006439424_comments_encoding_python_special_characters_string.txt |
Q:
Sending a reset in TCP/IP Socket connection
I am using python’s socket.py to create a connection to an ftp-server. Now I want to reset the connection (send a RST Flag) and listen to the response of the ftp-server. (FYI using socket.send('','R') does not work as the OS sends FIN flag instead of RST.)
A:
Turn the ... | Sending a reset in TCP/IP Socket connection | I am using python’s socket.py to create a connection to an ftp-server. Now I want to reset the connection (send a RST Flag) and listen to the response of the ftp-server. (FYI using socket.send('','R') does not work as the OS sends FIN flag instead of RST.)
| [
"Turn the SO_LINGER socket option on and set the linger time to 0 seconds. This will cause TCP to abort the connection when it is closed, flush the data and send a RST. See section 7.5 and example 15.21 in UNP.\nIn python:\ndef client(host, port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n ... | [
44,
3,
2
] | [] | [] | [
"networking",
"python",
"reset",
"sockets"
] | stackoverflow_0006439790_networking_python_reset_sockets.txt |
Q:
pip install for Multiple Python Distributions on Mac
I am fine having multiple distributions of Python on my system, given the advice found here.
However: I cannot get easy_install nor pip install to install to the distribution associated with /usr/bin/python on Mac. They will only install modules to the distribut... | pip install for Multiple Python Distributions on Mac | I am fine having multiple distributions of Python on my system, given the advice found here.
However: I cannot get easy_install nor pip install to install to the distribution associated with /usr/bin/python on Mac. They will only install modules to the distribution associated with /Library/Python/2.6/.
This is a proble... | [
"It turned out that easy_install (and pip) was not associated with Python 2.7 (the version used by my default python and XCode). Per vartec's instructions on an Answer that has now been deleted, I downloaded and installed easy_install for the correct version of python:\nsh setuptools-0.6c11-py2.7.egg\n(easy_install... | [
4,
1
] | [] | [] | [
"easy_install",
"macos",
"pip",
"python"
] | stackoverflow_0006439978_easy_install_macos_pip_python.txt |
Q:
Getting function object for int() and float() functions
I want to pass a function to a function in Python. I know I can do this simply by putting the function name as a parameter, eg:
blah(5, function)
However, I want to pass the int() function and the float() function to this function. If I just put the function... | Getting function object for int() and float() functions | I want to pass a function to a function in Python. I know I can do this simply by putting the function name as a parameter, eg:
blah(5, function)
However, I want to pass the int() function and the float() function to this function. If I just put the function name in then it assumes I am referring to the int and float ... | [
"Just passing int and float is fine. You are right that this will actually pass type objects instead of functions, but that's not important. The important thing is that the passed object is callable, and calling the type objects will do what you expect.\n",
"The type objects are what you want.\n>>> def converte... | [
11,
3
] | [] | [] | [
"function",
"python"
] | stackoverflow_0006440397_function_python.txt |
Q:
restoring list from unified_diff output
I need to generate the diff between two arrays of strings:
a=['1','2']
b=['1','2','3']
To achieve this I'm using the difflib library in Python (2.6):
c=difflib.unified_diff(a,b)
and I save the content of
d=list(c)
which is something like:
['--- \n', '+++ \n', '@@ -1,2 +... | restoring list from unified_diff output | I need to generate the diff between two arrays of strings:
a=['1','2']
b=['1','2','3']
To achieve this I'm using the difflib library in Python (2.6):
c=difflib.unified_diff(a,b)
and I save the content of
d=list(c)
which is something like:
['--- \n', '+++ \n', '@@ -1,2 +1,3 @@\n', ' 1', ' 2', '+3']
How can I build... | [
"Not sure that my sample is a good style, but you can use something like this:\nfrom collections import Counter\n\na=['1','2']\nb=['1','2','3']\n\na.extend(b)\n\n[k for k,v in Counter(a).items() if v == 1]\n\nOR if your lists could have only unique items:\nlist(set(a) ^ set(b))\n\nOR:\nmissed_in_a = [x for x in a i... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006440458_python.txt |
Q:
Python multiprocessing
This question is more fact finding and thought process than code oriented.
I have many compiled C++ programs that I need to run at different times and with different parameters. I'm looking at using Python multiprocessing to read a job from job queue (rabbitmq) and then feed that job to a C+... | Python multiprocessing | This question is more fact finding and thought process than code oriented.
I have many compiled C++ programs that I need to run at different times and with different parameters. I'm looking at using Python multiprocessing to read a job from job queue (rabbitmq) and then feed that job to a C++ program to run (maybe subp... | [
"\nThe Python program would be the\n central manager and would simply read\n jobs from the que, spawn a process (or\n subprocess?) with the appropriate C++\n program to run the job, get the\n results (subprocess stdout & stderr),\n feed that to a callback and put the\n process back in a que of processes\n w... | [
11,
1,
0
] | [] | [] | [
"multicore",
"multiprocessing",
"python"
] | stackoverflow_0006440474_multicore_multiprocessing_python.txt |
Q:
Python, working with lists
I have such list of tuples:
lst = [(10, u'1.15', u'1.15'), (5, 0, u'1.875'), (3, u'2.28', u'2.28')]
and I want to get the new one with just second and third element of each tuple, which not equal to the 0, in other words, I need something like:
new_lst = [u'1.15', u'1.15',u'1.875', u'2.... | Python, working with lists | I have such list of tuples:
lst = [(10, u'1.15', u'1.15'), (5, 0, u'1.875'), (3, u'2.28', u'2.28')]
and I want to get the new one with just second and third element of each tuple, which not equal to the 0, in other words, I need something like:
new_lst = [u'1.15', u'1.15',u'1.875', u'2.28', u'2.28']
Thanks for your a... | [
"new_lst = [x for t in lst for x in t[1:] if x != 0]\n\n",
">>> [x for y in lst for x in y[1:3] if x]\n[u'1.15', u'1.15', u'1.875', u'2.28', u'2.28']\n\n",
">>> L = [(10, u'1.15', u'1.15'), (5, 0, u'1.875'), (3, u'2.28', u'2.28')]\n>>> answer = []\n>>> for tup in L:\n... answer.extend([i for i in tup[1:] if... | [
4,
2,
0
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0006441064_list_python_tuples.txt |
Q:
Python: fast dictionary of big int keys
I have got a list of >10.000 int items. The values of the items can be very high, up to 10^27. Now I want to create all pairs of the items and calculate their sum. Then I want to look for different pairs with the same sum.
For example:
l[0] = 4
l[1] = 3
l[2] = 6
l[3] = 1
...... | Python: fast dictionary of big int keys | I have got a list of >10.000 int items. The values of the items can be very high, up to 10^27. Now I want to create all pairs of the items and calculate their sum. Then I want to look for different pairs with the same sum.
For example:
l[0] = 4
l[1] = 3
l[2] = 6
l[3] = 1
...
pairs[10] = [(0,2)] # 10 is the sum of the ... | [
"There are the trivial optimizations like caching constant values in a local variable and using xrange instead of range:\npairs = {}\nlen_l = len(l)\nfor i in xrange(len_l):\n for j in xrange(i+1, len_l):\n s = l[i] + l[j]\n res = pairs.setdefault(s, [])\n res.append((i,j))\n\nHowever, it is... | [
4,
1,
0,
0
] | [] | [] | [
"biginteger",
"dictionary",
"int",
"optimization",
"python"
] | stackoverflow_0005911191_biginteger_dictionary_int_optimization_python.txt |
Q:
Help with solving the DistributionNotFound error in Virtualenv
I've installed virtualenv on my system which the argument to not copy over any site packages. Then I did an easy_install to install Django and that went fine too.
In the virtual environ when i try and try django-admin.py, I get an error that I'm not be... | Help with solving the DistributionNotFound error in Virtualenv | I've installed virtualenv on my system which the argument to not copy over any site packages. Then I did an easy_install to install Django and that went fine too.
In the virtual environ when i try and try django-admin.py, I get an error that I'm not being able to resolve. Could someone help me out please? Thanks a ton.... | [
"I don't think easy_install knows about virtualenv. Use pip instead.\n"
] | [
2
] | [] | [] | [
"django",
"python",
"virtualenv"
] | stackoverflow_0006441010_django_python_virtualenv.txt |
Q:
Non-interactive installation of an additional Python environment on a computer which already has Python installed
I'm working on a deployment tool which will build a python environment with a number of dependancies pre-installed. According to the documentation on Python's web-site I should be able to do something ... | Non-interactive installation of an additional Python environment on a computer which already has Python installed | I'm working on a deployment tool which will build a python environment with a number of dependancies pre-installed. According to the documentation on Python's web-site I should be able to do something like this:
msiexec.exe /i python_installer\python-2.4.4.msi TARGETDIR=c:\temp\install\fooX
However in the case where t... | [
"You could try the /a instead of /i flag:\nFrom msiexec help:\n/a <Product.msi>\n Administrative install - Installs a product on the network\n\nAnother option to consider is /qn:\n/q[n|b|r|f]\n Sets user interface level\n n - No UI\n\nYou can get to the help window of msiexec by executing only msiexec with... | [
2
] | [] | [] | [
"python",
"windows",
"windows_installer"
] | stackoverflow_0006441353_python_windows_windows_installer.txt |
Q:
Error while running Google App Engine : unable to open database file
I have tried adding "--clear_datastore" flag but it still doesn't work.
Does it have something to do with my OS? My OS is Windows 7 and I'm using Python 2.5 .
App Engine DSK release: "1.5.1"
Error Reports:
2011-06-22 21:16:55 Running command: "[... | Error while running Google App Engine : unable to open database file | I have tried adding "--clear_datastore" flag but it still doesn't work.
Does it have something to do with my OS? My OS is Windows 7 and I'm using Python 2.5 .
App Engine DSK release: "1.5.1"
Error Reports:
2011-06-22 21:16:55 Running command: "['C:\\Python25\\pythonw.exe', 'C:\\Program Files\\Google\\google_appengine\... | [
"It may be because you have unicode characters in your username or maybe it just can't get your username for some reason (c:\\users\\username\\appdata\\local\\temp\\dev_appserver.rdbms). Try running app engine launcher with the admin flag or if it had been working previously, just delete the database file.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python",
"sqlite"
] | stackoverflow_0006441369_google_app_engine_python_sqlite.txt |
Q:
Executing python scripts with subprocess.call using shebang
I'm writing a (somewhat) modular application in Python 3 and I'd like to run arbitrary programs from it, said program being specified at runtime and not necessarily a python script.
So I use for example,
subprocess.call([spam, "-i", eggs, "-o", ham])
If ... | Executing python scripts with subprocess.call using shebang | I'm writing a (somewhat) modular application in Python 3 and I'd like to run arbitrary programs from it, said program being specified at runtime and not necessarily a python script.
So I use for example,
subprocess.call([spam, "-i", eggs, "-o", ham])
If spam is a python script, with shebang to python3 and executable r... | [
"You need to use shell=True, and you need your array to be turned into a command string, like this:\nsubprocess.call(' '.join([spam, \"-i\", eggs, \"-o\", ham]), shell=True)\n\nThis will invoke the shell instead of the direct command, and the shell should be able to handle the shebang.\n"
] | [
8
] | [
"Try\nsubprocess.call(['spam.py', \"-i\", eggs, \"-o\", ham])\n\n"
] | [
-2
] | [
"python",
"python_3.x",
"shebang",
"subprocess"
] | stackoverflow_0006441507_python_python_3.x_shebang_subprocess.txt |
Q:
PyGTK Glade File Manager
I am trying to make a file manager in python that looks like GNOME default file manager (nautilus) Because I am developing a FilePane plugin for a python written text editor. I don't know if there is a widget to give me the same look of Nautilus. If not, what widgets can I use to get a nic... | PyGTK Glade File Manager | I am trying to make a file manager in python that looks like GNOME default file manager (nautilus) Because I am developing a FilePane plugin for a python written text editor. I don't know if there is a widget to give me the same look of Nautilus. If not, what widgets can I use to get a nice looking file manager?
| [
"I searched GTK API and I found that GTK TreeView does what I want.\n"
] | [
0
] | [] | [] | [
"glade",
"pygtk",
"python"
] | stackoverflow_0006356190_glade_pygtk_python.txt |
Q:
Python in Emacs (no modes, plain installation)
I'm trying to start the Python interpreter in Emacs 22.3.1. I have no modes installed (nor I'm planning at the moment). Emacs recognises the Python file, but I have this in the initial message:
Loading python (compiled; note, source file is newer)...
Loading easymenu.... | Python in Emacs (no modes, plain installation) | I'm trying to start the Python interpreter in Emacs 22.3.1. I have no modes installed (nor I'm planning at the moment). Emacs recognises the Python file, but I have this in the initial message:
Loading python (compiled; note, source file is newer)...
Loading easymenu...done
Loading python (compiled; note, source file i... | [
"The answer has two parts. The first thing that was wrong was the extra space character in Windows path settings. This caused Emacs not to fail while calling python.\nThe second part was Emacs freezing. Updating to the newest version solved the problem.\nThanks everyone for their comments!\n"
] | [
0
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0006418257_emacs_python.txt |
Q:
python subprocess.Popen
I am having a difficult time understanding how to get python to call a system command with the subprocess.Popen function.
the_file = ('logs/consolidated.log.gz')
webstuff = subprocess.Popen(['/usr/bin/zgrep', '/meatsauce/', the_file ],stdout=subprocess.PIPE)
for line in webstuff.... | python subprocess.Popen | I am having a difficult time understanding how to get python to call a system command with the subprocess.Popen function.
the_file = ('logs/consolidated.log.gz')
webstuff = subprocess.Popen(['/usr/bin/zgrep', '/meatsauce/', the_file ],stdout=subprocess.PIPE)
for line in webstuff.stdout:
print line
Tryin... | [
"The problem is in how you're constructing your arguments. The way you have it now, you're running:\n/usr/bin/zgrep /meatsauce/ logs/consolidated.log.gz\nNote the space between /meatsauce/ and logs...\nTo do what I think you're intending, use os.path.join a la:\nimport os\n\nthe_file = 'logs/consolidated.log.gz' ... | [
2,
2,
1,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0006432134_python_subprocess.txt |
Q:
Follow user in Tweepy
I'm looking to follow users that follow me, but I don't already follow in Tweepy. I've got the logic, but my issue is the syntax.
for follower in followers_list:
if follower not in friends_list:
to_follow.append(follower)
print to_follow
for follower ... | Follow user in Tweepy | I'm looking to follow users that follow me, but I don't already follow in Tweepy. I've got the logic, but my issue is the syntax.
for follower in followers_list:
if follower not in friends_list:
to_follow.append(follower)
print to_follow
for follower in to_follow:
print ... | [
"Is your followers_list filled with Twitter user.screen_names? If so, there's a topic on the issue that should help you out here.\nThe followers_list should be inside a comma-separated list, like the following:\nstream = tweepy.Stream(auth, StreamWatcherListener(), timeout=None)\nfollow_list = ['1234567890', '2345... | [
4
] | [] | [] | [
"python",
"tweepy",
"twitter"
] | stackoverflow_0005944915_python_tweepy_twitter.txt |
Q:
Auto updating properties in sqlalchemy
I've got a sqlalchemy model that is set up like this:
class Entry(Base):
__tablename__ = 'entries'
__table__ = Table('entries', Base.metadata,
Column('id', Integer, primary_key=True, unique=True),
Column('user_id', Integer, ForeignKey('users.id... | Auto updating properties in sqlalchemy | I've got a sqlalchemy model that is set up like this:
class Entry(Base):
__tablename__ = 'entries'
__table__ = Table('entries', Base.metadata,
Column('id', Integer, primary_key=True, unique=True),
Column('user_id', Integer, ForeignKey('users.id', onupdate="CASCADE", ondelete="RESTRICT"))... | [
"@hybrid_descriptor certainly does it using the form described at http://www.sqlalchemy.org/docs/orm/mapper_config.html#using-descriptors . You assign to the database-mapped attribute, which you can map under a different name - since you're using the __table__, you can use a form like:\nclass Entry(Base):\n __t... | [
6
] | [] | [] | [
"automatic_properties",
"properties",
"python",
"sqlalchemy"
] | stackoverflow_0006422248_automatic_properties_properties_python_sqlalchemy.txt |
Q:
If the set increases in size add the word to the dict as a key with the value being the new length of the set
If the set increases in size (indicating this word has not been processed before),
add the word to the dict as a key with the value being the new length of the set.
Using another loop, display the list of... | If the set increases in size add the word to the dict as a key with the value being the new length of the set | If the set increases in size (indicating this word has not been processed before),
add the word to the dict as a key with the value being the new length of the set.
Using another loop, display the list of words in the dict along with their value,
which represents the order in which they were discovered by the program... | [
"Basing my answer on your comment...\nInstead of\nfor word in text.lower().split():#split text into words\n [...]\n print (freq)\n\nIt should be\nfor word in text.lower().split():#split text into words\n [...]\nprint (freq)\n\nSo that you're printing once all the words have been encountered.\nWhenever you ... | [
0
] | [] | [] | [
"python",
"set"
] | stackoverflow_0006441380_python_set.txt |
Q:
How to use Popen to run backgroud process and avoid zombie?
I've a listener server running new thread to for each client handler. Each handler can use:
proc = subprocess.Popen(argv, executable = "./Main.py", stdout = _stdout, stderr = subprocess.STDOUT, close_fds=False)
to run new process in background, after wha... | How to use Popen to run backgroud process and avoid zombie? | I've a listener server running new thread to for each client handler. Each handler can use:
proc = subprocess.Popen(argv, executable = "./Main.py", stdout = _stdout, stderr = subprocess.STDOUT, close_fds=False)
to run new process in background, after what the handler thread is ended.
After the background process is en... | [
"If you add a signal handler for SIGCHLD you will have the kernel handle the wait/reap piece.\nSpecifically the line:\nsignal.signal(signal.SIGCHLD, signal.SIG_IGN)\n\nWill take care of your Zombies.\n"
] | [
5
] | [] | [] | [
"process",
"python",
"subprocess",
"zombie_process"
] | stackoverflow_0006442428_process_python_subprocess_zombie_process.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.