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:
How to make two elements in gtk have the same size?
I'm using pyGTK. I want to layout a large element with 2 smaller ones on each side. For aesthetic reasons, I want the 2 smaller ones to be the same size. As it is, they differ by a few pixels, and the middle element is not centered as a result.
I tried using gtk.Table with 3 cells, but having homogeneous=True doesn't have the desired effect. I tried messing with it by making 8 cells, and then having the center one take up more cells, but it doesn't work well. Is there any way to do this?
A:
You should use GtkSizeGroup for this. Create a GtkSizeGroup, add both widgets to it. This will ensure that both widgets have the same size. If you want that widget have the same size in only one direction (width or height), set the "mode" property of SizeGroup.
|
How to make two elements in gtk have the same size?
|
I'm using pyGTK. I want to layout a large element with 2 smaller ones on each side. For aesthetic reasons, I want the 2 smaller ones to be the same size. As it is, they differ by a few pixels, and the middle element is not centered as a result.
I tried using gtk.Table with 3 cells, but having homogeneous=True doesn't have the desired effect. I tried messing with it by making 8 cells, and then having the center one take up more cells, but it doesn't work well. Is there any way to do this?
|
[
"You should use GtkSizeGroup for this. Create a GtkSizeGroup, add both widgets to it. This will ensure that both widgets have the same size. If you want that widget have the same size in only one direction (width or height), set the \"mode\" property of SizeGroup.\n"
] |
[
6
] |
[] |
[] |
[
"gtk",
"layout",
"pygtk",
"python"
] |
stackoverflow_0001229933_gtk_layout_pygtk_python.txt
|
Q:
Can anyone explain this strange python turtle occurance?
If you don't know, python turtle is an application for helping people learn python.
You are given a python interpreter and an onscreen turtle that you can pass directions to using python.
go(10) will cause the turtle to move 10 pixels
turn(10) will cause it to turn 10 degrees clockwise
now look at this
code:
import random
while(1):
r = random.randint(1,10)
go (r)
r = random.randint(-90,90)
turn (r)
can anyone explain this behavior? Notice the straight line. Is there something wrong with pythons random module?
A:
When debugging a problem like this, it might be worthwhile to print out the value of each instruction as you perform it. Hopefully your turtle environment has a way to print values to some window on the screen. You might do something like this:
while(1):
r = random.randint(1,10)
print "going:", r
go (r)
r = random.randint(-90, 90)
print "turning:", r
turn (r)
This technique goes by many names, but the one I like is "When in doubt, print more out." Doing this may provide some insight into why your turtle is showing the behaviour you see.
A:
I am the creator of PythonTurtle.
First of all, I'm really honored to see the first question about it in StackOverflow.
About your question: I tried running the code, and it didn't produce the bug, but since this is involving randomness, I can't really reproduce what happened in your computer.
It seems like a bug, but I can't really guess what is causing it. If this kind of bug happens to you again, preferably when randomness is not involved, I'd appreciate if you'll send me the screenshot and the code snippet. My mail is [email protected].
A:
Try printing out the values. Here's a little Python program based on your code snippet that does this:
import random
while(1):
distance = random.randint(1,10)
angle = random.randint(-90, 90)
print distance, angle
I tried this myself, and at no point does angle "get stuck". I suspect there may be some sort of bug in python turtle, but without trying out in that environment it's hard to say for sure.
Is there a way to ask python turtle for the current angle of the turtle? You may want to print that value out as well.
|
Can anyone explain this strange python turtle occurance?
|
If you don't know, python turtle is an application for helping people learn python.
You are given a python interpreter and an onscreen turtle that you can pass directions to using python.
go(10) will cause the turtle to move 10 pixels
turn(10) will cause it to turn 10 degrees clockwise
now look at this
code:
import random
while(1):
r = random.randint(1,10)
go (r)
r = random.randint(-90,90)
turn (r)
can anyone explain this behavior? Notice the straight line. Is there something wrong with pythons random module?
|
[
"When debugging a problem like this, it might be worthwhile to print out the value of each instruction as you perform it. Hopefully your turtle environment has a way to print values to some window on the screen. You might do something like this:\nwhile(1):\n r = random.randint(1,10)\n print \"going:\", r\n go (r)\n r = random.randint(-90, 90)\n print \"turning:\", r\n turn (r)\n\nThis technique goes by many names, but the one I like is \"When in doubt, print more out.\" Doing this may provide some insight into why your turtle is showing the behaviour you see.\n",
"I am the creator of PythonTurtle.\nFirst of all, I'm really honored to see the first question about it in StackOverflow.\nAbout your question: I tried running the code, and it didn't produce the bug, but since this is involving randomness, I can't really reproduce what happened in your computer.\nIt seems like a bug, but I can't really guess what is causing it. If this kind of bug happens to you again, preferably when randomness is not involved, I'd appreciate if you'll send me the screenshot and the code snippet. My mail is [email protected].\n",
"Try printing out the values. Here's a little Python program based on your code snippet that does this:\nimport random\nwhile(1):\n distance = random.randint(1,10)\n angle = random.randint(-90, 90)\n print distance, angle\n\nI tried this myself, and at no point does angle \"get stuck\". I suspect there may be some sort of bug in python turtle, but without trying out in that environment it's hard to say for sure.\nIs there a way to ask python turtle for the current angle of the turtle? You may want to print that value out as well.\n"
] |
[
7,
1,
0
] |
[] |
[] |
[
"python",
"random"
] |
stackoverflow_0001224944_python_random.txt
|
Q:
Decode complex JSON in Python
I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:
php > $insidejson = array('foo' => 'bar','foo1' => 'bar1');
php > $arr = array('a' => array('a1'=>json_encode($insidejson)));
php > echo json_encode($arr);
{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}
Then, with Python, I try deocding it using simplejson:
>>> import simplejson as json
>>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}')
This fails with the following error:
Traceback (most recent call last):
File "", line 1, in ?
File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads
File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode
File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode
ValueError: Expecting , delimiter: line 1 column 14 (char 14)
How can I get this JSON object decoded in Python? Both PHP and JS decode it successfully and I can't change it's structure since that would require major changes in many different components in different languages.
Thanks!
A:
Try prefixing your string with 'r' to make it a raw string:
# Python 2.6.2
>>> import json
>>> s = r'{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}'
>>> json.loads(s)
{u'a': {u'a1': u'{"foo":"bar","foo1":"bar1"}'}}
What Alex says below is true: you can just double the slashes. (His answer was not posted when I started mine.) I think that using raw strings is simpler, if only because it's a language feature that means the same thing and it's harder to get wrong.
A:
Try
The Python Standard Library
jyson
Maybe simplejson is too much "simple".
A:
If you want to insert backslashes into a string they need escaping themselves.
import simplejson as json
json.loads('{"a":{"a1":"{\\"foo\\":\\"bar\\",\\"foo1\\":\\"bar1\\"}"}}')
I've tested it and Python handles that input just fine - except I used the json module included in the standard library (import json, Python 3.1).
|
Decode complex JSON in Python
|
I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:
php > $insidejson = array('foo' => 'bar','foo1' => 'bar1');
php > $arr = array('a' => array('a1'=>json_encode($insidejson)));
php > echo json_encode($arr);
{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}
Then, with Python, I try deocding it using simplejson:
>>> import simplejson as json
>>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}')
This fails with the following error:
Traceback (most recent call last):
File "", line 1, in ?
File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads
File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode
File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode
ValueError: Expecting , delimiter: line 1 column 14 (char 14)
How can I get this JSON object decoded in Python? Both PHP and JS decode it successfully and I can't change it's structure since that would require major changes in many different components in different languages.
Thanks!
|
[
"Try prefixing your string with 'r' to make it a raw string:\n# Python 2.6.2\n>>> import json\n>>> s = r'{\"a\":{\"a1\":\"{\\\"foo\\\":\\\"bar\\\",\\\"foo1\\\":\\\"bar1\\\"}\"}}'\n>>> json.loads(s)\n{u'a': {u'a1': u'{\"foo\":\"bar\",\"foo1\":\"bar1\"}'}}\n\nWhat Alex says below is true: you can just double the slashes. (His answer was not posted when I started mine.) I think that using raw strings is simpler, if only because it's a language feature that means the same thing and it's harder to get wrong.\n",
"Try \n\nThe Python Standard Library\njyson\n\nMaybe simplejson is too much \"simple\".\n",
"If you want to insert backslashes into a string they need escaping themselves.\nimport simplejson as json\njson.loads('{\"a\":{\"a1\":\"{\\\\\"foo\\\\\":\\\\\"bar\\\\\",\\\\\"foo1\\\\\":\\\\\"bar1\\\\\"}\"}}')\n\nI've tested it and Python handles that input just fine - except I used the json module included in the standard library (import json, Python 3.1).\n"
] |
[
9,
1,
1
] |
[] |
[] |
[
"json",
"php",
"python",
"simplejson"
] |
stackoverflow_0001230347_json_php_python_simplejson.txt
|
Q:
Does Django have a built in way of getting the last app url the current user visited?
I was hoping that Django had a built in way of getting the last url that was visited in the app itself. As I write this I realize that there are some complications in doing something like that (excluding pages that redirect, for example) but i thought I'd give it a shot.
if there isn't a built-in for this, what strategy would you use? I mean other than just storing a url in the session manually and referring to that when redirecting. That would work, of course, but I hate the thought of having to remember to do that for each view. Seems error-prone and not very elegant.
Oh, and I'd rather not depend on server specific referral environment variables.
A:
No, there is nothing like that built in to Django core (and it's not built in because it isn't a common usage pattern).
Like Javier suggested, you could make some middleware which does what you want. Something like this:
class PreviousURLMiddleware(object):
def process_response(request, response):
if response.status_code == 200:
request.session['previous_url'] = request.get_full_url()
return response
This middleware would have to go after SessionMiddleware in your settings to ensure that the session will be updated after this (the docs have a pretty picture explaining why this is).
A:
you can just write a middleware that does exactly that, no need to repeat logging code on every view function.
|
Does Django have a built in way of getting the last app url the current user visited?
|
I was hoping that Django had a built in way of getting the last url that was visited in the app itself. As I write this I realize that there are some complications in doing something like that (excluding pages that redirect, for example) but i thought I'd give it a shot.
if there isn't a built-in for this, what strategy would you use? I mean other than just storing a url in the session manually and referring to that when redirecting. That would work, of course, but I hate the thought of having to remember to do that for each view. Seems error-prone and not very elegant.
Oh, and I'd rather not depend on server specific referral environment variables.
|
[
"No, there is nothing like that built in to Django core (and it's not built in because it isn't a common usage pattern).\nLike Javier suggested, you could make some middleware which does what you want. Something like this:\nclass PreviousURLMiddleware(object):\n def process_response(request, response):\n if response.status_code == 200:\n request.session['previous_url'] = request.get_full_url()\n return response\n\nThis middleware would have to go after SessionMiddleware in your settings to ensure that the session will be updated after this (the docs have a pretty picture explaining why this is).\n",
"you can just write a middleware that does exactly that, no need to repeat logging code on every view function.\n"
] |
[
5,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001230392_django_python.txt
|
Q:
XML Parsing in Python using document builder factory
I am working in STAF and STAX. Here python is used for coding . I am new to python.
Basically my task is to parse a XML file in python using Document Factory Parser.
The XML file I am trying to parse is :
<?xml version="1.0" encoding="utf-8"?>
<operating_system>
<unix_80sp1>
<tests type="quick_sanity_test">
<prerequisitescript>preparequicksanityscript</prerequisitescript>
<acbuildpath>acbuildpath</acbuildpath>
<testsuitscript>test quick sanity script</testsuitscript>
<testdir>quick sanity dir</testdir>
</tests>
<machine_name>u80sp1_L004</machine_name>
<machine_name>u80sp1_L005</machine_name>
<machine_name>xyz.pxy.dxe.cde</machine_name>
<vmware id="155.35.3.55">144.35.3.90</vmware>
<vmware id="155.35.3.56">144.35.3.91</vmware>
</unix_80sp1>
</operating_system>
I need to read all the tags .
For the tags machine_name i need to read them into a list
say all machine names should be in a list machname.
so machname should be [u80sp1_L004,u80sp1_L005,xyz.pxy.dxe.cde] after reading the tags.
I also need all the vmware tags:
all attributes should be vmware_attr =[155.35.3.55,155.35.3.56]
all vmware values should be vmware_value = [ 144.35.3.90,155.35.3.56]
I am able to read all tags properly except vmware tags and machine name tags:
I am using the following code:(i am new to xml and vmware).Help required.
The below code needs to be modified.
factory = DocumentBuilderFactory.newInstance();
factory.setValidating(1)
factory.setIgnoringElementContentWhitespace(0)
builder = factory.newDocumentBuilder()
document = builder.parse(xmlFileName)
vmware_value = None
vmware_attr = None
machname = None
# Get the text value for the element with tag name "vmware"
nodeList = document.getElementsByTagName("vmware")
for i in range(nodeList.getLength()):
node = nodeList.item(i)
if node.getNodeType() == Node.ELEMENT_NODE:
children = node.getChildNodes()
for j in range(children.getLength()):
thisChild = children.item(j)
if (thisChild.getNodeType() == Node.TEXT_NODE):
vmware_value = thisChild.getNodeValue()
vmware_attr ==??? what method to use ?
# Get the text value for the element with tag name "machine_name"
nodeList = document.getElementsByTagName("machine_name")
for i in range(nodeList.getLength()):
node = nodeList.item(i)
if node.getNodeType() == Node.ELEMENT_NODE:
children = node.getChildNodes()
for j in range(children.getLength()):
thisChild = children.item(j)
if (thisChild.getNodeType() == Node.TEXT_NODE):
machname = thisChild.getNodeValue()
Also how to check if a tag exists or not at all. I need to code the parsing properly.
A:
You are need to instantiate vmware_value, vmware_attr and machname as lists not as strings, so instead of this:
vmware_value = None
vmware_attr = None
machname = None
do this:
vmware_value = []
vmware_attr = []
machname = []
Then, to add items to the list, use the append method on your lists. E.g.:
factory = DocumentBuilderFactory.newInstance();
factory.setValidating(1)
factory.setIgnoringElementContentWhitespace(0)
builder = factory.newDocumentBuilder()
document = builder.parse(xmlFileName)
vmware_value = []
vmware_attr = []
machname = []
# Get the text value for the element with tag name "vmware"
nodeList = document.getElementsByTagName("vmware")
for i in range(nodeList.getLength()):
node = nodeList.item(i)
vmware_attr.append(node.attributes["id"].value)
if node.getNodeType() == Node.ELEMENT_NODE:
children = node.getChildNodes()
for j in range(children.getLength()):
thisChild = children.item(j)
if (thisChild.getNodeType() == Node.TEXT_NODE):
vmware_value.append(thisChild.getNodeValue())
I've also edited the code to something I think should work to append the correct values to vmware_attr and vmware_value.
I had to make the assumption that STAX uses xml.dom syntax, so if that isn't the case, you will have to edit my suggestion appropriately.
|
XML Parsing in Python using document builder factory
|
I am working in STAF and STAX. Here python is used for coding . I am new to python.
Basically my task is to parse a XML file in python using Document Factory Parser.
The XML file I am trying to parse is :
<?xml version="1.0" encoding="utf-8"?>
<operating_system>
<unix_80sp1>
<tests type="quick_sanity_test">
<prerequisitescript>preparequicksanityscript</prerequisitescript>
<acbuildpath>acbuildpath</acbuildpath>
<testsuitscript>test quick sanity script</testsuitscript>
<testdir>quick sanity dir</testdir>
</tests>
<machine_name>u80sp1_L004</machine_name>
<machine_name>u80sp1_L005</machine_name>
<machine_name>xyz.pxy.dxe.cde</machine_name>
<vmware id="155.35.3.55">144.35.3.90</vmware>
<vmware id="155.35.3.56">144.35.3.91</vmware>
</unix_80sp1>
</operating_system>
I need to read all the tags .
For the tags machine_name i need to read them into a list
say all machine names should be in a list machname.
so machname should be [u80sp1_L004,u80sp1_L005,xyz.pxy.dxe.cde] after reading the tags.
I also need all the vmware tags:
all attributes should be vmware_attr =[155.35.3.55,155.35.3.56]
all vmware values should be vmware_value = [ 144.35.3.90,155.35.3.56]
I am able to read all tags properly except vmware tags and machine name tags:
I am using the following code:(i am new to xml and vmware).Help required.
The below code needs to be modified.
factory = DocumentBuilderFactory.newInstance();
factory.setValidating(1)
factory.setIgnoringElementContentWhitespace(0)
builder = factory.newDocumentBuilder()
document = builder.parse(xmlFileName)
vmware_value = None
vmware_attr = None
machname = None
# Get the text value for the element with tag name "vmware"
nodeList = document.getElementsByTagName("vmware")
for i in range(nodeList.getLength()):
node = nodeList.item(i)
if node.getNodeType() == Node.ELEMENT_NODE:
children = node.getChildNodes()
for j in range(children.getLength()):
thisChild = children.item(j)
if (thisChild.getNodeType() == Node.TEXT_NODE):
vmware_value = thisChild.getNodeValue()
vmware_attr ==??? what method to use ?
# Get the text value for the element with tag name "machine_name"
nodeList = document.getElementsByTagName("machine_name")
for i in range(nodeList.getLength()):
node = nodeList.item(i)
if node.getNodeType() == Node.ELEMENT_NODE:
children = node.getChildNodes()
for j in range(children.getLength()):
thisChild = children.item(j)
if (thisChild.getNodeType() == Node.TEXT_NODE):
machname = thisChild.getNodeValue()
Also how to check if a tag exists or not at all. I need to code the parsing properly.
|
[
"You are need to instantiate vmware_value, vmware_attr and machname as lists not as strings, so instead of this:\nvmware_value = None\nvmware_attr = None\nmachname = None\n\ndo this:\nvmware_value = []\nvmware_attr = []\nmachname = []\n\nThen, to add items to the list, use the append method on your lists. E.g.:\nfactory = DocumentBuilderFactory.newInstance();\nfactory.setValidating(1)\nfactory.setIgnoringElementContentWhitespace(0)\nbuilder = factory.newDocumentBuilder()\ndocument = builder.parse(xmlFileName)\n\nvmware_value = []\nvmware_attr = []\nmachname = []\n\n# Get the text value for the element with tag name \"vmware\"\nnodeList = document.getElementsByTagName(\"vmware\")\nfor i in range(nodeList.getLength()):\n node = nodeList.item(i)\n vmware_attr.append(node.attributes[\"id\"].value)\n if node.getNodeType() == Node.ELEMENT_NODE:\n children = node.getChildNodes()\n for j in range(children.getLength()):\n thisChild = children.item(j)\n if (thisChild.getNodeType() == Node.TEXT_NODE):\n vmware_value.append(thisChild.getNodeValue())\n\nI've also edited the code to something I think should work to append the correct values to vmware_attr and vmware_value.\nI had to make the assumption that STAX uses xml.dom syntax, so if that isn't the case, you will have to edit my suggestion appropriately.\n"
] |
[
0
] |
[] |
[] |
[
"parsing",
"python",
"xml"
] |
stackoverflow_0001229507_parsing_python_xml.txt
|
Q:
Need to make multiple files from a single excel file
I have a excel file. With many columns . I need to make multiple files using this
Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others.
Thank you all for ur reply. To simplify the question:
I have a excel file as i mentioned with number of columns and rows. The columns are named as
alt text http://img44.imageshack.us/img44/3397/84200961244pm.png
Now I need to split this file into many excel files the 1st will have
A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on.
A:
You can use Spreadsheet::ParseExcel to read a spreadsheet. Unfortunately that is all I can help you with because, frankly, the description of your problem makes no sense.
A:
Use Python and xlrd & xlwt. See http://www.python-excel.org
The following script should do what you want:
import xlrd, xlwt, sys
def raj_split(in_path, out_stem):
in_book = xlrd.open_workbook(in_path)
in_sheet = in_book.sheet_by_index(0)
first_row = in_sheet.row_values(0)
# find the rightmost 1 value in the first row
split_pos = max(
colx for colx, value in enumerate(first_row) if value == 1.0
) + 1
out_book = xlwt.Workbook()
out_sheet = out_book.add_sheet("Sheet1", cell_overwrite_ok=True)
# copy the common cells
for rowx in xrange(in_sheet.nrows):
row_vals = in_sheet.row_values(rowx, end_colx=split_pos)
for colx in xrange(split_pos):
out_sheet.write(rowx, colx, row_vals[colx])
out_num = 0
# for each output file ...
for out_col in range(split_pos, in_sheet.ncols):
out_num += 1
# ... overwrite the `split_pos` column
for rowx, value in enumerate(in_sheet.col_values(colx=out_col)):
out_sheet.write(rowx, split_pos, value)
# ... and save the file.
out_book.save("%s_%03d.xls" % (out_stem, out_num))
raj_split(*sys.argv[1:3])
A:
In python, you can use xlrd to read an Excel spreadsheet into data you can work with. See the README for sample usage. You can then use xlwt to create new spreadsheets.
A:
in Excel, save your file as CSV.
in Python, use the CSV reader module to read it (read the python docs, search for csv)
now you say you have rows of maybe 20 columns and you want to put columns 1..10 in file A and columns 11..20 in file B, yes ?
open 2 csv writers (let's call them A and B)
you will read rows :
for row in csvreader:
A.writerow( row[:10 ] )
B.writerow( row[11: ] )
that's it.
go here :
How can I merge fields in a CSV string using Python?
A:
As others have commented your question is almost totally incomprehensible. Based on the difficulty you have describing your issue, you might want to take a look at
this post.
Some here have suggested saving your file as a CSV. Saving your file as a CSV file will greatly simplify the job of parsing it, but it will make converting to and from excel format a manual process. This may be acceptable if you have a small number of files to process. If you have hundreds, it won't work so well.
The Spreadsheet::ParseExcel and Spreadsheet::WriteExcel modules will help your read and write your spreadsheet file in native format.
The Text::CSV_XS module provides a powerful, fast CSV parser for perl.
A:
I think the xlrd and xlwt modules are the way to go in Python.
# Read the first 5 rows and columns of an excel file
import xlrd # Import the package
book = xlrd.open_workbook("sample.xls") # Open an .xls file
sheet = book.sheet_by_index(0) # Get the first sheet
for row in range(5): # Loop for five times (five rows)
# grab the current row
rowValues = sheet.row_values(row, start_col=0, end_colx=4)
# Do magic here, like printing
import xlrd # Import the package
print "%-10s | %-10s | %-10s | %-10s | %-10s" % tuple(rowValues)
Now if you feel like writing back Excel files...
import xlwt # Import the package
wbook = xlwt.Workbook() # Create a new workbook
sheet = wbook.add_sheet("Sample Sheet") # Create a sheet
data = "Sample data" # Something to write into the sheet
for rowx in range(5):
# Loop through the first five rows
for colx in range(5):
# Loop through the first five columns
# Write the data to rox, column
sheet.write(rowx, colx, data)
# Save our workbook on the harddrive
wbook.save(&quot;myFile.xls&quot;)
I have used this method in the part extensively to read/write data from Excel files for Input/Output models to use in NetworkX. The above examples are from my blog entries talking about that adventure.
As I am a new user, I can only post one link. Maybe you can Google xlwt? :)
|
Need to make multiple files from a single excel file
|
I have a excel file. With many columns . I need to make multiple files using this
Eg: 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2. So these are the excel columns with each having many rows. I need one file which would contain 0 0 0 0 0 1 1 1 1 1 2 then second will contain only the second no 0 0 0 0 0 1 1 1 1 1 2....similarly the others.
Thank you all for ur reply. To simplify the question:
I have a excel file as i mentioned with number of columns and rows. The columns are named as
alt text http://img44.imageshack.us/img44/3397/84200961244pm.png
Now I need to split this file into many excel files the 1st will have
A to O columns with all rows. The second will have A to N + P(this will not have columns O) and similarly the other 2. There will be like many columns with 2 and i will have to make a file containg all the columns containing O and 1 and each 2 at a time. i.e 1st 2 then the 2nd 2 and so on.
|
[
"You can use Spreadsheet::ParseExcel to read a spreadsheet. Unfortunately that is all I can help you with because, frankly, the description of your problem makes no sense.\n",
"Use Python and xlrd & xlwt. See http://www.python-excel.org\nThe following script should do what you want:\nimport xlrd, xlwt, sys\n\ndef raj_split(in_path, out_stem):\n in_book = xlrd.open_workbook(in_path)\n in_sheet = in_book.sheet_by_index(0)\n first_row = in_sheet.row_values(0)\n # find the rightmost 1 value in the first row\n split_pos = max(\n colx for colx, value in enumerate(first_row) if value == 1.0\n ) + 1\n out_book = xlwt.Workbook()\n out_sheet = out_book.add_sheet(\"Sheet1\", cell_overwrite_ok=True)\n # copy the common cells\n for rowx in xrange(in_sheet.nrows):\n row_vals = in_sheet.row_values(rowx, end_colx=split_pos)\n for colx in xrange(split_pos):\n out_sheet.write(rowx, colx, row_vals[colx])\n out_num = 0\n # for each output file ...\n for out_col in range(split_pos, in_sheet.ncols):\n out_num += 1\n # ... overwrite the `split_pos` column\n for rowx, value in enumerate(in_sheet.col_values(colx=out_col)):\n out_sheet.write(rowx, split_pos, value)\n # ... and save the file.\n out_book.save(\"%s_%03d.xls\" % (out_stem, out_num))\n\nraj_split(*sys.argv[1:3])\n\n",
"In python, you can use xlrd to read an Excel spreadsheet into data you can work with. See the README for sample usage. You can then use xlwt to create new spreadsheets.\n",
"in Excel, save your file as CSV.\nin Python, use the CSV reader module to read it (read the python docs, search for csv)\nnow you say you have rows of maybe 20 columns and you want to put columns 1..10 in file A and columns 11..20 in file B, yes ?\nopen 2 csv writers (let's call them A and B)\nyou will read rows :\nfor row in csvreader:\n A.writerow( row[:10 ] )\n B.writerow( row[11: ] )\nthat's it.\ngo here :\nHow can I merge fields in a CSV string using Python?\n",
"As others have commented your question is almost totally incomprehensible. Based on the difficulty you have describing your issue, you might want to take a look at \nthis post.\nSome here have suggested saving your file as a CSV. Saving your file as a CSV file will greatly simplify the job of parsing it, but it will make converting to and from excel format a manual process. This may be acceptable if you have a small number of files to process. If you have hundreds, it won't work so well. \nThe Spreadsheet::ParseExcel and Spreadsheet::WriteExcel modules will help your read and write your spreadsheet file in native format.\nThe Text::CSV_XS module provides a powerful, fast CSV parser for perl.\n",
"I think the xlrd and xlwt modules are the way to go in Python.\n# Read the first 5 rows and columns of an excel file\nimport xlrd # Import the package\nbook = xlrd.open_workbook(\"sample.xls\") # Open an .xls file\nsheet = book.sheet_by_index(0) # Get the first sheet\nfor row in range(5): # Loop for five times (five rows)\n # grab the current row\n rowValues = sheet.row_values(row, start_col=0, end_colx=4)\n # Do magic here, like printing\n import xlrd # Import the package\n print \"%-10s | %-10s | %-10s | %-10s | %-10s\" % tuple(rowValues)\n\nNow if you feel like writing back Excel files...\nimport xlwt # Import the package\nwbook = xlwt.Workbook() # Create a new workbook\nsheet = wbook.add_sheet(\"Sample Sheet\") # Create a sheet\ndata = \"Sample data\" # Something to write into the sheet\nfor rowx in range(5):\n # Loop through the first five rows\n for colx in range(5):\n # Loop through the first five columns\n # Write the data to rox, column\n sheet.write(rowx, colx, data)\n# Save our workbook on the harddrive\nwbook.save(&quot;myFile.xls&quot;)\n\nI have used this method in the part extensively to read/write data from Excel files for Input/Output models to use in NetworkX. The above examples are from my blog entries talking about that adventure.\nAs I am a new user, I can only post one link. Maybe you can Google xlwt? :)\n"
] |
[
6,
2,
1,
1,
1,
0
] |
[
"You could use Visual Basic for Applications to loop over the cells and then save to a text file.\nOR\nSave the file as a comma separated value file and use perl or python to easily parse the lines. (split on the comma for columns, end of line character for rows)\n"
] |
[
-1
] |
[
"perl",
"python"
] |
stackoverflow_0001225550_perl_python.txt
|
Q:
python unittest assertRaises throws exception when assertRaises fails
I've got code where assertRaises throws an exception when assertRaises fails. I thought that if assertRaises fails then the test would fail and I'd get a report at the end that says the test failed. I wasn't expecting the exception to be thrown. Below is my code. I'm I doing something wrong? I'm using Python 2.6.2.
import unittest
class myClass:
def getName(self):
raise myExcOne, "my exception one"
#raise myExcTwo, "my exception two"
#return "a"
class myExcOne(Exception):
"exception one"
class myExcTwo(Exception):
"exception two"
class test_myClass(unittest.TestCase):
def setUp(self):
self.myClass = myClass()
def testgetNameEmpty(self):
#self.assertRaises(myExcOne,self.myClass.getName)
#self.assertRaises(myExcTwo,self.myClass.getName)
try:
self.assertRaises(myExcTwo,self.myClass.getName)
except Exception as e:
pass
if __name__ == "__main__":
#unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(test_myClass)
unittest.TextTestRunner(verbosity=2).run(suite)
A:
The code as posted is wrong. For a start, class myClass(): shoudl be class myClass:. Also if name == "main": should be:
if __name__ == "__main__":
unittest.main()
Apart from these problems, this fails because getName() is raising exception myExcOne and your test expects exception myExcTwo.
Here is some code that works. Please edit the code in your question so that it is easy for us to cut and paste it into a Python session:
import unittest
class myExcOne(Exception): "exception one"
class myExcTwo(Exception): "exception two"
class myClass:
def getName(self):
raise myExcTwo
class test_myClass(unittest.TestCase):
def setUp(self):
self.myClass = myClass()
def testgetNameEmpty(self):
#self.assertRaises(myExcOne,self.myClass.getName)
self.assertRaises(myExcTwo,self.myClass.getName)
if __name__ == "__main__":
unittest.main()
A:
Starting with an aside, the () after the classname in a class statement is perfectly correct in modern Python -- not an error at all.
On the meat of the issue, assertRaises(MyException, foo) is documented to propagate exceptions raised by calling foo() whose type is NOT a subclass of MyException -- it only catches MyException and subclasses thereof. As your code raises an exception of one type and your test expects one of a different unrelated type, the raised exception will then propagate, as per the docs of the unittest module, here, and I quote:
The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised.
And "is an error" means "propagates the other exception".
As you catch the exception propagating in your try/except block, you nullify the error, and there's nothing left for unittest to diagnose. If your purpose is to turn this error into a failure (a debatable strategy...), your except block should call self.fail.
|
python unittest assertRaises throws exception when assertRaises fails
|
I've got code where assertRaises throws an exception when assertRaises fails. I thought that if assertRaises fails then the test would fail and I'd get a report at the end that says the test failed. I wasn't expecting the exception to be thrown. Below is my code. I'm I doing something wrong? I'm using Python 2.6.2.
import unittest
class myClass:
def getName(self):
raise myExcOne, "my exception one"
#raise myExcTwo, "my exception two"
#return "a"
class myExcOne(Exception):
"exception one"
class myExcTwo(Exception):
"exception two"
class test_myClass(unittest.TestCase):
def setUp(self):
self.myClass = myClass()
def testgetNameEmpty(self):
#self.assertRaises(myExcOne,self.myClass.getName)
#self.assertRaises(myExcTwo,self.myClass.getName)
try:
self.assertRaises(myExcTwo,self.myClass.getName)
except Exception as e:
pass
if __name__ == "__main__":
#unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(test_myClass)
unittest.TextTestRunner(verbosity=2).run(suite)
|
[
"The code as posted is wrong. For a start, class myClass(): shoudl be class myClass:. Also if name == \"main\": should be:\nif __name__ == \"__main__\":\n unittest.main()\n\nApart from these problems, this fails because getName() is raising exception myExcOne and your test expects exception myExcTwo.\nHere is some code that works. Please edit the code in your question so that it is easy for us to cut and paste it into a Python session:\nimport unittest\n\nclass myExcOne(Exception): \"exception one\"\n\nclass myExcTwo(Exception): \"exception two\"\n\nclass myClass:\n def getName(self):\n raise myExcTwo\n\nclass test_myClass(unittest.TestCase):\n def setUp(self):\n self.myClass = myClass()\n def testgetNameEmpty(self):\n #self.assertRaises(myExcOne,self.myClass.getName)\n self.assertRaises(myExcTwo,self.myClass.getName)\n\nif __name__ == \"__main__\":\n unittest.main()\n\n",
"Starting with an aside, the () after the classname in a class statement is perfectly correct in modern Python -- not an error at all.\nOn the meat of the issue, assertRaises(MyException, foo) is documented to propagate exceptions raised by calling foo() whose type is NOT a subclass of MyException -- it only catches MyException and subclasses thereof. As your code raises an exception of one type and your test expects one of a different unrelated type, the raised exception will then propagate, as per the docs of the unittest module, here, and I quote:\n\nThe test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised.\n\nAnd \"is an error\" means \"propagates the other exception\".\nAs you catch the exception propagating in your try/except block, you nullify the error, and there's nothing left for unittest to diagnose. If your purpose is to turn this error into a failure (a debatable strategy...), your except block should call self.fail.\n"
] |
[
6,
6
] |
[] |
[] |
[
"python",
"python_unittest",
"unit_testing"
] |
stackoverflow_0001230498_python_python_unittest_unit_testing.txt
|
Q:
Unicode utf-8/utf-16 encoding in Python
In python:
u'\u3053\n'
Is it utf-16?
I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset,
like if I have a=u'\u3053\n'.
print gives an exception and
decoding gives an exception.
a.encode("utf-16") > '\xff\xfeS0\n\x00'
a.encode("utf-8") > '\xe3\x81\x93\n'
print a.encode("utf-8") > πüô
print a.encode("utf-16") > ■S0
What's going on here?
A:
It's a unicode character that doesn't seem to be displayable in your terminals encoding. print tries to encode the unicode object in the encoding of your terminal and if this can't be done you get an exception.
On a terminal that can display utf-8 you get:
>>> print u'\u3053'
こ
Your terminal doesn't seem to be able to display utf-8, else at least the print a.encode("utf-8") line should produce the correct character.
A:
You ask:
u'\u3053\n'
Is it utf-16?
The answer is no: it's unicode, not any specific encoding. utf-16 is an encoding.
To print a Unicode string effectively to your terminal, you need to find out what encoding that terminal is willing to accept and able to display. For example, the Terminal.app on my laptop is set to UTF-8 and with a rich font, so:
(source: aleax.it)
...the Hiragana letter displays correctly. On a Linux workstation I have a terminal program that keeps resetting to Latin-1 so it would mangle things somewhat like yours -- I can set it to utf-8, but it doesn't have huge number of glyphs in the font, so it would display somewhat-useless placeholder glyphs instead.
A:
Character U+3053 "HIRAGANA LETTER KO".
The \xff\xfe bit at the start of the UTF-16 binary format is the encoded byte order mark (U+FEFF), then "S0" is \x5e\x30, then there's the \n from the original string. (Each of the characters has its bytes "reversed" as it's using little endian UTF-16 encoding.)
The UTF-8 form represents the same Hiragana character in three bytes, with the bit pattern as documented here.
Now, as for whether you should really have it in your data set... where is this data coming from? Is it reasonable for it to have Hiragana characters in it?
A:
Here's the Unicode HowTo Doc for Python 2.6.2:
http://docs.python.org/howto/unicode.html
Also see the links in the Reference section of that document for other explanations, including one by Joel Spolsky.
|
Unicode utf-8/utf-16 encoding in Python
|
In python:
u'\u3053\n'
Is it utf-16?
I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset,
like if I have a=u'\u3053\n'.
print gives an exception and
decoding gives an exception.
a.encode("utf-16") > '\xff\xfeS0\n\x00'
a.encode("utf-8") > '\xe3\x81\x93\n'
print a.encode("utf-8") > πüô
print a.encode("utf-16") > ■S0
What's going on here?
|
[
"It's a unicode character that doesn't seem to be displayable in your terminals encoding. print tries to encode the unicode object in the encoding of your terminal and if this can't be done you get an exception.\nOn a terminal that can display utf-8 you get:\n>>> print u'\\u3053'\nこ\n\nYour terminal doesn't seem to be able to display utf-8, else at least the print a.encode(\"utf-8\") line should produce the correct character.\n",
"You ask:\n\nu'\\u3053\\n'\nIs it utf-16?\n\nThe answer is no: it's unicode, not any specific encoding. utf-16 is an encoding.\nTo print a Unicode string effectively to your terminal, you need to find out what encoding that terminal is willing to accept and able to display. For example, the Terminal.app on my laptop is set to UTF-8 and with a rich font, so:\n\n(source: aleax.it) \n...the Hiragana letter displays correctly. On a Linux workstation I have a terminal program that keeps resetting to Latin-1 so it would mangle things somewhat like yours -- I can set it to utf-8, but it doesn't have huge number of glyphs in the font, so it would display somewhat-useless placeholder glyphs instead.\n",
"Character U+3053 \"HIRAGANA LETTER KO\".\nThe \\xff\\xfe bit at the start of the UTF-16 binary format is the encoded byte order mark (U+FEFF), then \"S0\" is \\x5e\\x30, then there's the \\n from the original string. (Each of the characters has its bytes \"reversed\" as it's using little endian UTF-16 encoding.)\nThe UTF-8 form represents the same Hiragana character in three bytes, with the bit pattern as documented here.\nNow, as for whether you should really have it in your data set... where is this data coming from? Is it reasonable for it to have Hiragana characters in it?\n",
"Here's the Unicode HowTo Doc for Python 2.6.2:\nhttp://docs.python.org/howto/unicode.html\nAlso see the links in the Reference section of that document for other explanations, including one by Joel Spolsky.\n"
] |
[
10,
8,
3,
1
] |
[] |
[] |
[
"decoding",
"encoding",
"python",
"unicode"
] |
stackoverflow_0001229414_decoding_encoding_python_unicode.txt
|
Q:
How should I close a multi-line variable/comment in Python?
I am receiving this error:
File "/DateDbLoop.py", line 33
d.Id""" % (str(day), str(2840))"
^
SyntaxError: EOL while scanning single-quoted string
Here is the script. There are 4 double quotes to open this, but I am unsure how to correctly close this out?
Follow Up Question:
Does this % (str(day), str(2840)) need to go in both the sql variable and the os.system() call?
#!/usr/bin/python
import datetime
import sys, os, time, string
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 2, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print "Running query for \"" + str(day) + "\""
sql=""""SELECT
d.Date,
SUM(d.Revenue),
FROM Table d
WHERE d.Date = '%s'
AND d.Id = %s
GROUP BY d.Date
""" % (str(day), str(2840))"
os.system('mysql -h -sN -u -p -e %s > FileName-%s.txt db' % (sql, str(day)))
day += one_day
A:
You have 4 double-quotes at your sql= line, make it 3 instead. Also remove the single quote after your %-substitution value.
#!/usr/bin/python
import datetime
import sys, os, time, string
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 2, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print "Running query for \"" + str(day) + "\""
sql="""SELECT
d.Date,
SUM(d.Revenue)
FROM Table d
WHERE d.Date = '%s'
AND d.Id = %s
GROUP BY d.Date
""" % (str(day), str(2840))
os.system('mysql -h -sN -u -p -e "%s" > FileName-%s.txt db' % (sql, str(day)))
day += one_day
Multi-line string values are done with paired triplets of double-quotes in Python, and don't nest inside regular double-quotes.
A:
Open and close the string with three quotes
sql = """
SELECT d.Date, SUM(d.Revenue),
FROM Table d WHERE d.Date = '%s' AND d.Id = %s
GROUP BY d.Date
""" % (str(day), str(2840))
You can also break a line in the middle of a string with the \ character.
#!/usr/bin/python
import datetime
import sys, os, time, string
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 2, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print "Running query for \"" + str(day) + "\""
sql="SELECT d.Date, SUM(d.Revenue), FROM Table d WHERE d.Date = '%s' \
AND d.Id = %s GROUP BY d.Date " % (str(day), str(2840))
os.system('mysql -h -sN -u -p -e %s > FileName-%s.txt db' % (sql, str(day)))
A:
You use triple quotes for this.
s = """
Python is awesome.
Python is cool.
I use Python.
And so should you.
"""
print s
Python is awesome.
Python is cool.
I use Python.
And so should you.
|
How should I close a multi-line variable/comment in Python?
|
I am receiving this error:
File "/DateDbLoop.py", line 33
d.Id""" % (str(day), str(2840))"
^
SyntaxError: EOL while scanning single-quoted string
Here is the script. There are 4 double quotes to open this, but I am unsure how to correctly close this out?
Follow Up Question:
Does this % (str(day), str(2840)) need to go in both the sql variable and the os.system() call?
#!/usr/bin/python
import datetime
import sys, os, time, string
a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 2, 1)
one_day = datetime.timedelta(1)
day = a
while day <= b:
print "Running query for \"" + str(day) + "\""
sql=""""SELECT
d.Date,
SUM(d.Revenue),
FROM Table d
WHERE d.Date = '%s'
AND d.Id = %s
GROUP BY d.Date
""" % (str(day), str(2840))"
os.system('mysql -h -sN -u -p -e %s > FileName-%s.txt db' % (sql, str(day)))
day += one_day
|
[
"You have 4 double-quotes at your sql= line, make it 3 instead. Also remove the single quote after your %-substitution value.\n#!/usr/bin/python\n\nimport datetime\nimport sys, os, time, string\n\na = datetime.date(2009, 1, 1)\nb = datetime.date(2009, 2, 1)\none_day = datetime.timedelta(1)\n\nday = a\n\nwhile day <= b:\n print \"Running query for \\\"\" + str(day) + \"\\\"\"\n\n sql=\"\"\"SELECT\n d.Date, \n SUM(d.Revenue)\n FROM Table d \n WHERE d.Date = '%s' \n AND d.Id = %s \n GROUP BY d.Date \n \"\"\" % (str(day), str(2840))\n\n os.system('mysql -h -sN -u -p -e \"%s\" > FileName-%s.txt db' % (sql, str(day)))\n day += one_day\n\nMulti-line string values are done with paired triplets of double-quotes in Python, and don't nest inside regular double-quotes.\n",
"Open and close the string with three quotes \nsql = \"\"\"\n SELECT d.Date, SUM(d.Revenue),\n FROM Table d WHERE d.Date = '%s' AND d.Id = %s \n GROUP BY d.Date\n \"\"\" % (str(day), str(2840))\n\nYou can also break a line in the middle of a string with the \\ character. \n#!/usr/bin/python\n\nimport datetime\nimport sys, os, time, string\n\na = datetime.date(2009, 1, 1)\nb = datetime.date(2009, 2, 1)\none_day = datetime.timedelta(1)\n\nday = a\n\nwhile day <= b:\n\n print \"Running query for \\\"\" + str(day) + \"\\\"\"\n\n sql=\"SELECT d.Date, SUM(d.Revenue), FROM Table d WHERE d.Date = '%s' \\\n AND d.Id = %s GROUP BY d.Date \" % (str(day), str(2840))\n\n os.system('mysql -h -sN -u -p -e %s > FileName-%s.txt db' % (sql, str(day)))\n\n",
"You use triple quotes for this.\ns = \"\"\"\nPython is awesome.\nPython is cool.\nI use Python.\nAnd so should you.\n\"\"\"\n\nprint s\n\nPython is awesome.\nPython is cool.\nI use Python.\nAnd so should you.\n\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001231333_python.txt
|
Q:
Python Multiprocessing Exit Elegantly How?
import multiprocessing
import time
class testM(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.exit = False
def run(self):
while not self.exit:
pass
print "You exited!"
return
def shutdown(self):
self.exit = True
print "SHUTDOWN initiated"
def dostuff(self):
print "haha", self.exit
a = testM()
a.start()
time.sleep(3)
a.shutdown()
time.sleep(3)
print a.is_alive()
a.dostuff()
exit()
I am just wondering how come the code above doesn't really print "you exited". What am I doing wrong? if so, may someone point me out the correct way to exit gracefully? (I am not referring to process.terminate or kill)
A:
The reason you are not seeing this happen is because you are not communicating with the subprocess. You are trying to use a local variable (local to the parent process) to signal to the child that it should shutdown.
Take a look at the information on synchonization primatives. You need to setup a signal of some sort that can be referenced in both processes. Once you have this you should be able to flick the switch in the parent process and wait for the child to die.
Try the following code:
import multiprocessing
import time
class MyProcess(multiprocessing.Process):
def __init__(self, ):
multiprocessing.Process.__init__(self)
self.exit = multiprocessing.Event()
def run(self):
while not self.exit.is_set():
pass
print "You exited!"
def shutdown(self):
print "Shutdown initiated"
self.exit.set()
if __name__ == "__main__":
process = MyProcess()
process.start()
print "Waiting for a while"
time.sleep(3)
process.shutdown()
time.sleep(3)
print "Child process state: %d" % process.is_alive()
|
Python Multiprocessing Exit Elegantly How?
|
import multiprocessing
import time
class testM(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.exit = False
def run(self):
while not self.exit:
pass
print "You exited!"
return
def shutdown(self):
self.exit = True
print "SHUTDOWN initiated"
def dostuff(self):
print "haha", self.exit
a = testM()
a.start()
time.sleep(3)
a.shutdown()
time.sleep(3)
print a.is_alive()
a.dostuff()
exit()
I am just wondering how come the code above doesn't really print "you exited". What am I doing wrong? if so, may someone point me out the correct way to exit gracefully? (I am not referring to process.terminate or kill)
|
[
"The reason you are not seeing this happen is because you are not communicating with the subprocess. You are trying to use a local variable (local to the parent process) to signal to the child that it should shutdown.\nTake a look at the information on synchonization primatives. You need to setup a signal of some sort that can be referenced in both processes. Once you have this you should be able to flick the switch in the parent process and wait for the child to die.\nTry the following code:\nimport multiprocessing\nimport time\n\nclass MyProcess(multiprocessing.Process):\n\n def __init__(self, ):\n multiprocessing.Process.__init__(self)\n self.exit = multiprocessing.Event()\n\n def run(self):\n while not self.exit.is_set():\n pass\n print \"You exited!\"\n\n def shutdown(self):\n print \"Shutdown initiated\"\n self.exit.set()\n\n\nif __name__ == \"__main__\":\n process = MyProcess()\n process.start()\n print \"Waiting for a while\"\n time.sleep(3)\n process.shutdown()\n time.sleep(3)\n print \"Child process state: %d\" % process.is_alive()\n\n"
] |
[
57
] |
[] |
[] |
[
"multiprocessing",
"python"
] |
stackoverflow_0001231599_multiprocessing_python.txt
|
Q:
Classes nested in functions and attribute lookup
The following works Ok, i.e. it doesn't give any errors:
def foo(arg):
class Nested(object):
x = arg
foo('hello')
But the following throws an exception:
def foo(arg):
class Nested(object):
arg = arg # note that names are the same
foo('hello')
Traceback:
Traceback (most recent call last):
File "test.py", line 6, in <module>
foo('hello')
File "test.py", line 3, in foo
class Nested(object):
File "test.py", line 4, in Nested
arg = arg
NameError: name 'arg' is not defined
I can't understand the reason of such behavior. Could anybody explain?
A:
The arg property shadows the arg function argument (inner scoping)
def foo(arg):
class Nested(object):
arg = arg # you try to read the `arg` property which isn't initialized
You get the same error if you type i = i in the interpreter window without having initialized the i variable.
A:
If you try and assign to a variable within a function, Python assumes that variable is local to that function. So by trying to assign arg to the value of itself, you are implicitly declaring it as a local variable.
A:
It is due to Python's scoping rules:
def foo(arg): # (1)
class Nested(object):
arg = arg # (2)
(2) defines a new 'arg' name in the class' namespace, which opaques the value of the other 'arg' in the outer namespace (1).
However, (2) is unnecessary and the following is completely valid:
def foo(arg):
class Nested(object):
def message(self):
print arg
return Nested()
nested = foo('hello')
nested.message()
(prints hello)
|
Classes nested in functions and attribute lookup
|
The following works Ok, i.e. it doesn't give any errors:
def foo(arg):
class Nested(object):
x = arg
foo('hello')
But the following throws an exception:
def foo(arg):
class Nested(object):
arg = arg # note that names are the same
foo('hello')
Traceback:
Traceback (most recent call last):
File "test.py", line 6, in <module>
foo('hello')
File "test.py", line 3, in foo
class Nested(object):
File "test.py", line 4, in Nested
arg = arg
NameError: name 'arg' is not defined
I can't understand the reason of such behavior. Could anybody explain?
|
[
"The arg property shadows the arg function argument (inner scoping)\ndef foo(arg):\n class Nested(object):\n arg = arg # you try to read the `arg` property which isn't initialized\n\n\nYou get the same error if you type i = i in the interpreter window without having initialized the i variable.\n",
"If you try and assign to a variable within a function, Python assumes that variable is local to that function. So by trying to assign arg to the value of itself, you are implicitly declaring it as a local variable.\n",
"It is due to Python's scoping rules:\ndef foo(arg): # (1)\n class Nested(object):\n arg = arg # (2)\n\n(2) defines a new 'arg' name in the class' namespace, which opaques the value of the other 'arg' in the outer namespace (1).\nHowever, (2) is unnecessary and the following is completely valid:\ndef foo(arg):\n class Nested(object):\n def message(self):\n print arg\n return Nested()\n\nnested = foo('hello')\nnested.message()\n\n(prints hello)\n"
] |
[
5,
3,
3
] |
[] |
[] |
[
"class",
"nested",
"python"
] |
stackoverflow_0001231814_class_nested_python.txt
|
Q:
New to Python. Need info on the environment for it
I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started.
A:
Under Unix, Emacs is a good choice, to which I always come back, because it is convenient to have a single editor for everything, and because it's open source.
What is best for you depends on your past experience with IDEs. I'd say: stick with what you've been using, or take this opportunity to try an even better IDE.
Note: Python comes with Idle, which is a very simple (if limited) IDE.
A:
Be sure to check out IPython. It's an enhanced interactive python shell with a bunch of useful features such as Tab-Completion using introspection (eg, type "my_object." to see a list of its attributes and methods), logging your interactive session to an executable python-file, defining macros, etc. The documentation page has a link to the tutorial as well as screencasts showing it in action.
A:
On my mac/Linux machines, python came pre-installed. On windows I use both jython under the eclipse IDE and ActivePython with their IDE/eclipse. With eclipse you'll want PyDev.
A:
It all depends on what you are looking for and what you are already using.
For instance, if you are using a more 'simple' editor at the moment: as long as it's got Python syntax you've got the basics.
If you are used to e.g. Eclipse you can just continue to use that, combined with Pydev. Besides syntax highlighting you'll also get more fancy features to help you debug and refactor your code.
Personally I use Emacs with python-mode (and a few other modes to interface with Subversion and Git). In the past I used Vim which also worked quite well.
My advice would be to start out with your current environment as long as it has some rudimentary support for Python. Once you are familiar with the language, start exploring what your environment is missing and either add it or if you cannot, switch to an enviroment which does support the feature.
A:
I use gvim with some plugin in order to have better support for python.
If you like IDE, look at wing IDE wich is the best I have tested so far. Especially the debuger included is really helpful.
A:
The Python Beginner's Guide and the official Python Tutorial both seem like good places to start.
A:
Geany is a good option for a Linux setup, it's intellisense isn't that great but syntax highlighting is good and it can compile your code directly from inside the editor, plus it handles other languages such as C/C++, PHP, Java etc... Eric is another popular choice as it's a full IDE and I know some people use Eclipse.
On windows I use Notepad++, but it's mostly because I like text editors instead of fully blown IDE's.
Reference wise Daniel's choices are very good places to start, also check out Green Tea Press who do free computer books, there are two Python choices on there but the "Python for Software Design" book hasn't yet been published properly although you can download the manuscript. The "How to Think Like a Computer Scientist" book is a good one and not as scary as it sounds.
A:
IDLE is nice to try out things. Other tools that people like are Eclipse with the Pydev plugin which seems to work ok, although it has crashed a few times (Eclipse, that is) and NetBeans (which I haven't tried) but some people seem to like.
A:
I can only help you if you're running a Mac. Download Xcode. I believe that Python 2.3 comes bundled with these development tools. Luckily enough, this is all you really need to get started, unless you want a newer version of Python.
All you need to do is open up Terminal and type python. You're done!
|
New to Python. Need info on the environment for it
|
I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started.
|
[
"Under Unix, Emacs is a good choice, to which I always come back, because it is convenient to have a single editor for everything, and because it's open source.\nWhat is best for you depends on your past experience with IDEs. I'd say: stick with what you've been using, or take this opportunity to try an even better IDE.\nNote: Python comes with Idle, which is a very simple (if limited) IDE.\n",
"Be sure to check out IPython. It's an enhanced interactive python shell with a bunch of useful features such as Tab-Completion using introspection (eg, type \"my_object.\" to see a list of its attributes and methods), logging your interactive session to an executable python-file, defining macros, etc. The documentation page has a link to the tutorial as well as screencasts showing it in action.\n",
"On my mac/Linux machines, python came pre-installed. On windows I use both jython under the eclipse IDE and ActivePython with their IDE/eclipse. With eclipse you'll want PyDev. \n",
"It all depends on what you are looking for and what you are already using. \nFor instance, if you are using a more 'simple' editor at the moment: as long as it's got Python syntax you've got the basics.\nIf you are used to e.g. Eclipse you can just continue to use that, combined with Pydev. Besides syntax highlighting you'll also get more fancy features to help you debug and refactor your code.\nPersonally I use Emacs with python-mode (and a few other modes to interface with Subversion and Git). In the past I used Vim which also worked quite well.\nMy advice would be to start out with your current environment as long as it has some rudimentary support for Python. Once you are familiar with the language, start exploring what your environment is missing and either add it or if you cannot, switch to an enviroment which does support the feature.\n",
"I use gvim with some plugin in order to have better support for python.\nIf you like IDE, look at wing IDE wich is the best I have tested so far. Especially the debuger included is really helpful.\n",
"The Python Beginner's Guide and the official Python Tutorial both seem like good places to start.\n",
"Geany is a good option for a Linux setup, it's intellisense isn't that great but syntax highlighting is good and it can compile your code directly from inside the editor, plus it handles other languages such as C/C++, PHP, Java etc... Eric is another popular choice as it's a full IDE and I know some people use Eclipse.\nOn windows I use Notepad++, but it's mostly because I like text editors instead of fully blown IDE's.\nReference wise Daniel's choices are very good places to start, also check out Green Tea Press who do free computer books, there are two Python choices on there but the \"Python for Software Design\" book hasn't yet been published properly although you can download the manuscript. The \"How to Think Like a Computer Scientist\" book is a good one and not as scary as it sounds.\n",
"IDLE is nice to try out things. Other tools that people like are Eclipse with the Pydev plugin which seems to work ok, although it has crashed a few times (Eclipse, that is) and NetBeans (which I haven't tried) but some people seem to like.\n",
"I can only help you if you're running a Mac. Download Xcode. I believe that Python 2.3 comes bundled with these development tools. Luckily enough, this is all you really need to get started, unless you want a newer version of Python.\nAll you need to do is open up Terminal and type python. You're done!\n"
] |
[
3,
2,
1,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"ide",
"python"
] |
stackoverflow_0001231397_ide_python.txt
|
Q:
Does using properties on an old-style python class cause problems
Pretty simple question. I've seen it mentioned in many places that using properties on an old-style class shouldn't work, but apparently Qt classes (through PyQt4) aren't new-style and there are properties on a few of them in the code I'm working with (and as far as I know the code isn't showing any sorts of problems)
I did run across a pyqtProperty function, but I can't seem to find any documentation about it. Would it be a good alternative in this instance?
A:
property works because QObject has a metaclass that takes care of them. Witness this small variation on @quark's code...:
from PyQt4.QtCore import QObject
def makec(base):
class X( base ):
def __init__(self):
self.__x = 10
def get_x(self):
print 'getting',
return self.__x
def set_x(self, x):
print 'setting', x
self.__x = x
x = property(get_x, set_x)
print 'made class of mcl', type(X), issubclass(type(X), type)
return X
class old: pass
for base in (QObject, old):
X = makec(base)
x = X()
print x.x # Should be 10
x.x = 30
print x.x # Should be 30
running this emits:
made class of mcl <type 'PyQt4.QtCore.pyqtWrapperType'> True
getting 10
setting 30
getting 30
made class of mcl <type 'classobj'> False
getting 10
30
see the difference? In the class that's really a legacy (old-type) class, the one made the second time, metaclass is classobj (which ISN'T a subclass of type) and properties don't work right (assigning x.x bypasses the property, and after that getting x.x doesn't see the property any more either). But in the first case, the Qt case, there's a different metaclass, and it IS a subclass of type (so it's not really correct to say the class "isn't new-style"!), and things therefore DO work correctly.
A:
Properties of the Python sort work, in my experience, just fine on PyQt4 objects. I don't know if they are explicitly supported by PyQt4 or not or if there are some hidden gotchas, but I've never seen them misbehave. Here's an example using PyQt 4.4 and Python 2.5:
from PyQt4.QtCore import QObject
class X( QObject ):
def __init__(self):
self.__x = 10
def get_x(self):
return self.__x
def set_x(self, x):
self.__x = x
x = property(get_x, set_x)
x = X()
print x.x # Should be 10
x.x = 30
print x.x # Should be 30
pyqtProperty is to allow using Qt's property system which is not the same as Python's. Qt properties are introspectable from within Qt's C++ classes (which raw Python properties are not), and are used by Qt for such things as their Qt Designer form editor, and Qt Creator IDE. They allow a lot of the sort of introspection of run-time state that you have in Python and miss in C++. In general Qt provides some of the features of dynamic languages to C++, and this is not the only area where PyQt provides More Than One Way To Do the same thing (consider also strings, dictionaries, file I/O and so on). With most of those choices the main advice I have is just to pick one side or the other and stick with it, just to avoid the possibility of some unpleasant incompatibility. I tend to prefer the Python version over the Qt version because Python is more core to my work than Qt is. If you were going to consider porting anything from PyQt back to C++ Qt, than you might prefer the Qt version of a feature over the Python one.
A:
At least in PyQt4.5, Qt classes certainly ARE new style objects, as seen from their method resolution order:
from PyQt4 import QtGui
print QtGui.QWidget.__mro__
(<class 'PyQt4.QtGui.QWidget'>, <class 'PyQt4.QtCore.QObject'>, <type 'sip.wrapper'>, <class 'PyQt4.QtGui.QPaintDevice'>, <type 'sip.simplewrapper'>, <type 'object'>)
|
Does using properties on an old-style python class cause problems
|
Pretty simple question. I've seen it mentioned in many places that using properties on an old-style class shouldn't work, but apparently Qt classes (through PyQt4) aren't new-style and there are properties on a few of them in the code I'm working with (and as far as I know the code isn't showing any sorts of problems)
I did run across a pyqtProperty function, but I can't seem to find any documentation about it. Would it be a good alternative in this instance?
|
[
"property works because QObject has a metaclass that takes care of them. Witness this small variation on @quark's code...:\nfrom PyQt4.QtCore import QObject\n\ndef makec(base):\n class X( base ):\n def __init__(self):\n self.__x = 10\n def get_x(self):\n print 'getting',\n return self.__x\n def set_x(self, x):\n print 'setting', x\n self.__x = x\n x = property(get_x, set_x)\n\n print 'made class of mcl', type(X), issubclass(type(X), type)\n return X\n\nclass old: pass\nfor base in (QObject, old):\n X = makec(base)\n x = X()\n print x.x # Should be 10\n x.x = 30\n print x.x # Should be 30\n\nrunning this emits:\nmade class of mcl <type 'PyQt4.QtCore.pyqtWrapperType'> True\ngetting 10\nsetting 30\ngetting 30\nmade class of mcl <type 'classobj'> False\ngetting 10\n30\n\nsee the difference? In the class that's really a legacy (old-type) class, the one made the second time, metaclass is classobj (which ISN'T a subclass of type) and properties don't work right (assigning x.x bypasses the property, and after that getting x.x doesn't see the property any more either). But in the first case, the Qt case, there's a different metaclass, and it IS a subclass of type (so it's not really correct to say the class \"isn't new-style\"!), and things therefore DO work correctly.\n",
"Properties of the Python sort work, in my experience, just fine on PyQt4 objects. I don't know if they are explicitly supported by PyQt4 or not or if there are some hidden gotchas, but I've never seen them misbehave. Here's an example using PyQt 4.4 and Python 2.5:\nfrom PyQt4.QtCore import QObject\n\nclass X( QObject ):\n\n def __init__(self):\n self.__x = 10\n\n def get_x(self):\n return self.__x\n\n def set_x(self, x):\n self.__x = x\n\n x = property(get_x, set_x)\n\nx = X()\nprint x.x # Should be 10\nx.x = 30\nprint x.x # Should be 30\n\npyqtProperty is to allow using Qt's property system which is not the same as Python's. Qt properties are introspectable from within Qt's C++ classes (which raw Python properties are not), and are used by Qt for such things as their Qt Designer form editor, and Qt Creator IDE. They allow a lot of the sort of introspection of run-time state that you have in Python and miss in C++. In general Qt provides some of the features of dynamic languages to C++, and this is not the only area where PyQt provides More Than One Way To Do the same thing (consider also strings, dictionaries, file I/O and so on). With most of those choices the main advice I have is just to pick one side or the other and stick with it, just to avoid the possibility of some unpleasant incompatibility. I tend to prefer the Python version over the Qt version because Python is more core to my work than Qt is. If you were going to consider porting anything from PyQt back to C++ Qt, than you might prefer the Qt version of a feature over the Python one.\n",
"At least in PyQt4.5, Qt classes certainly ARE new style objects, as seen from their method resolution order:\nfrom PyQt4 import QtGui\nprint QtGui.QWidget.__mro__\n(<class 'PyQt4.QtGui.QWidget'>, <class 'PyQt4.QtCore.QObject'>, <type 'sip.wrapper'>, <class 'PyQt4.QtGui.QPaintDevice'>, <type 'sip.simplewrapper'>, <type 'object'>)\n\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"class",
"properties",
"pyqt",
"python"
] |
stackoverflow_0001230383_class_properties_pyqt_python.txt
|
Q:
Django - Following a foreign key relationship (i.e JOIN in SQL)
Busy playing with django, but one thing seems to be tripping me up is following a foreign key relationship. Now, I have a ton of experience in writing SQL, so i could prob. return the result if the ORM was not there.
Basically this is the SQL query i want returned
Select
table1.id
table1.text
table1.user
table2.user_name
table2.url
from table1, table2
where table1.user_id = table2.id
My model classes have been defined as:
class Table1(models.Model):
#other fields
text = models.TextField()
user = models.ForeignKey('table2')
class Table2(models.Model):
# other fields
user_name = models.CharField(max_length=50)
url = models.URLField(blank=True, null=True)
I have been through the documentation and reference for querysets, models and views on the django website. But its still not clear on how to do this.
I have also setup the url with a generic list view, but would like to access the user_name field from the second table in the template. I tried select_related in urls.py and also via the shell but it does not seem to work. See examples below.
config in urls
url(r'^$','django.views.generic.list_detail.object_list', { 'queryset': Table1.objects.select_related() }),
At the shell
>>> a = Table1.objects.select_related().get(id=1)
>>> a.id
1
>>> a.user_name
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Table1' object has no attribute 'user_name'
So basically,
What am i doing wrong?
Am i missing something?
What's the best way to pass fields from two tables in the same queryset to your template (So fields from both tables can be accessed)
Can this be done with generic views?
A:
Something like this should work:
u = Table1.objects.get(id=1)
print u.id
print u.user.user_name
If you want to follow a foreign key, you must do it explicitly. You don't get an automatic join, when you retrieve an object from Table1. You will only get an object from Table2, when you access a foreign key field, which is user in this example
A:
select_related() do not add second table result directly to the query, it just "Loads" them, insead of giving to you lazily. You should only use it, when you are sure it can boost your site performance. To get second table you need to write
a.user.username
In Django to get related table you need to follow them through foreign-keys that you have designed. Query itself do not directly translate to SQL query, because it is "lazy". It will execute only SQL that you need and only when you need.
If you have select_related SQL would have been executed at the moment when you do original query for a. But if you didn't have select_related then it would load DB only when you actually execute a.user.username.
|
Django - Following a foreign key relationship (i.e JOIN in SQL)
|
Busy playing with django, but one thing seems to be tripping me up is following a foreign key relationship. Now, I have a ton of experience in writing SQL, so i could prob. return the result if the ORM was not there.
Basically this is the SQL query i want returned
Select
table1.id
table1.text
table1.user
table2.user_name
table2.url
from table1, table2
where table1.user_id = table2.id
My model classes have been defined as:
class Table1(models.Model):
#other fields
text = models.TextField()
user = models.ForeignKey('table2')
class Table2(models.Model):
# other fields
user_name = models.CharField(max_length=50)
url = models.URLField(blank=True, null=True)
I have been through the documentation and reference for querysets, models and views on the django website. But its still not clear on how to do this.
I have also setup the url with a generic list view, but would like to access the user_name field from the second table in the template. I tried select_related in urls.py and also via the shell but it does not seem to work. See examples below.
config in urls
url(r'^$','django.views.generic.list_detail.object_list', { 'queryset': Table1.objects.select_related() }),
At the shell
>>> a = Table1.objects.select_related().get(id=1)
>>> a.id
1
>>> a.user_name
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Table1' object has no attribute 'user_name'
So basically,
What am i doing wrong?
Am i missing something?
What's the best way to pass fields from two tables in the same queryset to your template (So fields from both tables can be accessed)
Can this be done with generic views?
|
[
"Something like this should work:\nu = Table1.objects.get(id=1)\nprint u.id\nprint u.user.user_name\n\nIf you want to follow a foreign key, you must do it explicitly. You don't get an automatic join, when you retrieve an object from Table1. You will only get an object from Table2, when you access a foreign key field, which is user in this example\n",
"select_related() do not add second table result directly to the query, it just \"Loads\" them, insead of giving to you lazily. You should only use it, when you are sure it can boost your site performance. To get second table you need to write\na.user.username\n\nIn Django to get related table you need to follow them through foreign-keys that you have designed. Query itself do not directly translate to SQL query, because it is \"lazy\". It will execute only SQL that you need and only when you need.\nIf you have select_related SQL would have been executed at the moment when you do original query for a. But if you didn't have select_related then it would load DB only when you actually execute a.user.username. \n"
] |
[
4,
2
] |
[] |
[] |
[
"django",
"django_models",
"django_urls",
"python"
] |
stackoverflow_0001232172_django_django_models_django_urls_python.txt
|
Q:
How to get a reference to the module something is implemented in from within that implementation?
Say I have the following code:
from foo.bar import Foo
from foo.foo import Bar
__all__ = ["Foo", "Bar"]
def iterate_over_all():
...
How can I implement code in the function iterate_over_all() that can dynamically obtain references to whatever is referenced in __all__ the module where the function is implemented? IE: in iterate_over_all() I want to work with foo.bar.Foo and foo.foo.Bar.
A:
Would this do?
def iterate_over_all():
for name in __all__:
value = globals()[name]
yield value # or do whatever with it
A:
eval is one way. e.g. eval("Foo") would give you Foo. However you can also just put Foo and Bar directly in your list e.g. __all__ = [Foo, Bar]
It would depend on where the contents of __all__ is coming from in your actual program.
A:
You can easily index with the strings from __all__ into the module's __dict__:
__dict__["Foo"] == foo.bar.Foo # -> True
|
How to get a reference to the module something is implemented in from within that implementation?
|
Say I have the following code:
from foo.bar import Foo
from foo.foo import Bar
__all__ = ["Foo", "Bar"]
def iterate_over_all():
...
How can I implement code in the function iterate_over_all() that can dynamically obtain references to whatever is referenced in __all__ the module where the function is implemented? IE: in iterate_over_all() I want to work with foo.bar.Foo and foo.foo.Bar.
|
[
"Would this do?\ndef iterate_over_all():\n for name in __all__:\n value = globals()[name]\n yield value # or do whatever with it\n\n",
"eval is one way. e.g. eval(\"Foo\") would give you Foo. However you can also just put Foo and Bar directly in your list e.g. __all__ = [Foo, Bar] \nIt would depend on where the contents of __all__ is coming from in your actual program.\n",
"You can easily index with the strings from __all__ into the module's __dict__:\n__dict__[\"Foo\"] == foo.bar.Foo # -> True\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"module",
"python"
] |
stackoverflow_0001231631_module_python.txt
|
Q:
python String Formatting Operations
Faulty code:
pos_1 = 234
pos_n = 12890
min_width = len(str(pos_n)) # is there a better way for this?
# How can I use min_width as the minimal width of the two conversion specifiers?
# I don't understand the Python documentation on this :(
raw_str = '... from %(pos1)0*d to %(posn)0*d ...' % {'pos1':pos_1, 'posn': pos_n}
Required output:
... from 00234 to 12890 ...
______________________EDIT______________________
New code:
# I changed my code according the second answer
pos_1 = 10234 # can be any value between 1 and pos_n
pos_n = 12890
min_width = len(str(pos_n))
raw_str = '... from % *d to % *d ...' % (min_width, pos_1, min_width, pos_n)
New Problem:
There is one extra whitespace (I marked it _) in front of the integer values, for intigers with min_width digits:
print raw_str
... from _10234 to _12890 ...
Also, I wonder if there is a way to add Mapping keys?
A:
pos_1 = 234
pos_n = 12890
min_width = len(str(pos_n))
raw_str = '... from %0*d to %0*d ...' % (min_width, pos_1, min_width, pos_n)
A:
"1234".rjust(13,"0")
Should do what you need
addition:
a = ["123", "12"]
max_width = sorted([len(i) for i in a])[-1]
put max_width instead of 13 above and put all your strings in a single array a (which seems to me much more usable than having a stack of variables).
additional nastyness:
(Using array of numbers to get closer to your question.)
a = [123, 33, 0 ,223]
[str(x).rjust(sorted([len(str(i)) for i in a])[-1],"0") for x in a]
Who said Perl is the only language to easily produce braindumps in? If regexps are the godfather of complex code, then list comprehension is the godmother.
(I am relatively new to python and rather convinced that there must be a max-function on arrays somewhere, which would reduce above complexity. .... OK, checked, there is. Pity, have to reduce the example.)
[str(x).rjust(max([len(str(i) for i in a]),"0") for x in a]
And please observe below comments on "not putting calculation of an invariant (the max value) inside the outer list comprehension".
A:
Concerning using a mapping type as second argument to '%':
I presume you mean something like that '%(mykey)d' % {'mykey': 3}, right?! I think you cannot use this if you use the "%*d" syntax, since there is no way to provide the necessary width arguments with a dict.
But why don't you generate your format string dynamically:
fmt = '... from %%%dd to %%%dd ...' % (min_width, min_width)
# assuming min_width is e.g. 7 fmt would be: '... from %7d to %7d ...'
raw_string = fmt % pos_values_as_tuple_or_dict
This way you decouple the width issue from the formatting of the actual values, and you can use a tuple or a dict for the latter, as it suits you.
|
python String Formatting Operations
|
Faulty code:
pos_1 = 234
pos_n = 12890
min_width = len(str(pos_n)) # is there a better way for this?
# How can I use min_width as the minimal width of the two conversion specifiers?
# I don't understand the Python documentation on this :(
raw_str = '... from %(pos1)0*d to %(posn)0*d ...' % {'pos1':pos_1, 'posn': pos_n}
Required output:
... from 00234 to 12890 ...
______________________EDIT______________________
New code:
# I changed my code according the second answer
pos_1 = 10234 # can be any value between 1 and pos_n
pos_n = 12890
min_width = len(str(pos_n))
raw_str = '... from % *d to % *d ...' % (min_width, pos_1, min_width, pos_n)
New Problem:
There is one extra whitespace (I marked it _) in front of the integer values, for intigers with min_width digits:
print raw_str
... from _10234 to _12890 ...
Also, I wonder if there is a way to add Mapping keys?
|
[
"pos_1 = 234\npos_n = 12890\nmin_width = len(str(pos_n))\n\nraw_str = '... from %0*d to %0*d ...' % (min_width, pos_1, min_width, pos_n)\n\n",
"\"1234\".rjust(13,\"0\")\n\nShould do what you need\naddition:\na = [\"123\", \"12\"] \nmax_width = sorted([len(i) for i in a])[-1]\n\nput max_width instead of 13 above and put all your strings in a single array a (which seems to me much more usable than having a stack of variables).\nadditional nastyness:\n(Using array of numbers to get closer to your question.)\na = [123, 33, 0 ,223]\n[str(x).rjust(sorted([len(str(i)) for i in a])[-1],\"0\") for x in a]\n\nWho said Perl is the only language to easily produce braindumps in? If regexps are the godfather of complex code, then list comprehension is the godmother. \n(I am relatively new to python and rather convinced that there must be a max-function on arrays somewhere, which would reduce above complexity. .... OK, checked, there is. Pity, have to reduce the example.)\n[str(x).rjust(max([len(str(i) for i in a]),\"0\") for x in a]\n\nAnd please observe below comments on \"not putting calculation of an invariant (the max value) inside the outer list comprehension\". \n",
"Concerning using a mapping type as second argument to '%':\nI presume you mean something like that '%(mykey)d' % {'mykey': 3}, right?! I think you cannot use this if you use the \"%*d\" syntax, since there is no way to provide the necessary width arguments with a dict.\nBut why don't you generate your format string dynamically:\nfmt = '... from %%%dd to %%%dd ...' % (min_width, min_width)\n# assuming min_width is e.g. 7 fmt would be: '... from %7d to %7d ...'\nraw_string = fmt % pos_values_as_tuple_or_dict\n\nThis way you decouple the width issue from the formatting of the actual values, and you can use a tuple or a dict for the latter, as it suits you.\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"formatting",
"python",
"string"
] |
stackoverflow_0001231784_formatting_python_string.txt
|
Q:
Django Model Sync Table
If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?
A:
Alas, Django does not support any easy solution to this.
The only thing django will do for you, is restart your database with new tables that match your new models:
$ #DON'T DO THIS UNLESS YOU CAN AFFORD TO LOSE ALL YOUR DATA!
$ python PROJECT_DIR/manage.py syncdb
the next option is to use the various sql* options to manage.py to see what django would do to match the current models to the database, then issue your own ALTER TABLE commands to make everything work right. Of course this is error prone and difficult.
The real solution is to use a database migration tool, such as south to generate migration code.
Here is a similar question with discussion about various database migration options for django.
A:
Can't seem to be able to add a comment to the marked answer, probably because I haven't got enough rep (be nice if SO told me so though).
Anyway, just wanted to add that in the answered post, I believe it is wrong about syncdb - syncdb does not touch tables once they have been created and have data in them. You should not lose data by calling it (otherwise, how could you add new tables for new apps?)
I believe the poster was referring to the reset command instead, which does result in data loss - it will drop the table and recreate it and hence it'll have all the latest model changes.
A:
Django Evolution can help, but the best option really is to plan out your schema in advance, or to make simple modifications manually. Or, to be willing to toast your test data by dropping tables and re-syncing.
A:
Django does not provide for this out of the box.
Here's some information from the Django Book on doing it by hand (see Making Changes to a Database Schema). This works for straightforward, simple changes.
Longer-term, you'll probably want to use a migration tool. There are three major options:
django-evolution
Dmigrations (written by Simon Willison, one of the creators of Django) (works only with MySQL)
South
EDIT: Looking through the question linked by TokenMacGuy, I'll add two more to the list for the sake of completeness:
Migratory
simplemigrations
A:
Just to throw in an extra opinion - dmigrations is pretty nice and clear to use, but I'd say South is your best bet. Again, it's easy to get into, but it's more powerful and also has support for more database backends than just MySQL. It even handles MSSQL, if that's your thing
|
Django Model Sync Table
|
If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?
|
[
"Alas, Django does not support any easy solution to this. \nThe only thing django will do for you, is restart your database with new tables that match your new models:\n$ #DON'T DO THIS UNLESS YOU CAN AFFORD TO LOSE ALL YOUR DATA!\n$ python PROJECT_DIR/manage.py syncdb\n\nthe next option is to use the various sql* options to manage.py to see what django would do to match the current models to the database, then issue your own ALTER TABLE commands to make everything work right. Of course this is error prone and difficult.\nThe real solution is to use a database migration tool, such as south to generate migration code.\nHere is a similar question with discussion about various database migration options for django.\n",
"Can't seem to be able to add a comment to the marked answer, probably because I haven't got enough rep (be nice if SO told me so though).\nAnyway, just wanted to add that in the answered post, I believe it is wrong about syncdb - syncdb does not touch tables once they have been created and have data in them. You should not lose data by calling it (otherwise, how could you add new tables for new apps?)\nI believe the poster was referring to the reset command instead, which does result in data loss - it will drop the table and recreate it and hence it'll have all the latest model changes.\n",
"Django Evolution can help, but the best option really is to plan out your schema in advance, or to make simple modifications manually. Or, to be willing to toast your test data by dropping tables and re-syncing.\n",
"Django does not provide for this out of the box.\nHere's some information from the Django Book on doing it by hand (see Making Changes to a Database Schema). This works for straightforward, simple changes.\nLonger-term, you'll probably want to use a migration tool. There are three major options:\n\ndjango-evolution\nDmigrations (written by Simon Willison, one of the creators of Django) (works only with MySQL)\nSouth\n\nEDIT: Looking through the question linked by TokenMacGuy, I'll add two more to the list for the sake of completeness:\n\nMigratory\nsimplemigrations\n\n",
"Just to throw in an extra opinion - dmigrations is pretty nice and clear to use, but I'd say South is your best bet. Again, it's easy to get into, but it's more powerful and also has support for more database backends than just MySQL. It even handles MSSQL, if that's your thing\n"
] |
[
6,
4,
3,
2,
0
] |
[] |
[] |
[
"database",
"django",
"django_models",
"python",
"synchronization"
] |
stackoverflow_0001115238_database_django_django_models_python_synchronization.txt
|
Q:
Python multiprocessing easy way to implement a simple counter?
Hey everyone, I am using multiprocessing in python now. and I am just wondering whether there exists some sort of simple counter variable that each process when they are done processing some task could just increment ( kind of like how much work done in total).
I looked up the API for Value, don't think it's mutable.
A:
Value is indeed mutable; you specify the datatype you want from the ctypes module and then it can be mutated. Here's a complete, working script that demonstrates this:
from time import sleep
from ctypes import c_int
from multiprocessing import Value, Lock, Process
counter = Value(c_int) # defaults to 0
counter_lock = Lock()
def increment():
with counter_lock:
counter.value += 1
def do_something():
print("I'm a separate process!")
increment()
Process(target=do_something).start()
sleep(1)
print counter.value # prints 1, because Value is shared and mutable
EDIT: Luper correctly points out in a comment below that Value values are locked by default. This is correct in the sense that even if an assignment consists of multiple operations (such as assigning a string which might be many characters) then this assignment is atomic. However, when incrementing a counter you'll still need an external lock as provided in my example, because incrementing loads the current value and then increments it and then assigns the result back to the Value.
So without an external lock, you might run into the following circumstance:
Process 1 reads (atomically) the current value of the counter, then increments it
before Process 1 can assign the incremented counter back to the Value, a context switch occurrs
Process 2 reads (atomically) the current (unincremented) value of the counter, increments it, and assigns the incremented result (atomically) back to Value
Process 1 assigns its incremented value (atomically), blowing away the increment performed by Process 2
|
Python multiprocessing easy way to implement a simple counter?
|
Hey everyone, I am using multiprocessing in python now. and I am just wondering whether there exists some sort of simple counter variable that each process when they are done processing some task could just increment ( kind of like how much work done in total).
I looked up the API for Value, don't think it's mutable.
|
[
"Value is indeed mutable; you specify the datatype you want from the ctypes module and then it can be mutated. Here's a complete, working script that demonstrates this:\nfrom time import sleep\nfrom ctypes import c_int\nfrom multiprocessing import Value, Lock, Process\n\ncounter = Value(c_int) # defaults to 0\ncounter_lock = Lock()\ndef increment():\n with counter_lock:\n counter.value += 1\n\ndef do_something():\n print(\"I'm a separate process!\")\n increment()\n\nProcess(target=do_something).start()\nsleep(1)\nprint counter.value # prints 1, because Value is shared and mutable\n\nEDIT: Luper correctly points out in a comment below that Value values are locked by default. This is correct in the sense that even if an assignment consists of multiple operations (such as assigning a string which might be many characters) then this assignment is atomic. However, when incrementing a counter you'll still need an external lock as provided in my example, because incrementing loads the current value and then increments it and then assigns the result back to the Value.\nSo without an external lock, you might run into the following circumstance:\n\nProcess 1 reads (atomically) the current value of the counter, then increments it\nbefore Process 1 can assign the incremented counter back to the Value, a context switch occurrs\nProcess 2 reads (atomically) the current (unincremented) value of the counter, increments it, and assigns the incremented result (atomically) back to Value\nProcess 1 assigns its incremented value (atomically), blowing away the increment performed by Process 2\n\n"
] |
[
27
] |
[] |
[] |
[
"multiprocessing",
"python"
] |
stackoverflow_0001233222_multiprocessing_python.txt
|
Q:
Django ManyToMany Template Questions
Good Morning All,
I've been a PHP programmer for quite some time, but I've felt the need to move more towards the Python direction and what's better than playing around with Django.
While in the process, I'm come to a stopping point where I know there is an easy solution, but I'm just missing it - How do I display manytomany relationships in a Django Template?
My Django Model: (most of the fields have been removed)
class Category(models.Model):
name = models.CharField(max_length=125)
slug = models.SlugField()
categories = models.ManyToManyField(Category, blank=True, null=True)
class Recipe(models.Model):
title = models.CharField('Title', max_length=250)
slug = models.SlugField()
class Photo(models.Model):
recipe = models.ForeignKey(Recipe)
image = models.ImageField(upload_to="images/recipes", blank=True)
So, there is the basic models I'm using in my application called "recipes."
With that said, there are two questions I'm looking for answers on:
How would I go about displaying the categories for a recipe on it's details page?
How would I go about displaying the image for the recipe on it's details page?
If I go into the Python shell, and input the following, I do get a result:
>>> photos = Photo.objects.filter(recipe=1)
>>> photos
[<Photo: Awesome Pasta>]
>>> for photo in photos:
... print "Photo: %s" % photo.logo
...
Photo: images/recipes/2550298482_46729d51af__.jpg
But when I try something like the following in my template, I get an error saying "Invalid block tag: 'photo.image'."
{% for photo in photos %}
{% photo.image %}
{% endfor %}
Although, even if that did work, the ID is still hard coded into the view, how would you go about having this dynamic for each recipe?
Details Page View.py snippet:
def details(request, slug='0'):
p = get_object_or_404(Recipe, slug=slug)
photos = Photo.objects.filter(recipe=1)
return render_to_response('recipes/recipes_detail.html', {'p': p, 'photos': photos})
Thanks in advance for the help and understanding for what is probably a very simple question to all of you!
UPDATE: When removing the additional fields in the models, I forgot the categories field for the Recipes model.
A:
From what I can see, I think you've got a small syntax error:
{% photo.image %}
should instead be:
{{ photo.image }}
The {% %} notation is used for django template tags. Variables, on the other hand, are expressed with the {{ }} notation.
To make it dynamic, you can take advantage of the fact that your Photo model has a foreign key to Recipe. This means that there will be a reverse relation from the Recipe instance you've loaded using the slug back to the set of photos:
def details(request, slug='0'):
p = get_object_or_404(Recipe, slug=slug)
photos = p.photo_set.all()
Hopefully that will work for you. Glad to see you're enjoying working with Django!
|
Django ManyToMany Template Questions
|
Good Morning All,
I've been a PHP programmer for quite some time, but I've felt the need to move more towards the Python direction and what's better than playing around with Django.
While in the process, I'm come to a stopping point where I know there is an easy solution, but I'm just missing it - How do I display manytomany relationships in a Django Template?
My Django Model: (most of the fields have been removed)
class Category(models.Model):
name = models.CharField(max_length=125)
slug = models.SlugField()
categories = models.ManyToManyField(Category, blank=True, null=True)
class Recipe(models.Model):
title = models.CharField('Title', max_length=250)
slug = models.SlugField()
class Photo(models.Model):
recipe = models.ForeignKey(Recipe)
image = models.ImageField(upload_to="images/recipes", blank=True)
So, there is the basic models I'm using in my application called "recipes."
With that said, there are two questions I'm looking for answers on:
How would I go about displaying the categories for a recipe on it's details page?
How would I go about displaying the image for the recipe on it's details page?
If I go into the Python shell, and input the following, I do get a result:
>>> photos = Photo.objects.filter(recipe=1)
>>> photos
[<Photo: Awesome Pasta>]
>>> for photo in photos:
... print "Photo: %s" % photo.logo
...
Photo: images/recipes/2550298482_46729d51af__.jpg
But when I try something like the following in my template, I get an error saying "Invalid block tag: 'photo.image'."
{% for photo in photos %}
{% photo.image %}
{% endfor %}
Although, even if that did work, the ID is still hard coded into the view, how would you go about having this dynamic for each recipe?
Details Page View.py snippet:
def details(request, slug='0'):
p = get_object_or_404(Recipe, slug=slug)
photos = Photo.objects.filter(recipe=1)
return render_to_response('recipes/recipes_detail.html', {'p': p, 'photos': photos})
Thanks in advance for the help and understanding for what is probably a very simple question to all of you!
UPDATE: When removing the additional fields in the models, I forgot the categories field for the Recipes model.
|
[
"From what I can see, I think you've got a small syntax error:\n{% photo.image %}\n\nshould instead be:\n{{ photo.image }}\n\nThe {% %} notation is used for django template tags. Variables, on the other hand, are expressed with the {{ }} notation.\nTo make it dynamic, you can take advantage of the fact that your Photo model has a foreign key to Recipe. This means that there will be a reverse relation from the Recipe instance you've loaded using the slug back to the set of photos:\ndef details(request, slug='0'):\n p = get_object_or_404(Recipe, slug=slug)\n photos = p.photo_set.all()\n\nHopefully that will work for you. Glad to see you're enjoying working with Django!\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_templates",
"many_to_many",
"python",
"templates"
] |
stackoverflow_0001233709_django_django_templates_many_to_many_python_templates.txt
|
Q:
How long do zipimported module imports remain cached in memory when using appengine / python and is there a way to keep them in memory?
I've recently uploaded an app that uses django appengine patch and currently have a cron job that runs every two minutes. On each invocation of the worker url it consumes quite a bit of resources
/worker_url 200 7633ms 34275cpu_ms 28116api_ms
That is because on each invocation it does a cold zipimport of all the libraries django etc.
How long do the imported modules stay in memory?
Is there a way to keep these modules in memory so even if subsequent calls are not within the timeframe that these modules stay in memory they still don't invoke the overhead?
A:
app engine keeps everything in memory according to normal Python semantics as long as it's serving one or more requests in the same process in the same node; if and when it needs those resources, the process goes away (so nothing stays in memory that it used to have), and new processes may be started (on the same node or different nodes) any time to serve requests (whether other processes serving other requests are still running, or not). This is much like the fast-CGI model: you're assured of normal semantics within a single request but apart from that anything between 0 and N (no upper limit) different nodes may be running your code, each serving sequentially anything between 0 and K (no upper limit) different requests.
There is nothing you can do to "stay in memory" (for zipimported modules or anything else).
For completeness let me mention memcache, which is an explicit hint/request to the app engine runtime to keep something in a special form of memory, a distributed hash table that's shared among all processes running your code -- that's hard though not impossible to use for imported modules (you'd need pretty sophisticated import hooks) and I recommend against the effort needed to develop such hooks because even in presence of such explicit hints the app engine runtime can still at any time choose to eject anything you've stashed away in the cache, anyway.
Rather -- I'm not sure why a cron job in particular would need all of django nor of why you're zipimporting it rather than just using the 1.0.2 that now comes with app engine, per the docs -- care to elaborate? This might be a useful issue for you to optimize.
|
How long do zipimported module imports remain cached in memory when using appengine / python and is there a way to keep them in memory?
|
I've recently uploaded an app that uses django appengine patch and currently have a cron job that runs every two minutes. On each invocation of the worker url it consumes quite a bit of resources
/worker_url 200 7633ms 34275cpu_ms 28116api_ms
That is because on each invocation it does a cold zipimport of all the libraries django etc.
How long do the imported modules stay in memory?
Is there a way to keep these modules in memory so even if subsequent calls are not within the timeframe that these modules stay in memory they still don't invoke the overhead?
|
[
"app engine keeps everything in memory according to normal Python semantics as long as it's serving one or more requests in the same process in the same node; if and when it needs those resources, the process goes away (so nothing stays in memory that it used to have), and new processes may be started (on the same node or different nodes) any time to serve requests (whether other processes serving other requests are still running, or not). This is much like the fast-CGI model: you're assured of normal semantics within a single request but apart from that anything between 0 and N (no upper limit) different nodes may be running your code, each serving sequentially anything between 0 and K (no upper limit) different requests.\nThere is nothing you can do to \"stay in memory\" (for zipimported modules or anything else).\nFor completeness let me mention memcache, which is an explicit hint/request to the app engine runtime to keep something in a special form of memory, a distributed hash table that's shared among all processes running your code -- that's hard though not impossible to use for imported modules (you'd need pretty sophisticated import hooks) and I recommend against the effort needed to develop such hooks because even in presence of such explicit hints the app engine runtime can still at any time choose to eject anything you've stashed away in the cache, anyway.\nRather -- I'm not sure why a cron job in particular would need all of django nor of why you're zipimporting it rather than just using the 1.0.2 that now comes with app engine, per the docs -- care to elaborate? This might be a useful issue for you to optimize.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"google_app_engine",
"import",
"python"
] |
stackoverflow_0001233826_django_google_app_engine_import_python.txt
|
Q:
PIL does not save transparency
from PIL import Image
img = Image.open('1.png')
img.save('2.png')
The first image has a transparent background, but when I save it, the transparency is gone (background is white)
What am I doing wrong?
A:
Probably the image is indexed (mode "P" in PIL), so the transparency is not set in PNG alpha channel, but in metadata info.
You can get transparent background palette index with the following code:
from PIL import Image
img = Image.open('1.png')
png_info = img.info
img.save('2.png', **png_info)
image info is a dictionary, so you can inspect it to see the info that it has:
eg: If you print it you will get an output like the following:
{'transparency': 7, 'gamma': 0.45454, 'dpi': (72, 72)}
The information saved there will vary depending on the tool that created the original PNG, but what is important for you here is the "transparency" key. In the example it says that palette index "7" must be treated as transparent.
A:
You can always force the the type to "RGBA",
img = Image.open('1.png')
img.convert('RGBA')
img.save('2.png')
|
PIL does not save transparency
|
from PIL import Image
img = Image.open('1.png')
img.save('2.png')
The first image has a transparent background, but when I save it, the transparency is gone (background is white)
What am I doing wrong?
|
[
"Probably the image is indexed (mode \"P\" in PIL), so the transparency is not set in PNG alpha channel, but in metadata info.\nYou can get transparent background palette index with the following code:\nfrom PIL import Image\n\nimg = Image.open('1.png')\npng_info = img.info\nimg.save('2.png', **png_info)\n\nimage info is a dictionary, so you can inspect it to see the info that it has:\neg: If you print it you will get an output like the following:\n{'transparency': 7, 'gamma': 0.45454, 'dpi': (72, 72)}\n\nThe information saved there will vary depending on the tool that created the original PNG, but what is important for you here is the \"transparency\" key. In the example it says that palette index \"7\" must be treated as transparent.\n",
"You can always force the the type to \"RGBA\",\nimg = Image.open('1.png')\nimg.convert('RGBA')\nimg.save('2.png')\n\n"
] |
[
31,
6
] |
[] |
[] |
[
"png",
"python",
"python_imaging_library"
] |
stackoverflow_0001233772_png_python_python_imaging_library.txt
|
Q:
PyQt : why adding a dummy class definition in my file make the application crash?
Consider the code below:
#!/usr/bin/env python
from PyQt4 import QtCore, QtGui
import os,sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.listWidget = QtGui.QListWidget(None)
self.setCentralWidget(self.listWidget)
if __name__ == '__main__':
app = QtGui.QApplication (sys.argv)
mainWin = MainWindow ()
mainWin.show ()
sys.exit (app.exec_())
Works ok.
Now if I add a dummy class (that inherits from a QtGui module's class) in the global scope ...
class MainWindow(QtGui.QMainWindow):
... # unchanged
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
if __name__ == '__main__':
... # unchanged
... when i launch the script i get the error:
TypeError: argument 1 of
QMainWindow.setCentralWidget() has an
invalid type
This error message is cryptic for me as i can't connect it to the modification done.
Do you have an idea what could be the source of this error?
A:
Can't reproduce the problem as reported: the following exact code
from PyQt4 import QtCore, QtGui
import os, sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.listWidget = QtGui.QListWidget(None)
self.setCentralWidget(self.listWidget)
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
runs just fine for me (showing an empty window of course). So I guess it's down to versions details! I'm using system-supplied Python 2.5.1 on Mac OS X 10.5.7 and adding a
print QtCore.PYQT_VERSION_STR
shows I'm on version 4.5.1 of PyQt. What about you?
A:
I have not worked with PyQt before, but didn't you forget to call the constructor of the superclass here?
class MyWidget(QtGui.QWidget):
def __init__(self):
# Where is the call to QtGui.QWidget's init ?
pass
|
PyQt : why adding a dummy class definition in my file make the application crash?
|
Consider the code below:
#!/usr/bin/env python
from PyQt4 import QtCore, QtGui
import os,sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.listWidget = QtGui.QListWidget(None)
self.setCentralWidget(self.listWidget)
if __name__ == '__main__':
app = QtGui.QApplication (sys.argv)
mainWin = MainWindow ()
mainWin.show ()
sys.exit (app.exec_())
Works ok.
Now if I add a dummy class (that inherits from a QtGui module's class) in the global scope ...
class MainWindow(QtGui.QMainWindow):
... # unchanged
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
if __name__ == '__main__':
... # unchanged
... when i launch the script i get the error:
TypeError: argument 1 of
QMainWindow.setCentralWidget() has an
invalid type
This error message is cryptic for me as i can't connect it to the modification done.
Do you have an idea what could be the source of this error?
|
[
"Can't reproduce the problem as reported: the following exact code\nfrom PyQt4 import QtCore, QtGui\n\nimport os, sys\n\nclass MainWindow(QtGui.QMainWindow):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent) \n self.listWidget = QtGui.QListWidget(None)\n self.setCentralWidget(self.listWidget) \n\nclass MyWidget(QtGui.QWidget):\n def __init__(self):\n super(MyWidget, self).__init__()\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n mainWin = MainWindow()\n mainWin.show()\n sys.exit(app.exec_())\n\nruns just fine for me (showing an empty window of course). So I guess it's down to versions details! I'm using system-supplied Python 2.5.1 on Mac OS X 10.5.7 and adding a\nprint QtCore.PYQT_VERSION_STR\n\nshows I'm on version 4.5.1 of PyQt. What about you?\n",
"I have not worked with PyQt before, but didn't you forget to call the constructor of the superclass here? \nclass MyWidget(QtGui.QWidget):\n def __init__(self):\n # Where is the call to QtGui.QWidget's init ?\n pass\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"pyqt4",
"python"
] |
stackoverflow_0001233711_pyqt4_python.txt
|
Q:
In GTK, how do I get the actual size of a widget on screen?
First I looked at the get_size_request method. The docs there end with:
To get the size a widget will actually use, call the size_request() instead of this method.
I look at size_request(), and it ends with
Also remember that the size request is not necessarily the size a widget will actually be allocated.
So, is there any function in GTK to get what size a widget actually is? This is a widget that is on-screen and actually being displayed, so GTK definitely has this information somewhere.
A:
This should be it (took some time to find):
The get_allocation() method returns a gtk.gdk.Rectangle containing the bounds of the widget's allocation.
From here.
|
In GTK, how do I get the actual size of a widget on screen?
|
First I looked at the get_size_request method. The docs there end with:
To get the size a widget will actually use, call the size_request() instead of this method.
I look at size_request(), and it ends with
Also remember that the size request is not necessarily the size a widget will actually be allocated.
So, is there any function in GTK to get what size a widget actually is? This is a widget that is on-screen and actually being displayed, so GTK definitely has this information somewhere.
|
[
"This should be it (took some time to find):\n\nThe get_allocation() method returns a gtk.gdk.Rectangle containing the bounds of the widget's allocation.\n\nFrom here.\n"
] |
[
15
] |
[] |
[] |
[
"api",
"gtk",
"pygtk",
"python",
"user_interface"
] |
stackoverflow_0001234223_api_gtk_pygtk_python_user_interface.txt
|
Q:
Concatenating Dictionaries
I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List_1[0] has corresponding data in List_2[0] and List_3[0], etc. I would like to turn these three lists into a dictionary inside a dictionary, with the values in List_1 being the primary keys. How do I do this while keeping everything in order?
A:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9]
>>> dict(zip(a, zip(b, c)))
{1: (4, 7), 2: (5, 8), 3: (6, 9)}
See the documentation for more info on zip.
As lionbest points out below, you might want to look at itertools.izip() if your input data is large. izip does essentially the same thing as zip, but it creates iterators instead of lists. This way, you don't create large temporary lists before creating the dictionary.
A:
Python 3:
combined = {name:dict(data1=List_2[i], data2=List_3[i]) for i, name in enumerate(List_1)}
Python 2.5:
combined = {}
for i, name in enumerate(List_1):
combined[name] = dict(data1=List_2[i], data2=List_3[i])
A:
if the order of these things matters, you should not use a dictionary. by definition, they are unordered. you can use one of the many ordered_dictionary implementations floating around, or wait for python 2.7 or 3.1 which will include an ordered dictionary implementation in the collections module.
|
Concatenating Dictionaries
|
I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List_1[0] has corresponding data in List_2[0] and List_3[0], etc. I would like to turn these three lists into a dictionary inside a dictionary, with the values in List_1 being the primary keys. How do I do this while keeping everything in order?
|
[
">>> a = [1,2,3]\n>>> b = [4,5,6]\n>>> c = [7,8,9]\n>>> dict(zip(a, zip(b, c)))\n{1: (4, 7), 2: (5, 8), 3: (6, 9)}\n\nSee the documentation for more info on zip.\nAs lionbest points out below, you might want to look at itertools.izip() if your input data is large. izip does essentially the same thing as zip, but it creates iterators instead of lists. This way, you don't create large temporary lists before creating the dictionary.\n",
"Python 3:\ncombined = {name:dict(data1=List_2[i], data2=List_3[i]) for i, name in enumerate(List_1)}\n\nPython 2.5:\ncombined = {}\nfor i, name in enumerate(List_1):\n combined[name] = dict(data1=List_2[i], data2=List_3[i])\n\n",
"if the order of these things matters, you should not use a dictionary. by definition, they are unordered. you can use one of the many ordered_dictionary implementations floating around, or wait for python 2.7 or 3.1 which will include an ordered dictionary implementation in the collections module.\n"
] |
[
13,
1,
0
] |
[] |
[] |
[
"dictionary",
"key",
"merge",
"python"
] |
stackoverflow_0001232904_dictionary_key_merge_python.txt
|
Q:
k-means clustering implementation in python, running out of memory
Note: updates/solutions at the bottom of this question
As part of a product recommendation engine, I'm trying to segment my users based on their product preferences starting with using the k-means clustering algorithm.
My data is a dictionary of the form:
prefs = {
'user_id_1': { 1L: 3.0f, 2L: 1.0f, },
'user_id_2': { 4L: 1.0f, 8L: 1.5f, },
}
where the product ids are the longs, and ratings are floats. the data is sparse. I currently have about 60,000 users, most of whom have only rated a handful of products. The dictionary of values for each user is implemented using a defaultdict(float) to simplify the code.
My implementation of k-means clustering is as follows:
def kcluster(prefs,sim_func=pearson,k=100,max_iterations=100):
from collections import defaultdict
users = prefs.keys()
centroids = [prefs[random.choice(users)] for i in range(k)]
lastmatches = None
for t in range(max_iterations):
print 'Iteration %d' % t
bestmatches = [[] for i in range(k)]
# Find which centroid is closest for each row
for j in users:
row = prefs[j]
bestmatch=(0,0)
for i in range(k):
d = simple_pearson(row,centroids[i])
if d < bestmatch[1]: bestmatch = (i,d)
bestmatches[bestmatch[0]].append(j)
# If the results are the same as last time, this is complete
if bestmatches == lastmatches: break
lastmatches=bestmatches
centroids = [defaultdict(float) for i in range(k)]
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
items = set.union(*[set(prefs[u].keys()) for u in bestmatches[i]])
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in items:
if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
return bestmatches
As far as I can tell, the algorithm is handling the first part (assigning each user to its nearest centroid) fine.
The problem is when doing the next part, taking the average rating for each product in each cluster and using these average ratings as the centroids for the next pass.
Basically, before it's even managed to do the calculations for the first cluster (i=0), the algorithm bombs out with a MemoryError at this line:
if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
Originally the division step was in a seperate loop, but fared no better.
This is the exception I get:
malloc: *** mmap(size=16777216) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Any help would be greatly appreciated.
Update: Final algorithms
Thanks to the help recieved here, this is my fixed algorithm. If you spot anything blatantly wrong please add a comment.
First, the simple_pearson implementation
def simple_pearson(v1,v2):
si = [val for val in v1 if val in v2]
n = len(si)
if n==0: return 0.0
sum1 = 0.0
sum2 = 0.0
sum1_sq = 0.0
sum2_sq = 0.0
p_sum = 0.0
for v in si:
sum1+=v1[v]
sum2+=v2[v]
sum1_sq+=pow(v1[v],2)
sum2_sq+=pow(v2[v],2)
p_sum+=(v1[v]*v2[v])
# Calculate Pearson score
num = p_sum-(sum1*sum2/n)
temp = (sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n)
if temp < 0.0:
temp = -temp
den = sqrt(temp)
if den==0: return 1.0
r = num/den
return r
A simple method to turn simple_pearson into a distance value:
def distance(v1,v2):
return 1.0-simple_pearson(v1,v2)
And finally, the k-means clustering implementation:
def kcluster(prefs,k=21,max_iterations=50):
from collections import defaultdict
users = prefs.keys()
centroids = [prefs[u] for u in random.sample(users, k)]
lastmatches = None
for t in range(max_iterations):
print 'Iteration %d' % t
bestmatches = [[] for i in range(k)]
# Find which centroid is closest for each row
for j in users:
row = prefs[j]
bestmatch=(0,2.0)
for i in range(k):
d = distance(row,centroids[i])
if d <= bestmatch[1]: bestmatch = (i,d)
bestmatches[bestmatch[0]].append(j)
# If the results are the same as last time, this is complete
if bestmatches == lastmatches: break
lastmatches=bestmatches
centroids = [defaultdict(float) for i in range(k)]
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in row:
centroids[i][m]+=row[m]
for key in centroids[i].keys():
centroids[i][key]/=len_best
# We may have made the centroids quite dense which significantly
# slows down subsequent iterations, so we delete values below a
# threshold to speed things up
if centroids[i][key] < 0.001:
del centroids[i][key]
return centroids, bestmatches
A:
Not all these observations are directly relevant to your issues as expressed, but..:
a. why are the key in prefs, as shown, longs? unless you have billions of users, simple ints will be fine and save you a little memory.
b. your code:
centroids = [prefs[random.choice(users)] for i in range(k)]
can give you repeats (two identical centroids), which in turn would not make the K-means algorithm happy. Just use the faster and more solid
centroids = [prefs[u] for random.sample(users, k)]
c. in your code as posted you're calling a function simple_pearson which you never define anywhere; I assume you mean to call sim_func, but it's really hard to help on different issues while at the same time having to guess how the code you posted differs from any code that might actually be working
d. one more indication that this posted code may be different from anything that might actually work: you set bestmatch=(0,0) but then test with if d < bestmatch[1]: -- how is the test ever going to succeed? is the distance function returning negative values?
e. the point of a defaultdict is that just accessing row[m] magically adds an item to row at index m (with the value obtained by calling the defaultdict's factory, here 0.0). That item will then take up memory forevermore. You absolutely DON'T need this behavior, and therefore your code:
row = prefs[user_id]
for m in items:
if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
is wasting huge amount of memory, making prefs into a dense matrix (mostly full of 0.0 values) from the sparse one it used to be. If you code instead
row = prefs[user_id]
for m in row:
centroids[i][m]+=(row[m]/len_best)
there will be no growth in row and therefore in prefs because you're looping over the keys that row already has.
There may be many other such issues, major like the last one or minor ones -- as an example of the latter,
f. don't divide a bazillion times by len_best: compute its inverse one outside the loop and multiply by that inverse -- also you don't need to do that multiplication inside the loop, you can do it at the end in a separate since it's the same value that's multiplying every item -- this saves no memory but avoids wantonly wasting CPU time;-). OK, these are two minor issues, I guess, not just one;-).
As I mentioned there may be many others, but with the density of issues already shown by these six (or seven), plus the separate suggestion already advanced by S.Lott (which I think would not fix your main out-of-memory problem, since his code still addressing the row defaultdict by too many keys it doesn't contain), I think it wouldn't be very productive to keep looking for even more -- maybe start by fixing these ones and if problems persist post a separate question about those...?
A:
Your centroids does not need to be an actual list.
You never appear to reference anything other than centroids[i][m]. If you only want centroids[i], then perhaps it doesn't need to be a list; a simple dictionary would probably do.
centroids = defaultdict(float)
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
items = set.union(*[set(prefs[u].keys()) for u in bestmatches[i]])
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in items:
if row[m] > 0.0: centroids[m]+=(row[m]/len_best)
May work better.
|
k-means clustering implementation in python, running out of memory
|
Note: updates/solutions at the bottom of this question
As part of a product recommendation engine, I'm trying to segment my users based on their product preferences starting with using the k-means clustering algorithm.
My data is a dictionary of the form:
prefs = {
'user_id_1': { 1L: 3.0f, 2L: 1.0f, },
'user_id_2': { 4L: 1.0f, 8L: 1.5f, },
}
where the product ids are the longs, and ratings are floats. the data is sparse. I currently have about 60,000 users, most of whom have only rated a handful of products. The dictionary of values for each user is implemented using a defaultdict(float) to simplify the code.
My implementation of k-means clustering is as follows:
def kcluster(prefs,sim_func=pearson,k=100,max_iterations=100):
from collections import defaultdict
users = prefs.keys()
centroids = [prefs[random.choice(users)] for i in range(k)]
lastmatches = None
for t in range(max_iterations):
print 'Iteration %d' % t
bestmatches = [[] for i in range(k)]
# Find which centroid is closest for each row
for j in users:
row = prefs[j]
bestmatch=(0,0)
for i in range(k):
d = simple_pearson(row,centroids[i])
if d < bestmatch[1]: bestmatch = (i,d)
bestmatches[bestmatch[0]].append(j)
# If the results are the same as last time, this is complete
if bestmatches == lastmatches: break
lastmatches=bestmatches
centroids = [defaultdict(float) for i in range(k)]
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
items = set.union(*[set(prefs[u].keys()) for u in bestmatches[i]])
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in items:
if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
return bestmatches
As far as I can tell, the algorithm is handling the first part (assigning each user to its nearest centroid) fine.
The problem is when doing the next part, taking the average rating for each product in each cluster and using these average ratings as the centroids for the next pass.
Basically, before it's even managed to do the calculations for the first cluster (i=0), the algorithm bombs out with a MemoryError at this line:
if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)
Originally the division step was in a seperate loop, but fared no better.
This is the exception I get:
malloc: *** mmap(size=16777216) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Any help would be greatly appreciated.
Update: Final algorithms
Thanks to the help recieved here, this is my fixed algorithm. If you spot anything blatantly wrong please add a comment.
First, the simple_pearson implementation
def simple_pearson(v1,v2):
si = [val for val in v1 if val in v2]
n = len(si)
if n==0: return 0.0
sum1 = 0.0
sum2 = 0.0
sum1_sq = 0.0
sum2_sq = 0.0
p_sum = 0.0
for v in si:
sum1+=v1[v]
sum2+=v2[v]
sum1_sq+=pow(v1[v],2)
sum2_sq+=pow(v2[v],2)
p_sum+=(v1[v]*v2[v])
# Calculate Pearson score
num = p_sum-(sum1*sum2/n)
temp = (sum1_sq-pow(sum1,2)/n) * (sum2_sq-pow(sum2,2)/n)
if temp < 0.0:
temp = -temp
den = sqrt(temp)
if den==0: return 1.0
r = num/den
return r
A simple method to turn simple_pearson into a distance value:
def distance(v1,v2):
return 1.0-simple_pearson(v1,v2)
And finally, the k-means clustering implementation:
def kcluster(prefs,k=21,max_iterations=50):
from collections import defaultdict
users = prefs.keys()
centroids = [prefs[u] for u in random.sample(users, k)]
lastmatches = None
for t in range(max_iterations):
print 'Iteration %d' % t
bestmatches = [[] for i in range(k)]
# Find which centroid is closest for each row
for j in users:
row = prefs[j]
bestmatch=(0,2.0)
for i in range(k):
d = distance(row,centroids[i])
if d <= bestmatch[1]: bestmatch = (i,d)
bestmatches[bestmatch[0]].append(j)
# If the results are the same as last time, this is complete
if bestmatches == lastmatches: break
lastmatches=bestmatches
centroids = [defaultdict(float) for i in range(k)]
# Move the centroids to the average of their members
for i in range(k):
len_best = len(bestmatches[i])
if len_best > 0:
for user_id in bestmatches[i]:
row = prefs[user_id]
for m in row:
centroids[i][m]+=row[m]
for key in centroids[i].keys():
centroids[i][key]/=len_best
# We may have made the centroids quite dense which significantly
# slows down subsequent iterations, so we delete values below a
# threshold to speed things up
if centroids[i][key] < 0.001:
del centroids[i][key]
return centroids, bestmatches
|
[
"Not all these observations are directly relevant to your issues as expressed, but..:\na. why are the key in prefs, as shown, longs? unless you have billions of users, simple ints will be fine and save you a little memory.\nb. your code:\ncentroids = [prefs[random.choice(users)] for i in range(k)]\n\ncan give you repeats (two identical centroids), which in turn would not make the K-means algorithm happy. Just use the faster and more solid\ncentroids = [prefs[u] for random.sample(users, k)]\n\nc. in your code as posted you're calling a function simple_pearson which you never define anywhere; I assume you mean to call sim_func, but it's really hard to help on different issues while at the same time having to guess how the code you posted differs from any code that might actually be working\nd. one more indication that this posted code may be different from anything that might actually work: you set bestmatch=(0,0) but then test with if d < bestmatch[1]: -- how is the test ever going to succeed? is the distance function returning negative values?\ne. the point of a defaultdict is that just accessing row[m] magically adds an item to row at index m (with the value obtained by calling the defaultdict's factory, here 0.0). That item will then take up memory forevermore. You absolutely DON'T need this behavior, and therefore your code:\n row = prefs[user_id] \n for m in items:\n if row[m] > 0.0: centroids[i][m]+=(row[m]/len_best)\n\nis wasting huge amount of memory, making prefs into a dense matrix (mostly full of 0.0 values) from the sparse one it used to be. If you code instead\n row = prefs[user_id] \n for m in row:\n centroids[i][m]+=(row[m]/len_best)\n\nthere will be no growth in row and therefore in prefs because you're looping over the keys that row already has.\nThere may be many other such issues, major like the last one or minor ones -- as an example of the latter, \nf. don't divide a bazillion times by len_best: compute its inverse one outside the loop and multiply by that inverse -- also you don't need to do that multiplication inside the loop, you can do it at the end in a separate since it's the same value that's multiplying every item -- this saves no memory but avoids wantonly wasting CPU time;-). OK, these are two minor issues, I guess, not just one;-).\nAs I mentioned there may be many others, but with the density of issues already shown by these six (or seven), plus the separate suggestion already advanced by S.Lott (which I think would not fix your main out-of-memory problem, since his code still addressing the row defaultdict by too many keys it doesn't contain), I think it wouldn't be very productive to keep looking for even more -- maybe start by fixing these ones and if problems persist post a separate question about those...?\n",
"Your centroids does not need to be an actual list.\nYou never appear to reference anything other than centroids[i][m]. If you only want centroids[i], then perhaps it doesn't need to be a list; a simple dictionary would probably do.\n centroids = defaultdict(float)\n\n # Move the centroids to the average of their members\n for i in range(k):\n len_best = len(bestmatches[i])\n\n if len_best > 0: \n items = set.union(*[set(prefs[u].keys()) for u in bestmatches[i]])\n\n for user_id in bestmatches[i]:\n row = prefs[user_id]\n for m in items:\n if row[m] > 0.0: centroids[m]+=(row[m]/len_best) \n\nMay work better.\n"
] |
[
6,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001233593_python.txt
|
Q:
Should I learn Python after C++?
I`m currently studying C++ and want to learn another language.
For work I use C# + ASP (just started learning it, actually), but I want something "less Microsoft" and powerful.
I have heard Python is a popular and powerful language, not so complicated as C++. But many people mentioned it was hard for them to get back to C++/Java from Python because they started thinking in it, get used to absence of memory management, etc.
What do you recommend?
A:
There's no right or wrong answer, really. But I think you'll benefit more from learning Python. Given the similarities between C# and C++, you'll learn a different way of thinking from Python. The more ways you learn to think about a problem, the better it makes you as a programmer, regardless of the language.
A:
The benefit of going from a more static language to a dynamic language is to change your programming paradigm -- it's not a matter of becoming "lazy" so much as realizing new ways of accomplishing things, which will make you better in any language.
A:
Well, I've learnt Python after C/C++, Java and C#. Python is a great language, and its simplicity and consistency have improved the way I code. It has also helped me think more clearly about the algorithms underlying my code. I could go on about the benifits it brought me, instead I'll summarize the reason to learn it ->
Learning a new lanuage doesn't take away, it adds to your programming skill and keeps you sharp by teaching you to shift between the frames of mind that each language requires.
So go out there and learn Python. Your code will improve(TM).
P.S.
1.You'll lose C++ (or any other language) skills, if you neglect their upkeep and maintainance. Thats entirely up to you.
2.Programmer (intelligent) laziness is a virtue.
A:
Many would argue that you would benefit from learning Python before C++.
The syntax hurdles are much, much lower;
Debugging is much more friendly
There are a plethora of libraries---batteries included, you know. It's easy to
experiment with web scraping, XML, etc. in Python. Again, the barriers to entry
in C++ are much higher.
It's still good to learn C/C++, because of its close connection to the machine. But a new programmer can learn an awful lot from exploring in Python.
A:
I don't think that "Python makes you lazy" (nice title, anyway!).
On the contrary, in programming as in life, knowing more than one language is important; I think you'll find python amusing and sufficiently different from C++ or C# so that the languages will not get mixed in your head...
A:
Python is complementary to C++ and easy to integrate with C++. (As evidence of this claim, the C++ gurus from Boost use Python.)
And as you said, Python gives you a way to get a perspective outside the Microsoft orbit. But even there, if you need to integrate Python with MS tools, there's IronPython.
A:
Learning more languages can only make you a better developer, regardless of their approach. Besides, your experience with C++ (or, at least C) will come in handy for writing high-performance parts of your applications using Python's C API, which lets "raw" C and C++ code intermingle nicely with the pure Python stuff.
I still write code in Objective-C (1.0... before memory management) and Python on a daily basis. The variety is actually fun, rather than confusing; keeps things from being boring.
A:
Flex your brain and improve your skill set. Give a functional language a whirl.
A:
It is up to what exactly is the kind of applications you want to program, for example for Websites that need access to databases I would go for Ruby( and Ruby on Rails framework ) , for financial applications or applications that need a lot of parallel processing I would go for a funcional programming language like Haskell, oCaml or the new F#, these last 3 wil make you a better programer even if you don't programm a lot in them , by the way c# has been lately in the latest versions adding more and more funcional programming features. I would learn Python for a security and exploits kinds of applications.
A:
I learned C/C++, Java, Python & C# in that order.
The two I actually invariably end up using are C++ & Python; I find the niche Java & C# occupy between them to be too narrow to feel the need to use them much (at least for the stuff I do).
I also think I didn't really "get" C++ functors and boost::bind until I'd been exposed to Python.
A:
Many languages are quite similar to others, but to move between imperitave and functional / dynamic and static / Object and Procedural languages you do need to train yourself to think within the constraints of the language you are using. Since most projects are at least a few weeks, this is generally not a problem after the first few days.
You will find it more difficult to switch away from a language+environment you enjoy in your after-hours / hobby development.
C, Macro Assembler => basically the same - difference is mainly libraries
C++, Java, C#, Delphi => basically the same paradigm - you learn quickly how to leverage the features of the specific language and adopt concepts from one syntax to another. It's basically the same way of thinking, the biggest exception is how you think of memory manangement.
Python - good language, strategically a better choice than ruby, although there are other aspects of ruby that can be argued to be superior. What make python a good choice is the presence of a formal language body which keeps python environments on different platforms very compatible to one another.
If you are interested, read this http://cmdematos.com/?p=120 on making a strategic language choice.
A:
You could learn a new programming language, like python, and use it to do all the tasks you'd normally perform in your 'core' languages; or you could take a language (like python, or perl) and use it to complement your core language.
You could learn VBScript and use it to write scripts that glue your code and others together. If you want something less Microsoft, then python, perl or bash scripting would be a good idea - not just to learn how to code in the new, but also how to do things differently from the usual 'code an app' way.
A:
From a utility perspective, it is good to learn one of the more dynamic languages like Python (or Ruby or Perl) too. Not only do they stretch your mind, but they are superior for certain kinds of tasks. If you want to manipulate text, for example, C++ is a lot harder to use than Python. It gives you another arrow in your quiver to use when appropriate.
A:
I learned, in order:
BASIC
Pascal
Ada
(A little bit of Haskell)
Java
Python
C++
C#
I don't feel Python inhibited my ability to learn or use C++. I am glad though that I learned pointers in Pascal before encountering reference types in Java, Python and C#, because I feel it gave me a good basis to understand the idea of the differences between "value types" and "reference types". I think for me the most important of those languages are Python, Haskell and C++. All of them complement each other, and although there are times I'm working in one and wish I had a feature from another, on the whole I think I benefit greatly from a deeper understanding of things like type systems, object orientation and metaprogramming by seeing the different ways these languages approach these things.
A:
Try LISP instead (or afterwards, it's your call). You are at least partially right, though. using Python for a while makes you not want to go back to a statically typed and compiled language. It's just sooo much more comfortable not to have to please the compiler like ALL THE TIME ;). And yet another aspect is the readability of python code, which is awesome.
A:
It is true. After learning python, everything else will seem like too much effort for the same amount of real work being done. You'll get used to the clean, small syntax and the freedom of GC. You will enjoy working in list comps, generators, etc. You'll start to think in python and C++ and Java will be like building a ship in a bottle one twiggy little stick at a time.
But since it's that much easier, doesn't it tempt you to try it all the more?
A:
I think it is always good to know several programming languages. I've learned c++ at school and I've used it a lot in the past years because it is really a standard in the industry. I've learned python by my own and I am using it to make a lot of nice tools that would be too long to write in c++.
Python has just a very positive influence on my c++ skills. It gives another way to think.
|
Should I learn Python after C++?
|
I`m currently studying C++ and want to learn another language.
For work I use C# + ASP (just started learning it, actually), but I want something "less Microsoft" and powerful.
I have heard Python is a popular and powerful language, not so complicated as C++. But many people mentioned it was hard for them to get back to C++/Java from Python because they started thinking in it, get used to absence of memory management, etc.
What do you recommend?
|
[
"There's no right or wrong answer, really. But I think you'll benefit more from learning Python. Given the similarities between C# and C++, you'll learn a different way of thinking from Python. The more ways you learn to think about a problem, the better it makes you as a programmer, regardless of the language.\n",
"The benefit of going from a more static language to a dynamic language is to change your programming paradigm -- it's not a matter of becoming \"lazy\" so much as realizing new ways of accomplishing things, which will make you better in any language.\n",
"Well, I've learnt Python after C/C++, Java and C#. Python is a great language, and its simplicity and consistency have improved the way I code. It has also helped me think more clearly about the algorithms underlying my code. I could go on about the benifits it brought me, instead I'll summarize the reason to learn it ->\n\nLearning a new lanuage doesn't take away, it adds to your programming skill and keeps you sharp by teaching you to shift between the frames of mind that each language requires.\n\nSo go out there and learn Python. Your code will improve(TM).\nP.S.\n1.You'll lose C++ (or any other language) skills, if you neglect their upkeep and maintainance. Thats entirely up to you.\n2.Programmer (intelligent) laziness is a virtue.\n",
"Many would argue that you would benefit from learning Python before C++. \n\nThe syntax hurdles are much, much lower;\nDebugging is much more friendly\nThere are a plethora of libraries---batteries included, you know. It's easy to \nexperiment with web scraping, XML, etc. in Python. Again, the barriers to entry\nin C++ are much higher.\n\nIt's still good to learn C/C++, because of its close connection to the machine. But a new programmer can learn an awful lot from exploring in Python.\n",
"I don't think that \"Python makes you lazy\" (nice title, anyway!).\nOn the contrary, in programming as in life, knowing more than one language is important; I think you'll find python amusing and sufficiently different from C++ or C# so that the languages will not get mixed in your head...\n",
"Python is complementary to C++ and easy to integrate with C++. (As evidence of this claim, the C++ gurus from Boost use Python.)\nAnd as you said, Python gives you a way to get a perspective outside the Microsoft orbit. But even there, if you need to integrate Python with MS tools, there's IronPython.\n",
"Learning more languages can only make you a better developer, regardless of their approach. Besides, your experience with C++ (or, at least C) will come in handy for writing high-performance parts of your applications using Python's C API, which lets \"raw\" C and C++ code intermingle nicely with the pure Python stuff.\nI still write code in Objective-C (1.0... before memory management) and Python on a daily basis. The variety is actually fun, rather than confusing; keeps things from being boring.\n",
"Flex your brain and improve your skill set. Give a functional language a whirl.\n",
"It is up to what exactly is the kind of applications you want to program, for example for Websites that need access to databases I would go for Ruby( and Ruby on Rails framework ) , for financial applications or applications that need a lot of parallel processing I would go for a funcional programming language like Haskell, oCaml or the new F#, these last 3 wil make you a better programer even if you don't programm a lot in them , by the way c# has been lately in the latest versions adding more and more funcional programming features. I would learn Python for a security and exploits kinds of applications.\n",
"I learned C/C++, Java, Python & C# in that order.\nThe two I actually invariably end up using are C++ & Python; I find the niche Java & C# occupy between them to be too narrow to feel the need to use them much (at least for the stuff I do).\nI also think I didn't really \"get\" C++ functors and boost::bind until I'd been exposed to Python.\n",
"Many languages are quite similar to others, but to move between imperitave and functional / dynamic and static / Object and Procedural languages you do need to train yourself to think within the constraints of the language you are using. Since most projects are at least a few weeks, this is generally not a problem after the first few days.\nYou will find it more difficult to switch away from a language+environment you enjoy in your after-hours / hobby development.\n\nC, Macro Assembler => basically the same - difference is mainly libraries\nC++, Java, C#, Delphi => basically the same paradigm - you learn quickly how to leverage the features of the specific language and adopt concepts from one syntax to another. It's basically the same way of thinking, the biggest exception is how you think of memory manangement.\nPython - good language, strategically a better choice than ruby, although there are other aspects of ruby that can be argued to be superior. What make python a good choice is the presence of a formal language body which keeps python environments on different platforms very compatible to one another.\n\nIf you are interested, read this http://cmdematos.com/?p=120 on making a strategic language choice.\n",
"You could learn a new programming language, like python, and use it to do all the tasks you'd normally perform in your 'core' languages; or you could take a language (like python, or perl) and use it to complement your core language.\nYou could learn VBScript and use it to write scripts that glue your code and others together. If you want something less Microsoft, then python, perl or bash scripting would be a good idea - not just to learn how to code in the new, but also how to do things differently from the usual 'code an app' way.\n",
"From a utility perspective, it is good to learn one of the more dynamic languages like Python (or Ruby or Perl) too. Not only do they stretch your mind, but they are superior for certain kinds of tasks. If you want to manipulate text, for example, C++ is a lot harder to use than Python. It gives you another arrow in your quiver to use when appropriate.\n",
"I learned, in order:\n\nBASIC\nPascal\nAda\n(A little bit of Haskell)\nJava\nPython\nC++\nC#\n\nI don't feel Python inhibited my ability to learn or use C++. I am glad though that I learned pointers in Pascal before encountering reference types in Java, Python and C#, because I feel it gave me a good basis to understand the idea of the differences between \"value types\" and \"reference types\". I think for me the most important of those languages are Python, Haskell and C++. All of them complement each other, and although there are times I'm working in one and wish I had a feature from another, on the whole I think I benefit greatly from a deeper understanding of things like type systems, object orientation and metaprogramming by seeing the different ways these languages approach these things.\n",
"Try LISP instead (or afterwards, it's your call). You are at least partially right, though. using Python for a while makes you not want to go back to a statically typed and compiled language. It's just sooo much more comfortable not to have to please the compiler like ALL THE TIME ;). And yet another aspect is the readability of python code, which is awesome.\n",
"It is true. After learning python, everything else will seem like too much effort for the same amount of real work being done. You'll get used to the clean, small syntax and the freedom of GC. You will enjoy working in list comps, generators, etc. You'll start to think in python and C++ and Java will be like building a ship in a bottle one twiggy little stick at a time.\nBut since it's that much easier, doesn't it tempt you to try it all the more?\n",
"I think it is always good to know several programming languages. I've learned c++ at school and I've used it a lot in the past years because it is really a standard in the industry. I've learned python by my own and I am using it to make a lot of nice tools that would be too long to write in c++. \nPython has just a very positive influence on my c++ skills. It gives another way to think.\n"
] |
[
30,
9,
4,
4,
2,
2,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"c++",
"python"
] |
stackoverflow_0000615100_c++_python.txt
|
Q:
Searching a Unicode file using Python
Setup
I'm writing a script to process and annotate build logs from Visual Studio. The build logs are HTML, and from what I can tell, Unicode (UTF-16?) as well. Here's a snippet from one of the files:
c:\anonyfolder\anonyfile.c(17169) : warning C4701: potentially uninitialized local variable 'object_adrs2' used
c:\anonyfolder\anonyfile.c(17409) : warning C4701: potentially uninitialized local variable 'pclcrd_ptr' used
c:\anonyfolder\anonyfile.c(17440) : warning C4701: potentially uninitialized local variable 'object_adrs2' used
The first 16 bytes of the file look like this:
feff 003c 0068 0074 006d 006c 003e 000d
The rest of the file is littered with null bytes as well.
I'd like to be able to perform string and regular expression searches/matches on these files. However, when I try the following code I get an error message.
buildLog = open(sys.argv[1]).readlines()
for line in buildLog:
match = u'warning'
if line.find(match) >= 0:
print line
The error message:
Traceback (most recent call last):
File "proclogs.py", line 60, in
if line.find(match) >= 0:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
Apparently it's choking on the 0xff byte in 0xfeff at the beginning of the file. If I skip the first line, I get no matches:
buildLog = open(sys.argv[1]).readlines()
for line in buildLog[1:]: # Skip the first line.
match = u'warning'
if line.find(match) >= 0:
print line
Likewise, using the non-Unicode match = 'warning' produces no results.
Question
How can I portably search a Unicode file using strings and regular expressions in Python? Additionally, how can I do so such that I can reconstruct the original file? (The goal is to be able to write annotations on the warning lines without mangling the file.)
A:
Try using the codecs package:
import codecs
buildLog = codecs.open(sys.argv[1], "r", "utf-16").readlines()
Also you may run into trouble with your print statement as it may try to convert the strings to your console encoding. If you're printing for your review you could use,
print repr(line)
A:
Tried this? When saving a parsing script with non-ascii characters, I had the interpreter suggest an alternate encoding to the front of the file.
Non-ASCII found, yet no encoding declared. Add a line like:
# -*- coding: cp1252 -*-
Adding that as the first line of the script fixed the problem for me. Not sure if this is what's causing your error, though.
|
Searching a Unicode file using Python
|
Setup
I'm writing a script to process and annotate build logs from Visual Studio. The build logs are HTML, and from what I can tell, Unicode (UTF-16?) as well. Here's a snippet from one of the files:
c:\anonyfolder\anonyfile.c(17169) : warning C4701: potentially uninitialized local variable 'object_adrs2' used
c:\anonyfolder\anonyfile.c(17409) : warning C4701: potentially uninitialized local variable 'pclcrd_ptr' used
c:\anonyfolder\anonyfile.c(17440) : warning C4701: potentially uninitialized local variable 'object_adrs2' used
The first 16 bytes of the file look like this:
feff 003c 0068 0074 006d 006c 003e 000d
The rest of the file is littered with null bytes as well.
I'd like to be able to perform string and regular expression searches/matches on these files. However, when I try the following code I get an error message.
buildLog = open(sys.argv[1]).readlines()
for line in buildLog:
match = u'warning'
if line.find(match) >= 0:
print line
The error message:
Traceback (most recent call last):
File "proclogs.py", line 60, in
if line.find(match) >= 0:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
Apparently it's choking on the 0xff byte in 0xfeff at the beginning of the file. If I skip the first line, I get no matches:
buildLog = open(sys.argv[1]).readlines()
for line in buildLog[1:]: # Skip the first line.
match = u'warning'
if line.find(match) >= 0:
print line
Likewise, using the non-Unicode match = 'warning' produces no results.
Question
How can I portably search a Unicode file using strings and regular expressions in Python? Additionally, how can I do so such that I can reconstruct the original file? (The goal is to be able to write annotations on the warning lines without mangling the file.)
|
[
"Try using the codecs package:\nimport codecs\nbuildLog = codecs.open(sys.argv[1], \"r\", \"utf-16\").readlines()\n\nAlso you may run into trouble with your print statement as it may try to convert the strings to your console encoding. If you're printing for your review you could use,\nprint repr(line)\n\n",
"Tried this? When saving a parsing script with non-ascii characters, I had the interpreter suggest an alternate encoding to the front of the file.\nNon-ASCII found, yet no encoding declared. Add a line like:\n# -*- coding: cp1252 -*-\n\nAdding that as the first line of the script fixed the problem for me. Not sure if this is what's causing your error, though.\n"
] |
[
7,
0
] |
[] |
[] |
[
"encoding",
"python",
"unicode"
] |
stackoverflow_0001235588_encoding_python_unicode.txt
|
Q:
how can I add a QMenu and QMenuItems to a window from Qt Designer
Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.
A:
When you edit a QMainWindow you can right click the window and then choose "create menu bar".
Or are you talking about a "context menu" aka "right click menu"?
A:
I have a single main window with a QGraphicsView and lots of QGraphicsItem objects. Each type of the Items have a different context menu.
I find that not being able to create the contextMenu's, or at least the actions that are in them a serious limitation of QtDesigner. It means that I can create about 10% or so of the actions using the designer, and I have to create 90% programaticaly. Compare that with the Microsoft resource editor which allows all of these things to be created, and maintained effortlessly.
I hope this will be addressed at some point.
A:
Adding menu editing for every widget in the designer would probably make a very awkward and inconvenient UI. There's really no place you can visualize it on.
If you're editing a QMainWindow you can edit the menu bar and its popups because there's a proper place for them to be displayed in.
|
how can I add a QMenu and QMenuItems to a window from Qt Designer
|
Is there any reason why a QMenu cannot be added from the Qt Designer? I find it weird that you can add other widget types but not this.
|
[
"When you edit a QMainWindow you can right click the window and then choose \"create menu bar\".\nOr are you talking about a \"context menu\" aka \"right click menu\"?\n",
"I have a single main window with a QGraphicsView and lots of QGraphicsItem objects. Each type of the Items have a different context menu.\nI find that not being able to create the contextMenu's, or at least the actions that are in them a serious limitation of QtDesigner. It means that I can create about 10% or so of the actions using the designer, and I have to create 90% programaticaly. Compare that with the Microsoft resource editor which allows all of these things to be created, and maintained effortlessly. \nI hope this will be addressed at some point.\n",
"Adding menu editing for every widget in the designer would probably make a very awkward and inconvenient UI. There's really no place you can visualize it on.\nIf you're editing a QMainWindow you can edit the menu bar and its popups because there's a proper place for them to be displayed in.\n"
] |
[
3,
3,
0
] |
[] |
[] |
[
"designer",
"python",
"qt",
"widget"
] |
stackoverflow_0000960467_designer_python_qt_widget.txt
|
Q:
Introspecting a given function's nested (local) functions in Python
Given the function
def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above:
>>> get, post = get_local_functions(f)
>>> get()
'get'
I can access the code objects for those local functions like so
import inspect
for c in f.func_code.co_consts:
if inspect.iscode(c):
print c.co_name, c
which results in
get <code object get at 0x26e78 ...>
post <code object post at 0x269f8 ...>
but I can't figure out how to get the actual callable function objects. Is that even possible?
Thanks for your help,
Will.
A:
You are pretty close of doing that - just missing new module:
import inspect
import new
def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
for c in f.func_code.co_consts:
if inspect.iscode(c):
f = new.function(c, globals())
print f # Here you have your function :].
But why the heck bother? Isn't it easier to use class? Instantiation looks like a function call anyway.
A:
You can return functions just like any other object in Python:
def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
return (get, post)
get, post = f()
Hope this helps!
Note, though, that if you want to use your 'x' and 'y' variables in get() or post(), you should make them a list.
If you do something like this:
def f():
x = [1]
def get():
print 'get', x[0]
x[0] -= 1
def post():
print 'post', x[0]
x[0] += 1
return (get, post)
get1, post1 = f()
get2, post2 = f()
get1 and post1 will reference a different 'x' list than get2 and post2.
A:
You could use exec to run the code objects. For example, if you had f defined as above, then
exec(f.func_code.co_consts[3])
would give
get
as output.
A:
The inner function objects don't exist before the function f() is executed. If you want to get them you'll have to construct them yourself. That is definitely non-trivial because they might be closures that capture variables from the scope of the function and will anyway require poking around in objects that should probably be regarded as implementation details of the interpreter.
If you want to collect the functions with less repetition I recommend one of the following approaches:
a) Just put the functions in a class definition and return a reference to that class. A collection of related functions that are accessed by name smells awfully like a class.
b) Create a dict subclass that has a method for registering functions and use that as a decorator.
The code for this would look something like this:
class FunctionCollector(dict):
def register(self, func):
self[func.__name__] = func
def f():
funcs = FunctionCollector()
@funcs.register
def get():
return 'get'
@funcs.register
def put():
return 'put'
return funcs
c) Poke around in locals() and filter out the function with inspect.isfunction. (usually not a good idea)
|
Introspecting a given function's nested (local) functions in Python
|
Given the function
def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above:
>>> get, post = get_local_functions(f)
>>> get()
'get'
I can access the code objects for those local functions like so
import inspect
for c in f.func_code.co_consts:
if inspect.iscode(c):
print c.co_name, c
which results in
get <code object get at 0x26e78 ...>
post <code object post at 0x269f8 ...>
but I can't figure out how to get the actual callable function objects. Is that even possible?
Thanks for your help,
Will.
|
[
"You are pretty close of doing that - just missing new module:\nimport inspect\nimport new\n\ndef f():\n x, y = 1, 2\n def get():\n print 'get'\n def post():\n print 'post'\n\nfor c in f.func_code.co_consts:\n if inspect.iscode(c):\n f = new.function(c, globals())\n print f # Here you have your function :].\n\nBut why the heck bother? Isn't it easier to use class? Instantiation looks like a function call anyway.\n",
"You can return functions just like any other object in Python:\ndef f():\n x, y = 1, 2 \n def get():\n print 'get'\n def post():\n print 'post'\n return (get, post)\n\n\nget, post = f()\n\nHope this helps!\nNote, though, that if you want to use your 'x' and 'y' variables in get() or post(), you should make them a list.\nIf you do something like this:\ndef f():\n x = [1]\n def get():\n print 'get', x[0]\n x[0] -= 1\n def post():\n print 'post', x[0]\n x[0] += 1\n return (get, post)\n\nget1, post1 = f()\nget2, post2 = f()\n\nget1 and post1 will reference a different 'x' list than get2 and post2.\n",
"You could use exec to run the code objects. For example, if you had f defined as above, then\nexec(f.func_code.co_consts[3])\n\nwould give \nget\n\nas output. \n",
"The inner function objects don't exist before the function f() is executed. If you want to get them you'll have to construct them yourself. That is definitely non-trivial because they might be closures that capture variables from the scope of the function and will anyway require poking around in objects that should probably be regarded as implementation details of the interpreter.\nIf you want to collect the functions with less repetition I recommend one of the following approaches:\na) Just put the functions in a class definition and return a reference to that class. A collection of related functions that are accessed by name smells awfully like a class.\nb) Create a dict subclass that has a method for registering functions and use that as a decorator.\nThe code for this would look something like this:\nclass FunctionCollector(dict):\n def register(self, func):\n self[func.__name__] = func\n\ndef f():\n funcs = FunctionCollector()\n @funcs.register\n def get():\n return 'get'\n @funcs.register\n def put():\n return 'put'\n return funcs\n\nc) Poke around in locals() and filter out the function with inspect.isfunction. (usually not a good idea)\n"
] |
[
4,
2,
2,
1
] |
[] |
[] |
[
"function",
"inspect",
"introspection",
"python"
] |
stackoverflow_0001234672_function_inspect_introspection_python.txt
|
Q:
py2app error: "can't copy '%s': doesn't exist or not a regular file"
I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:
File "C:\Python26\lib\distutils\file_util.py", line 119, in copy_file
"can't copy '%s': doesn't exist or not a regular file" % src
DistutilsFileError: can't copy '--dist-dir': doesn't exist or not a regular file
> c:\python26\lib\distutils\file_util.py(119)copy_file()
-> "can't copy '%s': doesn't exist or not a regular file" % src
Does anyone have any clue what I'm supposed to do?
A:
It looks like, for some reason or other, it's trying to interpret the command-line switch --dist-dir as a filename. Perhaps the actual switch is named something else and you typo'd it? Or perhaps it needs to be specified in a different order?
|
py2app error: "can't copy '%s': doesn't exist or not a regular file"
|
I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:
File "C:\Python26\lib\distutils\file_util.py", line 119, in copy_file
"can't copy '%s': doesn't exist or not a regular file" % src
DistutilsFileError: can't copy '--dist-dir': doesn't exist or not a regular file
> c:\python26\lib\distutils\file_util.py(119)copy_file()
-> "can't copy '%s': doesn't exist or not a regular file" % src
Does anyone have any clue what I'm supposed to do?
|
[
"It looks like, for some reason or other, it's trying to interpret the command-line switch --dist-dir as a filename. Perhaps the actual switch is named something else and you typo'd it? Or perhaps it needs to be specified in a different order?\n"
] |
[
2
] |
[] |
[] |
[
"macos",
"py2app",
"python"
] |
stackoverflow_0001236104_macos_py2app_python.txt
|
Q:
py2app error: "'module' object has no attribute 'symlink'"
I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 548, in _run
self.run_normal()
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 619, in run_normal
self.create_binaries(py_files, pkgdirs, extensions, loader_files)
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 710, in create_binaries
target, arcname, pkgexts, copyexts, target.script)
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 1067, in build_executable
self.symlink('../../site.py', os.path.join(pydir, 'site.py'))
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 377, in symlink
os.symlink(src, dst)
AttributeError: 'module' object has no attribute 'symlink'
> c:\python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py(377)s
ymlink()
-> os.symlink(src, dst)
Anyone has an idea?
A:
os.symlink is only available on Unix and Unix-like operating systems (including the Mac), not Windows.
py2app is for the Mac - are you deliberately running it on Windows? Did you mean to use py2exe?
|
py2app error: "'module' object has no attribute 'symlink'"
|
I'm trying to pack my Python app with py2app. I'm running the setup.py I created, and I get this error:
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 548, in _run
self.run_normal()
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 619, in run_normal
self.create_binaries(py_files, pkgdirs, extensions, loader_files)
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 710, in create_binaries
target, arcname, pkgexts, copyexts, target.script)
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 1067, in build_executable
self.symlink('../../site.py', os.path.join(pydir, 'site.py'))
File "C:\Python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py
", line 377, in symlink
os.symlink(src, dst)
AttributeError: 'module' object has no attribute 'symlink'
> c:\python26\lib\site-packages\py2app-0.3.6-py2.6.egg\py2app\build_app.py(377)s
ymlink()
-> os.symlink(src, dst)
Anyone has an idea?
|
[
"os.symlink is only available on Unix and Unix-like operating systems (including the Mac), not Windows.\npy2app is for the Mac - are you deliberately running it on Windows? Did you mean to use py2exe?\n"
] |
[
2
] |
[] |
[] |
[
"macos",
"py2app",
"python"
] |
stackoverflow_0001236172_macos_py2app_python.txt
|
Q:
In Twisted Python - Make sure a protocol instance would be completely deallocated
I have a pretty intensive chat socket server written in Twisted Python, I start it using internet.TCPServer with a factory and that factory references to a protocol object that handles all communications with the client.
How should I make sure a protocol instance completely destroys itself once a client has disconnected?
I've got a function named connectionLost that is fired up once a client disconnects and I try stopping all activity right there but I suspect some reactor stuff (like twisted.words instances) keep running for obsolete protocol instances.
What would be the best approach to handle this?
Thanks!
A:
ok, for sorting out this issue I have set a __del__ method in the protocol class and I am now logging protocol instances that have not been garbage collected within 1 minute from the time the client has disconnected.
If anybody has any better solution I'll still be glad to hear about it but so far I have already fixed a few potential memory leaks using this log.
Thanks!
|
In Twisted Python - Make sure a protocol instance would be completely deallocated
|
I have a pretty intensive chat socket server written in Twisted Python, I start it using internet.TCPServer with a factory and that factory references to a protocol object that handles all communications with the client.
How should I make sure a protocol instance completely destroys itself once a client has disconnected?
I've got a function named connectionLost that is fired up once a client disconnects and I try stopping all activity right there but I suspect some reactor stuff (like twisted.words instances) keep running for obsolete protocol instances.
What would be the best approach to handle this?
Thanks!
|
[
"ok, for sorting out this issue I have set a __del__ method in the protocol class and I am now logging protocol instances that have not been garbage collected within 1 minute from the time the client has disconnected. \nIf anybody has any better solution I'll still be glad to hear about it but so far I have already fixed a few potential memory leaks using this log.\nThanks!\n"
] |
[
0
] |
[] |
[] |
[
"python",
"sockets",
"twisted",
"twisted.words"
] |
stackoverflow_0001234292_python_sockets_twisted_twisted.words.txt
|
Q:
Creating multiple Python modules in different directories that share a portion of the package structure
I'm working on a Django project that contains a single application. The application will be released under the GPL so I want to develop it separately from the project - a personal site using the app. I'm attempting to use a package structure based on my domain name for both the project and the app, and that's where I'm running into problems.
Here's my file structure (with __init__.py files where appropriate):
$HOME/django-sites/mydomain
$HOME/django-apps/mydomain/cms
And my PYTHONPATH:
$HOME/django-sites:$HOME/django-apps
If I fire up a Python interpreter (from any directory on the filesystem) I can import classes from the site, but not the application. If I reverse the order of the two entries in the PYTHONPATH (apps first, then sites) I can import from the app but not the site.
It looks like Python's only attempting to import from the first entry in the PYTHONPATH that contains the first portion of the package name. Is that correct? Is this expected behavior? If so, I can only stick modules in package structures like domain/app1, domain/app2 if they live in the same directory structure - regardless of the PYTHONPATH.
It's not show-stopper because I can rename the site, but it's much different than I was expecting. The Python tutorial mentions __path__, but I have no idea how to use it:
Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.
While this feature is not often needed, it can be used to extend the set of modules found in a package.
Has anyone else come across this? Is there something I can do with __path__ to make this function as expected?
A:
Here's how __path__ in a package's __init__.py is intended to be used:
$ export PYTHONPATH=$HOME/django-sites
$ ls -d $HOME/django*
django-apps/ django-sites/
$ cat /tmp/django-sites/mydomain/__init__.py
import os
_components = __path__[0].split(os.path.sep)
if _components[-2] == 'django-sites':
_components[-2] = 'django-apps'
__path__.append(os.path.sep.join(_components))
$ python -c'import mydomain; import mydomain.foo'
foo here /tmp/django-apps/mydomain/foo.pyc
$
as you see, this makes the contents of django-apps/mydomain part of the mydomain package (whose __init__.py resides under django-sites/mydomain) -- you don't need django-apps on sys.path for this purpose, either, if you use this approach.
Whether this is a better arrangement than the one @defrex's answer suggests may be moot, but since a package's enriching its __path__ is a pretty important bit of a python programmer's bag of tools, I thought I had better illustrate it anyway;-).
A:
Your analysis seems about right. The python path is used to locate modules to import; python imports the first one it finds. I'm not sure what you could do to work around this other than name your modules different things or put them in the same location in the search path.
A:
You basically have two modules named the same thing (mydomain). Why not set up your PYTHONPATH like so?
$HOME/django-sites:$HOME/django-apps/mydomain
It would avoid your import problems.
|
Creating multiple Python modules in different directories that share a portion of the package structure
|
I'm working on a Django project that contains a single application. The application will be released under the GPL so I want to develop it separately from the project - a personal site using the app. I'm attempting to use a package structure based on my domain name for both the project and the app, and that's where I'm running into problems.
Here's my file structure (with __init__.py files where appropriate):
$HOME/django-sites/mydomain
$HOME/django-apps/mydomain/cms
And my PYTHONPATH:
$HOME/django-sites:$HOME/django-apps
If I fire up a Python interpreter (from any directory on the filesystem) I can import classes from the site, but not the application. If I reverse the order of the two entries in the PYTHONPATH (apps first, then sites) I can import from the app but not the site.
It looks like Python's only attempting to import from the first entry in the PYTHONPATH that contains the first portion of the package name. Is that correct? Is this expected behavior? If so, I can only stick modules in package structures like domain/app1, domain/app2 if they live in the same directory structure - regardless of the PYTHONPATH.
It's not show-stopper because I can rename the site, but it's much different than I was expecting. The Python tutorial mentions __path__, but I have no idea how to use it:
Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.
While this feature is not often needed, it can be used to extend the set of modules found in a package.
Has anyone else come across this? Is there something I can do with __path__ to make this function as expected?
|
[
"Here's how __path__ in a package's __init__.py is intended to be used:\n$ export PYTHONPATH=$HOME/django-sites\n$ ls -d $HOME/django*\ndjango-apps/ django-sites/ \n$ cat /tmp/django-sites/mydomain/__init__.py\nimport os\n\n_components = __path__[0].split(os.path.sep)\nif _components[-2] == 'django-sites':\n _components[-2] = 'django-apps'\n __path__.append(os.path.sep.join(_components))\n\n$ python -c'import mydomain; import mydomain.foo'\nfoo here /tmp/django-apps/mydomain/foo.pyc\n$ \n\nas you see, this makes the contents of django-apps/mydomain part of the mydomain package (whose __init__.py resides under django-sites/mydomain) -- you don't need django-apps on sys.path for this purpose, either, if you use this approach.\nWhether this is a better arrangement than the one @defrex's answer suggests may be moot, but since a package's enriching its __path__ is a pretty important bit of a python programmer's bag of tools, I thought I had better illustrate it anyway;-).\n",
"Your analysis seems about right. The python path is used to locate modules to import; python imports the first one it finds. I'm not sure what you could do to work around this other than name your modules different things or put them in the same location in the search path.\n",
"You basically have two modules named the same thing (mydomain). Why not set up your PYTHONPATH like so?\n$HOME/django-sites:$HOME/django-apps/mydomain\n\nIt would avoid your import problems.\n"
] |
[
4,
1,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001236443_django_python.txt
|
Q:
Is 'for x in array' always result in sorted x? [Python/NumPy]
For arrays and lists in Python and Numpy are the following lines equivalent:
itemlist = []
for j in range(len(myarray)):
item = myarray[j]
itemlist.append(item)
and:
itemlist = []
for item in myarray:
itemlist.append(item)
I'm interested in the order of itemlist. In a few examples that I have tried they are identical, but is it guaranteed? For example, I know that the foreach statement in C# doesn't guarantee order, and that I should be careful with it.
A:
Yes, it's entirely guaranteed. for item in myarray (where myarray is a sequence, which includes numpy's arrays, builtin lists, Python's array.arrays, etc etc), is in fact equivalent in Python to:
_aux = 0
while _aux < len(myarray):
item = myarray[_aux]
...etc...
for some phantom variable _aux;-). Btw, both of your constructs are also equivalent to
itemlist = list(myarray)
A:
It is guaranteed for lists. I think the more relevant Python parallel to your C# example would be to iterate over the keys in a dictionary, which is NOT guaranteed to be in any order.
# Always prints 0-9 in order
a_list = [0,1,2,3,4,5,6,7,8,9]
for x in a_list:
print x
# May or may not print 0-9 in order. Implementation dependent.
a_dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
for x in a_dict:
print x
The for <element> in <iterable> structure only worries that the iterable supplies a next() function which returns something. There is no general guarantee that these elements get returned in any order over the domain of the for..in statement; lists are a special case.
A:
Yes, the Python Language Reference guarantees this (emphasis is mine):
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
"The suite is then executed once for each item provided by the
iterator, in the order of ascending indices."
|
Is 'for x in array' always result in sorted x? [Python/NumPy]
|
For arrays and lists in Python and Numpy are the following lines equivalent:
itemlist = []
for j in range(len(myarray)):
item = myarray[j]
itemlist.append(item)
and:
itemlist = []
for item in myarray:
itemlist.append(item)
I'm interested in the order of itemlist. In a few examples that I have tried they are identical, but is it guaranteed? For example, I know that the foreach statement in C# doesn't guarantee order, and that I should be careful with it.
|
[
"Yes, it's entirely guaranteed. for item in myarray (where myarray is a sequence, which includes numpy's arrays, builtin lists, Python's array.arrays, etc etc), is in fact equivalent in Python to:\n_aux = 0\nwhile _aux < len(myarray):\n item = myarray[_aux]\n ...etc...\n\nfor some phantom variable _aux;-). Btw, both of your constructs are also equivalent to\nitemlist = list(myarray)\n\n",
"It is guaranteed for lists. I think the more relevant Python parallel to your C# example would be to iterate over the keys in a dictionary, which is NOT guaranteed to be in any order.\n# Always prints 0-9 in order\na_list = [0,1,2,3,4,5,6,7,8,9]\nfor x in a_list:\n print x\n\n# May or may not print 0-9 in order. Implementation dependent.\na_dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}\nfor x in a_dict:\n print x\n\nThe for <element> in <iterable> structure only worries that the iterable supplies a next() function which returns something. There is no general guarantee that these elements get returned in any order over the domain of the for..in statement; lists are a special case.\n",
"Yes, the Python Language Reference guarantees this (emphasis is mine):\n for_stmt ::= \"for\" target_list \"in\" expression_list \":\" suite\n [\"else\" \":\" suite]\n\n\n\"The suite is then executed once for each item provided by the\n iterator, in the order of ascending indices.\"\n\n"
] |
[
10,
10,
6
] |
[] |
[] |
[
"arrays",
"list",
"numpy",
"python"
] |
stackoverflow_0001236695_arrays_list_numpy_python.txt
|
Q:
Are there any examples on python-purple floating around?
I want to learn it but I have no idea where to start. Everything out there suggests reading the libpurple source but I don't think I understand enough c to really get a grasp of it.
A:
There isn't much about it yet... the intro, the howto, and the sources (here browsing them online but of course you can git clone them) are about it. In particular, the tiny example client you can get from here does have some miniscule example of use of purple's facilities (definitely not enough, but maybe it can get you started with the help of some 'dir', 'help' and the like...?)
A:
Not sure how much help this will be but based on information from here, it seems like you just install python-purple and import and call the functions as normal Python functions.
A:
Can't help you with a concrete example as I decided to use something else. However, one of the first things I wanted to do after I cloned the repo was remove the ecore dependency. Here's a patch submitted to the mailing list to do just that: https://garage.maemo.org/pipermail/python-purple-devel/2009-March/000000.html
Incidentally, if you're looking for AIM take a look at twisted.words. For Yahoo, trying getting the source for curphoo or zinc (both are console YMSG clients). For GTalk/Jabber, I've had good experiences with xmpppy.
|
Are there any examples on python-purple floating around?
|
I want to learn it but I have no idea where to start. Everything out there suggests reading the libpurple source but I don't think I understand enough c to really get a grasp of it.
|
[
"There isn't much about it yet... the intro, the howto, and the sources (here browsing them online but of course you can git clone them) are about it. In particular, the tiny example client you can get from here does have some miniscule example of use of purple's facilities (definitely not enough, but maybe it can get you started with the help of some 'dir', 'help' and the like...?)\n",
"Not sure how much help this will be but based on information from here, it seems like you just install python-purple and import and call the functions as normal Python functions.\n",
"Can't help you with a concrete example as I decided to use something else. However, one of the first things I wanted to do after I cloned the repo was remove the ecore dependency. Here's a patch submitted to the mailing list to do just that: https://garage.maemo.org/pipermail/python-purple-devel/2009-March/000000.html\nIncidentally, if you're looking for AIM take a look at twisted.words. For Yahoo, trying getting the source for curphoo or zinc (both are console YMSG clients). For GTalk/Jabber, I've had good experiences with xmpppy.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"libpurple",
"python"
] |
stackoverflow_0001186062_libpurple_python.txt
|
Q:
Cron job python Google App Engine
I want to add a scheduled task to fetch a URL via cron job using google app engine. I am continuously getting a failure. I am just fetching www.google.com. Why is the url fetch failing? Am I missing something?
A:
"fetch" your OWN url (on appspot.com probably, but, who cares -- use a relative url anywau1-), not google.com, the homepage of the search engine -- what's that got to do w/your app anyway?!-)...
|
Cron job python Google App Engine
|
I want to add a scheduled task to fetch a URL via cron job using google app engine. I am continuously getting a failure. I am just fetching www.google.com. Why is the url fetch failing? Am I missing something?
|
[
"\"fetch\" your OWN url (on appspot.com probably, but, who cares -- use a relative url anywau1-), not google.com, the homepage of the search engine -- what's that got to do w/your app anyway?!-)...\n"
] |
[
0
] |
[] |
[] |
[
"cron",
"google_app_engine",
"python",
"scheduled_tasks"
] |
stackoverflow_0001237126_cron_google_app_engine_python_scheduled_tasks.txt
|
Q:
wxPython gauge problem (skipping)
Pastebin link: http://pastebin.com/f40ae1bcf
The problem: I made a wx.Gauge, with the range of 50. Then a function that updates Gauge's value when the program is idle. When the gauge is filled by around 50% it empties and doesn't show anything for a while. The value is actually 50 when it does this, and I think that when the value is 50 it should be full.
Why does it do this? I also tried with a wx.Timer instead of binding to wx.EVT_IDLE but I didn't have luck.
A:
A few things.
I can't reproduce this on my iMac, it goes all the way to full. Python 2.5.4, wxPython 2.8.9.2
Idle events can come at strange times. Try adding print event to your idle handler to see exactly when those events are coming. A timer would be best. Is the gauge moving really fast or flickering?
You can try calling gauge.Update() to force a complete redraw too.
I always just use 100 as my gauge limit, maybe just try that.
An easier way than a timer could be:
import wx
class GaugeFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "Gauge example",
size=(350, 150))
panel = wx.Panel(self, -1)
self.count = 0
self.gauge = wx.Gauge(panel, -1, 50, (20, 50), (250, 25))
self.update_gauge()
def update_gauge(self):
self.count = self.count + 1
if self.count >= 50:
self.count = 0
self.gauge.SetValue(self.count)
wx.CallLater(100, self.update_gauge)
app = wx.PySimpleApp()
GaugeFrame().Show()
app.MainLoop()
A:
Are you sure that the code you posted is the code that is giving you the problems? This code looks very similar to the demo code for wxPython, and works on my machine without problems.
If you did actually set your gauge's value to 50, that could be your issue. You have to be sure not to exceed that range of a wx.Gauge. If the range is 50, the highest value you can set in it will be 49.
A:
After more tests I discovered that I must override the range of 2 units to display the gauge when completely full.
On windows vista it seems not to cause problems. Does it cause problems on linux or mac?
|
wxPython gauge problem (skipping)
|
Pastebin link: http://pastebin.com/f40ae1bcf
The problem: I made a wx.Gauge, with the range of 50. Then a function that updates Gauge's value when the program is idle. When the gauge is filled by around 50% it empties and doesn't show anything for a while. The value is actually 50 when it does this, and I think that when the value is 50 it should be full.
Why does it do this? I also tried with a wx.Timer instead of binding to wx.EVT_IDLE but I didn't have luck.
|
[
"A few things.\n\nI can't reproduce this on my iMac, it goes all the way to full. Python 2.5.4, wxPython 2.8.9.2\nIdle events can come at strange times. Try adding print event to your idle handler to see exactly when those events are coming. A timer would be best. Is the gauge moving really fast or flickering?\nYou can try calling gauge.Update() to force a complete redraw too.\nI always just use 100 as my gauge limit, maybe just try that.\n\nAn easier way than a timer could be:\nimport wx\n\nclass GaugeFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, -1, \"Gauge example\",\n size=(350, 150))\n panel = wx.Panel(self, -1)\n self.count = 0\n self.gauge = wx.Gauge(panel, -1, 50, (20, 50), (250, 25))\n self.update_gauge()\n\n def update_gauge(self):\n self.count = self.count + 1\n if self.count >= 50:\n self.count = 0\n self.gauge.SetValue(self.count)\n wx.CallLater(100, self.update_gauge)\n\napp = wx.PySimpleApp()\nGaugeFrame().Show()\napp.MainLoop()\n\n",
"Are you sure that the code you posted is the code that is giving you the problems? This code looks very similar to the demo code for wxPython, and works on my machine without problems.\nIf you did actually set your gauge's value to 50, that could be your issue. You have to be sure not to exceed that range of a wx.Gauge. If the range is 50, the highest value you can set in it will be 49.\n",
"After more tests I discovered that I must override the range of 2 units to display the gauge when completely full.\nOn windows vista it seems not to cause problems. Does it cause problems on linux or mac?\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0001235884_python_wxpython.txt
|
Q:
launching vs2008 build from python
The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?
As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes devenv without the necessary context.
os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')
think of it as in i'm in bash, and i need to execute a command in a perl context, so i type perl -c 'asdf'. executing perl and asdf back to back won't work, i need to get the devenv inside of the perl context.
A:
I think that the proper way for achieving this would be running this command:
%comspec% /C "%VCINSTALLDIR%\vcvarsall.bat" x86 && vcbuild "project.sln"
Below you'll see the Python version of the same command:
os.system('%comspec% /C "%VCINSTALLDIR%\\vcvarsall.bat" x86 && vcbuild "project.sln"')
This should work with any Visual Studio so it would be a good idea to edit the question to make it more generic.
There is a small problem I found regarding the location of vcvarsall.bat - Because VCINSTALLDIR is not always set, you have to use the registry entries in order to detect the location where it is installer:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0]
"InstallDir"="c:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\"
Add ..\..\VC\vcvarsall.bat to this path. Also is a good idea to test for other versions of Visual Studio.
A:
You could append the devenv command onto the end of the original batch file like so:
'%comspec% /k "...vcvarsall.bat" x86 && devenv asdf.sln /rebuild ...'
(obviously I have shortened the commands for simplicity's sake)
A:
I these situations I use script that does it all. That way you can chain as much as you want. Sometimes I will generate the script on the fly.
compileit.cmd
call C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat
devenv $1.sln /rebuild Debug /Out last-build.txt
A:
I run my Python script from a batch file that sets the variables :-)
call ...\vcvarsall.bat
c:\python26\python.exe myscript.py
But Brett's solution sounds better.
|
launching vs2008 build from python
|
The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?
As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes devenv without the necessary context.
os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')
think of it as in i'm in bash, and i need to execute a command in a perl context, so i type perl -c 'asdf'. executing perl and asdf back to back won't work, i need to get the devenv inside of the perl context.
|
[
"I think that the proper way for achieving this would be running this command:\n%comspec% /C \"%VCINSTALLDIR%\\vcvarsall.bat\" x86 && vcbuild \"project.sln\"\n\nBelow you'll see the Python version of the same command:\nos.system('%comspec% /C \"%VCINSTALLDIR%\\\\vcvarsall.bat\" x86 && vcbuild \"project.sln\"')\n\nThis should work with any Visual Studio so it would be a good idea to edit the question to make it more generic.\nThere is a small problem I found regarding the location of vcvarsall.bat - Because VCINSTALLDIR is not always set, you have to use the registry entries in order to detect the location where it is installer:\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0]\n\"InstallDir\"=\"c:\\\\Program Files\\\\Microsoft Visual Studio 9.0\\\\Common7\\\\IDE\\\\\"\n\nAdd ..\\..\\VC\\vcvarsall.bat to this path. Also is a good idea to test for other versions of Visual Studio.\n",
"You could append the devenv command onto the end of the original batch file like so:\n'%comspec% /k \"...vcvarsall.bat\" x86 && devenv asdf.sln /rebuild ...'\n\n(obviously I have shortened the commands for simplicity's sake)\n",
"I these situations I use script that does it all. That way you can chain as much as you want. Sometimes I will generate the script on the fly.\ncompileit.cmd\n call C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\n devenv $1.sln /rebuild Debug /Out last-build.txt\n\n",
"I run my Python script from a batch file that sets the variables :-)\ncall ...\\vcvarsall.bat\nc:\\python26\\python.exe myscript.py\n\nBut Brett's solution sounds better.\n"
] |
[
3,
2,
2,
2
] |
[] |
[] |
[
"build_automation",
"python",
"visual_studio_2008",
"windows"
] |
stackoverflow_0000263820_build_automation_python_visual_studio_2008_windows.txt
|
Q:
how to overwrite User model
I don't like models.User, but I like Admin view, and I will keep admin view in my application.
How to overwirte models.User ?
Make it just look like following:
from django.contrib.auth.models import User
class ShugeUser(User)
username = EmailField(uniqute=True, verbose_name='EMail as your
username', ...)
email = CharField(verbose_name='Nickname, ...)
User = ShugeUser
A:
That isn't possible right now. If all you want is to use the email address as the username, you could write a custom auth backend that checks if the email/password combination is correct instead of the username/password combination (here's an example from djangosnippets.org).
If you want more, you'll have to hack up Django pretty badly, or wait until Django better supports subclassing of the User model (according to this conversation on the django-users mailing list, it could happen as soon as Django 1.2, but don't count on it).
A:
The answer above is good and we use it on several sites successfully. I want to also point out though that many times people want to change the User model they are adding more information fields. This can be accommodated with the built in user profile support in the the contrib admin module.
You access the profile by utilizing the get_profile() method of a User object.
Related documentation is available here.
|
how to overwrite User model
|
I don't like models.User, but I like Admin view, and I will keep admin view in my application.
How to overwirte models.User ?
Make it just look like following:
from django.contrib.auth.models import User
class ShugeUser(User)
username = EmailField(uniqute=True, verbose_name='EMail as your
username', ...)
email = CharField(verbose_name='Nickname, ...)
User = ShugeUser
|
[
"That isn't possible right now. If all you want is to use the email address as the username, you could write a custom auth backend that checks if the email/password combination is correct instead of the username/password combination (here's an example from djangosnippets.org).\nIf you want more, you'll have to hack up Django pretty badly, or wait until Django better supports subclassing of the User model (according to this conversation on the django-users mailing list, it could happen as soon as Django 1.2, but don't count on it).\n",
"The answer above is good and we use it on several sites successfully. I want to also point out though that many times people want to change the User model they are adding more information fields. This can be accommodated with the built in user profile support in the the contrib admin module.\nYou access the profile by utilizing the get_profile() method of a User object.\nRelated documentation is available here.\n"
] |
[
4,
0
] |
[] |
[] |
[
"django",
"django_admin",
"django_models",
"python"
] |
stackoverflow_0001231943_django_django_admin_django_models_python.txt
|
Q:
Choose the filename of an uploaded file with Django
I'm uploading images (represented by a FileField) and I need to rename those files when they are uploaded.
I want them to be formated like that:
"%d-%d-%s.%s" % (width, height, md5hash, original_extension)
I've read the documentation but I don't know if I need to write my own FileSystemStorage class or my own FileField class or ... ? Everything is so linked I don't know where to start.
A:
You don't need to write your own FileStorage class or anything that complicated.
The 'upload_to' parameter on File/ImageFields can take a function that returns the path/file to use.
How to do this has already been answered here
|
Choose the filename of an uploaded file with Django
|
I'm uploading images (represented by a FileField) and I need to rename those files when they are uploaded.
I want them to be formated like that:
"%d-%d-%s.%s" % (width, height, md5hash, original_extension)
I've read the documentation but I don't know if I need to write my own FileSystemStorage class or my own FileField class or ... ? Everything is so linked I don't know where to start.
|
[
"You don't need to write your own FileStorage class or anything that complicated.\nThe 'upload_to' parameter on File/ImageFields can take a function that returns the path/file to use.\nHow to do this has already been answered here\n"
] |
[
19
] |
[
"My initial instinct when reading this was that you need to overload the save method on the model, and use the os.rename() method, but that causes a lot of overhead, and is just generally a hassle from start to finish. If you simply want to rename the file, but don't want to make any physical changes to it (resizing, duplicating, etc.), then I'd definitely recommend the approach arcanum suggests above.\n"
] |
[
-1
] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0001237602_django_django_models_python.txt
|
Q:
Is it possible to utilize a python module that isnt installed into the python directories in linux?
I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?
A:
There are several ways to do this. The fastest is the simple command:
export PYTHONPATH=path/to/module/directory
Alternatively, you can use virtualenv. Just sudo apt-get install python-virtualenv (?). It's a very common development tool used for using modules that you don't necessarily want installed in your local Python installation.
A:
If it's a single module I would consider including it on my project path. If it's something more complex (like a package, binary files, etc) and I don't want to modify the project sys.path (for example because it's the source of Django and I don't want to mess with updates) I install the package somewhere and then I add the path to a .pth file on my project directory (the current directory is always on the Python Path.) This way you don't have to be playing with your PYTHONPATH or project sys.path.
You can check the format of the pth files here:
http://bob.pythonmac.org/archives/2005/02/06/using-pth-files-for-python-development/
A:
Yes, there's no need to install most Python modules. uuid.py is simple enough you don't need to build or install it at all. Just download it, unpack it, and place the uuid.py file in your directory with your code. "import uuid" will work (the current working directory is in the Python path). This hack works fine up until you are doing serious application deployment management.
BTW, I believe the uuid module is installed already with Python 2.5 and above.
A:
Python looks for modules to import by means of the sys.path variable. You can change this in your program to point to new modules your program needs. By default this will include the programs own directory as well as the python system directories, but you can certainly add just about anything to it.
Link to the docs!
A:
To follow up on this in the future this is addressed in [PEP 370][1] a good blog article explain how it works here [http://jessenoller.com/2009/07/19/pep-370-per-user-site-packages-and-environment-stew/][2].
To install packages you can as well have a look to [virtualenv][3] and [pip][4] which give you the ultimate way to have a clean environment.
|
Is it possible to utilize a python module that isnt installed into the python directories in linux?
|
I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?
|
[
"There are several ways to do this. The fastest is the simple command:\nexport PYTHONPATH=path/to/module/directory\n\nAlternatively, you can use virtualenv. Just sudo apt-get install python-virtualenv (?). It's a very common development tool used for using modules that you don't necessarily want installed in your local Python installation.\n",
"If it's a single module I would consider including it on my project path. If it's something more complex (like a package, binary files, etc) and I don't want to modify the project sys.path (for example because it's the source of Django and I don't want to mess with updates) I install the package somewhere and then I add the path to a .pth file on my project directory (the current directory is always on the Python Path.) This way you don't have to be playing with your PYTHONPATH or project sys.path.\nYou can check the format of the pth files here:\nhttp://bob.pythonmac.org/archives/2005/02/06/using-pth-files-for-python-development/\n",
"Yes, there's no need to install most Python modules. uuid.py is simple enough you don't need to build or install it at all. Just download it, unpack it, and place the uuid.py file in your directory with your code. \"import uuid\" will work (the current working directory is in the Python path). This hack works fine up until you are doing serious application deployment management.\nBTW, I believe the uuid module is installed already with Python 2.5 and above.\n",
"Python looks for modules to import by means of the sys.path variable. You can change this in your program to point to new modules your program needs. By default this will include the programs own directory as well as the python system directories, but you can certainly add just about anything to it.\nLink to the docs!\n",
"To follow up on this in the future this is addressed in [PEP 370][1] a good blog article explain how it works here [http://jessenoller.com/2009/07/19/pep-370-per-user-site-packages-and-environment-stew/][2].\nTo install packages you can as well have a look to [virtualenv][3] and [pip][4] which give you the ultimate way to have a clean environment.\n"
] |
[
5,
1,
0,
0,
0
] |
[] |
[] |
[
"linux",
"python"
] |
stackoverflow_0001213448_linux_python.txt
|
Q:
What does % do to strings in Python?
I have failed to find documentation for the operator % as it is used on strings in Python. What does this operator do when it is used with a string on the left hand side?
A:
It's the string formatting operator. Read up on string formatting in Python.
format % values
Creates a string where format specifies a format and values are the values to be filled in.
A:
It applies printf-like formatting to a string, so that you can substitute certain parts of a string with values of variables.
Example
# assuming numFiles is an int variable
print "Found %d files" % (numFiles, )
See the link provided by Konrad
A:
Note that starting from Python 2.6, it's recommended to use the new str.format() method:
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
If you are using 2.6, you may want to keep using % in order to remain compatible with older versions, but in Python 3 there's no reason not to use str.format().
A:
The '%' operator is used for string interpolation. Since Python 2.6 the String method "format" is used insted. For details see http://www.python.org/dev/peps/pep-3101/
|
What does % do to strings in Python?
|
I have failed to find documentation for the operator % as it is used on strings in Python. What does this operator do when it is used with a string on the left hand side?
|
[
"It's the string formatting operator. Read up on string formatting in Python.\nformat % values\n\nCreates a string where format specifies a format and values are the values to be filled in.\n",
"It applies printf-like formatting to a string, so that you can substitute certain parts of a string with values of variables.\nExample\n# assuming numFiles is an int variable\nprint \"Found %d files\" % (numFiles, )\n\nSee the link provided by Konrad\n",
"Note that starting from Python 2.6, it's recommended to use the new str.format() method:\n>>> \"The sum of 1 + 2 is {0}\".format(1+2)\n'The sum of 1 + 2 is 3'\n\nIf you are using 2.6, you may want to keep using % in order to remain compatible with older versions, but in Python 3 there's no reason not to use str.format().\n",
"The '%' operator is used for string interpolation. Since Python 2.6 the String method \"format\" is used insted. For details see http://www.python.org/dev/peps/pep-3101/\n"
] |
[
39,
9,
8,
6
] |
[] |
[] |
[
"documentation",
"operators",
"python",
"string"
] |
stackoverflow_0001238306_documentation_operators_python_string.txt
|
Q:
Does 'a+' mode allow random access to files, on all systems?
According to the documentation of open function
'a' means appending, which on some Unix systems means that all writes append to the end of the file regardless of the current seek position.
Will 'a+' allow random writes to any position in the file on all systems?
A:
On my linux system with Python 2.5.2 writes to a file opened with 'a+' appear to always append to the end, regardless of the current seek position.
Here is an example:
import os
if __name__ == "__main__":
f = open("test", "w")
f.write("Hello")
f.close()
f = open("test", "a+")
f.seek(0, os.SEEK_SET)
f.write("Goodbye")
f.close()
On my system (event though I seeked to the beginning of the file) this results in the file "test" containing:
HelloGoodbye
The python documentation says that the mode argument is the same as stdio's.
The linux man page for fopen() does say that (emphasis added):
Opening a file in append mode (a as
the first character of mode) causes
all subsequent write operations to
this stream to occur at end-of-file,
as if preceded by an
fseek(stream,0,SEEK_END);
call.
My stdio reference says that appending a '+' to the mode (i.e. 'a+') means that the stream is opened for input and output. However before switching between input and output a call must be made to explicitly set the file position.
So adding the '+' doesn't change the fact that on some systems writes for a file opened in 'a' or 'a+' mode will always append to the end of the file.
|
Does 'a+' mode allow random access to files, on all systems?
|
According to the documentation of open function
'a' means appending, which on some Unix systems means that all writes append to the end of the file regardless of the current seek position.
Will 'a+' allow random writes to any position in the file on all systems?
|
[
"On my linux system with Python 2.5.2 writes to a file opened with 'a+' appear to always append to the end, regardless of the current seek position.\nHere is an example:\nimport os\n\nif __name__ == \"__main__\":\n\n f = open(\"test\", \"w\")\n f.write(\"Hello\")\n f.close()\n\n f = open(\"test\", \"a+\")\n f.seek(0, os.SEEK_SET)\n f.write(\"Goodbye\")\n f.close()\n\nOn my system (event though I seeked to the beginning of the file) this results in the file \"test\" containing:\n\nHelloGoodbye\n\nThe python documentation says that the mode argument is the same as stdio's.\nThe linux man page for fopen() does say that (emphasis added):\n\nOpening a file in append mode (a as\n the first character of mode) causes\n all subsequent write operations to\n this stream to occur at end-of-file,\n as if preceded by an\nfseek(stream,0,SEEK_END);\n\ncall.\n\nMy stdio reference says that appending a '+' to the mode (i.e. 'a+') means that the stream is opened for input and output. However before switching between input and output a call must be made to explicitly set the file position.\nSo adding the '+' doesn't change the fact that on some systems writes for a file opened in 'a' or 'a+' mode will always append to the end of the file.\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001238922_python.txt
|
Q:
Can all language constructs be first-class in languages with offside-rules?
In LISP-like languages all language constructs are first-class citizens.
Consider the following example in Dylan:
let x = if (c)
foo();
else
bar();
end;
and in LISP:
(setf x (if c (foo) (bar)))
In Python you would have to write:
if c:
x = foo();
else:
x = bar();
Because Python destinguishes statements and expressions.
Can all language constructs in a language which adheres to the off-side rule (has an indention-based syntax) be expressions, so that you can assign them to variables or pass them as parameters?
A:
Python has the following syntax that performs the same thing:
x = foo() if c else bar()
A:
I don't see the relation with first-classness here - you're not passing the if statement to the function, but the object it returns, which is as fully first class in python as in lisp. However as far as having a statement/expression dichotomy, clearly it is possible: Haskell for instance has indentation-based syntax, yet as a purely functional language obviously has no statements.
I think Python's separation here has more to do with forbidding dangerous constructs like "if x=4:" etc than any syntax limitation. (Though I think it loses more than it gains by this - sometimes having the flexibility sufficient to shoot off your foot is very valuable, even if you do risk losing a few toes now and again.)
|
Can all language constructs be first-class in languages with offside-rules?
|
In LISP-like languages all language constructs are first-class citizens.
Consider the following example in Dylan:
let x = if (c)
foo();
else
bar();
end;
and in LISP:
(setf x (if c (foo) (bar)))
In Python you would have to write:
if c:
x = foo();
else:
x = bar();
Because Python destinguishes statements and expressions.
Can all language constructs in a language which adheres to the off-side rule (has an indention-based syntax) be expressions, so that you can assign them to variables or pass them as parameters?
|
[
"Python has the following syntax that performs the same thing:\nx = foo() if c else bar()\n\n",
"I don't see the relation with first-classness here - you're not passing the if statement to the function, but the object it returns, which is as fully first class in python as in lisp. However as far as having a statement/expression dichotomy, clearly it is possible: Haskell for instance has indentation-based syntax, yet as a purely functional language obviously has no statements.\nI think Python's separation here has more to do with forbidding dangerous constructs like \"if x=4:\" etc than any syntax limitation. (Though I think it loses more than it gains by this - sometimes having the flexibility sufficient to shoot off your foot is very valuable, even if you do risk losing a few toes now and again.)\n"
] |
[
9,
5
] |
[] |
[] |
[
"expression",
"if_statement",
"indentation",
"lisp",
"python"
] |
stackoverflow_0001238975_expression_if_statement_indentation_lisp_python.txt
|
Q:
comparing and sorting array
From two unequal arrays, i need to compare & delete based on the last value of an array.
Example:
m[0] and n[0] are read form a text file & saved as a array, [0] - their column number in text file.
m[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40, 3.80, 4.10, 4.21, 4.44]
n[0] = [0.00, 1.12, 1.34, 1.45, 2.54, 3.12, 3.57]
n[0] last value is 3.57, it lies between 3.40 and 3.80 of m[0] so I need to print till 3.40 inm[0]`
Required output:
p[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40]
A:
Some details are a little unclear, but this should do what you want:
p[0] = [x for x in m[0] if x < n[0][-1]]
A:
if both lists are ordered, you can do:
import bisect
m[0][:bisect.bisect(m[0],n[0][-1])]
A:
I haven't been able to test this but here you go...
p = []
for item in m[0]:
if (item < n[0][-1]):
p.append(item)
else:
break
|
comparing and sorting array
|
From two unequal arrays, i need to compare & delete based on the last value of an array.
Example:
m[0] and n[0] are read form a text file & saved as a array, [0] - their column number in text file.
m[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40, 3.80, 4.10, 4.21, 4.44]
n[0] = [0.00, 1.12, 1.34, 1.45, 2.54, 3.12, 3.57]
n[0] last value is 3.57, it lies between 3.40 and 3.80 of m[0] so I need to print till 3.40 inm[0]`
Required output:
p[0] = [0.00, 1.15, 1.24, 1.35, 1.54, 2.32, 2.85, 3.10, 3.40]
|
[
"Some details are a little unclear, but this should do what you want:\np[0] = [x for x in m[0] if x < n[0][-1]]\n\n",
"if both lists are ordered, you can do:\nimport bisect\nm[0][:bisect.bisect(m[0],n[0][-1])]\n\n",
"I haven't been able to test this but here you go...\np = []\nfor item in m[0]:\n if (item < n[0][-1]):\n p.append(item)\n else:\n break\n\n"
] |
[
6,
1,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001239509_list_python.txt
|
Q:
Pythonic Comparison Functions
For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.
class Person:
def __init__(self, firstname, lastname, dob):
self.firstname = firstname;
self.lastname = lastname;
self.dob = dob;
In some situations I want to sort lists of Persons by lastname followed by firstname followed by dob. In other situations I want to sort first by dob, then by lastname and finally by firstname. And sometimes I just want to sort by firstname.
The naive solution for creating the first comparison function would be something like this:
def comparepeople(person1, person2):
if cmp(person1.lastname, person2.lastname) == 0:
if cmp(person1.firstname, person2.firstname) == 0:
return cmp(person1.dob, person2.dob);
return cmp(person1.firstname, person2.firstname);
return cmp(person1.lastname, person2.lastname);
It would seem like there should be an easy way to define comparison functions like these using a meta-programming approach where all I would need to do is provide the field names in order of precedence instead of writing these very verbose, ugly comparison methods. But I've only started playing with Python recently and haven't found anything like what I'm describing.
So the question is, what is the most Pythonic way to write a comparison function for a class with multiple comparable constituent members?
A:
If you really want a comparison function, you can use
def comparepeople(p1, p2):
o1 = p1.lastname, p1.firstname, p1.dob
o2 = p2.lastname, p2.firstname, p2.dob
return cmp(o1,o2)
This relies on tuple comparison. If you want to sort a list, you shouldn't write a comparison function, though, but a key function:
l.sort(key=lambda p:(p.lastname, p.firstname, p.dob))
This has the advantage that it is a) shorter and b) faster, because each key gets computed only once (rather than tons of tuples being created in the comparison function during sorting).
A:
Here's one way (maybe not the fastest):
def compare_people_flexibly(p1, p2, attrs):
"""Compare `p1` and `p2` based on the attributes in `attrs`."""
v1 = [getattr(p1, a) for a in attrs]
v2 = [getattr(p2, a) for a in attrs]
return cmp(v1, v2)
def compare_people_firstname(p1, p2):
return compare_people_flexibly(p1, p2, ['firstname', 'lastname', 'dob'])
def compare_people_lastname(p1, p2):
return compare_people_flexibly(p1, p2, ['lastname', 'firstname', 'dob'])
This works because getattr can be used to get attributes named by a string, and because Python compares lists as you'd expect, based on the comparison of the first non-equal items.
Another way:
def compare_people_flexibly(p1, p2, attrs):
"""Compare `p1` and `p2` based on the attributes in `attrs`."""
for a in attrs:
c = cmp(getattr(p1, a), getattr(p2, a))
if c:
return c
return 0
This has the advantage that it doesn't build two complete lists of attributes, so may be faster if the attribute lists are long, or if many comparisons complete on the first attribute.
Lastly, as Martin mentions, you may need a key function rather than a comparison function:
def flexible_person_key(attrs):
def key(p):
return [getattr(p, a) for a in attrs]
return key
l.sort(key=flexible_person_key('firstname', 'lastname', 'dob'))
A:
Can you not use the comparison methods on the class, see __cmp__ and the other rich comparison methods...
|
Pythonic Comparison Functions
|
For the sake of simplicity, let's say I have a Person class in Python. This class has fields for firstname, lastname, and dob.
class Person:
def __init__(self, firstname, lastname, dob):
self.firstname = firstname;
self.lastname = lastname;
self.dob = dob;
In some situations I want to sort lists of Persons by lastname followed by firstname followed by dob. In other situations I want to sort first by dob, then by lastname and finally by firstname. And sometimes I just want to sort by firstname.
The naive solution for creating the first comparison function would be something like this:
def comparepeople(person1, person2):
if cmp(person1.lastname, person2.lastname) == 0:
if cmp(person1.firstname, person2.firstname) == 0:
return cmp(person1.dob, person2.dob);
return cmp(person1.firstname, person2.firstname);
return cmp(person1.lastname, person2.lastname);
It would seem like there should be an easy way to define comparison functions like these using a meta-programming approach where all I would need to do is provide the field names in order of precedence instead of writing these very verbose, ugly comparison methods. But I've only started playing with Python recently and haven't found anything like what I'm describing.
So the question is, what is the most Pythonic way to write a comparison function for a class with multiple comparable constituent members?
|
[
"If you really want a comparison function, you can use\ndef comparepeople(p1, p2):\n o1 = p1.lastname, p1.firstname, p1.dob\n o2 = p2.lastname, p2.firstname, p2.dob\n return cmp(o1,o2)\n\nThis relies on tuple comparison. If you want to sort a list, you shouldn't write a comparison function, though, but a key function:\nl.sort(key=lambda p:(p.lastname, p.firstname, p.dob))\n\nThis has the advantage that it is a) shorter and b) faster, because each key gets computed only once (rather than tons of tuples being created in the comparison function during sorting).\n",
"Here's one way (maybe not the fastest):\ndef compare_people_flexibly(p1, p2, attrs):\n \"\"\"Compare `p1` and `p2` based on the attributes in `attrs`.\"\"\"\n v1 = [getattr(p1, a) for a in attrs]\n v2 = [getattr(p2, a) for a in attrs]\n return cmp(v1, v2)\n\ndef compare_people_firstname(p1, p2):\n return compare_people_flexibly(p1, p2, ['firstname', 'lastname', 'dob'])\n\ndef compare_people_lastname(p1, p2):\n return compare_people_flexibly(p1, p2, ['lastname', 'firstname', 'dob'])\n\nThis works because getattr can be used to get attributes named by a string, and because Python compares lists as you'd expect, based on the comparison of the first non-equal items.\nAnother way:\ndef compare_people_flexibly(p1, p2, attrs):\n \"\"\"Compare `p1` and `p2` based on the attributes in `attrs`.\"\"\"\n for a in attrs:\n c = cmp(getattr(p1, a), getattr(p2, a))\n if c:\n return c\n return 0\n\nThis has the advantage that it doesn't build two complete lists of attributes, so may be faster if the attribute lists are long, or if many comparisons complete on the first attribute.\nLastly, as Martin mentions, you may need a key function rather than a comparison function:\ndef flexible_person_key(attrs):\n def key(p):\n return [getattr(p, a) for a in attrs]\n return key\n\nl.sort(key=flexible_person_key('firstname', 'lastname', 'dob'))\n\n",
"Can you not use the comparison methods on the class, see __cmp__ and the other rich comparison methods...\n"
] |
[
10,
4,
0
] |
[] |
[] |
[
"comparison",
"metaprogramming",
"python"
] |
stackoverflow_0001239751_comparison_metaprogramming_python.txt
|
Q:
is it ever useful to define a class method with a reference to self not called 'self' in Python?
I'm teaching myself Python and I see the following in Dive into Python section 5.3:
By convention, the first argument of any Python class method (the reference to the current instance) is called self. This argument fills the role of the reserved word this in C++ or Java, but self is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but self; this is a very strong convention.
Considering that self is not a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it not a keyword?
A:
No, unless you want to confuse every other programmer that looks at your code after you write it. self is not a keyword because it is an identifier. It could have been a keyword and the fact that it isn't one was a design decision.
A:
As a side observation, note that Pilgrim is committing a common misuse of terms here: a class method is quite a different thing from an instance method, which is what he's talking about here. As wikipedia puts it, "a method is a subroutine that is exclusively associated either with a class (in which case it is called a class method or a static method) or with an object (in which case it is an instance method).". Python's built-ins include a staticmethod type, to make static methods, and a classmethod type, to make class methods, each generally used as a decorator; if you don't use either, a def in a class body makes an instance method. E.g.:
>>> class X(object):
... def noclass(self): print self
... @classmethod
... def withclass(cls): print cls
...
>>> x = X()
>>> x.noclass()
<__main__.X object at 0x698d0>
>>> x.withclass()
<class '__main__.X'>
>>>
As you see, the instance method noclass gets the instance as its argument, but the class method withclass gets the class instead.
So it would be extremely confusing and misleading to use self as the name of the first parameter of a class method: the convention in this case is instead to use cls, as in my example above. While this IS just a convention, there is no real good reason for violating it -- any more than there would be, say, for naming a variable number_of_cats if the purpose of the variable is counting dogs!-)
A:
The only case of this I've seen is when you define a function outside of a class definition, and then assign it to the class, e.g.:
class Foo(object):
def bar(self):
# Do something with 'self'
def baz(inst):
return inst.bar()
Foo.baz = baz
In this case, self is a little strange to use, because the function could be applied to many classes. Most often I've seen inst or cls used instead.
A:
I once had some code like (and I apologize for lack of creativity in the example):
class Animal:
def __init__(self, volume=1):
self.volume = volume
self.description = "Animal"
def Sound(self):
pass
def GetADog(self, newvolume):
class Dog(Animal):
def Sound(this):
return self.description + ": " + ("woof" * this.volume)
return Dog(newvolume)
Then we have output like:
>>> a = Animal(3)
>>> d = a.GetADog(2)
>>> d.Sound()
'Animal: woofwoof'
I wasn't sure if self within the Dog class would shadow self within the Animal class, so I opted to make Dog's reference the word "this" instead. In my opinion and for that particular application, that was more clear to me.
A:
I think that the main reason self is used by convention rather than being a Python keyword is because it's simpler to have all methods/functions take arguments the same way rather than having to put together different argument forms for functions, class methods, instance methods, etc.
Note that if you have an actual class method (i.e. one defined using the classmethod decorator), the convention is to use "cls" instead of "self".
A:
Because it is a convention, not language syntax. There is a Python style guide that people who program in Python follow. This way libraries have a familiar look and feel. Python places a lot of emphasis on readability, and consistency is an important part of this.
|
is it ever useful to define a class method with a reference to self not called 'self' in Python?
|
I'm teaching myself Python and I see the following in Dive into Python section 5.3:
By convention, the first argument of any Python class method (the reference to the current instance) is called self. This argument fills the role of the reserved word this in C++ or Java, but self is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but self; this is a very strong convention.
Considering that self is not a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it not a keyword?
|
[
"No, unless you want to confuse every other programmer that looks at your code after you write it. self is not a keyword because it is an identifier. It could have been a keyword and the fact that it isn't one was a design decision.\n",
"As a side observation, note that Pilgrim is committing a common misuse of terms here: a class method is quite a different thing from an instance method, which is what he's talking about here. As wikipedia puts it, \"a method is a subroutine that is exclusively associated either with a class (in which case it is called a class method or a static method) or with an object (in which case it is an instance method).\". Python's built-ins include a staticmethod type, to make static methods, and a classmethod type, to make class methods, each generally used as a decorator; if you don't use either, a def in a class body makes an instance method. E.g.:\n>>> class X(object):\n... def noclass(self): print self\n... @classmethod\n... def withclass(cls): print cls\n... \n>>> x = X()\n>>> x.noclass()\n<__main__.X object at 0x698d0>\n>>> x.withclass()\n<class '__main__.X'>\n>>> \n\nAs you see, the instance method noclass gets the instance as its argument, but the class method withclass gets the class instead.\nSo it would be extremely confusing and misleading to use self as the name of the first parameter of a class method: the convention in this case is instead to use cls, as in my example above. While this IS just a convention, there is no real good reason for violating it -- any more than there would be, say, for naming a variable number_of_cats if the purpose of the variable is counting dogs!-)\n",
"The only case of this I've seen is when you define a function outside of a class definition, and then assign it to the class, e.g.:\nclass Foo(object):\n def bar(self):\n # Do something with 'self'\n\ndef baz(inst):\n return inst.bar()\n\nFoo.baz = baz\n\nIn this case, self is a little strange to use, because the function could be applied to many classes. Most often I've seen inst or cls used instead.\n",
"I once had some code like (and I apologize for lack of creativity in the example):\nclass Animal:\n def __init__(self, volume=1):\n self.volume = volume\n self.description = \"Animal\"\n\n def Sound(self):\n pass\n\n def GetADog(self, newvolume):\n class Dog(Animal):\n def Sound(this):\n return self.description + \": \" + (\"woof\" * this.volume)\n return Dog(newvolume)\n\nThen we have output like:\n>>> a = Animal(3)\n>>> d = a.GetADog(2)\n>>> d.Sound()\n'Animal: woofwoof'\n\nI wasn't sure if self within the Dog class would shadow self within the Animal class, so I opted to make Dog's reference the word \"this\" instead. In my opinion and for that particular application, that was more clear to me.\n",
"I think that the main reason self is used by convention rather than being a Python keyword is because it's simpler to have all methods/functions take arguments the same way rather than having to put together different argument forms for functions, class methods, instance methods, etc.\nNote that if you have an actual class method (i.e. one defined using the classmethod decorator), the convention is to use \"cls\" instead of \"self\".\n",
"Because it is a convention, not language syntax. There is a Python style guide that people who program in Python follow. This way libraries have a familiar look and feel. Python places a lot of emphasis on readability, and consistency is an important part of this.\n"
] |
[
9,
5,
4,
2,
1,
1
] |
[] |
[] |
[
"naming_conventions",
"python"
] |
stackoverflow_0001240229_naming_conventions_python.txt
|
Q:
Python SOAP document handling
I've been trying to use suds for Python to call a SOAP WSDL. I just need to call the service programmatically and write the output XML document. However suds automatically parses this data into it's own pythonic data format. I've been looking through the examples and the documentation, but I can't seem to find a way to return the XML document that the SOAP service gives me.
Is there an easy way to do this I'm overlooking? Is there an easier way to do this in Python than suds?
A:
At this early stage in suds development, the easiest way to get to the raw XML content is not what one would expect.
The examples on the site show us with something like this:
client = Client(url)
result = client.service.Invoke(subm)
however, the result is a pre-parsed object that is great for access by Python, but not for XML document access. Fortunately the Client object still has the original SOAP message received stored.
result = client.last_received()
print result
Will give you the actual SOAP message received back.
A:
You could take a look at a library such as soaplib: its a really nice way to consume (and serve) SOAP webservices in Python. The latest version has some code to dynamically generate Python bindings either dynamically (at runtime) or statically (run a script against some WSDL).
[disclaimer: I'm the maintainer of the project! - I didn't write the bulk of it though]
|
Python SOAP document handling
|
I've been trying to use suds for Python to call a SOAP WSDL. I just need to call the service programmatically and write the output XML document. However suds automatically parses this data into it's own pythonic data format. I've been looking through the examples and the documentation, but I can't seem to find a way to return the XML document that the SOAP service gives me.
Is there an easy way to do this I'm overlooking? Is there an easier way to do this in Python than suds?
|
[
"At this early stage in suds development, the easiest way to get to the raw XML content is not what one would expect.\nThe examples on the site show us with something like this:\nclient = Client(url)\nresult = client.service.Invoke(subm)\n\nhowever, the result is a pre-parsed object that is great for access by Python, but not for XML document access. Fortunately the Client object still has the original SOAP message received stored.\nresult = client.last_received()\nprint result\n\nWill give you the actual SOAP message received back.\n",
"You could take a look at a library such as soaplib: its a really nice way to consume (and serve) SOAP webservices in Python. The latest version has some code to dynamically generate Python bindings either dynamically (at runtime) or statically (run a script against some WSDL). \n[disclaimer: I'm the maintainer of the project! - I didn't write the bulk of it though]\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"soap",
"suds",
"wsdl",
"xml"
] |
stackoverflow_0001239538_python_soap_suds_wsdl_xml.txt
|
Q:
How to scale matplotlib subplot heights individually
Using matplotlib/pylab....
How do I plot 5 heatmaps as subplots which have the same number of columns but different row counts? In other words, I need each subplot's height to be scaled differently.
Perhaps an image better illustrates the problem...
alt text http://img98.imageshack.us/img98/5853/heatmap.png
I need the data points to all be square, AND the columns to be lined up, so the heights have to change according to how many rows each subplot has.
I've tried:
The scaling options mentioned here. The above plot is with axis('tight').
The y-axis scaling solutions mentioned here.
... but no luck so far.
A:
I haven't tried this for any of my own work, but perhaps the matplotlib AxesGrid toolkit might be what you are looking for.
A:
Don't use subplot but axes to create your subplots - the latter allows arbitrary positioning of the subplot.
|
How to scale matplotlib subplot heights individually
|
Using matplotlib/pylab....
How do I plot 5 heatmaps as subplots which have the same number of columns but different row counts? In other words, I need each subplot's height to be scaled differently.
Perhaps an image better illustrates the problem...
alt text http://img98.imageshack.us/img98/5853/heatmap.png
I need the data points to all be square, AND the columns to be lined up, so the heights have to change according to how many rows each subplot has.
I've tried:
The scaling options mentioned here. The above plot is with axis('tight').
The y-axis scaling solutions mentioned here.
... but no luck so far.
|
[
"I haven't tried this for any of my own work, but perhaps the matplotlib AxesGrid toolkit might be what you are looking for.\n",
"Don't use subplot but axes to create your subplots - the latter allows arbitrary positioning of the subplot.\n"
] |
[
4,
2
] |
[] |
[] |
[
"matplotlib",
"python"
] |
stackoverflow_0001228315_matplotlib_python.txt
|
Q:
GTK: create a colored regular button
How do I do it? A lot of sites say I can just call .modify_bg() on the button, but that doesn't do anything. I'm able to add an EventBox to the button, and add a label to that, and then change its colors, but it looks horrendous - there is a ton of gray space between the edge of the button that doesn't change. I just want something that looks like this:
(source: kksou.com)
The site claims to have just done modify_bg() on the button. But that doesn't work for me. =(.
The right answer probably involves creating a style, or something with a gtkrc file, etc. Can someone point me in that direction?
A:
Here's a little example:
import gtk
win = gtk.Window()
win.connect("destroy", gtk.main_quit)
btn = gtk.Button("test")
#make a gdk.color for red
map = btn.get_colormap()
color = map.alloc_color("red")
#copy the current style and replace the background
style = btn.get_style().copy()
style.bg[gtk.STATE_NORMAL] = color
#set the button's style to the one you created
btn.set_style(style)
win.add(btn)
win.show_all()
gtk.main()
|
GTK: create a colored regular button
|
How do I do it? A lot of sites say I can just call .modify_bg() on the button, but that doesn't do anything. I'm able to add an EventBox to the button, and add a label to that, and then change its colors, but it looks horrendous - there is a ton of gray space between the edge of the button that doesn't change. I just want something that looks like this:
(source: kksou.com)
The site claims to have just done modify_bg() on the button. But that doesn't work for me. =(.
The right answer probably involves creating a style, or something with a gtkrc file, etc. Can someone point me in that direction?
|
[
"Here's a little example:\nimport gtk\n\nwin = gtk.Window()\nwin.connect(\"destroy\", gtk.main_quit)\n\nbtn = gtk.Button(\"test\")\n\n#make a gdk.color for red\nmap = btn.get_colormap() \ncolor = map.alloc_color(\"red\")\n\n#copy the current style and replace the background\nstyle = btn.get_style().copy()\nstyle.bg[gtk.STATE_NORMAL] = color\n\n#set the button's style to the one you created\nbtn.set_style(style)\n\nwin.add(btn)\nwin.show_all()\n\ngtk.main()\n\n"
] |
[
16
] |
[] |
[] |
[
"button",
"colors",
"gtk",
"pygtk",
"python"
] |
stackoverflow_0001241020_button_colors_gtk_pygtk_python.txt
|
Q:
How to filter a dictionary by value?
Newbie question here, so please bear with me.
Let's say I have a dictionary looking like this:
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.txt")}
I want all values that are equal to each other to be moved into another dictionary.
matched = {"2323232838": ("first/dir", "hello.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt")}
And the remaining unmatched items should be looking like this:
remainder = {"2323221383": ("second/dir", "foo.txt"),
"324234324": ("third/dir", "dog.txt")}
Thanks in advance, and if you provide an example, please comment it as much as possible.
A:
The code below will result in two variables, matches and remainders. matches is an array of dictionaries, in which matching items from the original dictionary will have a corresponding element. remainder will contain, as in your example, a dictionary containing all the unmatched items.
Note that in your example, there is only one set of matching values: ('first/dir', 'hello.txt'). If there were more than one set, each would have a corresponding entry in matches.
import itertools
# Original dict
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.txt")}
# Convert dict to sorted list of items
a = sorted(a.items(), key=lambda x:x[1])
# Group by value of tuple
groups = itertools.groupby(a, key=lambda x:x[1])
# Pull out matching groups of items, and combine items
# with no matches back into a single dictionary
remainder = []
matched = []
for key, group in groups:
group = list(group)
if len(group) == 1:
remainder.append( group[0] )
else:
matched.append( dict(group) )
else:
remainder = dict(remainder)
Output:
>>> matched
[
{
'3434221': ('first/dir', 'hello.txt'),
'2323232838': ('first/dir', 'hello.txt'),
'32232334': ('first/dir', 'hello.txt')
}
]
>>> remainder
{
'2323221383': ('second/dir', 'foo.txt'),
'324234324': ('third/dir', 'dog.txt')
}
As a newbie, you're probably being introduced to a few unfamiliar concepts in the code above. Here are some links:
A:
What you're asking for is called an "Inverted Index" -- the distinct items are recorded just once with a list of keys.
>>> from collections import defaultdict
>>> a = {"2323232838": ("first/dir", "hello.txt"),
... "2323221383": ("second/dir", "foo.txt"),
... "3434221": ("first/dir", "hello.txt"),
... "32232334": ("first/dir", "hello.txt"),
... "324234324": ("third/dir", "dog.txt")}
>>> invert = defaultdict( list )
>>> for key, value in a.items():
... invert[value].append( key )
...
>>> invert
defaultdict(<type 'list'>, {('first/dir', 'hello.txt'): ['3434221', '2323232838', '32232334'], ('second/dir', 'foo.txt'): ['2323221383'], ('third/dir', 'dog.txt'): ['324234324']})
The inverted dictionary has the original values associated with a list of 1 or more keys.
Now, to get your revised dictionaries from this.
Filtering:
>>> [ invert[multi] for multi in invert if len(invert[multi]) > 1 ]
[['3434221', '2323232838', '32232334']]
>>> [ invert[uni] for uni in invert if len(invert[uni]) == 1 ]
[['2323221383'], ['324234324']]
Expanding
>>> [ (i,multi) for multi in invert if len(invert[multi]) > 1 for i in invert[multi] ]
[('3434221', ('first/dir', 'hello.txt')), ('2323232838', ('first/dir', 'hello.txt')), ('32232334', ('first/dir', 'hello.txt'))]
>>> dict( (i,multi) for multi in invert if len(invert[multi]) > 1 for i in invert[multi] )
{'3434221': ('first/dir', 'hello.txt'), '2323232838': ('first/dir', 'hello.txt'), '32232334': ('first/dir', 'hello.txt')}
A similar (but simpler) treatment works for the items which occur once.
A:
Iterating over a dictionary is no different from iterating over a list in python:
for key in dic:
print("dic[%s] = %s" % (key, dic[key]))
This will print all of the keys and values of your dictionary.
A:
I assume that your unique id will be the key.
Probably not very beautiful, but returns a dict with your unique values:
>>> dict_ = {'1': ['first/dir', 'hello.txt'],
'3': ['first/dir', 'foo.txt'],
'2': ['second/dir', 'foo.txt'],
'4': ['second/dir', 'foo.txt']}
>>> dict((v[0]+v[1],k) for k,v in dict_.iteritems())
{'second/dir/foo.txt': '4', 'first/dir/hello.txt': '1', 'first/dir/foo.txt': '3'}
I've seen you updated your post:
>>> a
{'324234324': ('third/dir', 'dog.txt'),
'2323221383': ('second/dir', 'foo.txt'),
'3434221': ('first/dir', 'hello.txt'),
'2323232838': ('first/dir', 'hello.txt'),
'32232334': ('first/dir', 'hello.txt')}
>>> dict((v[0]+"/"+v[1],k) for k,v in a.iteritems())
{'second/dir/foo.txt': '2323221383',
'first/dir/hello.txt': '32232334',
'third/dir/dog.txt': '324234324'}
A:
if you know what value you want to filter out:
known_tuple = 'first/dir','hello.txt'
b = {k:v for k, v in a.items() if v == known_tuple}
then a would become:
a = dict(a.items() - b.items())
this is py3k notation, but I'm sure something similar can be implemented in legacy versions.
If you don't know what the known_tuple is, then you'd need to first find it out. for example like this:
c = list(a.values())
for i in set(c):
c.remove(i)
known_tuple = c[0]
|
How to filter a dictionary by value?
|
Newbie question here, so please bear with me.
Let's say I have a dictionary looking like this:
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.txt")}
I want all values that are equal to each other to be moved into another dictionary.
matched = {"2323232838": ("first/dir", "hello.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt")}
And the remaining unmatched items should be looking like this:
remainder = {"2323221383": ("second/dir", "foo.txt"),
"324234324": ("third/dir", "dog.txt")}
Thanks in advance, and if you provide an example, please comment it as much as possible.
|
[
"The code below will result in two variables, matches and remainders. matches is an array of dictionaries, in which matching items from the original dictionary will have a corresponding element. remainder will contain, as in your example, a dictionary containing all the unmatched items.\nNote that in your example, there is only one set of matching values: ('first/dir', 'hello.txt'). If there were more than one set, each would have a corresponding entry in matches.\nimport itertools\n\n# Original dict\na = {\"2323232838\": (\"first/dir\", \"hello.txt\"),\n \"2323221383\": (\"second/dir\", \"foo.txt\"),\n \"3434221\": (\"first/dir\", \"hello.txt\"),\n \"32232334\": (\"first/dir\", \"hello.txt\"),\n \"324234324\": (\"third/dir\", \"dog.txt\")}\n\n# Convert dict to sorted list of items\na = sorted(a.items(), key=lambda x:x[1])\n\n# Group by value of tuple\ngroups = itertools.groupby(a, key=lambda x:x[1])\n\n# Pull out matching groups of items, and combine items \n# with no matches back into a single dictionary\nremainder = []\nmatched = []\n\nfor key, group in groups:\n group = list(group)\n if len(group) == 1:\n remainder.append( group[0] )\n else:\n matched.append( dict(group) )\nelse:\n remainder = dict(remainder)\n\nOutput: \n>>> matched\n[\n {\n '3434221': ('first/dir', 'hello.txt'), \n '2323232838': ('first/dir', 'hello.txt'), \n '32232334': ('first/dir', 'hello.txt')\n }\n]\n\n>>> remainder\n{\n '2323221383': ('second/dir', 'foo.txt'), \n '324234324': ('third/dir', 'dog.txt')\n}\n\nAs a newbie, you're probably being introduced to a few unfamiliar concepts in the code above. Here are some links:\n",
"What you're asking for is called an \"Inverted Index\" -- the distinct items are recorded just once with a list of keys.\n>>> from collections import defaultdict\n>>> a = {\"2323232838\": (\"first/dir\", \"hello.txt\"),\n... \"2323221383\": (\"second/dir\", \"foo.txt\"),\n... \"3434221\": (\"first/dir\", \"hello.txt\"),\n... \"32232334\": (\"first/dir\", \"hello.txt\"),\n... \"324234324\": (\"third/dir\", \"dog.txt\")}\n>>> invert = defaultdict( list )\n>>> for key, value in a.items():\n... invert[value].append( key )\n... \n>>> invert\ndefaultdict(<type 'list'>, {('first/dir', 'hello.txt'): ['3434221', '2323232838', '32232334'], ('second/dir', 'foo.txt'): ['2323221383'], ('third/dir', 'dog.txt'): ['324234324']})\n\nThe inverted dictionary has the original values associated with a list of 1 or more keys.\nNow, to get your revised dictionaries from this. \nFiltering:\n>>> [ invert[multi] for multi in invert if len(invert[multi]) > 1 ]\n[['3434221', '2323232838', '32232334']]\n>>> [ invert[uni] for uni in invert if len(invert[uni]) == 1 ]\n[['2323221383'], ['324234324']]\n\nExpanding\n>>> [ (i,multi) for multi in invert if len(invert[multi]) > 1 for i in invert[multi] ]\n[('3434221', ('first/dir', 'hello.txt')), ('2323232838', ('first/dir', 'hello.txt')), ('32232334', ('first/dir', 'hello.txt'))]\n>>> dict( (i,multi) for multi in invert if len(invert[multi]) > 1 for i in invert[multi] )\n{'3434221': ('first/dir', 'hello.txt'), '2323232838': ('first/dir', 'hello.txt'), '32232334': ('first/dir', 'hello.txt')}\n\nA similar (but simpler) treatment works for the items which occur once.\n",
"Iterating over a dictionary is no different from iterating over a list in python:\nfor key in dic:\n print(\"dic[%s] = %s\" % (key, dic[key]))\n\nThis will print all of the keys and values of your dictionary.\n",
"I assume that your unique id will be the key.\nProbably not very beautiful, but returns a dict with your unique values: \n>>> dict_ = {'1': ['first/dir', 'hello.txt'],\n'3': ['first/dir', 'foo.txt'], \n'2': ['second/dir', 'foo.txt'], \n'4': ['second/dir', 'foo.txt']} \n>>> dict((v[0]+v[1],k) for k,v in dict_.iteritems()) \n{'second/dir/foo.txt': '4', 'first/dir/hello.txt': '1', 'first/dir/foo.txt': '3'} \n\nI've seen you updated your post: \n>>> a\n{'324234324': ('third/dir', 'dog.txt'), \n'2323221383': ('second/dir', 'foo.txt'), \n'3434221': ('first/dir', 'hello.txt'), \n'2323232838': ('first/dir', 'hello.txt'), \n'32232334': ('first/dir', 'hello.txt')}\n>>> dict((v[0]+\"/\"+v[1],k) for k,v in a.iteritems())\n{'second/dir/foo.txt': '2323221383', \n'first/dir/hello.txt': '32232334', \n'third/dir/dog.txt': '324234324'}\n\n",
"if you know what value you want to filter out:\nknown_tuple = 'first/dir','hello.txt'\nb = {k:v for k, v in a.items() if v == known_tuple}\n\nthen a would become:\na = dict(a.items() - b.items())\n\nthis is py3k notation, but I'm sure something similar can be implemented in legacy versions.\nIf you don't know what the known_tuple is, then you'd need to first find it out. for example like this:\nc = list(a.values())\nfor i in set(c):\n c.remove(i)\nknown_tuple = c[0]\n\n"
] |
[
10,
4,
1,
1,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0001241029_dictionary_python.txt
|
Q:
What is the recommended Python module for fast Fourier transforms (FFT)?
Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python?
A:
I would recommend numpy library, I not sure if it's the fastest implementation that exist but but surely it's one of best scientific module on the "market".
A:
FFTW would probably be the fastest implementation, if you can find a python binding that actually works.
The easiest thing to use is certainly scipy.fft, though. Plus, you get all the power of numpy/scipy to go along with it.
I've only used it for a toy project (a basic music visualization) but it was fast enough to process bog standard audio at 44khz at 60fps, as far as I can remember.
A:
I would recommend using the FFTW library ("the fastest Fourier transform in the West"). The FFTW download page states that Python wrappers exist, but the link is broken. A Google search turned up Python FFTW, which provides Python bindings to FFTW3.
|
What is the recommended Python module for fast Fourier transforms (FFT)?
|
Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python?
|
[
"I would recommend numpy library, I not sure if it's the fastest implementation that exist but but surely it's one of best scientific module on the \"market\". \n",
"FFTW would probably be the fastest implementation, if you can find a python binding that actually works.\nThe easiest thing to use is certainly scipy.fft, though. Plus, you get all the power of numpy/scipy to go along with it.\nI've only used it for a toy project (a basic music visualization) but it was fast enough to process bog standard audio at 44khz at 60fps, as far as I can remember.\n",
"I would recommend using the FFTW library (\"the fastest Fourier transform in the West\"). The FFTW download page states that Python wrappers exist, but the link is broken. A Google search turned up Python FFTW, which provides Python bindings to FFTW3.\n"
] |
[
8,
5,
3
] |
[] |
[] |
[
"benchmarking",
"fft",
"python"
] |
stackoverflow_0001241797_benchmarking_fft_python.txt
|
Q:
Python script knows how much memory it's using
How can a python script know the amount of system memory it's currently using? (assuming a unix-based OS)
A:
If you want to know the total memory that the interpreter uses, on Linux, read /proc/self/statm.
If you want to find out how much memory your objects use, use Pympler.
A:
Similar question:
Python memory profiler
Looks like there are memory profilers for python.
PySizer seems popular.
Heapy is another.
Google: "python memory profiler" for more.
A:
I've used once snippet I found on ActiveState and it seemed to work well.
Actually it's using same method Martin v. Löwis suggested.
A:
I don't think there's a simple way to do this. As a practical matter, on a Unix OS I'd probably do something with os.getpid() and calling ps or reading entries in /proc.
Python 2.6 adds sys.getsizeof(), which you could use in concert with gc.get_objects() to walk the size of the working set of objects:
>>> print sum([sys.getsizeof(o) for o in gc.get_objects()])
561616
I don't think that'd be a good idea in practice.
A:
I haven't used it, but you might take a look at heapy (http://guppy-pe.sourceforge.net/#Heapy), which looks to be a memory profiler for python programs.
|
Python script knows how much memory it's using
|
How can a python script know the amount of system memory it's currently using? (assuming a unix-based OS)
|
[
"If you want to know the total memory that the interpreter uses, on Linux, read /proc/self/statm.\nIf you want to find out how much memory your objects use, use Pympler.\n",
"Similar question:\nPython memory profiler\nLooks like there are memory profilers for python. \nPySizer seems popular. \nHeapy is another. \nGoogle: \"python memory profiler\" for more.\n",
"I've used once snippet I found on ActiveState and it seemed to work well.\nActually it's using same method Martin v. Löwis suggested.\n",
"I don't think there's a simple way to do this. As a practical matter, on a Unix OS I'd probably do something with os.getpid() and calling ps or reading entries in /proc.\nPython 2.6 adds sys.getsizeof(), which you could use in concert with gc.get_objects() to walk the size of the working set of objects:\n>>> print sum([sys.getsizeof(o) for o in gc.get_objects()])\n561616\n\nI don't think that'd be a good idea in practice.\n",
"I haven't used it, but you might take a look at heapy (http://guppy-pe.sourceforge.net/#Heapy), which looks to be a memory profiler for python programs.\n"
] |
[
11,
4,
2,
1,
0
] |
[] |
[] |
[
"memory_management",
"python"
] |
stackoverflow_0001240581_memory_management_python.txt
|
Q:
Specifying relative path in py2exe
When specifying my script file in setup.py, e.g. "script": 'pythonturtle.py', how can I specify its relative position in the file system? In my case, I need to go down two folders and then go into the "src" folder and it's in there. How do I write this in a cross-platform way?
A:
How can you speak of py2exe and cross-platform? py2exe is windows only.
As far as I know, you have to keep your setup file in the same place as your script. Or if you don't have to it is certainly a strong convention.
What you can do is define a dist_dir option so that your program gets built in the right place.
setup(
options = {"py2exe": {"dist_dir": os.path.join("..", "foo", "bar")}},
windows = ["pythonturtle.py"],
)
|
Specifying relative path in py2exe
|
When specifying my script file in setup.py, e.g. "script": 'pythonturtle.py', how can I specify its relative position in the file system? In my case, I need to go down two folders and then go into the "src" folder and it's in there. How do I write this in a cross-platform way?
|
[
"How can you speak of py2exe and cross-platform? py2exe is windows only.\nAs far as I know, you have to keep your setup file in the same place as your script. Or if you don't have to it is certainly a strong convention.\nWhat you can do is define a dist_dir option so that your program gets built in the right place.\nsetup(\n options = {\"py2exe\": {\"dist_dir\": os.path.join(\"..\", \"foo\", \"bar\")}},\n windows = [\"pythonturtle.py\"],\n)\n\n"
] |
[
3
] |
[] |
[] |
[
"path",
"py2exe",
"python"
] |
stackoverflow_0001241708_path_py2exe_python.txt
|
Q:
Optimal way to replace characters in large string with Python?
I'm dealing with cleaning relatively large (30ish lines) blocks of text. Here's an excerpt:
PID|1||06225401^^^PA0^MR||PATIENT^FAKE
R|||F
PV1|1|I|||||025631^DoctorZ^^^^^^^PA0^^^^DRH|DRH||||...
ORC|RE||CYT-09-06645^AP||||||200912110333|INTERFACE07
OBR|1||CYT09-06645|8104^^L|||20090602|||||||200906030000[conditio...
OBX|1|TX|8104|1|SOURCE OF
SPECIMEN:[source]||||||F|||200912110333|CYT
...
I currently have a script that takes out illegal characters or terms. Here's an example.
infile = open(thisFile,'r')
m = infile.read()
#remove junk headers
m = m.replace("4þPATHþ", "")
m = m.replace("10þALLþ", "")
My goal is to modify this script so that I can add 4 digits to the end of one of the fields. In specific, the date field ("20090602") in the OBR line. The finished script will be able to work with any file that follows this same format. Is this possible with the way I currently handle the file input or do I have to use some different logic?
A:
You may find the answers here helpful.
Iterative find/replace from a list of tuples in Python
A:
Here's an outline (untested) ... basically you do it a line at a time
for line in infile:
data = line.rstrip("\n").split("|")
kind = data[0]
# start of changes
if kind == "OBR":
data[7] += "0000" # check that 7 is correct!
# end of changes
outrecord = "|".join(data)
outfile.write(outrecord + "\n")
The above assumes that you are selecting fix-up targets by line-type (example: "OBR") and column index (example: 7). If there are only a few such targets, just add more similar fix statements. If there are many targets, you could specify them like this:
fix_targets = {
"OBR": [7],
"XYZ": [1, 42],
}
and the fix_up code would look like this:
if kind in fix_targets:
for col_index in fix_targets[kind]:
data[col_index] += "0000"
You may like in any case to add code to check that data[col_index] really is a date in YYYYMMDD format before changing it.
None of the above addresses removing the unwanted headers, because you didn't show example data. I guess that applying your replacements to each line (and avoiding writing the line if it became only whitespace after replacements) would do the trick.
|
Optimal way to replace characters in large string with Python?
|
I'm dealing with cleaning relatively large (30ish lines) blocks of text. Here's an excerpt:
PID|1||06225401^^^PA0^MR||PATIENT^FAKE
R|||F
PV1|1|I|||||025631^DoctorZ^^^^^^^PA0^^^^DRH|DRH||||...
ORC|RE||CYT-09-06645^AP||||||200912110333|INTERFACE07
OBR|1||CYT09-06645|8104^^L|||20090602|||||||200906030000[conditio...
OBX|1|TX|8104|1|SOURCE OF
SPECIMEN:[source]||||||F|||200912110333|CYT
...
I currently have a script that takes out illegal characters or terms. Here's an example.
infile = open(thisFile,'r')
m = infile.read()
#remove junk headers
m = m.replace("4þPATHþ", "")
m = m.replace("10þALLþ", "")
My goal is to modify this script so that I can add 4 digits to the end of one of the fields. In specific, the date field ("20090602") in the OBR line. The finished script will be able to work with any file that follows this same format. Is this possible with the way I currently handle the file input or do I have to use some different logic?
|
[
"You may find the answers here helpful.\nIterative find/replace from a list of tuples in Python\n",
"Here's an outline (untested) ... basically you do it a line at a time\nfor line in infile:\n data = line.rstrip(\"\\n\").split(\"|\")\n kind = data[0]\n # start of changes\n if kind == \"OBR\":\n data[7] += \"0000\" # check that 7 is correct!\n # end of changes\n outrecord = \"|\".join(data)\n outfile.write(outrecord + \"\\n\")\n\nThe above assumes that you are selecting fix-up targets by line-type (example: \"OBR\") and column index (example: 7). If there are only a few such targets, just add more similar fix statements. If there are many targets, you could specify them like this:\nfix_targets = {\n \"OBR\": [7],\n \"XYZ\": [1, 42],\n }\n\nand the fix_up code would look like this:\nif kind in fix_targets:\n for col_index in fix_targets[kind]:\n data[col_index] += \"0000\"\n\nYou may like in any case to add code to check that data[col_index] really is a date in YYYYMMDD format before changing it.\nNone of the above addresses removing the unwanted headers, because you didn't show example data. I guess that applying your replacements to each line (and avoiding writing the line if it became only whitespace after replacements) would do the trick.\n"
] |
[
2,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001242209_python.txt
|
Q:
How to co host django app with php5 on apache2 with mod_python?
I have django+python+apache2+mod_python installed hosted and working on ubuntu server/ linode VPS. php5 is installed and configured. We don't have a domain name as in example.com. Just IP address. So my apache .conf file looks like this
ServerAdmin webmaster@localhost
DocumentRoot /var/www
<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonPath "['/var/www/djangoprojects',] + sys.path"
PythonDebug On
</Location>
I want to install vtiger so if I change my .conf file like say this
<VirtualHost *:80>
DocumentRoot /var/www/vtigercrm/
ErrorLog /var/log/apache2/vtiger.error_log
CustomLog /var/log/apache2/vtiger.access_log combined
<Directory /var/www/vtigercrm>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
This way vtiger the php based app works fine and ofcourse django app is not accessible. How do I make both co-exist in one file. i cannot use virtual host/subdomains. I can do with a diff port no thou.
Any clue guys ?
Regards
Ankur Gupta
A:
I need to test it, but this should get your Django project running at /mysite/:
<VirtualHost *:80>
DocumentRoot /var/www/vtigercrm/
ErrorLog /var/log/apache2/vtiger.error_log
CustomLog /var/log/apache2/vtiger.access_log combined
<Directory /var/www/vtigercrm>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
<Location "/mysite/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonPath "['/var/www/djangoprojects',] + sys.path"
PythonDebug On
</Location>
</VirtualHost>
Also, the preferred way to host Django apps is with mod_wsgi.
|
How to co host django app with php5 on apache2 with mod_python?
|
I have django+python+apache2+mod_python installed hosted and working on ubuntu server/ linode VPS. php5 is installed and configured. We don't have a domain name as in example.com. Just IP address. So my apache .conf file looks like this
ServerAdmin webmaster@localhost
DocumentRoot /var/www
<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonPath "['/var/www/djangoprojects',] + sys.path"
PythonDebug On
</Location>
I want to install vtiger so if I change my .conf file like say this
<VirtualHost *:80>
DocumentRoot /var/www/vtigercrm/
ErrorLog /var/log/apache2/vtiger.error_log
CustomLog /var/log/apache2/vtiger.access_log combined
<Directory /var/www/vtigercrm>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
This way vtiger the php based app works fine and ofcourse django app is not accessible. How do I make both co-exist in one file. i cannot use virtual host/subdomains. I can do with a diff port no thou.
Any clue guys ?
Regards
Ankur Gupta
|
[
"I need to test it, but this should get your Django project running at /mysite/:\n<VirtualHost *:80>\n DocumentRoot /var/www/vtigercrm/\n ErrorLog /var/log/apache2/vtiger.error_log\n CustomLog /var/log/apache2/vtiger.access_log combined\n <Directory /var/www/vtigercrm>\n Options Indexes FollowSymLinks MultiViews\n AllowOverride None\n Order allow,deny\n allow from all\n </Directory>\n <Location \"/mysite/\">\n SetHandler python-program\n PythonHandler django.core.handlers.modpython\n SetEnv DJANGO_SETTINGS_MODULE mysite.settings\n PythonOption django.root /mysite\n PythonPath \"['/var/www/djangoprojects',] + sys.path\"\n PythonDebug On\n </Location>\n</VirtualHost>\n\nAlso, the preferred way to host Django apps is with mod_wsgi.\n"
] |
[
1
] |
[] |
[] |
[
"apache",
"django",
"mod_python",
"php",
"python"
] |
stackoverflow_0001239246_apache_django_mod_python_php_python.txt
|
Q:
Do I only need to check the users machine for the version of the MSVCR90.dll that was installed with my python installation?
I was working on an update to my application and before I began I migrated to 2.62 because it seemed to be the time to. I walked right into the issue of having problems building my application using py2exe because of the MSVCR90.dlls. There seems to be a fair amount of information on how to solve this issue, including some good answers here on SO.
I am deploying to users that more likely than not have 32 bit XP or Vista machines. Some of my users will be migrated to 64 bit Vista in the near future. My understanding of these issues is that I have to make sure they have the correct dlls that relate to the version of python that exists on the application development computer. Since I have an x86 processor then they need the x86 version of the dlls. The configuration of their computer is irrelevant.
Is this correct or do I have to account for their architecture if I am going to deliver the dlls as private assemblies?
Thanks for any responses
A:
Vista 64bit has a 32 bit emulator I believe, so you will not need to worry about this.
However, I would just tell them to install the msvcrt runtime which is supposed to be the correct way to deal with this sxs mess.
A:
From what I have gathered and learned the correct answer is that I have to worry about the MSCVCR90 dll that is used in the version of Python and mx that the application I am building rely on. This is important because it means that if the user has a different configuration I can't easily fix that problem unless I do some tricks to install the correct dll. If I have them download the MS installer from MS and their hardware (CPU type) does not match mine then they will potentially run into problems. There is a really good set of instructions on the wxpython users group site. WX Discussion.
|
Do I only need to check the users machine for the version of the MSVCR90.dll that was installed with my python installation?
|
I was working on an update to my application and before I began I migrated to 2.62 because it seemed to be the time to. I walked right into the issue of having problems building my application using py2exe because of the MSVCR90.dlls. There seems to be a fair amount of information on how to solve this issue, including some good answers here on SO.
I am deploying to users that more likely than not have 32 bit XP or Vista machines. Some of my users will be migrated to 64 bit Vista in the near future. My understanding of these issues is that I have to make sure they have the correct dlls that relate to the version of python that exists on the application development computer. Since I have an x86 processor then they need the x86 version of the dlls. The configuration of their computer is irrelevant.
Is this correct or do I have to account for their architecture if I am going to deliver the dlls as private assemblies?
Thanks for any responses
|
[
"Vista 64bit has a 32 bit emulator I believe, so you will not need to worry about this.\nHowever, I would just tell them to install the msvcrt runtime which is supposed to be the correct way to deal with this sxs mess.\n",
"From what I have gathered and learned the correct answer is that I have to worry about the MSCVCR90 dll that is used in the version of Python and mx that the application I am building rely on. This is important because it means that if the user has a different configuration I can't easily fix that problem unless I do some tricks to install the correct dll. If I have them download the MS installer from MS and their hardware (CPU type) does not match mine then they will potentially run into problems. There is a really good set of instructions on the wxpython users group site. WX Discussion.\n"
] |
[
1,
0
] |
[] |
[] |
[
"msvcr90.dll",
"py2exe",
"python"
] |
stackoverflow_0001230479_msvcr90.dll_py2exe_python.txt
|
Q:
How can I highlight a row in a gtk.Table?
I want to highlight specific rows in a gtk.Table. I also want a mouseover to highlight it w/ a different color (like on a link in a web browser). I thought of just packing each cell with an eventBox and changing the STATE_NORMAL and STATE_PRELIGHT bg colors, which does work, but mousing over the eventbox doesn't work. Is there a better way?
A:
This seems to work:
def attach(w,c1,c2,r1,r2):
eb = gtk.EventBox()
a = gtk.Alignment(xalign=0.0,yalign=0.5)
a.add(w)
eb.add(a)
eb.set_style(self.rowStyle)
def ene(eb,ev):
eb.set_state(gtk.STATE_PRELIGHT)
def lne(eb,ev):
eb.set_state(gtk.STATE_NORMAL)
eb.connect('enter-notify-event', ene)
eb.connect('leave-notify-event', lne)
self.table.attach(eb, c1, c2, r1, r2,
xoptions=gtk.EXPAND|gtk.FILL,
yoptions=gtk.SHRINK)
It only highlights each cell at a time, so I'll have to change the notify events to light up everything.
EDIT: self.rowStyle is set as follows:
tmpeb = gtk.EventBox()
st = tmpeb.get_style().copy()
st.bg[gtk.STATE_PRELIGHT] = gtk.gdk.Color(65535,65535,0)
self.rowStyle = st
I create an EventBox just to get its style.
|
How can I highlight a row in a gtk.Table?
|
I want to highlight specific rows in a gtk.Table. I also want a mouseover to highlight it w/ a different color (like on a link in a web browser). I thought of just packing each cell with an eventBox and changing the STATE_NORMAL and STATE_PRELIGHT bg colors, which does work, but mousing over the eventbox doesn't work. Is there a better way?
|
[
"This seems to work:\n def attach(w,c1,c2,r1,r2):\n eb = gtk.EventBox()\n a = gtk.Alignment(xalign=0.0,yalign=0.5)\n a.add(w)\n eb.add(a)\n eb.set_style(self.rowStyle)\n def ene(eb,ev):\n eb.set_state(gtk.STATE_PRELIGHT)\n def lne(eb,ev):\n eb.set_state(gtk.STATE_NORMAL)\n eb.connect('enter-notify-event', ene)\n eb.connect('leave-notify-event', lne)\n\n self.table.attach(eb, c1, c2, r1, r2,\n xoptions=gtk.EXPAND|gtk.FILL,\n yoptions=gtk.SHRINK)\n\nIt only highlights each cell at a time, so I'll have to change the notify events to light up everything. \nEDIT: self.rowStyle is set as follows:\ntmpeb = gtk.EventBox()\nst = tmpeb.get_style().copy()\nst.bg[gtk.STATE_PRELIGHT] = gtk.gdk.Color(65535,65535,0)\nself.rowStyle = st\n\nI create an EventBox just to get its style.\n"
] |
[
2
] |
[] |
[] |
[
"colors",
"gtk",
"pygtk",
"python"
] |
stackoverflow_0001242531_colors_gtk_pygtk_python.txt
|
Q:
What's the point of alloc_color() in gtk?
Various examples always use alloc_color() and stuff like gtk.color.parse('red'), etc. I just do gtk.gdk.Color(65535,0,0), and that seems to work. What's the need for alloc_color?
A:
If you're running on a system that uses a palette display (as opposed to a true-colour display), then you must allocate new colours in the palette before you can use them. This is because palette-based displays can only display a limited number of colours at once (usually 256 or sometimes 65536).
Most displays these days are capable of true colour display, which can display all available colours simultaneously, so this won't appear to be a problem and you can get away with directly asking for specific colours.
|
What's the point of alloc_color() in gtk?
|
Various examples always use alloc_color() and stuff like gtk.color.parse('red'), etc. I just do gtk.gdk.Color(65535,0,0), and that seems to work. What's the need for alloc_color?
|
[
"If you're running on a system that uses a palette display (as opposed to a true-colour display), then you must allocate new colours in the palette before you can use them. This is because palette-based displays can only display a limited number of colours at once (usually 256 or sometimes 65536).\nMost displays these days are capable of true colour display, which can display all available colours simultaneously, so this won't appear to be a problem and you can get away with directly asking for specific colours.\n"
] |
[
2
] |
[] |
[] |
[
"colors",
"gtk",
"pygtk",
"python"
] |
stackoverflow_0001242541_colors_gtk_pygtk_python.txt
|
Q:
pygtk: free variable referenced before assignment in enclosing scope
Very bizarre scoping error which I can't even see. Inside of an updater function, I have a nested helper function to... help w/ something:
def attach_row(ws,r1,r2):
es = []
for i,w in enumerate(ws):
eb = gtk.EventBox()
a = gtk.Alignment(xalign=0.0,yalign=0.5)
a.add(w)
eb.add(a)
eb.set_style(self.rowStyle.copy())
es.append(eb)
self.table.attach(eb, i, i+1, r1, r2,
xoptions=gtk.EXPAND|gtk.FILL,
yoptions=gtk.SHRINK)
def ene(_,ev):
for eb in es:
eb.set_state(gtk.STATE_PRELIGHT)
def lne(_,ev):
for eb in es:
eb.set_state(gtk.STATE_NORMAL)
for eb in es:
eb.connect('enter-notify-event', ene)
eb.connect('leave-notify-event', lne)
This works once in a while, but if the update() function runs too much, I eventually get:
for eb in es:
NameError: free variable 'es' referenced before assignment in enclosing scope
What is causing this? es is most certainly assigned before those functions ever get called. Isn't that right? Is some bizarre thing happening where for some reason the ene() for a previously created row gets called while the new one is being created, and the closed over es gets overwritten?
A:
Pretty mysterious indeed -- looks like the closure's disappearing out from under the inner functions. Wonder if that's related to how pygtk holds such callback functions (I'm not familiar with its internals). To try to probe for that -- what happens if you also append ene and lne to a global list at the end of attach_row, just to make sure they're held "normally" somewhere so their closure survives -- does the problem persist in that case?
If it does, then I have to admit the problem's just TOO mysterious and concur with the previous answer suggesting, as a workaround, the use of callables that hold their state in a clearer way (I'd suggest two bound methods of one class instance, since they share their state, but two instance of a single class with __call__ and receiving the state to set and the list of event boxes in its __init__ is surely also reasonable -- having two separate classes IMHO would be a slight exaggeration;-).
A:
Don't have enough points to leave this as a comment (just registered) ...
No 'es' variable globally or in a higher scope?
attach_row isn't also a nested function?
NameError exception points to for loop line in ene or lne functions?
One possible, but icky, workaround might be to make ene and lne classes that are instantiated and callable as functions via a __call__() method.
|
pygtk: free variable referenced before assignment in enclosing scope
|
Very bizarre scoping error which I can't even see. Inside of an updater function, I have a nested helper function to... help w/ something:
def attach_row(ws,r1,r2):
es = []
for i,w in enumerate(ws):
eb = gtk.EventBox()
a = gtk.Alignment(xalign=0.0,yalign=0.5)
a.add(w)
eb.add(a)
eb.set_style(self.rowStyle.copy())
es.append(eb)
self.table.attach(eb, i, i+1, r1, r2,
xoptions=gtk.EXPAND|gtk.FILL,
yoptions=gtk.SHRINK)
def ene(_,ev):
for eb in es:
eb.set_state(gtk.STATE_PRELIGHT)
def lne(_,ev):
for eb in es:
eb.set_state(gtk.STATE_NORMAL)
for eb in es:
eb.connect('enter-notify-event', ene)
eb.connect('leave-notify-event', lne)
This works once in a while, but if the update() function runs too much, I eventually get:
for eb in es:
NameError: free variable 'es' referenced before assignment in enclosing scope
What is causing this? es is most certainly assigned before those functions ever get called. Isn't that right? Is some bizarre thing happening where for some reason the ene() for a previously created row gets called while the new one is being created, and the closed over es gets overwritten?
|
[
"Pretty mysterious indeed -- looks like the closure's disappearing out from under the inner functions. Wonder if that's related to how pygtk holds such callback functions (I'm not familiar with its internals). To try to probe for that -- what happens if you also append ene and lne to a global list at the end of attach_row, just to make sure they're held \"normally\" somewhere so their closure survives -- does the problem persist in that case?\nIf it does, then I have to admit the problem's just TOO mysterious and concur with the previous answer suggesting, as a workaround, the use of callables that hold their state in a clearer way (I'd suggest two bound methods of one class instance, since they share their state, but two instance of a single class with __call__ and receiving the state to set and the list of event boxes in its __init__ is surely also reasonable -- having two separate classes IMHO would be a slight exaggeration;-).\n",
"Don't have enough points to leave this as a comment (just registered) ...\n\nNo 'es' variable globally or in a higher scope?\nattach_row isn't also a nested function?\nNameError exception points to for loop line in ene or lne functions?\n\nOne possible, but icky, workaround might be to make ene and lne classes that are instantiated and callable as functions via a __call__() method.\n"
] |
[
4,
0
] |
[] |
[] |
[
"closures",
"gtk",
"programming_languages",
"python",
"semantics"
] |
stackoverflow_0001242593_closures_gtk_programming_languages_python_semantics.txt
|
Q:
why does this python program print True
x=True
def stupid():
x=False
stupid()
print x
A:
You don't need to declare a function-local variable in Python. The "x=False" is referring to an x local to stupid(). If you really want to modify the global x inside stupid:
def stupid():
global x
x=False
A:
To answer your next question, use global:
x=True
def stupid():
global x
x=False
stupid()
print x
A:
Because x's scope is local to the function stupid(). once you call the function, and it ends, you're out of it's scope, and you print the value of "x" that's defined outside of the function stupid() -- and, the x that's defined inside of function stupid() doesn't exist on the stack anymore (once that function ends)
edit after your comment:
the outer x is referenced when you printed it, just like you did.
the inner x can only be referenced whilst your inside the function stupid(). so you can print inside of that function so that you see what value the x inside of it holds.
About "global"
it works & answers the question, apparently
not a good idea to use all that often
causes readability and scalability issues (and potentially more)
depending on your project, you may want to reconsider using a global variable defined inside of a local function.
A:
If that code is all inside a function though, global is not going to work, because then x would not be a global variable. In Python 3.x, they introduced the nonlocal keyword, which would make the code work regardless of whether it is at the top level or inside a function:
x=True
def stupid():
nonlocal x
x=False
stupid()
print x
A:
If you want to access the global variable x from a method in python, you need to do so explicitly:
x=True
def stupid():
global x
x=False
stupid()
print x
A:
The x in the function stupid() is a local variable, so you really have 2 variables named x.
A:
Add "global x" before x=False in the function and it will print True. Otherwise, it's there are two "x"'s, each in a different scope.
A:
Because you're making an assignment to x inside stupid(), Python creates a new x inside stupid().
If you were only reading from x inside stupid(), Python would in fact use the global x, which is what you wanted.
To force Python to use the global x, add global x as the first line inside stupid().
|
why does this python program print True
|
x=True
def stupid():
x=False
stupid()
print x
|
[
"You don't need to declare a function-local variable in Python. The \"x=False\" is referring to an x local to stupid(). If you really want to modify the global x inside stupid:\ndef stupid():\n global x\n x=False\n\n",
"To answer your next question, use global:\nx=True\ndef stupid():\n global x\n x=False\nstupid()\nprint x\n\n",
"Because x's scope is local to the function stupid(). once you call the function, and it ends, you're out of it's scope, and you print the value of \"x\" that's defined outside of the function stupid() -- and, the x that's defined inside of function stupid() doesn't exist on the stack anymore (once that function ends)\nedit after your comment:\nthe outer x is referenced when you printed it, just like you did.\nthe inner x can only be referenced whilst your inside the function stupid(). so you can print inside of that function so that you see what value the x inside of it holds.\nAbout \"global\"\n\nit works & answers the question, apparently\nnot a good idea to use all that often\ncauses readability and scalability issues (and potentially more)\ndepending on your project, you may want to reconsider using a global variable defined inside of a local function.\n\n",
"If that code is all inside a function though, global is not going to work, because then x would not be a global variable. In Python 3.x, they introduced the nonlocal keyword, which would make the code work regardless of whether it is at the top level or inside a function:\nx=True\ndef stupid():\n nonlocal x\n x=False\nstupid()\nprint x\n\n",
"If you want to access the global variable x from a method in python, you need to do so explicitly:\nx=True\ndef stupid():\n global x\n x=False\n\nstupid()\nprint x\n\n",
"The x in the function stupid() is a local variable, so you really have 2 variables named x.\n",
"Add \"global x\" before x=False in the function and it will print True. Otherwise, it's there are two \"x\"'s, each in a different scope.\n",
"\nBecause you're making an assignment to x inside stupid(), Python creates a new x inside stupid().\nIf you were only reading from x inside stupid(), Python would in fact use the global x, which is what you wanted.\nTo force Python to use the global x, add global x as the first line inside stupid().\n\n"
] |
[
18,
10,
6,
5,
3,
2,
2,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001242460_python.txt
|
Q:
subclassing int to attain a Hex representation
Basically I want to have access to all standard python int operators, eg __and__ and __xor__ etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)
class Hex(int):
def __repr__(self):
return "0x%x"%self
__str__=__repr__ # this certainly helps with printing
if __name__=="__main__":
print Hex(0x1abe11ed) ^ Hex(440720179)
print Hex(Hex(0x1abe11ed) ^ Hex(440720179))
Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934
Any ideas?
A:
You should define __repr__ and __str__ separately:
class Hex(int):
def __repr__(self):
return "Hex(0x%x)" % self
def __str__(self):
return "0x%x" % self
The __repr__ function should (if possible) provide Python text that can be eval()uated to reconstruct the original object. On the other hand, __str__ can just return a human readable representation of the object.
A:
A class decorator, especially in Python 2.6 and beyond, is the handiest way to wrap a lot of methods to "return an instance of this class's type rather than an instance of the superclass", which, as other have indicated, is your underlying issue (beyond quibbles with __str__ vs __repr__, worthwhile but not at all resolutory for your problem;-).
def returnthisclassfrom(specials):
specialnames = ['__%s__' % s for s in specials.split()]
def wrapit(cls, method):
return lambda *a: cls(method(*a))
def dowrap(cls):
for n in specialnames:
method = getattr(cls, n)
setattr(cls, n, wrapit(cls, method))
return cls
return dowrap
@returnthisclassfrom('and or xor')
class Hex(int):
def __repr__(self): return hex(self)
__str__ = __repr__
a = Hex(2345)
b = Hex(5432)
print a, b, a^b
In Python 2.6, this emits
0x929 0x1538 0x1c11
as desired. Of course you can add more methodnames to the decorator, etc; if you're stuck with Python 2.5, remove the decorating line (the one starting with @) and use instead
class Hex(int):
def __repr__(self): return hex(self)
__str__ = __repr__
Hex = returnthisclassfrom('and or xor')(Hex)
a mite less elegant, but just as effective;-)
Edit: fixed an occurence of "the usual scoping issue" in the code.
A:
You'll need to get the operators (+, -, ** etc) to return instances of Hex. As is, it will return ints, i.e.
class Hex(int):
def __repr__(self):
return "Hex(0x%x)" % self
def __str__(self):
return "0x%x" % self
>>> h1 = Hex(100)
>>> h2 = Hex(1000)
>>> h1
Hex(0x64)
>>> h2
Hex(0x3e8)
>>> h1+h2
1100
>>> type(h1+h2)
<type 'int'>
So, you can override the various operators:
class Hex(int):
def __repr__(self):
return "Hex(0x%x)" % self
def __str__(self):
return "0x%x" % self
def __add__(self, other):
return Hex(super(Hex, self).__add__(other))
def __sub__(self, other):
return self.__add__(-other)
def __pow__(self, power):
return Hex(super(Hex, self).__pow__(power))
def __xor__(self, other):
return Hex(super(Hex, self).__xor__(other))
>>> h1 = Hex(100)
>>> h2 = Hex(1000)
>>> h1+h2
Hex(0x44c)
>>> type(h1+h2)
<class '__main__.Hex'>
>>> h1 += h2
>>> h1
Hex(0x44c)
>>> h2 ** 2
Hex(0xf4240)
>>> Hex(0x1abe11ed) ^ Hex(440720179)
>>> Hex(0xfacade)
I don't know about this, I feel that there must be a better way without having to override every operator to return an instance of Hex???
A:
In response to your comment:
You could write a Mixin by yourself:
class IntMathMixin:
def __add__(self, other):
return type(self)(int(self).__add__(int(other)))
# ... analog for the others
Then use it like this:
class Hex(IntMathMixin, int):
def __repr__(self):
return "0x%x"%self
__str__=__repr__
A:
Override __str__ as well.
__repr__ is used when repr(o) is called, and to display a value at the interactive prompt. __str__ is called for most instances of stringifying an object, including when it is printed.
The default __str__ behavior for an object is to fall back to the repr, but int provides its own __str__ method (which is identical to __repr__ (before Python 3), but does not fall back to __repr__).
|
subclassing int to attain a Hex representation
|
Basically I want to have access to all standard python int operators, eg __and__ and __xor__ etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)
class Hex(int):
def __repr__(self):
return "0x%x"%self
__str__=__repr__ # this certainly helps with printing
if __name__=="__main__":
print Hex(0x1abe11ed) ^ Hex(440720179)
print Hex(Hex(0x1abe11ed) ^ Hex(440720179))
Ideally BOTH line of output should be hexadecimal: 0xfacade, however the first one yields decimal: 16435934
Any ideas?
|
[
"You should define __repr__ and __str__ separately:\nclass Hex(int):\n def __repr__(self):\n return \"Hex(0x%x)\" % self\n def __str__(self):\n return \"0x%x\" % self\n\nThe __repr__ function should (if possible) provide Python text that can be eval()uated to reconstruct the original object. On the other hand, __str__ can just return a human readable representation of the object.\n",
"A class decorator, especially in Python 2.6 and beyond, is the handiest way to wrap a lot of methods to \"return an instance of this class's type rather than an instance of the superclass\", which, as other have indicated, is your underlying issue (beyond quibbles with __str__ vs __repr__, worthwhile but not at all resolutory for your problem;-).\ndef returnthisclassfrom(specials):\n specialnames = ['__%s__' % s for s in specials.split()]\n def wrapit(cls, method):\n return lambda *a: cls(method(*a))\n def dowrap(cls):\n for n in specialnames:\n method = getattr(cls, n)\n setattr(cls, n, wrapit(cls, method))\n return cls\n return dowrap\n\n@returnthisclassfrom('and or xor')\nclass Hex(int):\n def __repr__(self): return hex(self)\n __str__ = __repr__\n\na = Hex(2345)\nb = Hex(5432)\nprint a, b, a^b\n\nIn Python 2.6, this emits\n0x929 0x1538 0x1c11\n\nas desired. Of course you can add more methodnames to the decorator, etc; if you're stuck with Python 2.5, remove the decorating line (the one starting with @) and use instead\nclass Hex(int):\n def __repr__(self): return hex(self)\n __str__ = __repr__\nHex = returnthisclassfrom('and or xor')(Hex)\n\na mite less elegant, but just as effective;-)\nEdit: fixed an occurence of \"the usual scoping issue\" in the code.\n",
"You'll need to get the operators (+, -, ** etc) to return instances of Hex. As is, it will return ints, i.e.\nclass Hex(int):\n def __repr__(self):\n return \"Hex(0x%x)\" % self\n def __str__(self):\n return \"0x%x\" % self\n>>> h1 = Hex(100)\n>>> h2 = Hex(1000)\n>>> h1\nHex(0x64)\n>>> h2\nHex(0x3e8)\n>>> h1+h2\n1100\n>>> type(h1+h2)\n<type 'int'>\n\nSo, you can override the various operators:\nclass Hex(int):\n def __repr__(self):\n return \"Hex(0x%x)\" % self\n def __str__(self):\n return \"0x%x\" % self\n def __add__(self, other):\n return Hex(super(Hex, self).__add__(other))\n def __sub__(self, other):\n return self.__add__(-other)\n def __pow__(self, power):\n return Hex(super(Hex, self).__pow__(power))\n def __xor__(self, other):\n return Hex(super(Hex, self).__xor__(other))\n\n>>> h1 = Hex(100)\n>>> h2 = Hex(1000)\n>>> h1+h2\nHex(0x44c)\n>>> type(h1+h2)\n<class '__main__.Hex'>\n>>> h1 += h2\n>>> h1\nHex(0x44c)\n>>> h2 ** 2\nHex(0xf4240)\n>>> Hex(0x1abe11ed) ^ Hex(440720179)\n>>> Hex(0xfacade)\n\nI don't know about this, I feel that there must be a better way without having to override every operator to return an instance of Hex???\n",
"In response to your comment: \nYou could write a Mixin by yourself:\nclass IntMathMixin:\n def __add__(self, other):\n return type(self)(int(self).__add__(int(other)))\n # ... analog for the others\n\nThen use it like this:\nclass Hex(IntMathMixin, int):\n def __repr__(self):\n return \"0x%x\"%self\n __str__=__repr__ \n\n",
"Override __str__ as well.\n__repr__ is used when repr(o) is called, and to display a value at the interactive prompt. __str__ is called for most instances of stringifying an object, including when it is printed.\nThe default __str__ behavior for an object is to fall back to the repr, but int provides its own __str__ method (which is identical to __repr__ (before Python 3), but does not fall back to __repr__).\n"
] |
[
7,
6,
1,
1,
0
] |
[] |
[] |
[
"hex",
"python",
"representation",
"subclassing"
] |
stackoverflow_0001242589_hex_python_representation_subclassing.txt
|
Q:
How to disable Control-C in a WindowsXP Python console program?
I'd like to put my cmd.com window into a mode where Control-C does not generate a SIGINT signal to Python (ActiveState if it matters).
I know I can use the signal module to handle SIGINT. The problem is that handling SIGINT is too late; by the time it is handled, it has already interrupted a system call.
I'd like something equivalent to the *nix "raw" mode. Just let the input queue up and when it is safe for my application to read it, it will.
Maddeningly enough, msvcrt.getch() seems to return Control-C as a character. But that only works while the program is blocked by getch() itself. If I am in another system call (sleep, just to use an example), I get the SIGINT.
A:
You need to call the win32 API function SetConsoleCtrlHandler with NULL (0) as its first parameter and TRUE (1) as its second parameter. If you're already using pywin32, win32.SetConsoleCtrlHandler is fine for the purpose, otherwise ctypes should work, specifically via ctypes.windll.kernel32.SetConsoleCtrlHandler(0, 1)/
|
How to disable Control-C in a WindowsXP Python console program?
|
I'd like to put my cmd.com window into a mode where Control-C does not generate a SIGINT signal to Python (ActiveState if it matters).
I know I can use the signal module to handle SIGINT. The problem is that handling SIGINT is too late; by the time it is handled, it has already interrupted a system call.
I'd like something equivalent to the *nix "raw" mode. Just let the input queue up and when it is safe for my application to read it, it will.
Maddeningly enough, msvcrt.getch() seems to return Control-C as a character. But that only works while the program is blocked by getch() itself. If I am in another system call (sleep, just to use an example), I get the SIGINT.
|
[
"You need to call the win32 API function SetConsoleCtrlHandler with NULL (0) as its first parameter and TRUE (1) as its second parameter. If you're already using pywin32, win32.SetConsoleCtrlHandler is fine for the purpose, otherwise ctypes should work, specifically via ctypes.windll.kernel32.SetConsoleCtrlHandler(0, 1)/\n"
] |
[
4
] |
[] |
[] |
[
"console_application",
"control_c",
"copy_paste",
"python",
"windows_xp"
] |
stackoverflow_0001243047_console_application_control_c_copy_paste_python_windows_xp.txt
|
Q:
Qt Image From Web
I'd like PyQt to load an image and display it from the web. Dozens of examples I've found online did not work, as they are for downloading the image.
I simply want to view it.
Something like
from PyQt4.QtWebKit import *
web = QWebView()
web.load(QUrl("http://stackoverflow.com/content/img/so/logo.png"))
A:
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
app = QtGui.QApplication(sys.argv)
web = QtWebKit.QWebView()
web.load(QtCore.QUrl("http://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png"))
web.show()
sys.exit(app.exec_())
|
Qt Image From Web
|
I'd like PyQt to load an image and display it from the web. Dozens of examples I've found online did not work, as they are for downloading the image.
I simply want to view it.
Something like
from PyQt4.QtWebKit import *
web = QWebView()
web.load(QUrl("http://stackoverflow.com/content/img/so/logo.png"))
|
[
"import sys\nfrom PyQt4 import QtCore, QtGui, QtWebKit\n\napp = QtGui.QApplication(sys.argv) \n\nweb = QtWebKit.QWebView()\nweb.load(QtCore.QUrl(\"http://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png\"))\nweb.show()\n\nsys.exit(app.exec_()) \n\n"
] |
[
5
] |
[] |
[] |
[
"pyqt",
"python",
"qt",
"qwebelement",
"qwebview"
] |
stackoverflow_0001243064_pyqt_python_qt_qwebelement_qwebview.txt
|
Q:
Access a large file in a zip archive with HTML in a python-webkit WebView without extracting
I apologize for any confusion from the question title. It's kind of a complex situation with components that are new to me so I'm unsure of how to describe it succinctly.
I have some xml data and an image in an archive (zip in this case, but could easily be tar or tar.gz) and using python, gtk, and webkit, place the image in a webkit.WebView, along with some of the other data. The xml is child's play to access without extracting the files, but the image is another issue.
I'd like to avoid extracting the image to to the hdd before putting it in the WebView and doing a base64 encode of the image data feels cludgy, especially since the images could potentially reach tens of megabytes.
Basically I'm looking for a way to construct an URI to a file stored inside a container file.
I asked a few days ago in IRC and was directed toward virtual file systems. In the searches I performed I found a few references to creating a vfs from a zip file, but no examples or even much in the way of documentation on virtual file systems themselves (gnomeVFS, gvfs, gio.) I may be looking in all the wrong places, however.
A:
The zipfile module in the standard Python library provides tools to create, read, write, append, and list a ZIP file.
Using ZipFile.read(name[, pwd]) ( return the bytes of the file name in the archive),
you can apply base64.b64encode(s[, altchars]) to the content. Note that in this straightforward process, the unzipped and the encoded versions are stored in memory.
|
Access a large file in a zip archive with HTML in a python-webkit WebView without extracting
|
I apologize for any confusion from the question title. It's kind of a complex situation with components that are new to me so I'm unsure of how to describe it succinctly.
I have some xml data and an image in an archive (zip in this case, but could easily be tar or tar.gz) and using python, gtk, and webkit, place the image in a webkit.WebView, along with some of the other data. The xml is child's play to access without extracting the files, but the image is another issue.
I'd like to avoid extracting the image to to the hdd before putting it in the WebView and doing a base64 encode of the image data feels cludgy, especially since the images could potentially reach tens of megabytes.
Basically I'm looking for a way to construct an URI to a file stored inside a container file.
I asked a few days ago in IRC and was directed toward virtual file systems. In the searches I performed I found a few references to creating a vfs from a zip file, but no examples or even much in the way of documentation on virtual file systems themselves (gnomeVFS, gvfs, gio.) I may be looking in all the wrong places, however.
|
[
"The zipfile module in the standard Python library provides tools to create, read, write, append, and list a ZIP file. \nUsing ZipFile.read(name[, pwd]) ( return the bytes of the file name in the archive),\nyou can apply base64.b64encode(s[, altchars]) to the content. Note that in this straightforward process, the unzipped and the encoded versions are stored in memory.\n"
] |
[
1
] |
[] |
[] |
[
"gzip",
"python",
"tar",
"virtualfilesystem",
"zip"
] |
stackoverflow_0001243485_gzip_python_tar_virtualfilesystem_zip.txt
|
Q:
Validating XML in Python without non-python dependencies
I'm writing a small Python app for distribution. I need to include simple XML validation (it's a debugging tool), but I want to avoid any dependencies on compiled C libraries such as lxml or pyxml as those will make the resulting app much harder to distribute. I can't find anything that seems to fit the bill - for DTDs, Relax NG or XML Schema. Any suggestions?
A:
Do you mean something like MiniXsv? I have never used it, but from the website, we can read that
minixsv is a lightweight XML schema
validator package written in pure
Python (at least Python 2.4 is
required).
so, it should work for you.
I believe that ElementTree could also be used for that goal, but I am not 100% sure.
A:
Why don't you try invoking an online XML validator and parsing the results?
I couldn't find any free REST or SOAP based services but it would be easy enough to use a normal HTML form based one such as this one or this one. You just need to construct the correct request and parse the results (httplib may be of help here if you don't want to use a third party library such as mechanize to easy the pain).
A:
I haven't looked at it in a while so it might have changed, but Fourthought's 4Suite (community edition) could still be pure Python.
Edit: just browsed through the docs and it's mostly Python which probably isn't enough for you.
A:
The beautifulsoup module is pure Python (and a single .py file), but I don't know if it will fulfill your validation needs, I've only used it for quickly extracting some fields on large XMLs.
http://www.crummy.com/software/BeautifulSoup/
|
Validating XML in Python without non-python dependencies
|
I'm writing a small Python app for distribution. I need to include simple XML validation (it's a debugging tool), but I want to avoid any dependencies on compiled C libraries such as lxml or pyxml as those will make the resulting app much harder to distribute. I can't find anything that seems to fit the bill - for DTDs, Relax NG or XML Schema. Any suggestions?
|
[
"Do you mean something like MiniXsv? I have never used it, but from the website, we can read that\n\nminixsv is a lightweight XML schema\n validator package written in pure\n Python (at least Python 2.4 is\n required).\n\nso, it should work for you.\nI believe that ElementTree could also be used for that goal, but I am not 100% sure.\n",
"Why don't you try invoking an online XML validator and parsing the results? \nI couldn't find any free REST or SOAP based services but it would be easy enough to use a normal HTML form based one such as this one or this one. You just need to construct the correct request and parse the results (httplib may be of help here if you don't want to use a third party library such as mechanize to easy the pain).\n",
"I haven't looked at it in a while so it might have changed, but Fourthought's 4Suite (community edition) could still be pure Python.\nEdit: just browsed through the docs and it's mostly Python which probably isn't enough for you.\n",
"The beautifulsoup module is pure Python (and a single .py file), but I don't know if it will fulfill your validation needs, I've only used it for quickly extracting some fields on large XMLs.\nhttp://www.crummy.com/software/BeautifulSoup/\n"
] |
[
4,
1,
1,
0
] |
[] |
[] |
[
"dtd",
"python",
"schema",
"validation",
"xml"
] |
stackoverflow_0001243449_dtd_python_schema_validation_xml.txt
|
Q:
Is there a Python module/recipe (not numpy) for 2d arrays for small games
I am writing some small games in Python with Pygame & Pyglet as hobby projects.
A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.
Could you suggest a Python module/recipe I could use for this.
-- Chirag
[Edit]:
List of lists would be usable as mentioned below by MatrixFrog and zvoase. But it is pretty primitive. A class with methods to insert/delete rows and columns as well as to rotate/flip the array would make it very easy and reusable too. dicts are good for sparse arrays only.
Thank you for your ideas.
A:
How about using a defaultdict?
>>> import collections
>>> Matrix = lambda: collections.defaultdict(int)
>>> m = Matrix()
>>> m[3,2] = 6
>>> print m[3,4] # deliberate typo :-)
0
>>> m[3,2] += 4
>>> print m[3,2]
10
>>> print m
defaultdict(<type 'int'>, {(3, 2): 10, (3, 4): 0})
As the underlying dict uses tuples as keys, this supports 1D, 2D, 3D, ... matrices.
A:
The simplest approach would just be to use nested lists:
>>> matrix = [[0] * num_cols] * num_rows
>>> matrix[i][j] = 'value' # row i, column j, value 'value'
>>> print repr(matrix[i][j])
'value'
Alternatively, if you’re going to be dealing with sparse matrices (i.e. matrices with a lot of empty or zero values), it might be more efficient to use nested dictionaries. In this case, you could implement setter and getter functions which will operate on a matrix, like so:
def get_element(mat, i, j, default=None):
# This will also set the accessed row to a dictionary.
row = mat.setdefault(i, {})
return row.setdefault(j, default)
def set_element(mat, i, j, value):
row = mat.setdefault(i, {})
row[j] = value
And then you would use them like this:
>>> matrix = {}
>>> set_element(matrix, 2, 3, 'value') # row 2, column 3, value 'value'
>>> print matrix
{2: {3: 'value'}}
>>> print repr(get_element(matrix, 2, 3))
'value'
If you wanted, you could implement a Matrix class which implemented these methods, but that might be overkill:
class Matrix(object):
def __init__(self, initmat=None, default=0):
if initmat is None: initmat = {}
self._mat = initmat
self._default = default
def __getitem__(self, pos):
i, j = pos
return self._mat.setdefault(i, {}).setdefault(j, self._default)
def __setitem__(self, pos, value):
i, j = pos
self._mat.setdefault(i, {})[j] = value
def __repr__(self):
return 'Matrix(%r, %r)' % (self._mat, self._default)
>>> m = Matrix()
>>> m[2,3] = 'value'
>>> print m[2,3]
'value'
>>> m
Matrix({2: {3: 'value'}}, 0)
A:
Maybe pyeuclid matches your needs -- (dated but usable) formatted docs are here, up-to-date docs in ReST format are in this text file in the pyeuclid sources (to do your own formatting of ReST text, use the docutils).
A:
I wrote the class. Don't know if it is a good or redundant but... Posted it here http://bitbucket.org/pieceofpeace/container2d/
|
Is there a Python module/recipe (not numpy) for 2d arrays for small games
|
I am writing some small games in Python with Pygame & Pyglet as hobby projects.
A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.
Could you suggest a Python module/recipe I could use for this.
-- Chirag
[Edit]:
List of lists would be usable as mentioned below by MatrixFrog and zvoase. But it is pretty primitive. A class with methods to insert/delete rows and columns as well as to rotate/flip the array would make it very easy and reusable too. dicts are good for sparse arrays only.
Thank you for your ideas.
|
[
"How about using a defaultdict?\n>>> import collections\n>>> Matrix = lambda: collections.defaultdict(int)\n>>> m = Matrix()\n>>> m[3,2] = 6\n>>> print m[3,4] # deliberate typo :-)\n0\n>>> m[3,2] += 4\n>>> print m[3,2]\n10\n>>> print m\ndefaultdict(<type 'int'>, {(3, 2): 10, (3, 4): 0})\n\nAs the underlying dict uses tuples as keys, this supports 1D, 2D, 3D, ... matrices.\n",
"The simplest approach would just be to use nested lists:\n>>> matrix = [[0] * num_cols] * num_rows\n>>> matrix[i][j] = 'value' # row i, column j, value 'value'\n>>> print repr(matrix[i][j])\n'value'\n\nAlternatively, if you’re going to be dealing with sparse matrices (i.e. matrices with a lot of empty or zero values), it might be more efficient to use nested dictionaries. In this case, you could implement setter and getter functions which will operate on a matrix, like so:\ndef get_element(mat, i, j, default=None):\n # This will also set the accessed row to a dictionary.\n row = mat.setdefault(i, {})\n return row.setdefault(j, default)\n\ndef set_element(mat, i, j, value):\n row = mat.setdefault(i, {})\n row[j] = value\n\nAnd then you would use them like this:\n>>> matrix = {}\n>>> set_element(matrix, 2, 3, 'value') # row 2, column 3, value 'value'\n>>> print matrix\n{2: {3: 'value'}}\n>>> print repr(get_element(matrix, 2, 3))\n'value'\n\nIf you wanted, you could implement a Matrix class which implemented these methods, but that might be overkill:\nclass Matrix(object):\n def __init__(self, initmat=None, default=0):\n if initmat is None: initmat = {}\n self._mat = initmat\n self._default = default\n def __getitem__(self, pos):\n i, j = pos\n return self._mat.setdefault(i, {}).setdefault(j, self._default) \n def __setitem__(self, pos, value):\n i, j = pos\n self._mat.setdefault(i, {})[j] = value\n def __repr__(self):\n return 'Matrix(%r, %r)' % (self._mat, self._default)\n\n>>> m = Matrix()\n>>> m[2,3] = 'value'\n>>> print m[2,3]\n'value'\n>>> m\nMatrix({2: {3: 'value'}}, 0)\n\n",
"Maybe pyeuclid matches your needs -- (dated but usable) formatted docs are here, up-to-date docs in ReST format are in this text file in the pyeuclid sources (to do your own formatting of ReST text, use the docutils).\n",
"I wrote the class. Don't know if it is a good or redundant but... Posted it here http://bitbucket.org/pieceofpeace/container2d/\n"
] |
[
6,
3,
2,
0
] |
[] |
[] |
[
"arrays",
"multidimensional_array",
"python"
] |
stackoverflow_0000929274_arrays_multidimensional_array_python.txt
|
Q:
Consuming COM events in Python
I am trying to do a sample app in python which uses some COM objects. I've read the famous chapter 12 from Python Programing on Win32 but regarding this issue it only states:
All event handling is done using
normal IConnectionPoint interfaces,
and although beyond the scope of this
book, is fully supported by the
standard Python COM framework.
Can anybody shed some light on this? I'd need a simple starter sample. Something like adding code to this sample to catch the OnActivate event for the spreadsheet
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
...
A:
I haven't automated Excel, but I'm using some code from Microsoft's Speech API that may be similar enough to get you started:
ListenerBase = win32com.client.getevents("SAPI.SpInProcRecoContext")
class Listener(ListenerBase):
def OnRecognition(self, _1, _2, _3, Result):
"""Callback whenever something is recognized."""
# Work with Result
def OnHypothesis(self, _1, _2, Result):
"""Callback whenever we have a potential match."""
# Work with Result
then later in a main loop:
while not self.shutting_down.is_set():
# Trigger the event handlers if we have anything.
pythoncom.PumpWaitingMessages()
time.sleep(0.1) # Don't use up all our CPU checking constantly
Edit for more detail on the main loop:
When something happens, the callback doesn't get called immediately; instead you have to call PumpWaitingMessages(), which checks if there are any events waiting and then calls the appropriate callback.
If you want to do something else while this is happening, you'll have to run the loop in a separate thread (see the threading module); otherwise it can just sit at the bottom of your script. In my example I was running it in a separate thread because I also had a GUI running; the shutting_down variable is a threading.Event you can use to tell the looping thread to stop.
|
Consuming COM events in Python
|
I am trying to do a sample app in python which uses some COM objects. I've read the famous chapter 12 from Python Programing on Win32 but regarding this issue it only states:
All event handling is done using
normal IConnectionPoint interfaces,
and although beyond the scope of this
book, is fully supported by the
standard Python COM framework.
Can anybody shed some light on this? I'd need a simple starter sample. Something like adding code to this sample to catch the OnActivate event for the spreadsheet
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
...
|
[
"I haven't automated Excel, but I'm using some code from Microsoft's Speech API that may be similar enough to get you started:\nListenerBase = win32com.client.getevents(\"SAPI.SpInProcRecoContext\")\nclass Listener(ListenerBase):\n def OnRecognition(self, _1, _2, _3, Result):\n \"\"\"Callback whenever something is recognized.\"\"\"\n # Work with Result\n\n def OnHypothesis(self, _1, _2, Result):\n \"\"\"Callback whenever we have a potential match.\"\"\"\n # Work with Result\n\nthen later in a main loop:\n while not self.shutting_down.is_set():\n # Trigger the event handlers if we have anything.\n pythoncom.PumpWaitingMessages() \n time.sleep(0.1) # Don't use up all our CPU checking constantly\n\nEdit for more detail on the main loop:\nWhen something happens, the callback doesn't get called immediately; instead you have to call PumpWaitingMessages(), which checks if there are any events waiting and then calls the appropriate callback.\nIf you want to do something else while this is happening, you'll have to run the loop in a separate thread (see the threading module); otherwise it can just sit at the bottom of your script. In my example I was running it in a separate thread because I also had a GUI running; the shutting_down variable is a threading.Event you can use to tell the looping thread to stop.\n"
] |
[
6
] |
[] |
[] |
[
"com",
"python",
"pywin32"
] |
stackoverflow_0001244463_com_python_pywin32.txt
|
Q:
Accessing a pointer in an object's internal structure
I'm using the pyOpenSSL interface to the OpenSSL library but it is missing some functions I need and I can't or don't want to modify it to support these methods (for various reasons).
So what I want to achieve, is to retrieve the OpenSSL object pointer. After that, I will be able to call the missing functions through ctypes. What is the best method to do that ?
I have already found that I can use id() to get the pointer to the pyOpenSSL object. How can I access the ssl variable with that.
From pyOpenSSL/connections.h:
typedef struct {
PyObject_HEAD
SSL *ssl;
ssl_ContextObj *context;
PyObject *socket;
PyThreadState *tstate;
PyObject *app_data;
} ssl_ConnectionObj;
A:
Pointers doesn't really make much sense in Python, as you can't do anything with them. They would just be an integer. As you have noticed you can get the address of an object with the id method. But that's just what it is, the address. It's not a pointer, so you can't do anything with it.
You could also see it like this: Everything in Python are pointers. The variable you have for the pyOpenSSL object is the pointer. But it is the pointer to the pyOpenSSL-object, not to the connection structure. It's unlikely you can access that structure directly.
So you have to tell us what you want to do instead. Maybe there is another solution.
|
Accessing a pointer in an object's internal structure
|
I'm using the pyOpenSSL interface to the OpenSSL library but it is missing some functions I need and I can't or don't want to modify it to support these methods (for various reasons).
So what I want to achieve, is to retrieve the OpenSSL object pointer. After that, I will be able to call the missing functions through ctypes. What is the best method to do that ?
I have already found that I can use id() to get the pointer to the pyOpenSSL object. How can I access the ssl variable with that.
From pyOpenSSL/connections.h:
typedef struct {
PyObject_HEAD
SSL *ssl;
ssl_ContextObj *context;
PyObject *socket;
PyThreadState *tstate;
PyObject *app_data;
} ssl_ConnectionObj;
|
[
"Pointers doesn't really make much sense in Python, as you can't do anything with them. They would just be an integer. As you have noticed you can get the address of an object with the id method. But that's just what it is, the address. It's not a pointer, so you can't do anything with it.\nYou could also see it like this: Everything in Python are pointers. The variable you have for the pyOpenSSL object is the pointer. But it is the pointer to the pyOpenSSL-object, not to the connection structure. It's unlikely you can access that structure directly.\nSo you have to tell us what you want to do instead. Maybe there is another solution.\n"
] |
[
3
] |
[] |
[] |
[
"internals",
"pointers",
"python"
] |
stackoverflow_0001243806_internals_pointers_python.txt
|
Q:
Flexible 'em' style Fonts with wxPython
Im looking for a way to present a flexible font, that will increase and decrease in size according to to the size of the screen resolution. I want to be able to do this without the HTML window class. Is there a way? I thought I've done quite a bit of googling without success.
EDIT
This seems a good question, I changed the title to reflect closer what I was looking for.
EDIT
So now I've realized that the regular pixel sizes will scale in the way I mentioned already - but I saw this the other day and realized it might be helpful if someone wanted to use CSS with their wxPython Apps - its a library that allows you to 'skin' your application and I can think of a dozen neat ways to use it already - here is a link in lieu of a more well thought out question :)
link text
A:
Maybe something like this? You can scale any wx.Window in this way. Not sure if this is exactly what you mean though.
import wx
def scale(widget, percentage):
font = widget.GetFont()
font.SetPointSize(int(font.GetPointSize() * percentage / 100.0))
widget.SetFont(font)
class Frame(wx.Frame):
def __init__(self):
super(Frame, self).__init__(None, -1, 'Scaling Fonts')
panel = wx.Panel(self, -1)
sizer = wx.BoxSizer(wx.VERTICAL)
for i in range(50, 201, 25):
widget = wx.StaticText(panel, -1, 'Scale Factor = %d' % i)
scale(widget, i)
sizer.Add(widget, 0, wx.ALL, 5)
panel.SetSizer(sizer)
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = Frame()
frame.Show()
app.MainLoop()
|
Flexible 'em' style Fonts with wxPython
|
Im looking for a way to present a flexible font, that will increase and decrease in size according to to the size of the screen resolution. I want to be able to do this without the HTML window class. Is there a way? I thought I've done quite a bit of googling without success.
EDIT
This seems a good question, I changed the title to reflect closer what I was looking for.
EDIT
So now I've realized that the regular pixel sizes will scale in the way I mentioned already - but I saw this the other day and realized it might be helpful if someone wanted to use CSS with their wxPython Apps - its a library that allows you to 'skin' your application and I can think of a dozen neat ways to use it already - here is a link in lieu of a more well thought out question :)
link text
|
[
"Maybe something like this? You can scale any wx.Window in this way. Not sure if this is exactly what you mean though.\nimport wx\n\ndef scale(widget, percentage):\n font = widget.GetFont()\n font.SetPointSize(int(font.GetPointSize() * percentage / 100.0))\n widget.SetFont(font)\n\nclass Frame(wx.Frame):\n def __init__(self):\n super(Frame, self).__init__(None, -1, 'Scaling Fonts')\n panel = wx.Panel(self, -1)\n sizer = wx.BoxSizer(wx.VERTICAL)\n for i in range(50, 201, 25):\n widget = wx.StaticText(panel, -1, 'Scale Factor = %d' % i)\n scale(widget, i)\n sizer.Add(widget, 0, wx.ALL, 5)\n panel.SetSizer(sizer)\n\nif __name__ == '__main__':\n app = wx.PySimpleApp()\n frame = Frame()\n frame.Show()\n app.MainLoop()\n\n"
] |
[
1
] |
[] |
[] |
[
"font_size",
"fonts",
"python",
"wxpython"
] |
stackoverflow_0001225248_font_size_fonts_python_wxpython.txt
|
Q:
Disable console output from subprocess.Popen in Python
I run Python 2.5 on Windows, and somewhere in the code I have
subprocess.Popen("taskkill /PID " + str(p.pid))
to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess in subprocess.py, but can't go from there.
Anyone knows how to disable this?
A:
import os
from subprocess import check_call, STDOUT
DEVNULL = open(os.devnull, 'wb')
try:
check_call(("taskkill", "/PID", str(p.pid)), stdout=DEVNULL, stderr=STDOUT)
finally:
DEVNULL.close()
I always pass in tuples to subprocess as it saves me worrying about escaping. check_call ensures (a) the subprocess has finished before the pipe closes, and (b) a failure in the called process is not ignored. Finally, os.devnull is the standard, cross-platform way of saying NUL in Python 2.4+.
Note that in Py3K, subprocess provides DEVNULL for you, so you can just write:
from subprocess import check_call, DEVNULL, STDOUT
check_call(("taskkill", "/PID", str(p.pid)), stdout=DEVNULL, stderr=STDOUT)
A:
fh = open("NUL","w")
subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh)
fh.close()
|
Disable console output from subprocess.Popen in Python
|
I run Python 2.5 on Windows, and somewhere in the code I have
subprocess.Popen("taskkill /PID " + str(p.pid))
to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess in subprocess.py, but can't go from there.
Anyone knows how to disable this?
|
[
"import os\nfrom subprocess import check_call, STDOUT\n\nDEVNULL = open(os.devnull, 'wb')\ntry:\n check_call((\"taskkill\", \"/PID\", str(p.pid)), stdout=DEVNULL, stderr=STDOUT)\nfinally:\n DEVNULL.close()\n\nI always pass in tuples to subprocess as it saves me worrying about escaping. check_call ensures (a) the subprocess has finished before the pipe closes, and (b) a failure in the called process is not ignored. Finally, os.devnull is the standard, cross-platform way of saying NUL in Python 2.4+.\nNote that in Py3K, subprocess provides DEVNULL for you, so you can just write:\nfrom subprocess import check_call, DEVNULL, STDOUT\n\ncheck_call((\"taskkill\", \"/PID\", str(p.pid)), stdout=DEVNULL, stderr=STDOUT)\n\n",
"fh = open(\"NUL\",\"w\")\nsubprocess.Popen(\"taskkill /PID \" + str(p.pid), stdout = fh, stderr = fh)\nfh.close()\n\n"
] |
[
17,
9
] |
[] |
[] |
[
"console",
"popen",
"python",
"subprocess"
] |
stackoverflow_0001244723_console_popen_python_subprocess.txt
|
Q:
How to implement a state-space tree?
I'm trying to solve a knapsack like problem from MIT OCW.
Its problem set 5.
I need use branch and bound algorithm to find the optimal states.
So I need implement a state-space tree.
I understand the idea of this algorithm, but I find it's not so easy to implement.
If I find a node where the budget is not enough, I should stop here.
Should I add an attribute to every tree node?
When I add a node, I should start from a node with the largest upper bound.
How can I find such a node? Do I need to traverse all the nodes before I add each node? Or could I save some var to help with that?
Do you have any idea? Could you implement it in python?
A:
I hope I understood correctly the problem, if not please direct me :)
(sorry for the confusion arising from the two different meanings of "state")
You can of course add the attribute in the node (it's part of the state!), since it's a very tiny amount of data. Mind that it is not mandatory to save it though, since it is implicitly present in the rest of the state (given the states that you have already chosen, you can compute it). Personally, I'd add the attribute, since there's no point in calculating it many times.
On the second question: IIRC, when you add nodes, you don't have to traverse ALL the tree, but rather only the fringe (that is, the set of nodes which have no descendants - not to be confused by the deepest level of the tree).
Since you're looking for an upper bound, (and since you're using only positive costs), there are three cases when you are looking for the node with the highest value:
on the last step you appended to the node which had the highest value, so the node which you just added has now the highest value
on the last step adding the you exceeded the budget, so you had to exclude the option. try to add another state
there are no more states to try to add to build a new node. This branch can't go further. Look at the fringe for the highest value in the other nodes
|
How to implement a state-space tree?
|
I'm trying to solve a knapsack like problem from MIT OCW.
Its problem set 5.
I need use branch and bound algorithm to find the optimal states.
So I need implement a state-space tree.
I understand the idea of this algorithm, but I find it's not so easy to implement.
If I find a node where the budget is not enough, I should stop here.
Should I add an attribute to every tree node?
When I add a node, I should start from a node with the largest upper bound.
How can I find such a node? Do I need to traverse all the nodes before I add each node? Or could I save some var to help with that?
Do you have any idea? Could you implement it in python?
|
[
"I hope I understood correctly the problem, if not please direct me :)\n(sorry for the confusion arising from the two different meanings of \"state\")\nYou can of course add the attribute in the node (it's part of the state!), since it's a very tiny amount of data. Mind that it is not mandatory to save it though, since it is implicitly present in the rest of the state (given the states that you have already chosen, you can compute it). Personally, I'd add the attribute, since there's no point in calculating it many times.\nOn the second question: IIRC, when you add nodes, you don't have to traverse ALL the tree, but rather only the fringe (that is, the set of nodes which have no descendants - not to be confused by the deepest level of the tree).\nSince you're looking for an upper bound, (and since you're using only positive costs), there are three cases when you are looking for the node with the highest value:\n\non the last step you appended to the node which had the highest value, so the node which you just added has now the highest value\non the last step adding the you exceeded the budget, so you had to exclude the option. try to add another state\nthere are no more states to try to add to build a new node. This branch can't go further. Look at the fringe for the highest value in the other nodes\n\n"
] |
[
2
] |
[] |
[] |
[
"algorithm",
"python"
] |
stackoverflow_0001237634_algorithm_python.txt
|
Q:
Can I use more than a single filter on a variable in template?
For example:
{{test|linebreaksbr|safe}}
A:
Yes you can, this is common practice to string together many filters consecutively.
Could you turn debugging on and see what the error is and update the question?
Make sure this is set in your settings.py
DEBUG = True
TEMPLATE_DEBUG = DEBUG
A:
Yes, have you tried it? Did something go wrong?
|
Can I use more than a single filter on a variable in template?
|
For example:
{{test|linebreaksbr|safe}}
|
[
"Yes you can, this is common practice to string together many filters consecutively.\nCould you turn debugging on and see what the error is and update the question?\nMake sure this is set in your settings.py\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\n",
"Yes, have you tried it? Did something go wrong?\n"
] |
[
2,
2
] |
[] |
[] |
[
"django",
"filter",
"python",
"templates"
] |
stackoverflow_0001246968_django_filter_python_templates.txt
|
Q:
How can I process this text file and parse what I need?
I'm trying to parse ouput from the Python doctest module and store it in an HTML file.
I've got output similar to this:
**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6, 24, 120]
Got:
[1, 1, 2, 6, 24, 120]
**********************************************************************
File "example.py", line 20, in __main__.factorial
Failed example:
factorial(30)
Expected:
25252859812191058636308480000000L
Got:
265252859812191058636308480000000L
**********************************************************************
1 items had failures:
2 of 8 in __main__.factorial
***Test Failed*** 2 failures.
Each failure is preceded by a line of asterisks, which delimit each test failure from each other.
What I'd like to do is strip out the filename and method that failed, as well as the expected and actual results. Then I'd like to create an HTML document using this (or store it in a text file and then do a second round of parsing).
How can I do this using just Python or some combination of UNIX shell utilities?
EDIT: I formulated the following shell script which matches each block how I'd like,but I'm unsure how to redirect each sed match to its own file.
python example.py | sed -n '/.*/,/^\**$/p' > `mktemp error.XXX`
A:
You can write a Python program to pick this apart, but maybe a better thing to do would be to look into modifying doctest to output the report you want in the first place. From the docs for doctest.DocTestRunner:
... the display output
can be also customized by subclassing DocTestRunner, and
overriding the methods `report_start`, `report_success`,
`report_unexpected_exception`, and `report_failure`.
A:
This is a quick and dirty script that parses the output into tuples with the relevant information:
import sys
import re
stars_re = re.compile('^[*]+$', re.MULTILINE)
file_line_re = re.compile(r'^File "(.*?)", line (\d*), in (.*)$')
doctest_output = sys.stdin.read()
chunks = stars_re.split(doctest_output)[1:-1]
for chunk in chunks:
chunk_lines = chunk.strip().splitlines()
m = file_line_re.match(chunk_lines[0])
file, line, module = m.groups()
failed_example = chunk_lines[2].strip()
expected = chunk_lines[4].strip()
got = chunk_lines[6].strip()
print (file, line, module, failed_example, expected, got)
A:
I wrote a quick parser in pyparsing to do it.
from pyparsing import *
str = """
**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6, 24, 120]
Got:
[1, 1, 2, 6, 24, 120]
**********************************************************************
File "example.py", line 20, in __main__.factorial
Failed example:
factorial(30)
Expected:
25252859812191058636308480000000L
Got:
265252859812191058636308480000000L
**********************************************************************
"""
quote = Literal('"').suppress()
comma = Literal(',').suppress()
in_ = Keyword('in').suppress()
block = OneOrMore("**").suppress() + \
Keyword("File").suppress() + \
quote + Word(alphanums + ".") + quote + \
comma + Keyword("line").suppress() + Word(nums) + comma + \
in_ + Word(alphanums + "._") + \
LineStart() + restOfLine.suppress() + \
LineStart() + restOfLine + \
LineStart() + restOfLine.suppress() + \
LineStart() + restOfLine + \
LineStart() + restOfLine.suppress() + \
LineStart() + restOfLine
all = OneOrMore(Group(block))
result = all.parseString(str)
for section in result:
print section
gives
['example.py', '16', '__main__.factorial', ' [factorial(n) for n in range(6)]', ' [0, 1, 2, 6, 24, 120]', ' [1, 1, 2, 6, 24, 120]']
['example.py', '20', '__main__.factorial', ' factorial(30)', ' 25252859812191058636308480000000L', ' 265252859812191058636308480000000L']
A:
This is probably one of the least elegant python scripts I've ever written, but it should have the framework to do what you want without resorting to UNIX utilities and separate scripts to create the html. It's untested, but it should only need minor tweaking to work.
import os
import sys
#create a list of all files in directory
dirList = os.listdir('')
#Ignore anything that isn't a .txt file.
#
#Read in text, then split it into a list.
for thisFile in dirList:
if thisFile.endswith(".txt"):
infile = open(thisFile,'r')
rawText = infile.read()
yourList = rawText.split('\n')
#Strings
compiledText = ''
htmlText = ''
for i in yourList:
#clunky way of seeing whether or not current line
#should be included in compiledText
if i.startswith("*****"):
compiledText += "\n\n--- New Report ---\n"
if i.startswith("File"):
compiledText += i + '\n'
if i.startswith("Fail"):
compiledText += i + '\n'
if i.startswith("Expe"):
compiledText += i + '\n'
if i.startswith("Got"):
compiledText += i + '\n'
if i.startswith(" "):
compiledText += i + '\n'
#insert your HTML template below
htmlText = '<html>...\n <body> \n '+htmlText+'</body>... </html>'
#write out to file
outfile = open('processed/'+thisFile+'.html','w')
outfile.write(htmlText)
outfile.close()
|
How can I process this text file and parse what I need?
|
I'm trying to parse ouput from the Python doctest module and store it in an HTML file.
I've got output similar to this:
**********************************************************************
File "example.py", line 16, in __main__.factorial
Failed example:
[factorial(n) for n in range(6)]
Expected:
[0, 1, 2, 6, 24, 120]
Got:
[1, 1, 2, 6, 24, 120]
**********************************************************************
File "example.py", line 20, in __main__.factorial
Failed example:
factorial(30)
Expected:
25252859812191058636308480000000L
Got:
265252859812191058636308480000000L
**********************************************************************
1 items had failures:
2 of 8 in __main__.factorial
***Test Failed*** 2 failures.
Each failure is preceded by a line of asterisks, which delimit each test failure from each other.
What I'd like to do is strip out the filename and method that failed, as well as the expected and actual results. Then I'd like to create an HTML document using this (or store it in a text file and then do a second round of parsing).
How can I do this using just Python or some combination of UNIX shell utilities?
EDIT: I formulated the following shell script which matches each block how I'd like,but I'm unsure how to redirect each sed match to its own file.
python example.py | sed -n '/.*/,/^\**$/p' > `mktemp error.XXX`
|
[
"You can write a Python program to pick this apart, but maybe a better thing to do would be to look into modifying doctest to output the report you want in the first place. From the docs for doctest.DocTestRunner:\n ... the display output\ncan be also customized by subclassing DocTestRunner, and\noverriding the methods `report_start`, `report_success`,\n`report_unexpected_exception`, and `report_failure`.\n\n",
"This is a quick and dirty script that parses the output into tuples with the relevant information:\nimport sys\nimport re\n\nstars_re = re.compile('^[*]+$', re.MULTILINE)\nfile_line_re = re.compile(r'^File \"(.*?)\", line (\\d*), in (.*)$')\n\ndoctest_output = sys.stdin.read()\nchunks = stars_re.split(doctest_output)[1:-1]\n\nfor chunk in chunks:\n chunk_lines = chunk.strip().splitlines()\n m = file_line_re.match(chunk_lines[0])\n\n file, line, module = m.groups()\n failed_example = chunk_lines[2].strip()\n expected = chunk_lines[4].strip()\n got = chunk_lines[6].strip()\n\n print (file, line, module, failed_example, expected, got)\n\n",
"I wrote a quick parser in pyparsing to do it.\nfrom pyparsing import *\n\nstr = \"\"\"\n**********************************************************************\nFile \"example.py\", line 16, in __main__.factorial\nFailed example:\n [factorial(n) for n in range(6)]\nExpected:\n [0, 1, 2, 6, 24, 120]\nGot:\n [1, 1, 2, 6, 24, 120]\n**********************************************************************\nFile \"example.py\", line 20, in __main__.factorial\nFailed example:\n factorial(30)\nExpected:\n 25252859812191058636308480000000L\nGot:\n 265252859812191058636308480000000L\n**********************************************************************\n\"\"\"\n\nquote = Literal('\"').suppress()\ncomma = Literal(',').suppress()\nin_ = Keyword('in').suppress()\nblock = OneOrMore(\"**\").suppress() + \\\n Keyword(\"File\").suppress() + \\\n quote + Word(alphanums + \".\") + quote + \\\n comma + Keyword(\"line\").suppress() + Word(nums) + comma + \\\n in_ + Word(alphanums + \"._\") + \\\n LineStart() + restOfLine.suppress() + \\\n LineStart() + restOfLine + \\\n LineStart() + restOfLine.suppress() + \\\n LineStart() + restOfLine + \\\n LineStart() + restOfLine.suppress() + \\\n LineStart() + restOfLine \n\nall = OneOrMore(Group(block))\n\nresult = all.parseString(str)\n\nfor section in result:\n print section\n\ngives\n['example.py', '16', '__main__.factorial', ' [factorial(n) for n in range(6)]', ' [0, 1, 2, 6, 24, 120]', ' [1, 1, 2, 6, 24, 120]']\n['example.py', '20', '__main__.factorial', ' factorial(30)', ' 25252859812191058636308480000000L', ' 265252859812191058636308480000000L']\n\n",
"This is probably one of the least elegant python scripts I've ever written, but it should have the framework to do what you want without resorting to UNIX utilities and separate scripts to create the html. It's untested, but it should only need minor tweaking to work.\nimport os\nimport sys\n\n#create a list of all files in directory\ndirList = os.listdir('')\n\n#Ignore anything that isn't a .txt file.\n#\n#Read in text, then split it into a list.\nfor thisFile in dirList:\n if thisFile.endswith(\".txt\"):\n infile = open(thisFile,'r')\n\n rawText = infile.read()\n\n yourList = rawText.split('\\n')\n\n #Strings\n compiledText = ''\n htmlText = ''\n\n for i in yourList:\n\n #clunky way of seeing whether or not current line \n #should be included in compiledText\n\n if i.startswith(\"*****\"):\n compiledText += \"\\n\\n--- New Report ---\\n\"\n\n if i.startswith(\"File\"):\n compiledText += i + '\\n'\n\n if i.startswith(\"Fail\"):\n compiledText += i + '\\n'\n\n if i.startswith(\"Expe\"):\n compiledText += i + '\\n'\n\n if i.startswith(\"Got\"):\n compiledText += i + '\\n'\n\n if i.startswith(\" \"):\n compiledText += i + '\\n'\n\n\n #insert your HTML template below\n\n htmlText = '<html>...\\n <body> \\n '+htmlText+'</body>... </html>'\n\n\n #write out to file\n outfile = open('processed/'+thisFile+'.html','w')\n outfile.write(htmlText)\n outfile.close()\n\n"
] |
[
4,
1,
1,
0
] |
[] |
[] |
[
"doctest",
"parsing",
"python",
"shell"
] |
stackoverflow_0001246752_doctest_parsing_python_shell.txt
|
Q:
how to include % sign in docutils html template
I want to generate HTML pages with rst2html, using my own templates. these templates include many % signs, like in
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
now, when I call rst2html using the command
rst2html --template=layout2.tpl rst/index.rst > index.html
i get the error
ValueError: unsupported format character '"' (0x22) at index 827
i found out the problem is that rst2html thinks that the %" is a placeholder.
i already tried escaping the % in the template, like
<TABLE border="0" cellpadding="0" cellspacing="0" width="100\%">
but this is not working, the error is the same.
so my question is how i can solve this issue. any help is greatly appreciated!
A:
Have you tried obvious things: escaping the '%' with '%'?
Here is normal string formatting to display a percent sign in the result:
>>> print "%d%%" % 100
100%
Maybe rst2html is the same? (I haven't tried this in rst2html -- I don't have it installed.)
Okay, now I've installed docutils. This works for me:
layout2.tpl:
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%%">
Command line:
C:\Python26\Lib\site-packages>python C:\Python26\Lib\site-packages\docutils-0.5-
py2.6.egg\EGG-INFO\scripts\rst2html.py --template=c:\temp\layout2.tpl
^Z
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
So the result is as desired, I believe.
A:
Doubt it, but maybe the XML command CDATA works.
<![CDATA[
...
]]>
I use it for storing paypal buttons in an XML document and inserting them with PHP.
|
how to include % sign in docutils html template
|
I want to generate HTML pages with rst2html, using my own templates. these templates include many % signs, like in
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
now, when I call rst2html using the command
rst2html --template=layout2.tpl rst/index.rst > index.html
i get the error
ValueError: unsupported format character '"' (0x22) at index 827
i found out the problem is that rst2html thinks that the %" is a placeholder.
i already tried escaping the % in the template, like
<TABLE border="0" cellpadding="0" cellspacing="0" width="100\%">
but this is not working, the error is the same.
so my question is how i can solve this issue. any help is greatly appreciated!
|
[
"Have you tried obvious things: escaping the '%' with '%'? \nHere is normal string formatting to display a percent sign in the result:\n>>> print \"%d%%\" % 100\n100%\n\nMaybe rst2html is the same? (I haven't tried this in rst2html -- I don't have it installed.)\nOkay, now I've installed docutils. This works for me:\nlayout2.tpl:\n<TABLE border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%%\">\n\nCommand line:\nC:\\Python26\\Lib\\site-packages>python C:\\Python26\\Lib\\site-packages\\docutils-0.5-\npy2.6.egg\\EGG-INFO\\scripts\\rst2html.py --template=c:\\temp\\layout2.tpl\n^Z\n<TABLE border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n\nSo the result is as desired, I believe.\n",
"Doubt it, but maybe the XML command CDATA works.\n<![CDATA[\n...\n]]>\n\nI use it for storing paypal buttons in an XML document and inserting them with PHP.\n"
] |
[
7,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001247284_python.txt
|
Q:
Open-source fractal maps
I'm interested in creating a game that uses fractal maps for more realistic geography. However, the only fractal map programs I have found are Windows-only, for example Fractal Mapper. Needless to say, they are also not open-sourced.
Are there any open-sourced fractal map creators available, preferably in Python or C/C++? Ideally I would like something that can be "plugged into" a program, rather then being standalone.
A:
Fracplanet may be of use.
A:
Basic terrain generation involves creating a height map (an image) and rendering it using the pixel colour as height. So you may find image or texture generation code useful. This is a good tutorial.
A:
For the terrain aspect take a look at libnoise.
It's packaged for Debian, and has excellent documentation with a chapter on terrain generation with example C++ code.
Of course there's a lot more to "maps" than slapping some colours on a height field (for example Fracplanet adds rivers and lakes). And the sort of terrain you get from these methods isn't actually that realistic; continents don't generally ramp up from the coast into a rocky hinterland, so maybe simulating continental drift and mountain building and erosion processes would help (alternatively, fake it). And then if you want vegetation, or the artefacts of lifeforms (roads and towns, say) to populate your map you might want to look at cellular automata or other "artificial life" tools. Finally, the Virtual Terrain Project is well worth a browse for more links and ideas.
A:
I'd highly recommend purchasing a copy of
Texturing & Modeling: A Procedural Approach
I see it's now in it's third edition (I only have the second) but it's packed full of useful articles about the use of procedural texturing including several chapters on their use in fractal terrains. It starts out with extensive discussion of noise algorithms too - so you have everything from the basics upwards. The authors include Musgrave, Perlin and Worley, so you really can't do better.
A:
If you want truely realistic geography, you could use NASA's SRTM dataset, perhaps combined with OpenStreetMap features. :-)
A:
A very simple implementation would be to use the midpoint displacement fractal, http://en.wikipedia.org/wiki/Diamond-square_algorithm, or the somewhat more complicated Diamond-Squares algorithm.
http://www.gameprogrammer.com/fractal.html#diamond
These are similar algorithms to the "Difference cloud" in Photoshop.
|
Open-source fractal maps
|
I'm interested in creating a game that uses fractal maps for more realistic geography. However, the only fractal map programs I have found are Windows-only, for example Fractal Mapper. Needless to say, they are also not open-sourced.
Are there any open-sourced fractal map creators available, preferably in Python or C/C++? Ideally I would like something that can be "plugged into" a program, rather then being standalone.
|
[
"Fracplanet may be of use.\n",
"Basic terrain generation involves creating a height map (an image) and rendering it using the pixel colour as height. So you may find image or texture generation code useful. This is a good tutorial.\n",
"For the terrain aspect take a look at libnoise.\nIt's packaged for Debian, and has excellent documentation with a chapter on terrain generation with example C++ code.\nOf course there's a lot more to \"maps\" than slapping some colours on a height field (for example Fracplanet adds rivers and lakes). And the sort of terrain you get from these methods isn't actually that realistic; continents don't generally ramp up from the coast into a rocky hinterland, so maybe simulating continental drift and mountain building and erosion processes would help (alternatively, fake it). And then if you want vegetation, or the artefacts of lifeforms (roads and towns, say) to populate your map you might want to look at cellular automata or other \"artificial life\" tools. Finally, the Virtual Terrain Project is well worth a browse for more links and ideas.\n",
"I'd highly recommend purchasing a copy of \nTexturing & Modeling: A Procedural Approach\nI see it's now in it's third edition (I only have the second) but it's packed full of useful articles about the use of procedural texturing including several chapters on their use in fractal terrains. It starts out with extensive discussion of noise algorithms too - so you have everything from the basics upwards. The authors include Musgrave, Perlin and Worley, so you really can't do better.\n",
"If you want truely realistic geography, you could use NASA's SRTM dataset, perhaps combined with OpenStreetMap features. :-)\n",
"A very simple implementation would be to use the midpoint displacement fractal, http://en.wikipedia.org/wiki/Diamond-square_algorithm, or the somewhat more complicated Diamond-Squares algorithm.\nhttp://www.gameprogrammer.com/fractal.html#diamond\nThese are similar algorithms to the \"Difference cloud\" in Photoshop.\n"
] |
[
9,
4,
1,
1,
0,
0
] |
[] |
[] |
[
"c++",
"fractals",
"maps",
"open_source",
"python"
] |
stackoverflow_0000157211_c++_fractals_maps_open_source_python.txt
|
Q:
Python: StopIteration exception and list comprehensions
I'd like to read at most 20 lines from a csv file:
rows = [csvreader.next() for i in range(20)]
Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.
Is there an elegant way to deal with an iterator that could throw a StopIteration exception in a list comprehension or should I use a regular for loop?
A:
You can use itertools.islice. It is the iterator version of list slicing. If the iterator has less than 20 elements, it will return all elements.
import itertools
rows = list(itertools.islice(csvreader, 20))
A:
itertools.izip (2) provides a way to easily make list comprehensions work, but islice looks to be the way to go in this case.
from itertools import izip
[row for (row,i) in izip(csvreader, range(20))]
|
Python: StopIteration exception and list comprehensions
|
I'd like to read at most 20 lines from a csv file:
rows = [csvreader.next() for i in range(20)]
Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.
Is there an elegant way to deal with an iterator that could throw a StopIteration exception in a list comprehension or should I use a regular for loop?
|
[
"You can use itertools.islice. It is the iterator version of list slicing. If the iterator has less than 20 elements, it will return all elements.\nimport itertools\nrows = list(itertools.islice(csvreader, 20))\n\n",
"itertools.izip (2) provides a way to easily make list comprehensions work, but islice looks to be the way to go in this case.\nfrom itertools import izip\n[row for (row,i) in izip(csvreader, range(20))]\n\n"
] |
[
15,
0
] |
[
"If for whatever reason you need also to keep track of the line number, I'd recommend you:\nrows = zip(xrange(20), csvreader)\n\nIf not, you can strip it out after or... well, you'd better try other option more optimal from the beginning :-)\n"
] |
[
-1
] |
[
"iterator",
"list_comprehension",
"python",
"stopiteration"
] |
stackoverflow_0001106903_iterator_list_comprehension_python_stopiteration.txt
|
Q:
Web Service require Python List as argument. Need to invoke from C#
I need to consume a webservice over XML-RPC. The webservice is written in Python, and one of the arguments is a Python list.
I'm using XML-RPC.NET to invoke all the methods and it works fine, except for those that require a Python list argument.
What would be the corresponding structure in C# which, if I pass as the argument, would be construed by the web service as a Python list? I've tried Python-style code in a string. I've also tried string arrays.
Any example would be really helpful.
Thanks,
V
A:
You need to use arrays of System.Object[]. See http://www.xml-rpc.net/faq/xmlrpcnetfaq.html#1.12 These are generally equivalent to Python lists.
A:
What you need to obtain in the underlying XML is an <array> tag, e.g.
<array>
<data>
<value><i4>12</i4></value>
<value><string>Egypt</string></value>
<value><boolean>0</boolean></value>
<value><i4>-31</i4></value>
</data>
</array>
for Python list
[12, 'Egypt', False, -31]
How you get XML-RPC.NET to emit an <array> tag with a heterogenous "array", I'm not sure. Do you have a way to visualize the XML that's getting emitted for certain C# input constructs/data structures...?
|
Web Service require Python List as argument. Need to invoke from C#
|
I need to consume a webservice over XML-RPC. The webservice is written in Python, and one of the arguments is a Python list.
I'm using XML-RPC.NET to invoke all the methods and it works fine, except for those that require a Python list argument.
What would be the corresponding structure in C# which, if I pass as the argument, would be construed by the web service as a Python list? I've tried Python-style code in a string. I've also tried string arrays.
Any example would be really helpful.
Thanks,
V
|
[
"You need to use arrays of System.Object[]. See http://www.xml-rpc.net/faq/xmlrpcnetfaq.html#1.12 These are generally equivalent to Python lists.\n",
"What you need to obtain in the underlying XML is an <array> tag, e.g.\n<array>\n <data>\n <value><i4>12</i4></value>\n <value><string>Egypt</string></value>\n <value><boolean>0</boolean></value>\n <value><i4>-31</i4></value>\n </data>\n</array>\n\nfor Python list\n[12, 'Egypt', False, -31]\n\nHow you get XML-RPC.NET to emit an <array> tag with a heterogenous \"array\", I'm not sure. Do you have a way to visualize the XML that's getting emitted for certain C# input constructs/data structures...?\n"
] |
[
2,
1
] |
[] |
[] |
[
"c#",
"python",
"xml_rpc"
] |
stackoverflow_0001247638_c#_python_xml_rpc.txt
|
Q:
Finding the domain name of a site that is hotlinking in Google app engine using web2py
Let's say we have an image in the Google App Engine and sites are hotlinking it.
How can I find the domain names of the sites?
My first thought was:
request.client
and then do a reverse lookup but that it's not possible in GAE and would take a lot of time.
I am pretty sure that there is a property that allows me to get the url of the site that is requesting the file
(somewhere in request?). GAE has a Request class but I couldn't make it work inside web2py.
Any ideas?
A:
You can easily get the referrer from the request headers. This referrer can be spoofed, but most people do not spoof it and it is already resolved.
There is no automatic way to resolve the DNS other than manually resolving it. Like you said, a DNS resolution takes extra time and it makes no sense for Web2Py or any other framework to do it.
A:
If you're just looking to find out the domain names (not to block the requests by running a script when the image URL is requested), then they'll be in the request logs. In the admin thingy go to "Logs", select "Requests only" from the drop-down. If you expand "Options" you can filter on the relevant filename.
Then expand each request log entry, and the referer is either a hyphen, or the string in quotes immediately following the 200 (or whatever) status code and the size transferred. Chances are very high that not all of the clients have blocked or spoofed the header, so you'll see the URLs linked from.
You can also download the logs using the SDK, and search/process them locally:
appcfg.py --email=whatever request_logs some_filename
|
Finding the domain name of a site that is hotlinking in Google app engine using web2py
|
Let's say we have an image in the Google App Engine and sites are hotlinking it.
How can I find the domain names of the sites?
My first thought was:
request.client
and then do a reverse lookup but that it's not possible in GAE and would take a lot of time.
I am pretty sure that there is a property that allows me to get the url of the site that is requesting the file
(somewhere in request?). GAE has a Request class but I couldn't make it work inside web2py.
Any ideas?
|
[
"You can easily get the referrer from the request headers. This referrer can be spoofed, but most people do not spoof it and it is already resolved.\nThere is no automatic way to resolve the DNS other than manually resolving it. Like you said, a DNS resolution takes extra time and it makes no sense for Web2Py or any other framework to do it.\n",
"If you're just looking to find out the domain names (not to block the requests by running a script when the image URL is requested), then they'll be in the request logs. In the admin thingy go to \"Logs\", select \"Requests only\" from the drop-down. If you expand \"Options\" you can filter on the relevant filename.\nThen expand each request log entry, and the referer is either a hyphen, or the string in quotes immediately following the 200 (or whatever) status code and the size transferred. Chances are very high that not all of the clients have blocked or spoofed the header, so you'll see the URLs linked from.\nYou can also download the logs using the SDK, and search/process them locally:\nappcfg.py --email=whatever request_logs some_filename\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"google_app_engine",
"python",
"reverse_lookup",
"web2py"
] |
stackoverflow_0001247593_google_app_engine_python_reverse_lookup_web2py.txt
|
Q:
Python - printing out all references to a specific instance
I am investigating garbage collection issues in a Python app. What would be the best readable option to print out all variables referencing a specific instance?
A:
Use the inspect module. This script helps if you just want to track down reference leaks:
http://mg.pov.lt/objgraph.py http://mg.pov.lt/blog/hunting-python-memleaks http://mg.pov.lt/blog/python-object-graphs.html
A:
Try Finding objects' names, it prints all names that reference a given object.
|
Python - printing out all references to a specific instance
|
I am investigating garbage collection issues in a Python app. What would be the best readable option to print out all variables referencing a specific instance?
|
[
"Use the inspect module. This script helps if you just want to track down reference leaks:\nhttp://mg.pov.lt/objgraph.py http://mg.pov.lt/blog/hunting-python-memleaks http://mg.pov.lt/blog/python-object-graphs.html\n",
"Try Finding objects' names, it prints all names that reference a given object.\n"
] |
[
2,
1
] |
[] |
[] |
[
"garbage_collection",
"oop",
"python"
] |
stackoverflow_0001247697_garbage_collection_oop_python.txt
|
Q:
Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers?
I am trying to plot a bunch of data points (many thousands) in Python using matplotlib so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data:
matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black')
Then I can look at it either with pl.show() and then save it. Or directly use plt.savefig('filename.ps') in the code to save it. The problem is this: when I use pl.show() to view the file in the GUI it looks great with small tiny black marks, however when I save from the show() GUI to a file or use directly savefig and then view the ps I created it looks different! Each marker has gained a little blue halo around it (as if it started at each point to connect them with the default blue lines, but did not) and the style is all wrong. Why does it change the style when saved? How do I stop python from forcing the style of the markers? And yes I have looked at some alternative packages like CairoPlot, but I want to keep using matplotlib for now.
Update: It turns out that the save to PNG first makes the colors turn out okay, but it forces a conversion of the image when I want to save it again as a .ps later (for inclusion in a PDF) and then I lose quality. How do I preserve the vector nature of the file and get the right formatting?
A:
For nice-looking vectorized output, don't use the '.' marker style. Use e.g. 'o' (circle) or 's' (square) (see help(plot) for the options) and set the markersize keyword argument to something suitably small, e.g.:
plot(x, y, 'ko', markersize=2)
savefig('foo.ps')
That '.' (point) produces less nice results could be construed as a bug in matplotlib, but then, what should "point" mean in a vector graphic format?
A:
Have you tried the ',' point shape? It creates "pixels" (small dots, instead of shapes).
You can play with the markersize option as well, with this shape?
A:
If you haven't, you should try saving in a rasterizing engine -- save it to a PNG file and see if that fixes it. If you need a vector plot, try saving to PDF and converting with an external utility. I've also had problems before with the PS engine that were resolved by saving with the Agg or PDF engines and converting externally.
|
Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers?
|
I am trying to plot a bunch of data points (many thousands) in Python using matplotlib so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data:
matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black')
Then I can look at it either with pl.show() and then save it. Or directly use plt.savefig('filename.ps') in the code to save it. The problem is this: when I use pl.show() to view the file in the GUI it looks great with small tiny black marks, however when I save from the show() GUI to a file or use directly savefig and then view the ps I created it looks different! Each marker has gained a little blue halo around it (as if it started at each point to connect them with the default blue lines, but did not) and the style is all wrong. Why does it change the style when saved? How do I stop python from forcing the style of the markers? And yes I have looked at some alternative packages like CairoPlot, but I want to keep using matplotlib for now.
Update: It turns out that the save to PNG first makes the colors turn out okay, but it forces a conversion of the image when I want to save it again as a .ps later (for inclusion in a PDF) and then I lose quality. How do I preserve the vector nature of the file and get the right formatting?
|
[
"For nice-looking vectorized output, don't use the '.' marker style. Use e.g. 'o' (circle) or 's' (square) (see help(plot) for the options) and set the markersize keyword argument to something suitably small, e.g.:\nplot(x, y, 'ko', markersize=2)\nsavefig('foo.ps')\n\nThat '.' (point) produces less nice results could be construed as a bug in matplotlib, but then, what should \"point\" mean in a vector graphic format?\n",
"Have you tried the ',' point shape? It creates \"pixels\" (small dots, instead of shapes).\nYou can play with the markersize option as well, with this shape?\n",
"If you haven't, you should try saving in a rasterizing engine -- save it to a PNG file and see if that fixes it. If you need a vector plot, try saving to PDF and converting with an external utility. I've also had problems before with the PS engine that were resolved by saving with the Agg or PDF engines and converting externally.\n"
] |
[
20,
10,
2
] |
[] |
[] |
[
"coding_style",
"matplotlib",
"python"
] |
stackoverflow_0000544542_coding_style_matplotlib_python.txt
|
Q:
django extreme slowness
I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow.
Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very slow (12+ seconds on a quad core..)
I've tried many solution found on the net for similar problem, but they don't seem related to me.
The problem doesn't seem to come from Django's development server since the request are also very slow on the production server with apache and mod_python.
Then I thought it might be a DNS issue, but the site loads instantly when served with Apache2.
I tried to strace the development server, but I didn't find anything interesting.
Even commenting all the apps (except django apps) didn't change anything.. models still take age to validate.
I really don't know where I should be looking now ..
Anybody has an idea ?
A:
I've posted this question on serverfault maybe it will help you.
If you are serving big static files - those will slow down response.
This will be the case in any mode if your mod_python or development server process big static files like images, client scripts, etc.
You want to configure the production server to handle those files directly - i.e. bypassing the modules.
btw, mod_wsgi is nowadays the preferred way to run django in the production environment.
If you have issues with system services or hardware then you might get some clues from log messages.
A:
Then I thought it might be a DNS
issue, but the site loads instantly
when served with Apache2.
How are you serving your Django site? I presume you're running mod_python on Apache2?
You may want to start by running an Apache2 locally on you computer (use MAMP or WAMP and install mod_python there) and seeing if it's still slow. Then you can tell whether it's a django/python issue or an Apache/mod_python issue
A:
I've once used remote edit to develop my Django site. The validating process seem to be very slow too. But, everything else is fine not like yours.
It's come from the webserver can't add/change .pyc in that directory.
A:
If the validating models takes forever don't search for anything else. On a dual core some of my largest enterprise applications (+30 models) take less then a second to validate.
The problem must lie somewhere with your models but without source code it's hard to tell what the problem is.
Kind regards,
Michael
Open Source Consultant
|
django extreme slowness
|
I have a slowness problem with Django and I can't find the source .. I'm not sure what I'm doing wrong, but at least twice while working on projects Django became really slow.
Requests takes age to complete (~15 seconds) and Validating model when starting the development server is also very slow (12+ seconds on a quad core..)
I've tried many solution found on the net for similar problem, but they don't seem related to me.
The problem doesn't seem to come from Django's development server since the request are also very slow on the production server with apache and mod_python.
Then I thought it might be a DNS issue, but the site loads instantly when served with Apache2.
I tried to strace the development server, but I didn't find anything interesting.
Even commenting all the apps (except django apps) didn't change anything.. models still take age to validate.
I really don't know where I should be looking now ..
Anybody has an idea ?
|
[
"I've posted this question on serverfault maybe it will help you. \nIf you are serving big static files - those will slow down response.\nThis will be the case in any mode if your mod_python or development server process big static files like images, client scripts, etc.\nYou want to configure the production server to handle those files directly - i.e. bypassing the modules.\nbtw, mod_wsgi is nowadays the preferred way to run django in the production environment.\nIf you have issues with system services or hardware then you might get some clues from log messages. \n",
"\nThen I thought it might be a DNS\n issue, but the site loads instantly\n when served with Apache2.\n\nHow are you serving your Django site? I presume you're running mod_python on Apache2? \nYou may want to start by running an Apache2 locally on you computer (use MAMP or WAMP and install mod_python there) and seeing if it's still slow. Then you can tell whether it's a django/python issue or an Apache/mod_python issue\n",
"I've once used remote edit to develop my Django site. The validating process seem to be very slow too. But, everything else is fine not like yours. \nIt's come from the webserver can't add/change .pyc in that directory.\n",
"If the validating models takes forever don't search for anything else. On a dual core some of my largest enterprise applications (+30 models) take less then a second to validate.\nThe problem must lie somewhere with your models but without source code it's hard to tell what the problem is.\nKind regards,\nMichael\nOpen Source Consultant\n"
] |
[
6,
0,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001247501_django_python.txt
|
Q:
django binary (no source code) deployment
is there possible only to deploy binary version of web application based on django , no source code publish?
Thanks
A:
Oh, again that old one... Simply stated, you can't deploy an application in a non-compiled language (Python, Perl, PHP, Ruby...) in a source-safe way - all existing tricks are extremely easy to circumvent. Anyway, that doesn't matter at all: the contract you have with your customer does. Even for Java there are neat decompilers.
If your customer wants to redeploy by hand your application on another machine, he could anyway even if the application was in C. Unless you wrote a dongle-protected anti-piracy scheme? Come on. You have to build a relation with your client. This is a social, commercial and legal problem that can't be solved with a technical stunt.
A:
Yes, you can, sort of.
Have a read of http://effbot.org/zone/python-compile.htm - that should answer your question!
A:
No, there isn't a reliable to do this at the moment. Even compiled code like referenced in the answer above this one isn't 100% secure.
My advice: clean open code for your clients and a good relation with them is the only way to go. Keeping your code hidden can be good from a business point of view but from a client relation point of view it's a real show stopper. Advertise: "Our code is open!", which doesn't mean your clients can do anything they want with it.
|
django binary (no source code) deployment
|
is there possible only to deploy binary version of web application based on django , no source code publish?
Thanks
|
[
"Oh, again that old one... Simply stated, you can't deploy an application in a non-compiled language (Python, Perl, PHP, Ruby...) in a source-safe way - all existing tricks are extremely easy to circumvent. Anyway, that doesn't matter at all: the contract you have with your customer does. Even for Java there are neat decompilers.\nIf your customer wants to redeploy by hand your application on another machine, he could anyway even if the application was in C. Unless you wrote a dongle-protected anti-piracy scheme? Come on. You have to build a relation with your client. This is a social, commercial and legal problem that can't be solved with a technical stunt.\n",
"Yes, you can, sort of.\nHave a read of http://effbot.org/zone/python-compile.htm - that should answer your question!\n",
"No, there isn't a reliable to do this at the moment. Even compiled code like referenced in the answer above this one isn't 100% secure.\nMy advice: clean open code for your clients and a good relation with them is the only way to go. Keeping your code hidden can be good from a business point of view but from a client relation point of view it's a real show stopper. Advertise: \"Our code is open!\", which doesn't mean your clients can do anything they want with it.\n"
] |
[
14,
5,
3
] |
[] |
[] |
[
"binary",
"django",
"python"
] |
stackoverflow_0001241813_binary_django_python.txt
|
Q:
Using Cheetah Templating system with windows and python 2.6.1 (namemapper problem)
So I am trying to use the Cheetah templating engine in conjunction with the Django web framework, and that is actually working fine. I did some simple tests with that and I was able to render pages and whatnot.
However, problems arise whenever doing anything other than using very simple variable/attribute/methods in the Cheetah templates. It gets mad and says:
You don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with the compiled C version of NameMapper. "\nYou don't have the C version of NameMapper installed! "
And then it will be unable to find whatever attribute or method I was trying to call inside the Cheetah template.
I attempted to download the C version of Namemapper and install it, but I wasn't sure how to 'install' a .pyd file (when I looked up '.pyd' files on the web it said they are just dynamic python modules that can be used with an import statement). Additionally, the Cheetah website only has C versions of Namemapper for python 2.4 and 2.5, while I am using python 2.6.1, so that is probably an issue as well.
Does anyone have a solution for this? Thanks.
A:
I have compiled the PYD file for Python 2.6 as well as Windows installers that have it bundled in, so that users don't have to figure out where to drop the PYD on Windows.
Installers: http://feisley.com/python/cheetah/ (pyd files are in the /pyd folder)
Hope this helps!
|
Using Cheetah Templating system with windows and python 2.6.1 (namemapper problem)
|
So I am trying to use the Cheetah templating engine in conjunction with the Django web framework, and that is actually working fine. I did some simple tests with that and I was able to render pages and whatnot.
However, problems arise whenever doing anything other than using very simple variable/attribute/methods in the Cheetah templates. It gets mad and says:
You don't have the C version of NameMapper installed! I'm disabling Cheetah's useStackFrames option as it is painfully slow with the Python version of NameMapper. You should get a copy of Cheetah with the compiled C version of NameMapper. "\nYou don't have the C version of NameMapper installed! "
And then it will be unable to find whatever attribute or method I was trying to call inside the Cheetah template.
I attempted to download the C version of Namemapper and install it, but I wasn't sure how to 'install' a .pyd file (when I looked up '.pyd' files on the web it said they are just dynamic python modules that can be used with an import statement). Additionally, the Cheetah website only has C versions of Namemapper for python 2.4 and 2.5, while I am using python 2.6.1, so that is probably an issue as well.
Does anyone have a solution for this? Thanks.
|
[
"I have compiled the PYD file for Python 2.6 as well as Windows installers that have it bundled in, so that users don't have to figure out where to drop the PYD on Windows.\nInstallers: http://feisley.com/python/cheetah/ (pyd files are in the /pyd folder)\nHope this helps!\n"
] |
[
6
] |
[] |
[] |
[
"cheetah",
"django",
"python",
"template_engine",
"windows"
] |
stackoverflow_0001155065_cheetah_django_python_template_engine_windows.txt
|
Q:
Dropping the Unicode markers in Html output
I have a python list which holds a few email ids accepted as unicode strings:
[u'[email protected]',u'[email protected]',u'[email protected]']
This is assigned to values['Emails'] and values is passed to render as html.
The Html renders as this:
Emails: [u'[email protected]',u'[email protected]',u'[email protected]']
I would like it to look like this:
Emails: [ [email protected], [email protected], [email protected] ]
How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?
A:
In Python:
'[%s]' % ', '.join(pythonlistwithemails)
In bare HTML it is impossible... you'd have to use javascript.
A:
I don't know any Python, but if those u-markers and the single quotes show, doesn't that actually indicate that you're accessing the list members in the wrong way?
You're printing the whole list rather than each item, and the output looks like debug information to me. Such debug information could very well look different in another version or configuration of Python. So, though I don't know Python, I'd say: you should NOT try to parse that.
Using liori's answer does not actually drop the u-markers, but ensures the items from the list are accessed individually, which gives you the true value rather than some debug information. You could also use some loop to achieve the same (though the join makes the code a lot easier).
A:
"[{0}]".format(", ".join(python_email_list))
From Python 2.6 format() method is the preferred way of string formatting.
Docs here.
A:
It all depends how the HTML generation is treating your values array. Here is what you usually do to serialize a unicode string:
In [550]: ss=u'[email protected]'
In [551]: print ss # uses str() implicitly
Out[552]: [email protected]
In [552]: str(ss)
Out[552]: '[email protected]'
In [553]: repr(ss)
Out[553]: "u'[email protected]'"
If you are confident values only contains ASCII character strings, just use str() on the values. If you are unsure, use an explicit encoding like
ss.encode('ascii', error='replace')
A:
In the template
[ {{ email_list|join:", " }} ]
note: the [, and ] are literal square brackets, not code :)
A:
Option 1:
myStr = str('[ ' + ', '.join(ss) + ' ]')
Option 2:
myStr = '[ ' + ', '.join(ss) + ' ]'
myStr = myStr.encode(<whatever encoding you want>, <whatever way of handling errors you wish to use>)
I'm not used to Python pre-version 3, so I'm not really sure whether the additional strings need a u prefix or if it's an implicit conversion.
A:
This is actually a long and formatted comment on the last answer. Still not knowing any Python, I am a bit disappointed by not using join to get commas between each address (like suggested by liori). Replacing the comma with some space feels like walking away from the problem, and is not going to learn anyone anything. We don't sacrifice quality here at Stack Overflow! ;-)
I just typed the following on my Mac:
$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> lst = [ u'[email protected]', u'[email protected]', u'[email protected]' ]
>>> print lst
[u'[email protected]', u'[email protected]', u'[email protected]']
>>> print ', '.join(lst)
[email protected], [email protected], [email protected]
>>> print 'Emails: [%s]' % ', '.join(lst)
Emails: [[email protected], [email protected], [email protected]]
>>> lst = [ u'[email protected]' ]
>>> print lst
[u'[email protected]']
>>> print ', '.join(lst)
[email protected]
>>> print 'Emails: [%s]' % ', '.join(lst)
Emails: [[email protected]]
>>> s = u'[email protected]'
>>> print s
[email protected]
>>> print ', '.join(s)
o, n, e, @, e, x, a, m, p, l, e, ., c, o, m
Makes perfect sense to me... Now, using a different separator for the last item (like [email protected], [email protected] and [email protected]) will need some more work, but printing the very same separator between each item should not be complicated at all.
A:
The easiest way for you to do it would be to iterate over your email list. e.g.
{% for email in Emails %}
email,
{% endfor %}
This way you (or a designer) will have a lot more control of the layout.
Have a look at the template documentation for more details.
|
Dropping the Unicode markers in Html output
|
I have a python list which holds a few email ids accepted as unicode strings:
[u'[email protected]',u'[email protected]',u'[email protected]']
This is assigned to values['Emails'] and values is passed to render as html.
The Html renders as this:
Emails: [u'[email protected]',u'[email protected]',u'[email protected]']
I would like it to look like this:
Emails: [ [email protected], [email protected], [email protected] ]
How can I do this in the server script?
Is there a simple way to achieve this in the HTML itself?
|
[
"In Python:\n'[%s]' % ', '.join(pythonlistwithemails)\n\nIn bare HTML it is impossible... you'd have to use javascript.\n",
"I don't know any Python, but if those u-markers and the single quotes show, doesn't that actually indicate that you're accessing the list members in the wrong way? \nYou're printing the whole list rather than each item, and the output looks like debug information to me. Such debug information could very well look different in another version or configuration of Python. So, though I don't know Python, I'd say: you should NOT try to parse that.\nUsing liori's answer does not actually drop the u-markers, but ensures the items from the list are accessed individually, which gives you the true value rather than some debug information. You could also use some loop to achieve the same (though the join makes the code a lot easier).\n",
"\"[{0}]\".format(\", \".join(python_email_list))\n\nFrom Python 2.6 format() method is the preferred way of string formatting.\nDocs here.\n",
"It all depends how the HTML generation is treating your values array. Here is what you usually do to serialize a unicode string:\nIn [550]: ss=u'[email protected]'\n\nIn [551]: print ss # uses str() implicitly\nOut[552]: [email protected]\n\nIn [552]: str(ss)\nOut[552]: '[email protected]'\n\nIn [553]: repr(ss)\nOut[553]: \"u'[email protected]'\"\n\nIf you are confident values only contains ASCII character strings, just use str() on the values. If you are unsure, use an explicit encoding like\nss.encode('ascii', error='replace')\n\n",
"In the template\n[ {{ email_list|join:\", \" }} ]\n\nnote: the [, and ] are literal square brackets, not code :)\n",
"Option 1:\nmyStr = str('[ ' + ', '.join(ss) + ' ]')\n\nOption 2:\nmyStr = '[ ' + ', '.join(ss) + ' ]'\nmyStr = myStr.encode(<whatever encoding you want>, <whatever way of handling errors you wish to use>)\n\nI'm not used to Python pre-version 3, so I'm not really sure whether the additional strings need a u prefix or if it's an implicit conversion.\n",
"This is actually a long and formatted comment on the last answer. Still not knowing any Python, I am a bit disappointed by not using join to get commas between each address (like suggested by liori). Replacing the comma with some space feels like walking away from the problem, and is not going to learn anyone anything. We don't sacrifice quality here at Stack Overflow! ;-)\nI just typed the following on my Mac:\n$ python\nPython 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n\n>>> lst = [ u'[email protected]', u'[email protected]', u'[email protected]' ]\n>>> print lst\n[u'[email protected]', u'[email protected]', u'[email protected]']\n\n>>> print ', '.join(lst)\[email protected], [email protected], [email protected]\n\n>>> print 'Emails: [%s]' % ', '.join(lst)\nEmails: [[email protected], [email protected], [email protected]]\n\n>>> lst = [ u'[email protected]' ]\n>>> print lst\n[u'[email protected]']\n\n>>> print ', '.join(lst)\[email protected]\n\n>>> print 'Emails: [%s]' % ', '.join(lst)\nEmails: [[email protected]]\n\n>>> s = u'[email protected]'\n>>> print s\[email protected]\n\n>>> print ', '.join(s)\no, n, e, @, e, x, a, m, p, l, e, ., c, o, m\nMakes perfect sense to me... Now, using a different separator for the last item (like [email protected], [email protected] and [email protected]) will need some more work, but printing the very same separator between each item should not be complicated at all.\n",
"The easiest way for you to do it would be to iterate over your email list. e.g. \n{% for email in Emails %}\nemail,\n{% endfor %}\n\nThis way you (or a designer) will have a lot more control of the layout.\nHave a look at the template documentation for more details.\n"
] |
[
4,
2,
2,
1,
1,
0,
0,
-1
] |
[] |
[] |
[
"django",
"html",
"html_lists",
"python",
"unicode"
] |
stackoverflow_0001222508_django_html_html_lists_python_unicode.txt
|
Q:
What does the "s!" operator in Perl do?
I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.
$var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
What is each line doing? I'd like to know in case I run into this operator again.
And, what would equivalent statements in Python be?
A:
s!foo!bar! is the same as the more common s/foo/bar/, except that foo and bar can contain unescaped slashes without causing problems. What it does is, it replaces the first occurence of the regex foo with bar. The version with g replaces all occurences.
A:
It's doing exactly the same as $var =~ s///. i.e. performing a search and replace within the $var variable.
In Perl you can define the delimiting character following the s. Why ? So, for example, if you're matching '/', you can specify another delimiting character ('!' in this case) and not have to escape or backtick the character you're matching. Otherwise you'd end up with (say)
s/;/\//g;
which is a little more confusing.
Perlre has more info on this.
A:
Perl lets you choose the delimiter for many of its constructs. This makes it easier to see what is going on in expressions like
$str =~ s{/foo/bar/baz/}{/quux/};
As you can see though, not all delimiters have the same effects. Bracketing characters (<>, [], {}, and ()) use different characters for the beginning and ending. And ?, when used as a delimiter to a regex, causes the regexes to match only once between calls to the reset() operator.
You may find it helpful to read perldoc perlop (in particular the sections on m/PATTERN/msixpogc, ?PATTERN?, and s/PATTERN/REPLACEMENT/msixpogce).
A:
s is the substitution operator. Normally this uses '/' for the delimiter:
s/foo/bar/
, but this is not required: a number of other characters can be used as delimiters instead. In this case, '!' has been used as the delimiter, presumably to avoid the need to escape the '/' characters in the actual text to be substituted.
In your specific case, the first line removes text matching '.+?'; i.e. it removes 'foo' tags with or without content.
The second line replaces all ';' characters with '/' characters, globally (all occurences).
The python equivalent code uses the re module:
f=re.sub(searchregx,replacement_str,line)
A:
s is the substitution operator. Usually it is in the form of s/foo/bar/, but you can replace // separator characters some other characters like !. Using other separator charaters may make working with things like paths a lot easier since you don't need to escape path separators.
See manual page for further info.
You can find similar functionality for python in re-module.
A:
s! is syntactic sugar for the 'proper' s/// operator. Basically, you can substitute whatever delimiter you want instead of the '/'s.
As to what each line is doing, the first line is matching occurances of the regex <foo>.+?</foo> and replacing the whole lot with nothing. The second is matching the regex ; and replacing it with /.
s/// is the substitute operator. It takes a regular expression and a substitution string.
s/regex/replace string/;
It supports most (all?) of the normal regular expression switches, which are used in the normal way (by appending them to the end of the operator).
A:
And the python equivalent is to use the re module.
|
What does the "s!" operator in Perl do?
|
I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.
$var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
What is each line doing? I'd like to know in case I run into this operator again.
And, what would equivalent statements in Python be?
|
[
"s!foo!bar! is the same as the more common s/foo/bar/, except that foo and bar can contain unescaped slashes without causing problems. What it does is, it replaces the first occurence of the regex foo with bar. The version with g replaces all occurences.\n",
"It's doing exactly the same as $var =~ s///. i.e. performing a search and replace within the $var variable.\nIn Perl you can define the delimiting character following the s. Why ? So, for example, if you're matching '/', you can specify another delimiting character ('!' in this case) and not have to escape or backtick the character you're matching. Otherwise you'd end up with (say)\ns/;/\\//g;\n\nwhich is a little more confusing.\nPerlre has more info on this.\n",
"Perl lets you choose the delimiter for many of its constructs. This makes it easier to see what is going on in expressions like\n$str =~ s{/foo/bar/baz/}{/quux/};\n\nAs you can see though, not all delimiters have the same effects. Bracketing characters (<>, [], {}, and ()) use different characters for the beginning and ending. And ?, when used as a delimiter to a regex, causes the regexes to match only once between calls to the reset() operator.\nYou may find it helpful to read perldoc perlop (in particular the sections on m/PATTERN/msixpogc, ?PATTERN?, and s/PATTERN/REPLACEMENT/msixpogce).\n",
"s is the substitution operator. Normally this uses '/' for the delimiter:\ns/foo/bar/\n\n, but this is not required: a number of other characters can be used as delimiters instead. In this case, '!' has been used as the delimiter, presumably to avoid the need to escape the '/' characters in the actual text to be substituted.\nIn your specific case, the first line removes text matching '.+?'; i.e. it removes 'foo' tags with or without content.\nThe second line replaces all ';' characters with '/' characters, globally (all occurences).\nThe python equivalent code uses the re module:\nf=re.sub(searchregx,replacement_str,line)\n\n",
"s is the substitution operator. Usually it is in the form of s/foo/bar/, but you can replace // separator characters some other characters like !. Using other separator charaters may make working with things like paths a lot easier since you don't need to escape path separators.\nSee manual page for further info.\nYou can find similar functionality for python in re-module.\n",
"s! is syntactic sugar for the 'proper' s/// operator. Basically, you can substitute whatever delimiter you want instead of the '/'s.\nAs to what each line is doing, the first line is matching occurances of the regex <foo>.+?</foo> and replacing the whole lot with nothing. The second is matching the regex ; and replacing it with /.\ns/// is the substitute operator. It takes a regular expression and a substitution string.\ns/regex/replace string/;\n\nIt supports most (all?) of the normal regular expression switches, which are used in the normal way (by appending them to the end of the operator).\n",
"And the python equivalent is to use the re module.\n"
] |
[
15,
13,
10,
3,
3,
3,
0
] |
[] |
[] |
[
"perl",
"python",
"regex"
] |
stackoverflow_0001248812_perl_python_regex.txt
|
Q:
Recursive? looping to n levels in Python
Working in python I want to extract a dataset with the following structure:
Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the potential to go on for infinity, in reality a depth of 10 levels is unusual, as is having more than 10 siblings at each level.
For each item in the dataset I want to show show all items for which this item is their parent... and so on until it reaches the bottom of the dataset.
Doing the first two levels is easy, but I'm unsure how to make it efficiently recurs down through the levels.
Any pointers very much appreciated.
A:
Are you saying that each item only maintains a reference to its parents? If so, then how about
def getChildren(item) :
children = []
for possibleChild in allItems :
if (possibleChild.parent == item) :
children.extend(getChildren(possibleChild))
return children
This returns a list that contains all items who are in some way descended from item.
A:
If you want to keep the structure of your dataset, this will produce a list of the format [id, [children of id], id2, [children of id2]]
def children(id):
return [id]+[children(x.id) for x in filter(lambda x:x.parent == id, items)]
A:
you should probably use a defaultdictionary for this:
from collections import defaultdict
itemdict = defaultdict(list)
for id, parent_id in itemlist:
itemdict[parent_id].append(id)
then you can recursively print it (with indentation) like
def printitem(id, depth=0):
print ' '*depth, id
for child in itemdict[id]:
printitem(child, depth+1)
A:
How about something like this,
#!/usr/bin/python
tree = { 0:(None, [1,2,3]),
1:(0, [4]),
2:(0, []),
3:(0, [5,6]),
4:(1, [7]),
5:(3, []),
6:(3, []),
7:(4, []),
}
def find_children( tree, id ):
print "node:", id, tree[id]
for child in tree[id][1]:
find_children( tree, child )
if __name__=="__main__":
import sys
find_children( tree, int(sys.argv[1]) )
$ ./tree.py 3
node: 3 (0, [5, 6])
node: 5 (3, [])
node: 6 (3, [])
It's also worth noting that python has a pretty low default recursion limit, 1000 I think.
In the event that your tree actually gets pretty deep you'll hit this very quickly.
You can crank this up with,
sys.setrecursionlimit(100000)
and check it with,
sys.getrecursionlimit()
|
Recursive? looping to n levels in Python
|
Working in python I want to extract a dataset with the following structure:
Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the potential to go on for infinity, in reality a depth of 10 levels is unusual, as is having more than 10 siblings at each level.
For each item in the dataset I want to show show all items for which this item is their parent... and so on until it reaches the bottom of the dataset.
Doing the first two levels is easy, but I'm unsure how to make it efficiently recurs down through the levels.
Any pointers very much appreciated.
|
[
"Are you saying that each item only maintains a reference to its parents? If so, then how about\ndef getChildren(item) :\n children = []\n for possibleChild in allItems :\n if (possibleChild.parent == item) :\n children.extend(getChildren(possibleChild))\n return children\n\nThis returns a list that contains all items who are in some way descended from item.\n",
"If you want to keep the structure of your dataset, this will produce a list of the format [id, [children of id], id2, [children of id2]]\ndef children(id): \n return [id]+[children(x.id) for x in filter(lambda x:x.parent == id, items)]\n\n",
"you should probably use a defaultdictionary for this:\nfrom collections import defaultdict \n\nitemdict = defaultdict(list)\nfor id, parent_id in itemlist:\n itemdict[parent_id].append(id)\n\nthen you can recursively print it (with indentation) like\ndef printitem(id, depth=0):\n print ' '*depth, id\n for child in itemdict[id]:\n printitem(child, depth+1)\n\n",
"How about something like this,\n\n#!/usr/bin/python \n\ntree = { 0:(None, [1,2,3]),\n 1:(0, [4]),\n 2:(0, []),\n 3:(0, [5,6]),\n 4:(1, [7]),\n 5:(3, []),\n 6:(3, []),\n 7:(4, []),\n }\n\ndef find_children( tree, id ):\n print \"node:\", id, tree[id]\n for child in tree[id][1]:\n find_children( tree, child )\n\nif __name__==\"__main__\":\n import sys\n find_children( tree, int(sys.argv[1]) )\n\n$ ./tree.py 3\nnode: 3 (0, [5, 6])\nnode: 5 (3, [])\nnode: 6 (3, [])\n\nIt's also worth noting that python has a pretty low default recursion limit, 1000 I think.\nIn the event that your tree actually gets pretty deep you'll hit this very quickly. \nYou can crank this up with, \n\nsys.setrecursionlimit(100000)\n\nand check it with,\n\nsys.getrecursionlimit()\n\n"
] |
[
1,
1,
1,
0
] |
[] |
[] |
[
"python",
"recursion"
] |
stackoverflow_0001247133_python_recursion.txt
|
Q:
Store data series in file or database if I want to do row level math operations?
I'm developing an app that handle sets of financial series data (input as csv or open document), one set could be say 10's x 1000's up to double precision numbers (Simplifying, but thats what matters).
I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input. This will be between columns (row level operations) on one set and also between columns on many (potentially all) sets at the row level also. I plan to write it in Python and it will eventually need a intranet facing interface to display the results/graphs etc. for now, csv output based on some input parameters will suffice.
What is the best way to store the data and manipulate? So far I see my choices as being either (1) to write csv files to disk and trawl through them to do the math or (2) I could put them into a database and rely on the database to handle the math. My main concern is speed/performance as the number of datasets grows as there will be inter-dataset row level math that needs to be done.
-Has anyone had experience going down either path and what are the pitfalls/gotchas that I should be aware of?
-What are the reasons why one should be chosen over another?
-Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design?
-Is there any project or framework out there to help with this type of task?
-Edit-
More info:
The rows will all read all in order, BUT I may need to do some resampling/interpolation to match the differing input lengths as well as differing timestamps for each row. Since each dataset will always have a differing length that is not fixed, I'll have some scratch table/memory somewhere to hold the interpolated/resampled versions. I'm not sure if it makes more sense to try to store this (and try to upsample/interploate to a common higher length) or just regenerate it each time its needed.
A:
"I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input."
This is the standard use case for a data warehouse star-schema design. Buy Kimball's The Data Warehouse Toolkit. Read (and understand) the star schema before doing anything else.
"What is the best way to store the data and manipulate?"
A Star Schema.
You can implement this as flat files (CSV is fine) or RDBMS. If you use flat files, you write simple loops to do the math. If you use an RDBMS you write simple SQL and simple loops.
"My main concern is speed/performance as the number of datasets grows"
Nothing is as fast as a flat file. Period. RDBMS is slower.
The RDBMS value proposition stems from SQL being a relatively simple way to specify SELECT SUM(), COUNT() FROM fact JOIN dimension WHERE filter GROUP BY dimension attribute. Python isn't as terse as SQL, but it's just as fast and just as flexible. Python competes against SQL.
"pitfalls/gotchas that I should be aware of?"
DB design. If you don't get the star schema and how to separate facts from dimensions, all approaches are doomed. Once you separate facts from dimensions, all approaches are approximately equal.
"What are the reasons why one should be chosen over another?"
RDBMS slow and flexible. Flat files fast and (sometimes) less flexible. Python levels the playing field.
"Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design?"
Star Schema: central fact table surrounded by dimension tables. Nothing beats it.
"Is there any project or framework out there to help with this type of task?"
Not really.
A:
For speed optimization, I would suggest two other avenues of investigation beyond changing your underlying storage mechanism:
1) Use an intermediate data structure.
If maximizing speed is more important than minimizing memory usage, you may get good results out of using a different data structure as the basis of your calculations, rather than focusing on the underlying storage mechanism. This is a strategy that, in practice, has reduced runtime in projects I've worked on dramatically, regardless of whether the data was stored in a database or text (in my case, XML).
While sums and averages will require runtime in only O(n), more complex calculations could easily push that into O(n^2) without applying this strategy. O(n^2) would be a performance hit that would likely have far more of a perceived speed impact than whether you're reading from CSV or a database. An example case would be if your data rows reference other data rows, and there's a need to aggregate data based on those references.
So if you find yourself doing calculations more complex than a sum or an average, you might explore data structures that can be created in O(n) and would keep your calculation operations in O(n) or better. As Martin pointed out, it sounds like your whole data sets can be held in memory comfortably, so this may yield some big wins. What kind of data structure you'd create would be dependent on the nature of the calculation you're doing.
2) Pre-cache.
Depending on how the data is to be used, you could store the calculated values ahead of time. As soon as the data is produced/loaded, perform your sums, averages, etc., and store those aggregations alongside your original data, or hold them in memory as long as your program runs. If this strategy is applicable to your project (i.e. if the users aren't coming up with unforeseen calculation requests on the fly), reading the data shouldn't be prohibitively long-running, whether the data comes from text or a database.
A:
Are you likely to need all rows in order or will you want only specific known rows?
If you need to read all the data there isn't much advantage to having it in a database.
edit: If the code fits in memory then a simple CSV is fine. Plain text data formats are always easier to deal with than opaque ones if you can use them.
A:
What matters most if all data will fit simultaneously into memory. From the size that you give, it seems that this is easily the case (a few megabytes at worst).
If so, I would discourage using a relational database, and do all operations directly in Python. Depending on what other processing you need, I would probably rather use binary pickles, than CSV.
|
Store data series in file or database if I want to do row level math operations?
|
I'm developing an app that handle sets of financial series data (input as csv or open document), one set could be say 10's x 1000's up to double precision numbers (Simplifying, but thats what matters).
I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input. This will be between columns (row level operations) on one set and also between columns on many (potentially all) sets at the row level also. I plan to write it in Python and it will eventually need a intranet facing interface to display the results/graphs etc. for now, csv output based on some input parameters will suffice.
What is the best way to store the data and manipulate? So far I see my choices as being either (1) to write csv files to disk and trawl through them to do the math or (2) I could put them into a database and rely on the database to handle the math. My main concern is speed/performance as the number of datasets grows as there will be inter-dataset row level math that needs to be done.
-Has anyone had experience going down either path and what are the pitfalls/gotchas that I should be aware of?
-What are the reasons why one should be chosen over another?
-Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design?
-Is there any project or framework out there to help with this type of task?
-Edit-
More info:
The rows will all read all in order, BUT I may need to do some resampling/interpolation to match the differing input lengths as well as differing timestamps for each row. Since each dataset will always have a differing length that is not fixed, I'll have some scratch table/memory somewhere to hold the interpolated/resampled versions. I'm not sure if it makes more sense to try to store this (and try to upsample/interploate to a common higher length) or just regenerate it each time its needed.
|
[
"\"I plan to do operations on that data (eg. sum, difference, averages etc.) as well including generation of say another column based on computations on the input.\"\nThis is the standard use case for a data warehouse star-schema design. Buy Kimball's The Data Warehouse Toolkit. Read (and understand) the star schema before doing anything else.\n\"What is the best way to store the data and manipulate?\" \nA Star Schema.\nYou can implement this as flat files (CSV is fine) or RDBMS. If you use flat files, you write simple loops to do the math. If you use an RDBMS you write simple SQL and simple loops. \n\"My main concern is speed/performance as the number of datasets grows\" \nNothing is as fast as a flat file. Period. RDBMS is slower. \nThe RDBMS value proposition stems from SQL being a relatively simple way to specify SELECT SUM(), COUNT() FROM fact JOIN dimension WHERE filter GROUP BY dimension attribute. Python isn't as terse as SQL, but it's just as fast and just as flexible. Python competes against SQL.\n\"pitfalls/gotchas that I should be aware of?\"\nDB design. If you don't get the star schema and how to separate facts from dimensions, all approaches are doomed. Once you separate facts from dimensions, all approaches are approximately equal.\n\"What are the reasons why one should be chosen over another?\"\nRDBMS slow and flexible. Flat files fast and (sometimes) less flexible. Python levels the playing field.\n\"Are there any potential speed/performance pitfalls/boosts that I need to be aware of before I start that could influence the design?\"\nStar Schema: central fact table surrounded by dimension tables. Nothing beats it.\n\"Is there any project or framework out there to help with this type of task?\"\nNot really.\n",
"For speed optimization, I would suggest two other avenues of investigation beyond changing your underlying storage mechanism:\n1) Use an intermediate data structure.\nIf maximizing speed is more important than minimizing memory usage, you may get good results out of using a different data structure as the basis of your calculations, rather than focusing on the underlying storage mechanism. This is a strategy that, in practice, has reduced runtime in projects I've worked on dramatically, regardless of whether the data was stored in a database or text (in my case, XML).\nWhile sums and averages will require runtime in only O(n), more complex calculations could easily push that into O(n^2) without applying this strategy. O(n^2) would be a performance hit that would likely have far more of a perceived speed impact than whether you're reading from CSV or a database. An example case would be if your data rows reference other data rows, and there's a need to aggregate data based on those references.\nSo if you find yourself doing calculations more complex than a sum or an average, you might explore data structures that can be created in O(n) and would keep your calculation operations in O(n) or better. As Martin pointed out, it sounds like your whole data sets can be held in memory comfortably, so this may yield some big wins. What kind of data structure you'd create would be dependent on the nature of the calculation you're doing.\n2) Pre-cache.\nDepending on how the data is to be used, you could store the calculated values ahead of time. As soon as the data is produced/loaded, perform your sums, averages, etc., and store those aggregations alongside your original data, or hold them in memory as long as your program runs. If this strategy is applicable to your project (i.e. if the users aren't coming up with unforeseen calculation requests on the fly), reading the data shouldn't be prohibitively long-running, whether the data comes from text or a database.\n",
"Are you likely to need all rows in order or will you want only specific known rows?\nIf you need to read all the data there isn't much advantage to having it in a database.\nedit: If the code fits in memory then a simple CSV is fine. Plain text data formats are always easier to deal with than opaque ones if you can use them.\n",
"What matters most if all data will fit simultaneously into memory. From the size that you give, it seems that this is easily the case (a few megabytes at worst).\nIf so, I would discourage using a relational database, and do all operations directly in Python. Depending on what other processing you need, I would probably rather use binary pickles, than CSV.\n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"database",
"database_design",
"file_io",
"python"
] |
stackoverflow_0001241758_database_database_design_file_io_python.txt
|
Q:
Is the default configuration of re incorrect on macbooks? Or have I simply misunderstood something?
Python came pre-installed on my macbook and I have been slowly getting acquainted with the langauge. However, it seems that my configuration of the re library is incorrect, or I simply misunderstand something and things are amiss. Whenever I run a python script with "import re", I recieve the following error:
Traceback (most recent call last):
File "regex.py", line 2, in <module>
import re
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 4, in <module>
# re-compatible interface for the sre matching engine
AttributeError: 'module' object has no attribute 'compile'
What gives!
A:
Pretty mysterious problem, given that line 4 in that file (and many other lines around that line number) is a comment (indeed the error msg itself shows that comment line!-) so even with the worst misconfiguration I'd be hard put to reproduce the problem as given.
Let's try to simplify things and check how they may (or may not) break. Please open a Terminal, mkdir a new empty directory somewhere and cd into it (so we know there's no filename conflict wrt modules etc), at the bash prompt unset PYTHONPATH (so we know for sure that isn't interfering), unset PYTHONSTARTUP (ditto); then type the command:
$ python -c'import re; print re.__file__'
It should emit the line:
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.pyc
does it? If so, then we can keep rooting around to understand what name clash (or whatever) caused your original problem. If the problem persists under such "clean" conditions then your system is jinxed and I would reinstal Mac OS X Leopard if I were in your shoes!
|
Is the default configuration of re incorrect on macbooks? Or have I simply misunderstood something?
|
Python came pre-installed on my macbook and I have been slowly getting acquainted with the langauge. However, it seems that my configuration of the re library is incorrect, or I simply misunderstand something and things are amiss. Whenever I run a python script with "import re", I recieve the following error:
Traceback (most recent call last):
File "regex.py", line 2, in <module>
import re
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 4, in <module>
# re-compatible interface for the sre matching engine
AttributeError: 'module' object has no attribute 'compile'
What gives!
|
[
"Pretty mysterious problem, given that line 4 in that file (and many other lines around that line number) is a comment (indeed the error msg itself shows that comment line!-) so even with the worst misconfiguration I'd be hard put to reproduce the problem as given.\nLet's try to simplify things and check how they may (or may not) break. Please open a Terminal, mkdir a new empty directory somewhere and cd into it (so we know there's no filename conflict wrt modules etc), at the bash prompt unset PYTHONPATH (so we know for sure that isn't interfering), unset PYTHONSTARTUP (ditto); then type the command:\n$ python -c'import re; print re.__file__'\n\nIt should emit the line:\n/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.pyc\n\ndoes it? If so, then we can keep rooting around to understand what name clash (or whatever) caused your original problem. If the problem persists under such \"clean\" conditions then your system is jinxed and I would reinstal Mac OS X Leopard if I were in your shoes!\n"
] |
[
3
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001249390_python_regex.txt
|
Q:
Run Python script without opening Pythonwin
I have a python script which I can run from pythonwin on which I give the arguments.
Is it possible to automate this so that when I just click on the *.py file, I don't see the script and it asks for the path in a dos window?
A:
You're running on Windows, so you need an association between .py files and some binary to run them. Have a look at this post.
When you run "assoc .py", do you get Python.File? When you run "ftype Python.File", what do you get? If "ftype Python.File" points at some python.exe, your python script should run without any prompting.
A:
Rename it to *.pyw to hide the console on execution in Windows.
A:
You can also wrap it in a batch file, containing:
c:\path to python.exe c:\path to file.py
You can then also easily set an icon, run in window/run hidden etc on the batch file.
A:
how does your script ask for or get its parameters? If it expects them from the call to the script (i.e. in sys.argv) and Pythonwin just notices that and prompts you for them (I think Pyscripter does something similar) you can either run it from a CMD window (commandline) where you can give the arguments as in
python myscript.py argument-1 argument-2
or modify your script to ask for the arguments itself instead (using a gui like Tkinter if you don't want to run from commandline).
|
Run Python script without opening Pythonwin
|
I have a python script which I can run from pythonwin on which I give the arguments.
Is it possible to automate this so that when I just click on the *.py file, I don't see the script and it asks for the path in a dos window?
|
[
"You're running on Windows, so you need an association between .py files and some binary to run them. Have a look at this post.\nWhen you run \"assoc .py\", do you get Python.File? When you run \"ftype Python.File\", what do you get? If \"ftype Python.File\" points at some python.exe, your python script should run without any prompting.\n",
"Rename it to *.pyw to hide the console on execution in Windows.\n",
"You can also wrap it in a batch file, containing:\nc:\\path to python.exe c:\\path to file.py\n\nYou can then also easily set an icon, run in window/run hidden etc on the batch file.\n",
"how does your script ask for or get its parameters? If it expects them from the call to the script (i.e. in sys.argv) and Pythonwin just notices that and prompts you for them (I think Pyscripter does something similar) you can either run it from a CMD window (commandline) where you can give the arguments as in\npython myscript.py argument-1 argument-2\n\nor modify your script to ask for the arguments itself instead (using a gui like Tkinter if you don't want to run from commandline).\n"
] |
[
4,
3,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001245818_python.txt
|
Q:
Is it safe to track trunk in Django?
I'm currently using Django 1.1 beta for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if trunk is stable enough for using in production, or I should stick to 1.0 for mission critical systems.
Edit
Putting all the information in answer for correctness.
A:
You probably shouldn't pull Django trunk every day, sometimes there are big commits that might break some things on your site. Also it depends what features you use, the new ones will of cause be a bit more buggy than older features. But all in all there shouldn't be a problem using trunk for production. You just need to be careful when updating to latest revision.
You could for example set up a new virtual environment to test, before updating the live site. There are many ways to do something simelar, but I will let you take your pick.
A:
I think you've done a good job of gathering the right links in the question. The only links I would add are:
http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges
http://code.djangoproject.com/wiki/FutureBackwardsIncompatibleChanges
The first is for anyone still on a pre 1.0 release and wondering about the upgrade path, even to the trunk. The second is a work in progress it seems, and may be updated as things progress toward the 2.0 release.
A:
As with the trunk of any software project, it's only as stable as the people commiting things test for. Typically this is probably pretty stable, but you need to be aware that if you get caught with a 'bad' version (which can happen), your site/s just might come down over it temporarily.
A:
First, Django 1.1 is one step closer to being released, as RC1 is available for download.
With that out of the way, I've found some useful things.
If you are planning following this project, you should keep an eye in the Django deprecation timeline, along the Django deprecation policy.
Another important place to look, is the API Stability page of the documentation.
Keep an eye on the django-users mailing list, as well as the django-developer mailing list.
Am I missing something I should be looking too?
Edit
Django 1.1 was released!!! You can download it right now! :)
The question remains if trunk following is not recommended (once upon a time, Django didn't have releases, you only had head of trunk)
Acording to the tech team at The Onion, which has migrated from Drupal to Django, Django trunk is extremely stable.
A:
For what it's worth, I've read in multiple places (in the documentation here: http://www.djangoproject.com/download/ (see the side bar) and from the project's lead developers in a book of theirs) that it's fine to use the trunk. Many of their own developers use trunk for their sites and so they have incentive to keep it stable.
Recently, however, they mentioned that the 1.1 RC along with any other pre-release packages should not be used for production ( http://www.djangoproject.com/weblog/2009/jul/21/rc/ ) so the signals are somewhat mixed.
That said, my personal feeling is that the trunk is very stable most of the time but as with any code you haven't used before you should run it through its paces before deploying anything.
As the other posters said though: the choice is ultimately yours to make based on your best judgement.
|
Is it safe to track trunk in Django?
|
I'm currently using Django 1.1 beta for some personal projects, and plan to start messing arround with the trunk to see the new stuff under the hood. But I might start using it on a professional basis, and I'd need to know if trunk is stable enough for using in production, or I should stick to 1.0 for mission critical systems.
Edit
Putting all the information in answer for correctness.
|
[
"You probably shouldn't pull Django trunk every day, sometimes there are big commits that might break some things on your site. Also it depends what features you use, the new ones will of cause be a bit more buggy than older features. But all in all there shouldn't be a problem using trunk for production. You just need to be careful when updating to latest revision.\nYou could for example set up a new virtual environment to test, before updating the live site. There are many ways to do something simelar, but I will let you take your pick. \n",
"I think you've done a good job of gathering the right links in the question. The only links I would add are:\n\nhttp://code.djangoproject.com/wiki/BackwardsIncompatibleChanges\nhttp://code.djangoproject.com/wiki/FutureBackwardsIncompatibleChanges\n\nThe first is for anyone still on a pre 1.0 release and wondering about the upgrade path, even to the trunk. The second is a work in progress it seems, and may be updated as things progress toward the 2.0 release.\n",
"As with the trunk of any software project, it's only as stable as the people commiting things test for. Typically this is probably pretty stable, but you need to be aware that if you get caught with a 'bad' version (which can happen), your site/s just might come down over it temporarily.\n",
"First, Django 1.1 is one step closer to being released, as RC1 is available for download.\nWith that out of the way, I've found some useful things.\n\nIf you are planning following this project, you should keep an eye in the Django deprecation timeline, along the Django deprecation policy.\nAnother important place to look, is the API Stability page of the documentation.\nKeep an eye on the django-users mailing list, as well as the django-developer mailing list.\n\nAm I missing something I should be looking too?\nEdit\nDjango 1.1 was released!!! You can download it right now! :)\nThe question remains if trunk following is not recommended (once upon a time, Django didn't have releases, you only had head of trunk)\n\nAcording to the tech team at The Onion, which has migrated from Drupal to Django, Django trunk is extremely stable.\n",
"For what it's worth, I've read in multiple places (in the documentation here: http://www.djangoproject.com/download/ (see the side bar) and from the project's lead developers in a book of theirs) that it's fine to use the trunk. Many of their own developers use trunk for their sites and so they have incentive to keep it stable.\nRecently, however, they mentioned that the 1.1 RC along with any other pre-release packages should not be used for production ( http://www.djangoproject.com/weblog/2009/jul/21/rc/ ) so the signals are somewhat mixed.\nThat said, my personal feeling is that the trunk is very stable most of the time but as with any code you haven't used before you should run it through its paces before deploying anything.\nAs the other posters said though: the choice is ultimately yours to make based on your best judgement.\n"
] |
[
2,
1,
0,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001165631_django_python.txt
|
Q:
How to write a setup.py for a program that depends on packages outside pypi
For instance, what if PIL, python-rsvg and libev3 are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.
A:
You could use setuptools. setuptools allows you to add any kind of Python installable (any distutils/setuptools enabled package) as a dependency, no matter if it is on PyPI or not.
For example, to depend on PIL 1.1.6, use something like:
setup(...,
install_requires = ["http://effbot.org/downloads/Imaging-1.1.6.tar.gz"],
...)
See setuptools docs for more information.
A:
Simply don't put them in your dependencies and document that in your INSTALL or README.
A:
If you are packaging something to be installed on Debian (as implied), the best way to manage dependencies is to package your program as a .deb and express the dependencies the Debian way. (Note, PIL is available in Debian as python-imaging.)
A:
Since the setup.py is Python code too, you just can download and run the setup.py on those packages.
|
How to write a setup.py for a program that depends on packages outside pypi
|
For instance, what if PIL, python-rsvg and libev3 are dependencies of the program? These dependencies are not in pypi index, the latter two are Debian package names.
|
[
"You could use setuptools. setuptools allows you to add any kind of Python installable (any distutils/setuptools enabled package) as a dependency, no matter if it is on PyPI or not.\nFor example, to depend on PIL 1.1.6, use something like:\nsetup(...,\n install_requires = [\"http://effbot.org/downloads/Imaging-1.1.6.tar.gz\"],\n ...)\n\nSee setuptools docs for more information.\n",
"Simply don't put them in your dependencies and document that in your INSTALL or README.\n",
"If you are packaging something to be installed on Debian (as implied), the best way to manage dependencies is to package your program as a .deb and express the dependencies the Debian way. (Note, PIL is available in Debian as python-imaging.)\n",
"Since the setup.py is Python code too, you just can download and run the setup.py on those packages.\n"
] |
[
4,
2,
0,
0
] |
[] |
[] |
[
"python",
"setuptools"
] |
stackoverflow_0001244784_python_setuptools.txt
|
Q:
`cat filename | grep -B 5 -C 5 foo`
for filename in os.listdir("."):
for line in open(filename).xreadlines():
if "foo" in line:
print line
So this is a simple python equivalent of cat filename | grep foo. However, I would like the equivalent of cat filename | grep -B 5 -C 5 foo, how should the above code be modified?
A:
Simplest way is:
for filename in os.listdir("."):
lines = open(filename).readlines()
for i, line in enumerate(lines):
if "foo" in line:
for x in lines[i-5 : i+6]:
print x,
add line numbers, breaks between blocks, etc, to taste;-).
In the extremely unlikely case that you have to deal with absolutely humungous text files (ones over 200-300 times larger than the King James Bible, for example, which is about 4.3 MB in its entirety as a text file), I recommend a generator producing a sliding window (a "FIFO" of lines). Focusing for simplicity only on searching lines excluding the first and last few ones of the file (which requires a couple of special-case loops in addition -- that's why I'm returning the index as well... because it's not always 5 in those two extra loops!-):
import collections
def sliding_windows(it):
fifo = collections.deque()
# prime the FIFO with the first 10
for i, line in enumerate(it):
fifo.append(line)
if i == 9: break
# keep yielding 11-line sliding-windows
for line in it:
fifo.append(line)
yield fifo, 5
fifo.popleft()
for w, i in sliding_windows(open(filename)):
if "foo" in w[i]:
for line in w: print line,
I think I'll leave the special-case loops (and worries about files of very few lines;-) as exercises, since the whole thing is so incredibly hypothetical anyway.
Just a few hints...: the closing "special-case loop" is really simple -- just repeatedly drop the first line, without appending, obviously, as there's nothing more to append... the index should still be always 5, and you're done when you've just yielded a window where 5 is the last index (i.e., the last line of the file); the starting case is a tad subtler as you don't want to yield until you've read the first 6 lines, and at that point the index will be 0 (first line of the file)...
Finally, for extra credit, consider how to make this work on very short files, too!-)
A:
Although I like the simplicity of Alex's answer, it would require lots of memory when grepping large files. How about this algorithm?
import os
for filename in (f for f in os.listdir(".") if os.path.isfile(f)):
prevLines = []
followCount = 0
for line in open(filename):
prevLines.append(line)
if "foo" in line:
if followCount <= 0:
for prevLine in prevLines:
print prevLine.strip()
else:
print line.strip()
followCount = 5
elif followCount > 0:
print line.strip()
followCount -= 1
if len(prevLines) > 5:
prevLines.pop(0)
|
`cat filename | grep -B 5 -C 5 foo`
|
for filename in os.listdir("."):
for line in open(filename).xreadlines():
if "foo" in line:
print line
So this is a simple python equivalent of cat filename | grep foo. However, I would like the equivalent of cat filename | grep -B 5 -C 5 foo, how should the above code be modified?
|
[
"Simplest way is:\nfor filename in os.listdir(\".\"):\n lines = open(filename).readlines()\n for i, line in enumerate(lines):\n if \"foo\" in line:\n for x in lines[i-5 : i+6]:\n print x,\n\nadd line numbers, breaks between blocks, etc, to taste;-).\nIn the extremely unlikely case that you have to deal with absolutely humungous text files (ones over 200-300 times larger than the King James Bible, for example, which is about 4.3 MB in its entirety as a text file), I recommend a generator producing a sliding window (a \"FIFO\" of lines). Focusing for simplicity only on searching lines excluding the first and last few ones of the file (which requires a couple of special-case loops in addition -- that's why I'm returning the index as well... because it's not always 5 in those two extra loops!-):\nimport collections\n\ndef sliding_windows(it):\n fifo = collections.deque()\n # prime the FIFO with the first 10 \n for i, line in enumerate(it):\n fifo.append(line)\n if i == 9: break\n # keep yielding 11-line sliding-windows\n for line in it:\n fifo.append(line)\n yield fifo, 5\n fifo.popleft()\n\nfor w, i in sliding_windows(open(filename)):\n if \"foo\" in w[i]:\n for line in w: print line,\n\nI think I'll leave the special-case loops (and worries about files of very few lines;-) as exercises, since the whole thing is so incredibly hypothetical anyway.\nJust a few hints...: the closing \"special-case loop\" is really simple -- just repeatedly drop the first line, without appending, obviously, as there's nothing more to append... the index should still be always 5, and you're done when you've just yielded a window where 5 is the last index (i.e., the last line of the file); the starting case is a tad subtler as you don't want to yield until you've read the first 6 lines, and at that point the index will be 0 (first line of the file)...\nFinally, for extra credit, consider how to make this work on very short files, too!-)\n",
"Although I like the simplicity of Alex's answer, it would require lots of memory when grepping large files. How about this algorithm?\nimport os\nfor filename in (f for f in os.listdir(\".\") if os.path.isfile(f)):\n prevLines = []\n followCount = 0\n for line in open(filename):\n prevLines.append(line)\n if \"foo\" in line:\n if followCount <= 0:\n for prevLine in prevLines:\n print prevLine.strip() \n else:\n print line.strip()\n followCount = 5\n elif followCount > 0:\n print line.strip()\n followCount -= 1\n if len(prevLines) > 5:\n prevLines.pop(0)\n\n"
] |
[
7,
1
] |
[] |
[] |
[
"grep",
"python"
] |
stackoverflow_0001249412_grep_python.txt
|
Q:
Convert Python exception information to string for logging
I try logging exceptions in Python 2.5, but I can't do it. All formatting functions do something else than what I want.
I came up with this:
def logexception(type, value, traceback):
print traceback.format_exception(type, value, traceback)
sys.excepthook = logexception
but it bails out with an argument error when called, though according to the docs it should work. Anyone knows what the problem is with this or have an other drop-in solution?
A:
Why should that traceback argument have a format_exception method just like the function in the traceback module whose name it's usurping, and if it had one why would that method require the same object on which it's called to be passed in as the last argument as well?
I suspect you just want to give the third argument a different name, so as not to hide the traceback module, say:
import sys
import traceback
def logexception(type, value, tb):
print traceback.format_exception(type, value, tb)
sys.excepthook = logexception
and things should work much better.
|
Convert Python exception information to string for logging
|
I try logging exceptions in Python 2.5, but I can't do it. All formatting functions do something else than what I want.
I came up with this:
def logexception(type, value, traceback):
print traceback.format_exception(type, value, traceback)
sys.excepthook = logexception
but it bails out with an argument error when called, though according to the docs it should work. Anyone knows what the problem is with this or have an other drop-in solution?
|
[
"Why should that traceback argument have a format_exception method just like the function in the traceback module whose name it's usurping, and if it had one why would that method require the same object on which it's called to be passed in as the last argument as well?\nI suspect you just want to give the third argument a different name, so as not to hide the traceback module, say:\nimport sys\nimport traceback\n\ndef logexception(type, value, tb):\n print traceback.format_exception(type, value, tb)\n\nsys.excepthook = logexception\n\nand things should work much better.\n"
] |
[
5
] |
[
"you can use this very simpe logging solution\nor this one \n"
] |
[
-1
] |
[
"exception",
"python"
] |
stackoverflow_0001249795_exception_python.txt
|
Q:
Is there a string-collapse library function in python?
Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?
I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps even optimized in C?
def collapse(input):
import re
rn = re.compile(r'(\r\n)+')
r = re.compile(r'\r+')
n = re.compile(r'\n+')
s = re.compile(r'\ +')
return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input))))
P.S. Thanks for good observations. ' '.join(input.split()) seems to be the winner as it actually runs faster about twice in my case compared to search-replace with a precompiled r'\s+' regex.
A:
The built-in string.split() method will split on runs of whitespace, so you can use that and then join the resulting list using spaces, like this:
' '.join(my_string.split())
Here's a complete test script:
TEST = """This
is a test\twith a
mix of\ttabs, newlines and repeating
whitespace"""
print ' '.join(TEST.split())
# Prints:
# This is a test with a mix of tabs, newlines and repeating whitespace
A:
You had the right idea, you just needed to read the python manual a little more closely:
import re
somewhitespace = re.compile(r'\s+')
TEST = """This
is a test\twith a
mix of\ttabs, newlines and repeating
whitespace"""
somewhitespace.sub(' ', TEST)
'This is a test with a mix of tabs, newlines and repeating whitespace'
A:
multi_line.replace('\n', '')
will do the job. '\n' is a universal end of line character in python.
|
Is there a string-collapse library function in python?
|
Is there a cross-platform library function that would collapse a multiline string into a single-line string with no repeating spaces?
I've come up with some snip below, but I wonder if there is a standard function which I could just import which is perhaps even optimized in C?
def collapse(input):
import re
rn = re.compile(r'(\r\n)+')
r = re.compile(r'\r+')
n = re.compile(r'\n+')
s = re.compile(r'\ +')
return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input))))
P.S. Thanks for good observations. ' '.join(input.split()) seems to be the winner as it actually runs faster about twice in my case compared to search-replace with a precompiled r'\s+' regex.
|
[
"The built-in string.split() method will split on runs of whitespace, so you can use that and then join the resulting list using spaces, like this:\n' '.join(my_string.split())\n\nHere's a complete test script:\nTEST = \"\"\"This\nis a test\\twith a\n mix of\\ttabs, newlines and repeating\nwhitespace\"\"\"\n\nprint ' '.join(TEST.split())\n# Prints:\n# This is a test with a mix of tabs, newlines and repeating whitespace\n\n",
"You had the right idea, you just needed to read the python manual a little more closely:\nimport re\nsomewhitespace = re.compile(r'\\s+')\nTEST = \"\"\"This\nis a test\\twith a\n mix of\\ttabs, newlines and repeating\nwhitespace\"\"\"\n\nsomewhitespace.sub(' ', TEST)\n\n'This is a test with a mix of tabs, newlines and repeating whitespace'\n\n",
"multi_line.replace('\\n', '')\n\nwill do the job. '\\n' is a universal end of line character in python.\n"
] |
[
12,
4,
0
] |
[] |
[] |
[
"line_breaks",
"python",
"string"
] |
stackoverflow_0001249786_line_breaks_python_string.txt
|
Q:
Comparing persistent storage solutions in python
I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:
Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.
Ease-of-use. This is python. The storage should feel like python.
Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine.
Ease of installation. My sysadmin should be able to get this running on our cluster.
I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.
Some potential options that I've started looking at (see this post):
pyTables
ZopeDB
shove
shelve
redis
durus
Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?
A:
Might want to give mongodb a shot - the PyMongo library works with dictionaries and supports most Python types. Easy to install, very performant + scalable. MongoDB (and PyMongo) is also used in production at some big names.
A:
A RDBMS.
Nothing is more realiable than using tables on a well known RDBMS. Postgresql comes to mind.
That automatically gives you some choices for the future like clustering. Also you automatically have a lot of tools to administer your database, and you can use it from other software written in virtually any language.
It is really fast.
In the "feel like python" point, I might add that you can use an ORM. A strong name is sqlalchemy. Maybe with the elixir "extension".
Using sqlalchemy you can leave your user/sysadmin choose which database backend he wants to use. Maybe they already have MySql installed - no problem.
RDBMSs are still the best choice for data storage.
A:
I'm working on such a project and I'm using SQLite.
SQLite stores everything in one file and is part of Python's standard library. Hence, installation and configuration is virtually for free (ease of installation).
You can easily manage the database file with small Python scripts or via various tools. There is also a Firefox plugin (ease of installation / ease-of-use).
I find it very convenient to use SQL to filter/sort/manipulate/... the data. Although, I'm not an SQL expert. (ease-of-use)
I'm not sure if SQLite is the fastes DB system for this work and it lacks some features you might need e.g. stored procedures.
Anyway, SQLite works for me.
A:
if you really just need dictionary-like storage, some of the new key/value or column stores like Cassandra or MongoDB might provide a lot more speed than you'd get with a relational database. Of course if you decide to go with RDBMS, SQLAlchemy is the way to go (disclaimer: I am its creator), but your desired featurelist seems to lean in the direction of "I just want a dictionary that feels like Python" - if you aren't interested in relational queries or strong ACIDity, those facets of RDBMS will probably feel cumbersome.
A:
Sqlite -- it comes with python, fast, widely availible and easy to maintain
A:
If you only need simple (dict like) access mechanisms and need efficiency for processing a lot of data, then HDF5 might be a good option. If you are going to be using numpy then it is really worth considering.
A:
Go with a RDBMS is reliable scalable and fast.
If you need a more scalabre solution and don't need the features of RDBMS, you can go with a key-value store like couchdb that has a good python api.
A:
The NEMO collaboration (building a cosmic neutrino detector underwater) had much of the same problems, and they used mysql and postgresql without major problems.
A:
It really depends on what you're trying to do. An RDBMS is designed for relational data, so if your data is relational, then use one of the various SQL options. But it sounds like your data is more oriented towards a key-value store with very fast random GET operations. If that's the case, compare the benchmarks of the various key-stores, focusing on the GET speed. The ideal key-value store will keep or cache requests in memory, and be able to handle many GET requests concurrently. You may actually want to create your own benchmark suite so you can effectively compare random concurrent GET operations.
Why do you need a cluster? Is the size of each value very large? If not, you shouldn't need a cluster to handle storage of a million entries. But if you're storing large blobs of data, that matters, and you may need something easily supports read slaves and/or transparent partitioning. Some of the key-value stores are document oriented and/or optimized for storing larger values. Redis is technically more storage efficient for larger values due to the indexing overhead required for fast GETs, but that doesn't necessarily mean it's slower. In fact, the extra indexing makes lookups faster.
You're the only one that can truly answer this question, and I strongly recommend putting together a custom benchmark suite to test available options with actual usage scenarios. The data you get from that will give you more insight than anything else.
|
Comparing persistent storage solutions in python
|
I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a dictionary of dictionaries. Some potential considerations:
Speed. I can't load all the data off disk every time I start a new script, and I'd like as quick access to random entries as possible.
Ease-of-use. This is python. The storage should feel like python.
Stability/maturity. I'd like something that's currently supported, although something that works well but is still in development would be fine.
Ease of installation. My sysadmin should be able to get this running on our cluster.
I don't really care that much about the size of the storage, but it could be a consideration if an option is really terrible on this front. Also, if it matters, I'll most likely be creating the database once, and thereafter only reading from it.
Some potential options that I've started looking at (see this post):
pyTables
ZopeDB
shove
shelve
redis
durus
Any suggestions on which of these might be better for my purposes? Any better ideas? Some of these have a back-end; any suggestions on which file-system back-end would be best?
|
[
"Might want to give mongodb a shot - the PyMongo library works with dictionaries and supports most Python types. Easy to install, very performant + scalable. MongoDB (and PyMongo) is also used in production at some big names.\n",
"A RDBMS.\nNothing is more realiable than using tables on a well known RDBMS. Postgresql comes to mind.\nThat automatically gives you some choices for the future like clustering. Also you automatically have a lot of tools to administer your database, and you can use it from other software written in virtually any language.\nIt is really fast.\nIn the \"feel like python\" point, I might add that you can use an ORM. A strong name is sqlalchemy. Maybe with the elixir \"extension\".\nUsing sqlalchemy you can leave your user/sysadmin choose which database backend he wants to use. Maybe they already have MySql installed - no problem.\nRDBMSs are still the best choice for data storage.\n",
"I'm working on such a project and I'm using SQLite.\nSQLite stores everything in one file and is part of Python's standard library. Hence, installation and configuration is virtually for free (ease of installation).\nYou can easily manage the database file with small Python scripts or via various tools. There is also a Firefox plugin (ease of installation / ease-of-use).\nI find it very convenient to use SQL to filter/sort/manipulate/... the data. Although, I'm not an SQL expert. (ease-of-use)\nI'm not sure if SQLite is the fastes DB system for this work and it lacks some features you might need e.g. stored procedures.\nAnyway, SQLite works for me.\n",
"if you really just need dictionary-like storage, some of the new key/value or column stores like Cassandra or MongoDB might provide a lot more speed than you'd get with a relational database. Of course if you decide to go with RDBMS, SQLAlchemy is the way to go (disclaimer: I am its creator), but your desired featurelist seems to lean in the direction of \"I just want a dictionary that feels like Python\" - if you aren't interested in relational queries or strong ACIDity, those facets of RDBMS will probably feel cumbersome.\n",
"Sqlite -- it comes with python, fast, widely availible and easy to maintain\n",
"If you only need simple (dict like) access mechanisms and need efficiency for processing a lot of data, then HDF5 might be a good option. If you are going to be using numpy then it is really worth considering.\n",
"Go with a RDBMS is reliable scalable and fast.\nIf you need a more scalabre solution and don't need the features of RDBMS, you can go with a key-value store like couchdb that has a good python api.\n",
"The NEMO collaboration (building a cosmic neutrino detector underwater) had much of the same problems, and they used mysql and postgresql without major problems.\n",
"It really depends on what you're trying to do. An RDBMS is designed for relational data, so if your data is relational, then use one of the various SQL options. But it sounds like your data is more oriented towards a key-value store with very fast random GET operations. If that's the case, compare the benchmarks of the various key-stores, focusing on the GET speed. The ideal key-value store will keep or cache requests in memory, and be able to handle many GET requests concurrently. You may actually want to create your own benchmark suite so you can effectively compare random concurrent GET operations.\nWhy do you need a cluster? Is the size of each value very large? If not, you shouldn't need a cluster to handle storage of a million entries. But if you're storing large blobs of data, that matters, and you may need something easily supports read slaves and/or transparent partitioning. Some of the key-value stores are document oriented and/or optimized for storing larger values. Redis is technically more storage efficient for larger values due to the indexing overhead required for fast GETs, but that doesn't necessarily mean it's slower. In fact, the extra indexing makes lookups faster.\nYou're the only one that can truly answer this question, and I strongly recommend putting together a custom benchmark suite to test available options with actual usage scenarios. The data you get from that will give you more insight than anything else.\n"
] |
[
13,
9,
5,
4,
3,
2,
1,
1,
1
] |
[] |
[] |
[
"orm",
"persistence",
"python"
] |
stackoverflow_0001235594_orm_persistence_python.txt
|
Q:
If a python module says its dependent on debhelper and cdbs is there no way to get it to run on a nondebian linux?
I want to try python purple but I don't have debian. Is there a way to get it to run on either windows or a different linux?
A:
I suppose compiling from source (if availiable) or looking for dbhelper and cbds install files for your distribution
|
If a python module says its dependent on debhelper and cdbs is there no way to get it to run on a nondebian linux?
|
I want to try python purple but I don't have debian. Is there a way to get it to run on either windows or a different linux?
|
[
"I suppose compiling from source (if availiable) or looking for dbhelper and cbds install files for your distribution\n"
] |
[
0
] |
[] |
[] |
[
"cdbs",
"debian",
"linux",
"python"
] |
stackoverflow_0001249873_cdbs_debian_linux_python.txt
|
Q:
is it possible to get python purple running either in cygwin or on a linux that isn't debian?
python purple says it needs dbms and debhelper in order to run, but I don't run debian. Is there a way to get this running on a different linux? or in cygwin?
A:
Both cdbs and debhelper are only needed if you are trying to build a debian package. Just do a regular python setup.py build, and it should work fine (assuming you have the other prerequisites available).
|
is it possible to get python purple running either in cygwin or on a linux that isn't debian?
|
python purple says it needs dbms and debhelper in order to run, but I don't run debian. Is there a way to get this running on a different linux? or in cygwin?
|
[
"Both cdbs and debhelper are only needed if you are trying to build a debian package. Just do a regular python setup.py build, and it should work fine (assuming you have the other prerequisites available).\n"
] |
[
5
] |
[] |
[] |
[
"cygwin",
"debhelper",
"linux",
"python"
] |
stackoverflow_0001224726_cygwin_debhelper_linux_python.txt
|
Q:
What is best way to remove duplicate lines matching regex from string using Python?
This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern and return modified string.
Just to be clear...regex .*Dog.* would take
Cat
Dog
My Dog
Her Dog
Mouse
and return
Cat
Dog
::::: Pattern .*Dog.* repeats 2 more times.
Mouse
#!/usr/bin/env python
#
import re
import types
def remove_repeats (l_string, l_regex):
"""Take a string, remove similar lines and replace with a summary message.
l_regex accepts strings and tuples.
"""
# Convert string to tuple.
if type(l_regex) == types.StringType:
l_regex = l_regex,
for t in l_regex:
r = ''
p = ''
for l in l_string.splitlines(True):
if l.startswith('::::: Pattern'):
r = r + l
else:
if re.search(t, l): # If line matches regex.
m += 1
if m == 1: # If this is first match in a set of lines add line to file.
r = r + l
elif m > 1: # Else update the message string.
p = "::::: Pattern '" + t + "' repeats " + str(m-1) + ' more times.\n'
else:
if p: # Write the message string if it has value.
r = r + p
p = ''
m = 0
r = r + l
if p: # Write the message if loop ended in a pattern.
r = r + p
p = ''
l_string = r # Reset string to modified string.
return l_string
A:
The rematcher function seems to do what you want:
def rematcher(re_str, iterable):
matcher= re.compile(re_str)
in_match= 0
for item in iterable:
if matcher.match(item):
if in_match == 0:
yield item
in_match+= 1
else:
if in_match > 1:
yield "%s repeats %d more times\n" % (re_str, in_match-1)
in_match= 0
yield item
if in_match > 1:
yield "%s repeats %d more times\n" % (re_str, in_match-1)
import sys, re
for line in rematcher(".*Dog.*", sys.stdin):
sys.stdout.write(line)
EDIT
In your case, the final string should be:
final_string= '\n'.join(rematcher(".*Dog.*", your_initial_string.split("\n")))
A:
Updated your code to be a bit more effective
#!/usr/bin/env python
#
import re
import types
def remove_repeats (l_string, l_regex):
"""Take a string, remove similar lines and replace with a summary message.
l_regex accepts strings/patterns or tuples of strings/patterns.
"""
# Convert string/pattern to tuple.
if not hasattr(l_regex, '__iter__'):
l_regex = l_regex,
ret = []
last_regex = None
count = 0
for line in l_string.splitlines(True):
if last_regex:
# Previus line matched one of the regexes
if re.match(last_regex, line):
# This one does too
count += 1
continue # skip to next line
elif count > 1:
ret.append("::::: Pattern %r repeats %d more times.\n" % (last_regex, count-1))
count = 0
last_regex = None
ret.append(line)
# Look for other patterns that could match
for regex in l_regex:
if re.match(regex, line):
# Found one
last_regex = regex
count = 1
break # exit inner loop
return ''.join(ret)
A:
First, your regular expression will match more slowly than if you had left off the greedy match.
.*Dog.*
is equivalent to
Dog
but the latter matches more quickly because no backtracking is involved. The longer the strings, the more likely "Dog" appears multiple times and thus the more backtracking work the regex engine has to do. As it is, ".*D" virtually guarantees backtracking.
That said, how about:
#! /usr/bin/env python
import re # regular expressions
import fileinput # read from STDIN or file
my_regex = '.*Dog.*'
my_matches = 0
for line in fileinput.input():
line = line.strip()
if re.search(my_regex, line):
if my_matches == 0:
print(line)
my_matches = my_matches + 1
else:
if my_matches != 0:
print('::::: Pattern %s repeats %i more times.' % (my_regex, my_matches - 1))
print(line)
my_matches = 0
It's not clear what should happen with non-neighboring matches.
It's also not clear what should happen with single-line matches surrounded by non-matching lines. Append "Doggy" and "Hula" to the input file and you'll get the matching message "0" more times.
|
What is best way to remove duplicate lines matching regex from string using Python?
|
This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern and return modified string.
Just to be clear...regex .*Dog.* would take
Cat
Dog
My Dog
Her Dog
Mouse
and return
Cat
Dog
::::: Pattern .*Dog.* repeats 2 more times.
Mouse
#!/usr/bin/env python
#
import re
import types
def remove_repeats (l_string, l_regex):
"""Take a string, remove similar lines and replace with a summary message.
l_regex accepts strings and tuples.
"""
# Convert string to tuple.
if type(l_regex) == types.StringType:
l_regex = l_regex,
for t in l_regex:
r = ''
p = ''
for l in l_string.splitlines(True):
if l.startswith('::::: Pattern'):
r = r + l
else:
if re.search(t, l): # If line matches regex.
m += 1
if m == 1: # If this is first match in a set of lines add line to file.
r = r + l
elif m > 1: # Else update the message string.
p = "::::: Pattern '" + t + "' repeats " + str(m-1) + ' more times.\n'
else:
if p: # Write the message string if it has value.
r = r + p
p = ''
m = 0
r = r + l
if p: # Write the message if loop ended in a pattern.
r = r + p
p = ''
l_string = r # Reset string to modified string.
return l_string
|
[
"The rematcher function seems to do what you want:\ndef rematcher(re_str, iterable):\n\n matcher= re.compile(re_str)\n in_match= 0\n for item in iterable:\n if matcher.match(item):\n if in_match == 0:\n yield item\n in_match+= 1\n else:\n if in_match > 1:\n yield \"%s repeats %d more times\\n\" % (re_str, in_match-1)\n in_match= 0\n yield item\n if in_match > 1:\n yield \"%s repeats %d more times\\n\" % (re_str, in_match-1)\n\nimport sys, re\n\nfor line in rematcher(\".*Dog.*\", sys.stdin):\n sys.stdout.write(line)\n\nEDIT\nIn your case, the final string should be:\nfinal_string= '\\n'.join(rematcher(\".*Dog.*\", your_initial_string.split(\"\\n\")))\n\n",
"Updated your code to be a bit more effective\n#!/usr/bin/env python\n#\n\nimport re\nimport types\n\ndef remove_repeats (l_string, l_regex):\n \"\"\"Take a string, remove similar lines and replace with a summary message.\n\n l_regex accepts strings/patterns or tuples of strings/patterns.\n \"\"\"\n\n # Convert string/pattern to tuple.\n if not hasattr(l_regex, '__iter__'):\n l_regex = l_regex,\n\n ret = []\n last_regex = None\n count = 0\n\n for line in l_string.splitlines(True):\n if last_regex:\n # Previus line matched one of the regexes\n if re.match(last_regex, line):\n # This one does too\n count += 1\n continue # skip to next line\n elif count > 1:\n ret.append(\"::::: Pattern %r repeats %d more times.\\n\" % (last_regex, count-1))\n count = 0\n last_regex = None\n\n ret.append(line)\n\n # Look for other patterns that could match\n for regex in l_regex:\n if re.match(regex, line):\n # Found one\n last_regex = regex\n count = 1\n break # exit inner loop\n\n return ''.join(ret)\n\n",
"First, your regular expression will match more slowly than if you had left off the greedy match.\n.*Dog.*\n\nis equivalent to\nDog\n\nbut the latter matches more quickly because no backtracking is involved. The longer the strings, the more likely \"Dog\" appears multiple times and thus the more backtracking work the regex engine has to do. As it is, \".*D\" virtually guarantees backtracking.\nThat said, how about:\n#! /usr/bin/env python\n\nimport re # regular expressions\nimport fileinput # read from STDIN or file\n\nmy_regex = '.*Dog.*'\nmy_matches = 0\n\nfor line in fileinput.input():\n line = line.strip()\n\n if re.search(my_regex, line):\n if my_matches == 0:\n print(line)\n my_matches = my_matches + 1\n else:\n if my_matches != 0:\n print('::::: Pattern %s repeats %i more times.' % (my_regex, my_matches - 1))\n print(line)\n my_matches = 0\n\nIt's not clear what should happen with non-neighboring matches.\nIt's also not clear what should happen with single-line matches surrounded by non-matching lines. Append \"Doggy\" and \"Hula\" to the input file and you'll get the matching message \"0\" more times.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0000167923_python_regex.txt
|
Q:
parsing XML file in python with cElementTree: dealing with errors and line number in the file
I am using the cElementTree library to parse XML files in Python.
Everything is working fine
But I would like to provide full error messages for the user when a value in the XML is not correct.
For example, let's suppose I have the following XML:
<A name="xxxx" href="yyyy"/>
and want to tell the user if the href attribute doesn't exist or have a value that is not in a given list.
For the moment, I have something like
if elem.get("ref") not in myList:
raise XMLException( elem, "the 'href' attribute is not valid or does not exist")
where my exception is caught somewhere.
But, in addition, I would like to display the line number of the XML element in the file. It seems that the cElementTree doesn't store any information about the line numbers of the XML elements of the tree... :-(
Question: Is there an equivalent XML library that is able to do that?
Or a way to have access to the position of an XML element in the XML file ?
Thanks
A:
The equivalent library that you should be using is lxml. lxml is a wrapper on very fast c libraries libxml2 and libxslt and is generally considered superior to the built in ones.
It, luckly, tries to keep to the element tree api and extend it in lxml.etree.
lxml.etree has an attribute sourceline for all elements which is just what you are after.
So elem.sourceline above in the error message should work.
|
parsing XML file in python with cElementTree: dealing with errors and line number in the file
|
I am using the cElementTree library to parse XML files in Python.
Everything is working fine
But I would like to provide full error messages for the user when a value in the XML is not correct.
For example, let's suppose I have the following XML:
<A name="xxxx" href="yyyy"/>
and want to tell the user if the href attribute doesn't exist or have a value that is not in a given list.
For the moment, I have something like
if elem.get("ref") not in myList:
raise XMLException( elem, "the 'href' attribute is not valid or does not exist")
where my exception is caught somewhere.
But, in addition, I would like to display the line number of the XML element in the file. It seems that the cElementTree doesn't store any information about the line numbers of the XML elements of the tree... :-(
Question: Is there an equivalent XML library that is able to do that?
Or a way to have access to the position of an XML element in the XML file ?
Thanks
|
[
"The equivalent library that you should be using is lxml. lxml is a wrapper on very fast c libraries libxml2 and libxslt and is generally considered superior to the built in ones.\nIt, luckly, tries to keep to the element tree api and extend it in lxml.etree.\nlxml.etree has an attribute sourceline for all elements which is just what you are after.\nSo elem.sourceline above in the error message should work.\n"
] |
[
4
] |
[] |
[] |
[
"celementtree",
"error_handling",
"line_numbers",
"python"
] |
stackoverflow_0001250192_celementtree_error_handling_line_numbers_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.