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 xml.dom.minidom Unicode
I'm trying to create an xml document in python, however some of the strings i'm working with are encoded in unicode. Is there a way to create a text node using xml.dom.minidom using unicode strings? Is there another module I can use?
Thanks.
A:
In theory, per the docs:
the DOMStri... | Python xml.dom.minidom Unicode | I'm trying to create an xml document in python, however some of the strings i'm working with are encoded in unicode. Is there a way to create a text node using xml.dom.minidom using unicode strings? Is there another module I can use?
Thanks.
| [
"In theory, per the docs:\n\nthe DOMString defined in the\n recommendation is mapped to a Python\n string or Unicode string. Applications\n should be able to handle Unicode\n whenever a string is returned from the\n DOM.\n\nso you should be fine with either a Unicode string, or a Python string (utf-8 is the de... | [
3,
1,
1
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0001610948_python_unicode.txt |
Q:
appengine, urlfetch, and the content-length header
I have a Google Appengine app requesting pages from another server using urllib2 POSTs. I recently enabled gzip compression on the other server running Apache2, and the Appengine page requests started failing on key-error, indicating 'content-length' is not in th... | appengine, urlfetch, and the content-length header | I have a Google Appengine app requesting pages from another server using urllib2 POSTs. I recently enabled gzip compression on the other server running Apache2, and the Appengine page requests started failing on key-error, indicating 'content-length' is not in the headers.
I am not explicitly declaring gzip as an acce... | [
"According to this thread:\nhttp://groups.google.com/group/google-appengine-java/browse_thread/thread/5c5f2a7e2d2beadc?pli=1) \non an Appengine Java newsgroup, Google does generally set the 'Accept-Encoding: gzip' header on urlfetch requests, and then decompresses (ungzips) the input before handing the data to the ... | [
2
] | [] | [] | [
"apache2",
"google_app_engine",
"post",
"python"
] | stackoverflow_0001590844_apache2_google_app_engine_post_python.txt |
Q:
In python, how can I do a non-blocking system call?
In Python, is it possible to do a non-blocking system call without forking off a thread? i.e., can I avoid:
import thread
thread.start_new_thread(os.system,('cmd',))
A:
Use the subprocess module (Popen) and have the result written to a file. You can either "w... | In python, how can I do a non-blocking system call? | In Python, is it possible to do a non-blocking system call without forking off a thread? i.e., can I avoid:
import thread
thread.start_new_thread(os.system,('cmd',))
| [
"Use the subprocess module (Popen) and have the result written to a file. You can either \"wait\" for the subprocess to terminate or proceed with other business and poll for the result in the file etc.\n"
] | [
10
] | [] | [] | [
"python"
] | stackoverflow_0001613713_python.txt |
Q:
Daemon dies unexpectedly
I have a python script, which I daemonise using this code
def daemonise():
from os import fork, setsid, umask, dup2
from sys import stdin, stdout, stderr
if fork(): exit(0)
umask(0)
setsid()
if fork(): exit(... | Daemon dies unexpectedly | I have a python script, which I daemonise using this code
def daemonise():
from os import fork, setsid, umask, dup2
from sys import stdin, stdout, stderr
if fork(): exit(0)
umask(0)
setsid()
if fork(): exit(0)
stdout.flush()... | [
"You really should use python-daemon for this which is a library that implements PEP 3141 for a standard daemon process library. This way you will ensure that your application does all the right things for whichever type of UNIX it is running under. No need to reinvent the wheel.\n",
"Why are you silently swallo... | [
3,
1,
0
] | [] | [] | [
"daemon",
"python"
] | stackoverflow_0001599798_daemon_python.txt |
Q:
Is there easy way in python to extrapolate data points to the future?
I have a simple numpy array, for every date there is a data point. Something like this:
>>> import numpy as np
>>> from datetime import date
>>> from datetime import date
>>> x = np.array( [(date(2008,3,5), 4800 ), (date(2008,3,15), 4000 ), (dat... | Is there easy way in python to extrapolate data points to the future? | I have a simple numpy array, for every date there is a data point. Something like this:
>>> import numpy as np
>>> from datetime import date
>>> from datetime import date
>>> x = np.array( [(date(2008,3,5), 4800 ), (date(2008,3,15), 4000 ), (date(2008,3,
20), 3500 ), (date(2008,4,5), 3000 ) ] )
Is there easy way to ex... | [
"It's all too easy for extrapolation to generate garbage; try this. \nMany different extrapolations are of course possible;\nsome produce obvious garbage, some non-obvious garbage, many are ill-defined.\n\n\n\"\"\" extrapolate y,m,d data with scipy UnivariateSpline \"\"\"\nimport numpy as np\nfrom scipy.interpolate... | [
17,
4,
3,
1
] | [] | [] | [
"burndowncharts",
"interpolation",
"numpy",
"python",
"spline"
] | stackoverflow_0001599754_burndowncharts_interpolation_numpy_python_spline.txt |
Q:
How does `setup.py sdist` work?
I'm trying to make a source distribution of my project with setup.py sdist. I already have a functioning setup.py that I can install with. But when I do the sdist, all I get is another my_project folder inside my my_project folder, a MANIFEST file I have no interest in, and a zip fi... | How does `setup.py sdist` work? | I'm trying to make a source distribution of my project with setup.py sdist. I already have a functioning setup.py that I can install with. But when I do the sdist, all I get is another my_project folder inside my my_project folder, a MANIFEST file I have no interest in, and a zip file which contains two text files, and... | [
"Tarek Ziade explained this, and related software packaging tools, in this article (broken original link) called Writing a Package in Python.\nBasically, it creates a simple package by\ncreating a release tree where everything needed to run the package is copied. This tree is then archived in one or many archived f... | [
10,
8
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0001614086_distutils_python.txt |
Q:
How do I add text describing the code into a Python source file?
When writing code in Python, how can you write something next to it that explains what the code is doing, but which doesn't affect the code?
A:
I think you're talking about comments?
There are plain comments, which start with #:
return sys.stdin.re... | How do I add text describing the code into a Python source file? | When writing code in Python, how can you write something next to it that explains what the code is doing, but which doesn't affect the code?
| [
"I think you're talking about comments?\nThere are plain comments, which start with #:\nreturn sys.stdin.readline() # This is a comment\n\nAnd also Docstrings, which document modules, classes, methods and functions:\ndef getline():\n \"\"\"This is a docstring\"\"\"\n return sys.stdin.readline()\n\nUnlik... | [
17,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0001614190_python.txt |
Q:
restore registry from file
I am trying to migrate microsoft office settings from one system to other system by backing up office registry and restoring it on the destination machine using Python.I am able to do the saving part,but on trying to restore the existing settings in destination machine to overwrite exist... | restore registry from file | I am trying to migrate microsoft office settings from one system to other system by backing up office registry and restoring it on the destination machine using Python.I am able to do the saving part,but on trying to restore the existing settings in destination machine to overwrite existing office settings,i am getting... | [
"The registry system has a built-in method for updating registry keys by creating and importing a .reg text file. I suggest that you try to write your changes to a .reg file and import that.\nAlso, you don't mention what Windows version you are using. In the newer versions, the permission system is rather more comp... | [
1
] | [] | [] | [
"python",
"registry"
] | stackoverflow_0001074467_python_registry.txt |
Q:
Pythoncard item setsize
Below is the base class of my pythoncard application:
class MyBackground(model.Background):
def on_initialize(self, event):
# if you have any initialization
# including sizer setup, do it here
self.setLayout()
def setLayout(self):
sizer1 = wx.BoxSiz... | Pythoncard item setsize | Below is the base class of my pythoncard application:
class MyBackground(model.Background):
def on_initialize(self, event):
# if you have any initialization
# including sizer setup, do it here
self.setLayout()
def setLayout(self):
sizer1 = wx.BoxSizer(wx.VERTICAL) # main size... | [
"Why 80,21?\nYou told it to make the item 732,220 and that's what it did.\nOr is there something else that you didn't tell us?\n"
] | [
0
] | [] | [] | [
"python",
"pythoncard",
"wxpython"
] | stackoverflow_0000441815_python_pythoncard_wxpython.txt |
Q:
Dice Roller using Tkinter
Thank you to everybody who helped answer my last question:
My friend took the code, and has attempted to use Tkinter to make a box that we could use to make things nicer-looking, but he has been unable to integrate the dice roller from the last question and the Tkinter. Any help or ideas... | Dice Roller using Tkinter | Thank you to everybody who helped answer my last question:
My friend took the code, and has attempted to use Tkinter to make a box that we could use to make things nicer-looking, but he has been unable to integrate the dice roller from the last question and the Tkinter. Any help or ideas in getting the dice roller int... | [
"Because half the fun is trying to work it out yourself I'll give you a few hints instead of a complete program.\nYou should store the variables for your input entries, so you can use them later to get the values out again, but don't do this:\nentry = Entry(root,bg = 'white').pack(padx = 10, pady = 10)\n\nThat does... | [
2
] | [] | [] | [
"python",
"random",
"tkinter"
] | stackoverflow_0001614244_python_random_tkinter.txt |
Q:
How does indexing a list with a tuple work?
I am learning Python and came across this example:
W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6))
b = ['a','b','c','d','e','f','g','h','i']
for row in W:
print b[row[0]], b[row[1]], b[row[2]]
which prints:
a b c
d e f
a e i
c e g
I am trying to figure out why!
I get that for... | How does indexing a list with a tuple work? | I am learning Python and came across this example:
W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6))
b = ['a','b','c','d','e','f','g','h','i']
for row in W:
print b[row[0]], b[row[1]], b[row[2]]
which prints:
a b c
d e f
a e i
c e g
I am trying to figure out why!
I get that for example the first time thru the expanded version... | [
"In shot, the (0,1,2) does nothing. Its a tuple and can be indexed just like a list, so b[(0,1,2)[0]] becomes b[0] since (0,1,2)[0] == 0.\nIn the first step Python does b[row[0]] → b[(0,1,2)[0]] → b[0] → 'a' \nBtw, to get multiple items from a sequence at once you can use a operator:\nfrom operator import itemgette... | [
4,
4,
0,
0,
0,
0
] | [] | [] | [
"indexing",
"list",
"python",
"tuples"
] | stackoverflow_0001614613_indexing_list_python_tuples.txt |
Q:
Copying values from a dictionary into an object in Python
I have a dictionary that I would like to iterate through and copy the key-value pairs into an object in Python. The dictionary is POST, and the object is a Model (in Django, perhaps Django has better way to do this).
In PHP, I'd be able to use variable ass... | Copying values from a dictionary into an object in Python | I have a dictionary that I would like to iterate through and copy the key-value pairs into an object in Python. The dictionary is POST, and the object is a Model (in Django, perhaps Django has better way to do this).
In PHP, I'd be able to use variable assignments:
foreach($post as $key => $value) {
$my_model->$ke... | [
"for key, value in post.iteritems():\n setattr(my_model, key, value)\n\n",
"You can use setattr, but it's likely the wrong way to do it in your context. You should look at Django's ModelForms documentation first.\n"
] | [
5,
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001614804_django_python.txt |
Q:
How do I do 'from foo import *' using Python's __import__ function
I want to replace settings.py in my Django system with a module implemented as a directory settings containing __init__.py. This will try to import a module named after the server, thus allowing for per-server settings.
If I don't know the name of ... | How do I do 'from foo import *' using Python's __import__ function | I want to replace settings.py in my Django system with a module implemented as a directory settings containing __init__.py. This will try to import a module named after the server, thus allowing for per-server settings.
If I don't know the name of a module before I import it then I can't use the import keyword but must... | [
"For similar situation where based on lang setting I import different messages in messages.py module it is something like\n# set values in current namespace\nfor name in vars(messages):\n v = getattr(messages, name)\n globals()[name] = v\n\nBtw why do you want to create a package for settings.py? whatever you... | [
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0001614884_import_python.txt |
Q:
In Python, can I print 3 lists in order by index number?
So I have three lists:
['this', 'is', 'the', 'first', 'list']
[1, 2, 3, 4, 5]
[0.01, 0.2, 0.3, 0.04, 0.05]
Is there a way that would allow me to print the values in these lists in order by index?
e.g.
this, 1, 0.01 (all items at list[0])
is, 2, 0.2 (all it... | In Python, can I print 3 lists in order by index number? | So I have three lists:
['this', 'is', 'the', 'first', 'list']
[1, 2, 3, 4, 5]
[0.01, 0.2, 0.3, 0.04, 0.05]
Is there a way that would allow me to print the values in these lists in order by index?
e.g.
this, 1, 0.01 (all items at list[0])
is, 2, 0.2 (all items at list[1])
the, 3, 0.3 (all items at list[2])
first, 4, 0... | [
"What you are probably looking for is called zip:\n>>> x = ['this', 'is', 'the', 'first', 'list']\n>>> y = [1, 2, 3, 4, 5]\n>>> z = [0.01, 0.2, 0.3, 0.04, 0.05]\n>>> zip(x,y,z)\n[('this', 1, 0.01), ('is', 2, 0.20000000000000001), ('the', 3, 0.29999999999999999), ('first', 4, 0.040000000000000001), ('list', 5, 0.050... | [
9,
3,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001615289_list_python.txt |
Q:
How to script a google search without google license key?
I'm looking at 'pygoogle' python library for google search, call from my python script. But google doesn't give out license key anymore, and looks like pygoogle needs license key to work.
Does anyone have suggestions of libraries to use for scripting web se... | How to script a google search without google license key? | I'm looking at 'pygoogle' python library for google search, call from my python script. But google doesn't give out license key anymore, and looks like pygoogle needs license key to work.
Does anyone have suggestions of libraries to use for scripting web searches? Languages doesn't matter. It can be in python, perl, li... | [
"They don't give out keys for the SOAP API anymore, because that's deprecated. But you can use their AJAX API, which is now the preferred interface. You can get a developer key here.\n",
"Your question made me look. \n\nYahoo! now offers a new search service called BOSS which looks very interesting.\nMicrosoft of... | [
10,
0,
0
] | [] | [] | [
"api",
"perl",
"python",
"search"
] | stackoverflow_0001608442_api_perl_python_search.txt |
Q:
Python dictionary creation error
I am trying to create a Python dictionary from a stored list. This first method works
>>> myList = []
>>> myList.append('Prop1')
>>> myList.append('Prop2')
>>> myDict = dict([myList])
However, the following method does not work
>>> myList2 = ['Prop1','Prop2','Prop3','Prop4']
>>> m... | Python dictionary creation error | I am trying to create a Python dictionary from a stored list. This first method works
>>> myList = []
>>> myList.append('Prop1')
>>> myList.append('Prop2')
>>> myDict = dict([myList])
However, the following method does not work
>>> myList2 = ['Prop1','Prop2','Prop3','Prop4']
>>> myDict2 = dict([myList2])
ValueError: d... | [
"You're doing it wrong.\nThe dict() constructor doesn't take a list of items (much less a list containing a single list of items), it takes an iterable of 2-element iterables. So if you changed your code to be:\nmyList = []\nmyList.append([\"mykey1\", \"myvalue1\"])\nmyList.append([\"mykey2\", \"myvalue2\"])\nmyDi... | [
13
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0001615501_python_python_2.5.txt |
Q:
Engines built on pygame
I am currently writing an RTS for pygame and have written a number of modules on top of pygame for common things, such as efficient collision detection, a state system and more featured sprites. Now while writing games, except for Rect and Surface, I barely write any calls to Pygame itsel... | Engines built on pygame | I am currently writing an RTS for pygame and have written a number of modules on top of pygame for common things, such as efficient collision detection, a state system and more featured sprites. Now while writing games, except for Rect and Surface, I barely write any calls to Pygame itself.
When Googling around on th... | [
"Well Pygame itself is essentially a Python wrapper to SDL calls. I think in essence you would just be wrapping a wrapper.\nYou could always build your own adapter API, but what in particular about Pygame's API do you dislike so much that you feel you need to separate it from your code?\nI think your generic method... | [
6
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0001615693_pygame_python.txt |
Q:
Setting an object in the Django cache API fails due to pickle error
I'm trying to manually set an object in the Django cache API but it fails (i think due to pickling?)
The object is given to me by a third party, my code is:
def index(request, template_name="mytemplate.htm"):
user_list = cache.get("user_list_d... | Setting an object in the Django cache API fails due to pickle error | I'm trying to manually set an object in the Django cache API but it fails (i think due to pickling?)
The object is given to me by a third party, my code is:
def index(request, template_name="mytemplate.htm"):
user_list = cache.get("user_list_ds")
if user_list is None:
# this is the expensive bit I'm... | [
"It appears that you need to install ElementTree, because the pickle operation tries and fails to import the etree module.\nUPDATE: Looking at it further, are you actually trying to cache document nodes? If you're trying to cache the data from the node, you probably need to do some processing of the value you're cu... | [
2
] | [] | [] | [
"django",
"memcached",
"pickle",
"python"
] | stackoverflow_0001615721_django_memcached_pickle_python.txt |
Q:
How to programmatically change urls of images in word documents
I have a set of word documents that contains a lot of non-embedded images in them. The url that the images point to no longer exist. I would like to programmatically change the domain name of the url to something else. How can I go about doing this in... | How to programmatically change urls of images in word documents | I have a set of word documents that contains a lot of non-embedded images in them. The url that the images point to no longer exist. I would like to programmatically change the domain name of the url to something else. How can I go about doing this in Java or Python ?
| [
"This is the sort of thing that VBA is for:\nSub HlinkChanger()\nDim oRange As Word.Range\nDim oField As Field\nDim link As Variant\nWith ActiveDocument\n.Range.AutoFormat\nFor Each oRange In .StoryRanges\n For Each oFld In oRange.Fields\n If oFld.Type = wdFieldHyperlink Then\n For ... | [
1,
0,
0,
0
] | [] | [] | [
"image",
"java",
"ms_word",
"python"
] | stackoverflow_0000428308_image_java_ms_word_python.txt |
Q:
Resources (resx) with Python
Do you know of any Python module for resources (resx files) manipulation?
P.S.: I know I could write a custom wrapper on top of base XML processor available, I'm just checking out before going to hack my own code...
A:
This question Resources (resx) maintenance in big projects has an... | Resources (resx) with Python | Do you know of any Python module for resources (resx files) manipulation?
P.S.: I know I could write a custom wrapper on top of base XML processor available, I'm just checking out before going to hack my own code...
| [
"This question Resources (resx) maintenance in big projects has an answer pointing to some .NET source code for a tool to manage RESX resources. Since IronPython can interface with any existing .NET objects written in C#, you should be able to adapt that RESX tool source code into an object that you can then use in... | [
1
] | [] | [] | [
"module",
"python",
"resources",
"resx"
] | stackoverflow_0000812644_module_python_resources_resx.txt |
Q:
copy worksheet from one spreadsheet to another
Is it possible to copy spreadsheets with gdata API or worksheets from one spreadsheet to other? For now i copy all cells from one worksheet to another. One cell per request. It is too slow. I read about "cell batch processing" and write this code:
src_key = 'rFQqEnFW... | copy worksheet from one spreadsheet to another | Is it possible to copy spreadsheets with gdata API or worksheets from one spreadsheet to other? For now i copy all cells from one worksheet to another. One cell per request. It is too slow. I read about "cell batch processing" and write this code:
src_key = 'rFQqEnFWuR6qoU2HEfdVuTw'; dst_key = 'rPCVJ80MHt7K2EVlXNqytL... | [
"You probably should be using a cell range query to get a whole row at a time, then inserting rows in the target spreadsheet.\n"
] | [
1
] | [] | [] | [
"gdata",
"gdata_api",
"google_docs",
"python"
] | stackoverflow_0000944419_gdata_gdata_api_google_docs_python.txt |
Q:
Running commands from a file in PDB
I would like to run a set of python commands from a file in the PDB debugger.
Related to this, can I set up a file that is automatically run when PDB starts?
A:
make a subclass of pdb.Pdb and put a call to your extra stuff in the __init__
alternatively
pdb.Pdb() looks for a .... | Running commands from a file in PDB | I would like to run a set of python commands from a file in the PDB debugger.
Related to this, can I set up a file that is automatically run when PDB starts?
| [
"make a subclass of pdb.Pdb and put a call to your extra stuff in the __init__\nalternatively\npdb.Pdb() looks for a .pdbrc file, so you may be able to put your stuff in there\n # Read $HOME/.pdbrc and ./.pdbrc\n self.rcLines = []\n if 'HOME' in os.environ:\n envHome = os.environ['HOME']\n tr... | [
1
] | [] | [] | [
"debugging",
"pdb",
"python"
] | stackoverflow_0001614983_debugging_pdb_python.txt |
Q:
Navigating in the python terminal
I want a 64-bit python interpreter on my Mac so I had to rebuild from source. However, with my own custom build interpreter I run into issues when I try to navigate when I run the interpreter from inside a shell. Typing python into the bash shell results in the familiar:
Python 2.... | Navigating in the python terminal | I want a 64-bit python interpreter on my Mac so I had to rebuild from source. However, with my own custom build interpreter I run into issues when I try to navigate when I run the interpreter from inside a shell. Typing python into the bash shell results in the familiar:
Python 2.6.3 (r263:75183, Oct 23 2009, 14:23:25)... | [
"Sounds like your custom build didn't include readline. Should be a simple config change and rebuild, check here for more info.\n",
"Installing the GNU readline library from here, and rebuilding python fixes the problem.\n"
] | [
6,
0
] | [] | [] | [
"navigation",
"python",
"shell"
] | stackoverflow_0001616321_navigation_python_shell.txt |
Q:
Trying to position subplots next to each other
I am trying to position two subplots next to each other (as opposed to under each other). I am expecting to see [sp1] [sp2]
Instead, only the second plot [sp2] is getting displayed.
from matplotlib import pyplot
x = [0, 1, 2]
pyplot.figure()
# sp1
pyplot.subplot(21... | Trying to position subplots next to each other | I am trying to position two subplots next to each other (as opposed to under each other). I am expecting to see [sp1] [sp2]
Instead, only the second plot [sp2] is getting displayed.
from matplotlib import pyplot
x = [0, 1, 2]
pyplot.figure()
# sp1
pyplot.subplot(211)
pyplot.bar(x, x)
# sp2
pyplot.subplot(221)
pyplo... | [
"The 3 numbers are rows, columns, and plot #. What you're doing is respecifying the number of columns in your second call to subplot, which in turn changes the configuration and causes pyplot to start over.\nWhat you mean is:\nsubplot(121) # 1 row, 2 columns, Plot 1\n...\nsubplot(122) # 1 row, 2 columns, Plot 2\... | [
12,
5
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0001616427_matplotlib_python.txt |
Q:
writing a font viewer - getting font properties, loading ttf dynamically
I'm trying to write a font viewer for TrueType / OpenType fonts with VB6 / VB5 code (under Windows).
it is surprisingly difficult:
1) in VB / winAPI, i did not find how to extract the font's name, or font properties in general.
2) i can insta... | writing a font viewer - getting font properties, loading ttf dynamically | I'm trying to write a font viewer for TrueType / OpenType fonts with VB6 / VB5 code (under Windows).
it is surprisingly difficult:
1) in VB / winAPI, i did not find how to extract the font's name, or font properties in general.
2) i can install the font (using AddFontResource API function), but then have to uninstall i... | [
"You could use the FreeType library.\n",
"It indeed is. I have faced the same problem myself (see my question). I ended up writing my own parser though because I needed to detect if the font was corrupt or not. There is a AddFontMemResourceEx function which:\n\nWhen the function succeeds, the caller of this funct... | [
1,
0
] | [] | [] | [
"python",
"truetype",
"vb6"
] | stackoverflow_0001616505_python_truetype_vb6.txt |
Q:
Python POST XML not executed
The Headers post fine but the associated XML seems to be taken as string data only, XML is not processed.
XML string is of the form:
params = '''<?xml version="1.0" encoding"="UTF-8 "?>
<MainRequest>
<requestEnvelope><errorLanguage>en_US</errorLanguage>
</requestEnvelope></MainRequest>... | Python POST XML not executed | The Headers post fine but the associated XML seems to be taken as string data only, XML is not processed.
XML string is of the form:
params = '''<?xml version="1.0" encoding"="UTF-8 "?>
<MainRequest>
<requestEnvelope><errorLanguage>en_US</errorLanguage>
</requestEnvelope></MainRequest>'''
The POST is of the form:
enc_... | [
"Are you adding a content-type header? To tell the server your request is XML, add the following before sending the request:\nrequest.add_header('Content-Type', 'text/xml')\n\n",
"Take out the \"urllib.quote()\" call. That's what created the string which starts \"%3C%3Fxml\". If you want to POST XML then just se... | [
2,
0
] | [] | [] | [
"python",
"xmlhttprequest"
] | stackoverflow_0001615115_python_xmlhttprequest.txt |
Q:
server side marker clustering in django
I am creating a mashup in django and google maps and I am wondering if there is a way of clustering markers on the server side using django/python.
A:
I have implemented server side clustering in Django on my real estate/rentals site; I explain it here.
A:
I came up wit... | server side marker clustering in django | I am creating a mashup in django and google maps and I am wondering if there is a way of clustering markers on the server side using django/python.
| [
"I have implemented server side clustering in Django on my real estate/rentals site; I explain it here.\n",
"I came up with the code below to figure out if one marker is close enough to another for clustering - close if two cluster icons start overlapping. Works for the whole world map for all zoom levels.\nThe p... | [
1,
0
] | [] | [] | [
"django",
"google_maps",
"python"
] | stackoverflow_0001131400_django_google_maps_python.txt |
Q:
Python strategy for extracting text from malformed html pages
I'm trying to extract text from arbitrary html pages. Some of the pages (which I have no control over) have malformed html or scripts which make this difficult. Also I'm on a shared hosting environment, so I can install any python lib, but I can't just ... | Python strategy for extracting text from malformed html pages | I'm trying to extract text from arbitrary html pages. Some of the pages (which I have no control over) have malformed html or scripts which make this difficult. Also I'm on a shared hosting environment, so I can install any python lib, but I can't just install anything I want on the server.
pyparsing and html2text.py ... | [
"Try not to laugh, but:\nclass TextFormatter:\n def __init__(self,lynx='/usr/bin/lynx'):\n self.lynx = lynx\n\n def html2text(self, unicode_html_source):\n \"Expects unicode; returns unicode\"\n return Popen([self.lynx, \n '-assume-charset=UTF-8', \n ... | [
5,
0,
0
] | [] | [] | [
"html",
"html_content_extraction",
"python",
"text"
] | stackoverflow_0001615072_html_html_content_extraction_python_text.txt |
Q:
Are there any problems with this symlink traversal code for Windows?
In my efforts to resolve Python issue 1578269, I've been working on trying to resolve the target of a symlink in a robust way. I started by using GetFinalPathNameByHandle as recommended here on stackoverflow and by Microsoft, but it turns out tha... | Are there any problems with this symlink traversal code for Windows? | In my efforts to resolve Python issue 1578269, I've been working on trying to resolve the target of a symlink in a robust way. I started by using GetFinalPathNameByHandle as recommended here on stackoverflow and by Microsoft, but it turns out that technique fails when the target is in use (such as with pagefile.sys).
S... | [
"Unfortunately I can't test with Vista until next week, but GetFinalPathNameByHandle should work, even for files in use - what's the problem you noticed?\nIn your code above, you forget to close the file handle.\n"
] | [
0
] | [] | [] | [
"filesystems",
"python",
"symlink_traversal",
"winapi",
"windows"
] | stackoverflow_0001616245_filesystems_python_symlink_traversal_winapi_windows.txt |
Q:
Using Python, how do I get an array of file info objects, based on a search of a file system?
Currently I have a bash script which runs the find command, like so:
find /storage/disk-1/Media/Video/TV -name *.avi -mtime -7
This gets a list of TV shows that were added to my system in the last 7 days. I then go on to... | Using Python, how do I get an array of file info objects, based on a search of a file system? | Currently I have a bash script which runs the find command, like so:
find /storage/disk-1/Media/Video/TV -name *.avi -mtime -7
This gets a list of TV shows that were added to my system in the last 7 days. I then go on to create some symbolic links so I can get to my newest TV shows.
I'm looking to re-code this in Pyth... | [
"import os, time\n\nallfiles = []\nnow = time.time()\n\n# walk will return triples (current dir, list of subdirs, list of regular files)\n# file names are relative to dir at first\nfor dir, subdirs, files in os.walk(\"/storage/disk-1/Media/Video/TV\"):\n for f in files:\n if not f.endswith(\".avi\"):\n ... | [
3,
2,
1
] | [] | [] | [
"fileinfo",
"find",
"python"
] | stackoverflow_0001617666_fileinfo_find_python.txt |
Q:
Vim Python omni-completion failing to work on system modules
I'm noticing that even for system modules, code completion doesn't work too well.
For example, if I have a simple file that does:
import re
p = re.compile(pattern)
m = p.search(line)
If I type p., I don't get completion for methods I'd expect to see (I ... | Vim Python omni-completion failing to work on system modules | I'm noticing that even for system modules, code completion doesn't work too well.
For example, if I have a simple file that does:
import re
p = re.compile(pattern)
m = p.search(line)
If I type p., I don't get completion for methods I'd expect to see (I don't see search() for example, but I do see others, such as func_... | [
"Completion for this kind of things is tricky, because it would need to execute the actual code to work.\nFor example p.search() could return None or a MatchObject, depending on the data that is passed to it.\nThis is why omni-completion does not work here, and probably never will. It works for things that can be s... | [
2,
0
] | [] | [] | [
"omnicomplete",
"python",
"vim"
] | stackoverflow_0001617415_omnicomplete_python_vim.txt |
Q:
How do I validate a Django form containing a file on App Engine with google-app-engine-django?
I have a model and form like so:
class Image(BaseModel):
original = db.BlobProperty()
class ImageForm(ModelForm):
class Meta:
model = Image
I do the following in my view:
form = ImageForm(request.POST, request.... | How do I validate a Django form containing a file on App Engine with google-app-engine-django? | I have a model and form like so:
class Image(BaseModel):
original = db.BlobProperty()
class ImageForm(ModelForm):
class Meta:
model = Image
I do the following in my view:
form = ImageForm(request.POST, request.FILES, instance=image)
if form.is_valid():
And I get:
AttributeError at /image/add/
'NoneType' obj... | [
"It doesn't work with default django version. And bug is reported. \nBTW, default installation raise other exeption. So possible problem with other part of your code.\n",
"The docs for the constructor say:\n\nfiles: dict of file upload values;\n Django 0.97 or later only\n\nAre you using Django 0.97? The bundled... | [
4,
0
] | [] | [] | [
"django",
"django_forms",
"google_app_engine",
"python",
"validation"
] | stackoverflow_0001573913_django_django_forms_google_app_engine_python_validation.txt |
Q:
What's wrong with this `setup.py`?
I've been having problems withe getting setup.py to do the sdist thing correctly. I boiled it down to this. I have the following directory structure:
my_package\
my_subpackage\
__init__.py
deep_module.py
__init__.py
module.py
setup.py
And here's w... | What's wrong with this `setup.py`? | I've been having problems withe getting setup.py to do the sdist thing correctly. I boiled it down to this. I have the following directory structure:
my_package\
my_subpackage\
__init__.py
deep_module.py
__init__.py
module.py
setup.py
And here's what I have in setup.py:
#!/usr/bin/env p... | [
"The problem is well explained here:\n\nSetuptools has many silent failure\n modes. One of them is failure to\n include all files in sdist release\n (well not exactly a failure, you could\n RTFM, but the default behavior is\n unexpected). This post will serve as a\n google-yourself-answer for this\n problem,... | [
6,
4
] | [] | [] | [
"distribution",
"distutils",
"python"
] | stackoverflow_0001618674_distribution_distutils_python.txt |
Q:
Mapping complex python objects to django models
I have a certain class structure in my app, that currently utilizes django for presentation. I was not using the model layer at all, - the database interaction routines are hand-written.
I am, however, considering the possibility of actually using django to its full... | Mapping complex python objects to django models | I have a certain class structure in my app, that currently utilizes django for presentation. I was not using the model layer at all, - the database interaction routines are hand-written.
I am, however, considering the possibility of actually using django to its full potential and actually using the database-abstractio... | [
"It somewhat depends on what specific behavior you want to encode. In most cases, you should try to put per-object behavior into the model class. It's a regular Python class, after all, so you can give it any methods you desire. You do need to account for the persistent nature, of course, e.g. by avoiding additiona... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001618773_django_python.txt |
Q:
how to reduce size of exe using py2exe
I developed a small program using python and wxwidgets. It is a very simple program that uses only a mini frame to display some information when needed, and the rest of the time it shows nothing, only an icon in the taskbar.
When I build the exe using py2exe (single file exe ... | how to reduce size of exe using py2exe | I developed a small program using python and wxwidgets. It is a very simple program that uses only a mini frame to display some information when needed, and the rest of the time it shows nothing, only an icon in the taskbar.
When I build the exe using py2exe (single file exe mode, optimized), I get a 6MB size file!
I t... | [
"The fact that your program is simple does not mean that it's small. Your program has many dependency through the wxWidget stack and 6 Mb does not look that big with all this in mind.\nBut, back to the question. To shrink a py2exe generated program, you can do a few obvious things:\n\nDistribute less stuff: it seem... | [
5,
3
] | [] | [] | [
"executable",
"filesize",
"py2exe",
"python"
] | stackoverflow_0001617868_executable_filesize_py2exe_python.txt |
Q:
regular expression in python
I am sorry if this question is too simple but I can't seem to reason this out. I want to parse a string. I want to extract the words between 'The final score is: ' and '.'. In other words, if i have a string "The final score is: 25." I want it to extract 25. I don't know how to do this... | regular expression in python | I am sorry if this question is too simple but I can't seem to reason this out. I want to parse a string. I want to extract the words between 'The final score is: ' and '.'. In other words, if i have a string "The final score is: 25." I want it to extract 25. I don't know how to do this. Should I use match? or split??
T... | [
"If you know your information is always going to be formatted like that then you can simply use split:\ns = \"The final score is: 25\"\nscore = s.split(':')[1].strip()\n\nThis will result in score being 25. I use .strip() at the end to remove any whitespace as a safety measure.\n",
"You're talking about \"captur... | [
3,
2,
2
] | [
"you don't need a regex to do this... do the split on \":\" , then get the last element. OR , just use string slicing \n>>> \"The final score is: 25.\"[-3:-1]\n'25'\n\n>>> s.split(\":\")[-1].strip() #use -1 to always get the last element\n'25'\n\n"
] | [
-1
] | [
"python",
"regex",
"string"
] | stackoverflow_0001617808_python_regex_string.txt |
Q:
Openoffice3.1 pyuno confusing errors
I'm trying to get the sample and other sample codes i find for pyuno running with openoffice 3.1.1 and python 2.5 with no luck.
Unfortunately, pyuno does not give any clues about what goes wrong.
In [1]: import uno
In [2]: local = uno.getComponentContext()
In [3]: resolver = ... | Openoffice3.1 pyuno confusing errors | I'm trying to get the sample and other sample codes i find for pyuno running with openoffice 3.1.1 and python 2.5 with no luck.
Unfortunately, pyuno does not give any clues about what goes wrong.
In [1]: import uno
In [2]: local = uno.getComponentContext()
In [3]: resolver = local.ServiceManager.createInstanceWithCo... | [
"In [1]: import uno\nIn [2]: local = uno.getComponentContext()\nIn [3]: resolver = local.ServiceManager.createInstanceWithContext(\"com.sun.star.bridge.UnoUrlResolver\", local)\nOOP gone wrong, imho. i know its OT, but i tried getting uno to work before, and gave up. this is pure Steve Yegge Prose (read up on http:... | [
5
] | [] | [] | [
"openoffice.org",
"python",
"pyuno",
"uno"
] | stackoverflow_0001618833_openoffice.org_python_pyuno_uno.txt |
Q:
Python + SVN + Windows/Mac = Invalid syntax?
I'm pretty sure the following error is related to the fact that I'm sharing code via SVN with a colleague that is using a Windows system.
Myself, I use Python on Mac, editing with TextMate.
#!/usr/bin/python
import os
from google.appengine.api import users
from googl... | Python + SVN + Windows/Mac = Invalid syntax? | I'm pretty sure the following error is related to the fact that I'm sharing code via SVN with a colleague that is using a Windows system.
Myself, I use Python on Mac, editing with TextMate.
#!/usr/bin/python
import os
from google.appengine.api import users
from google.appengine.ext import webapp
...
When running th... | [
"While Python shouldn't care about line endings, your Mac won't like having a CRLF line ending on the first line, so this may be your problem.\n0000000 # ! / u s r / b i n / p y t h o n \\r \\n\n ^^\n\nSVN can be told to translate line endings by setting the svn:eol-style pr... | [
4,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"operating_system",
"python",
"svn",
"textmate"
] | stackoverflow_0001619229_google_app_engine_operating_system_python_svn_textmate.txt |
Q:
Grouping on an attribute using itertools.groupby
I have a list of instances of the class 'Chromosome'.
The list is sorted on the Chromosome attribute 'equation'
I now want to remove instances where the attribute 'equation' is the same, leaving only one.
I don't know how to pass the key, ie the ?, so that it groups... | Grouping on an attribute using itertools.groupby | I have a list of instances of the class 'Chromosome'.
The list is sorted on the Chromosome attribute 'equation'
I now want to remove instances where the attribute 'equation' is the same, leaving only one.
I don't know how to pass the key, ie the ?, so that it groups on 'equation'.
b = [a for a,b in groupby(list, ?)]
| [
"import operator\n\n[a for a, b in groupby(thelist, operator.attrgetter('equation')]\n\nBtw, don't use builtin type names (such as list, file, etc) for your own identifiers, it's a confusing and best-avoided practice that will eventually byte you with peculiar bugs unless you wean yourself off it (i.e one day you'l... | [
7,
3
] | [] | [] | [
"python"
] | stackoverflow_0001619227_python.txt |
Q:
python locale currency and negative numbers
Why?
C:\path\>manage.py shell
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.getlocale()
('Spanish_Colombia', '1252')
>>> loca... | python locale currency and negative numbers | Why?
C:\path\>manage.py shell
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.getlocale()
('Spanish_Colombia', '1252')
>>> locale.currency( 1885, grouping=True )
'$ 1.885,00'
>... | [
"In your locale, surrounding a number with brackets indicates it's a negative number. Check this in Control Panel/Regional and Language settings, Python's probably picking it up from there.\n",
"Parentheses around a number to indicate it's a debit (i.e. negative), not a credit (positive), are a common convention ... | [
2,
2
] | [] | [] | [
"currency",
"django",
"locale",
"python"
] | stackoverflow_0001618975_currency_django_locale_python.txt |
Q:
Python zlib output, how to recover out of mysql utf-8 table?
In python, I compressed a string using zlib, and then inserted it into a mysql column that is of type blob, using the utf-8 encoding. The string comes back as utf-8, but it's not clear how to get it back into a format where I can decompress it. Here is s... | Python zlib output, how to recover out of mysql utf-8 table? | In python, I compressed a string using zlib, and then inserted it into a mysql column that is of type blob, using the utf-8 encoding. The string comes back as utf-8, but it's not clear how to get it back into a format where I can decompress it. Here is some pseduo-output:
valueInserted = zlib.compress('a')
= 'x\x9cK\x0... | [
"Unicode is designed to be compatible with latin-1, so try:\n>>> import zlib\n>>> u = zlib.compress(\"test\").decode('latin1')\n>>> u\nu'x\\x9c+I-.\\x01\\x00\\x04]\\x01\\xc1'\n\nAnd then\n>>> zlib.decompress(u.encode('latin1'))\n'test'\n\nEDIT: Fixed typo, latin-1 isn't designed to be compatible with unicode, it's ... | [
7,
2,
1
] | [] | [] | [
"mysql",
"python",
"unicode",
"utf_8",
"zlib"
] | stackoverflow_0001618926_mysql_python_unicode_utf_8_zlib.txt |
Q:
with python's win32com and parsing html problem
I'm new to python. I want to extract some text from the CNN website.
I want to use python win32com module.
EDIT: on [why win32com]
Because of javascript in website... I thought of using win32com; I have looked for other solution but without success in regard to my re... | with python's win32com and parsing html problem | I'm new to python. I want to extract some text from the CNN website.
I want to use python win32com module.
EDIT: on [why win32com]
Because of javascript in website... I thought of using win32com; I have looked for other solution but without success in regard to my requirement. In fact, I wanted to use mechanize or a si... | [
"Are you trying to parse some text on cnn's web site?\nYou can get the page with\nimport urllib\nf = urllib.urlopen('http://www.cnn.com')\npage = f.read()\nf.close()\n\nYou can then use BeautifulSoup to find whatever it is you are looking for on page.\nWhy win32com, dispatch, etc.?\n"
] | [
1
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0001619489_parsing_python.txt |
Q:
Using Python Regular Expression in Django
I have an web address:
http://www.example.com/org/companyA
I want to be able to pass CompanyA to a view using regular expressions.
This is what I have:
(r'^org/?P<company_name>\w+/$',"orgman.views.orgman")
and it doesn't match.
Ideally all URL's that look like example.c... | Using Python Regular Expression in Django | I have an web address:
http://www.example.com/org/companyA
I want to be able to pass CompanyA to a view using regular expressions.
This is what I have:
(r'^org/?P<company_name>\w+/$',"orgman.views.orgman")
and it doesn't match.
Ideally all URL's that look like example.com/org/X would pass x to the view.
Thanks in ad... | [
"You need to wrap the group name in parentheses. The syntax for named groups is (?P<name>regex), not ?P<name>regex. Also, if you don't want to require a trailing slash, you should make it optional.\nIt's easy to test regular expression matching with the Python interpreter, for example:\n>>> import re\n>>> re.match... | [
20,
2,
1
] | [] | [] | [
"django",
"django_urls",
"python",
"regex"
] | stackoverflow_0001619554_django_django_urls_python_regex.txt |
Q:
How to import win32api
I'm trying to use some python-2.1 code to control another program (ArcGIS). The version of python I am using is 2.5. I am getting the following error message when I run the code.
<type'exceptions.ImportError'>: No module named win32api
Failed to execute (polyline2geonetwork2).
I tried insta... | How to import win32api | I'm trying to use some python-2.1 code to control another program (ArcGIS). The version of python I am using is 2.5. I am getting the following error message when I run the code.
<type'exceptions.ImportError'>: No module named win32api
Failed to execute (polyline2geonetwork2).
I tried installing pywin32-214.win32-py2.... | [
"Your sys.path is \n['C:\\\\Documents and Settings\\\\david\\\\My Documents\\\\GIS_References\\\\public\\\\funconn_public', 'C:\\\\Python25\\\\Lib\\\\idlelib', 'C:\\\\Program Files\\\\ArcGIS\\\\bin', 'C:\\\\WINDOWS\\\\system32\\\\python25.zip', 'C:\\\\Python25\\\\DLLs', 'C:\\\\Python25\\\\lib', 'C:\\\\Python25\\\\l... | [
2,
1
] | [] | [] | [
"import",
"python",
"python_2.5"
] | stackoverflow_0001619469_import_python_python_2.5.txt |
Q:
Extracting decimals from a number in Python
I am writing a function to extract decimals from a number. Ignore the exception and its syntax, I am working on 2.5.2 (default Leopard version). My function does not yet handle 0's. My issue is, the function produces random errors with certain numbers, and I don't unders... | Extracting decimals from a number in Python | I am writing a function to extract decimals from a number. Ignore the exception and its syntax, I am working on 2.5.2 (default Leopard version). My function does not yet handle 0's. My issue is, the function produces random errors with certain numbers, and I don't understand the reason. I will post an error readout aft... | [
"The problem is that (binary) floating point numbers aren't precisely representable as decimals. See Why can't decimal numbers be represented exactly in binary? for more information.\n",
"As Ned Batchelder said, not all decimals are exactly representable as floats. A float is represented by a certain number of b... | [
5,
1,
1,
1,
0
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0001619818_python_python_2.5.txt |
Q:
What is causing this Python exception?
I have a C++ app that uses Python to load some scripts. It calls some functions in the scripts, and everything works fine until the app exits and calls Py_Finalize. Then it displays the following: (GetName is a function in one of the scripts)
Exception AttributeError: "'modul... | What is causing this Python exception? | I have a C++ app that uses Python to load some scripts. It calls some functions in the scripts, and everything works fine until the app exits and calls Py_Finalize. Then it displays the following: (GetName is a function in one of the scripts)
Exception AttributeError: "'module' object has no attribute 'GetName'" in 'ga... | [
"From the docs to Py_Finalize():\n\nBugs and caveats: The destruction of\n modules and objects in modules is done\n in random order; this may cause\n destructors (__del__() methods) to\n fail when they depend on other objects\n (even functions) or modules.\n Dynamically loaded extension modules\n loaded by P... | [
4
] | [] | [] | [
"attributes",
"exception",
"python"
] | stackoverflow_0001619908_attributes_exception_python.txt |
Q:
name a column and then call items with name instead of index
I have a list of columns that I will be analyzing. Instead of referring back to the specific index such as data[1][2], I'd like to assign a name to a column and then loop through the rows of the columns for different tasks. How do I assign a name to a ... | name a column and then call items with name instead of index | I have a list of columns that I will be analyzing. Instead of referring back to the specific index such as data[1][2], I'd like to assign a name to a column and then loop through the rows of the columns for different tasks. How do I assign a name to a column and then is this the correct format to refer back to it?
fo... | [
"There's a bunch of different ways of doing this. If you know the association between names and columns at the time you write your code, the easiest way by far is this:\nfor row in data:\n (foo, bar, baz, bat) = row\n\n...assuming that you don't need to update row (and data). \nIf you need to update the row, co... | [
3,
2,
0
] | [] | [] | [
"names",
"python"
] | stackoverflow_0001619880_names_python.txt |
Q:
In Django, how can I embed something in CSS?
background: url({{ MEDIA_URL }}/bg.jpg);
That does not work, because this Django template function only works in .html!
A:
Django template function only works in .html!
This is totally wrong. Django templates are independent of the format. It can be easily used on a... | In Django, how can I embed something in CSS? | background: url({{ MEDIA_URL }}/bg.jpg);
That does not work, because this Django template function only works in .html!
| [
"\nDjango template function only works in .html!\n\nThis is totally wrong. Django templates are independent of the format. It can be easily used on any other format, infact for many other purposes.\n\nhow can I embed something in CSS?\n\nYou serve your css from a static server like nginx or apache (configured for s... | [
9,
9
] | [] | [] | [
"css",
"django",
"python",
"templates"
] | stackoverflow_0001620122_css_django_python_templates.txt |
Q:
Which key:value store to use with Python?
So I'm looking at various key:value (where value is either strictly a single value or possibly an object) stores for use with Python, and have found a few promising ones. I have no specific requirement as of yet because I am in the evaluation phase. I'm looking for what's ... | Which key:value store to use with Python? | So I'm looking at various key:value (where value is either strictly a single value or possibly an object) stores for use with Python, and have found a few promising ones. I have no specific requirement as of yet because I am in the evaluation phase. I'm looking for what's good, what's bad, what are the corner cases the... | [
"That mostly depends on your need.\nRead Caveats of Evaluating Databases to understand how to evaluate them. \n",
"shelve (storing dictonaris in file / standard python module) \nZODB - persisatnce object database (python objects database, no SQL)\nMore persistance tools:\nhttp://wiki.python.org/moin/PersistenceTo... | [
7,
3,
3
] | [
"How about Amazon's SimpleDB?\nThere is an open-source python library called boto for python interfacing Amazon web services.\n"
] | [
-1
] | [
"couchdb",
"memcached",
"python",
"tokyo_tyrant"
] | stackoverflow_0001617309_couchdb_memcached_python_tokyo_tyrant.txt |
Q:
Best resources for learning python in a 'class type setting'?
One of the best classes I took in college was Programming Languages where the prof would introduce a language or language concept, do a little playing with it in real time, and send us home with like 10 small little functions or programs to write that u... | Best resources for learning python in a 'class type setting'? | One of the best classes I took in college was Programming Languages where the prof would introduce a language or language concept, do a little playing with it in real time, and send us home with like 10 small little functions or programs to write that used what we learned in class and stretched it just enough to make s... | [
"I am teaching Python to graduate students at the University of Paris, and I exactly chose the kind of approach you like! I could not agree more with how useful it can be.\nI thus had to ask myself the same question as the one you ask here: I would recommend the following sources, in the given order:\n\nInstant Py... | [
4,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001619018_python.txt |
Q:
What is a light python library that can eliminate HTML tags? (and only text)
I know that NLTK has it. But any else?
A:
python standard module html.parser should allow you to parse simple html content and eliminate tags. you only have to derive HTMLParser, then overload all handle_*() methods so that they output ... | What is a light python library that can eliminate HTML tags? (and only text) | I know that NLTK has it. But any else?
| [
"python standard module html.parser should allow you to parse simple html content and eliminate tags. you only have to derive HTMLParser, then overload all handle_*() methods so that they output or discard content, depending on the surrounding element tags.\n",
"BeautifulSoup: http://www.crummy.com/software/Beaut... | [
4,
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001620363_python.txt |
Q:
How to start a long-running process from a Django view?
I need to run a process that might take hours to complete from a Django view. I don't need to know the state or communicate with it but I need that view to redirect away right after starting the process.
I've tried using subprocess.Popen, using it within a ne... | How to start a long-running process from a Django view? | I need to run a process that might take hours to complete from a Django view. I don't need to know the state or communicate with it but I need that view to redirect away right after starting the process.
I've tried using subprocess.Popen, using it within a new threading.Thread, multiprocessing.Process. However, the pa... | [
"I don't know if this will be suitable for your case, nevertheless here is what I do: I use a task queue (via a django model); when the view is called, it enters a new record in the tasks and redirects happily. Tasks in turn are executed by cron on a regular basis independently from django. \nEdit: cron calls the r... | [
10,
5,
2,
2
] | [] | [] | [
"django",
"long_running_processes",
"python"
] | stackoverflow_0001619397_django_long_running_processes_python.txt |
Q:
Friendlier error messages on import for missing modules
I want to implement some friendlier error messages if the user tries to run a python script which tries to import modules that have not been installed. This includes printing out instructions on how to install the missing module.
One way to do this would be t... | Friendlier error messages on import for missing modules | I want to implement some friendlier error messages if the user tries to run a python script which tries to import modules that have not been installed. This includes printing out instructions on how to install the missing module.
One way to do this would be to put a try..catch block around the imports, but this is a bi... | [
"You can put, somewhere that it will always be executed (e.g. in site.py or sitecustomize.py):\nimport __builtin__\n\nrealimport = __builtin__.__import__\n\ndef myimport(modname, *a):\n try:\n return realimport(modname, *a)\n except ImportError, e:\n print \"Oops, couldn't import %s (%s)\" % (modname, e)\n ... | [
6,
3,
2,
1
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0001618762_exception_handling_python.txt |
Q:
Installing satchmo without ssh access
I want to install satchmo in my virtual hosting, but they dont provide ssh access for it. I want to know if it is possible. As i can see, adding some Satchmo requirements(http://www.satchmoproject.com/docs/svn/requirements.html) to pythonpath in my .fcgi file seems to be worki... | Installing satchmo without ssh access | I want to install satchmo in my virtual hosting, but they dont provide ssh access for it. I want to know if it is possible. As i can see, adding some Satchmo requirements(http://www.satchmoproject.com/docs/svn/requirements.html) to pythonpath in my .fcgi file seems to be working, but some requirements like pycrypto and... | [
"Sure you can, In the past I wrote a cgi to download and build Python on hosting that only allowed ftp access.\nIf you know the target platform it will be easier to set up a virtual machine locally, build the files you need there and upload the compiled versions. Make sure you statically link them if the hosting is... | [
1,
0
] | [] | [] | [
"django",
"python",
"satchmo",
"ssh"
] | stackoverflow_0001620620_django_python_satchmo_ssh.txt |
Q:
place labels between ticks
in matplotlib, how do i place ticks labels between ticks (not below ticks)
for example: when plotting a the stock price over time i would like the x axis minor ticks to display months and the years to show up between consecutive x axis major ticks (not just below the major ticks)
---|---... | place labels between ticks | in matplotlib, how do i place ticks labels between ticks (not below ticks)
for example: when plotting a the stock price over time i would like the x axis minor ticks to display months and the years to show up between consecutive x axis major ticks (not just below the major ticks)
---|---|---|---|---|---|---|---|---|---... | [
"Will this do the trick?\nenter code here\nx = 'j f m a m j j a s o n d j f m a m j j a s o n d'.split()\ny = abs(randn(24))\nx[6] = 'j\\n2008' # replace \"j\" (January) with ('j' and the appropriate year\nx[18] = 'j\\n2009'\nbar(xrange(len(x)), y, width=0.1)\nbar(xrange(len(x)), y, width=0.1)\nxticks(xrange(len(x)... | [
5,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0001620927_matplotlib_python.txt |
Q:
Python script to print all function definitions of a C/C++ file
I want a python script to print list of all functions defined in a C/C++ file.
e.g. abc.c defines two functions as:
void func1() { }
int func2(int i) { printf("%d", i); return 1; }
I just want to search the file (abc.c) and print all the functions de... | Python script to print all function definitions of a C/C++ file | I want a python script to print list of all functions defined in a C/C++ file.
e.g. abc.c defines two functions as:
void func1() { }
int func2(int i) { printf("%d", i); return 1; }
I just want to search the file (abc.c) and print all the functions defined in it (function names only). In the example above, I would like... | [
"I would suggest using the PLY lex/yacc tool. There's a prebuilt C parser, and the parser itself is quite fast. Once you have the file parsed, it shouldn't be too hard to find all of the functions.\nhttp://www.dabeaz.com/ply/\n",
"antlr is your tool\n",
"To do this reliably, you'd need to parse the C or C++ cod... | [
3,
2,
2,
1
] | [] | [] | [
"parsing",
"python",
"string"
] | stackoverflow_0001620851_parsing_python_string.txt |
Q:
Nesting generator expressions in the argument list for a python function call
I like to use the following idiom for combining lists together, sometimes:
>>> list(itertools.chain(*[[(e, n) for e in l] for n, l in (('a', [1,2]),('b',[3,4]))]))
[(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')]
(I know there are easier ways t... | Nesting generator expressions in the argument list for a python function call | I like to use the following idiom for combining lists together, sometimes:
>>> list(itertools.chain(*[[(e, n) for e in l] for n, l in (('a', [1,2]),('b',[3,4]))]))
[(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')]
(I know there are easier ways to get this particular result, but it comes comes in handy when you want to iterate ... | [
"wouldn't a nested list comprehension be more appropriate?\n>>> tt = (('a', [1,2]),('b',[3,4]))\n>>> [(s, i) for i, l in tt for s in l]\n[(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')]\n\n",
"Your approach almost works, you just need to flatten the generators. See how the for e in l is moved to the very right\n>>> list(... | [
6,
2,
0
] | [] | [] | [
"generator",
"list_comprehension",
"python"
] | stackoverflow_0001620957_generator_list_comprehension_python.txt |
Q:
Python RegEx skipping the first few characters?
Hey I have a fairly basic question about regular expressions. I want to just return the text inside (and including) the body tags, and I know the following isn't right because it'll also match all the characters before the opening body tag. I was wondering how you wo... | Python RegEx skipping the first few characters? | Hey I have a fairly basic question about regular expressions. I want to just return the text inside (and including) the body tags, and I know the following isn't right because it'll also match all the characters before the opening body tag. I was wondering how you would go about skipping those?
x = re.match('(.*<body).... | [
"I don't know Python, but here's a quick example thrown together using Beautiful Soup, which I often see recommended for Python HTML parsing.\nimport BeautifulSoup\n\nsoup = BeautifulSoup(fileString)\n\nbodyTag = soup.html.body.string\n\nThat will (in theory) deal with all the complexities of HTML, which is very di... | [
9,
2,
0
] | [
" x = re.match('.*(<body>.*?</body>)', fileString)\n\nConsider minidom for HTML parsing.\n",
"x = re.search('(<body>.*</body>)', fileString)\nx.group(1)\n\nLess typing than the match answers\n",
"Does your fileString contain multiple lines? In that case you may need to specify it or skip the lines explicitly:\n... | [
-2,
-2,
-2
] | [
"html_parsing",
"python",
"regex"
] | stackoverflow_0001620889_html_parsing_python_regex.txt |
Q:
dynamically adding functions to a Python module
Our framework requires wrapping certain functions in some ugly boilerplate code:
def prefix_myname_suffix(obj):
def actual():
print 'hello world'
obj.register(actual)
return obj
I figured this might be simplified with a decorator:
@register
def m... | dynamically adding functions to a Python module | Our framework requires wrapping certain functions in some ugly boilerplate code:
def prefix_myname_suffix(obj):
def actual():
print 'hello world'
obj.register(actual)
return obj
I figured this might be simplified with a decorator:
@register
def myname():
print 'hello world'
However, that turne... | [
"use either \ncurrent_module.new_name = func\n\nor \nsetattr(current_module, new_name, func)\n\n",
"It seems the solution to your problem would be to make the decorated function act as the original function. \nTry using the function mergeFunctionMetadata from Twisted, found here:\ntwisted/python/util.py\nI... | [
22,
0
] | [] | [] | [
"decorator",
"metaprogramming",
"python"
] | stackoverflow_0001621350_decorator_metaprogramming_python.txt |
Q:
How to make easy_install execute custom commands in setup.py?
I want my setup.py to do some custom actions besides just installing the Python package (like installing an init.d script, creating directories and files, etc.) I know I can customize the distutils/setuptools classes to do my own actions. The problem I ... | How to make easy_install execute custom commands in setup.py? | I want my setup.py to do some custom actions besides just installing the Python package (like installing an init.d script, creating directories and files, etc.) I know I can customize the distutils/setuptools classes to do my own actions. The problem I am having is that everything works when I cd to the package directo... | [
"Paver takes setuptools to the next level and lets you write custom tasks. It allows you to extend the typical setup.py file and provides a simple way to bootstrap the Paver environment.\n",
"It cannot be done. Enthought has a custom version of setuptools that does support this, but otherwise it is in the bug tra... | [
5,
4
] | [] | [] | [
"easy_install",
"python",
"setuptools"
] | stackoverflow_0001446682_easy_install_python_setuptools.txt |
Q:
Fastest way to convert '(-1,0)' into tuple(-1, 0)?
I've got a huge tuple of strings, which are being returned from a program. An example tuple being returned might look like this:
('(-1,0)', '(1,0)', '(2,0)', '(3,0)', '(4,0)', '(5,0)', '(6,0)')
I can convert these strings to real tuples (with integers inside), bu... | Fastest way to convert '(-1,0)' into tuple(-1, 0)? | I've got a huge tuple of strings, which are being returned from a program. An example tuple being returned might look like this:
('(-1,0)', '(1,0)', '(2,0)', '(3,0)', '(4,0)', '(5,0)', '(6,0)')
I can convert these strings to real tuples (with integers inside), but i am hoping someone knows a nice trick to speed this u... | [
"I don't advice you to use eval at all. It is slow and insecure. You can do this:\nresult = map(lambda a: tuple(map(int, a[1:-1].split(','))), s)\n\nThe numbers speak for themselves:\ntimeit.Timer(\"map(lambda a: tuple(map(int, a[1:-1].split(','))), s)\", \"s = ('(-1,0)', '(1,0)', '(2,0)', '(3,0)', '(4,0)', '(5,0)'... | [
10,
3,
2,
2,
1,
1,
1,
0
] | [] | [] | [
"python",
"string",
"tuples"
] | stackoverflow_0001618965_python_string_tuples.txt |
Q:
how to extract some text by use lxml?
i want to extract some text in certain website.
here is web address what i want to extract some text to make scraper.
http://news.search.naver.com/search.naver?sm=tab_hty&where=news&query=times&x=0&y=0
in this page, i want to extract some text with subject and content field se... | how to extract some text by use lxml? | i want to extract some text in certain website.
here is web address what i want to extract some text to make scraper.
http://news.search.naver.com/search.naver?sm=tab_hty&where=news&query=times&x=0&y=0
in this page, i want to extract some text with subject and content field separately.
for example,if you open that page... | [
"In general, to solve such problems you must first download the page of interest as text (use urllib.urlopen or anything else, even external utilities such as curl or wget, but not a browser since you want to see how the page looks before any Javascript has had a chance to run) and study it to understand its struct... | [
2
] | [] | [] | [
"lxml",
"parsing",
"python"
] | stackoverflow_0001621410_lxml_parsing_python.txt |
Q:
Finding and adding twitter users?
Any suggestions for a good twitter library (preferably in Ruby or Python)? I have a list of usernames, and I need to be able to programmatically follow these users.
I tried twitter4r in Ruby, but finding users doesn't seem to work. When I do
twitter = Twitter::Client.new(:login =... | Finding and adding twitter users? | Any suggestions for a good twitter library (preferably in Ruby or Python)? I have a list of usernames, and I need to be able to programmatically follow these users.
I tried twitter4r in Ruby, but finding users doesn't seem to work. When I do
twitter = Twitter::Client.new(:login => 'mylogin', :password => 'mypassword')... | [
"http://github.com/jnunemaker/twitter/ has been working pretty good for me.\nAlthough, If I am just doing something simple, I usually resort to the bare HTTP API. In this case it would be this one: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-friendships%C2%A0create\nUsing Ruby with RestClient that would l... | [
1
] | [] | [] | [
"python",
"ruby",
"twitter"
] | stackoverflow_0001621863_python_ruby_twitter.txt |
Q:
Is there a way to split a string by every nth separator in Python?
For example, if I had the following string:
"this-is-a-string"
Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?
A:
Here’s another solution:
span = 2
words... | Is there a way to split a string by every nth separator in Python? | For example, if I had the following string:
"this-is-a-string"
Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?
| [
"Here’s another solution:\nspan = 2\nwords = \"this-is-a-string\".split(\"-\")\nprint [\"-\".join(words[i:i+span]) for i in range(0, len(words), span)]\n\n",
">>> s=\"a-b-c-d-e-f-g-h-i-j-k-l\" # use zip(*[i]*n)\n>>> i=iter(s.split('-')) # for the nth case \n>>> map(\"-\".join,zip(i,i)) ... | [
46,
16,
12,
1,
0
] | [
"l = 'this-is-a-string'.split()\nnl = []\nss = \"\"\nc = 0\nfor s in l:\n c += 1\n if c%2 == 0:\n ss = s\n else:\n ss = \"%s-%s\"%(ss,s)\n nl.insert(ss)\n\nprint nl\n\n"
] | [
-1
] | [
"python",
"split",
"string"
] | stackoverflow_0001621906_python_split_string.txt |
Q:
Python Selenium handling Timeout Exceptions with a long list of URLs
I am using selenium RC to cycle through a long list of URLs, sequentially writing the HTML from each URL to a csv file. Problem: the program frequently exits at various points in list due to URL "Timed out after 30000ms" exceptions. Instead of s... | Python Selenium handling Timeout Exceptions with a long list of URLs | I am using selenium RC to cycle through a long list of URLs, sequentially writing the HTML from each URL to a csv file. Problem: the program frequently exits at various points in list due to URL "Timed out after 30000ms" exceptions. Instead of stopping the program when it hits a URL time-out, I was trying to have the ... | [
"Try the following:\nfrom selenium import selenium\nimport unittest, time, re, csv, logging\n\nclass Untitled(unittest.TestCase):\n def setUp(self):\n self.verificationErrors = []\n self.selenium = selenium(\"localhost\", 4444, \"*firefox\", \"http://example.com\")\n self.selenium.start()\n ... | [
3
] | [] | [] | [
"exception",
"loops",
"python",
"selenium",
"timeout"
] | stackoverflow_0001621806_exception_loops_python_selenium_timeout.txt |
Q:
White listing certain HTML tags in python?
Let's say allowed_bits = ['a', 'p']
re.compile(r'<(%s)[^>]*(/>|.*?</\1>)' % ('|'.join(allowed_bits)))
matches:
<a href="blah blah">blah</a>
<p />
and not:
<html>blah blah blah</html>
What I want to do is turn it on its head, so that it matches
<html>blah blah</html>
<... | White listing certain HTML tags in python? | Let's say allowed_bits = ['a', 'p']
re.compile(r'<(%s)[^>]*(/>|.*?</\1>)' % ('|'.join(allowed_bits)))
matches:
<a href="blah blah">blah</a>
<p />
and not:
<html>blah blah blah</html>
What I want to do is turn it on its head, so that it matches
<html>blah blah</html>
<script type="text/javascript">blah blah</script>... | [
"Use a negative lookahead assertion (?! … ):\nre.compile(r'<(?!%s)[^>](/>|.?)' % ('|'.join(allowed_bits)))\n\n"
] | [
2
] | [] | [] | [
"python",
"regex",
"regex_negation"
] | stackoverflow_0001622314_python_regex_regex_negation.txt |
Q:
How do I trim the number of words in Python?
For example...
s = 'The fox jumped over a big brown log.'
k = FUNCTION(s,4)
k should be... "The fox jumped over"
I can write my own function that splits on whitespace, cuts the list and then joins the list. But that is too much work.
Anyone else knows a simpler way?
... | How do I trim the number of words in Python? | For example...
s = 'The fox jumped over a big brown log.'
k = FUNCTION(s,4)
k should be... "The fox jumped over"
I can write my own function that splits on whitespace, cuts the list and then joins the list. But that is too much work.
Anyone else knows a simpler way?
| [
"Something like this:\ndef f(s, n):\n return ' '.join(s.split()[:n])\n\nBut it is still splitting, slicing and joining...\n",
"x = \"Hello how are you?\"\n' '.join(x.split()[1:3])\n>>> \"how are\"\n\nyou can then change the numbers 1 and 3 in the list to get which words you want it to return\ndef split_me(stri... | [
8,
3,
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001622421_python_string.txt |
Q:
Werkzeug in General, and in Python 3.1
I've been looking really hard at all of the way**(s)** one can develop web applications using Python. For reference, we are using RHEL 64bit, apache, mod_wsgi.
History:
PHP + MySQL years ago
PHP + Python 2.x + MySQL recently and current
Python + PostgreSQL working on it
We... | Werkzeug in General, and in Python 3.1 | I've been looking really hard at all of the way**(s)** one can develop web applications using Python. For reference, we are using RHEL 64bit, apache, mod_wsgi.
History:
PHP + MySQL years ago
PHP + Python 2.x + MySQL recently and current
Python + PostgreSQL working on it
We use a great library for communicating betwe... | [
"mod_wsgi for Python 3.x is also not ready. There is no satisfactory definition of WSGI for Python 3.x yet; the WEB-SIG are still bashing out the issues. mod_wsgi targets a guess at what might be in it, but there are very likely to be changes to both the spec and to standard libraries. Any web application you write... | [
3,
1,
1
] | [] | [] | [
"python",
"python_3.x",
"werkzeug"
] | stackoverflow_0001523706_python_python_3.x_werkzeug.txt |
Q:
what exactly is a "register machine"?
From http://code.google.com/p/unladen-swallow/wiki/ProjectPlan I quote:
"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languages (Ierusalimschy et al, 2005; Shi et al... | what exactly is a "register machine"? | From http://code.google.com/p/unladen-swallow/wiki/ProjectPlan I quote:
"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languages (Ierusalimschy et al, 2005; Shi et al, 2005)."
In college I built a simple compi... | [
"A register machine is a hardware or software unit that when working with data takes it from memory, puts it in a location where it can work with it quickly, and then returns the result.\nFor example a regular CPU is a register machine. Since the ALU (the unit that works with numbers in a CPU) can only work with nu... | [
24,
11,
5,
4,
2,
2
] | [] | [] | [
"language_design",
"language_implementation",
"language_theory",
"python"
] | stackoverflow_0001622530_language_design_language_implementation_language_theory_python.txt |
Q:
Overriding set methods in Python
I want to create a custom set that will automatically convert objects into a different form for storage in the set (see Using a Python Dictionary as a key non-nested) for background.
If I override add, remove, __contains__, __str__, update, __iter__, will that be sufficient to mak... | Overriding set methods in Python | I want to create a custom set that will automatically convert objects into a different form for storage in the set (see Using a Python Dictionary as a key non-nested) for background.
If I override add, remove, __contains__, __str__, update, __iter__, will that be sufficient to make the other operations behave properly... | [
"Working from collections's abstract classes, as @kaizer.se suggests, is the appropriate solution in 2.6 (not sure why you want to call super -- what functionality are you trying to delegate that can't best done by containment rather than inheritance?!).\nIt's true that you don't get update -- by providing the abst... | [
9,
1
] | [] | [] | [
"python",
"python_3.x",
"set"
] | stackoverflow_0001622722_python_python_3.x_set.txt |
Q:
Execute and monitor multiple instances of external program in Python
Main program is like this:
PREPARE PARAMETERS FOR CHILD PROCESSES
subprocess.Popen('python child.py param=example1'.split(' '))
subprocess.Popen('python child.py param=example2'.split(' '))
...
How to make main program to monitor each instances ... | Execute and monitor multiple instances of external program in Python | Main program is like this:
PREPARE PARAMETERS FOR CHILD PROCESSES
subprocess.Popen('python child.py param=example1'.split(' '))
subprocess.Popen('python child.py param=example2'.split(' '))
...
How to make main program to monitor each instances of child process it launched and restart it with its corresponding paramet... | [
"Keep a dict with the .pids of the child processes as keys, and the commandlines to restart them as corresponding values. i.e.:\nchildid = []\nfor cmdline in cmdlines:\n p = subprocess.Popen(cmdline.split())\n childid[p.pid] = cmdline\n\nos.wait will return whenever any child process terminates: it gives you (pi... | [
5
] | [] | [] | [
"external_process",
"python"
] | stackoverflow_0001623192_external_process_python.txt |
Q:
Adventure game - walking around inside a room
I'm working on an adventure game in Python using Pygame. My main problem is how I am going to define the boundaries of the room and make the main character walk aroud without hitting a boundary every time. Sadly, I have never studied algorithms so I have no clue on how... | Adventure game - walking around inside a room | I'm working on an adventure game in Python using Pygame. My main problem is how I am going to define the boundaries of the room and make the main character walk aroud without hitting a boundary every time. Sadly, I have never studied algorithms so I have no clue on how to calculate a path. I know this question is quite... | [
"There are two easy ways of defining your boundaries which are appropriate for such a game.\nThe simpler method is to divide your area into a grid, and use a 2D array to keep track of which squares in the grid are passable. Usually, this array stores your map information too, so in each position, there is a number ... | [
4,
3,
3,
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0001623331_pygame_python.txt |
Q:
Does using Psyco with django make any sense?
I know the benefits of Psyco for a Desktop app, but in a Web app where a process ( = a web page or an AJAX call) dies immediately after been fired, isn't it pointless ?
A:
You should be using fastcgi or wsgi with django, so the process won't be starting up for each re... | Does using Psyco with django make any sense? | I know the benefits of Psyco for a Desktop app, but in a Web app where a process ( = a web page or an AJAX call) dies immediately after been fired, isn't it pointless ?
| [
"You should be using fastcgi or wsgi with django, so the process won't be starting up for each request.\nYou really need to write your code to be psyco friendly if you want decent gains, and you will not benefit if your bottleneck is the database.\n",
"First, as gribbler and Ibrahim mentioned, your process won't ... | [
4,
4,
4
] | [] | [] | [
"django",
"psyco",
"python"
] | stackoverflow_0001623538_django_psyco_python.txt |
Q:
Escaping '<' and '>' in xml when using xml.dom.minidom
I am stuck while escaping "<" and ">" in the xml file using xml.dom.minidom.
I tried to get the unicode hex value and use that instead
http://slayeroffice.com/tools/unicode_lookup/
Tried to use the standard "<" and ">" but still with no success.
from xml.do... | Escaping '<' and '>' in xml when using xml.dom.minidom | I am stuck while escaping "<" and ">" in the xml file using xml.dom.minidom.
I tried to get the unicode hex value and use that instead
http://slayeroffice.com/tools/unicode_lookup/
Tried to use the standard "<" and ">" but still with no success.
from xml.dom.minidom import Document
doc = Document()
e = doc.createEle... | [
"This is not a bug, it is a feature. To insert actual XML, insert DOM objects instead. Text inside an XML tag needs to be entity escaped though to be valid XML.\nfrom xml.dom.minidom import Document\ndoc = Document()\ne = doc.createElement(\"abc\")\neh = doc.createElement(\"hello\")\ns1 = 'bhaskar'\ntext = doc.crea... | [
6,
3
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0001623607_python_xml.txt |
Q:
SQLAlchemy: Shallow copy avoiding lazy loading
I'm trying to automatically build a shallow copy of a SA-mapped
object.. At the moment my function is just:
newobj = src.__class__()
for prop in class_mapper(src.__class__).iterate_properties:
setattr(newobj, prop.key, getattr(src, prop.key))
but I'm having troub... | SQLAlchemy: Shallow copy avoiding lazy loading | I'm trying to automatically build a shallow copy of a SA-mapped
object.. At the moment my function is just:
newobj = src.__class__()
for prop in class_mapper(src.__class__).iterate_properties:
setattr(newobj, prop.key, getattr(src, prop.key))
but I'm having troubles with lazy relations... Obviously getattr
trigger... | [
"What you need is to copy column properties only, which can be easily filtered using isinstance(prop, sqlalchemy.orm.ColumnProperty). Note, that you HAVE to copy externally stored relations (all many-to-many), since there is no columns corresponding to them in the main table. This can't be done with high-level inte... | [
6
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001623661_python_sqlalchemy.txt |
Q:
Restrict access to images on my website except through my own htmls
On my website I store user pictures in a simple manner such as:
"image/user_1.jpg".
I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, ... | Restrict access to images on my website except through my own htmls | On my website I store user pictures in a simple manner such as:
"image/user_1.jpg".
I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, so on...)
So far I have three solutions in mind:
I tried using .htaccess... | [
"Any method you choose to determine the source of a request is only as reliable as the HTTP_REFERER information that is sent by the user's browser, which is not very. Requiring authentication is the only good way to protect content. \n",
"Method #1 is not viable as it will ask for user name and password on each a... | [
6,
5,
3,
2,
0
] | [] | [] | [
"linux",
"perl",
"php",
"python"
] | stackoverflow_0001623311_linux_perl_php_python.txt |
Q:
Python - RegExp - Modify text files
Newbie to Python.... help requested with the following task :-)
I have tree of various files, some of them are C source code.
I would like to modify these C files with python script.
The C code has 4 defines -
#define ZR_LOG0(Id, Class, Seveity, Format)
#define ZR_LOG1(Id, Class... | Python - RegExp - Modify text files | Newbie to Python.... help requested with the following task :-)
I have tree of various files, some of them are C source code.
I would like to modify these C files with python script.
The C code has 4 defines -
#define ZR_LOG0(Id, Class, Seveity, Format)
#define ZR_LOG1(Id, Class, Seveity, Format, Attr0)
#define ZR_LOG2... | [
"A few points:\n\nYou can match whitespace with '\\s'.\nThe regexp 'capturing groups' are useful here.\n\nSo, I would do something like this:\noutput = ''\ncounter = 1\nfor line in lines:\n # Match only ZR_LOG lines and capture everything surrounding \"Id\"\n match = re.match('^(.*\\sZR_LOG[0-3]\\s*\\(\\s*)' ... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001624050_python_regex.txt |
Q:
How to make a private download area with django?
I would like to implement a private download area on a website powered by django. The user would have to be logged in with the appropriate rights in order to be able to get some static files.
What would you recommend for writing this feature. Any tips or tricks?
Tha... | How to make a private download area with django? | I would like to implement a private download area on a website powered by django. The user would have to be logged in with the appropriate rights in order to be able to get some static files.
What would you recommend for writing this feature. Any tips or tricks?
Thanks in advance
Update:
Maybe because of my bad english... | [
"So, searching I found this discussion thread.\nThere were three things said you might be interested in.\nFirst there is the mod_python method\nThen there is the mod_wsgi method\nBoth of which don't seem all that great.\nBetter is the X-Sendfile header which isn't fully standard, but works at least within apache, a... | [
11,
3,
1
] | [] | [] | [
"authentication",
"django",
"download",
"python"
] | stackoverflow_0001609273_authentication_django_download_python.txt |
Q:
How to avoid repetition of exception handling?
I've moved IOError handling to a separate function to avoid boilerplate when opening files for reading.
But what if IOError fires when the file is being read? If sshfs disconnects, or file is deleted by root, etc.?
def safe_open(*args):
try:
return open(*a... | How to avoid repetition of exception handling? | I've moved IOError handling to a separate function to avoid boilerplate when opening files for reading.
But what if IOError fires when the file is being read? If sshfs disconnects, or file is deleted by root, etc.?
def safe_open(*args):
try:
return open(*args)
except IOError:
quit('Error when op... | [
"I would probably try move the file operations into separate functions and wrap those in a try... except\nactually I just got an even better idea... put the error handling into a decorator and apply the decorator to each of the functions that does file operations\ndef catch_io_errors(fn):\n def decorator(*args, ... | [
7
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0001624518_exception_handling_python.txt |
Q:
Django or similar for composite primary keys
I am writing a web application for my engineering company (warning: I am a programmer only by hobby) and was planning on using Django until I hit this snag. The models I want to use naturally have multi-column primary keys. Per http://code.djangoproject.com/ticket/373, ... | Django or similar for composite primary keys | I am writing a web application for my engineering company (warning: I am a programmer only by hobby) and was planning on using Django until I hit this snag. The models I want to use naturally have multi-column primary keys. Per http://code.djangoproject.com/ticket/373, I can't use Django, at least not a released versio... | [
"Why not add a normal primary key, and then specify that part_number and part_revision as unique_together?\nThis essentially is the Djangoish (Djangonic?) way of doing what Mitch Wheat said.\n",
"A work around is to create a surrogate key (an auto increment column) as the primary key column and place a unique ind... | [
24,
20,
14,
2
] | [] | [] | [
"django",
"django_models",
"python",
"web_applications"
] | stackoverflow_0001624257_django_django_models_python_web_applications.txt |
Q:
Python package install using pip or easy_install from repos
The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder.
Clearly since source control provides the complete ... | Python package install using pip or easy_install from repos | The simplest way to deal with python package installations, so far, to me, has been to check out the source from the source control system and then add a symbolic link in the python dist-packages folder.
Clearly since source control provides the complete control to downgrade, upgrade to any branch, tag, it works very w... | [
"Using pip this is quite easy. For instance:\npip install -e hg+http://bitbucket.org/andrewgodwin/south/#egg=South\n\nPip will automatically clone the source repo and run \"setup.py develop\" for you to install it into your environment (which hopefully is a virtualenv). Git, Subversion, Bazaar and Mercurial are all... | [
26,
11,
4,
0
] | [] | [] | [
"easy_install",
"pip",
"python",
"svn",
"version_control"
] | stackoverflow_0001033897_easy_install_pip_python_svn_version_control.txt |
Q:
How to determine default Accept-Language header based on IP (country code)?
I want like to enhance spam protection on my site. I've found out that after being banned by ip bots don't change the Accept-Language and Accept-Charset http headers (so most of spam comes with windows-1251 accept-charset). I understand th... | How to determine default Accept-Language header based on IP (country code)? | I want like to enhance spam protection on my site. I've found out that after being banned by ip bots don't change the Accept-Language and Accept-Charset http headers (so most of spam comes with windows-1251 accept-charset). I understand that there may be normal users with unordinary preferences, but anyways, how can I ... | [
"This answer has two parts: determining where your user comes from, and what language they speak. To determine where they come from, you can use a service such as hostip.info, which has an API which takes an IP address and returns a country code. Second, you would need a list such as this one to translate the count... | [
1
] | [] | [] | [
"geoip",
"python",
"spam"
] | stackoverflow_0001624816_geoip_python_spam.txt |
Q:
Python Tornado Web - AttributeError: 'Connection' object has no attribute '_execute'
I'm experiencing a strange behaviour working with the latest branch of tornadoweb when I deploy my app on my production server.
I tested several times the code and it is fully working when I test it on my laptop (Archlinux) with p... | Python Tornado Web - AttributeError: 'Connection' object has no attribute '_execute' | I'm experiencing a strange behaviour working with the latest branch of tornadoweb when I deploy my app on my production server.
I tested several times the code and it is fully working when I test it on my laptop (Archlinux) with python 2.6.3 and MySQLdb 1.2.3b2.
As soon as I deploy on my production server (Ubuntu x64) ... | [
"I finally fixed my problem moving to a fresh ubuntu x64 instead of using a i386 version.\n"
] | [
-2
] | [] | [] | [
"attributeerror",
"mysql",
"python",
"tornado",
"ubuntu"
] | stackoverflow_0001618339_attributeerror_mysql_python_tornado_ubuntu.txt |
Q:
Python loops with multiple lists?
<edit>
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:
zip(range(len(files)), files, directories)
</edit>
Hi,
I'm in the process of learning Python, b... | Python loops with multiple lists? | <edit>
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:
zip(range(len(files)), files, directories)
</edit>
Hi,
I'm in the process of learning Python, but I come from a background where the f... | [
"import os.path\nfor dir, file in zip(directories, files):\n print(os.path.join(dir, file)) # for directories, files\n\nyou can have it as a list comprehension as well, creating list of string with print going after that]\nwith counter:\nfor i, (dir, file) in enumerate(zip(directories, files... | [
35,
10,
1
] | [
"Building on Ryan's answer, you can do:\nfor fileDir in [dir + '/' + file for dir in directories for file in files]:\n print(fileDir)\n\n"
] | [
-1
] | [
"arrays",
"list",
"loops",
"python"
] | stackoverflow_0000521321_arrays_list_loops_python.txt |
Q:
Is there an easy way to create derived attributes in Django Model/Python classes?
Every Django model has a default primary-key id created automatically. I want the model objects to have another attribute big_id which is calculated as:
big_id = id * SOME_CONSTANT
I want to access big_id as model_obj.big_id without ... | Is there an easy way to create derived attributes in Django Model/Python classes? | Every Django model has a default primary-key id created automatically. I want the model objects to have another attribute big_id which is calculated as:
big_id = id * SOME_CONSTANT
I want to access big_id as model_obj.big_id without the corresponding database table having a column called big_id.
Is this possible?
| [
"Well, django model instances are just python objects, or so I've been told anyway :P\nThat is how I would do it:\nclass MyModel(models.Model):\n CONSTANT = 1234\n id = models.AutoField(primary_key=True) # not really needed, but hey\n\n @property\n def big_id(self):\n return self.pk * MyModel.CON... | [
8,
1,
0
] | [] | [] | [
"django",
"django_models",
"oop",
"python"
] | stackoverflow_0001626155_django_django_models_oop_python.txt |
Q:
How can this behavior be acomplished? Python "short circuting" test
I have the following code:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
else:
pass
return F... | How can this behavior be acomplished? Python "short circuting" test | I have the following code:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
else:
pass
return False
What i need to know the following: in case the if condition evaluat... | [
"return is the end of the line, and nothing else will happen in that function afterwards. On the other hand, you could rewrite your function as\ndef testGeodatabase(self):\n return self.outputGeodatabase in self.gp.ListWorkspaces(\"*\",\"ALL\")\n\n",
"You don't need the break keyword in the code above. Actuall... | [
8,
2,
1,
0
] | [] | [] | [
"python",
"short_circuiting"
] | stackoverflow_0001626267_python_short_circuiting.txt |
Q:
Python __getattribute__ (or __getattr__) to emulate php __call
I would like to create a class that effectively does this (mixing a little PHP with Python)
class Middle(object) :
# self.apply is a function that applies a function to a list
# e.g self.apply = [] ... self.apply.append(foobar)
... | Python __getattribute__ (or __getattr__) to emulate php __call | I would like to create a class that effectively does this (mixing a little PHP with Python)
class Middle(object) :
# self.apply is a function that applies a function to a list
# e.g self.apply = [] ... self.apply.append(foobar)
def __call(self, name, *args) :
self.apply(name, *args) ... | [
"You need to define __getattr__, it is called if an attribute is not otherwise found on your object.\nNotice that getattr is called for any failed lookup, and that you don't get it like a function all, so you have to return the method that will be called.\ndef __getattr__(self, attr):\n def default_method(*args):\... | [
3,
2
] | [
"I actually did this recently. Here's an example of how I solved it:\nclass Example:\n def FUNC_1(self, arg):\n return arg - 1\n\n def FUNC_2(self, arg):\n return arg - 2\n\n def decode(self, func, arg):\n try:\n exec( \"result = self.FUNC_%s(arg)\" % (func) )\n excep... | [
-1
] | [
"class",
"python"
] | stackoverflow_0001626478_class_python.txt |
Q:
pythonic approach to dynamic class variable names (ala PHP's $$var)
The following code:
class Log:
BAT_STATS = ['AB', 'R', 'H', 'HR']
def __init__(self, type):
for cat in Log.BAT_STATS:
self.cat = 0
I want the loop there to create a class property of each key in BAT_STATS, so I ca... | pythonic approach to dynamic class variable names (ala PHP's $$var) | The following code:
class Log:
BAT_STATS = ['AB', 'R', 'H', 'HR']
def __init__(self, type):
for cat in Log.BAT_STATS:
self.cat = 0
I want the loop there to create a class property of each key in BAT_STATS, so I can go:
log = Log()
print log.HR;
Similar to PHP with $this->$$foo = 'bar'... | [
"Maybe this?\nclass Log:\n BAT_STATS = ['AB', 'R', 'H', 'HR']\n\n def __init__(self, type):\n for cat in Log.BAT_STATS:\n setattr(self, cat, 0)\n\nEDIT - Oops, indentation was a bit messed up.\n@EOL: Are you suggesting putting it straight into the class definition? While for some application... | [
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0001626842_python.txt |
Q:
Installing TurboGears on windows 7
I tried installing TurboGears 1.0 on Windows 7 using tgsetup.py. and got following error
error: Couldn't find a setup script in c:\users\sandre~1\appdata\local\temp\
easy_install-jimbkt\Cheetah-2.4.0.linux-i686.tar.gz
When looking into this folder I see easy_install-jimbkt folde... | Installing TurboGears on windows 7 | I tried installing TurboGears 1.0 on Windows 7 using tgsetup.py. and got following error
error: Couldn't find a setup script in c:\users\sandre~1\appdata\local\temp\
easy_install-jimbkt\Cheetah-2.4.0.linux-i686.tar.gz
When looking into this folder I see easy_install-jimbkt folder appearing and disappearing right away.... | [
"Looks like it's trying to install the Linux binaries of Cheetah, which definitely won't work on Windows. To get that piece of the puzzle to run in Windows, you can download and install the source version with the following command (I'll assume you already have Python and setuptools installed and working): \neasy_i... | [
0
] | [] | [] | [
"easy_install",
"python",
"turbogears"
] | stackoverflow_0001626619_easy_install_python_turbogears.txt |
Q:
How to convert dumbo sequence file input to tab separated text
I have in input, which could be a single primitive or a list or tuple of primitives.
I'd like to flatten it to just a list, like so:
def flatten(values):
return list(values)
The normal case would be flatten(someiterablethatisn'tastring)
But if val... | How to convert dumbo sequence file input to tab separated text | I have in input, which could be a single primitive or a list or tuple of primitives.
I'd like to flatten it to just a list, like so:
def flatten(values):
return list(values)
The normal case would be flatten(someiterablethatisn'tastring)
But if values = '1234', I'd get ['1', '2', '3', '4'], but I'd want ['1234']
An... | [
"Sounds like you want itertools.chain(). You will need to special-case strings, though, since they are really just iterables of characters.\nUpdate:\nThis is a much simpler problem if you do it as a recursive generator. Try this:\ndef flatten(*seq):\n for item in seq:\n if isinstance(item, basestring):\... | [
3,
1,
0
] | [] | [] | [
"hadoop",
"python",
"text"
] | stackoverflow_0001625757_hadoop_python_text.txt |
Q:
Would it be a good idea or bad idea to connect a VB.NET frontend with a Python backend using sockets?
I have some really nice Python code to do what I need to do. I don't particularly like any of the Python GUI choices though. wxPython is nice, but for what I need, the speed on resizing, refreshing and dynamically... | Would it be a good idea or bad idea to connect a VB.NET frontend with a Python backend using sockets? | I have some really nice Python code to do what I need to do. I don't particularly like any of the Python GUI choices though. wxPython is nice, but for what I need, the speed on resizing, refreshing and dynamically adding controls just isn't there. I would like to create the GUI in VB.NET. I imagine I could use IronPyth... | [
"It's not a terrible idea. In fact, if you write the Python code to have a RESTful interface, and then access that from VB.NET, it is a downright good idea. Later on you could reuse that Python server from any other application written in Python or VB.NET or something else. Because REST is standard and easy to test... | [
1,
0
] | [] | [] | [
"python",
"sockets",
"user_interface",
"vb.net"
] | stackoverflow_0001626631_python_sockets_user_interface_vb.net.txt |
Q:
How do I extract a ieee-be binary file embedded in a zipfile?
I have a set of zip files which contains several ieee-be encoded binary and text files. I have used Pythons ZipFile module and can extract the contents of the text file
def readPropFile(myZipFile):
zf = zipfile.ZipFile(myZipFile,'r') # Open zip file... | How do I extract a ieee-be binary file embedded in a zipfile? | I have a set of zip files which contains several ieee-be encoded binary and text files. I have used Pythons ZipFile module and can extract the contents of the text file
def readPropFile(myZipFile):
zf = zipfile.ZipFile(myZipFile,'r') # Open zip file for reading
zFileList=zf.namelist() # extract list of files em... | [
"Most of what you need is in this answer How do I convert a Python float to a hexadecimal string in python 2.5? Nonworking solution attached\nSee the stuff about struct.pack.\nMore details on struct are in the Python docs\n",
"You could also try the Numpy extension (here), which is a bit lighter than SciPy. Nump... | [
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001627376_python.txt |
Q:
Problem in importing classes from models file in GAE
I am very new to python and after a brief intro on to python + Google app engine, I've started to work on a pilot project. I have bulkloaded 2 entities UserDetails and PhoneBook with data onto the app engine. Now in my UI I try to first take in the user name the... | Problem in importing classes from models file in GAE | I am very new to python and after a brief intro on to python + Google app engine, I've started to work on a pilot project. I have bulkloaded 2 entities UserDetails and PhoneBook with data onto the app engine. Now in my UI I try to first take in the user name then query it to get the user id from UserDetails, then using... | [
"The first error you're getting occurs when it can import the module ('models') fine, but can't find the member ('UserDetails') in it. This would generally be the case if you'd mistyped the name of the class, or hadn't defined it in that module.\nThe second error is expected, because you're importing the 'models' m... | [
1,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0001623941_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python, Perl And C/C++ With GUI
I'm now thinking, is it possible to integrate Python, Perl and C/C++ and also doing a GUI application with this very nice mix of languages?
A:
Well, there is Wx, Inline::Python and Inline::C, but the question is why?
A:
Anything is "possible", but whether it is necessary or ben... | Python, Perl And C/C++ With GUI | I'm now thinking, is it possible to integrate Python, Perl and C/C++ and also doing a GUI application with this very nice mix of languages?
| [
"Well, there is Wx, Inline::Python and Inline::C, but the question is why?\n",
"Anything is \"possible\", but whether it is necessary or beneficial is debatable and highly depends on your requirements. Don't mix if you don't need to. Use the language that best fits the domain or target requirements. \nI can't th... | [
9,
5,
3,
1,
1
] | [] | [] | [
"c",
"c++",
"integration",
"perl",
"python"
] | stackoverflow_0001628001_c_c++_integration_perl_python.txt |
Q:
Can someone explain this unexpected Python import behavior?
I've run into some behavior from Python 2.6.1 that I didn't expect. Here is some trivial code to reproduce the problem:
---- ControlPointValue.py ------
class ControlPointValue:
def __init__(self):
pass
---- ControlPointValueSet.py ----
import ... | Can someone explain this unexpected Python import behavior? | I've run into some behavior from Python 2.6.1 that I didn't expect. Here is some trivial code to reproduce the problem:
---- ControlPointValue.py ------
class ControlPointValue:
def __init__(self):
pass
---- ControlPointValueSet.py ----
import ControlPointValue
---- main.py --------------------
from Control... | [
"I don't think it's unexpected. What you are basically doing is:\n1) the first import in main.py imports the contents of ControlPointValue module into the global namespace. this produces a class bound to that name.\n2) the second import in main.py imports the contents of ControlPointValueSet module into the global ... | [
10,
4
] | [] | [] | [
"import",
"python"
] | stackoverflow_0001628085_import_python.txt |
Q:
The advantages of having static function like len(), max(), and min() over inherited method calls
i am a python newbie, and i am not sure why python implemented len(obj), max(obj), and min(obj) as a static like functions (i am from the java language) over obj.len(), obj.max(), and obj.min()
what are the advantages... | The advantages of having static function like len(), max(), and min() over inherited method calls | i am a python newbie, and i am not sure why python implemented len(obj), max(obj), and min(obj) as a static like functions (i am from the java language) over obj.len(), obj.max(), and obj.min()
what are the advantages and disadvantages (other than obvious inconsistency) of having len()... over the method calls?
why gui... | [
"The big advantage is that built-in functions (and operators) can apply extra logic when appropriate, beyond simply calling the special methods. For example, min can look at several arguments and apply the appropriate inequality checks, or it can accept a single iterable argument and proceed similarly; abs when ca... | [
20,
3,
3,
1
] | [] | [] | [
"language_design",
"python"
] | stackoverflow_0001628222_language_design_python.txt |
Q:
Python mkdir giving me wrong permissions
I'm trying to create a folder and create a file within it.
Whenever i create that folder (via Python), it creates a folder that gives me no permissions at all and read-only mode.
When i try to create the file i get an IOError.
Error: <type 'exceptions.IOError'>
I tried cr... | Python mkdir giving me wrong permissions | I'm trying to create a folder and create a file within it.
Whenever i create that folder (via Python), it creates a folder that gives me no permissions at all and read-only mode.
When i try to create the file i get an IOError.
Error: <type 'exceptions.IOError'>
I tried creating (and searching) for a description of al... | [
"After you create the folder you can set the permissions with os.chmod\nThe mod is written in base 8, if you convert it to binary it would be\n000 111 111 000\n rwx rwx rwx\n\nThe first rwx is for owner, the second is for the group and the third is for world \nr=read,w=write,x=execute\nThe permissions you see m... | [
23,
5,
3,
1
] | [] | [] | [
"filesystems",
"mkdir",
"python",
"windows"
] | stackoverflow_0001627198_filesystems_mkdir_python_windows.txt |
Q:
SimpleParse non-deterministic grammar until runtime
I'm working on a basic networking protocol in Python, which should be able to transfer both ASCII strings (read: EOL-terminated) and binary data.
For the latter to be possible, I chose to create the grammar such that it contains the number of bytes to come which ... | SimpleParse non-deterministic grammar until runtime | I'm working on a basic networking protocol in Python, which should be able to transfer both ASCII strings (read: EOL-terminated) and binary data.
For the latter to be possible, I chose to create the grammar such that it contains the number of bytes to come which are going to be binary.
For SimpleParse, the grammar woul... | [
"If the grammar is as simple as the one you quoted, then perhaps using a parser generator is overkill? You might find that rolling your own recursive parser by hand is simpler and quicker.\n",
"If you want your application to be portable and reliable I would suggest you pass only standard ASCII characters over th... | [
4,
1,
0
] | [] | [] | [
"parsing",
"python",
"text_parsing"
] | stackoverflow_0001537708_parsing_python_text_parsing.txt |
Q:
Using the same handler for multiple wx.TextCtrls?
I'm having a bit of trouble with a panel that has two wxPython TextCtrls in it. I want either an EVT_CHAR or EVT_KEY_UP handler bound to both controls, and I want to be able to tell which TextCtrl generated the event. I would think that event.Id would tell me this,... | Using the same handler for multiple wx.TextCtrls? | I'm having a bit of trouble with a panel that has two wxPython TextCtrls in it. I want either an EVT_CHAR or EVT_KEY_UP handler bound to both controls, and I want to be able to tell which TextCtrl generated the event. I would think that event.Id would tell me this, but in the following sample code it's always 0. Any th... | [
"You could try event.GetId() or event.GetEventObject() and see if either of these work.\nAnother approach to this is to use lambda or functools.partial to effectively pass a parameter to the handler. So, for example, sub in the lines below into your program:\n self.entry.Bind(wx.EVT_KEY_UP, functools.partia... | [
4
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001628010_python_wxpython.txt |
Q:
chaining queries together in Django
I have a query that gets me 32 avatar images from my avatar application:
newUserAv = Avatar.objects.filter(valid=True)[:32]
I'd like to combine this with a query to django's Auth user model, so I can get the last the last 32 people, who have avatar images, sorted by the date jo... | chaining queries together in Django | I have a query that gets me 32 avatar images from my avatar application:
newUserAv = Avatar.objects.filter(valid=True)[:32]
I'd like to combine this with a query to django's Auth user model, so I can get the last the last 32 people, who have avatar images, sorted by the date joined.
What is the best way to chain these... | [
"Either you put a field in your own User class (you might have to subclass User or compose with django.contrib.auth.models.User) that indicates that the User has an avatar. Than you can make your query easily.\nOr do something like that:\nfrom django.utils.itercompat import groupby\navatars = Avatar.objects.select_... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001628162_django_django_models_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.