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:
regular expression to parse option string in python
I can't seem to create the correct regular expression to extract the correct tokens from my string. Padding the beginning of the string with a space generates the correct output, but seems less than optimal:
>>> import re
>>> s = '-edge_0triggered a-b | -level_Sensitive c-d | a-b-c'
>>> re.findall(r'\W(-[\w_]+)',' '+s)
['-edge_0triggered', '-level_Sensitive'] # correct output
Here are some of the regular expressions I've tried, does anyone have a regex suggestion that doesn't involve changing the original string and generates the correct output
>>> re.findall(r'(-[\w_]+)',s)
['-edge_0triggered', '-b', '-level_Sensitive', '-d', '-b', '-c']
>>> re.findall(r'\W(-[\w_]+)',s)
['-level_Sensitive']
A:
Change the first qualifier to accept either a beginning anchor or a not-word, instead of only a not-word:
>>> re.findall(r'(?:^|\W)(-[\w_]+)', s)
['-edge_0triggered', '-level_Sensitive']
The ?: at the beginning of the group simply tells the regex engine to not treat that as a group for purposes of results.
A:
r'(?:^|\W)(-\w+)'
\w already includes the underscore.
A:
You could use a negative-lookbehind:
re.findall(r'(?<!\w)(-\w+)', s)
the (?<!\w) part means "match only if not preceded by a word-character".
| regular expression to parse option string in python | I can't seem to create the correct regular expression to extract the correct tokens from my string. Padding the beginning of the string with a space generates the correct output, but seems less than optimal:
>>> import re
>>> s = '-edge_0triggered a-b | -level_Sensitive c-d | a-b-c'
>>> re.findall(r'\W(-[\w_]+)',' '+s)
['-edge_0triggered', '-level_Sensitive'] # correct output
Here are some of the regular expressions I've tried, does anyone have a regex suggestion that doesn't involve changing the original string and generates the correct output
>>> re.findall(r'(-[\w_]+)',s)
['-edge_0triggered', '-b', '-level_Sensitive', '-d', '-b', '-c']
>>> re.findall(r'\W(-[\w_]+)',s)
['-level_Sensitive']
| [
"Change the first qualifier to accept either a beginning anchor or a not-word, instead of only a not-word:\n>>> re.findall(r'(?:^|\\W)(-[\\w_]+)', s)\n['-edge_0triggered', '-level_Sensitive']\n\nThe ?: at the beginning of the group simply tells the regex engine to not treat that as a group for purposes of results.\n",
"r'(?:^|\\W)(-\\w+)'\n\n\\w already includes the underscore.\n",
"You could use a negative-lookbehind:\nre.findall(r'(?<!\\w)(-\\w+)', s)\n\nthe (?<!\\w) part means \"match only if not preceded by a word-character\".\n"
] | [
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003019564_python_regex.txt |
Q:
exec: 23: python: not found error?
im trying to build android from source on ubuntu 10.04. when i enter the repo command:
repo init -u git://android.git.kernel.org/platform/manifest.git -b eclair
it get this error back
exec: 23: python: not found
any ideas.
A:
You should check your python instalation as the repo command is an python script made by Google to interact with git repositories.
If you do have python installed it is possible that it is not in your shell path or you are using a diferent version than required by repo, ie. you have version 3 while repo requires version 2.5 (just an example, I'm not sure what version repo uses).
| exec: 23: python: not found error? | im trying to build android from source on ubuntu 10.04. when i enter the repo command:
repo init -u git://android.git.kernel.org/platform/manifest.git -b eclair
it get this error back
exec: 23: python: not found
any ideas.
| [
"You should check your python instalation as the repo command is an python script made by Google to interact with git repositories.\nIf you do have python installed it is possible that it is not in your shell path or you are using a diferent version than required by repo, ie. you have version 3 while repo requires version 2.5 (just an example, I'm not sure what version repo uses).\n"
] | [
0
] | [] | [] | [
"android",
"python"
] | stackoverflow_0003019742_android_python.txt |
Q:
how to import the parent model on gae-python
main:.
├─a
│ ├─__init__.py
│ └─aa.py
├─b
│ ├─__init__.py
│ └─bb.py
└─cc.py
if i am in aa.py , how to import cc.py ?
this is my code ,but it is error :
from main import cc
what should i do .
thanks
updated
in normal python file (not on gae),i can use this code :
import os,sys
dirname=os.path.dirname
path=os.path.join(dirname(dirname(__file__)))
sys.path.insert(0,path)
import cc
print cc.c
but on gae , it show error :
ImportError: No module named cc
A:
I don't understand how the code you've shown can possibly be failing for you. Trying to reproduce your problem, I built the following pared-to-the-bone project:
$ ls -lR
total 32
-rw-r--r-- 1 aleax staff 0 Jun 10 21:20 __init__.py
drwxr-xr-x 4 aleax staff 136 Jun 10 21:28 a
-rw-r-----@ 1 aleax staff 107 Jun 10 21:27 app.yaml
-rw-r--r-- 1 aleax staff 21 Jun 10 21:20 cc.py
-rw-r--r-- 1 aleax staff 471 Jun 10 21:25 index.yaml
-rw-r--r-- 1 aleax staff 75 Jun 10 21:20 main.py
./a:
total 8
-rw-r--r-- 1 aleax staff 0 Jun 10 21:20 __init__.py
-rw-r--r-- 1 aleax staff 130 Jun 10 21:20 aa.py
Here are the nonempty Python files:
$ for f in main.py cc.py a/aa.py; do echo "File: $f"; cat $f; echo; done
File: main.py
print 'Content-Type: text/plain'
print ''
print 'in main'
from a import aa
File: cc.py
print 'in cc'
c = 23
File: a/aa.py
import os, sys
dirname=os.path.dirname
path=os.path.join(dirname(dirname(__file__)))
sys.path.insert(0,path)
import cc
print cc.c
$
It runs just fine, as predicted, showing (both when run locally on the SDK and when run on google's servers at appspot.com):
in main
in cc
23
So there must be some other error in parts of your code that you're not showing us. Please confirm this by reproducing this tiny project and trying it both locally and on appspot.com and let us know how it works (or fails...?) for you.
| how to import the parent model on gae-python | main:.
├─a
│ ├─__init__.py
│ └─aa.py
├─b
│ ├─__init__.py
│ └─bb.py
└─cc.py
if i am in aa.py , how to import cc.py ?
this is my code ,but it is error :
from main import cc
what should i do .
thanks
updated
in normal python file (not on gae),i can use this code :
import os,sys
dirname=os.path.dirname
path=os.path.join(dirname(dirname(__file__)))
sys.path.insert(0,path)
import cc
print cc.c
but on gae , it show error :
ImportError: No module named cc
| [
"I don't understand how the code you've shown can possibly be failing for you. Trying to reproduce your problem, I built the following pared-to-the-bone project:\n$ ls -lR\ntotal 32\n-rw-r--r-- 1 aleax staff 0 Jun 10 21:20 __init__.py\ndrwxr-xr-x 4 aleax staff 136 Jun 10 21:28 a\n-rw-r-----@ 1 aleax staff 107 Jun 10 21:27 app.yaml\n-rw-r--r-- 1 aleax staff 21 Jun 10 21:20 cc.py\n-rw-r--r-- 1 aleax staff 471 Jun 10 21:25 index.yaml\n-rw-r--r-- 1 aleax staff 75 Jun 10 21:20 main.py\n\n./a:\ntotal 8\n-rw-r--r-- 1 aleax staff 0 Jun 10 21:20 __init__.py\n-rw-r--r-- 1 aleax staff 130 Jun 10 21:20 aa.py\n\nHere are the nonempty Python files:\n$ for f in main.py cc.py a/aa.py; do echo \"File: $f\"; cat $f; echo; done\nFile: main.py\nprint 'Content-Type: text/plain'\nprint ''\nprint 'in main'\nfrom a import aa\n\nFile: cc.py\nprint 'in cc'\nc = 23\n\nFile: a/aa.py\nimport os, sys\ndirname=os.path.dirname\npath=os.path.join(dirname(dirname(__file__)))\nsys.path.insert(0,path)\nimport cc\nprint cc.c\n$ \n\nIt runs just fine, as predicted, showing (both when run locally on the SDK and when run on google's servers at appspot.com):\nin main\nin cc\n23\n\nSo there must be some other error in parts of your code that you're not showing us. Please confirm this by reproducing this tiny project and trying it both locally and on appspot.com and let us know how it works (or fails...?) for you.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"import",
"model",
"parent",
"python"
] | stackoverflow_0003019944_google_app_engine_import_model_parent_python.txt |
Q:
to overcome type error?
i have a file of this format:
3.334 1
2.345 1
1.453 1
3.343 1
and so on
but in middle at times in file there are few number which are not in float format and i receive type msg when i run them performation some operation..
I want to give a condition that:
if(not in float format):
continue
else:
perform operation
please tell me how to put the condtion
A:
You can use an exception handler:
try:
f = float(thing)
except ValueError:
# This is not a float
f = 0.0
ValueError is thrown by invalid conversions. You should have seen it in your application traceback when an invalid float value conversion was tried.
| to overcome type error? | i have a file of this format:
3.334 1
2.345 1
1.453 1
3.343 1
and so on
but in middle at times in file there are few number which are not in float format and i receive type msg when i run them performation some operation..
I want to give a condition that:
if(not in float format):
continue
else:
perform operation
please tell me how to put the condtion
| [
"You can use an exception handler:\ntry:\n f = float(thing)\nexcept ValueError:\n # This is not a float\n f = 0.0\n\nValueError is thrown by invalid conversions. You should have seen it in your application traceback when an invalid float value conversion was tried.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003020375_python.txt |
Q:
Why does "as" cause a SyntaxError in an "except" statement in Jython 2.5?
I got the following syntax error at the following line when I run my program in jython:
except Exception as detail:
SyntaxError: mismatched input 'as' expecting COLON
but on python is it ok? What is wrong? I am trying to use the stanford pos tagger api (java) in my python program. Are there other ways?
A:
There are 2 current versions of Jython: the 2.5 version is the stable one, and 2.7 is a release candidate. The as syntax for except appeared in CPython 2.6 and thus will be supported in Jython 2.7; I guess you're using Jython 2.5,
You can use the older (Python 3 incompatible) except syntax in Jython 2.5:
except Exception, detail:
| Why does "as" cause a SyntaxError in an "except" statement in Jython 2.5? | I got the following syntax error at the following line when I run my program in jython:
except Exception as detail:
SyntaxError: mismatched input 'as' expecting COLON
but on python is it ok? What is wrong? I am trying to use the stanford pos tagger api (java) in my python program. Are there other ways?
| [
"There are 2 current versions of Jython: the 2.5 version is the stable one, and 2.7 is a release candidate. The as syntax for except appeared in CPython 2.6 and thus will be supported in Jython 2.7; I guess you're using Jython 2.5,\nYou can use the older (Python 3 incompatible) except syntax in Jython 2.5:\nexcept Exception, detail:\n\n"
] | [
15
] | [] | [] | [
"jython",
"python",
"python_2.x"
] | stackoverflow_0003020966_jython_python_python_2.x.txt |
Q:
Problem about python import with error
I have write a small python module with one class and two functions. The skeleton of the module is as following:
#file name: test_module.py
class TestClass:
@classmethod
def method1(cls, param1):
#to do something
pass
def __init__(self, param1):
#to do something
...
def fun1(*params):
#to do something
...
def fun2(*params):
#to do something
...
Another py file is a small script which imports function and class from the module, as following:
import sys
from test_module import TestClass, fun1, fun2
def main(sys_argv):
li = range(5)
inst1 = TestClass(li)
fun1(inst1)
fun2(inst1)
return
if __name__ == "__main__":
main(sys.argv)
But when I execute the script, it is broken with following message:
from: can't read
/var/mail/test_module
./script.py: line 4: syntax error
near unexpected token `('
./script.py: line 4: `def
main(sys_argv):'
I am not sure what the problem is. Is it a problem with import? But when I try to import the module in ipython, everything is just ok.
A:
Add a proper shebang line to your "small script". It's being interpreted as a shell script.
| Problem about python import with error | I have write a small python module with one class and two functions. The skeleton of the module is as following:
#file name: test_module.py
class TestClass:
@classmethod
def method1(cls, param1):
#to do something
pass
def __init__(self, param1):
#to do something
...
def fun1(*params):
#to do something
...
def fun2(*params):
#to do something
...
Another py file is a small script which imports function and class from the module, as following:
import sys
from test_module import TestClass, fun1, fun2
def main(sys_argv):
li = range(5)
inst1 = TestClass(li)
fun1(inst1)
fun2(inst1)
return
if __name__ == "__main__":
main(sys.argv)
But when I execute the script, it is broken with following message:
from: can't read
/var/mail/test_module
./script.py: line 4: syntax error
near unexpected token `('
./script.py: line 4: `def
main(sys_argv):'
I am not sure what the problem is. Is it a problem with import? But when I try to import the module in ipython, everything is just ok.
| [
"Add a proper shebang line to your \"small script\". It's being interpreted as a shell script.\n"
] | [
3
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003021010_import_python.txt |
Q:
Comparing two large sets of attributes
Suppose you have a Django view that has two functions:
The first function renders some XML using a XSLT stylesheet and produces a div with 1000 subelements like this:
<div id="myText">
<p id="p1"><a class="note-p1" href="#" style="display:none" target="bot">✽</a></strong>Lorem ipsum</p>
<p id="p2"><a class="note-p2" href="#" style="display:none" target="bot">✽</a></strong>Foo bar</p>
<p id="p3"><a class="note-p3" href="#" style="display:none" target="bot">✽</a></strong>Chocolate peanut butter</p>
(etc for 1000 lines)
<p id="p1000"><a class="note-p1000" href="#" style="display:none" target="bot">✽</a></strong>Go Yankees!</p>
</div>
The second function renders another XML document using another stylesheet to produce a div like this:
<div id="myNotes">
<p id="n1"><cite class="note-p1"><sup>1</sup><span>Trololo</span></cite></p>
<p id="n2"><cite class="note-p1"><sup>2</sup><span>Trololo</span></cite></p>
<p id="n3"><cite class="note-p2"><sup>3</sup><span>lololo</span></cite></p>
(etc for n lines)
<p id="n"><cite class="note-p885"><sup>n</sup><span>lololo</span></cite></p>
</div>
I need to see which elements in #myText have classes that match elements in #myNotes, and display them. I can do this using the following jQuery:
$('#myText').find('a').each(function() {
var $anchor = $(this);
$('#myNotes').find('cite').each(function() {
if($(this).attr('class') == $anchor.attr('class')) {
$anchor.show();
});
});
However this is incredibly slow and inefficient for a large number of comparisons.
What is the fastest/most efficient way to do this - is there a jQuery/js method that is reasonable for a large number of items? Or do I need to reengineer the Django code to do the work before passing it to the template?
A:
How about something like this:
http://jsfiddle.net/9eXws/
$('#myText a').each(function() {
$("#myNotes ." + $(this).attr('class')).show();
});
Instead of doing an inner each, it simply appends the class for the current a element into the selector, and performs a show() on any items found.
A:
For best-possible performance, make an index once and then re-use it:
function revealCite() {
var cites_index = $("#myText").data("cites_index");
// if no cached index exists, prepare one (one-time hit code section)
if (!cites_index) {
var cites = $("#myNotes cite");
var cites_count = cites.length();
var cites_index = {};
for (var i=0; i<cites_count; i++) {
var cite = cites[i], group = cites_index[cite.className];
if (!group) cites_index[cite.className] = [];
group.push(cite);
}
$("#myText").data("cites_index", cites_index);
}
// use the index to work with related elements ("this" must be an <a> element)
$(cites_index[this.className]).show();
}
Now trigger the above function any way you like:
$("#myText a").each(revealCite);
PS: You could also do this, in place of the for loop:
cites.each( function() {
var group = cites_index[this.className];
if (!group) cites_index[this.className] = [];
group.push(this);
});
But it's the same number lof lines of code, and probably is a bit slower.
A:
I think the inner find is redundantly re-executing for every iteration of the outer each. Try storing the matched elements in a variable before the looping commences. I've also tweaked your solution to get class names via the DOM attribute as opposed to using jQuery's attr:
var $cites = $('#myNotes').find('cite');
$('#myText').find('a').each(function() {
var anchor = this;
$cites.each(function() {
if(this.className == anchor.className) {
$anchor.show();
});
});
A:
Instead of always looping through every element and comparing each of them, you should use Jquery's selectors to do the search for you.
This should work significantly faster:
$('#myText > a').each(function() {
var $anchor = $(this);
var anchor_class = $(this).attr('class');
var elements = $('#myNotes > cite[class=' + anchor_class + ']');
if (elements[0] != undefined) {
$anchor.show();
}
});
| Comparing two large sets of attributes | Suppose you have a Django view that has two functions:
The first function renders some XML using a XSLT stylesheet and produces a div with 1000 subelements like this:
<div id="myText">
<p id="p1"><a class="note-p1" href="#" style="display:none" target="bot">✽</a></strong>Lorem ipsum</p>
<p id="p2"><a class="note-p2" href="#" style="display:none" target="bot">✽</a></strong>Foo bar</p>
<p id="p3"><a class="note-p3" href="#" style="display:none" target="bot">✽</a></strong>Chocolate peanut butter</p>
(etc for 1000 lines)
<p id="p1000"><a class="note-p1000" href="#" style="display:none" target="bot">✽</a></strong>Go Yankees!</p>
</div>
The second function renders another XML document using another stylesheet to produce a div like this:
<div id="myNotes">
<p id="n1"><cite class="note-p1"><sup>1</sup><span>Trololo</span></cite></p>
<p id="n2"><cite class="note-p1"><sup>2</sup><span>Trololo</span></cite></p>
<p id="n3"><cite class="note-p2"><sup>3</sup><span>lololo</span></cite></p>
(etc for n lines)
<p id="n"><cite class="note-p885"><sup>n</sup><span>lololo</span></cite></p>
</div>
I need to see which elements in #myText have classes that match elements in #myNotes, and display them. I can do this using the following jQuery:
$('#myText').find('a').each(function() {
var $anchor = $(this);
$('#myNotes').find('cite').each(function() {
if($(this).attr('class') == $anchor.attr('class')) {
$anchor.show();
});
});
However this is incredibly slow and inefficient for a large number of comparisons.
What is the fastest/most efficient way to do this - is there a jQuery/js method that is reasonable for a large number of items? Or do I need to reengineer the Django code to do the work before passing it to the template?
| [
"How about something like this:\nhttp://jsfiddle.net/9eXws/\n$('#myText a').each(function() {\n $(\"#myNotes .\" + $(this).attr('class')).show();\n});\n\nInstead of doing an inner each, it simply appends the class for the current a element into the selector, and performs a show() on any items found.\n",
"For best-possible performance, make an index once and then re-use it:\nfunction revealCite() {\n var cites_index = $(\"#myText\").data(\"cites_index\");\n\n // if no cached index exists, prepare one (one-time hit code section)\n if (!cites_index) {\n var cites = $(\"#myNotes cite\");\n var cites_count = cites.length();\n var cites_index = {};\n\n for (var i=0; i<cites_count; i++) {\n var cite = cites[i], group = cites_index[cite.className];\n if (!group) cites_index[cite.className] = [];\n group.push(cite);\n }\n $(\"#myText\").data(\"cites_index\", cites_index);\n }\n\n // use the index to work with related elements (\"this\" must be an <a> element)\n $(cites_index[this.className]).show();\n}\n\nNow trigger the above function any way you like:\n$(\"#myText a\").each(revealCite);\n\nPS: You could also do this, in place of the for loop:\ncites.each( function() {\n var group = cites_index[this.className];\n if (!group) cites_index[this.className] = [];\n group.push(this);\n});\n\nBut it's the same number lof lines of code, and probably is a bit slower.\n",
"I think the inner find is redundantly re-executing for every iteration of the outer each. Try storing the matched elements in a variable before the looping commences. I've also tweaked your solution to get class names via the DOM attribute as opposed to using jQuery's attr:\nvar $cites = $('#myNotes').find('cite');\n$('#myText').find('a').each(function() {\n var anchor = this;\n $cites.each(function() {\n if(this.className == anchor.className) {\n $anchor.show();\n });\n});\n\n",
"Instead of always looping through every element and comparing each of them, you should use Jquery's selectors to do the search for you.\nThis should work significantly faster:\n$('#myText > a').each(function() {\n var $anchor = $(this);\n var anchor_class = $(this).attr('class');\n var elements = $('#myNotes > cite[class=' + anchor_class + ']');\n if (elements[0] != undefined) {\n $anchor.show();\n }\n});\n\n"
] | [
1,
1,
0,
0
] | [] | [] | [
"django",
"jquery",
"python",
"xml"
] | stackoverflow_0003017714_django_jquery_python_xml.txt |
Q:
PyQt4 Move QTableWidget row with widgets
I have the following method in my PyQt4 app. r2 is the number of row to move, and r1 is the position where it should be moved. To clarify: the table is filled with cellWidgets, not widgetItems.
def move_row(self, r1, r2):
tt = self.tableWidget
tt.insertRow(r1)
for c in range(tt.columnCount()):
tt.setCellWidget(r1, c, tt.cellWidget(r2 + 1, c))
tt.removeRow(r2 + 1) # <--- ???
If I comment out the last line, it behaves as expected: the new row is inserted at position r1, it is filled with widgets from r2 (now it's r2+1), and the r2+1 row is empty. If I even hide this row, it behaves well, though it is not what I want (I have the rows numbered, and I don't want this hidden row to occupy the number).
But if I remove the row, the widgets initially owned by it disappear. Looks like their ownership is taken on first placement, and is not changed after the move.
Any ideas?
A:
I finally ended up with widgets values copying.
| PyQt4 Move QTableWidget row with widgets | I have the following method in my PyQt4 app. r2 is the number of row to move, and r1 is the position where it should be moved. To clarify: the table is filled with cellWidgets, not widgetItems.
def move_row(self, r1, r2):
tt = self.tableWidget
tt.insertRow(r1)
for c in range(tt.columnCount()):
tt.setCellWidget(r1, c, tt.cellWidget(r2 + 1, c))
tt.removeRow(r2 + 1) # <--- ???
If I comment out the last line, it behaves as expected: the new row is inserted at position r1, it is filled with widgets from r2 (now it's r2+1), and the r2+1 row is empty. If I even hide this row, it behaves well, though it is not what I want (I have the rows numbered, and I don't want this hidden row to occupy the number).
But if I remove the row, the widgets initially owned by it disappear. Looks like their ownership is taken on first placement, and is not changed after the move.
Any ideas?
| [
"I finally ended up with widgets values copying.\n"
] | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0002964482_pyqt_pyqt4_python.txt |
Q:
send xml file to http using python
how can i send an xml file on my system to an http server using python standard library??
A:
import urllib
URL = "http://host.domain.tld/resource"
XML = "<xml />"
parameter = urllib.urlencode({'XML': XML})
a) using HTTP POST
response = urllib.urlopen(URL, parameter)
print response.read()
b) using HTTP GET
response = urllib.urlopen(URL + "?%s" % parameter)
print response.read()
That would be the simplest solution.
A:
You can achieve that through a standard http post request.
| send xml file to http using python | how can i send an xml file on my system to an http server using python standard library??
| [
"import urllib\n\nURL = \"http://host.domain.tld/resource\"\nXML = \"<xml />\"\n\nparameter = urllib.urlencode({'XML': XML})\n\na) using HTTP POST \nresponse = urllib.urlopen(URL, parameter)\nprint response.read()\n\nb) using HTTP GET\nresponse = urllib.urlopen(URL + \"?%s\" % parameter)\nprint response.read()\n\nThat would be the simplest solution.\n",
"You can achieve that through a standard http post request.\n"
] | [
9,
1
] | [] | [] | [
"http",
"python",
"xml"
] | stackoverflow_0003020979_http_python_xml.txt |
Q:
wav file manupalation
I want get the details of the wave such as its frames into a array of integers.
Using fname.getframes we can ge the properties of the frame and save in list or anything for writing into another wav or anything,but fname.getframes gives information not in integers some thing like a "/xt/x4/0w' etc..
But i want them in integer so that would be helpful for manupation and smoothening join of 2 wav files
A:
I don't know what library you're using, but it looks like it's probably returning a string of bytes. To get it into a list of integers, you could do something like this:
data = [ord(character) for character in data]
To convert it back, you could do something like this:
data = ''.join(chr(character) for character in data)
A:
If you need to convert the frame data into integers, you can create an array.array('h') (array of signed 16-bit words) and load it from the frame data using its .fromstring or .fromfile methods.
However, I'm almost sure that you can keep the frame data as they are, and manipulate them using functions in the audioop module.
A:
NumPy can load the data into arrays for easy manipulation. Or SciPy. I forget which.
| wav file manupalation | I want get the details of the wave such as its frames into a array of integers.
Using fname.getframes we can ge the properties of the frame and save in list or anything for writing into another wav or anything,but fname.getframes gives information not in integers some thing like a "/xt/x4/0w' etc..
But i want them in integer so that would be helpful for manupation and smoothening join of 2 wav files
| [
"I don't know what library you're using, but it looks like it's probably returning a string of bytes. To get it into a list of integers, you could do something like this:\ndata = [ord(character) for character in data]\n\nTo convert it back, you could do something like this:\ndata = ''.join(chr(character) for character in data)\n\n",
"If you need to convert the frame data into integers, you can create an array.array('h') (array of signed 16-bit words) and load it from the frame data using its .fromstring or .fromfile methods.\nHowever, I'm almost sure that you can keep the frame data as they are, and manipulate them using functions in the audioop module.\n",
"NumPy can load the data into arrays for easy manipulation. Or SciPy. I forget which.\n"
] | [
1,
1,
0
] | [] | [] | [
"python",
"wav"
] | stackoverflow_0003021046_python_wav.txt |
Q:
Help me sort programming languages a bit
so I asked here few days ago about C# and its principles. Now, if I may, I have some additional general questions about some languages, because for novice like me, it seems a bit confusing. To be exact I want to ask more about language functions capabilities than syntax and so.
To be honest, its just these special functions that bothers me and make me so confused. For example, C has its printf(), Pascal has writeln() and so. I know in basic the output in assembler of these functions would be similar, every language has more or less its special functions. For console output, for file manipulation, etc. But all these functions are de-facto part of its OS API, so why is for example in C distinguished between C standard library functions and (on Windows) WinAPI functions when even printf() has to use some Windows feature, call some of its function to actually show desired text on console window, becouse the actual "showing" is done by OS. Where is the line between language functions and system API?
Now languages I don't quite understand - Python, Ruby and similar. To be more specific, I know they are similar to java and C# in term they are compiled into bytecode. But, I do not unerstand what are its capabilities in term of building GUI applications. I saw tutorial for using Ruby to program GUI applications on Linux and Windows. But isn´t that just some kind of upgrade? I mean fram other tutorials It seemed like these languages was first intended for small scripts than building big applications.
I hope you understand why I am confused. If you do, please help me sort it out a bit, I have no one to ask.
A:
C is portable. That means that on different systems the assembler output for printf will be different... this is something the compiler does based on what your target system is. Write C code and compile as a Linux app and the output will be different than as a Win32 app, and also different than if you compile the exact same code for an iPhone or something like that.
Internally, the C standard libraries might wrap a call to Win32 API when you call printf, but that's not really your concern in most cases. The C standard library (like printf and other I/O for files and stuff) wraps the low-level OS or hardware code needed to do what you want.
It's worth noting the same effect happens in Java, but in a different way. At a broad level: In Java, the code you write always compiles to the same byte-code. But then when the JVM runs this byte-code, the JRE translates it to machine-specific instructions at run-time, rather than at compile-time on C.
A:
At the bottom you have the OS kernel itself - code that runs in a special CPU mode that allows direct access to otherwise protected resources. You will never have to deal with this unless you're an OS developer.
Then comes a do-not-cross line seperating this "kernel space" from "user space". Everything you do as "normal" developer is done in user space.
The OS kernel exports a limited number of very basic functions into user space, dubbed "system calls". Open a file, read / write a number of bytes, closing the file, for example.
Because these system calls usually require some Assembler code developers don't want to be bothered with, they are "wrapped" in (usually) C code functions: open(), read(), write(), close().
Now come two sets of APIs available to the developer: The OS API, and the standard language API.
The standard language API provides functions that can be used on any platform supporting the language: fopen(), fputc(), fgetc(), fclose(). It will also provide higher-level functions that make life easier: fprintf(), for example.
The OS API provides its own set of functions. These are not portable to a different operating system, but might be more intuitive to use, or more powerful, or merely different. OpenFile(), ReadFile(), WriteFile(), CloseFile(). Again, higher-level functions might be available, i.e. PrintLn().
The two sets of functions might partially rely on each other, or make system calls directly, but that shouldn't bother you too much. You should, however, decide beforehand which set of functions you will want to use for your project, because mixing the two sets - while not a mistake in itself - opens a whole new can of worms (i.e., potential errors).
A:
So.
For your first question, the interface between the C API and the OS API is the C runtime. On Windows this is some incarnation of MSVCRT.DLL, whereas on Linux this is glibc.
For the second, the native language for most GUI toolkits is either C or C++. Higher-level languages seeking to use them require bindings which translate back and forth between the language and the C/C++ API.
For the third, these high-level languages only appear to be used for "small scripts". The simple fact is that they are far more expressive than C or C++, which means that they have equal or more capabilities than a C or C++ program while being written in fewer lines of code.
A:
If I assume this is your central question:
Where is the line between language functions and system API?
Then imagine if you will this analogy:
OS API system calls are like lego bricks and lego components.
Programming 'functions' are merely an arrangement of many lego bricks. Such that the combination results in a tool.
Thus different languages may 'arrange' and create the tool in different ways.
If I asked you to create a car with lego's, you could come up with many different designs.
A:
C's printf() is a wrapper. You can use it and compile your code under any OS, but the resulting machine code will be different. In Windows, it might call some function inside the Windows API. In Linux, it will use the Linux API. You ask why is the Windows API distinguished. That's because, if you're programming for Windows, you can use it to do some OS-specific things like create GUIs, manipulate console text instead of just printing, asking for OS resources, and stuff like that. An API like that exists for Linux and Mac (and I guess all the other OS's) too, and they let you do more or less the same things. Unlike printf(), though, they are not portable.
You ask what is the line between language functions and the system API. The language functions simply call the OS's API. You can call these yourself, but then you won't be able to compile your code on different systems.
Python and Ruby (and some others) are interpreted. They are compiled to bytecode behind the scenes, but all the user sees is that double-clicking the source file will run it. No need to compile. That means, obviously, that they're slower than compiled languages. However, their dynamic nature makes for faster development, since you usually need less code to do the same thing (I said usually).
That doesn't mean these languages can't be used for "big" applications: There are GUI libraries for them. That's because these are general purpose languages, unlike some others like Bash.
| Help me sort programming languages a bit | so I asked here few days ago about C# and its principles. Now, if I may, I have some additional general questions about some languages, because for novice like me, it seems a bit confusing. To be exact I want to ask more about language functions capabilities than syntax and so.
To be honest, its just these special functions that bothers me and make me so confused. For example, C has its printf(), Pascal has writeln() and so. I know in basic the output in assembler of these functions would be similar, every language has more or less its special functions. For console output, for file manipulation, etc. But all these functions are de-facto part of its OS API, so why is for example in C distinguished between C standard library functions and (on Windows) WinAPI functions when even printf() has to use some Windows feature, call some of its function to actually show desired text on console window, becouse the actual "showing" is done by OS. Where is the line between language functions and system API?
Now languages I don't quite understand - Python, Ruby and similar. To be more specific, I know they are similar to java and C# in term they are compiled into bytecode. But, I do not unerstand what are its capabilities in term of building GUI applications. I saw tutorial for using Ruby to program GUI applications on Linux and Windows. But isn´t that just some kind of upgrade? I mean fram other tutorials It seemed like these languages was first intended for small scripts than building big applications.
I hope you understand why I am confused. If you do, please help me sort it out a bit, I have no one to ask.
| [
"C is portable. That means that on different systems the assembler output for printf will be different... this is something the compiler does based on what your target system is. Write C code and compile as a Linux app and the output will be different than as a Win32 app, and also different than if you compile the exact same code for an iPhone or something like that.\nInternally, the C standard libraries might wrap a call to Win32 API when you call printf, but that's not really your concern in most cases. The C standard library (like printf and other I/O for files and stuff) wraps the low-level OS or hardware code needed to do what you want.\nIt's worth noting the same effect happens in Java, but in a different way. At a broad level: In Java, the code you write always compiles to the same byte-code. But then when the JVM runs this byte-code, the JRE translates it to machine-specific instructions at run-time, rather than at compile-time on C.\n",
"At the bottom you have the OS kernel itself - code that runs in a special CPU mode that allows direct access to otherwise protected resources. You will never have to deal with this unless you're an OS developer.\nThen comes a do-not-cross line seperating this \"kernel space\" from \"user space\". Everything you do as \"normal\" developer is done in user space.\nThe OS kernel exports a limited number of very basic functions into user space, dubbed \"system calls\". Open a file, read / write a number of bytes, closing the file, for example.\nBecause these system calls usually require some Assembler code developers don't want to be bothered with, they are \"wrapped\" in (usually) C code functions: open(), read(), write(), close().\nNow come two sets of APIs available to the developer: The OS API, and the standard language API. \nThe standard language API provides functions that can be used on any platform supporting the language: fopen(), fputc(), fgetc(), fclose(). It will also provide higher-level functions that make life easier: fprintf(), for example.\nThe OS API provides its own set of functions. These are not portable to a different operating system, but might be more intuitive to use, or more powerful, or merely different. OpenFile(), ReadFile(), WriteFile(), CloseFile(). Again, higher-level functions might be available, i.e. PrintLn().\nThe two sets of functions might partially rely on each other, or make system calls directly, but that shouldn't bother you too much. You should, however, decide beforehand which set of functions you will want to use for your project, because mixing the two sets - while not a mistake in itself - opens a whole new can of worms (i.e., potential errors).\n",
"So.\nFor your first question, the interface between the C API and the OS API is the C runtime. On Windows this is some incarnation of MSVCRT.DLL, whereas on Linux this is glibc.\nFor the second, the native language for most GUI toolkits is either C or C++. Higher-level languages seeking to use them require bindings which translate back and forth between the language and the C/C++ API.\nFor the third, these high-level languages only appear to be used for \"small scripts\". The simple fact is that they are far more expressive than C or C++, which means that they have equal or more capabilities than a C or C++ program while being written in fewer lines of code.\n",
"If I assume this is your central question:\n\nWhere is the line between language functions and system API?\n\nThen imagine if you will this analogy:\nOS API system calls are like lego bricks and lego components.\nProgramming 'functions' are merely an arrangement of many lego bricks. Such that the combination results in a tool.\nThus different languages may 'arrange' and create the tool in different ways.\nIf I asked you to create a car with lego's, you could come up with many different designs.\n",
"C's printf() is a wrapper. You can use it and compile your code under any OS, but the resulting machine code will be different. In Windows, it might call some function inside the Windows API. In Linux, it will use the Linux API. You ask why is the Windows API distinguished. That's because, if you're programming for Windows, you can use it to do some OS-specific things like create GUIs, manipulate console text instead of just printing, asking for OS resources, and stuff like that. An API like that exists for Linux and Mac (and I guess all the other OS's) too, and they let you do more or less the same things. Unlike printf(), though, they are not portable.\nYou ask what is the line between language functions and the system API. The language functions simply call the OS's API. You can call these yourself, but then you won't be able to compile your code on different systems.\nPython and Ruby (and some others) are interpreted. They are compiled to bytecode behind the scenes, but all the user sees is that double-clicking the source file will run it. No need to compile. That means, obviously, that they're slower than compiled languages. However, their dynamic nature makes for faster development, since you usually need less code to do the same thing (I said usually).\nThat doesn't mean these languages can't be used for \"big\" applications: There are GUI libraries for them. That's because these are general purpose languages, unlike some others like Bash.\n"
] | [
2,
2,
1,
1,
0
] | [
"\nTo be more specific, I know they are similiar to java and C# in term they are compiled into \n bytecode.\n\nRuby and Python are both interpreted languages, http://en.wikipedia.org/wiki/Interpreted_language, and their code is not translated into bytecode prior the execution.\n"
] | [
-2
] | [
"c",
"programming_languages",
"python",
"ruby"
] | stackoverflow_0003021652_c_programming_languages_python_ruby.txt |
Q:
Defining the hash of an object as the sum of hashes of its members
I have a class that represents undirected edges in a graph. Every edge has two members vertex1 and vertex2 representing the vertices it connects. The problem is, that an edge can be specified two directions. My idea was now to define the hash of an edge as the sum of the hashes of its vertices. This way, the direction plays no role anymore, the hash would be the same. Are there any pitfalls with that?
A:
I have had to solve a similar problem and found that using the sum of hashes as a hash results in too many collisions. The distribution of the sum of hashes is just not spread out enough.
I found that using the product of hashes resulted in much less collisions. This of course depends on the nature of the hashes for the individual vertices.
Set up a test bed and test a few symmetric hash functions and then choose the best based on collisions.
You could try
h(x,y) = x+y
h(x,y) = x*y
h(x,y) = x * y + (x ^ y)
h(x,y) = x *y + x + y
where x^y = min(x,y)
| Defining the hash of an object as the sum of hashes of its members | I have a class that represents undirected edges in a graph. Every edge has two members vertex1 and vertex2 representing the vertices it connects. The problem is, that an edge can be specified two directions. My idea was now to define the hash of an edge as the sum of the hashes of its vertices. This way, the direction plays no role anymore, the hash would be the same. Are there any pitfalls with that?
| [
"I have had to solve a similar problem and found that using the sum of hashes as a hash results in too many collisions. The distribution of the sum of hashes is just not spread out enough. \nI found that using the product of hashes resulted in much less collisions. This of course depends on the nature of the hashes for the individual vertices.\nSet up a test bed and test a few symmetric hash functions and then choose the best based on collisions.\nYou could try\nh(x,y) = x+y\nh(x,y) = x*y\nh(x,y) = x * y + (x ^ y)\nh(x,y) = x *y + x + y\n\nwhere x^y = min(x,y)\n"
] | [
3
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0003021868_hash_python.txt |
Q:
using remove on nested lists
n=[['dgd','sd','gsg'],['fsdsdf','sds','sdf']]
>>> n.remove('sd')
if i have a nested list like above and want to remove 'sd'.how can i doing the above thing is giving an error??
A:
n[0].remove('sd')
or
for i in n:
try:
i.remove('sd')
except ValueError:
pass
A:
When you have nested lists you need to index the top level list to get to the child lists, only then can you use list operations on the child lists. So you need something like:
n[0].remove('sd')
The code you have is trying to remove the string : 'sd' from a list that only contains two lists: ['dgd','sd','gsg'] and ['fsdsdf','sds','sdf'].
Simply calling n.remove('sd') would work on nest lists if Python performed automatic tree recursion on nested collections which it does not.
| using remove on nested lists | n=[['dgd','sd','gsg'],['fsdsdf','sds','sdf']]
>>> n.remove('sd')
if i have a nested list like above and want to remove 'sd'.how can i doing the above thing is giving an error??
| [
"n[0].remove('sd')\n\nor\nfor i in n:\n try:\n i.remove('sd')\n except ValueError:\n pass\n\n",
"When you have nested lists you need to index the top level list to get to the child lists, only then can you use list operations on the child lists. So you need something like:\nn[0].remove('sd')\n\nThe code you have is trying to remove the string : 'sd' from a list that only contains two lists: ['dgd','sd','gsg'] and ['fsdsdf','sds','sdf'].\nSimply calling n.remove('sd') would work on nest lists if Python performed automatic tree recursion on nested collections which it does not.\n"
] | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003021167_python.txt |
Q:
MySQL Module for Python
What is a good, and easy to install MySQL module for Python? Especially for Mac OS X (in terms of installation)?
A:
I think you should consider to install MacPorts, it will save time for this case and in the future.
Installing py-mysql is a matter of:
sudo port install py-mysql
| MySQL Module for Python | What is a good, and easy to install MySQL module for Python? Especially for Mac OS X (in terms of installation)?
| [
"I think you should consider to install MacPorts, it will save time for this case and in the future.\nInstalling py-mysql is a matter of:\nsudo port install py-mysql\n\n"
] | [
1
] | [] | [] | [
"module",
"mysql",
"python",
"sql"
] | stackoverflow_0003022080_module_mysql_python_sql.txt |
Q:
What's a better choice for SQL-backed number crunching - Ruby 1.9, Python 2, Python 3, or PHP 5.3?
Criteria for 'better': fast in math and simple (few fields, many records) db transactions, convenient to develop/read/extend, flexible, connectible.
The task is to use a common web development scripting language to process and calculate long time series and multidimensional surfaces (mostly selecting/inserting sets of floats and doing maths with them).
The choice is Ruby 1.9, Python 2, Python 3, PHP 5.3, Perl 5.12, or JavaScript (node.js).
All the data is to be stored in a relational database (due to its heavily multidimensional nature); all the communication with outer world is to be done by means of web services.
A:
I would suggest Python with it's great Scientifical/Mathematical libraries (SciPy, NumPy). Otherwise the languages are not differing so much, although I doubt that Ruby, PHP or JS can keep up with the speed of Python or Perl.
And what the comments below here say: at this moment, go for the latest Python2 (which is Python2.7). This has mature versions of all needed libraries, and if you follow the coding guidelines, transferring some day to Python 3 will be only a small pain.
A:
The best option is probably the language you're most familiar with. My second consideration would be if you need to use any special maths libraries and whether they're supported in each of the languages.
| What's a better choice for SQL-backed number crunching - Ruby 1.9, Python 2, Python 3, or PHP 5.3? | Criteria for 'better': fast in math and simple (few fields, many records) db transactions, convenient to develop/read/extend, flexible, connectible.
The task is to use a common web development scripting language to process and calculate long time series and multidimensional surfaces (mostly selecting/inserting sets of floats and doing maths with them).
The choice is Ruby 1.9, Python 2, Python 3, PHP 5.3, Perl 5.12, or JavaScript (node.js).
All the data is to be stored in a relational database (due to its heavily multidimensional nature); all the communication with outer world is to be done by means of web services.
| [
"I would suggest Python with it's great Scientifical/Mathematical libraries (SciPy, NumPy). Otherwise the languages are not differing so much, although I doubt that Ruby, PHP or JS can keep up with the speed of Python or Perl.\nAnd what the comments below here say: at this moment, go for the latest Python2 (which is Python2.7). This has mature versions of all needed libraries, and if you follow the coding guidelines, transferring some day to Python 3 will be only a small pain.\n",
"The best option is probably the language you're most familiar with. My second consideration would be if you need to use any special maths libraries and whether they're supported in each of the languages. \n"
] | [
10,
4
] | [] | [] | [
"math",
"performance",
"php",
"python",
"ruby"
] | stackoverflow_0003022232_math_performance_php_python_ruby.txt |
Q:
working on django development server but not on apache
i am facing an issue with the apache server, we have written the code, in which if the url entered in the form field is valid it will display an error message, when i run the code through django developement server it works fine, displays the error message, but when running through apache, then does not show the error message just returns back to that page itself. here is the code below of both the python and the html:
objc= {
"addRecipeBttn": "/project/add",
"addRecipeUrlBttn": "/project/add/import",
}
def __showAddRecipe__(request):
global objc
#global objc
if "userid" in request.session:
objc["ErrorMsgURL"]= ""
try:
urlList= request.POST
URL= str(urlList['url'])
URL= URL.strip('http://')
URL= "http://" + URL
recipe= __addRecipeUrl__(URL)
if (recipe == 'FailToOpenURL') or (recipe == 'Invalid-website-URL'):
#request.session["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
objc["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
print "here global_context =", objc
return HttpResponseRedirect("/project/add/import/")
#return render_to_response('addRecipeUrl.html', objc, context_instance = RequestContext(request))
else:
objc["recipe"] = recipe
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
except:
objc["recipe"] = ""
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
else:
login_redirect['next']= "/project/add/"
return HttpResponseRedirect("/project/login")
def __showAddRecipeUrl__(request):
global objc
if "userid" in request.session:
return render_to_response('addRecipeUrl.html',
objc,
context_instance = RequestContext(request))
else:
login_redirect['next']= "/project/add/import/"
return HttpResponseRedirect("/project/login")
_
The HTML file:-
kindly check and let me know if anyone can help on this issue, its working on django development server.
Thank you
Suhail
A:
hey guys, thanks for the support, the issue is resolved, i did it this way.
def showAddRecipe(request):
#global objc
if "userid" in request.session:
objc["ErrorMsgURL"]= ""
try:
urlList= request.POST
URL= str(urlList['url'])
URL= URL.strip('http://')
URL= "http://" + URL
recipe= __addRecipeUrl__(URL)
if (recipe == 'FailToOpenURL') or (recipe == 'Invalid-website-URL'):
#request.session["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
objc["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
print "here global_context =", objc
arurl= HttpResponseRedirect("/project/add/import/")
arurl['ErrorMsgURL']= objc["ErrorMsgURL"]
return (arurl)
else:
objc["recipe"] = recipe
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
except:
objc["recipe"] = ""
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
else:
login_redirect['next']= "/project/add/"
return HttpResponseRedirect("/project/login")
| working on django development server but not on apache | i am facing an issue with the apache server, we have written the code, in which if the url entered in the form field is valid it will display an error message, when i run the code through django developement server it works fine, displays the error message, but when running through apache, then does not show the error message just returns back to that page itself. here is the code below of both the python and the html:
objc= {
"addRecipeBttn": "/project/add",
"addRecipeUrlBttn": "/project/add/import",
}
def __showAddRecipe__(request):
global objc
#global objc
if "userid" in request.session:
objc["ErrorMsgURL"]= ""
try:
urlList= request.POST
URL= str(urlList['url'])
URL= URL.strip('http://')
URL= "http://" + URL
recipe= __addRecipeUrl__(URL)
if (recipe == 'FailToOpenURL') or (recipe == 'Invalid-website-URL'):
#request.session["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
objc["ErrorMsgURL"]= "Kindly check URL, Please enter a valid URL"
print "here global_context =", objc
return HttpResponseRedirect("/project/add/import/")
#return render_to_response('addRecipeUrl.html', objc, context_instance = RequestContext(request))
else:
objc["recipe"] = recipe
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
except:
objc["recipe"] = ""
return render_to_response('addRecipe.html',
objc,
context_instance = RequestContext(request))
else:
login_redirect['next']= "/project/add/"
return HttpResponseRedirect("/project/login")
def __showAddRecipeUrl__(request):
global objc
if "userid" in request.session:
return render_to_response('addRecipeUrl.html',
objc,
context_instance = RequestContext(request))
else:
login_redirect['next']= "/project/add/import/"
return HttpResponseRedirect("/project/login")
_
The HTML file:-
kindly check and let me know if anyone can help on this issue, its working on django development server.
Thank you
Suhail
| [
"hey guys, thanks for the support, the issue is resolved, i did it this way.\ndef showAddRecipe(request):\n #global objc\n if \"userid\" in request.session:\n objc[\"ErrorMsgURL\"]= \"\"\n try:\n urlList= request.POST\n URL= str(urlList['url'])\n URL= URL.strip('http://')\n URL= \"http://\" + URL\n\n recipe= __addRecipeUrl__(URL)\n\n if (recipe == 'FailToOpenURL') or (recipe == 'Invalid-website-URL'):\n #request.session[\"ErrorMsgURL\"]= \"Kindly check URL, Please enter a valid URL\"\n objc[\"ErrorMsgURL\"]= \"Kindly check URL, Please enter a valid URL\"\n print \"here global_context =\", objc\n arurl= HttpResponseRedirect(\"/project/add/import/\")\n arurl['ErrorMsgURL']= objc[\"ErrorMsgURL\"]\n return (arurl)\n else:\n objc[\"recipe\"] = recipe\n return render_to_response('addRecipe.html',\n objc,\n context_instance = RequestContext(request))\n except:\n objc[\"recipe\"] = \"\"\n return render_to_response('addRecipe.html',\n objc,\n context_instance = RequestContext(request))\n else:\n login_redirect['next']= \"/project/add/\"\n return HttpResponseRedirect(\"/project/login\")\n\n"
] | [
1
] | [] | [] | [
"apache",
"django",
"python",
"url"
] | stackoverflow_0003021418_apache_django_python_url.txt |
Q:
Web application architecture, and application servers?
I'm building a web application, and I need to use an architecture that allows me to run it over two servers. The application scrapes information from other sites periodically, and on input from the end user. To do this I'm using Php+curl to scrape the information, Php or python to parse it and store the results in a MySQLDB.
Then I will use Python to run some algorithms on the data, this will happen both periodically and on input from the end user. I'm going to cache some of the results in the MySQL DB and sometimes if it is specific to the user, skip storing the data and serve it to the user.
I'm think of using Php for the website front end on a separate web server, running the Php spider, MySQL DB and python on another server.
What frame work(s) should I use for this kind of job? Is MVC and Cakephp a good solution? If so will I be able to control and monitor the Python code using it?
Thanks
A:
How do go about implementing this?
Too big a question for an answer here. Certainly you don't want 2 sets of code for the scraping (1 for scheduled, 1 for demand) in addition to the added complication, you really don't want to be running job which will take an indefinite time to complete within the thread generated by a request to your webserver - user requests for a scrape should be run via the scheduling mechanism and reported back to users (although if necessary you could use Ajax polling to give the illusion that it's happening in the same thread).
What frame work(s) should I use?
Frameworks are not magic bullets. And you shouldn't be choosing a framework based primarily on the nature of the application you are writing. Certainly if specific, critical functionality is precluded by a specific framework, then you are using the wrong framework - but in my experience that has never been the case - you just need to write some code yourself.
using something more complex than a cron job
Yes, a cron job is probably not the right way to go for lots of reasons. If it were me I'd look at writing a daemon which would schedule scrapes (and accept connections from web page scripts to enqueue additional scrapes). But I'd run the scrapes as separate processes.
Is MVC a good architecture for this? (I'm new to MVC, architectures etc.)
No. Don't start by thinking whether a pattern fits the application - patterns are a useful tool for teaching but describe what code is not what it will be
(Your application might include some MVC patterns - but it should also include lots of other ones).
C.
A:
I think you have already a clear Idea on how to organize your layers.
First of all you would need a Web Framework for your front-end.
You have many choices here, Cakephp afaik is a good choice and it is designed to force you to follow the design pattern MVC.
Then, you would need to design your database to store what users want to be spidered.
Your db will be accessed by your web application to store users requests, by your php script to know what to scrape and finally by your python batch to confirm to the users that the data requested is available.
A possible over-simplified scenario:
User register to your site
User commands to grab a random page from Wikipedia
Request is stored though CakePhp application to db
Cron php batch starts and checks db for new requests
Batch founds new request and scrapes from Wikipedia
Batch updates db with a scraped flag
Cron python batch starts and checks db for new scraped flag
Batch founds new scraped flag and parse Wikipedia to extract some tags
Batch updates db with a done flag
User founds the requested information on his profile.
| Web application architecture, and application servers? | I'm building a web application, and I need to use an architecture that allows me to run it over two servers. The application scrapes information from other sites periodically, and on input from the end user. To do this I'm using Php+curl to scrape the information, Php or python to parse it and store the results in a MySQLDB.
Then I will use Python to run some algorithms on the data, this will happen both periodically and on input from the end user. I'm going to cache some of the results in the MySQL DB and sometimes if it is specific to the user, skip storing the data and serve it to the user.
I'm think of using Php for the website front end on a separate web server, running the Php spider, MySQL DB and python on another server.
What frame work(s) should I use for this kind of job? Is MVC and Cakephp a good solution? If so will I be able to control and monitor the Python code using it?
Thanks
| [
"\nHow do go about implementing this? \n\nToo big a question for an answer here. Certainly you don't want 2 sets of code for the scraping (1 for scheduled, 1 for demand) in addition to the added complication, you really don't want to be running job which will take an indefinite time to complete within the thread generated by a request to your webserver - user requests for a scrape should be run via the scheduling mechanism and reported back to users (although if necessary you could use Ajax polling to give the illusion that it's happening in the same thread).\n\nWhat frame work(s) should I use?\n\nFrameworks are not magic bullets. And you shouldn't be choosing a framework based primarily on the nature of the application you are writing. Certainly if specific, critical functionality is precluded by a specific framework, then you are using the wrong framework - but in my experience that has never been the case - you just need to write some code yourself. \n\nusing something more complex than a cron job\n\nYes, a cron job is probably not the right way to go for lots of reasons. If it were me I'd look at writing a daemon which would schedule scrapes (and accept connections from web page scripts to enqueue additional scrapes). But I'd run the scrapes as separate processes. \n\nIs MVC a good architecture for this? (I'm new to MVC, architectures etc.)\n\nNo. Don't start by thinking whether a pattern fits the application - patterns are a useful tool for teaching but describe what code is not what it will be\n(Your application might include some MVC patterns - but it should also include lots of other ones).\nC.\n",
"I think you have already a clear Idea on how to organize your layers.\nFirst of all you would need a Web Framework for your front-end.\nYou have many choices here, Cakephp afaik is a good choice and it is designed to force you to follow the design pattern MVC.\nThen, you would need to design your database to store what users want to be spidered.\nYour db will be accessed by your web application to store users requests, by your php script to know what to scrape and finally by your python batch to confirm to the users that the data requested is available. \nA possible over-simplified scenario:\n\nUser register to your site \nUser commands to grab a random page from Wikipedia \nRequest is stored though CakePhp application to db \nCron php batch starts and checks db for new requests \nBatch founds new request and scrapes from Wikipedia \nBatch updates db with a scraped flag\nCron python batch starts and checks db for new scraped flag \nBatch founds new scraped flag and parse Wikipedia to extract some tags\nBatch updates db with a done flag\nUser founds the requested information on his profile.\n\n"
] | [
2,
1
] | [] | [] | [
"application_server",
"cakephp",
"model_view_controller",
"php",
"python"
] | stackoverflow_0003021921_application_server_cakephp_model_view_controller_php_python.txt |
Q:
Get table with maximum number of rows in a page using BeautifulSoup
Can anyone tell me how i can get the table in a HTML page which has a the most rows? I'm using BeautifulSoup.
There is one little problem though. Sometimes, there seems to be one table nested inside another.
<table>
<tr>
<td>
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<td>
</tr>
</table>
When the table.findAll('tr') code executes, it would count all the child rows for the table and the rows for the nested table under it. The parent table has just one row but the nested table has three and I would consider that to be the largest table. Below is the code that I'm using to dig out the largest table currently but it doesn't take the aforementioned scenario into consideration.
soup = BeautifulSoup(html)
#Get the largest table
largest_table = None
max_rows = 0
for table in soup.findAll('table'):
number_of_rows = len(table.findAll('tr'))
if number_of_rows > max_rows:
largest_table = table
max_rows = number_of_rows
I'm really lost with this. Any help guys?
Thanks in advance
A:
Calculate number_of_rows like that:
number_of_rows = len(table.findAll(lambda tag: tag.name == 'tr' and tag.findParent('table') == table))
| Get table with maximum number of rows in a page using BeautifulSoup | Can anyone tell me how i can get the table in a HTML page which has a the most rows? I'm using BeautifulSoup.
There is one little problem though. Sometimes, there seems to be one table nested inside another.
<table>
<tr>
<td>
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<td>
</tr>
</table>
When the table.findAll('tr') code executes, it would count all the child rows for the table and the rows for the nested table under it. The parent table has just one row but the nested table has three and I would consider that to be the largest table. Below is the code that I'm using to dig out the largest table currently but it doesn't take the aforementioned scenario into consideration.
soup = BeautifulSoup(html)
#Get the largest table
largest_table = None
max_rows = 0
for table in soup.findAll('table'):
number_of_rows = len(table.findAll('tr'))
if number_of_rows > max_rows:
largest_table = table
max_rows = number_of_rows
I'm really lost with this. Any help guys?
Thanks in advance
| [
"Calculate number_of_rows like that:\nnumber_of_rows = len(table.findAll(lambda tag: tag.name == 'tr' and tag.findParent('table') == table))\n\n"
] | [
3
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003020841_beautifulsoup_python.txt |
Q:
Python Application in right click menu of OS X
I know that there is the PyObjC bridge is OSX and what I want to do is to put a python application/script in the rightclick context menu of OS X. there is the OnMyCommand plugin but I dont think that supports python. I've had a look at how to do it in Carbon/ Objective-C and i'll admit it im a wuss and am just not smart enough yet to grok how to do it (I aint even close to groking it actually.)
Anybody got any idea's on how I might go about this?
Cheers
A:
Looking through the documentation for OnMyCommand (neat find by the way) I would say you shouldn't have any problem using a Python script. Just make sure the Python script is executable and in your PATH.
Going along with the example in 1, instead of executing touch you would simply execute your Python script.
| Python Application in right click menu of OS X | I know that there is the PyObjC bridge is OSX and what I want to do is to put a python application/script in the rightclick context menu of OS X. there is the OnMyCommand plugin but I dont think that supports python. I've had a look at how to do it in Carbon/ Objective-C and i'll admit it im a wuss and am just not smart enough yet to grok how to do it (I aint even close to groking it actually.)
Anybody got any idea's on how I might go about this?
Cheers
| [
"Looking through the documentation for OnMyCommand (neat find by the way) I would say you shouldn't have any problem using a Python script. Just make sure the Python script is executable and in your PATH.\nGoing along with the example in 1, instead of executing touch you would simply execute your Python script.\n"
] | [
1
] | [] | [] | [
"macos",
"objective_c",
"python"
] | stackoverflow_0003022691_macos_objective_c_python.txt |
Q:
Can Python ctypes load a 32bit C library on x86-64?
I have a 64 bit RHEL host with 32 bit libraries installed. One vendor has a 32 bit .so I'd like to load into Python using ctypes.
from ctypes import CDLL
CDLL('32bitdinosaur.so')
OSError: 32bitdinosaur.so: wrong ELF class: ELFCLASS32
Of course 64 bit libraries are OK. Eg:
CDLL('libc.so.6')
Works fine.
A:
It looks like the best way to do this is to have a 32 bit python in a separate process load the .so, and call the 32 bit python from a 64 bit Python.
| Can Python ctypes load a 32bit C library on x86-64? | I have a 64 bit RHEL host with 32 bit libraries installed. One vendor has a 32 bit .so I'd like to load into Python using ctypes.
from ctypes import CDLL
CDLL('32bitdinosaur.so')
OSError: 32bitdinosaur.so: wrong ELF class: ELFCLASS32
Of course 64 bit libraries are OK. Eg:
CDLL('libc.so.6')
Works fine.
| [
"It looks like the best way to do this is to have a 32 bit python in a separate process load the .so, and call the 32 bit python from a 64 bit Python.\n"
] | [
1
] | [] | [] | [
"32bit_64bit",
"ctypes",
"python"
] | stackoverflow_0003015970_32bit_64bit_ctypes_python.txt |
Q:
Python equivalent of C++ getline()
In C++ we can enter multiple lines by giving our own choice of delimiting character in the getline() function.. however I am not able to do the same in Python!! it has only raw_input() and sys.stdin.readline() methods that read till I press enter. Is there any way to customize this so that I can specify my own delimiter?
A:
Do you still want to press enter to create multiple lines? How do you end the input? Or do you want do specify multiple lines on a single line?
If the former, try looping raw_input() until something is written that tells it to stop:
lines = []
while True:
user_input = raw_input()
if user_input.strip() == "": # empty line signals stop
break
lines.append(user_input)
Or to specify multiple lines on a single line using a delimiter:
lines = raw_input().split(";")
A:
You can try modify this method a bit to use it and use it in your program.
First, import the linecache module:
import linecache
The linecache module allows you to access any line from any file. Of its three methods, the one you are likely to use the most is getline. The syntax for getline is as follows:
linecache.getline('filename', line_number)
If you have a file called 'myfile.txt' and would like to read line 138 from it, getline allows you to do so with ease.
retrieved_line = linecache.getline('myfile.txt', 138)
Then you can simply print retrieved_line or otherwise manipulate the data of line 138 without doing surgery on the file itself.
A:
You will need to implement such a function yourself. For example:
def getline(stream, delimiter="\n"):
def _gen():
while 1:
line = stream.readline()
if delimiter in line:
yield line[0:line.index(delimiter)]
break
else:
yield line
return "".join(_gen())
import sys
getline(sys.stdin, ".")
| Python equivalent of C++ getline() | In C++ we can enter multiple lines by giving our own choice of delimiting character in the getline() function.. however I am not able to do the same in Python!! it has only raw_input() and sys.stdin.readline() methods that read till I press enter. Is there any way to customize this so that I can specify my own delimiter?
| [
"Do you still want to press enter to create multiple lines? How do you end the input? Or do you want do specify multiple lines on a single line? \nIf the former, try looping raw_input() until something is written that tells it to stop:\nlines = []\nwhile True:\n user_input = raw_input()\n if user_input.strip() == \"\": # empty line signals stop\n break\n lines.append(user_input)\n\nOr to specify multiple lines on a single line using a delimiter:\nlines = raw_input().split(\";\")\n\n",
"You can try modify this method a bit to use it and use it in your program.\nFirst, import the linecache module:\nimport linecache\n\nThe linecache module allows you to access any line from any file. Of its three methods, the one you are likely to use the most is getline. The syntax for getline is as follows:\nlinecache.getline('filename', line_number)\n\nIf you have a file called 'myfile.txt' and would like to read line 138 from it, getline allows you to do so with ease.\nretrieved_line = linecache.getline('myfile.txt', 138)\n\nThen you can simply print retrieved_line or otherwise manipulate the data of line 138 without doing surgery on the file itself. \n",
"You will need to implement such a function yourself. For example:\ndef getline(stream, delimiter=\"\\n\"):\n def _gen():\n while 1:\n line = stream.readline()\n if delimiter in line:\n yield line[0:line.index(delimiter)]\n break\n else:\n yield line\n return \"\".join(_gen())\n\nimport sys\ngetline(sys.stdin, \".\")\n\n"
] | [
3,
2,
0
] | [] | [] | [
"c++",
"getline",
"python"
] | stackoverflow_0003022572_c++_getline_python.txt |
Q:
Launch an SWF full screen
I have a swf file (a flash game). I want to run some script to open it in full-screen mode. I'm not attached to any browser, but I do run Linux, so a bash, or generic answer is what I'm looking for. I'm also open to building a lite browser application if need-be.
A:
The SWF can be launched in full screen in several ways, here comes some suggested solutions:
1) You can open the SWF-file directly (works for me, in Firefox).
2) You can add a HTML page with this JavaScript that redirects to your SWF-file.
<script language="JavaScript" type="text/javascript">
document.location.href='packman.swf';
</script>
3) You can embed the SWF-file in a HTML page.
A:
i think this might do it if you put it in the initialization part:
Stage["displayState"]="fullScreen";
| Launch an SWF full screen | I have a swf file (a flash game). I want to run some script to open it in full-screen mode. I'm not attached to any browser, but I do run Linux, so a bash, or generic answer is what I'm looking for. I'm also open to building a lite browser application if need-be.
| [
"The SWF can be launched in full screen in several ways, here comes some suggested solutions:\n1) You can open the SWF-file directly (works for me, in Firefox).\n2) You can add a HTML page with this JavaScript that redirects to your SWF-file.\n<script language=\"JavaScript\" type=\"text/javascript\">\n document.location.href='packman.swf'; \n</script>\n\n3) You can embed the SWF-file in a HTML page.\n",
"i think this might do it if you put it in the initialization part:\nStage[\"displayState\"]=\"fullScreen\";\n"
] | [
1,
0
] | [] | [] | [
"bash",
"browser",
"firefox",
"flash",
"python"
] | stackoverflow_0002889561_bash_browser_firefox_flash_python.txt |
Q:
How to create temporary files in memory visible for other process, using python
I'm trying to write simple batch file generator in python. Batch file consist of about 30-50 lines of text and is passed to other applications. During the execution of script there a lot of calls to external applications. I want to create file in memory (like named pipes in win32). Is there any platform-independent way?
UPD:
Thanks for suggestions. Finally decided to use sockets for message passing between applications using cogen.
A:
If you don't mind running a separate server, I'd use Memcached. It's very simple to use and very robust.
http://memcached.org/
| How to create temporary files in memory visible for other process, using python | I'm trying to write simple batch file generator in python. Batch file consist of about 30-50 lines of text and is passed to other applications. During the execution of script there a lot of calls to external applications. I want to create file in memory (like named pipes in win32). Is there any platform-independent way?
UPD:
Thanks for suggestions. Finally decided to use sockets for message passing between applications using cogen.
| [
"If you don't mind running a separate server, I'd use Memcached. It's very simple to use and very robust.\nhttp://memcached.org/\n"
] | [
0
] | [] | [] | [
"memory",
"python",
"temporary_files"
] | stackoverflow_0003023438_memory_python_temporary_files.txt |
Q:
Python win32com - Automating Word - How to replace text in a text box?
I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4)
The first part of my replace method below works on everything except text in text boxes. The text just doesn't get selected. I notice when I go into Word manually and hit ctrl-A all of the text gets selected except for the text box.
Here's my code so far:
class Word:
def __init__(self,visible=0,screenupdating=0):
pythoncom.CoInitialize()
self.app=gencache.EnsureDispatch(WORD)
self.app.Visible = visible
self.app.DisplayAlerts = 0
self.app.ScreenUpdating = screenupdating
print 'Starting word'
def open(self,doc):
self.opendoc=os.path.basename(doc)
self.app.Documents.Open(FileName=doc)
def replace(self,source,target):
if target=='':target=' '
alltext=self.app.Documents(self.opendoc).Range(Start=0,End=self.app.Documents(self.opendoc).Characters.Count) #select all
alltext.Find.Text = source
alltext.Find.Replacement.Text = target
alltext.Find.Execute(Replace=1,Forward=True)
#Special handling to do replace in text boxes
#http://word.tips.net/Pages/T003879_Updating_a_Field_in_a_Text_Box.html
for shp in self.app.Documents(self.opendoc).Shapes:
if shp.TextFrame.HasText:
shp.TextFrame.TextRange.Find.Text = source
shp.TextFrame.TextRange.Find.Replacement.Text = target
shp.TextFrame.TextRange.Find.Execute(Replace=1,Forward=True)
#My Usage
word=Word(visible=1,screenupdating=1)
word.open(r'C:\Invoice Automation\testTB.doc')
word.replace('[PGN]','1')
The for shp in self.app .. section is my attempt to hit the text boxes. It seems to find the text box, but it doesn't replace anything.
A:
When I add text boxes to a word document, they are added inside a drawing canvas. Therefore the top level shape is the canvas, and the text boxes are contained within the canvas. You should use the CanvasItems method to access the objects in the canvas, ie the text boxes
The following example works for me. I created a word document with a single text box.
import win32com.client
word = win32com.client.Dispatch("Word.Application")
canvas = word.ActiveDocument.Shapes[0]
for item in canvas.CanvasItems:
print item.TextFrame.TextRange.Text
Update: answering OP's comment.
I think the problem with your code is that each line of code with Find creates a new Find object. You have to create and bind a Find object to a name, then modify its attributes and execute it. So in your code you should have:
find = shp.TextFrame.TextRange.Find
find.Text = source
find.Replacement.Text = target
find.Execute(Replace=1, Forward=True)
Or a single line:
shp.TextFrame.TextRange.Find.Execute(FindText=source, ReplaceWith=target, Replace=1, Forward=True)
Both of these methods work in my test code.
| Python win32com - Automating Word - How to replace text in a text box? | I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4)
The first part of my replace method below works on everything except text in text boxes. The text just doesn't get selected. I notice when I go into Word manually and hit ctrl-A all of the text gets selected except for the text box.
Here's my code so far:
class Word:
def __init__(self,visible=0,screenupdating=0):
pythoncom.CoInitialize()
self.app=gencache.EnsureDispatch(WORD)
self.app.Visible = visible
self.app.DisplayAlerts = 0
self.app.ScreenUpdating = screenupdating
print 'Starting word'
def open(self,doc):
self.opendoc=os.path.basename(doc)
self.app.Documents.Open(FileName=doc)
def replace(self,source,target):
if target=='':target=' '
alltext=self.app.Documents(self.opendoc).Range(Start=0,End=self.app.Documents(self.opendoc).Characters.Count) #select all
alltext.Find.Text = source
alltext.Find.Replacement.Text = target
alltext.Find.Execute(Replace=1,Forward=True)
#Special handling to do replace in text boxes
#http://word.tips.net/Pages/T003879_Updating_a_Field_in_a_Text_Box.html
for shp in self.app.Documents(self.opendoc).Shapes:
if shp.TextFrame.HasText:
shp.TextFrame.TextRange.Find.Text = source
shp.TextFrame.TextRange.Find.Replacement.Text = target
shp.TextFrame.TextRange.Find.Execute(Replace=1,Forward=True)
#My Usage
word=Word(visible=1,screenupdating=1)
word.open(r'C:\Invoice Automation\testTB.doc')
word.replace('[PGN]','1')
The for shp in self.app .. section is my attempt to hit the text boxes. It seems to find the text box, but it doesn't replace anything.
| [
"When I add text boxes to a word document, they are added inside a drawing canvas. Therefore the top level shape is the canvas, and the text boxes are contained within the canvas. You should use the CanvasItems method to access the objects in the canvas, ie the text boxes\nThe following example works for me. I created a word document with a single text box.\nimport win32com.client\n\nword = win32com.client.Dispatch(\"Word.Application\")\ncanvas = word.ActiveDocument.Shapes[0]\nfor item in canvas.CanvasItems:\n print item.TextFrame.TextRange.Text\n\n\nUpdate: answering OP's comment.\nI think the problem with your code is that each line of code with Find creates a new Find object. You have to create and bind a Find object to a name, then modify its attributes and execute it. So in your code you should have:\nfind = shp.TextFrame.TextRange.Find\nfind.Text = source\nfind.Replacement.Text = target\nfind.Execute(Replace=1, Forward=True)\n\nOr a single line:\nshp.TextFrame.TextRange.Find.Execute(FindText=source, ReplaceWith=target, Replace=1, Forward=True)\n\nBoth of these methods work in my test code.\n"
] | [
5
] | [] | [] | [
"ms_word",
"python",
"vba",
"win32com"
] | stackoverflow_0003022898_ms_word_python_vba_win32com.txt |
Q:
How to define multi-argument decorators within a class in 2.6
Generally don't do OO-programming in Python. This project requires it and am running into a bit of trouble. Here's my scratch code for attempting to figure out where it went wrong:
class trial(object):
def output( func, x ):
def ya( self, y ):
return func( self, x ) + y
return ya
def f1( func ):
return output( func, 1 )
@f1
def sum1( self, x ):
return x
which doesn't compile. I've attempted to add the @staticmethod tag to the "output" and "f1" functions but to no avail. Normally I'd do this
def output( func, x ):
def ya( y ):
return func( x ) + y
return ya
def f1( func ):
return output( func, 1 )
@f1
def sum1( x ):
return x
which does work. So how do I get this going in a class?
A:
There's no need for your method decorators to be a part of the class:
def output(meth, x):
def ya(self, y):
return meth(self, x) + y
return ya
def f1(meth):
return output(meth, 1)
class trial(object):
@f1
def sum1( self, x ):
return x
>>> trial().sum1(1)
2
I tend to use meth instead of func in decorators I know I'll be applying to methods, just to try to keep it straight in my own head.
A:
Try this ugly solution
class trial(object):
def __init__(self):
#doing this instead of @ statement
self.sum1 = self.f1(self.sum1)
def output(self, func, x ):
def ya(y):
return func(x) + y
return ya
def f1(self, func):
return self.output( func, 1 )
def sum1(self, x ):
return x
t = trial()
print t.sum1(5)
| How to define multi-argument decorators within a class in 2.6 | Generally don't do OO-programming in Python. This project requires it and am running into a bit of trouble. Here's my scratch code for attempting to figure out where it went wrong:
class trial(object):
def output( func, x ):
def ya( self, y ):
return func( self, x ) + y
return ya
def f1( func ):
return output( func, 1 )
@f1
def sum1( self, x ):
return x
which doesn't compile. I've attempted to add the @staticmethod tag to the "output" and "f1" functions but to no avail. Normally I'd do this
def output( func, x ):
def ya( y ):
return func( x ) + y
return ya
def f1( func ):
return output( func, 1 )
@f1
def sum1( x ):
return x
which does work. So how do I get this going in a class?
| [
"There's no need for your method decorators to be a part of the class:\ndef output(meth, x):\n def ya(self, y):\n return meth(self, x) + y\n return ya\n\ndef f1(meth):\n return output(meth, 1)\n\nclass trial(object):\n @f1\n def sum1( self, x ):\n return x\n\n>>> trial().sum1(1)\n2\n\nI tend to use meth instead of func in decorators I know I'll be applying to methods, just to try to keep it straight in my own head.\n",
"Try this ugly solution\nclass trial(object):\n\n def __init__(self):\n #doing this instead of @ statement\n self.sum1 = self.f1(self.sum1)\n\n def output(self, func, x ):\n def ya(y):\n return func(x) + y\n return ya\n\n def f1(self, func):\n return self.output( func, 1 )\n\n\n def sum1(self, x ):\n return x\n\nt = trial()\n\nprint t.sum1(5)\n\n"
] | [
5,
0
] | [
"No way. \nThis is a wrong design. \nFollow for The Zen of Python\nWhen you decorate a function calling the decorator by @ it must be already defined.\nYou must at first - define decorator and at the second step decorate a function.\n"
] | [
-2
] | [
"decorator",
"python"
] | stackoverflow_0003023448_decorator_python.txt |
Q:
How to process user supplied formulas?
I have a dictionary containing a set of key values available through a web application:
I want to process user supplied formulas like:
((value1+value3)/value4)*100
What would be the easiest way to get the formula calculated matching values with ones from the dictionary?
Consider this example:
#!/usr/bin/python
values={'value1':10,'value2':1245,'value3':674365,'value4':65432,'value5':131}
formula=raw_input('Please enter formula:')
If I supply the formula '((value1+value3)/value4)*100' how can I map the value1 etc to map value1 from the dictionary and calculate the result?
Cheers,
A:
eval can be used execute malicious code.
Do you trust your users? If so, you can pass values along as a global dict to be used by eval. Thus, eval can evaluate the user formula directly without any additional string manipulation:
values={'value1':10,'value2':1245,'value3':674365,'value4':65432,'value5':131}
formula=raw_input('Please enter formula:')
values=eval(formula,values)
print(values)
If you do not trust your potential users, you could use pyparsing:
The following is Paul McGuire's numeric expression parser, fourFn.py, wrapped in a class for easier use.
utils_parse_numeric.py:
from __future__ import division
from pyparsing import (Literal,CaselessLiteral,Word,Combine,Group,Optional,
ZeroOrMore,Forward,nums,alphas,oneOf)
import math
import operator
class NumericStringParser(object):
'''
Most of this code comes from the fourFn.py pyparsing example
'''
def pushFirst(self, strg, loc, toks ):
self.exprStack.append( toks[0] )
def pushUMinus(self, strg, loc, toks ):
if toks and toks[0]=='-':
self.exprStack.append( 'unary -' )
def __init__(self):
"""
expop :: '^'
multop :: '*' | '/'
addop :: '+' | '-'
integer :: ['+' | '-'] '0'..'9'+
atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'
factor :: atom [ expop factor ]*
term :: factor [ multop factor ]*
expr :: term [ addop term ]*
"""
point = Literal( "." )
e = CaselessLiteral( "E" )
fnumber = Combine( Word( "+-"+nums, nums ) +
Optional( point + Optional( Word( nums ) ) ) +
Optional( e + Word( "+-"+nums, nums ) ) )
ident = Word(alphas, alphas+nums+"_$")
plus = Literal( "+" )
minus = Literal( "-" )
mult = Literal( "*" )
div = Literal( "/" )
lpar = Literal( "(" ).suppress()
rpar = Literal( ")" ).suppress()
addop = plus | minus
multop = mult | div
expop = Literal( "^" )
pi = CaselessLiteral( "PI" )
expr = Forward()
atom = ((Optional(oneOf("- +")) +
(pi|e|fnumber|ident+lpar+expr+rpar).setParseAction(self.pushFirst))
| Optional(oneOf("- +")) + Group(lpar+expr+rpar)
).setParseAction(self.pushUMinus)
factor = Forward()
factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( self.pushFirst ) )
term = factor + ZeroOrMore( ( multop + factor ).setParseAction( self.pushFirst ) )
expr << term + ZeroOrMore( ( addop + term ).setParseAction( self.pushFirst ) )
self.bnf = expr
epsilon = 1e-12
self.opn = { "+" : operator.add,
"-" : operator.sub,
"*" : operator.mul,
"/" : operator.truediv,
"^" : operator.pow }
self.fn = { "sin" : math.sin,
"cos" : math.cos,
"tan" : math.tan,
"abs" : abs,
"trunc" : lambda a: int(a),
"round" : round,
"sgn" : lambda a: abs(a)>epsilon and cmp(a,0) or 0}
def evaluateStack(self, s ):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack( s )
if op in "+-*/^":
op2 = self.evaluateStack( s )
op1 = self.evaluateStack( s )
return self.opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op]( self.evaluateStack( s ) )
elif op[0].isalpha():
return 0
else:
return float( op )
def eval(self,num_string,parseAll=True):
self.exprStack=[]
results=self.bnf.parseString(num_string,parseAll)
val=self.evaluateStack( self.exprStack[:] )
return val
Then your script could do something like this:
import re
import utils_parse_numeric as upn
my_dict={
'number1':54,
'number2':1234,
'number3':778,
'number25':2109}
This uses the re module to substitute my_dict["numberXXX"] for 'numberXXX':
def callback(match):
num=match.group(1)
key='number{0}'.format(num)
val=my_dict[key]
return str(val)
astr='((number1+number3)/number2)*100'
astr=re.sub('number(\d+)',callback,astr)
and here's how the NumericStringParser can be used to safely evaluate numeric expressions:
nsp=upn.NumericStringParser()
result=nsp.eval(astr)
print(result)
This is much safer than using eval. All invalid expressions will raise a pyparsing.ParseException.
A:
After validating both the formula and the numbers value (f.e. via a regexp) you can do something like:
arr = {'num1':4, 'num2':5, 'num3':7}
formula = '(num1+num2)*num3'
for key, val in arr.items():
formula = formula.replace(key, str(val))
res = eval(formula)
print res
A:
Thanks for all the input. I personally found that lacopo's answer suites my situation best.
Here's a rough idea of the solution:
import sys
values={'one':10,'two':1245,'three':674365,'four':65432,'five':131}
print str(values)
formula=raw_input('Please enter formula:')
for key, val in values.items():
formula = formula.replace(key, str(val))
whitelist=[ '+','-','/','*','^','(',')' ]
to_evaluate=re.findall('\D',formula)
to_evaluate=list(set(to_evaluate))
for element in to_evaluate:
if not element in whitelist:
print "Formula contains an invalid character: "+str(element)
sys.exit(1)
print eval(formula)
| How to process user supplied formulas? | I have a dictionary containing a set of key values available through a web application:
I want to process user supplied formulas like:
((value1+value3)/value4)*100
What would be the easiest way to get the formula calculated matching values with ones from the dictionary?
Consider this example:
#!/usr/bin/python
values={'value1':10,'value2':1245,'value3':674365,'value4':65432,'value5':131}
formula=raw_input('Please enter formula:')
If I supply the formula '((value1+value3)/value4)*100' how can I map the value1 etc to map value1 from the dictionary and calculate the result?
Cheers,
| [
"eval can be used execute malicious code.\nDo you trust your users? If so, you can pass values along as a global dict to be used by eval. Thus, eval can evaluate the user formula directly without any additional string manipulation:\nvalues={'value1':10,'value2':1245,'value3':674365,'value4':65432,'value5':131}\nformula=raw_input('Please enter formula:')\nvalues=eval(formula,values)\nprint(values)\n\nIf you do not trust your potential users, you could use pyparsing:\nThe following is Paul McGuire's numeric expression parser, fourFn.py, wrapped in a class for easier use.\nutils_parse_numeric.py:\nfrom __future__ import division\nfrom pyparsing import (Literal,CaselessLiteral,Word,Combine,Group,Optional,\n ZeroOrMore,Forward,nums,alphas,oneOf)\nimport math\nimport operator \n\nclass NumericStringParser(object):\n '''\n Most of this code comes from the fourFn.py pyparsing example\n\n '''\n def pushFirst(self, strg, loc, toks ):\n self.exprStack.append( toks[0] )\n def pushUMinus(self, strg, loc, toks ):\n if toks and toks[0]=='-': \n self.exprStack.append( 'unary -' )\n def __init__(self):\n \"\"\"\n expop :: '^'\n multop :: '*' | '/'\n addop :: '+' | '-'\n integer :: ['+' | '-'] '0'..'9'+\n atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'\n factor :: atom [ expop factor ]*\n term :: factor [ multop factor ]*\n expr :: term [ addop term ]*\n \"\"\"\n point = Literal( \".\" )\n e = CaselessLiteral( \"E\" )\n fnumber = Combine( Word( \"+-\"+nums, nums ) + \n Optional( point + Optional( Word( nums ) ) ) +\n Optional( e + Word( \"+-\"+nums, nums ) ) )\n ident = Word(alphas, alphas+nums+\"_$\") \n plus = Literal( \"+\" )\n minus = Literal( \"-\" )\n mult = Literal( \"*\" )\n div = Literal( \"/\" )\n lpar = Literal( \"(\" ).suppress()\n rpar = Literal( \")\" ).suppress()\n addop = plus | minus\n multop = mult | div\n expop = Literal( \"^\" )\n pi = CaselessLiteral( \"PI\" )\n expr = Forward()\n atom = ((Optional(oneOf(\"- +\")) +\n (pi|e|fnumber|ident+lpar+expr+rpar).setParseAction(self.pushFirst))\n | Optional(oneOf(\"- +\")) + Group(lpar+expr+rpar)\n ).setParseAction(self.pushUMinus) \n factor = Forward()\n factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( self.pushFirst ) )\n term = factor + ZeroOrMore( ( multop + factor ).setParseAction( self.pushFirst ) )\n expr << term + ZeroOrMore( ( addop + term ).setParseAction( self.pushFirst ) )\n self.bnf = expr\n epsilon = 1e-12\n self.opn = { \"+\" : operator.add,\n \"-\" : operator.sub,\n \"*\" : operator.mul,\n \"/\" : operator.truediv,\n \"^\" : operator.pow }\n self.fn = { \"sin\" : math.sin,\n \"cos\" : math.cos,\n \"tan\" : math.tan,\n \"abs\" : abs,\n \"trunc\" : lambda a: int(a),\n \"round\" : round,\n \"sgn\" : lambda a: abs(a)>epsilon and cmp(a,0) or 0}\n def evaluateStack(self, s ):\n op = s.pop()\n if op == 'unary -':\n return -self.evaluateStack( s )\n if op in \"+-*/^\":\n op2 = self.evaluateStack( s )\n op1 = self.evaluateStack( s )\n return self.opn[op]( op1, op2 )\n elif op == \"PI\":\n return math.pi # 3.1415926535\n elif op == \"E\":\n return math.e # 2.718281828\n elif op in self.fn:\n return self.fn[op]( self.evaluateStack( s ) )\n elif op[0].isalpha():\n return 0\n else:\n return float( op )\n def eval(self,num_string,parseAll=True):\n self.exprStack=[]\n results=self.bnf.parseString(num_string,parseAll)\n val=self.evaluateStack( self.exprStack[:] )\n return val\n\nThen your script could do something like this:\nimport re\nimport utils_parse_numeric as upn\n\nmy_dict={\n 'number1':54,\n 'number2':1234,\n 'number3':778,\n 'number25':2109}\n\nThis uses the re module to substitute my_dict[\"numberXXX\"] for 'numberXXX':\ndef callback(match):\n num=match.group(1)\n key='number{0}'.format(num)\n val=my_dict[key]\n return str(val)\n\nastr='((number1+number3)/number2)*100'\nastr=re.sub('number(\\d+)',callback,astr)\n\nand here's how the NumericStringParser can be used to safely evaluate numeric expressions:\nnsp=upn.NumericStringParser()\nresult=nsp.eval(astr)\nprint(result)\n\nThis is much safer than using eval. All invalid expressions will raise a pyparsing.ParseException.\n",
"After validating both the formula and the numbers value (f.e. via a regexp) you can do something like:\narr = {'num1':4, 'num2':5, 'num3':7}\nformula = '(num1+num2)*num3'\n\nfor key, val in arr.items():\n formula = formula.replace(key, str(val))\n\nres = eval(formula)\nprint res\n\n",
"Thanks for all the input. I personally found that lacopo's answer suites my situation best.\nHere's a rough idea of the solution:\nimport sys\n\nvalues={'one':10,'two':1245,'three':674365,'four':65432,'five':131}\nprint str(values)\n\nformula=raw_input('Please enter formula:')\n\nfor key, val in values.items():\n formula = formula.replace(key, str(val))\n\nwhitelist=[ '+','-','/','*','^','(',')' ]\n\nto_evaluate=re.findall('\\D',formula)\nto_evaluate=list(set(to_evaluate))\n\nfor element in to_evaluate:\n if not element in whitelist:\n print \"Formula contains an invalid character: \"+str(element)\n sys.exit(1)\n\n\nprint eval(formula)\n\n"
] | [
6,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003022414_python.txt |
Q:
How to store password on gae properly when someone registers?
For example:
username:zjm1126
password:11
I store the password to the datastore on gae. When I see the data view at /_ah/admin, I can see the password of all people that have registered.
Is it safe to do so? If not, how to store it properly?
And the check_password method is:
user=MyUser.get_by_key_name(self.request.get('username'))
if user.password == self.request.get('password'):
session['user.key']=str(user.key())
else:
raise Exception('error 404')
A:
You should never store a password in plain text.
Use a ir-reversable data hashing algorithm, like sha or md5
Here is how you can create a hash in python:
from hashlib import sha256
from random import random
random_key = random()
sha256('%s%s%s'%('YOUR SECRET KEY',random_key,password))
You should also store the random key and hash the user supplied password similarly.
A:
There is nothing app-engine specific or new about this question that hasn't been answered 10 times before on SO. Search Stack Overflow for
store password and read the first 5 questions. That should give you a good foundation in the subject.
A:
There are numerous posts on stackoverflow about how to use various algorithms to product the integrity of passwords. Algorithms you should look into are SHA-256/SHA-512 in conjunction with a long randomly generated salt (which would also be stored in the database) or bcrypt. I won't go into the discussion of why one is better than the other here because that discussion is already taking place in other questions.
| How to store password on gae properly when someone registers? | For example:
username:zjm1126
password:11
I store the password to the datastore on gae. When I see the data view at /_ah/admin, I can see the password of all people that have registered.
Is it safe to do so? If not, how to store it properly?
And the check_password method is:
user=MyUser.get_by_key_name(self.request.get('username'))
if user.password == self.request.get('password'):
session['user.key']=str(user.key())
else:
raise Exception('error 404')
| [
"You should never store a password in plain text.\nUse a ir-reversable data hashing algorithm, like sha or md5\nHere is how you can create a hash in python:\nfrom hashlib import sha256\nfrom random import random\nrandom_key = random()\nsha256('%s%s%s'%('YOUR SECRET KEY',random_key,password))\n\nYou should also store the random key and hash the user supplied password similarly.\n",
"There is nothing app-engine specific or new about this question that hasn't been answered 10 times before on SO. Search Stack Overflow for\nstore password and read the first 5 questions. That should give you a good foundation in the subject.\n",
"There are numerous posts on stackoverflow about how to use various algorithms to product the integrity of passwords. Algorithms you should look into are SHA-256/SHA-512 in conjunction with a long randomly generated salt (which would also be stored in the database) or bcrypt. I won't go into the discussion of why one is better than the other here because that discussion is already taking place in other questions.\n"
] | [
10,
2,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"passwords",
"python"
] | stackoverflow_0003022366_google_app_engine_google_cloud_datastore_passwords_python.txt |
Q:
How to list all the objects with a specific date no matter the time in a DateTime Field
I Have a model like this
foo=models.char
bar=models.dateime
In wich several foos arrives in one day in different time. I need to list all the foos in a specific date, no matter the time they arrive.
I can't change the model, so splitting the bar in two fields(one for date and one for time) is out of reach right now :(
A:
I personally used the range filter and the internal datetime timestamps for max/min. For example:
date = datetime.date.today()
YourModel.objects.filter(bar__range=(
datetime.datetime.combine(
date,
datetime.time.min
),
datetime.datetime.combine(
date,
datetime.time.max
),
))
A:
Assuming a datetime format like so : YYYYMMDD HHmmss
eg : 20100611 171000 would be the 11th of June 1020, 5:10pm
Assuming a list of models with the following dates:
20100609 120000
20100611 161204
20100611 121204
20100611 191204
And you want all models for 20100611, in pseudo-code you could do :
for (model in models)
if (model.datetime >='20100611 000000' or model.datetime<='20100611 235959')
filtered_foos.add(model.foo)
This will effecttively ignore the time part of the date (sorry I don't have a python interpreter the syntax is clearly off but you should get the idea)
| How to list all the objects with a specific date no matter the time in a DateTime Field | I Have a model like this
foo=models.char
bar=models.dateime
In wich several foos arrives in one day in different time. I need to list all the foos in a specific date, no matter the time they arrive.
I can't change the model, so splitting the bar in two fields(one for date and one for time) is out of reach right now :(
| [
"I personally used the range filter and the internal datetime timestamps for max/min. For example:\ndate = datetime.date.today()\nYourModel.objects.filter(bar__range=(\n datetime.datetime.combine(\n date,\n datetime.time.min\n ),\n datetime.datetime.combine(\n date,\n datetime.time.max\n ),\n ))\n\n",
"Assuming a datetime format like so : YYYYMMDD HHmmss \neg : 20100611 171000 would be the 11th of June 1020, 5:10pm\nAssuming a list of models with the following dates: \n20100609 120000\n20100611 161204\n20100611 121204\n20100611 191204\nAnd you want all models for 20100611, in pseudo-code you could do : \nfor (model in models) \n if (model.datetime >='20100611 000000' or model.datetime<='20100611 235959')\n filtered_foos.add(model.foo)\n\nThis will effecttively ignore the time part of the date (sorry I don't have a python interpreter the syntax is clearly off but you should get the idea)\n"
] | [
2,
0
] | [] | [] | [
"date",
"datetime",
"django",
"orm",
"python"
] | stackoverflow_0003023913_date_datetime_django_orm_python.txt |
Q:
How to merge or copy anonymous session data into user data when user logs in?
This is a general question, or perhaps a request for pointers to other open source projects to look at:
I'm wondering how people merge an anonymous user's session data into the authenticated user data when a user logs in. For example, someone is browsing around your websites saving various items as favourites. He's not logged in, so they're saved to an anonymous user's data. Then he logs in, and we need to merge all that data into their (possibly existing) user data.
Is this done different ways in an ad-hoc fashion for different applications? Or are there some best practices or other projects people can direct me to?
A:
If very much depends on your system ofcourse. But personally I always try to merge the data and immediately store it in the same way as it would be stored as when the user would be logged in.
So if you store it in a session for an anonymous user and in the database for any authenticated user. Just merge all data as soon as you login.
| How to merge or copy anonymous session data into user data when user logs in? | This is a general question, or perhaps a request for pointers to other open source projects to look at:
I'm wondering how people merge an anonymous user's session data into the authenticated user data when a user logs in. For example, someone is browsing around your websites saving various items as favourites. He's not logged in, so they're saved to an anonymous user's data. Then he logs in, and we need to merge all that data into their (possibly existing) user data.
Is this done different ways in an ad-hoc fashion for different applications? Or are there some best practices or other projects people can direct me to?
| [
"If very much depends on your system ofcourse. But personally I always try to merge the data and immediately store it in the same way as it would be stored as when the user would be logged in.\nSo if you store it in a session for an anonymous user and in the database for any authenticated user. Just merge all data as soon as you login.\n"
] | [
1
] | [] | [] | [
"e_commerce",
"python",
"session",
"web.py"
] | stackoverflow_0003024191_e_commerce_python_session_web.py.txt |
Q:
Finding a list of indices from master array using secondary array with non-unique entries
I have a master array of length n of id numbers that apply to other analogous arrays with corresponding data for elements in my simulation that belong to those id numbers (e.g. data[id]). Were I to generate a list of id numbers of length m separately and need the information in the data array for those ids, what is the best method of getting a list of indices idx of the original array of ids in order to extract data[idx]? That is, given:
a=numpy.array([1,3,4,5,6]) # master array
b=numpy.array([3,4,3,6,4,1,5]) # secondary array
I would like to generate
idx=numpy.array([1,2,1,4,2,0,3])
The array a is typically in sequential order but it's not a requirement. Also, array b will most definitely have repeats and will not be in any order.
My current method of doing this is:
idx=numpy.array([numpy.where(a==bi)[0][0] for bi in b])
I timed it using the following test:
a=(numpy.random.uniform(100,size=100)).astype('int')
b=numpy.repeat(a,100)
timeit method1(a,b)
10 loops, best of 3: 53.1 ms per loop
Is there a better way of doing this?
A:
The current way you are doing it with where searching through the whole array of a each time. You can make this look-up O(1) instead of O(N) using a dict. For instance, I used the following method:
def method2(a,b):
tmpdict = dict(zip(a,range(len(a))))
idx = numpy.array([tmpdict[bi] for bi in b])
and got a very large speed-up which will be even better for larger arrays. For the sizes that you had in your example code, I got a speed-up of 15x. The only problem with my code is that if there are repeated elements in a, then the dict will currently point to the last instance of the element while with your method it will point to the first instance. However, that can remedied if there are to be repeated elements in the actual usage of the code.
A:
I'm not sure if there is a way to do this automatically in python, but you're probably best off sorting the two arrays and then generating your output in one pass through b. The complexity of that operation should be O(|a|*log|a|)+O(|b|*log|b|)+O(|b|) = O(|b|*log|b|) (assuming |b| > |a|). I believe your original try has complexity O(|a|*|b|), so this should provide a noticeable improvement for a sufficiently large b.
| Finding a list of indices from master array using secondary array with non-unique entries | I have a master array of length n of id numbers that apply to other analogous arrays with corresponding data for elements in my simulation that belong to those id numbers (e.g. data[id]). Were I to generate a list of id numbers of length m separately and need the information in the data array for those ids, what is the best method of getting a list of indices idx of the original array of ids in order to extract data[idx]? That is, given:
a=numpy.array([1,3,4,5,6]) # master array
b=numpy.array([3,4,3,6,4,1,5]) # secondary array
I would like to generate
idx=numpy.array([1,2,1,4,2,0,3])
The array a is typically in sequential order but it's not a requirement. Also, array b will most definitely have repeats and will not be in any order.
My current method of doing this is:
idx=numpy.array([numpy.where(a==bi)[0][0] for bi in b])
I timed it using the following test:
a=(numpy.random.uniform(100,size=100)).astype('int')
b=numpy.repeat(a,100)
timeit method1(a,b)
10 loops, best of 3: 53.1 ms per loop
Is there a better way of doing this?
| [
"The current way you are doing it with where searching through the whole array of a each time. You can make this look-up O(1) instead of O(N) using a dict. For instance, I used the following method:\ndef method2(a,b):\n tmpdict = dict(zip(a,range(len(a))))\n idx = numpy.array([tmpdict[bi] for bi in b])\n\nand got a very large speed-up which will be even better for larger arrays. For the sizes that you had in your example code, I got a speed-up of 15x. The only problem with my code is that if there are repeated elements in a, then the dict will currently point to the last instance of the element while with your method it will point to the first instance. However, that can remedied if there are to be repeated elements in the actual usage of the code. \n",
"I'm not sure if there is a way to do this automatically in python, but you're probably best off sorting the two arrays and then generating your output in one pass through b. The complexity of that operation should be O(|a|*log|a|)+O(|b|*log|b|)+O(|b|) = O(|b|*log|b|) (assuming |b| > |a|). I believe your original try has complexity O(|a|*|b|), so this should provide a noticeable improvement for a sufficiently large b.\n"
] | [
1,
0
] | [] | [] | [
"indexing",
"numpy",
"python"
] | stackoverflow_0003024353_indexing_numpy_python.txt |
Q:
Search for a String and replace it with a variable
I am trying to use regular expression to search a document fo a UUID number and replace the end of it with a new number. The code I have so far is:
read_file = open('test.txt', 'r+')
write_file = open('test.txt', 'w')
r = re.compile(r'(self.uid\s*=\s*5EFF837F-EFC2-4c32-A3D4\s*)(\S+)')
for l in read_file:
m1 = r.match(l)
if m1:
new=(str,m1.group(2))
new??????
This where I get stuck.
The file test.txt has the below UUID stored in it:
self.uid = '5EFF837F-EFC2-4c32-A3D4-D15C7F9E1F22'
I want to replace the part D15C7F9E1F22.
I have also tried this:
r = re.compile(r'(self.uid\s*=\s*)(\S+)')
for l in fp:
m1 = r.match(l)
new=map(int,m1.group(2).split("-")
new[4]='RHUI5345JO'
But I cannot seem to match the string.
Thanks in advance for any help.
A:
Why are you using a regex for such a straight forward substitution?
Couldn't you just use
for l in read_file:
l.replace("5EFF837F-EFC2-4c32-A3D4-D15C7F9E1F22",
"5EFF837F-EFC2-4c32-A3D4-RHUI5345JO")
# Write to file..
or is there more to the story than you're telling us? Also, unless it is a too big of a file, I would recommend reading the whole file into a string and doing just one replace on it for the sake of speed.
A:
I think your regular expression is off:
r = re.compile(r'(self.uid\s*=\s*5EFF837F-EFC2-4c32-A3D4\s*)(\S+)')
Should be:
r = re.compile(r"(self\.uid\s*=\s*'5EFF837F-EFC2-4c32-A3D4-)([^']*)'")
Then, when you have a match, grab group 1 and assign it to a variable and append your replacement string to it.
The ([^']*) group will search for any character up to the ' mark. That's your target remove group.
Edit: June 11th, 2010 @ 2:27 EST: Justin Peel has a good point. You can do a straight search and replace with this data. Unless you are looking for the pattern of 8 characters, followed by 4, 4, 4, and 12... In which case you could use the pattern:
r = re.compile(r"self\.uid\s*=\s*('\w{8}-(:?\w{4}-){3})(\w{12})'")
| Search for a String and replace it with a variable | I am trying to use regular expression to search a document fo a UUID number and replace the end of it with a new number. The code I have so far is:
read_file = open('test.txt', 'r+')
write_file = open('test.txt', 'w')
r = re.compile(r'(self.uid\s*=\s*5EFF837F-EFC2-4c32-A3D4\s*)(\S+)')
for l in read_file:
m1 = r.match(l)
if m1:
new=(str,m1.group(2))
new??????
This where I get stuck.
The file test.txt has the below UUID stored in it:
self.uid = '5EFF837F-EFC2-4c32-A3D4-D15C7F9E1F22'
I want to replace the part D15C7F9E1F22.
I have also tried this:
r = re.compile(r'(self.uid\s*=\s*)(\S+)')
for l in fp:
m1 = r.match(l)
new=map(int,m1.group(2).split("-")
new[4]='RHUI5345JO'
But I cannot seem to match the string.
Thanks in advance for any help.
| [
"Why are you using a regex for such a straight forward substitution?\nCouldn't you just use\nfor l in read_file:\n l.replace(\"5EFF837F-EFC2-4c32-A3D4-D15C7F9E1F22\",\n \"5EFF837F-EFC2-4c32-A3D4-RHUI5345JO\")\n # Write to file..\n\nor is there more to the story than you're telling us? Also, unless it is a too big of a file, I would recommend reading the whole file into a string and doing just one replace on it for the sake of speed.\n",
"I think your regular expression is off:\nr = re.compile(r'(self.uid\\s*=\\s*5EFF837F-EFC2-4c32-A3D4\\s*)(\\S+)')\n\nShould be:\nr = re.compile(r\"(self\\.uid\\s*=\\s*'5EFF837F-EFC2-4c32-A3D4-)([^']*)'\")\n\nThen, when you have a match, grab group 1 and assign it to a variable and append your replacement string to it.\nThe ([^']*) group will search for any character up to the ' mark. That's your target remove group.\nEdit: June 11th, 2010 @ 2:27 EST: Justin Peel has a good point. You can do a straight search and replace with this data. Unless you are looking for the pattern of 8 characters, followed by 4, 4, 4, and 12... In which case you could use the pattern:\nr = re.compile(r\"self\\.uid\\s*=\\s*('\\w{8}-(:?\\w{4}-){3})(\\w{12})'\")\n\n"
] | [
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003024331_python_regex.txt |
Q:
How do I get python to load .NET .dlls referenced by mixed mode .dlls?
I have a python .pyd that is a mixed mode C++ DLL. The DLL loads fine and loads unmanaged C++ dlls without a problem, but when it tries to load the .NET dlls referenced by the managed C++ dlls it fails with this error message:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly '...'
Copying these .NET dlls to the directory that pythod_d.exe is contained in allows the .NET libraries to load successfully, but this is not a good long term solution. Is there an environment variable I have to set or some command line option to python_d.exe that will solve my problem?
Note that using IronPython or Python .NET is NOT acceptable.
A:
I think I've resolved the problem. Assembly loading doesn't use the path set by SetDllDirectory(), and it looks like Python calls this function. By registering a delegate for the event AppDomain.AssemblyResolve(), I can catch the name of the dll that failed, append it to the directory obtained from GetDllDirectory(), and then manually load the assembly myself.
A:
I have a little bit experience with this. I believe it's related to the path and init issues as stated in http://effbot.org/pyfaq/is-a-pyd-file-the-same-as-a-dll.htm.
| How do I get python to load .NET .dlls referenced by mixed mode .dlls? | I have a python .pyd that is a mixed mode C++ DLL. The DLL loads fine and loads unmanaged C++ dlls without a problem, but when it tries to load the .NET dlls referenced by the managed C++ dlls it fails with this error message:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly '...'
Copying these .NET dlls to the directory that pythod_d.exe is contained in allows the .NET libraries to load successfully, but this is not a good long term solution. Is there an environment variable I have to set or some command line option to python_d.exe that will solve my problem?
Note that using IronPython or Python .NET is NOT acceptable.
| [
"I think I've resolved the problem. Assembly loading doesn't use the path set by SetDllDirectory(), and it looks like Python calls this function. By registering a delegate for the event AppDomain.AssemblyResolve(), I can catch the name of the dll that failed, append it to the directory obtained from GetDllDirectory(), and then manually load the assembly myself.\n",
"I have a little bit experience with this. I believe it's related to the path and init issues as stated in http://effbot.org/pyfaq/is-a-pyd-file-the-same-as-a-dll.htm.\n"
] | [
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0002970681_python_windows.txt |
Q:
Tkinter Spinbox Widget
How do I do a command that will set the default value on a Tkinter spinbox widget?
For some reason they didn't give it the attribute .set()
A:
Maybe you're looking for the "insert" command?
The following example sets the value to 2:
Tkinter.Spinbox(values=(1,2,3,4))
sb.delete(0,"end")
sb.insert(0,2)
| Tkinter Spinbox Widget | How do I do a command that will set the default value on a Tkinter spinbox widget?
For some reason they didn't give it the attribute .set()
| [
"Maybe you're looking for the \"insert\" command?\nThe following example sets the value to 2:\nTkinter.Spinbox(values=(1,2,3,4))\nsb.delete(0,\"end\")\nsb.insert(0,2)\n\n"
] | [
2
] | [] | [] | [
"python",
"set",
"tkinter",
"widget"
] | stackoverflow_0003019800_python_set_tkinter_widget.txt |
Q:
how to make a python or perl script portable to both linux and windows?
I was wondering how to make a python script portable to both linux and windows?
One problem I see is shebang. How to write the shebang so that the script can be run on both windows and linux?
Are there other problems besides shebang that I should know?
Is the solution same for perl script?
Thanks and regards!
A:
Windows will just ignore the shebang (which is, after all, a comment); in Windows you need to associate the .py extension to the Python executable in the registry, but you can perfectly well leave the shebang on, it will be perfectly innocuous there.
There are many bits and pieces which are platform-specific (many only exist on Unix, msvcrt only on Windows) so if you want to be portable you should abstain from those; some are subtly different (such as the detailed precise behavior of subprocess.Popen or mmap) -- it's all pretty advanced stuff and the docs will guide you there. If you're executing (via subprocess or otherwise) external commands you'd better make sure they exist on both platforms, of course, or check what platform you're in and use different external commands in each case.
Remember to always use /, not \, as path separator (forward slash works in both platforms, backwards slash is windows-only), and be meticulous as to whether each file you're opening is binary or text.
I think that's about it...
A:
Make sure you don't handle files and directories as strings and simply concatenate them with a slash in between. Perl:
$path = File::Spec->catfile("dir1", "dir2", "file")
Remember that Windows has volumes:
($volume, $path, $file) = File::Spec->splitpath($full_path);
@directories = File::Spec->splitdir($path);
When running other programs, try to avoid involving the shell. In Perl, when you run a command with the system function, you can easily get it wrong with:
$full_command = 'C:\Documents and Settings/program.exe "arg1" arg2'; # spaces alert!
system($full_command);
Instead, you can run system with a list as argument: the executable and the arguments being separate strings. In that case, the shell doesn't get involved and you don't get into trouble regarding shell escaping or spaces in file names.
system('C:\Documents and Settings/program.exe', 'arg1', 'arg2');
There's a bunch of portability nits documented in the perlport manual.
A:
The shebang line will be interpreted as a comment by Perl or Python. The only thing that assigns it a special meaning is the UNIX/Linux shell; it gets ignored on Windows. The way Windows knows which interpreter to use to run the file is through the file associations in the registry, a different mechanism altogether.
A:
I don't know enough to comment on Python approaches to this problem, so I won't.
Most things in Perl will just work. There are a few gotchas that are easy to avoid.
Here are a few things I have come across in the years I've been working with Win32 Perl:
Use 3 argument form of open. The two argument form can have problems with spaces in paths. (You should already be doing this anyway.)
Make sure that the case is correct when you use a module. use Warnings; will appear to work, but in reality it will fail.
select only works on actual sockets under Windows. You can't use it on any other sort of handle.
Use File::Spec to manage paths to files.
When you open a file handle CRLF will automatically be converted to LF line endings as the handle is read. LF is changed to CRLF on write. If you want to avoid this, use binmode on the handle to prevent the translation.
If you need to pass arguments through a shell, put double quotes around each argument. This will prevent errors due to spaces in file names.
See perlport for more information on individual functions.
| how to make a python or perl script portable to both linux and windows? | I was wondering how to make a python script portable to both linux and windows?
One problem I see is shebang. How to write the shebang so that the script can be run on both windows and linux?
Are there other problems besides shebang that I should know?
Is the solution same for perl script?
Thanks and regards!
| [
"Windows will just ignore the shebang (which is, after all, a comment); in Windows you need to associate the .py extension to the Python executable in the registry, but you can perfectly well leave the shebang on, it will be perfectly innocuous there.\nThere are many bits and pieces which are platform-specific (many only exist on Unix, msvcrt only on Windows) so if you want to be portable you should abstain from those; some are subtly different (such as the detailed precise behavior of subprocess.Popen or mmap) -- it's all pretty advanced stuff and the docs will guide you there. If you're executing (via subprocess or otherwise) external commands you'd better make sure they exist on both platforms, of course, or check what platform you're in and use different external commands in each case.\nRemember to always use /, not \\, as path separator (forward slash works in both platforms, backwards slash is windows-only), and be meticulous as to whether each file you're opening is binary or text.\nI think that's about it...\n",
"Make sure you don't handle files and directories as strings and simply concatenate them with a slash in between. Perl:\n$path = File::Spec->catfile(\"dir1\", \"dir2\", \"file\")\n\nRemember that Windows has volumes:\n($volume, $path, $file) = File::Spec->splitpath($full_path);\n@directories = File::Spec->splitdir($path);\n\nWhen running other programs, try to avoid involving the shell. In Perl, when you run a command with the system function, you can easily get it wrong with:\n$full_command = 'C:\\Documents and Settings/program.exe \"arg1\" arg2'; # spaces alert!\nsystem($full_command);\n\nInstead, you can run system with a list as argument: the executable and the arguments being separate strings. In that case, the shell doesn't get involved and you don't get into trouble regarding shell escaping or spaces in file names.\nsystem('C:\\Documents and Settings/program.exe', 'arg1', 'arg2');\n\nThere's a bunch of portability nits documented in the perlport manual.\n",
"The shebang line will be interpreted as a comment by Perl or Python. The only thing that assigns it a special meaning is the UNIX/Linux shell; it gets ignored on Windows. The way Windows knows which interpreter to use to run the file is through the file associations in the registry, a different mechanism altogether.\n",
"I don't know enough to comment on Python approaches to this problem, so I won't.\nMost things in Perl will just work. There are a few gotchas that are easy to avoid.\nHere are a few things I have come across in the years I've been working with Win32 Perl:\n\nUse 3 argument form of open. The two argument form can have problems with spaces in paths. (You should already be doing this anyway.)\nMake sure that the case is correct when you use a module. use Warnings; will appear to work, but in reality it will fail.\nselect only works on actual sockets under Windows. You can't use it on any other sort of handle.\nUse File::Spec to manage paths to files.\nWhen you open a file handle CRLF will automatically be converted to LF line endings as the handle is read. LF is changed to CRLF on write. If you want to avoid this, use binmode on the handle to prevent the translation.\nIf you need to pass arguments through a shell, put double quotes around each argument. This will prevent errors due to spaces in file names.\n\nSee perlport for more information on individual functions.\n"
] | [
14,
7,
2,
2
] | [] | [] | [
"cross_platform",
"perl",
"python",
"scripting",
"shebang"
] | stackoverflow_0003020267_cross_platform_perl_python_scripting_shebang.txt |
Q:
Making pygtksourceview work in windows
So, I'm trying to get gtksourceview python bindings work under windows (I'm developing a cross platform gtk application that shows code, so gtksourceview seemed like a natural choice).
I have pygtk installed and working (I followed the instructions in http://www.pygtk.org/downloads.html)
I tried the instructions in http://projects.gnome.org/gtksourceview/ for gtksourceview.
Here is what I did:
Downloaded and extracted the latest gtksourceview window binaries from: http://ftp.gnome.org/pub/gnome/binaries/win32/gtksourceview/2.10/gtksourceview-2.10.0.zip
The website said gtksourceview needs libxml, so I downloaded and extracted the latest libxml window binaries from:
http://xmlsoft.org/sources/win32/libxml2-2.7.6.win32.zip
Added the folders containing dll files to the PATH (in my computer they were c:\opt\gtksourceview\bin; C:\opt\libxml2-2.7.6.win32\bin)
Installed pygtksourceview with the windows installer:
http://ftp.gnome.org/pub/gnome/binaries/win32/pygtksourceview/2.10/pygtksourceview-2.10.0.win32-py2.6.exe
Renamed the file libxml2.dll to libxml2-2.dll (after running depends on the gtksourceview dll)
Now, the gtksouceview widget seems to work, until I'm trying to set the code's language. When I do that python crashes.
Here is how I crash it in the console (the simplest way i could come up with):
>>>import gtksourceview2
>>>lang = gtksourceview2.language_manager_get_default().get_language('cpp')
>>>lang.get_style_ids()
I'm hoping I'm not the first person to use gtksourceview in python on windows. Any ideas what I should try?
A:
So in case anyone else is wondering -- I grabbed the wrong libxml dll. The right one is in:
http://ftp.gnome.org/pub/GNOME/binaries/win32/dependencies/libxml2_2.7.7-1_win32.zip
| Making pygtksourceview work in windows | So, I'm trying to get gtksourceview python bindings work under windows (I'm developing a cross platform gtk application that shows code, so gtksourceview seemed like a natural choice).
I have pygtk installed and working (I followed the instructions in http://www.pygtk.org/downloads.html)
I tried the instructions in http://projects.gnome.org/gtksourceview/ for gtksourceview.
Here is what I did:
Downloaded and extracted the latest gtksourceview window binaries from: http://ftp.gnome.org/pub/gnome/binaries/win32/gtksourceview/2.10/gtksourceview-2.10.0.zip
The website said gtksourceview needs libxml, so I downloaded and extracted the latest libxml window binaries from:
http://xmlsoft.org/sources/win32/libxml2-2.7.6.win32.zip
Added the folders containing dll files to the PATH (in my computer they were c:\opt\gtksourceview\bin; C:\opt\libxml2-2.7.6.win32\bin)
Installed pygtksourceview with the windows installer:
http://ftp.gnome.org/pub/gnome/binaries/win32/pygtksourceview/2.10/pygtksourceview-2.10.0.win32-py2.6.exe
Renamed the file libxml2.dll to libxml2-2.dll (after running depends on the gtksourceview dll)
Now, the gtksouceview widget seems to work, until I'm trying to set the code's language. When I do that python crashes.
Here is how I crash it in the console (the simplest way i could come up with):
>>>import gtksourceview2
>>>lang = gtksourceview2.language_manager_get_default().get_language('cpp')
>>>lang.get_style_ids()
I'm hoping I'm not the first person to use gtksourceview in python on windows. Any ideas what I should try?
| [
"So in case anyone else is wondering -- I grabbed the wrong libxml dll. The right one is in:\nhttp://ftp.gnome.org/pub/GNOME/binaries/win32/dependencies/libxml2_2.7.7-1_win32.zip\n"
] | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python",
"windows"
] | stackoverflow_0002968273_gtk_pygtk_python_windows.txt |
Q:
How to create a HTML world map with GeoDjango?
The GeoDjango tutorial explains how to insert world borders into a spatial database.
I would like to create a world Map in HTML with these data, with both map and area tags. Something like that.
I just don't know how to retrieve the coordinates for each country (required for the area's coords attribute).
from world.models import WorldBorders
for country in WorldBorders.objects.all():
print u'<area shape="poly" title="%s" alt="%s" coords="%s" />' % (v.name, v.name, "???")
Thanks !
A:
In the worldborders example, the attribute mpoly is where the geographic polygon is actually stored.
In your example, you're going to want to access v.mpoly
You're not going to be able to use it directly however because mpoly is itself a MultiPolygon field. Consider a country like Canada that has a bunch of islands, each island and the main landmass is a polygon. So to arrive at your points and a complete description of Canada's borders you need to:
Iterate over the polygons inside of multipolygon. Each polygon corresponds to an area (so your assumption in the example of one area per country is wrong).
Iterate over the points inside of each polygon.
Convert your point coordinates (latitude/longitude) into the coordinates used by your svg graphic.
A:
To use lat/lon in an SVG, you need to project them into pixel (x/y) space. A simple transformation might look like this:
>>> x = (lon + 180) / 360 * image_width
>>> y = (90 - lat) / 180 * image_height
For an image where image_width == 2 * image_height, this will give you something like the map at the link posted (which looks like an equirectangular projection).
To use a different projection (e.g. Mercator), use the GEOSGeometry.transform method in GeoDjango before applying the transform.
| How to create a HTML world map with GeoDjango? | The GeoDjango tutorial explains how to insert world borders into a spatial database.
I would like to create a world Map in HTML with these data, with both map and area tags. Something like that.
I just don't know how to retrieve the coordinates for each country (required for the area's coords attribute).
from world.models import WorldBorders
for country in WorldBorders.objects.all():
print u'<area shape="poly" title="%s" alt="%s" coords="%s" />' % (v.name, v.name, "???")
Thanks !
| [
"In the worldborders example, the attribute mpoly is where the geographic polygon is actually stored.\nIn your example, you're going to want to access v.mpoly\nYou're not going to be able to use it directly however because mpoly is itself a MultiPolygon field. Consider a country like Canada that has a bunch of islands, each island and the main landmass is a polygon. So to arrive at your points and a complete description of Canada's borders you need to:\n\nIterate over the polygons inside of multipolygon. Each polygon corresponds to an area (so your assumption in the example of one area per country is wrong).\nIterate over the points inside of each polygon.\nConvert your point coordinates (latitude/longitude) into the coordinates used by your svg graphic.\n\n",
"To use lat/lon in an SVG, you need to project them into pixel (x/y) space. A simple transformation might look like this:\n>>> x = (lon + 180) / 360 * image_width\n>>> y = (90 - lat) / 180 * image_height\n\nFor an image where image_width == 2 * image_height, this will give you something like the map at the link posted (which looks like an equirectangular projection).\nTo use a different projection (e.g. Mercator), use the GEOSGeometry.transform method in GeoDjango before applying the transform. \n"
] | [
0,
0
] | [] | [] | [
"django",
"geodjango",
"gis",
"html",
"python"
] | stackoverflow_0002981450_django_geodjango_gis_html_python.txt |
Q:
Python as an end user script in a python app
I have an app written in python. I want to give my users the ability to manipulate the apps objects by allowing them to run their own scripts. They are likely to make errors in their scripts. If there is an error I want to ensure that the app doesn't stop running. I'd like to embed a debugger in my app to help them debug their scripts.
e.g. I define a point class in my app in shapes.py:
class QVPoint(object):
def __init__(self, x, y):
self.x = x
self.y = y
def addPoint(self, aPoint):
self.x = self.x + aPoint.x
self.y = self.y + aPoint.y
I want to enable them to run scripts like:
from shapes import QVPoint
a = QVPoint(1,1)
a.addPoint(QVPoint(2,2))
print "<" + str(a.x) + ',' + str(a.y) + ">"
print "<%d,%d>" % (a.x, a.y)
print 'done'
I figure this must use the interpreter, the debugger but I'm not sure on two counts, 1) how to expose objects that are created in the App to the script, and 2) how to ensure that the app doesn't stop if a bug causes the script to stop.
I'm sure this must have been asked before but I can't find it. All answers welcome.
Many thx
David
A:
I would suggest you use a separate interpreter instance (separate python process) to evaluate user's scripts. This will guarantee that whatever breaks in the user script would never affect you application. You can run external processes using os module, this would be one way to do so: http://docs.python.org/library/os.html#os.popen
You can allow user's scripts to import certain module(s) from your application so that the variables you define are accessible by the scripts.
A:
There are a few decisions to be made.
Do you want to run it in the same process of your app or in a separate process?
Without knowing much detail of your app, I'd tend to favor running them in a separate process. Use the subprocess module for this. You can create an app launcher that in turn calls your users script. If it throws an exception you can catch it and format the result and report back to the user.
Do you want to expose the classes to your user or the objects to your user?
In your example, it seems sharing the classes is enough. This should be fairly simple.
If it is only classes, you can simply include it in the PYTHONPATH. Then your user can just import them. If you want to expose an object, it may requires you to do this in process. Or otherwise you have to find a way to serialize you objects and transfer it to the new process.
| Python as an end user script in a python app | I have an app written in python. I want to give my users the ability to manipulate the apps objects by allowing them to run their own scripts. They are likely to make errors in their scripts. If there is an error I want to ensure that the app doesn't stop running. I'd like to embed a debugger in my app to help them debug their scripts.
e.g. I define a point class in my app in shapes.py:
class QVPoint(object):
def __init__(self, x, y):
self.x = x
self.y = y
def addPoint(self, aPoint):
self.x = self.x + aPoint.x
self.y = self.y + aPoint.y
I want to enable them to run scripts like:
from shapes import QVPoint
a = QVPoint(1,1)
a.addPoint(QVPoint(2,2))
print "<" + str(a.x) + ',' + str(a.y) + ">"
print "<%d,%d>" % (a.x, a.y)
print 'done'
I figure this must use the interpreter, the debugger but I'm not sure on two counts, 1) how to expose objects that are created in the App to the script, and 2) how to ensure that the app doesn't stop if a bug causes the script to stop.
I'm sure this must have been asked before but I can't find it. All answers welcome.
Many thx
David
| [
"I would suggest you use a separate interpreter instance (separate python process) to evaluate user's scripts. This will guarantee that whatever breaks in the user script would never affect you application. You can run external processes using os module, this would be one way to do so: http://docs.python.org/library/os.html#os.popen\nYou can allow user's scripts to import certain module(s) from your application so that the variables you define are accessible by the scripts.\n",
"There are a few decisions to be made.\n\nDo you want to run it in the same process of your app or in a separate process?\nWithout knowing much detail of your app, I'd tend to favor running them in a separate process. Use the subprocess module for this. You can create an app launcher that in turn calls your users script. If it throws an exception you can catch it and format the result and report back to the user.\nDo you want to expose the classes to your user or the objects to your user?\nIn your example, it seems sharing the classes is enough. This should be fairly simple.\nIf it is only classes, you can simply include it in the PYTHONPATH. Then your user can just import them. If you want to expose an object, it may requires you to do this in process. Or otherwise you have to find a way to serialize you objects and transfer it to the new process.\n\n"
] | [
3,
1
] | [] | [] | [
"extensibility",
"python"
] | stackoverflow_0003025031_extensibility_python.txt |
Q:
Any simple frameworks for pagination in App Engine?
I want to find a framework for pagination in Google App Engine.
Do you know of one?
A:
If you want to do paging you should read about cursors.
The article linked to by Jason was written before cursors were around. Cursors can simplify paging greatly, especially in cases that Andrew mentions, when dealing with sorts and filters.
A:
Pagination is not always easy-to-do, especially when you consider sorting and filtering. Check out this recipe as a start: http://appengine-cookbook.appspot.com/recipe/efficient-paging-for-any-query-and-any-model/
| Any simple frameworks for pagination in App Engine? | I want to find a framework for pagination in Google App Engine.
Do you know of one?
| [
"If you want to do paging you should read about cursors.\nThe article linked to by Jason was written before cursors were around. Cursors can simplify paging greatly, especially in cases that Andrew mentions, when dealing with sorts and filters.\n",
"Pagination is not always easy-to-do, especially when you consider sorting and filtering. Check out this recipe as a start: http://appengine-cookbook.appspot.com/recipe/efficient-paging-for-any-query-and-any-model/\n"
] | [
3,
2
] | [] | [] | [
"google_app_engine",
"pagination",
"python"
] | stackoverflow_0003011352_google_app_engine_pagination_python.txt |
Q:
Appengine backreferences - need composite index?
I have a query that is very recently starting to throw:
"The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query."
I checked the line on which this exception is being thrown, and the problem query is this one:
count = self.vote_set.filter("direction =", 1).count()
This is literally a one-filter operation using appengine's built-in backreferences. I have no idea how to optimize this query...anyone have any suggestions? I tried to add this index:
- kind: Vote
properties:
- name: direction
direction: desc
- kind: Vote
properties:
- name: direction
And I got a message (obviously) saying this was an unnecessary index.
Thanks for your help in advance.
A:
The backreferences actually just construct a query that's filtered on the reference property, so by adding another filter you have a 2-filter query.
Your compsite index would look something like:
- kind: Vote
properties:
- name: your_reference_property_name
- name: direction
direction: desc
A:
If you run all relevant queries on your local SDK, it should generate all needed indices (in index.yaml) and the recommended policy is not to edit index.yaml yourself but rather to let the local SDK do it for you. If the SDK is not generating all needed indices, as long of course as you do exercise all relevant code paths in your local testing!, you should open a bug for it in the App Engine tracker here (after checking that there isn't already a bug report for this problem, of course).
| Appengine backreferences - need composite index? | I have a query that is very recently starting to throw:
"The built-in indices are not efficient enough for this query and your data. Please add a composite index for this query."
I checked the line on which this exception is being thrown, and the problem query is this one:
count = self.vote_set.filter("direction =", 1).count()
This is literally a one-filter operation using appengine's built-in backreferences. I have no idea how to optimize this query...anyone have any suggestions? I tried to add this index:
- kind: Vote
properties:
- name: direction
direction: desc
- kind: Vote
properties:
- name: direction
And I got a message (obviously) saying this was an unnecessary index.
Thanks for your help in advance.
| [
"The backreferences actually just construct a query that's filtered on the reference property, so by adding another filter you have a 2-filter query. \nYour compsite index would look something like:\n- kind: Vote\n properties:\n - name: your_reference_property_name\n - name: direction\n direction: desc\n\n",
"If you run all relevant queries on your local SDK, it should generate all needed indices (in index.yaml) and the recommended policy is not to edit index.yaml yourself but rather to let the local SDK do it for you. If the SDK is not generating all needed indices, as long of course as you do exercise all relevant code paths in your local testing!, you should open a bug for it in the App Engine tracker here (after checking that there isn't already a bug report for this problem, of course).\n"
] | [
3,
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003025018_google_app_engine_google_cloud_datastore_python.txt |
Q:
Google App Engine - update_indexes error
I have a Java app deployed on app engine and I use appcfg.py of the
Python SDK to vacuum and update my indexes.
Yesterday I first ran vacuum_indexes and that completed successfully -
i.e. it en-queued tasks to delete my existing indexes.
The next step was probably a mistake on my part - I then ran
update_indexes even though my previous indexes weren't yet deleted.
Needless to say that my update_indexes call errored out. So much so
that now when I look at my app engine console, it shows the status of
all my indexes as "Error".
A day has passed an it still shows the status on my indexes as "Error".
Can someone help my out of my fix?!
Thanks,
Keyur
P.S.: I have posted this on the GAE forums as well but hoping SO users have faced and resolved this issue as well.
A:
I followed what was suggested in the error logs and that worked for me:
Empty the index.yaml file (create a backup first)
Run vacuum_indexes again
Look at your app's admin console and don't go to the next step till all your indexes are deleted.
Specify the indexes you want to be created in index.yaml
Run update_indexes
Look at your app's admin console and it should show that your indexes are now building.
Enjoy the fruits of your labor :)
Cheers,
Keyur
| Google App Engine - update_indexes error | I have a Java app deployed on app engine and I use appcfg.py of the
Python SDK to vacuum and update my indexes.
Yesterday I first ran vacuum_indexes and that completed successfully -
i.e. it en-queued tasks to delete my existing indexes.
The next step was probably a mistake on my part - I then ran
update_indexes even though my previous indexes weren't yet deleted.
Needless to say that my update_indexes call errored out. So much so
that now when I look at my app engine console, it shows the status of
all my indexes as "Error".
A day has passed an it still shows the status on my indexes as "Error".
Can someone help my out of my fix?!
Thanks,
Keyur
P.S.: I have posted this on the GAE forums as well but hoping SO users have faced and resolved this issue as well.
| [
"I followed what was suggested in the error logs and that worked for me:\n\nEmpty the index.yaml file (create a backup first)\nRun vacuum_indexes again\nLook at your app's admin console and don't go to the next step till all your indexes are deleted.\nSpecify the indexes you want to be created in index.yaml\nRun update_indexes\nLook at your app's admin console and it should show that your indexes are now building.\nEnjoy the fruits of your labor :)\n\nCheers,\nKeyur\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"java",
"python"
] | stackoverflow_0003024663_google_app_engine_google_cloud_datastore_java_python.txt |
Q:
Define Classes in Packages
I'm learning Python and I have been playing around with packages. I wanted to know the best way to define classes in packages. It seems that the only way to define classes in a package is to define them in the __init__.py of that package. Coming from Java, I'd kind of like to define individual files for my classes. Is this a recommended practice?
I'd like to have my directory look somewhat like this:
recursor/
__init__.py
RecursionException.py
RecursionResult.py
Recursor.py
So I could refer to my classes as recursor.Recursor, recursor.RecursionException, and recursor.RecursionResult. Is this doable or recommended in Python?
A:
Go ahead and define your classes in separate modules. Then make __init__.py do something like this:
from RecursionException import RecursionException
from RecursionResult import RecursionResult
from Recursor import Recursor
That will import each class into the package's root namespace, so calling code can refer to recursor.Recursor instead of recursor.Recursor.Recursor.
I feel the need to echo some of the other comments here, though: Python is not Java. Rather than creating a new module for every class under the sun, I suggest grouping closely related classes into a single module. It's easier to understand your code that way, and calling code won't need a bazillion imports.
A:
This is perfectly doable. Just create a new class module for each of those classes, and create exactly the structure you posted.
You can also make a Recursion.py module or something similar, and include all 3 classes in that file.
(I'm also new to Python from Java, and I haven't yet put anything in my __init__.py files...)
A:
In Python you're not restricted to defining 1 class per file and few do that. You can if you want to though - it's totally up to you. A Package in Python is just a directory with an
__init__.py
file. You don't have to put anything in that file you can to control what gets imported etc.
| Define Classes in Packages | I'm learning Python and I have been playing around with packages. I wanted to know the best way to define classes in packages. It seems that the only way to define classes in a package is to define them in the __init__.py of that package. Coming from Java, I'd kind of like to define individual files for my classes. Is this a recommended practice?
I'd like to have my directory look somewhat like this:
recursor/
__init__.py
RecursionException.py
RecursionResult.py
Recursor.py
So I could refer to my classes as recursor.Recursor, recursor.RecursionException, and recursor.RecursionResult. Is this doable or recommended in Python?
| [
"Go ahead and define your classes in separate modules. Then make __init__.py do something like this:\nfrom RecursionException import RecursionException\nfrom RecursionResult import RecursionResult\nfrom Recursor import Recursor\n\nThat will import each class into the package's root namespace, so calling code can refer to recursor.Recursor instead of recursor.Recursor.Recursor.\nI feel the need to echo some of the other comments here, though: Python is not Java. Rather than creating a new module for every class under the sun, I suggest grouping closely related classes into a single module. It's easier to understand your code that way, and calling code won't need a bazillion imports.\n",
"This is perfectly doable. Just create a new class module for each of those classes, and create exactly the structure you posted.\nYou can also make a Recursion.py module or something similar, and include all 3 classes in that file.\n(I'm also new to Python from Java, and I haven't yet put anything in my __init__.py files...)\n",
"In Python you're not restricted to defining 1 class per file and few do that. You can if you want to though - it's totally up to you. A Package in Python is just a directory with an \n__init__.py \n\nfile. You don't have to put anything in that file you can to control what gets imported etc.\n"
] | [
10,
2,
1
] | [] | [] | [
"class",
"module",
"package",
"python"
] | stackoverflow_0003024472_class_module_package_python.txt |
Q:
howto scroll a gtk.scrolledwindow object from python code
I'm writing a python application that has a glade gui. Using subprocess to execute some shell commands in the background.
Using a glade GUI which has a scrolledwindow widget and a textview widget inside the scrolledwindow widget. The textview gets populated as the subprocess.Popen object run and display their stdout and stderr to this textview.
My problem is that the textview is constantly populated, but stays still @ scroll position 0, 0 (top-most, left-most)
I want this scrolledwindow widget to stays at bottom-most, left-most at all times...
Does anyone have any idea which method I need to call scroll this thing downwards?
A:
You need to get the horizontal and/or vertical gtk.Adjustment from the scrolledwindow, and change its values. See
get_vadjustment
gtk.Adjustment
The set_all method of gtk.Adjustment is probably what you want.
A:
This is probably what you are looking for.
http://faq.pygtk.org/index.py?req=show&file=faq14.010.htp
A:
look at gtk.ScrolledWindow.set_placement.
(never tried)
| howto scroll a gtk.scrolledwindow object from python code | I'm writing a python application that has a glade gui. Using subprocess to execute some shell commands in the background.
Using a glade GUI which has a scrolledwindow widget and a textview widget inside the scrolledwindow widget. The textview gets populated as the subprocess.Popen object run and display their stdout and stderr to this textview.
My problem is that the textview is constantly populated, but stays still @ scroll position 0, 0 (top-most, left-most)
I want this scrolledwindow widget to stays at bottom-most, left-most at all times...
Does anyone have any idea which method I need to call scroll this thing downwards?
| [
"You need to get the horizontal and/or vertical gtk.Adjustment from the scrolledwindow, and change its values. See \n\nget_vadjustment\ngtk.Adjustment\n\nThe set_all method of gtk.Adjustment is probably what you want.\n",
"This is probably what you are looking for.\nhttp://faq.pygtk.org/index.py?req=show&file=faq14.010.htp\n",
"look at gtk.ScrolledWindow.set_placement.\n(never tried)\n"
] | [
2,
1,
0
] | [] | [] | [
"glade",
"pygtk",
"python",
"subprocess"
] | stackoverflow_0001940957_glade_pygtk_python_subprocess.txt |
Q:
using wild card when listing directories in python
how can I use wild cars like '*' when getting a list of files inside a directory in Python? for example, I want something like:
os.listdir('foo/*bar*/*.txt')
which would return a list of all the files ending in .txt in directories that have bar in their name inside of the foo parent directory.
how can I do this?
thanks.
A:
glob.glob for the win.
| using wild card when listing directories in python | how can I use wild cars like '*' when getting a list of files inside a directory in Python? for example, I want something like:
os.listdir('foo/*bar*/*.txt')
which would return a list of all the files ending in .txt in directories that have bar in their name inside of the foo parent directory.
how can I do this?
thanks.
| [
"glob.glob for the win.\n"
] | [
17
] | [] | [] | [
"directory_structure",
"file_io",
"filesystems",
"python"
] | stackoverflow_0003025759_directory_structure_file_io_filesystems_python.txt |
Q:
Can one Python project use both 2.x and 3.x code?
I'm going to start on a long (~1-year) programming project in Python. I want to use wxPython for my GUI (supports 2.6), but I also want to use 3.1 for the rest of the project (to start using the 3.x syntax).
Is there any way for me to design a project that mixes 2.x and 3.x modules? Or should I just bite the bullet and use either 2.x (preferred, since I really want to learn wxPython) or 3.x throughout?
Thanks,
Mike
A:
You should use python 2.7 (a release candidate is expected in the next days) that is very close to python 3.1 and to code taking care of no using deprecated features. There is a recent version of wxpython for python 2.7.
After wxpython gets 3.1-3.2 builds, conversion of the code should not be too hurting.
Still, wxpython has no deadline for the transition :-(
Another option is to use pyQt that already has builds for python 3.1
A:
Python 2 and 3 are not that different. If you have learned Python 2 well, it will be a matter of minutes to get acquainted with Python 3. The official recommendation says that you should use Python 2.6 (the current version) and try to be forward-compatible. Python 3 is currently not an option for large projects as virtually none of the popular packages have been translated yet. But development of Python 2 and 3 will continue in parallel for a long time, so you won't lose much by not using Python 3. You can import many syntactical features of 3 (Unicode string literals, division, print function, absolute imports) using the __future__ module, and the standard library remains mostly the same. So I'd recommend using Python 2.
A:
mixing the ability to use wxPython (2.x) + with learning new syntax (3.x)
Don't "mix".
Write Python 2. Get it to work.
Play with Python 3 separately. Don't "mix".
When the various packages and modules are available in Python 3, use the 2to3 conversion to create Python 3. You'll find some small problems. Fix your Python 2 so that your package works in Python 2 and also works after the conversion.
Then, you can drop support for Python 2 and focus on Python 3.
Don't "mix".
| Can one Python project use both 2.x and 3.x code? | I'm going to start on a long (~1-year) programming project in Python. I want to use wxPython for my GUI (supports 2.6), but I also want to use 3.1 for the rest of the project (to start using the 3.x syntax).
Is there any way for me to design a project that mixes 2.x and 3.x modules? Or should I just bite the bullet and use either 2.x (preferred, since I really want to learn wxPython) or 3.x throughout?
Thanks,
Mike
| [
"You should use python 2.7 (a release candidate is expected in the next days) that is very close to python 3.1 and to code taking care of no using deprecated features. There is a recent version of wxpython for python 2.7.\nAfter wxpython gets 3.1-3.2 builds, conversion of the code should not be too hurting.\nStill, wxpython has no deadline for the transition :-( \nAnother option is to use pyQt that already has builds for python 3.1 \n",
"Python 2 and 3 are not that different. If you have learned Python 2 well, it will be a matter of minutes to get acquainted with Python 3. The official recommendation says that you should use Python 2.6 (the current version) and try to be forward-compatible. Python 3 is currently not an option for large projects as virtually none of the popular packages have been translated yet. But development of Python 2 and 3 will continue in parallel for a long time, so you won't lose much by not using Python 3. You can import many syntactical features of 3 (Unicode string literals, division, print function, absolute imports) using the __future__ module, and the standard library remains mostly the same. So I'd recommend using Python 2.\n",
"\nmixing the ability to use wxPython (2.x) + with learning new syntax (3.x) \n\nDon't \"mix\".\nWrite Python 2. Get it to work.\nPlay with Python 3 separately. Don't \"mix\".\nWhen the various packages and modules are available in Python 3, use the 2to3 conversion to create Python 3. You'll find some small problems. Fix your Python 2 so that your package works in Python 2 and also works after the conversion.\nThen, you can drop support for Python 2 and focus on Python 3. \nDon't \"mix\".\n"
] | [
5,
3,
2
] | [] | [] | [
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0002951982_python_python_2.x_python_3.x.txt |
Q:
How can I list all form related errors in Django?
Is there a direct way of listing out all form errors in Django templates. I'd like to list out both field and non-field errors and any other form errors.
I've found out how to do this on a per-field basis but as said earlier, I'd like to list out everything.
The method I'm using doesn't seem to list out everything.
{% for error in form.errors %}
{{ error|escape }}
{% endfor %}
Thanks.
A:
You could loop over all the field in addition to non-field errors:
http://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields
Short Django snippet: List all Form Errors
| How can I list all form related errors in Django? | Is there a direct way of listing out all form errors in Django templates. I'd like to list out both field and non-field errors and any other form errors.
I've found out how to do this on a per-field basis but as said earlier, I'd like to list out everything.
The method I'm using doesn't seem to list out everything.
{% for error in form.errors %}
{{ error|escape }}
{% endfor %}
Thanks.
| [
"You could loop over all the field in addition to non-field errors: \n\nhttp://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields\nShort Django snippet: List all Form Errors\n\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003026310_django_python.txt |
Q:
Is there a performance gain from defining routes in app.yaml versus one large mapping in a WSGIApplication in AppEngine?
Scenario 1
This involves using one "gateway" route in app.yaml and then choosing the RequestHandler in the WSGIApplication.
app.yaml
- url: /.*
script: main.py
main.py
from google.appengine.ext import webapp
class Page1(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 1")
class Page2(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 2")
application = webapp.WSGIApplication([
('/page1/', Page1),
('/page2/', Page2),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
Scenario 2:
This involves defining two routes in app.yaml and then two separate scripts for each (page1.py and page2.py).
app.yaml
- url: /page1/
script: page1.py
- url: /page2/
script: page2.py
page1.py
from google.appengine.ext import webapp
class Page1(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 1")
application = webapp.WSGIApplication([
('/page1/', Page1),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
page2.py
from google.appengine.ext import webapp
class Page2(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 2")
application = webapp.WSGIApplication([
('/page2/', Page2),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
Question
What are the benefits and drawbacks of each pattern? Is one much faster than the other?
A:
The only performance implication relates to the loading of modules: Modules are loaded on an instance when they're first used, and splitting things up requires fewer module loads to serve a page on a new instance.
This is pretty minimal, though, as you can just as easily have the handler script dynamically load the needed module on-demand - and that's what many common frameworks already do.
In general, app.yaml routing is designed for routing between distinct components or applications. For example, remote_api and deferred both have their own handlers. It's perfectly reasonable, therefore, to have a single handler defined for your app that handles everything else.
A:
I don't believe there's any performance implication, but splitting your app into files based on functionality will help you manage it better, especially if it's being developed by multiple people.
For example, all handlers that have to do with viewing, editing, deleting, etc., pages could be in pages.py while all handlers that have to do with viewing, etc., user profiles could be in user_profiles.py, and all handlers having to do with a JSON REST API could be in rest_api.py, and so on.
But again, I don't believe this has any runtime performance implication, just a development-time performance implication.
| Is there a performance gain from defining routes in app.yaml versus one large mapping in a WSGIApplication in AppEngine? | Scenario 1
This involves using one "gateway" route in app.yaml and then choosing the RequestHandler in the WSGIApplication.
app.yaml
- url: /.*
script: main.py
main.py
from google.appengine.ext import webapp
class Page1(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 1")
class Page2(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 2")
application = webapp.WSGIApplication([
('/page1/', Page1),
('/page2/', Page2),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
Scenario 2:
This involves defining two routes in app.yaml and then two separate scripts for each (page1.py and page2.py).
app.yaml
- url: /page1/
script: page1.py
- url: /page2/
script: page2.py
page1.py
from google.appengine.ext import webapp
class Page1(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 1")
application = webapp.WSGIApplication([
('/page1/', Page1),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
page2.py
from google.appengine.ext import webapp
class Page2(webapp.RequestHandler):
def get(self):
self.response.out.write("Page 2")
application = webapp.WSGIApplication([
('/page2/', Page2),
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
Question
What are the benefits and drawbacks of each pattern? Is one much faster than the other?
| [
"The only performance implication relates to the loading of modules: Modules are loaded on an instance when they're first used, and splitting things up requires fewer module loads to serve a page on a new instance.\nThis is pretty minimal, though, as you can just as easily have the handler script dynamically load the needed module on-demand - and that's what many common frameworks already do.\nIn general, app.yaml routing is designed for routing between distinct components or applications. For example, remote_api and deferred both have their own handlers. It's perfectly reasonable, therefore, to have a single handler defined for your app that handles everything else.\n",
"I don't believe there's any performance implication, but splitting your app into files based on functionality will help you manage it better, especially if it's being developed by multiple people.\nFor example, all handlers that have to do with viewing, editing, deleting, etc., pages could be in pages.py while all handlers that have to do with viewing, etc., user profiles could be in user_profiles.py, and all handlers having to do with a JSON REST API could be in rest_api.py, and so on.\nBut again, I don't believe this has any runtime performance implication, just a development-time performance implication.\n"
] | [
12,
6
] | [] | [] | [
"google_app_engine",
"performance",
"python",
"yaml"
] | stackoverflow_0003025921_google_app_engine_performance_python_yaml.txt |
Q:
Invoking a superclass's class methods in Python
I am working on a Flask extension that adds CouchDB support to Flask. To make it easier, I have subclassed couchdb.mapping.Document so the store and load methods can use the current thread-local database. Right now, my code looks like this:
class Document(mapping.Document):
# rest of the methods omitted for brevity
@classmethod
def load(cls, id, db=None):
return mapping.Document.load(cls, db or g.couch, id)
I left out some for brevity, but that's the important part. However, due to the way classmethod works, when I try to call this method, I receive the error message
File "flaskext/couchdb.py", line 187, in load
return mapping.Document.load(cls, db or g.couch, id)
TypeError: load() takes exactly 3 arguments (4 given)
I tested replacing the call with mapping.Document.load.im_func(cls, db or g.couch, id), and it works, but I'm not particularly happy about accessing the internal im_ attributes (even though they are documented). Does anyone have a more elegant way to handle this?
A:
I think you actually need to use super here. That's the neater way to call superclass methods anyway:
class A(object):
@classmethod
def load(cls):
return cls
class B(A):
@classmethod
def load(cls):
# return A.load() would simply do "A.load()" and thus return a A
return super(B, cls).load() # super figures out how to do it right ;-)
print B.load()
| Invoking a superclass's class methods in Python | I am working on a Flask extension that adds CouchDB support to Flask. To make it easier, I have subclassed couchdb.mapping.Document so the store and load methods can use the current thread-local database. Right now, my code looks like this:
class Document(mapping.Document):
# rest of the methods omitted for brevity
@classmethod
def load(cls, id, db=None):
return mapping.Document.load(cls, db or g.couch, id)
I left out some for brevity, but that's the important part. However, due to the way classmethod works, when I try to call this method, I receive the error message
File "flaskext/couchdb.py", line 187, in load
return mapping.Document.load(cls, db or g.couch, id)
TypeError: load() takes exactly 3 arguments (4 given)
I tested replacing the call with mapping.Document.load.im_func(cls, db or g.couch, id), and it works, but I'm not particularly happy about accessing the internal im_ attributes (even though they are documented). Does anyone have a more elegant way to handle this?
| [
"I think you actually need to use super here. That's the neater way to call superclass methods anyway:\nclass A(object):\n @classmethod\n def load(cls):\n return cls\n\nclass B(A):\n @classmethod\n def load(cls):\n # return A.load() would simply do \"A.load()\" and thus return a A\n return super(B, cls).load() # super figures out how to do it right ;-)\n\n\nprint B.load()\n\n"
] | [
7
] | [] | [] | [
"class_method",
"python",
"superclass"
] | stackoverflow_0003026392_class_method_python_superclass.txt |
Q:
Outgoing UDP sniffer in python?
I want to figure out whether my computer is somehow causing a UDP flood that is originating from my network. So that's my underlying problem, and what follows is simply my non-network-person attempt to hypothesize a solution using python. I'm extrapolating from recipe 13.1 ("Passing Messages with Socket Datagrams") from the python cookbook (also here).
Would it possible/sensible/not insane to try somehow writing an outgoing UDP proxy in python, so that outgoing packets could be logged before being sent on their merry way? If so, how would one go about it? Based on my quick research, perhaps I could start a server process listening on suspect UDP ports and log anything that gets sent, then forward it on, such as:
import socket
s =socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", MYPORT))
while True:
packet = dict(zip('data', 'addr'), s.recvfrom(1,024))
log.info("Recieved {data} from {addr}.".format(**packet))
But what about doing this for a large number of ports simultaneously? Impractical? Are there drawbacks or other reasons not to bother with this? Is there a better way to solve this problem (please be gentle).
A:
It might be easier just to install Wireshark, instead of rolling your own in Python.
| Outgoing UDP sniffer in python? | I want to figure out whether my computer is somehow causing a UDP flood that is originating from my network. So that's my underlying problem, and what follows is simply my non-network-person attempt to hypothesize a solution using python. I'm extrapolating from recipe 13.1 ("Passing Messages with Socket Datagrams") from the python cookbook (also here).
Would it possible/sensible/not insane to try somehow writing an outgoing UDP proxy in python, so that outgoing packets could be logged before being sent on their merry way? If so, how would one go about it? Based on my quick research, perhaps I could start a server process listening on suspect UDP ports and log anything that gets sent, then forward it on, such as:
import socket
s =socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", MYPORT))
while True:
packet = dict(zip('data', 'addr'), s.recvfrom(1,024))
log.info("Recieved {data} from {addr}.".format(**packet))
But what about doing this for a large number of ports simultaneously? Impractical? Are there drawbacks or other reasons not to bother with this? Is there a better way to solve this problem (please be gentle).
| [
"It might be easier just to install Wireshark, instead of rolling your own in Python.\n"
] | [
5
] | [] | [] | [
"networking",
"proxy",
"python",
"twisted",
"udp"
] | stackoverflow_0003026833_networking_proxy_python_twisted_udp.txt |
Q:
Universal syntax file format?
Hey as a project to improve my programing skills I've begun programing a nice code editor in python to teach myself project management, version control, and gui programming. I was wanting to utilize syntax files made for other programs so I could have a large collection already. I was wondering if there was any kind of universal syntax file format much in the same sense as .odt files. I heard of one once in a forum, it had a website, but I can't remember it now. If not I may just try to use gedit syntax files or geany.
thanks
A:
If you're planning to do syntax highlighting, check out Pygments, especially the bit about lexers.
Since you mentioned Geany, you might want to look at the Scintilla docs. (Geany is built upon Scintilla).
You might find this post interesting.
Also, be sure to get familiar with the venerable lex and yacc.
A:
Not sure what .odt has to do with any of this.
I could see some sort of BNF being able to describe (almost) any syntax: Just run the text and the BNF through a parser, and apply a color scheme to the terminals. You could even get a bit more fancy, since you'd have the syntax tree.
In reality, I think most syntax files take an easier approach, such as regular expressions. This would put then somewhere above regular expressions but not really quite context-free in terms of power.
As for file formats, if you re-use something that exists, then you can just loot and pillage (subject to license agreements) their syntax file data.
| Universal syntax file format? | Hey as a project to improve my programing skills I've begun programing a nice code editor in python to teach myself project management, version control, and gui programming. I was wanting to utilize syntax files made for other programs so I could have a large collection already. I was wondering if there was any kind of universal syntax file format much in the same sense as .odt files. I heard of one once in a forum, it had a website, but I can't remember it now. If not I may just try to use gedit syntax files or geany.
thanks
| [
"If you're planning to do syntax highlighting, check out Pygments, especially the bit about lexers.\nSince you mentioned Geany, you might want to look at the Scintilla docs. (Geany is built upon Scintilla).\nYou might find this post interesting.\nAlso, be sure to get familiar with the venerable lex and yacc.\n",
"Not sure what .odt has to do with any of this.\nI could see some sort of BNF being able to describe (almost) any syntax: Just run the text and the BNF through a parser, and apply a color scheme to the terminals. You could even get a bit more fancy, since you'd have the syntax tree.\nIn reality, I think most syntax files take an easier approach, such as regular expressions. This would put then somewhere above regular expressions but not really quite context-free in terms of power.\nAs for file formats, if you re-use something that exists, then you can just loot and pillage (subject to license agreements) their syntax file data.\n"
] | [
2,
0
] | [] | [] | [
"editor",
"python",
"syntax",
"text_editor"
] | stackoverflow_0003026786_editor_python_syntax_text_editor.txt |
Q:
Templates vs. coded HTML
I have a web-app consisting of some html forms for maintaining some tables (SQlite, with CherryPy for web-server stuff). First I did it entirely 'the Python way', and generated html strings via. code, with common headers, footers, etc. defined as functions in a separate module.
I also like the idea of templates, so I tried Jinja2, which I find quite developer-friendly. In the beginning I thought templates were the way to go, but that was when pages were simple. Once .css and .js files were introduced (not necessarily in the same folder as the .html files), and an ever-increasing number of {{...}} variables and {%...%} commands were introduced, things started getting messy at design-time, even though they looked great at run-time. Things got even more difficult when I needed additional javascript in the or sections.
As far as I can see, the main advantages of using templates are:
Non-dynamic elements of page can easily be viewed in browser during design.
Except for {} placeholders, html is kept separate from python code.
If your company has a web-page designer, they can still design without knowing Python.
while some disadvantages are:
{{}} delimiters visible when viewed at design-time in browser
Associated .css and .js files have to be in same folder to see effects in browser at design-time.
Data, variables, lists, etc., must be prepared in advanced and either declared globally or passed as parameters to render() function.
So - when to use 'hard-coded' HTML, and when to use templates? I am not sure of the best way to go, so I would be interested to hear other developers' views.
TIA, Alan
A:
Although I'm not a Python developer, I'll answer here - I believe the idea of using templates is common for PHP and Python.
Using templates has many advantages, like:
keeping the code clean. Separating the "logic" (controller) code from the presentation (view) is very important. Working on projects that mix HTML / CSS / JS / Python is really hard.
keeping HTML in separate files doesn't require you to modify the code itself. For example, placing in the controller code (Python code) might require you to put a slash before each " character.
you can ask your web designer to learn the basics of templates syntax so he's able to help you much without destroying your work on the controller code (which is quite common when a person with no experience in a given language modifies something)
in fact, there are many more advantages, but those are most important for me.
The only disadvantage is that you have to pass parameters to the rendering function ... which doesn't require much of work. Anyway it's much easier than maintaining any project that mixes controller code with view code.
Generally, you should have a look at >MVC pros and cons question< :
What is MVC and what are the advantages of it?
A:
The simplest way to solve your static file problem is to use relative paths when referring to them in your html. For example: <img src="static/image.jpg" />
If you're willing to put in a little more work, you can solve all the design-time problems you mentioned by writing a mini-server to display your templates.
Maintain a file full of simple data structures containing example values for all your templates.
Use a microframework like Werkzeug to serve http on your local machine.
Write a root request handler that scans your data structure list or templates directory to produce an index page with links to all your templates.
Write a secondary request handler for non-root requests, which renders the requested template with the data structure of the same name.
You can write this tool in a few hours, and it makes template design very convenient. One nice feature of Werkzeug's built-in wsgi server is that it can automatically reload itself when it detects that a file has changed. You can leave your mini-server running while you edit templates and click links on your index page all day.
A:
I would highly recommend using templates. Templates help to encourage a good MVC structure to your application. Python code that emits HTML, IMHO, is wrong. The reason I say that is because Python code should be responsible for doing logic and not have to worry about presentation. Template syntax is usually restrictive enough that you can't really do much logic within the template, but you can do any presentation specific type logic that you may need.
ymmv.
A:
I think that templates are still the best way to separate presentation from business logic. The key is a good templating engine, in particular, one that can make decisions in the template itself. For Python, I've found the Genshi templating engine to be quite good. It's used by the Trac Wiki/Issue tracking system and is quite powerful, while still leaving the templates easy to work with.
For other tasks, I tend to use the BeautifulSoup module. I'll create a simple HTML page, parse it with BeautifulSoup, use the resulting object to add the necessary data, and then write the output to its destination (typically a file for me).
A:
As a Seaside developer, I see no use for templates, if your designer can do css. In practice, I find it impossible to keep templates DRY. Take a look at this question to see the advantages of using code (a DSL) to generate your page. You might be bound by legacy, of course.
Separation of presentation (html) and business logic in web apps does not lead to good modularisation, i.e. low coupling and high cohesion. That is why separate template systems don't work well.
I just read Jeff Atwoods "What's Wrong With CSS". This again is a problem long solved in the smalltalk world with the Phantasia DSL
| Templates vs. coded HTML | I have a web-app consisting of some html forms for maintaining some tables (SQlite, with CherryPy for web-server stuff). First I did it entirely 'the Python way', and generated html strings via. code, with common headers, footers, etc. defined as functions in a separate module.
I also like the idea of templates, so I tried Jinja2, which I find quite developer-friendly. In the beginning I thought templates were the way to go, but that was when pages were simple. Once .css and .js files were introduced (not necessarily in the same folder as the .html files), and an ever-increasing number of {{...}} variables and {%...%} commands were introduced, things started getting messy at design-time, even though they looked great at run-time. Things got even more difficult when I needed additional javascript in the or sections.
As far as I can see, the main advantages of using templates are:
Non-dynamic elements of page can easily be viewed in browser during design.
Except for {} placeholders, html is kept separate from python code.
If your company has a web-page designer, they can still design without knowing Python.
while some disadvantages are:
{{}} delimiters visible when viewed at design-time in browser
Associated .css and .js files have to be in same folder to see effects in browser at design-time.
Data, variables, lists, etc., must be prepared in advanced and either declared globally or passed as parameters to render() function.
So - when to use 'hard-coded' HTML, and when to use templates? I am not sure of the best way to go, so I would be interested to hear other developers' views.
TIA, Alan
| [
"Although I'm not a Python developer, I'll answer here - I believe the idea of using templates is common for PHP and Python.\nUsing templates has many advantages, like:\n\nkeeping the code clean. Separating the \"logic\" (controller) code from the presentation (view) is very important. Working on projects that mix HTML / CSS / JS / Python is really hard.\nkeeping HTML in separate files doesn't require you to modify the code itself. For example, placing in the controller code (Python code) might require you to put a slash before each \" character.\nyou can ask your web designer to learn the basics of templates syntax so he's able to help you much without destroying your work on the controller code (which is quite common when a person with no experience in a given language modifies something)\n\nin fact, there are many more advantages, but those are most important for me.\nThe only disadvantage is that you have to pass parameters to the rendering function ... which doesn't require much of work. Anyway it's much easier than maintaining any project that mixes controller code with view code.\nGenerally, you should have a look at >MVC pros and cons question< :\nWhat is MVC and what are the advantages of it?\n",
"The simplest way to solve your static file problem is to use relative paths when referring to them in your html. For example: <img src=\"static/image.jpg\" />\nIf you're willing to put in a little more work, you can solve all the design-time problems you mentioned by writing a mini-server to display your templates.\n\nMaintain a file full of simple data structures containing example values for all your templates.\nUse a microframework like Werkzeug to serve http on your local machine.\nWrite a root request handler that scans your data structure list or templates directory to produce an index page with links to all your templates.\nWrite a secondary request handler for non-root requests, which renders the requested template with the data structure of the same name.\n\nYou can write this tool in a few hours, and it makes template design very convenient. One nice feature of Werkzeug's built-in wsgi server is that it can automatically reload itself when it detects that a file has changed. You can leave your mini-server running while you edit templates and click links on your index page all day.\n",
"I would highly recommend using templates. Templates help to encourage a good MVC structure to your application. Python code that emits HTML, IMHO, is wrong. The reason I say that is because Python code should be responsible for doing logic and not have to worry about presentation. Template syntax is usually restrictive enough that you can't really do much logic within the template, but you can do any presentation specific type logic that you may need.\nymmv.\n",
"I think that templates are still the best way to separate presentation from business logic. The key is a good templating engine, in particular, one that can make decisions in the template itself. For Python, I've found the Genshi templating engine to be quite good. It's used by the Trac Wiki/Issue tracking system and is quite powerful, while still leaving the templates easy to work with.\nFor other tasks, I tend to use the BeautifulSoup module. I'll create a simple HTML page, parse it with BeautifulSoup, use the resulting object to add the necessary data, and then write the output to its destination (typically a file for me).\n",
"As a Seaside developer, I see no use for templates, if your designer can do css. In practice, I find it impossible to keep templates DRY. Take a look at this question to see the advantages of using code (a DSL) to generate your page. You might be bound by legacy, of course.\nSeparation of presentation (html) and business logic in web apps does not lead to good modularisation, i.e. low coupling and high cohesion. That is why separate template systems don't work well.\nI just read Jeff Atwoods \"What's Wrong With CSS\". This again is a problem long solved in the smalltalk world with the Phantasia DSL\n"
] | [
5,
4,
1,
1,
1
] | [] | [] | [
"html",
"python",
"templates"
] | stackoverflow_0003026731_html_python_templates.txt |
Q:
How to use a Proxy with Youtube API? (Python)
I'm working a script that will upload videos to YouTube with different accounts. Is there a way to use HTTPS or SOCKS proxies to filter all the requests. My client doesn't want to leave any footprints for Google. The only way I found was to set the proxy environment variable beforehand but this seems cumbersome. Is there some way I'm missing?
Thanks :)
A:
Setting an environment variable (e.g. import os; os.environ['BLAH']='BLUH' once at the start of your program "seems cumbersome"?! What does count as "non-cumbersome" for you, pray?
| How to use a Proxy with Youtube API? (Python) | I'm working a script that will upload videos to YouTube with different accounts. Is there a way to use HTTPS or SOCKS proxies to filter all the requests. My client doesn't want to leave any footprints for Google. The only way I found was to set the proxy environment variable beforehand but this seems cumbersome. Is there some way I'm missing?
Thanks :)
| [
"Setting an environment variable (e.g. import os; os.environ['BLAH']='BLUH' once at the start of your program \"seems cumbersome\"?! What does count as \"non-cumbersome\" for you, pray?\n"
] | [
0
] | [] | [] | [
"api",
"gdata",
"python",
"youtube"
] | stackoverflow_0003026881_api_gdata_python_youtube.txt |
Q:
Execute a PyQt app from an acpi event in linux
I want to use a PyQt application to display an image when some acpi event is triggered under linux.
I already setting up the configuration for the event and the python scrip is executed when the event is triggered, but when program reach the creation of the QApplication
app = QApplication(sys.argv)
it stops without error.
I tried setting up the same DISPLAY and PATH environment variables as my current user but it doesn't work.
This is my event file:
event=sony/hotkey SNC 00000001 00000011
action=/etc/acpi/vaio-tools/brightness/sonybright.sh up 2>&1>/tmp/vaio-tools_brightness.log
I tried to find some error in the /tmp/vaio-tools_brightness.log but it doesn't log anything after it reach the QApp creation in code.
any hints??
A:
Your application is run by root who doesn't have access to your users's X display.
Either set $XAUTHORITY to the path of the X authority file used by your user or use something like this (untested):
su your_user -l -c "xauth extract - $DISPLAY" | xauth merge -
See the man pages for xauth and Xsecurity for more about this.
A better solution would be to have the ACPI event to send a message via DBus and run your application in the user's session listening to that message.
| Execute a PyQt app from an acpi event in linux | I want to use a PyQt application to display an image when some acpi event is triggered under linux.
I already setting up the configuration for the event and the python scrip is executed when the event is triggered, but when program reach the creation of the QApplication
app = QApplication(sys.argv)
it stops without error.
I tried setting up the same DISPLAY and PATH environment variables as my current user but it doesn't work.
This is my event file:
event=sony/hotkey SNC 00000001 00000011
action=/etc/acpi/vaio-tools/brightness/sonybright.sh up 2>&1>/tmp/vaio-tools_brightness.log
I tried to find some error in the /tmp/vaio-tools_brightness.log but it doesn't log anything after it reach the QApp creation in code.
any hints??
| [
"Your application is run by root who doesn't have access to your users's X display. \nEither set $XAUTHORITY to the path of the X authority file used by your user or use something like this (untested):\nsu your_user -l -c \"xauth extract - $DISPLAY\" | xauth merge -\n\nSee the man pages for xauth and Xsecurity for more about this.\nA better solution would be to have the ACPI event to send a message via DBus and run your application in the user's session listening to that message.\n"
] | [
0
] | [] | [] | [
"acpi",
"linux",
"pyqt",
"python",
"qt"
] | stackoverflow_0003026678_acpi_linux_pyqt_python_qt.txt |
Q:
Python imports by folder module
I have a directory structure:
example.py
templates/
__init__.py
a.py
b.py
a.py and b.py have only one class, named the same as the file (because they are cheetah templates). For purely style reasons, I want to be able to import and use these classes in example.py like so:
import templates
t = templates.a()
Right now I do that by having this in the template folder's __init__.py:
__all__ = ["a", "b"]
from . import *
However, this seems pretty poor (and maybe superfluous), and doesn't even do what I want, as I have to use the classes like this:
t = templates.a.a()
Thoughts?
A:
To avoid repeating from <whatever> import * 25 times, you need a loop, such as:
import sys
def _allimports(modnames)
thismod = sys.modules[__name__]
for modname in modnames:
submodname = '%s.%s' % (thismod, modname)
__import__(submodname)
submod = sys.modules[submodname]
thismod.__dict__.update(submod.__dict__)
_allimports('a b c d e'.split()) # or whatever
I'm putting the meaningful code in a function because (a) it's always best [[for performance and to avoid polluting the module's namespace]], (b) in this particular case it also avoids accidents (e.g., some submodule might define a name thismod or modnames... so it's important to keep those names that we're using in the loop local to the function, not module globals, so they can't be accidentally trampled;-).
If you want to enforce the fact that a module named modname only has one class (or other global) with the same name, change the last statement of the loop to:
setattr(thismod, modname, getattr(submod, modname))
A:
In your __init__.py:
from a import *
from b import *
Now all of a's contents will be in templates, as will all of b's contents.
A:
I didn't even know you could have from . import *. My python interpreter complains about such statements. Still, to your problem, you could do:
# __init__.py
from . import a, b
a = a.a
b = a.b
you can now use
# example.py
import templates
t = templates.a()
other solution:
# __init__.py
from a import *
from b import *
| Python imports by folder module | I have a directory structure:
example.py
templates/
__init__.py
a.py
b.py
a.py and b.py have only one class, named the same as the file (because they are cheetah templates). For purely style reasons, I want to be able to import and use these classes in example.py like so:
import templates
t = templates.a()
Right now I do that by having this in the template folder's __init__.py:
__all__ = ["a", "b"]
from . import *
However, this seems pretty poor (and maybe superfluous), and doesn't even do what I want, as I have to use the classes like this:
t = templates.a.a()
Thoughts?
| [
"To avoid repeating from <whatever> import * 25 times, you need a loop, such as:\nimport sys\n\ndef _allimports(modnames)\n thismod = sys.modules[__name__]\n\n for modname in modnames:\n submodname = '%s.%s' % (thismod, modname)\n __import__(submodname)\n submod = sys.modules[submodname]\n thismod.__dict__.update(submod.__dict__)\n\n_allimports('a b c d e'.split()) # or whatever\n\nI'm putting the meaningful code in a function because (a) it's always best [[for performance and to avoid polluting the module's namespace]], (b) in this particular case it also avoids accidents (e.g., some submodule might define a name thismod or modnames... so it's important to keep those names that we're using in the loop local to the function, not module globals, so they can't be accidentally trampled;-).\nIf you want to enforce the fact that a module named modname only has one class (or other global) with the same name, change the last statement of the loop to:\n setattr(thismod, modname, getattr(submod, modname))\n\n",
"In your __init__.py:\nfrom a import *\nfrom b import *\n\nNow all of a's contents will be in templates, as will all of b's contents.\n",
"I didn't even know you could have from . import *. My python interpreter complains about such statements. Still, to your problem, you could do:\n# __init__.py\nfrom . import a, b\na = a.a\nb = a.b\n\nyou can now use\n# example.py\nimport templates\nt = templates.a()\n\nother solution:\n# __init__.py\nfrom a import *\nfrom b import *\n\n"
] | [
4,
3,
3
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003027091_import_python.txt |
Q:
create a class attribute without going through __setattr__
What I have below is a class I made to easily store a bunch of data as attributes.
They wind up getting stored in a dictionary.
I override __getattr__ and __setattr__ to store and retrieve the values back in different types of units.
When I started overriding __setattr__ I was having trouble creating that initial dicionary in the 2nd line of __init__ like so...
super(MyDataFile, self).__setattr__('_data', {})
My question...
Is there an easier way to create a class level attribute with going through __setattr__?
Also, should I be concerned about keeping a separate dictionary or should I just store everything in self.__dict__?
#!/usr/bin/env python
from unitconverter import convert
import re
special_attribute_re = re.compile(r'(.+)__(.+)')
class MyDataFile(object):
def __init__(self, *args, **kwargs):
super(MyDataFile, self).__init__(*args, **kwargs)
super(MyDataFile, self).__setattr__('_data', {})
#
# For attribute type access
#
def __setattr__(self, name, value):
self._data[name] = value
def __getattr__(self, name):
if name in self._data:
return self._data[name]
match = special_attribute_re.match(name)
if match:
varname, units = match.groups()
if varname in self._data:
return self.getvaras(varname, units)
raise AttributeError
#
# other methods
#
def getvaras(self, name, units):
from_val, from_units = self._data[name]
if from_units == units:
return from_val
return convert(from_val, from_units, units), units
def __str__(self):
return str(self._data)
d = MyDataFile()
print d
# set like a dictionary or an attribute
d.XYZ = 12.34, 'in'
d.ABC = 76.54, 'ft'
# get it back like a dictionary or an attribute
print d.XYZ
print d.ABC
# get conversions using getvaras or using a specially formed attribute
print d.getvaras('ABC', 'cm')
print d.XYZ__mm
A:
Your __setattr__ in the example doesn't do anything except put things in _data instead of __dict__ Remove it.
Change your __getattr__ to use __dict__.
Store your value and units as a simple 2-tuple.
| create a class attribute without going through __setattr__ | What I have below is a class I made to easily store a bunch of data as attributes.
They wind up getting stored in a dictionary.
I override __getattr__ and __setattr__ to store and retrieve the values back in different types of units.
When I started overriding __setattr__ I was having trouble creating that initial dicionary in the 2nd line of __init__ like so...
super(MyDataFile, self).__setattr__('_data', {})
My question...
Is there an easier way to create a class level attribute with going through __setattr__?
Also, should I be concerned about keeping a separate dictionary or should I just store everything in self.__dict__?
#!/usr/bin/env python
from unitconverter import convert
import re
special_attribute_re = re.compile(r'(.+)__(.+)')
class MyDataFile(object):
def __init__(self, *args, **kwargs):
super(MyDataFile, self).__init__(*args, **kwargs)
super(MyDataFile, self).__setattr__('_data', {})
#
# For attribute type access
#
def __setattr__(self, name, value):
self._data[name] = value
def __getattr__(self, name):
if name in self._data:
return self._data[name]
match = special_attribute_re.match(name)
if match:
varname, units = match.groups()
if varname in self._data:
return self.getvaras(varname, units)
raise AttributeError
#
# other methods
#
def getvaras(self, name, units):
from_val, from_units = self._data[name]
if from_units == units:
return from_val
return convert(from_val, from_units, units), units
def __str__(self):
return str(self._data)
d = MyDataFile()
print d
# set like a dictionary or an attribute
d.XYZ = 12.34, 'in'
d.ABC = 76.54, 'ft'
# get it back like a dictionary or an attribute
print d.XYZ
print d.ABC
# get conversions using getvaras or using a specially formed attribute
print d.getvaras('ABC', 'cm')
print d.XYZ__mm
| [
"Your __setattr__ in the example doesn't do anything except put things in _data instead of __dict__ Remove it. \nChange your __getattr__ to use __dict__.\nStore your value and units as a simple 2-tuple. \n"
] | [
0
] | [] | [] | [
"class",
"python",
"setattr"
] | stackoverflow_0003024790_class_python_setattr.txt |
Q:
What does this `_time_independent_equals` mean?
In the tornado.web module there is a function called _time_independent_equals:
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
It is used to compare secure cookie signatures, and thus the name.
But regarding the implementation of this function, is it just a complex way to say a==b?
A:
That function does not simply compare the strings, it tries to always take the same amount of time to execute.
This is useful for security tasks like comparing passwords. If the function returned on the first mismatching byte, an attacker could try all possible first bytes and know that the one that takes longest is a match. Then they could try all possible second bytes and know that the one that takes longest is a match. This can be repeated until the entire string is deduced. (In reality you have to do a lot of averaging to overcome random delays in the network, but it works if you are patient.)
| What does this `_time_independent_equals` mean? | In the tornado.web module there is a function called _time_independent_equals:
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
It is used to compare secure cookie signatures, and thus the name.
But regarding the implementation of this function, is it just a complex way to say a==b?
| [
"That function does not simply compare the strings, it tries to always take the same amount of time to execute.\nThis is useful for security tasks like comparing passwords. If the function returned on the first mismatching byte, an attacker could try all possible first bytes and know that the one that takes longest is a match. Then they could try all possible second bytes and know that the one that takes longest is a match. This can be repeated until the entire string is deduced. (In reality you have to do a lot of averaging to overcome random delays in the network, but it works if you are patient.)\n"
] | [
18
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0003027286_python_tornado.txt |
Q:
Django not recognizing django admin urls
I just registered my models my models with django admin.
I navigate to the django admin at /admin. I log in sucessfully and I can see all my models. great so far.
But now if I try to click one of the links, for Ex: 'users', django gives me a 404 saying
The current URL, admin/auth/user/, didn't match any of these.
Its really weird because in my urls.py I have it mapped correctly
(r'^admin/', include(admin.site.urls)),
I have all the required middleware enabled and have these in my installed apps
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
anyone have any idea? Thanks.
A:
Do you have this one in your urls.py?:
from django.contrib import admin
admin.autodiscover()
But in fact without this you shouldn't even see models from django.contrib.auth... weird, can you post complete urls.pt file?
| Django not recognizing django admin urls | I just registered my models my models with django admin.
I navigate to the django admin at /admin. I log in sucessfully and I can see all my models. great so far.
But now if I try to click one of the links, for Ex: 'users', django gives me a 404 saying
The current URL, admin/auth/user/, didn't match any of these.
Its really weird because in my urls.py I have it mapped correctly
(r'^admin/', include(admin.site.urls)),
I have all the required middleware enabled and have these in my installed apps
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
anyone have any idea? Thanks.
| [
"Do you have this one in your urls.py?:\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nBut in fact without this you shouldn't even see models from django.contrib.auth... weird, can you post complete urls.pt file?\n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003027440_django_django_admin_python.txt |
Q:
How to select random image of specific size using Django / Python?
I've been using this little snippet to select random images. However I would like to change it to select only images of a certain size. I'm running into trouble checking against image size. If I use get_image_dimensions() I need to use a conditional statement, which then requires that I allow exceptions. So, I guess I need some pointers on just limiting by image dimensions. Thanks.
import os
import random
import posixpath
from django import template
from django.conf import settings
register = template.Library()
def is_image_file(filename):
"""Does `filename` appear to be an image file?"""
img_types = [".jpg", ".jpeg", ".png", ".gif"]
ext = os.path.splitext(filename)[1]
return ext in img_types
@register.simple_tag
def random_image(path):
"""
Select a random image file from the provided directory
and return its href. `path` should be relative to MEDIA_ROOT.
Usage: <img src='{% random_image "images/whatever/" %}'>
"""
fullpath = os.path.join(settings.MEDIA_ROOT, path)
filenames = [f for f in os.listdir(fullpath) if is_image_file(f)]
pick = random.choice(filenames)
return posixpath.join(settings.MEDIA_URL, path, pick)
A:
Well, a more direct way to get image dimensions is using the Python Imaging Library (which is what Django uses for get_image_dimensions in the backend anyway).
So, you use it like:
>> import Image
>> img = Image.open("foo.png")
>> img.size
(1729,828)
And your very simplest solution would be something like:
img_dimensions = lambda f: Image.open(f).size
filenames = filter(lambda f: is_image_file(f) and img_dimensions(f)==my_dimensions, os.listdir(fullpath))
where my_dimensions are -- your dimensions.
Problem is, that this (as well as any other method that checks file dimensions) actually has to open and read the images each time, which is not smart to do repeatedly. So depending on the load of your application, you will probably want to put img_dimensions() into a real, separate function and memoize it (http://code.activestate.com/recipes/52201-memoizing-cacheing-function-return-values/). Or if this is going to be a common task, just put images into folders pre-ordered by dimensions.
| How to select random image of specific size using Django / Python? | I've been using this little snippet to select random images. However I would like to change it to select only images of a certain size. I'm running into trouble checking against image size. If I use get_image_dimensions() I need to use a conditional statement, which then requires that I allow exceptions. So, I guess I need some pointers on just limiting by image dimensions. Thanks.
import os
import random
import posixpath
from django import template
from django.conf import settings
register = template.Library()
def is_image_file(filename):
"""Does `filename` appear to be an image file?"""
img_types = [".jpg", ".jpeg", ".png", ".gif"]
ext = os.path.splitext(filename)[1]
return ext in img_types
@register.simple_tag
def random_image(path):
"""
Select a random image file from the provided directory
and return its href. `path` should be relative to MEDIA_ROOT.
Usage: <img src='{% random_image "images/whatever/" %}'>
"""
fullpath = os.path.join(settings.MEDIA_ROOT, path)
filenames = [f for f in os.listdir(fullpath) if is_image_file(f)]
pick = random.choice(filenames)
return posixpath.join(settings.MEDIA_URL, path, pick)
| [
"Well, a more direct way to get image dimensions is using the Python Imaging Library (which is what Django uses for get_image_dimensions in the backend anyway).\nSo, you use it like:\n>> import Image\n>> img = Image.open(\"foo.png\")\n>> img.size\n(1729,828)\n\nAnd your very simplest solution would be something like:\nimg_dimensions = lambda f: Image.open(f).size\nfilenames = filter(lambda f: is_image_file(f) and img_dimensions(f)==my_dimensions, os.listdir(fullpath))\n\nwhere my_dimensions are -- your dimensions.\nProblem is, that this (as well as any other method that checks file dimensions) actually has to open and read the images each time, which is not smart to do repeatedly. So depending on the load of your application, you will probably want to put img_dimensions() into a real, separate function and memoize it (http://code.activestate.com/recipes/52201-memoizing-cacheing-function-return-values/). Or if this is going to be a common task, just put images into folders pre-ordered by dimensions.\n"
] | [
1
] | [] | [] | [
"django",
"image",
"limit",
"python",
"size"
] | stackoverflow_0003026274_django_image_limit_python_size.txt |
Q:
Assigning a material in Blender with a script
Question: How do you assign a material with a script to an object in blender?
Info:
I have this script to import a proprietary model type of mine that is basically a star map with object consisting of a single vertex. in order to make them look like stars and be visible they are all going to have a halo material assigned to them. I'm figuring out how to make this material and give it the values just fine, but I can't seem to get it to assign. I tried the most obvious thing which was:
objectName.setMaterial(materialName)
but that did nothing. and when i would take an object that had a material and call the getMaterial function on it, it would return nothing. there is something I'm missing here, can some one shed some light on it? Thanks.
~TA
A:
objectName.setMaterials([materials]) --- forgot that little "s".
Where the argument to setMaterials is a list of 16 items or less, all of which must be Materials or None.
http://www.zoo-logique.org/3D.Blender/scripts_python/API/Object.Object-class.html
| Assigning a material in Blender with a script | Question: How do you assign a material with a script to an object in blender?
Info:
I have this script to import a proprietary model type of mine that is basically a star map with object consisting of a single vertex. in order to make them look like stars and be visible they are all going to have a halo material assigned to them. I'm figuring out how to make this material and give it the values just fine, but I can't seem to get it to assign. I tried the most obvious thing which was:
objectName.setMaterial(materialName)
but that did nothing. and when i would take an object that had a material and call the getMaterial function on it, it would return nothing. there is something I'm missing here, can some one shed some light on it? Thanks.
~TA
| [
"objectName.setMaterials([materials]) --- forgot that little \"s\".\nWhere the argument to setMaterials is a list of 16 items or less, all of which must be Materials or None.\nhttp://www.zoo-logique.org/3D.Blender/scripts_python/API/Object.Object-class.html\n"
] | [
2
] | [] | [] | [
"blender",
"python",
"scripting"
] | stackoverflow_0003026498_blender_python_scripting.txt |
Q:
PycURL RESUME_FROM
I can't seem to get the RESUME_FROM option to work. Here's some example code that I have been testing with:
import os
import pycurl
import sys
def progress(total, existing, upload_t, upload_d):
try:
frac = float(existing)/float(total)
except:
frac = 0
sys.stdout.write("\r%s %3i%%" % ("file", frac*100) )
url = "http://launchpad.net/keryx/stable/0.92/+download/keryx_0.92.4.tar.gz"
filename = url.split("/")[-1].strip()
def test(debug_type, debug_msg):
print "debug(%d): %s" % (debug_type, debug_msg)
c = pycurl.Curl()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
# Setup writing
if os.path.exists(filename):
f = open(filename, "ab")
c.setopt(pycurl.RESUME_FROM, os.path.getsize(filename))
else:
f = open(filename, "wb")
c.setopt(pycurl.WRITEDATA, f)
#c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.DEBUGFUNCTION, test)
c.setopt(pycurl.NOPROGRESS, 0)
c.setopt(pycurl.PROGRESSFUNCTION, progress)
c.perform()
A:
It was actually resuming properly, however it appeared to be starting from the beginning again because the length from os.path.getsize(filename) was not added to existing in the progress function. Just a minor mistake! :)
| PycURL RESUME_FROM | I can't seem to get the RESUME_FROM option to work. Here's some example code that I have been testing with:
import os
import pycurl
import sys
def progress(total, existing, upload_t, upload_d):
try:
frac = float(existing)/float(total)
except:
frac = 0
sys.stdout.write("\r%s %3i%%" % ("file", frac*100) )
url = "http://launchpad.net/keryx/stable/0.92/+download/keryx_0.92.4.tar.gz"
filename = url.split("/")[-1].strip()
def test(debug_type, debug_msg):
print "debug(%d): %s" % (debug_type, debug_msg)
c = pycurl.Curl()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
# Setup writing
if os.path.exists(filename):
f = open(filename, "ab")
c.setopt(pycurl.RESUME_FROM, os.path.getsize(filename))
else:
f = open(filename, "wb")
c.setopt(pycurl.WRITEDATA, f)
#c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.DEBUGFUNCTION, test)
c.setopt(pycurl.NOPROGRESS, 0)
c.setopt(pycurl.PROGRESSFUNCTION, progress)
c.perform()
| [
"It was actually resuming properly, however it appeared to be starting from the beginning again because the length from os.path.getsize(filename) was not added to existing in the progress function. Just a minor mistake! :)\n"
] | [
3
] | [] | [] | [
"pycurl",
"python",
"resume_download"
] | stackoverflow_0003027677_pycurl_python_resume_download.txt |
Q:
Overlapping matches with finditer() in Python
I'm using a regex to match Bible verse references in a text. The current regex is
REF_REGEX = re.compile('''
(?<!\w) # Not preceded by any words
(?P<quote>q(?:uote)?\s+)? # Match optional 'q' or 'quote' followed by many spaces
(?P<book>
(?:(?:[1-3]|I{1,3})\s*)? # Match an optional arabic or roman number between 1 and 3.
[A-Za-z]+ # Match any alphabetics
)\.? # Followed by an optional dot
(?:
\s*(?P<chapter>\d+) # Match the chapter number
(?:
[:\.](?P<startverse>\d+) # Match the starting verse number, preceded by ':' or '.'
(?:-(?P<endverse>\d+))? # Match the optional ending verse number, preceded by '-'
)? # Verse numbers are optional
)
(?:
\s+(?: # Here be spaces
(?:from\s+)|(?:in\s+)|(?P<lbrace>\()) # Match 'from[:space:]', 'in[:space:]' or '('
\s*(?P<version>\w+) # Match a word preceded by optional spaces
(?(lbrace)\)) # Close the '(' if found earlier
)? # The whole 'in|from|()' is optional
''', re.IGNORECASE | re.VERBOSE | re.UNICODE)
This matches the following expressions fine:
"jn 3:16": (None, 'jn', '3', '16', None, None, None),
"matt. 18:21-22": (None, 'matt', '18', '21', '22', None, None),
"q matt. 18:21-22": ('q ', 'matt', '18', '21', '22', None, None),
"QuOTe jn 3:16": ('QuOTe ', 'jn', '3', '16', None, None, None),
"q 1co13:1": ('q ', '1co', '13', '1', None, None, None),
"q 1 co 13:1": ('q ', '1 co', '13', '1', None, None, None),
"quote 1 co 13:1": ('quote ', '1 co', '13', '1', None, None, None),
"quote 1co13:1": ('quote ', '1co', '13', '1', None, None, None),
"jean 3:18 (PDV)": (None, 'jean', '3', '18', None, '(', 'PDV'),
"quote malachie 1.1-2 fRom Colombe": ('quote ', 'malachie', '1', '1', '2', None, 'Colombe'),
"quote malachie 1.1-2 In Colombe": ('quote ', 'malachie', '1', '1', '2', None, 'Colombe'),
"cinq jn 3:16 (test)": (None, 'jn', '3', '16', None, '(', 'test'),
"Q IIKings5.13-58 from wolof": ('Q ', 'IIKings', '5', '13', '58', None, 'wolof'),
"This text is about lv5.4-6 in KJV only": (None, 'lv', '5', '4', '6', None, 'KJV'),
but it fails to parse:
"Found in 2 Cor. 5:18-21 ( Ministers": (None, '2 Cor', '5', '18', '21', None, None),
because it returns (None, 'in', '2', None, None, None, None) instead.
Is there a way to get finditer() to return all matches, even if they overlap, or is there a way to improve my regex so it matches this last bit properly?
Thanks.
A:
A character consumed is consumed, you should not ask the regex engine to go back.
From your examples the verse part (e.g. :1) seems not optional. Removing that will match the last bit.
ref_regex = re.compile('''
(?<!\w) # Not preceeded by any words
((?i)q(?:uote)?\s+)? # Match 'q' or 'quote' followed by many spaces
(
(?:(?:[1-3]|I{1,3})\s*)? # Match an arabic or roman number between 1 and 3.
[A-Za-z]+ # Match many alphabetics
)\.? # Followed by an optional dot
(?:
\s*(\d+) # Match the chapter number
(?:
[:.](\d+) # Match the verse number
(?:-(\d+))? # Match the ending verse number
) # <-- no '?' here
)
(?:
\s+
(?:
(?i)(?:from\s+)| # Match the keyword 'from' or 'in'
(?:in\s+)|
(?P<lbrace>\() # or stuff between (...)
)\s*(\w+)
(?(lbrace)\))
)?
''', re.X | re.U)
(If you're going to write a gigantic RegEx like this, please use the /x flag.)
If you really need overlapping matches, you could use a lookahead. A simple example is
>>> rx = re.compile('(.)(?=(.))')
>>> x = rx.finditer("abcdefgh")
>>> [y.groups() for y in x]
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f'), ('f', 'g'), ('g', 'h')]
You may extend this idea to your RegEx.
| Overlapping matches with finditer() in Python | I'm using a regex to match Bible verse references in a text. The current regex is
REF_REGEX = re.compile('''
(?<!\w) # Not preceded by any words
(?P<quote>q(?:uote)?\s+)? # Match optional 'q' or 'quote' followed by many spaces
(?P<book>
(?:(?:[1-3]|I{1,3})\s*)? # Match an optional arabic or roman number between 1 and 3.
[A-Za-z]+ # Match any alphabetics
)\.? # Followed by an optional dot
(?:
\s*(?P<chapter>\d+) # Match the chapter number
(?:
[:\.](?P<startverse>\d+) # Match the starting verse number, preceded by ':' or '.'
(?:-(?P<endverse>\d+))? # Match the optional ending verse number, preceded by '-'
)? # Verse numbers are optional
)
(?:
\s+(?: # Here be spaces
(?:from\s+)|(?:in\s+)|(?P<lbrace>\()) # Match 'from[:space:]', 'in[:space:]' or '('
\s*(?P<version>\w+) # Match a word preceded by optional spaces
(?(lbrace)\)) # Close the '(' if found earlier
)? # The whole 'in|from|()' is optional
''', re.IGNORECASE | re.VERBOSE | re.UNICODE)
This matches the following expressions fine:
"jn 3:16": (None, 'jn', '3', '16', None, None, None),
"matt. 18:21-22": (None, 'matt', '18', '21', '22', None, None),
"q matt. 18:21-22": ('q ', 'matt', '18', '21', '22', None, None),
"QuOTe jn 3:16": ('QuOTe ', 'jn', '3', '16', None, None, None),
"q 1co13:1": ('q ', '1co', '13', '1', None, None, None),
"q 1 co 13:1": ('q ', '1 co', '13', '1', None, None, None),
"quote 1 co 13:1": ('quote ', '1 co', '13', '1', None, None, None),
"quote 1co13:1": ('quote ', '1co', '13', '1', None, None, None),
"jean 3:18 (PDV)": (None, 'jean', '3', '18', None, '(', 'PDV'),
"quote malachie 1.1-2 fRom Colombe": ('quote ', 'malachie', '1', '1', '2', None, 'Colombe'),
"quote malachie 1.1-2 In Colombe": ('quote ', 'malachie', '1', '1', '2', None, 'Colombe'),
"cinq jn 3:16 (test)": (None, 'jn', '3', '16', None, '(', 'test'),
"Q IIKings5.13-58 from wolof": ('Q ', 'IIKings', '5', '13', '58', None, 'wolof'),
"This text is about lv5.4-6 in KJV only": (None, 'lv', '5', '4', '6', None, 'KJV'),
but it fails to parse:
"Found in 2 Cor. 5:18-21 ( Ministers": (None, '2 Cor', '5', '18', '21', None, None),
because it returns (None, 'in', '2', None, None, None, None) instead.
Is there a way to get finditer() to return all matches, even if they overlap, or is there a way to improve my regex so it matches this last bit properly?
Thanks.
| [
"A character consumed is consumed, you should not ask the regex engine to go back. \nFrom your examples the verse part (e.g. :1) seems not optional. Removing that will match the last bit.\nref_regex = re.compile('''\n(?<!\\w) # Not preceeded by any words\n((?i)q(?:uote)?\\s+)? # Match 'q' or 'quote' followed by many spaces\n(\n (?:(?:[1-3]|I{1,3})\\s*)? # Match an arabic or roman number between 1 and 3.\n [A-Za-z]+ # Match many alphabetics\n)\\.? # Followed by an optional dot\n(?:\n \\s*(\\d+) # Match the chapter number\n (?:\n [:.](\\d+) # Match the verse number\n (?:-(\\d+))? # Match the ending verse number\n ) # <-- no '?' here\n)\n(?:\n \\s+\n (?:\n (?i)(?:from\\s+)| # Match the keyword 'from' or 'in'\n (?:in\\s+)|\n (?P<lbrace>\\() # or stuff between (...)\n )\\s*(\\w+)\n (?(lbrace)\\))\n)?\n''', re.X | re.U)\n\n(If you're going to write a gigantic RegEx like this, please use the /x flag.)\n\nIf you really need overlapping matches, you could use a lookahead. A simple example is\n>>> rx = re.compile('(.)(?=(.))')\n>>> x = rx.finditer(\"abcdefgh\")\n>>> [y.groups() for y in x]\n[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f'), ('f', 'g'), ('g', 'h')]\n\nYou may extend this idea to your RegEx.\n"
] | [
4
] | [] | [] | [
"iteration",
"overlapping_matches",
"python",
"regex"
] | stackoverflow_0003027718_iteration_overlapping_matches_python_regex.txt |
Q:
Contrary to Python 3.1 Docs, hash(obj) != id(obj). So which is correct?
The following is from the Python v3.1.2 documentation:
From The Python Language Reference Section 3.3.1 Basic Customization:
object.__hash__(self)
... User-defined classes have __eq__() and __hash__() methods
by default; with them, all objects compare unequal (except
with themselves) and x.__hash__() returns id(x).
From The Glossary:
hashable
... Objects which are instances of user-defined classes are
hashable by default; they all compare unequal, and their hash
value is their id().
This is true up through version 2.6.5:
Python 2.6.5 (r265:79096, Mar 19 2010 21:48:26) ...
...
>>> class C(object): pass
...
>>> c = C()
>>> id(c)
11335856
>>> hash(c)
11335856
But in version 3.1.2:
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) ...
...
>>> class C: pass
...
>>> c = C()
>>> id(c)
11893680
>>> hash(c)
743355
So which is it? Should I report a documentation bug or a program bug?
And if it's a documentation bug, and the default hash() value for a user
class instance is no longer the same as the id() value, then it would be
interesting to know what it is or how it is calculated, and why it was
changed in version 3.
A:
I'm guessing this was a change made in Python 3.x to improve performance. Check out issue 5186, then look a little more closely at your mismatched numbers:
>>> bin(11893680)
'0b101101010111101110110000'
>>> bin(743355)
'0b10110101011110111011'
>>> 11893680 >> 4
743355
It's probably worth reporting as a documentation bug.
| Contrary to Python 3.1 Docs, hash(obj) != id(obj). So which is correct? | The following is from the Python v3.1.2 documentation:
From The Python Language Reference Section 3.3.1 Basic Customization:
object.__hash__(self)
... User-defined classes have __eq__() and __hash__() methods
by default; with them, all objects compare unequal (except
with themselves) and x.__hash__() returns id(x).
From The Glossary:
hashable
... Objects which are instances of user-defined classes are
hashable by default; they all compare unequal, and their hash
value is their id().
This is true up through version 2.6.5:
Python 2.6.5 (r265:79096, Mar 19 2010 21:48:26) ...
...
>>> class C(object): pass
...
>>> c = C()
>>> id(c)
11335856
>>> hash(c)
11335856
But in version 3.1.2:
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) ...
...
>>> class C: pass
...
>>> c = C()
>>> id(c)
11893680
>>> hash(c)
743355
So which is it? Should I report a documentation bug or a program bug?
And if it's a documentation bug, and the default hash() value for a user
class instance is no longer the same as the id() value, then it would be
interesting to know what it is or how it is calculated, and why it was
changed in version 3.
| [
"I'm guessing this was a change made in Python 3.x to improve performance. Check out issue 5186, then look a little more closely at your mismatched numbers:\n>>> bin(11893680)\n'0b101101010111101110110000'\n>>> bin(743355)\n'0b10110101011110111011'\n>>> 11893680 >> 4\n743355\n\nIt's probably worth reporting as a documentation bug.\n"
] | [
10
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0003027838_hash_python.txt |
Q:
Compiling C-dll for Python OR SWIG-module creation, how to continue?
I reference this file "kbdext.c" and its headerfile listed on http://www.docdroppers.org/wiki/index.php?title=Writing_Keyloggers (the listings are at the bottom).
I've been trying to compile this into a dll for use in Python or Visual Basic, but have not succeeded. I'm not familiar with C or GCC to sort out the problems or do the dll compile correctly. (I also get an error about snprintf not being declared when doing a regular compile of all the files).
What are the steps I should do to make all functions available for other languages and external apps?
Or is it perhaps easier to use SWIG and make a python module, instead of compiling a DLL?
A:
I've succeeded in compiling the dll with GCC, and am able to import its functions in C. I have yet to test the import in VB and Python but can't see why it would pose problems.
| Compiling C-dll for Python OR SWIG-module creation, how to continue? | I reference this file "kbdext.c" and its headerfile listed on http://www.docdroppers.org/wiki/index.php?title=Writing_Keyloggers (the listings are at the bottom).
I've been trying to compile this into a dll for use in Python or Visual Basic, but have not succeeded. I'm not familiar with C or GCC to sort out the problems or do the dll compile correctly. (I also get an error about snprintf not being declared when doing a regular compile of all the files).
What are the steps I should do to make all functions available for other languages and external apps?
Or is it perhaps easier to use SWIG and make a python module, instead of compiling a DLL?
| [
"I've succeeded in compiling the dll with GCC, and am able to import its functions in C. I have yet to test the import in VB and Python but can't see why it would pose problems.\n"
] | [
0
] | [] | [] | [
"c",
"dll",
"python",
"swig"
] | stackoverflow_0003018249_c_dll_python_swig.txt |
Q:
Urllib's urlopen breaking on some sites (e.g. StackApps api): returns garbage results
I'm using urllib2's urlopen function to try and get a JSON result from the StackOverflow api.
The code I'm using:
>>> import urllib2
>>> conn = urllib2.urlopen("http://api.stackoverflow.com/0.8/users/")
>>> conn.readline()
The result I'm getting:
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xed\xbd\x07`\x1cI\x96%&/m\xca{\x7fJ\...
I'm fairly new to urllib, but this doesn't seem like the result I should be getting. I've tried it in other places and I get what I expect (the same as visiting the address with a browser gives me: a JSON object).
Using urlopen on other sites (e.g. "http://google.com") works fine, and gives me actual html. I've also tried using urllib and it gives the same result.
I'm pretty stuck, not even knowing where to look to solve this problem. Any ideas?
A:
That almost looks like something you would be feeding to pickle. Maybe something in the User-Agent string or Accepts header that urllib2 is sending is causing StackOverflow to send something other than JSON.
One telltale is to look at conn.headers.headers to see what the Content-Type header says.
And this question, Odd String Format Result from API Call, may have your answer. Basically, you might have to run your result through a gzip decompressor.
Double checking with this code:
>>> req = urllib2.Request("http://api.stackoverflow.com/0.8/users/",
headers={'Accept-Encoding': 'gzip, identity'})
>>> conn = urllib2.urlopen(req)
>>> val = conn.read()
>>> conn.close()
>>> val[0:25]
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xed\xbd\x07`\x1cI\x96%&/m\xca{\x7fJ'
Yes, you are definitely getting gzip encoded data back.
Since you seem to be getting different results on different machines with the same version of Python, and in general it looks like the urllib2 API would require you do something special to request gzip encoded data, my guess is that you have a transparent proxy in there someplace.
I saw a presentation by the EFF at CodeCon in 2009. They were doing end-to-end connectivity testing to discover dirty ISP tricks of various kinds. One of the things they discovered while doing this testing is that a surprising number of consumer level NAT routers add random HTTP headers or do transparent proxying. You might have some piece of equipment on your network that's adding or modifying the Accept-Encoding header in order to make your connection seem faster.
| Urllib's urlopen breaking on some sites (e.g. StackApps api): returns garbage results | I'm using urllib2's urlopen function to try and get a JSON result from the StackOverflow api.
The code I'm using:
>>> import urllib2
>>> conn = urllib2.urlopen("http://api.stackoverflow.com/0.8/users/")
>>> conn.readline()
The result I'm getting:
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xed\xbd\x07`\x1cI\x96%&/m\xca{\x7fJ\...
I'm fairly new to urllib, but this doesn't seem like the result I should be getting. I've tried it in other places and I get what I expect (the same as visiting the address with a browser gives me: a JSON object).
Using urlopen on other sites (e.g. "http://google.com") works fine, and gives me actual html. I've also tried using urllib and it gives the same result.
I'm pretty stuck, not even knowing where to look to solve this problem. Any ideas?
| [
"That almost looks like something you would be feeding to pickle. Maybe something in the User-Agent string or Accepts header that urllib2 is sending is causing StackOverflow to send something other than JSON.\nOne telltale is to look at conn.headers.headers to see what the Content-Type header says.\nAnd this question, Odd String Format Result from API Call, may have your answer. Basically, you might have to run your result through a gzip decompressor.\nDouble checking with this code:\n>>> req = urllib2.Request(\"http://api.stackoverflow.com/0.8/users/\",\n headers={'Accept-Encoding': 'gzip, identity'})\n>>> conn = urllib2.urlopen(req)\n>>> val = conn.read()\n>>> conn.close()\n>>> val[0:25]\n'\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\xed\\xbd\\x07`\\x1cI\\x96%&/m\\xca{\\x7fJ'\n\nYes, you are definitely getting gzip encoded data back.\nSince you seem to be getting different results on different machines with the same version of Python, and in general it looks like the urllib2 API would require you do something special to request gzip encoded data, my guess is that you have a transparent proxy in there someplace.\nI saw a presentation by the EFF at CodeCon in 2009. They were doing end-to-end connectivity testing to discover dirty ISP tricks of various kinds. One of the things they discovered while doing this testing is that a surprising number of consumer level NAT routers add random HTTP headers or do transparent proxying. You might have some piece of equipment on your network that's adding or modifying the Accept-Encoding header in order to make your connection seem faster.\n"
] | [
10
] | [] | [] | [
"python",
"urllib",
"urllib2",
"urlopen"
] | stackoverflow_0003028426_python_urllib_urllib2_urlopen.txt |
Q:
Is it possible to detect an incoming call to a GSM modem (HUAWEI E160) plugged into the USB port?
Ideally I'd like to find a library for Python.
All I need is the caller number, I do not need to answer the call.
A:
i don't know for this specific model, but GSM modem are generally handled as a communication port. they are mapped as a communication port (COMXX under windows, don't know for linux).
the documentation of the modem will give you a set of AT command which will allow you to configure the modem so that it notifies incoming calls to the port. just open the port, send the configuration commands and listen for incoming events. (you should also be able to receive SMS this way).
| Is it possible to detect an incoming call to a GSM modem (HUAWEI E160) plugged into the USB port? | Ideally I'd like to find a library for Python.
All I need is the caller number, I do not need to answer the call.
| [
"i don't know for this specific model, but GSM modem are generally handled as a communication port. they are mapped as a communication port (COMXX under windows, don't know for linux). \nthe documentation of the modem will give you a set of AT command which will allow you to configure the modem so that it notifies incoming calls to the port. just open the port, send the configuration commands and listen for incoming events. (you should also be able to receive SMS this way).\n"
] | [
0
] | [] | [] | [
"call",
"gsm",
"modem",
"python"
] | stackoverflow_0003024344_call_gsm_modem_python.txt |
Q:
Newbie : installing and upgrading python module
I have downloaded and install a python library, via setup.py , python2.5 setup.py install ...
now the version is changed at the source . a newer library is available. originally , i have clone it via mercurial, and install it. right now , i have updated repository.
how do i use the newer version ? overwrite the installation ?
by simply doing setup.py install again ?
A:
Yes, just do setup.py install again.
| Newbie : installing and upgrading python module | I have downloaded and install a python library, via setup.py , python2.5 setup.py install ...
now the version is changed at the source . a newer library is available. originally , i have clone it via mercurial, and install it. right now , i have updated repository.
how do i use the newer version ? overwrite the installation ?
by simply doing setup.py install again ?
| [
"Yes, just do setup.py install again.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003028561_python.txt |
Q:
Comments in XML at beginning of document
my PYTHON xml parser fails if there´s a comment at the beginnging of an xml file like::
<?xml version="1.0" encoding="utf-8"?>
<!-- Script version: "1"-->
<!-- Date: "07052010"-->
<component name="abc">
<pp>
....
</pp>
</component>
is it illegal to place a comment like this?
EDIT:
well it´s not throwing an error but the DOM module will fail and not recognize the child nodes:
import xml.dom.minidom as dom
sub_tree = dom.parse('xyz.xml')
for component in sub_tree.firstChild.childNodes:
print(component)
I cannot acces the child nodes; sub_tree.firstChild.childNodes returns an empty list,but if I remove those 2 comments I can loop through the list and read the childnodes as usual!
EDIT:
Guys, this simple example is working and enough to figure it out. start your python shell and execute this small code above. Once it will output nothing and after deleting the comments it will show up the node!
A:
It is legal; from XML 1.0 Reference:
2.5 Comments
[Definition: Comments may appear
anywhere in a document outside other
markup; in addition, they may appear
within the document type declaration
at places allowed by the grammar. They
are not part of the document's
character data; an XML processor MAY,
but need not, make it possible for an
application to retrieve the text of
comments. For compatibility, the
string " -- " (double-hyphen) MUST NOT
occur within comments.] Parameter
entity references MUST NOT be
recognized within comments.
A:
To get better answers, show us (a) a small complete Python script and (b) a small complete XML document that together demonstrate the unexpected behaviour.
Have you considered using ElementTree?
A:
If you do this:
import xml.dom.minidom as dom
sub_tree = dom.parse('xyz.xml')
print sub_tree.children
You will see what is your problem:
>>> print sub_tree.childNodes
[<DOM Comment node " Script ve...">, <DOM Comment node " Date: "07...">, <DOM Element: component at 0x7fecf88c>]
firstChild will obviously pick up the first child, which is a comment and doesn't have any children of its own.
You could iterate over the children and skip all comment nodes.
Or you could ditch the DOM model and use ElementTree, which is so much nicer to work with. :)
A:
That should be legal as long as the XML declaration is on the first line.
| Comments in XML at beginning of document | my PYTHON xml parser fails if there´s a comment at the beginnging of an xml file like::
<?xml version="1.0" encoding="utf-8"?>
<!-- Script version: "1"-->
<!-- Date: "07052010"-->
<component name="abc">
<pp>
....
</pp>
</component>
is it illegal to place a comment like this?
EDIT:
well it´s not throwing an error but the DOM module will fail and not recognize the child nodes:
import xml.dom.minidom as dom
sub_tree = dom.parse('xyz.xml')
for component in sub_tree.firstChild.childNodes:
print(component)
I cannot acces the child nodes; sub_tree.firstChild.childNodes returns an empty list,but if I remove those 2 comments I can loop through the list and read the childnodes as usual!
EDIT:
Guys, this simple example is working and enough to figure it out. start your python shell and execute this small code above. Once it will output nothing and after deleting the comments it will show up the node!
| [
"It is legal; from XML 1.0 Reference:\n\n2.5 Comments\n[Definition: Comments may appear\n anywhere in a document outside other\n markup; in addition, they may appear\n within the document type declaration\n at places allowed by the grammar. They\n are not part of the document's\n character data; an XML processor MAY,\n but need not, make it possible for an\n application to retrieve the text of\n comments. For compatibility, the\n string \" -- \" (double-hyphen) MUST NOT\n occur within comments.] Parameter\n entity references MUST NOT be\n recognized within comments.\n\n",
"To get better answers, show us (a) a small complete Python script and (b) a small complete XML document that together demonstrate the unexpected behaviour.\nHave you considered using ElementTree?\n",
"If you do this:\nimport xml.dom.minidom as dom\nsub_tree = dom.parse('xyz.xml')\nprint sub_tree.children\n\nYou will see what is your problem:\n>>> print sub_tree.childNodes\n[<DOM Comment node \" Script ve...\">, <DOM Comment node \" Date: \"07...\">, <DOM Element: component at 0x7fecf88c>]\n\nfirstChild will obviously pick up the first child, which is a comment and doesn't have any children of its own.\nYou could iterate over the children and skip all comment nodes.\nOr you could ditch the DOM model and use ElementTree, which is so much nicer to work with. :)\n",
"That should be legal as long as the XML declaration is on the first line.\n"
] | [
1,
1,
1,
0
] | [] | [] | [
"parsing",
"python",
"xml"
] | stackoverflow_0003021884_parsing_python_xml.txt |
Q:
ruby or python more suitable for scripting in all OSes?
if i want to script a mini-application (in the Terminal) in mac and windows, which one is preferred: ruby or python?
or is there no major difference just a matter of taste?
cause i know python definetely is a good scripting language.
thanks
A:
Matter of taste, really. They each have a pretty good set of libraries and are cross-platform, so it'll be a matter of which one you prefer to code in.
A:
Personally, I find the documentation for Python is much better than that for Ruby. The Docs for Ruby are full of cryptic examples that are terse, short, and just not very helpful.
On the other hand, docs for Python exist everywhere, but more importantly, in a useful, helpful form.
A:
I believe python and ruby (since at least OS X 10.4) came pre-installed on Mac, that is a convenience.
There are easy installers for Windows. On Linux of course your mileage may vary.
As much as i like python myself, don't think one is better than the other for your purpose.
A:
Python is perhaps a little more common, and arguably more mature, so on that basis alone, it may be worth choosing Python.
That said, both are available by default on Mac OS X, and neither are available on Windows by default, so in this case it really does not matter.
A:
I would suggest to go for Python over Ruby on Windows unless you are willing to port some gems as a few (no I cannot say what percentage) of the gems use unix/mac specific stuff (example from ENV[OSTYPE] to wget to unix processes) that I have seen break on windows.
A:
Both are excelent options, you won't go wrong no matter which one you chose. You should check out the availability of libraries for the task at hand and also how helpful the community is. The Python community is humongous and seems friendlier to me. Rubists seem to have some anger management issues.
| ruby or python more suitable for scripting in all OSes? | if i want to script a mini-application (in the Terminal) in mac and windows, which one is preferred: ruby or python?
or is there no major difference just a matter of taste?
cause i know python definetely is a good scripting language.
thanks
| [
"Matter of taste, really. They each have a pretty good set of libraries and are cross-platform, so it'll be a matter of which one you prefer to code in.\n",
"Personally, I find the documentation for Python is much better than that for Ruby. The Docs for Ruby are full of cryptic examples that are terse, short, and just not very helpful.\nOn the other hand, docs for Python exist everywhere, but more importantly, in a useful, helpful form.\n",
"I believe python and ruby (since at least OS X 10.4) came pre-installed on Mac, that is a convenience. \nThere are easy installers for Windows. On Linux of course your mileage may vary.\nAs much as i like python myself, don't think one is better than the other for your purpose. \n",
"Python is perhaps a little more common, and arguably more mature, so on that basis alone, it may be worth choosing Python.\nThat said, both are available by default on Mac OS X, and neither are available on Windows by default, so in this case it really does not matter.\n",
"I would suggest to go for Python over Ruby on Windows unless you are willing to port some gems as a few (no I cannot say what percentage) of the gems use unix/mac specific stuff (example from ENV[OSTYPE] to wget to unix processes) that I have seen break on windows. \n",
"Both are excelent options, you won't go wrong no matter which one you chose. You should check out the availability of libraries for the task at hand and also how helpful the community is. The Python community is humongous and seems friendlier to me. Rubists seem to have some anger management issues.\n"
] | [
5,
5,
2,
2,
2,
0
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0002978801_python_ruby.txt |
Q:
pyODBC and Unicode
I'm working with pyODBC communicate with a MS SQL 2005 Express server.
The table to which i'm trying to save the data consists of nvarchar columns.
query = u"INSERT INTO tblPersons (name, birthday, gender) VALUES('"
query = query + name + u"', '"
query = query + birthday + u"', '"
query = query + gender + u"')"
cur.execute(query)
The variables name, birthrday and gende are read from an Excel file and they are Unicode strings.
When I execute the query and either look at the table with SQL Server Management Studio or execute a query that fetches the data that was just inserted, all the data that was written in a non-English languages turn into question marks. The data that was written in English is preserved and appears in the table in the correct way.
I tried adding CHARSET=UTF16 to my connection string, but had no luck with that.
I can use UTF-8 which works fine but as a working convention, I need all the data saved in my DB to be UTF16.
Thanks!
A:
It could be something related to the odbc driver that pyodbc is using. If that doesn't support unicode, you will probably have to encode the params yourself, like name.encode('utf-16')
Also, you should really, really use query parameters, instead of concatenating the sql string yourself, for example:
query = "INSERT INTO tblPersons (name, birthday, gender) VALUES (?, ?, ?)"
cur.execute(query, [name, birthday, gender])
I doubt that this will help with your unicode trouble, but it is a lot safer, and easier.
(and another unrelated tip: using pyodbc via sqlalchemy is a lot nicer, even if you use it just for simple queries and do not use the object-relational mapping stuff)
A:
I'm so stupid.. The problem was with the server (had to change my collation to the language I needed)
Thanks!
| pyODBC and Unicode | I'm working with pyODBC communicate with a MS SQL 2005 Express server.
The table to which i'm trying to save the data consists of nvarchar columns.
query = u"INSERT INTO tblPersons (name, birthday, gender) VALUES('"
query = query + name + u"', '"
query = query + birthday + u"', '"
query = query + gender + u"')"
cur.execute(query)
The variables name, birthrday and gende are read from an Excel file and they are Unicode strings.
When I execute the query and either look at the table with SQL Server Management Studio or execute a query that fetches the data that was just inserted, all the data that was written in a non-English languages turn into question marks. The data that was written in English is preserved and appears in the table in the correct way.
I tried adding CHARSET=UTF16 to my connection string, but had no luck with that.
I can use UTF-8 which works fine but as a working convention, I need all the data saved in my DB to be UTF16.
Thanks!
| [
"It could be something related to the odbc driver that pyodbc is using. If that doesn't support unicode, you will probably have to encode the params yourself, like name.encode('utf-16')\nAlso, you should really, really use query parameters, instead of concatenating the sql string yourself, for example:\nquery = \"INSERT INTO tblPersons (name, birthday, gender) VALUES (?, ?, ?)\"\ncur.execute(query, [name, birthday, gender])\n\nI doubt that this will help with your unicode trouble, but it is a lot safer, and easier.\n(and another unrelated tip: using pyodbc via sqlalchemy is a lot nicer, even if you use it just for simple queries and do not use the object-relational mapping stuff)\n",
"I'm so stupid.. The problem was with the server (had to change my collation to the language I needed)\nThanks!\n"
] | [
2,
0
] | [] | [] | [
"pyodbc",
"python",
"unicode",
"utf_16"
] | stackoverflow_0003015967_pyodbc_python_unicode_utf_16.txt |
Q:
help('modules') crashing? Not sure how to fix
I was trying to install a module for opencv and added an opencv.pth file to the folder beyond my sites.py file. I have since deleted it and no change.
When I try to run help('modules'), I get the following error:
Please wait a moment while I gather a
list of all available modules...
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/twisted/words/im/init.py:8:
UserWarning: twisted.im will be
undergoing a rewrite at some point in
the future.
warnings.warn("twisted.im will be
undergoing a rewrite at some point in
the future.")
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pkgutil.py:110:
DeprecationWarning: The wxPython
compatibility package is no longer
automatically generated or actively
maintained. Please switch to the wx
package as soon as possible.
import(name) Traceback (most recent call last): File "",
line 1, in File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.py",
line 348, in call
return pydoc.help(*args, **kwds) File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pydoc.py",
line 1644, in call
self.help(request) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pydoc.py",
line 1681, in help
elif request == 'modules': self.listmodules() File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pydoc.py",
line 1802, in listmodules
ModuleScanner().run(callback) File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pydoc.py",
line 1853, in run
for importer, modname, ispkg in pkgutil.walk_packages(): File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pkgutil.py",
line 110, in walk_packages
import(name) File "/BinaryCache/wxWidgets/wxWidgets-11~262/Root/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/wxaddons/init.py",
line 180, in import_hook File
"/Library/Python/2.5/site-packages/ctypes_opencv/init.py",
line 19, in
from ctypes_opencv.cv import * File
"/BinaryCache/wxWidgets/wxWidgets-11~262/Root/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/wxaddons/init.py",
line 180, in import_hook File
"/Library/Python/2.5/site-packages/ctypes_opencv/cv.py",
line 2567, in ('desc', CvMat_r, 1), # CvMat* desc File
"/Library/Python/2.5/site-packages/ctypes_opencv/cxcore.py",
line 114, in cfunc
return CFUNCTYPE(result, *atypes)((name, dll), tuple(aflags)) AttributeError: dlsym(0x2674d10, cvCreateFeatureTree): symbol not found
What gives?!
A:
This happens because help('modules') imports all modules, which can result in a lot of unsentineled code being executed. There's nothing you can do short of reporting bugs in every single package that causes this (opencv in this case) and wait for them to fix it.
| help('modules') crashing? Not sure how to fix | I was trying to install a module for opencv and added an opencv.pth file to the folder beyond my sites.py file. I have since deleted it and no change.
When I try to run help('modules'), I get the following error:
Please wait a moment while I gather a
list of all available modules...
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/twisted/words/im/init.py:8:
UserWarning: twisted.im will be
undergoing a rewrite at some point in
the future.
warnings.warn("twisted.im will be
undergoing a rewrite at some point in
the future.")
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pkgutil.py:110:
DeprecationWarning: The wxPython
compatibility package is no longer
automatically generated or actively
maintained. Please switch to the wx
package as soon as possible.
import(name) Traceback (most recent call last): File "",
line 1, in File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site.py",
line 348, in call
return pydoc.help(*args, **kwds) File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pydoc.py",
line 1644, in call
self.help(request) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pydoc.py",
line 1681, in help
elif request == 'modules': self.listmodules() File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pydoc.py",
line 1802, in listmodules
ModuleScanner().run(callback) File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pydoc.py",
line 1853, in run
for importer, modname, ispkg in pkgutil.walk_packages(): File
"/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pkgutil.py",
line 110, in walk_packages
import(name) File "/BinaryCache/wxWidgets/wxWidgets-11~262/Root/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/wxaddons/init.py",
line 180, in import_hook File
"/Library/Python/2.5/site-packages/ctypes_opencv/init.py",
line 19, in
from ctypes_opencv.cv import * File
"/BinaryCache/wxWidgets/wxWidgets-11~262/Root/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/wxaddons/init.py",
line 180, in import_hook File
"/Library/Python/2.5/site-packages/ctypes_opencv/cv.py",
line 2567, in ('desc', CvMat_r, 1), # CvMat* desc File
"/Library/Python/2.5/site-packages/ctypes_opencv/cxcore.py",
line 114, in cfunc
return CFUNCTYPE(result, *atypes)((name, dll), tuple(aflags)) AttributeError: dlsym(0x2674d10, cvCreateFeatureTree): symbol not found
What gives?!
| [
"This happens because help('modules') imports all modules, which can result in a lot of unsentineled code being executed. There's nothing you can do short of reporting bugs in every single package that causes this (opencv in this case) and wait for them to fix it.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003029053_python.txt |
Q:
Too many values problem
i was trying to make a full lot of ips for testing using this code :
ip_is = [i for i in range(256)]
ports = [i for i in range(1024,49152)]
return [str(i1)+"."+str(i2)+"."+str(i3)+"."+str(i4)+":"+str(p) for i1,i2,i3,i4,port in ip_is,ip_is,ip_is,ip_is,ports]
The problem is the 3rd line in which is made the ip list. If there is a way to make it all at once or how can make one at time in a lazy way ?
I'm pretty noob at python :P.
Thanks for the Help :)
A:
You're trying (quite apart from the syntax issues) to make a list of
256 * 256 * 256 * 256 * (49152 - 1024)
strings -- i.e., 206708186021888 strings... about two hundred thousand billions of strings.
If you made one per microsecond, that would take you 6.5 years (even quite apart from the problem of finding the petabytes of RAM to hold them).
I know you want to "make a full lot of ips for testing", but that's way too full a lot.
Why not take a random sample from this huge set, instead? E.g.:
import random
def random_address():
ip = tuple(random.randrange(256) for i in range(4))
port = random.randrange(1024, 49152)
format = '.'.join(['%s'] * 4) + ':%s'
return format % (ip + (port,))
now, if you want (e.g.) a million such strings for your testing, just do:
millionstrings = [random_address() for i in xrange(1000*1000)]
A:
You should use a generator instead of creating the full list:
def all_addresses():
ip_is = [i for i in range(256)]
ports = [i for i in range(1024,49152)]
# note (...) instead of [...] to create a generator instead of a list;
# separate |for|s to iterate over the lists individually
return (str(i1)+"."+str(i2)+"."+str(i3)+"."+str(i4)+":"+str(p)
for i1 in ip_is
for i2 in ip_is
for i3 in ip_is
for i4 in ip_is
for p in ports)
for addr in all_addresses():
print addr
This way you will not run out of memory, but it will still take a very, very long time to iterate through all these addresses.
A:
return ('%d.%d.%d.%d:%d' % (i1, i2, i3, i4, port) for i1, i2, i3, i4, port in itertools.product(ip_is, ip_is, ip_is, ip_is, ports))
| Too many values problem | i was trying to make a full lot of ips for testing using this code :
ip_is = [i for i in range(256)]
ports = [i for i in range(1024,49152)]
return [str(i1)+"."+str(i2)+"."+str(i3)+"."+str(i4)+":"+str(p) for i1,i2,i3,i4,port in ip_is,ip_is,ip_is,ip_is,ports]
The problem is the 3rd line in which is made the ip list. If there is a way to make it all at once or how can make one at time in a lazy way ?
I'm pretty noob at python :P.
Thanks for the Help :)
| [
"You're trying (quite apart from the syntax issues) to make a list of\n256 * 256 * 256 * 256 * (49152 - 1024)\n\nstrings -- i.e., 206708186021888 strings... about two hundred thousand billions of strings.\nIf you made one per microsecond, that would take you 6.5 years (even quite apart from the problem of finding the petabytes of RAM to hold them).\nI know you want to \"make a full lot of ips for testing\", but that's way too full a lot.\nWhy not take a random sample from this huge set, instead? E.g.:\nimport random\n\ndef random_address():\n ip = tuple(random.randrange(256) for i in range(4))\n port = random.randrange(1024, 49152)\n format = '.'.join(['%s'] * 4) + ':%s'\n return format % (ip + (port,))\n\nnow, if you want (e.g.) a million such strings for your testing, just do:\nmillionstrings = [random_address() for i in xrange(1000*1000)]\n\n",
"You should use a generator instead of creating the full list:\ndef all_addresses():\n ip_is = [i for i in range(256)]\n ports = [i for i in range(1024,49152)]\n # note (...) instead of [...] to create a generator instead of a list;\n # separate |for|s to iterate over the lists individually\n return (str(i1)+\".\"+str(i2)+\".\"+str(i3)+\".\"+str(i4)+\":\"+str(p)\n for i1 in ip_is\n for i2 in ip_is\n for i3 in ip_is\n for i4 in ip_is\n for p in ports)\n\nfor addr in all_addresses():\n print addr\n\nThis way you will not run out of memory, but it will still take a very, very long time to iterate through all these addresses.\n",
"return ('%d.%d.%d.%d:%d' % (i1, i2, i3, i4, port) for i1, i2, i3, i4, port in itertools.product(ip_is, ip_is, ip_is, ip_is, ports))\n\n"
] | [
6,
5,
5
] | [] | [] | [
"python"
] | stackoverflow_0003029132_python.txt |
Q:
How to draw the "trail" in a maze solving application
Hello i have designed a maze and i want to draw a path between the cells as the 'person' moves from one cell to the next.
So each time i move the cell a line is drawn
Also i am using the graphics module
The graphics module is an object oriented library
Im importing
from graphics import*
from maze import*
my circle which is my cell
center = Point(15, 15)
c = Circle(center, 12)
c.setFill('blue')
c.setOutline('yellow')
c.draw(win)
p1 = Point(c.getCenter().getX(), c.getCenter().getY())
this is my loop
if mazez.blockedCount(cloc)> 2:
mazez.addDecoration(cloc, "grey")
mazez[cloc].deadend = True
c.move(-25, 0)
p2 = Point(p1.getX(), p1.getY())
line = graphics.Line(p1, p2)
cloc.col = cloc.col - 1
Now it says getX not defined every time i press a key is this because of p2???
This is the most important bits in the module for this part
def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=True):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master, width=width, height=height)
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>", self._onClick)
self.height = height
self.width = width
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
master.lift()
if autoflush: _root.update()
def __checkOpen(self):
if self.closed:
raise GraphicsError("window is closed")
def setCoords(self, x1, y1, x2, y2):
"""Set coordinates of window to run from (x1,y1) in the
lower-left corner to (x2,y2) in the upper-right corner."""
self.trans = Transform(self.width, self.height, x1, y1, x2, y2)
def plot(self, x, y, color="black"):
"""Set pixel (x,y) to the given color"""
self.__checkOpen()
xs,ys = self.toScreen(x,y)
self.create_line(xs,ys,xs+1,ys, fill=color)
self.__autoflush()
def plotPixel(self, x, y, color="black"):
"""Set pixel raw (independent of window coordinates) pixel
(x,y) to color"""
self.__checkOpen()
self.create_line(x,y,x+1,y, fill=color)
self.__autoflush()
def draw(self, graphwin):
if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)
if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window")
self.canvas = graphwin
self.id = self._draw(graphwin, self.config)
if graphwin.autoflush:
_root.update()
def move(self, dx, dy):
"""move object dx units in x direction and dy units in y
direction"""
self._move(dx,dy)
canvas = self.canvas
if canvas and not canvas.isClosed():
trans = canvas.trans
if trans:
x = dx/ trans.xscale
y = -dy / trans.yscale
else:
x = dx
y = dy
self.canvas.move(self.id, x, y)
if canvas.autoflush:
_root.update()
class Point(GraphicsObject):
def __init__(self, x, y):
GraphicsObject.__init__(self, ["outline", "fill"])
self.setFill = self.setOutline
self.x = x
self.y = y
def _draw(self, canvas, options):
x,y = canvas.toScreen(self.x,self.y)
return canvas.create_rectangle(x,y,x+1,y+1,options)
def _move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy
def clone(self):
other = Point(self.x,self.y)
other.config = self.config.copy()
return other
def getX(self): return self.x
def getY(self): return self.y
def __init__(self, p1, p2, options=["outline","width","fill"]):
GraphicsObject.__init__(self, options)
self.p1 = p1.clone()
self.p2 = p2.clone()
def _move(self, dx, dy):
self.p1.x = self.p1.x + dx
self.p1.y = self.p1.y + dy
self.p2.x = self.p2.x + dx
self.p2.y = self.p2.y + dy
def getP1(self): return self.p1.clone()
def getP2(self): return self.p2.clone()
def getCenter(self):
p1 = self.p1
p2 = self.p2
return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)
A:
You might try this from an interactive Python shell:
>>> import graphics
>>> help(graphics.Circle)
That should tell you what attributes Circle does have.
A:
You're trying to use getX() and getY() as free-standing FUNCTIONS:
p2 = Point(getX(), getY())
Note that you're calling them as bare names, not qualified names -- therefore, as functions, not as methods.
And yet the docs you quote say they're methods -- therefore, they must be called as part of qualified names ("after a dot"...!-) and before the dot must be an instance of Point.
Presumably, therefore, you need p1.getX() and p1.getY() instead of the bare names you're using. p1.getX is a qualified name (i.e., one with a dot) and it means "method or attribute getX of object p1.
This is really super-elementary Python, and I recommend you first study the official Python tutorial or other even simpler introductory documents before you try making or modifying applications in Python.
A:
I don't know how maze solves the puzzle, so I am going to assume it works like a generator, yielding the next move for the circle to make. Something to this effect:
while not this_maze.solved():
next_position = this_maze.next()
my_circle.move(next_position)
Then all you need to do is keep track of the current circle position and the previous circle position.
prev_position = this_maze.starting_point
while not this_maze.solved():
next_position = this_maze.next()
my_circle.clear()
draw_trail(prev_position, next_position)
my_circle.draw_at(next_position)
prev_position = next_position
Obviously, changing this in something compatible with your framework is left up to you. dir(), help() and reading the libraries' source will all help you.
| How to draw the "trail" in a maze solving application | Hello i have designed a maze and i want to draw a path between the cells as the 'person' moves from one cell to the next.
So each time i move the cell a line is drawn
Also i am using the graphics module
The graphics module is an object oriented library
Im importing
from graphics import*
from maze import*
my circle which is my cell
center = Point(15, 15)
c = Circle(center, 12)
c.setFill('blue')
c.setOutline('yellow')
c.draw(win)
p1 = Point(c.getCenter().getX(), c.getCenter().getY())
this is my loop
if mazez.blockedCount(cloc)> 2:
mazez.addDecoration(cloc, "grey")
mazez[cloc].deadend = True
c.move(-25, 0)
p2 = Point(p1.getX(), p1.getY())
line = graphics.Line(p1, p2)
cloc.col = cloc.col - 1
Now it says getX not defined every time i press a key is this because of p2???
This is the most important bits in the module for this part
def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=True):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master, width=width, height=height)
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>", self._onClick)
self.height = height
self.width = width
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
master.lift()
if autoflush: _root.update()
def __checkOpen(self):
if self.closed:
raise GraphicsError("window is closed")
def setCoords(self, x1, y1, x2, y2):
"""Set coordinates of window to run from (x1,y1) in the
lower-left corner to (x2,y2) in the upper-right corner."""
self.trans = Transform(self.width, self.height, x1, y1, x2, y2)
def plot(self, x, y, color="black"):
"""Set pixel (x,y) to the given color"""
self.__checkOpen()
xs,ys = self.toScreen(x,y)
self.create_line(xs,ys,xs+1,ys, fill=color)
self.__autoflush()
def plotPixel(self, x, y, color="black"):
"""Set pixel raw (independent of window coordinates) pixel
(x,y) to color"""
self.__checkOpen()
self.create_line(x,y,x+1,y, fill=color)
self.__autoflush()
def draw(self, graphwin):
if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)
if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window")
self.canvas = graphwin
self.id = self._draw(graphwin, self.config)
if graphwin.autoflush:
_root.update()
def move(self, dx, dy):
"""move object dx units in x direction and dy units in y
direction"""
self._move(dx,dy)
canvas = self.canvas
if canvas and not canvas.isClosed():
trans = canvas.trans
if trans:
x = dx/ trans.xscale
y = -dy / trans.yscale
else:
x = dx
y = dy
self.canvas.move(self.id, x, y)
if canvas.autoflush:
_root.update()
class Point(GraphicsObject):
def __init__(self, x, y):
GraphicsObject.__init__(self, ["outline", "fill"])
self.setFill = self.setOutline
self.x = x
self.y = y
def _draw(self, canvas, options):
x,y = canvas.toScreen(self.x,self.y)
return canvas.create_rectangle(x,y,x+1,y+1,options)
def _move(self, dx, dy):
self.x = self.x + dx
self.y = self.y + dy
def clone(self):
other = Point(self.x,self.y)
other.config = self.config.copy()
return other
def getX(self): return self.x
def getY(self): return self.y
def __init__(self, p1, p2, options=["outline","width","fill"]):
GraphicsObject.__init__(self, options)
self.p1 = p1.clone()
self.p2 = p2.clone()
def _move(self, dx, dy):
self.p1.x = self.p1.x + dx
self.p1.y = self.p1.y + dy
self.p2.x = self.p2.x + dx
self.p2.y = self.p2.y + dy
def getP1(self): return self.p1.clone()
def getP2(self): return self.p2.clone()
def getCenter(self):
p1 = self.p1
p2 = self.p2
return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)
| [
"You might try this from an interactive Python shell:\n>>> import graphics\n>>> help(graphics.Circle)\n\nThat should tell you what attributes Circle does have.\n",
"You're trying to use getX() and getY() as free-standing FUNCTIONS:\np2 = Point(getX(), getY())\n\nNote that you're calling them as bare names, not qualified names -- therefore, as functions, not as methods.\nAnd yet the docs you quote say they're methods -- therefore, they must be called as part of qualified names (\"after a dot\"...!-) and before the dot must be an instance of Point.\nPresumably, therefore, you need p1.getX() and p1.getY() instead of the bare names you're using. p1.getX is a qualified name (i.e., one with a dot) and it means \"method or attribute getX of object p1.\nThis is really super-elementary Python, and I recommend you first study the official Python tutorial or other even simpler introductory documents before you try making or modifying applications in Python.\n",
"I don't know how maze solves the puzzle, so I am going to assume it works like a generator, yielding the next move for the circle to make. Something to this effect:\nwhile not this_maze.solved():\n next_position = this_maze.next()\n my_circle.move(next_position)\n\nThen all you need to do is keep track of the current circle position and the previous circle position.\nprev_position = this_maze.starting_point\nwhile not this_maze.solved():\n next_position = this_maze.next()\n my_circle.clear()\n draw_trail(prev_position, next_position)\n my_circle.draw_at(next_position)\n prev_position = next_position\n\nObviously, changing this in something compatible with your framework is left up to you. dir(), help() and reading the libraries' source will all help you.\n"
] | [
1,
1,
0
] | [] | [] | [
"graphics",
"python"
] | stackoverflow_0003027571_graphics_python.txt |
Q:
Programmatically determining the status of a file download
Is there a way I can programmatically determine the status of a download in Chrome or Mozilla Firefox? I would like to know if the download was aborted or completed successfully.
For writing the code I'd be using either Perl, PHP or Python.
Please help.
Thank You.
A:
I don't know about Chrome, but recent versions of Firefox keep the download records in a SQLite database (downloads.sqlite in your profile directory). I'm not sure if that gets updated while the download is in progress, but it should tell you the status once the download is complete/aborted.
| Programmatically determining the status of a file download | Is there a way I can programmatically determine the status of a download in Chrome or Mozilla Firefox? I would like to know if the download was aborted or completed successfully.
For writing the code I'd be using either Perl, PHP or Python.
Please help.
Thank You.
| [
"I don't know about Chrome, but recent versions of Firefox keep the download records in a SQLite database (downloads.sqlite in your profile directory). I'm not sure if that gets updated while the download is in progress, but it should tell you the status once the download is complete/aborted.\n"
] | [
1
] | [
"There are scripts out there that output the file in chunks, recording how many bytes they've echoed out, but those are completely unreliable and you can't accurately ascertain whether or not the user successfully received the complete file.\nThe short answer is no, really, unless you write your own download manager (in Java) that runs a callback to your server when the download completes.\n"
] | [
-2
] | [
"download",
"perl",
"php",
"python"
] | stackoverflow_0003029824_download_perl_php_python.txt |
Q:
what does the '~' mean in python?
what does the '~' mean in python?
i found this BF interpreter in python a while ago.
import sys
#c,i,r,p=0,0,[0]*255,raw_input()
c=0
i=0
p=raw_input()
r=[0]*255
while c<len(p):
m,n,u=p[c],0,r[i]
if m==">":i+=1
if m=="<":i-=1
if m=="+":r[i]+=1
if m=="-":r[i]-=1
if m==".":sys.stdout.write(chr(u))
if m=="[":
if ~u:
while 1:
m=p[c]
if m=="]":n-=1
if m=="[":n+=1
if ~n:break
c+=1
if m=="]":
if u:
while 1:
m=p[c]
if m=="]":n-=1
if m=="[":n+=1
if ~n:break
c-=1
c+=1
and i want to know what it does because i want to make one on my ti 84 (and a PF one)
BF is http://en.wikipedia.org/wiki/Brainfuck
and PF is something similar
A:
Bitwise NOT, just like in C.
In two's complement representation, ~n is equivalent to -n - 1.
A:
In this particular context, just replace '~' with 'not'.
PS. ok i guess i will have to explain - started getting slapped with -1's, probably on the premise i don't know the difference between logical and bitwise negation.
The thing is, the code in the question is broken. There is a bug in it. If you check how Brainfuck should work, it loops within [ ] braces while the current memory cell is !=0 (this is checked as pre-condition when entering [ and as optimization before returning from ]).
But instead of arguing, perhaps is easier to show with examples of the code not working. Let's take the simple program '[+]'. Trying to tun this should just exit (because current cell is 0, it won even enter the loop). Instead if you run it in this interpreter, it goes into infinite loop.
So i'll kindly ask you to revert your -1 votes if my clarification makes sense now ;-)
Here is the interpreter slightly beautified, with fixed ~ bug and i also added the missing , input:
from sys import stdin, stdout
bfHelloWorld = '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.'
# http://esoteric.sange.fi/brainfuck/bf-source/prog/yapi.b
bfPiDigits = '''> +++++ (5 digits)
[<+>>>>>>>>++++++++++<<<<<<<-]>+++++[<+++++++++>-]+>>>>>>+[<<+++[>>[-<]<[>]<-]>>
[>+>]<[<]>]>[[->>>>+<<<<]>>>+++>-]<[<<<<]<<<<<<<<+[->>>>>>>>>>>>[<+[->>>>+<<<<]>
>>>>]<<<<[>>>>>[<<<<+>>>>-]<<<<<-[<<++++++++++>>-]>>>[<<[<+<<+>>>-]<[>+<-]<++<<+
>>>>>>-]<<[-]<<-<[->>+<-[>>>]>[[<+>-]>+>>]<<<<<]>[-]>+<<<-[>>+<<-]<]<<<<+>>>>>>>
>[-]>[<<<+>>>-]<<++++++++++<[->>+<-[>>>]>[[<+>-]>+>>]<<<<<]>[-]>+>[<<+<+>>>-]<<<
<+<+>>[-[-[-[-[-[-[-[-[-<->[-<+<->>]]]]]]]]]]<[+++++[<<<++++++++<++++++++>>>>-]<
<<<+<->>>>[>+<<<+++++++++<->>>-]<<<<<[>>+<<-]+<[->-<]>[>>.<<<<[+.[-]]>>-]>[>>.<<
-]>[-]>[-]>>>[>>[<<<<<<<<+>>>>>>>>-]<<-]]>>[-]<<<[-]<<<<<<<<]++++++++++.
'''
code = bfPiDigits # the code
data = [0] * 255 # data memory
cp = 0 # code pointer
dp = 0 # data pointer
while cp < len(code):
cmd = code[cp]
if cmd == '>': dp += 1
elif cmd == '<': dp -= 1
elif cmd == '+': data[dp] += 1
elif cmd == '-': data[dp] -= 1
elif cmd == '.': stdout.write(chr(data[dp]))
elif cmd == ',': data[dp] = ord(stdin.read(1))
elif cmd == '[' and not data[dp]: # skip loop if ==0
n = 0
while True:
cmd = code[cp]
if cmd == '[': n += 1
elif cmd == ']': n -= 1
if not n: break
cp += 1
elif cmd == ']' and data[dp]: # loop back if !=0
n = 0
while True:
cmd = code[cp]
if cmd == '[': n+=1
elif cmd == ']': n-=1
if not n: break
cp -= 1
cp += 1
A:
And to bring up one thing none of the other answers mentioned: the behavior of ~ for user-defined classes can be changed by overriding the __invert__ method (or the nb_invert slot if you're using the Python/C API).
A:
~ is bitwise-not.
I can't really think of a good way to illustrate it (unless you know that -1 is the bitwise negation of 0), but the wikipedia entry is pretty good.
| what does the '~' mean in python? | what does the '~' mean in python?
i found this BF interpreter in python a while ago.
import sys
#c,i,r,p=0,0,[0]*255,raw_input()
c=0
i=0
p=raw_input()
r=[0]*255
while c<len(p):
m,n,u=p[c],0,r[i]
if m==">":i+=1
if m=="<":i-=1
if m=="+":r[i]+=1
if m=="-":r[i]-=1
if m==".":sys.stdout.write(chr(u))
if m=="[":
if ~u:
while 1:
m=p[c]
if m=="]":n-=1
if m=="[":n+=1
if ~n:break
c+=1
if m=="]":
if u:
while 1:
m=p[c]
if m=="]":n-=1
if m=="[":n+=1
if ~n:break
c-=1
c+=1
and i want to know what it does because i want to make one on my ti 84 (and a PF one)
BF is http://en.wikipedia.org/wiki/Brainfuck
and PF is something similar
| [
"Bitwise NOT, just like in C.\nIn two's complement representation, ~n is equivalent to -n - 1.\n",
"In this particular context, just replace '~' with 'not'. \nPS. ok i guess i will have to explain - started getting slapped with -1's, probably on the premise i don't know the difference between logical and bitwise negation. \nThe thing is, the code in the question is broken. There is a bug in it. If you check how Brainfuck should work, it loops within [ ] braces while the current memory cell is !=0 (this is checked as pre-condition when entering [ and as optimization before returning from ]).\nBut instead of arguing, perhaps is easier to show with examples of the code not working. Let's take the simple program '[+]'. Trying to tun this should just exit (because current cell is 0, it won even enter the loop). Instead if you run it in this interpreter, it goes into infinite loop.\nSo i'll kindly ask you to revert your -1 votes if my clarification makes sense now ;-)\nHere is the interpreter slightly beautified, with fixed ~ bug and i also added the missing , input:\nfrom sys import stdin, stdout\n\nbfHelloWorld = '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.'\n\n# http://esoteric.sange.fi/brainfuck/bf-source/prog/yapi.b\nbfPiDigits = '''> +++++ (5 digits)\n[<+>>>>>>>>++++++++++<<<<<<<-]>+++++[<+++++++++>-]+>>>>>>+[<<+++[>>[-<]<[>]<-]>>\n[>+>]<[<]>]>[[->>>>+<<<<]>>>+++>-]<[<<<<]<<<<<<<<+[->>>>>>>>>>>>[<+[->>>>+<<<<]>\n>>>>]<<<<[>>>>>[<<<<+>>>>-]<<<<<-[<<++++++++++>>-]>>>[<<[<+<<+>>>-]<[>+<-]<++<<+\n>>>>>>-]<<[-]<<-<[->>+<-[>>>]>[[<+>-]>+>>]<<<<<]>[-]>+<<<-[>>+<<-]<]<<<<+>>>>>>>\n>[-]>[<<<+>>>-]<<++++++++++<[->>+<-[>>>]>[[<+>-]>+>>]<<<<<]>[-]>+>[<<+<+>>>-]<<<\n<+<+>>[-[-[-[-[-[-[-[-[-<->[-<+<->>]]]]]]]]]]<[+++++[<<<++++++++<++++++++>>>>-]<\n<<<+<->>>>[>+<<<+++++++++<->>>-]<<<<<[>>+<<-]+<[->-<]>[>>.<<<<[+.[-]]>>-]>[>>.<<\n-]>[-]>[-]>>>[>>[<<<<<<<<+>>>>>>>>-]<<-]]>>[-]<<<[-]<<<<<<<<]++++++++++.\n'''\n\ncode = bfPiDigits # the code\ndata = [0] * 255 # data memory\ncp = 0 # code pointer\ndp = 0 # data pointer\n\nwhile cp < len(code):\n cmd = code[cp]\n if cmd == '>': dp += 1\n elif cmd == '<': dp -= 1\n elif cmd == '+': data[dp] += 1 \n elif cmd == '-': data[dp] -= 1 \n elif cmd == '.': stdout.write(chr(data[dp]))\n elif cmd == ',': data[dp] = ord(stdin.read(1))\n elif cmd == '[' and not data[dp]: # skip loop if ==0\n n = 0\n while True:\n cmd = code[cp]\n if cmd == '[': n += 1\n elif cmd == ']': n -= 1\n if not n: break\n cp += 1\n elif cmd == ']' and data[dp]: # loop back if !=0\n n = 0\n while True:\n cmd = code[cp]\n if cmd == '[': n+=1\n elif cmd == ']': n-=1\n if not n: break\n cp -= 1\n cp += 1\n\n",
"And to bring up one thing none of the other answers mentioned: the behavior of ~ for user-defined classes can be changed by overriding the __invert__ method (or the nb_invert slot if you're using the Python/C API). \n",
"~ is bitwise-not.\nI can't really think of a good way to illustrate it (unless you know that -1 is the bitwise negation of 0), but the wikipedia entry is pretty good.\n"
] | [
22,
14,
10,
5
] | [] | [] | [
"brainfuck",
"interpreter",
"python"
] | stackoverflow_0003027394_brainfuck_interpreter_python.txt |
Q:
Using Google AppEngine app as a OAuth provider
I'm using the Google AppEngine 1.3.4 SDK which offers to allow your application to act as a OAuth service provider (http://code.google.com/appengine/docs/python/oauth/). Setting up a standard application on my localhost and using the following:
Request URL /_ah/OAuthGetRequestToken
Authorize URL /_ah/OAuthAuthorizeToken
Access Token URL /_ah/OAuthGetAccessToken
The client application just gets sent to a page requesting to grant OAuth access even though no user is logged in. Clicking 'Grant access' results in a message saying 'OAuth access granted' with no tokens or anything exchange. Can't see how this could work when it's not even prompting for a login.
As this functionality is quite new I can't find much out there. I've created a OAuth provider before in Rails and know that you need a Consumer Key and Secret, something that seems to be lacking in GAE?
Any ideas on how to get OAuth working in a sample GAE project are most welcome.
A:
I would hazard a guess that the SDK implementation simply grants access regardless. It's also possible you still have a dev_appserver login cookie. Either way, try it in production - it'll almost certainly request login in that case.
| Using Google AppEngine app as a OAuth provider | I'm using the Google AppEngine 1.3.4 SDK which offers to allow your application to act as a OAuth service provider (http://code.google.com/appengine/docs/python/oauth/). Setting up a standard application on my localhost and using the following:
Request URL /_ah/OAuthGetRequestToken
Authorize URL /_ah/OAuthAuthorizeToken
Access Token URL /_ah/OAuthGetAccessToken
The client application just gets sent to a page requesting to grant OAuth access even though no user is logged in. Clicking 'Grant access' results in a message saying 'OAuth access granted' with no tokens or anything exchange. Can't see how this could work when it's not even prompting for a login.
As this functionality is quite new I can't find much out there. I've created a OAuth provider before in Rails and know that you need a Consumer Key and Secret, something that seems to be lacking in GAE?
Any ideas on how to get OAuth working in a sample GAE project are most welcome.
| [
"I would hazard a guess that the SDK implementation simply grants access regardless. It's also possible you still have a dev_appserver login cookie. Either way, try it in production - it'll almost certainly request login in that case.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003029556_google_app_engine_python.txt |
Q:
Writing to a file in Python inserts null bytes
I'm writing a todo list program. It keeps a file with a thing to do per line, and lets the user add or delete items. The problem is that for some reason, I end up with a lot of zero bytes at the start of the file, even though the item is correctly deleted. I'll show you a couple of screenshots to make sure I'm making myself clear.
This is the file in Notepad++ before running the program:
This is the file after deleting item 3 (counting from 1):
This is the relevant code. The actual program is bigger, but running just this part triggers the error.
import os
TODO_FILE = r"E:\javi\code\Python\todo-list\src\todo.txt"
def del_elems(f, delete):
"""Takes an open file and either a number or a list of numbers, and deletes the
lines corresponding to those numbers (counting from 1)."""
if isinstance(delete, int):
delete = [delete]
lines = f.readlines()
f.truncate(0)
counter = 1
for line in lines:
if counter not in delete:
f.write(line)
counter += 1
f = open(TODO_FILE, "r+")
del_elems(f, 3)
f.close()
Could you please point out where's the mistake?
A:
It looks to me like you're forgetting to rewind your file stream. After f.truncate(0), add f.seek(0). Otherwise, I think your next write will try to start at the position from which you left off, filling in null bytes on its way there.
(Notice that the number of null characters in your example equals the number of characters in your deleted lines plus a carriage-return and line-feed character for each one.)
A:
From the Python manual:
file.truncate([size])
Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants.
You are truncating the file and then writing item1 and item2 at the former end of the file. Everything before that ends up padded with 0 bytes.
f.seek(0)
Call this to reset the file position after the truncate.
A:
Take the hint. Don't do this.
In the olden days (30 years ago -- seriously) we "updated" files with complex add/change/delete logic.
Nowadays, life is simpler if you write programs that
Read the entire file into memory.
Work on the objects in memory.
Write the objects to a file periodically and when the user wants to save.
It's faster and simpler. Use pickle to dump your objects to a file. Don't mess with "records" or any attempt to change a file "in place".
If you really think you need SQL capabilities (Insert, Update, Delete) then use SQLite. It's more reliable than what you're attempting to do.
| Writing to a file in Python inserts null bytes | I'm writing a todo list program. It keeps a file with a thing to do per line, and lets the user add or delete items. The problem is that for some reason, I end up with a lot of zero bytes at the start of the file, even though the item is correctly deleted. I'll show you a couple of screenshots to make sure I'm making myself clear.
This is the file in Notepad++ before running the program:
This is the file after deleting item 3 (counting from 1):
This is the relevant code. The actual program is bigger, but running just this part triggers the error.
import os
TODO_FILE = r"E:\javi\code\Python\todo-list\src\todo.txt"
def del_elems(f, delete):
"""Takes an open file and either a number or a list of numbers, and deletes the
lines corresponding to those numbers (counting from 1)."""
if isinstance(delete, int):
delete = [delete]
lines = f.readlines()
f.truncate(0)
counter = 1
for line in lines:
if counter not in delete:
f.write(line)
counter += 1
f = open(TODO_FILE, "r+")
del_elems(f, 3)
f.close()
Could you please point out where's the mistake?
| [
"It looks to me like you're forgetting to rewind your file stream. After f.truncate(0), add f.seek(0). Otherwise, I think your next write will try to start at the position from which you left off, filling in null bytes on its way there.\n(Notice that the number of null characters in your example equals the number of characters in your deleted lines plus a carriage-return and line-feed character for each one.)\n",
"From the Python manual:\n\nfile.truncate([size])\n Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants.\n\nYou are truncating the file and then writing item1 and item2 at the former end of the file. Everything before that ends up padded with 0 bytes.\nf.seek(0)\n\nCall this to reset the file position after the truncate.\n",
"Take the hint. Don't do this.\nIn the olden days (30 years ago -- seriously) we \"updated\" files with complex add/change/delete logic.\nNowadays, life is simpler if you write programs that \n\nRead the entire file into memory. \nWork on the objects in memory.\nWrite the objects to a file periodically and when the user wants to save.\n\nIt's faster and simpler. Use pickle to dump your objects to a file. Don't mess with \"records\" or any attempt to change a file \"in place\".\nIf you really think you need SQL capabilities (Insert, Update, Delete) then use SQLite. It's more reliable than what you're attempting to do. \n"
] | [
16,
8,
3
] | [] | [] | [
"file",
"file_io",
"python"
] | stackoverflow_0003030343_file_file_io_python.txt |
Q:
"TypeError: draw() takes exactly 1 non-keyword argument (3 given)"
I wrote this code to open a window with Pyglet in Python...
import pyglet
from pyglet import window
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__()
myLabel = pyglet.text.Label("Prototype")
windowText = myLabel.draw(Window, "Hello World",
font_name = "Times New Roman",
font_size = 36,
color = (193, 205, 193, 255))
def on_draw(self):
self.clear()
self.label.draw()
if __name__ == '__main__':
window = Window()
pyglet.app.run()
however every time I run it I get this error:
TypeError: draw() takes exactly 1 non-keyword argument (3 given)
AFAIK the "(3 given)" means the problem is with the font_size or color arguments but I'm not sure. Could someone explain what's wrong and help me make this work?
A:
The three non-keyword arguments you've given are the object instance, Window, and "Hello World". It only expects the object instance. Check the docs again for which arguments the draw() method takes. Consider printing the repr() of myLabel so that you know which type it is.
A:
The three non-keyword arguments you're passing to draw() are myLabel (implied, becomes self), Window, and "Hello World". The documentation for this method is here.
Are you sure you didn't intend to do something more like this?
myLabel = pyglet.text.Label("Hello World")
A:
I've never used pyglet but according to the documentation draw does not take any parameters.
However the constructor does take these parameters so the following would be legal:
label = pyglet.text.Label('Hello, world',
font_name='Times New Roman',
font_size=36,
x=10, y=10)
From here.
| "TypeError: draw() takes exactly 1 non-keyword argument (3 given)" | I wrote this code to open a window with Pyglet in Python...
import pyglet
from pyglet import window
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__()
myLabel = pyglet.text.Label("Prototype")
windowText = myLabel.draw(Window, "Hello World",
font_name = "Times New Roman",
font_size = 36,
color = (193, 205, 193, 255))
def on_draw(self):
self.clear()
self.label.draw()
if __name__ == '__main__':
window = Window()
pyglet.app.run()
however every time I run it I get this error:
TypeError: draw() takes exactly 1 non-keyword argument (3 given)
AFAIK the "(3 given)" means the problem is with the font_size or color arguments but I'm not sure. Could someone explain what's wrong and help me make this work?
| [
"The three non-keyword arguments you've given are the object instance, Window, and \"Hello World\". It only expects the object instance. Check the docs again for which arguments the draw() method takes. Consider printing the repr() of myLabel so that you know which type it is.\n",
"The three non-keyword arguments you're passing to draw() are myLabel (implied, becomes self), Window, and \"Hello World\". The documentation for this method is here.\nAre you sure you didn't intend to do something more like this?\nmyLabel = pyglet.text.Label(\"Hello World\")\n\n",
"I've never used pyglet but according to the documentation draw does not take any parameters.\nHowever the constructor does take these parameters so the following would be legal:\nlabel = pyglet.text.Label('Hello, world',\n font_name='Times New Roman',\n font_size=36,\n x=10, y=10)\n\nFrom here.\n"
] | [
1,
1,
0
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0003030579_pyglet_python.txt |
Q:
Python, dictionaries, and chi-square contingency table
This is a problem I've been racking my brains on for a long time, so any help would be great. I have a file which contains several lines in the following format (word, time that the word occurred in, and frequency of documents containing the given word within the given instance in time). Below is an example of what the inputfile looks like.
#inputfile
<word, time, frequency>
apple, 1, 3
banana, 1, 2
apple, 2, 1
banana, 2, 4
orange, 3, 1
I have Python class below that I used to create 2-D dictionaries to store the above file using as the key, and frequency as the value:
class Ddict(dict):
'''
2D dictionary class
'''
def __init__(self, default=None):
self.default = default
def __getitem__(self, key):
if not self.has_key(key):
self[key] = self.default()
return dict.__getitem__(self, key)
wordtime=Ddict(dict) # Store each inputfile entry with a <word,time> key
timeword=Ddict(dict) # Store each inputfile entry with a <time,word> key
# Loop over every line of the inputfile
for line in open('inputfile'):
word,time,count=line.split(',')
# If <word,time> already a key, increment count
try:
wordtime[word][time]+=count
# Otherwise, create the key
except KeyError:
wordtime[word][time]=count
# If <time,word> already a key, increment count
try:
timeword[time][word]+=count
# Otherwise, create the key
except KeyError:
timeword[time][word]=count
The question that I have pertains to calculating certain things while iterating over the entries in this 2D dictionary. For each word 'w' at each time 't', calculate:
The number of documents with
word 'w' within time 't'. (a)
The number of documents without
word 'w' within time 't'. (b)
The number of documents with
word 'w' outside time 't'. (c)
The number of documents without
word 'w' outside time 't'. (d)
Each of the items above represents one of the cells of a chi-square contingency table for each word and time. Can all of these be calculated within a single loop or do they need to be done one at a time?
Ideally, I would like the output to be what's below, where a,b,c,d are all the items calculated above:
print "%s, %s, %s, %s" %(a,b,c,d)
In the case of the input file above, the result of trying to find the contingency table for the word 'apple' at time '1' would be (3,2,1,6). I'll explain how each cell is calculated:
'3' documents contain 'apple' within
time '1'.
There are '2' documents within time
'1' that don't contain 'apple'.
There is '1' document containing
'apple' outside time '1'.
There are 6 documents outside time
'1' that don't contain the word
'apple' (1+4+1).
A:
Your 4 numbers for apple/1 add up to 12, more than the total number of observations (11)! There are only 5 documents outside time '1' that don't contain the word 'apple'.
You need to partition the observations into 4 disjoint subsets:
a: apple and 1 => 3
b: not-apple and 1 => 2
c: apple and not-1 => 1
d: not-apple and not-1 => 5
Here is some code that shows one way of doing it:
from collections import defaultdict
class Crosstab(object):
def __init__(self):
self.count = defaultdict(lambda: defaultdict(int))
self.row_tot = defaultdict(int)
self.col_tot = defaultdict(int)
self.grand_tot = 0
def add(self, r, c, n):
self.count[r][c] += n
self.row_tot[r] += n
self.col_tot[c] += n
self.grand_tot += n
def load_data(line_iterator, conv_funcs):
ct = Crosstab()
for line in line_iterator:
r, c, n = [func(s) for func, s in zip(conv_funcs, line.split(','))]
ct.add(r, c, n)
return ct
def display_all_2x2_tables(crosstab):
for rx in crosstab.row_tot:
for cx in crosstab.col_tot:
a = crosstab.count[rx][cx]
b = crosstab.col_tot[cx] - a
c = crosstab.row_tot[rx] - a
d = crosstab.grand_tot - a - b - c
assert all(x >= 0 for x in (a, b, c, d))
print ",".join(str(x) for x in (rx, cx, a, b, c, d))
if __name__ == "__main__":
# inputfile
# <word, time, frequency>
lines = """\
apple, 1, 3
banana, 1, 2
apple, 2, 1
banana, 2, 4
orange, 3, 1""".splitlines()
ct = load_data(lines, (str.strip, int, int))
display_all_2x2_tables(ct)
and here is the output:
orange,1,0,5,1,5
orange,2,0,5,1,5
orange,3,1,0,0,10
apple,1,3,2,1,5
apple,2,1,4,3,3
apple,3,0,1,4,6
banana,1,2,3,4,2
banana,2,4,1,2,4
banana,3,0,1,6,4
| Python, dictionaries, and chi-square contingency table | This is a problem I've been racking my brains on for a long time, so any help would be great. I have a file which contains several lines in the following format (word, time that the word occurred in, and frequency of documents containing the given word within the given instance in time). Below is an example of what the inputfile looks like.
#inputfile
<word, time, frequency>
apple, 1, 3
banana, 1, 2
apple, 2, 1
banana, 2, 4
orange, 3, 1
I have Python class below that I used to create 2-D dictionaries to store the above file using as the key, and frequency as the value:
class Ddict(dict):
'''
2D dictionary class
'''
def __init__(self, default=None):
self.default = default
def __getitem__(self, key):
if not self.has_key(key):
self[key] = self.default()
return dict.__getitem__(self, key)
wordtime=Ddict(dict) # Store each inputfile entry with a <word,time> key
timeword=Ddict(dict) # Store each inputfile entry with a <time,word> key
# Loop over every line of the inputfile
for line in open('inputfile'):
word,time,count=line.split(',')
# If <word,time> already a key, increment count
try:
wordtime[word][time]+=count
# Otherwise, create the key
except KeyError:
wordtime[word][time]=count
# If <time,word> already a key, increment count
try:
timeword[time][word]+=count
# Otherwise, create the key
except KeyError:
timeword[time][word]=count
The question that I have pertains to calculating certain things while iterating over the entries in this 2D dictionary. For each word 'w' at each time 't', calculate:
The number of documents with
word 'w' within time 't'. (a)
The number of documents without
word 'w' within time 't'. (b)
The number of documents with
word 'w' outside time 't'. (c)
The number of documents without
word 'w' outside time 't'. (d)
Each of the items above represents one of the cells of a chi-square contingency table for each word and time. Can all of these be calculated within a single loop or do they need to be done one at a time?
Ideally, I would like the output to be what's below, where a,b,c,d are all the items calculated above:
print "%s, %s, %s, %s" %(a,b,c,d)
In the case of the input file above, the result of trying to find the contingency table for the word 'apple' at time '1' would be (3,2,1,6). I'll explain how each cell is calculated:
'3' documents contain 'apple' within
time '1'.
There are '2' documents within time
'1' that don't contain 'apple'.
There is '1' document containing
'apple' outside time '1'.
There are 6 documents outside time
'1' that don't contain the word
'apple' (1+4+1).
| [
"Your 4 numbers for apple/1 add up to 12, more than the total number of observations (11)! There are only 5 documents outside time '1' that don't contain the word 'apple'.\nYou need to partition the observations into 4 disjoint subsets:\na: apple and 1 => 3\nb: not-apple and 1 => 2\nc: apple and not-1 => 1\nd: not-apple and not-1 => 5 \nHere is some code that shows one way of doing it:\nfrom collections import defaultdict\n\nclass Crosstab(object):\n\n def __init__(self):\n self.count = defaultdict(lambda: defaultdict(int))\n self.row_tot = defaultdict(int)\n self.col_tot = defaultdict(int)\n self.grand_tot = 0\n\n def add(self, r, c, n):\n self.count[r][c] += n\n self.row_tot[r] += n\n self.col_tot[c] += n\n self.grand_tot += n\n\ndef load_data(line_iterator, conv_funcs):\n ct = Crosstab()\n for line in line_iterator:\n r, c, n = [func(s) for func, s in zip(conv_funcs, line.split(','))]\n ct.add(r, c, n)\n return ct\n\ndef display_all_2x2_tables(crosstab):\n for rx in crosstab.row_tot:\n for cx in crosstab.col_tot:\n a = crosstab.count[rx][cx]\n b = crosstab.col_tot[cx] - a\n c = crosstab.row_tot[rx] - a\n d = crosstab.grand_tot - a - b - c\n assert all(x >= 0 for x in (a, b, c, d))\n print \",\".join(str(x) for x in (rx, cx, a, b, c, d))\n\nif __name__ == \"__main__\":\n\n # inputfile\n # <word, time, frequency>\n lines = \"\"\"\\\n apple, 1, 3\n banana, 1, 2\n apple, 2, 1\n banana, 2, 4\n orange, 3, 1\"\"\".splitlines()\n\n ct = load_data(lines, (str.strip, int, int))\n display_all_2x2_tables(ct)\n\nand here is the output:\norange,1,0,5,1,5\norange,2,0,5,1,5\norange,3,1,0,0,10\napple,1,3,2,1,5\napple,2,1,4,3,3\napple,3,0,1,4,6\nbanana,1,2,3,4,2\nbanana,2,4,1,2,4\nbanana,3,0,1,6,4\n\n"
] | [
2
] | [] | [] | [
"dictionary",
"discrete_mathematics",
"python"
] | stackoverflow_0003029600_dictionary_discrete_mathematics_python.txt |
Q:
Image resizing web service
Does someone know a good web service to resize images ? Either an open source (PHP/Python/Ruby) application, or a company providing a web service api.
A:
Make your own service at Utility Mill (http://utilitymill.com). Here's one that I wrote that adds a simulated gallery wrap - http://utilitymill.com/utility/Gallery_Wrap_Image. Define your own interface, parameters, processing logic, and you get not only an interactive web service, but you also get a callable API.
A:
Another alternative is the image processing web service at www.lightspun.com .
A:
So you're asking for a website?
http://www.picnik.com/ is what Flickr uses.
http://www.shrinkpictures.com/
A:
PHP provides image resizing support using image magick.
Smart Image Resizer is a PHP script ready for use. Look at http://shiftingpixel.com/2008/03/03/smart-image-resizer/
To build your own PHP app, look at http://www.php.net/manual/de/ref.image.php
| Image resizing web service | Does someone know a good web service to resize images ? Either an open source (PHP/Python/Ruby) application, or a company providing a web service api.
| [
"Make your own service at Utility Mill (http://utilitymill.com). Here's one that I wrote that adds a simulated gallery wrap - http://utilitymill.com/utility/Gallery_Wrap_Image. Define your own interface, parameters, processing logic, and you get not only an interactive web service, but you also get a callable API.\n",
"Another alternative is the image processing web service at www.lightspun.com .\n",
"So you're asking for a website?\nhttp://www.picnik.com/ is what Flickr uses.\nhttp://www.shrinkpictures.com/\n",
"PHP provides image resizing support using image magick. \nSmart Image Resizer is a PHP script ready for use. Look at http://shiftingpixel.com/2008/03/03/smart-image-resizer/\nTo build your own PHP app, look at http://www.php.net/manual/de/ref.image.php\n"
] | [
4,
3,
1,
0
] | [] | [] | [
"image_processing",
"php",
"python",
"ruby",
"web_services"
] | stackoverflow_0001000195_image_processing_php_python_ruby_web_services.txt |
Q:
Look for match in a nested list in Python
I have two nested lists of different sizes:
A = [[1, 7, 3, 5], [5, 5, 14, 10]]
B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]]
I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L:
L = [[1, 17, 3, 5], [141, 25, 14, 10]]
Additionally if the match occurs then I want to change last element of sublist B into first element of sublist A so the final solution would look like this:
L1 = [[1, 17, 3, 1], [141, 25, 14, 5]]
A:
It looks like this does what you want:
> [b for b in B if b[2:4] in [a[2:4] for a in A]]
[[1, 17, 3, 5], [141, 25, 14, 10]]
But, for efficiency's sake, you may want to precompute the slices of A.
> a_slices = [a[2:4] for a in A]
> [b for b in B if b[2:4] in a_slices]
[[1, 17, 3, 5], [141, 25, 14, 10]]
Here's something that looks like it meets your new requirements:
> [b[:-1] + a[:1] for b in B for a in A if b[2:4] == a[2:4]]
[[1, 17, 3, 1], [141, 25, 14, 5]]
A:
[x for x in B if any(x[2:4] == y[2:4] for y in A)]
| Look for match in a nested list in Python | I have two nested lists of different sizes:
A = [[1, 7, 3, 5], [5, 5, 14, 10]]
B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]]
I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L:
L = [[1, 17, 3, 5], [141, 25, 14, 10]]
Additionally if the match occurs then I want to change last element of sublist B into first element of sublist A so the final solution would look like this:
L1 = [[1, 17, 3, 1], [141, 25, 14, 5]]
| [
"It looks like this does what you want:\n> [b for b in B if b[2:4] in [a[2:4] for a in A]]\n[[1, 17, 3, 5], [141, 25, 14, 10]]\n\nBut, for efficiency's sake, you may want to precompute the slices of A.\n> a_slices = [a[2:4] for a in A]\n> [b for b in B if b[2:4] in a_slices]\n[[1, 17, 3, 5], [141, 25, 14, 10]]\n\nHere's something that looks like it meets your new requirements:\n> [b[:-1] + a[:1] for b in B for a in A if b[2:4] == a[2:4]]\n[[1, 17, 3, 1], [141, 25, 14, 5]]\n\n",
"[x for x in B if any(x[2:4] == y[2:4] for y in A)]\n\n"
] | [
3,
1
] | [] | [] | [
"list",
"nested",
"python"
] | stackoverflow_0003030790_list_nested_python.txt |
Q:
Best style for Python programs: what do you suggest?
A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program turned out (after adding my own requirements).
#! /usr/bin/env python
################################################################################
"""\
CLASS INFORMATION
-----------------
Program Name: Program 11
Programmer: Stephen Chappell
Instructor: Stephen Chappell for CS 999-0, Python
Due Date: 17 May 2010
DOCUMENTATION
-------------
This is a simple encryption program that can encode and decode messages."""
################################################################################
import sys
KEY_FILE = 'Key.txt'
BACKUP = '''\
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO\
PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
_@/6-UC'GzaV0%5Mo9g+yNh8b">Bi=<Lx [sQn#^R.D2Xc(\
Jm!4e${lAEWud&t7]H\`}pvPw)FY,Z~?qK|3SOfk*:1;jTrI''' #`
################################################################################
def main():
"Run the program: loads key, runs processing loop, and saves key."
encode_map, decode_map = load_key(KEY_FILE)
try:
run_interface_loop(encode_map, decode_map)
except SystemExit:
pass
save_key(KEY_FILE, encode_map)
def run_interface_loop(encode_map, decode_map):
"Shows the menu and runs the appropriate command."
print('This program handles encryption via a customizable key.')
while True:
print('''\
MENU
====
(1) Encode
(2) Decode
(3) Custom
(4) Finish''')
switch = get_character('Select: ', tuple('1234'))
FUNC[switch](encode_map, decode_map)
def get_character(prompt, choices):
"Gets a valid menu option and returns it."
while True:
sys.stdout.write(prompt)
sys.stdout.flush()
line = sys.stdin.readline()[:-1]
if not line:
sys.exit()
if line in choices:
return line
print(repr(line), 'is not a valid choice.')
################################################################################
def load_key(filename):
"Gets the key file data and returns encoding/decoding dictionaries."
plain, cypher = open_file(filename)
return dict(zip(plain, cypher)), dict(zip(cypher, plain))
def open_file(filename):
"Load the keys and tries to create it when not available."
while True:
try:
with open(filename) as file:
plain, cypher = file.read().split('\n')
return plain, cypher
except:
with open(filename, 'w') as file:
file.write(BACKUP)
def save_key(filename, encode_map):
"Dumps the map into two buffers and saves them to the key file."
plain = cypher = str()
for p, c in encode_map.items():
plain += p
cypher += c
with open(filename, 'w') as file:
file.write(plain + '\n' + cypher)
################################################################################
def encode(encode_map, decode_map):
"Encodes message for the user."
print('Enter your message to encode (EOF when finished).')
message = get_message()
for char in message:
sys.stdout.write(encode_map[char] if char in encode_map else char)
def decode(encode_map, decode_map):
"Decodes message for the user."
print('Enter your message to decode (EOF when finished).')
message = get_message()
for char in message:
sys.stdout.write(decode_map[char] if char in decode_map else char)
def custom(encode_map, decode_map):
"Allows user to edit the encoding/decoding dictionaries."
plain, cypher = get_new_mapping()
for p, c in zip(plain, cypher):
encode_map[p] = c
decode_map[c] = p
################################################################################
def get_message():
"Gets and returns text entered by the user (until EOF)."
buffer = []
while True:
line = sys.stdin.readline()
if line:
buffer.append(line)
else:
return ''.join(buffer)
def get_new_mapping():
"Prompts for strings to edit encoding/decoding maps."
while True:
plain = get_unique_chars('What do you want to encode from?')
cypher = get_unique_chars('What do you want to encode to?')
if len(plain) == len(cypher):
return plain, cypher
print('Both lines should have the same length.')
def get_unique_chars(prompt):
"Gets strings that only contain unique characters."
print(prompt)
while True:
line = input()
if len(line) == len(set(line)):
return line
print('There were duplicate characters: please try again.')
################################################################################
# This map is used for dispatching commands in the interface loop.
FUNC = {'1': encode, '2': decode, '3': custom, '4': lambda a, b: sys.exit()}
################################################################################
if __name__ == '__main__':
main()
For all those Python programmers out there, your help is being requested. How should the formatting (not necessarily the coding by altered to fit Python's style guide? My friend does not need to be learning things that are not correct. If you have suggestions on the code, feel free to post them to this wiki as well.
EDIT: For those interested, here is the original code source in C that my friend gave me for translation.
/******************************************************************************
CLASS INFORMATION
-----------------
Program Name: Program 11 - Encodes/Decodes
Programmer: Evgnto nAl.Wi a
Instructor: fsSP21 .C emgr2rCHoMal4 gyia ro-rm n ,
Date Due: MAY 4, 2010
PLEDGE STATEMENT
----------------
I pledge that all of the code in this program is my own _original_ work for
the spring 2010 semester. None of the code in this program has been copied
from anyone or anyplace unless I was specifically authorized to do so by my
CS 214 instructor. This program has been created using properly licensed
software.
Signed: ________________________________
DOCUMENTATION
-------------
This program Encodes and decodes a program. It also gives you the option of
making your own code.
******************************************************************************/
#include <stdio.h>
#define ENCODE 1
#define DECODE 2
#define OWNCODE 3
#define QUIT 4
void printPurpose();
void encode(char input[], char code1[]);
void decode(char input[], char code1[]);
void ownCode();
int main()
{
char charIn;
char code1[100] = "";
char input[100] = "";
int a;
int b;
int closeStatus;
int number;
a = 0;
b = 0;
FILE *code;
printPurpose();
if (!(code = fopen("code.txt", "r")))
{
printf("Error opening code.txt for reading");
return 100;
}
while ((charIn = fgetc(code)) != '\n')
{
input[a] = charIn;
a++;
}
while ((charIn = fgetc(code)) != EOF)
{
code1[b] = charIn;
b++;
}
scanf("%d", &number);
while (number != QUIT)
{
if (number == ENCODE)
encode(input, code1);
else if (number == DECODE)
decode(input, code1);
else if (number == OWNCODE)
ownCode();
printf("\n\n");
printPurpose();
scanf("%d", &number);
}
printf("Thank you for using my program Mr. Halsey!!!!!!!!\n");
closeStatus = fclose(code);
if (closeStatus == EOF)
{
printf("File close error.\n");
return 201;
}
else
printf("Exit successfully.\n");
return 0;
}
/******************************************************************************
Prints the purpose of the program
******************************************************************************/
void printPurpose()
{
printf("This program Encodes, Decodes, and allows you to make your own");
printf("code.\n");
printf("Enter a 1 to Encode\n");
printf("Enter a 2 to Decode\n");
printf("Enter a 3 to make your own code\n");
printf("Enter a 4 to Quit\n");
}
/******************************************************************************
Encodes the sentence entered
******************************************************************************/
void encode(char input[], char code1[])
{
char sentence[100] = "";
char x;
char y;
int index;
int index2;
index = 0;
printf("Enter your sentence\n");
gets(sentence);
gets(sentence);
printf("Your encoded message is >");
for (index2 = 0; (y = sentence[index2]) != '\0'; index2++)
{
while ((x = input[index]) != y)
index++;
if (x == y)
printf("%c", code1[index]);
else
printf("error");
index = 0;
}
return;
}
/******************************************************************************
Decodes the sentence entered
******************************************************************************/
void decode(char input[], char code1[])
{
char encodedMessage[100] = "";
char x;
char y;
int index1;
int index2;
index2 = 0;
printf("Enter encoded message\n");
gets(encodedMessage);
gets(encodedMessage);
printf("Your decoded message is >");
for (index1 = 0; (y = encodedMessage[index1]) != '\0'; index1++)
{
while (( x = code1[index2]) != y)
index2++;
if (x == y)
printf("%c", input[index2]);
else
printf("error");
index2 = 0;
}
return;
}
/******************************************************************************
Reads in your code and encodes / decodes
******************************************************************************/
void ownCode()
{
char charactersUsed[50] = "";
char codeUsed[50] = "";
char sentence[50] = "";
int index1;
int index2;
int number;
int x;
int y;
index2 = 0;
y = 0;
printf("Enter the characters you want to use.\n");
printf("Use less than 50 characters and DO NOT REPEAT the characters.\n");
gets(charactersUsed);
gets(charactersUsed);
printf("Enter the code for the characters.\n");
gets(codeUsed);
printf("\nEnter 1 to encode and 2 to decode or 3 to return to main menu.\n");
scanf("%d", &number);
while (number != OWNCODE)
{
if (number == ENCODE)
{
printf("Enter your sentence.\n");
gets(sentence);
gets(sentence);
printf("Your encoded message is > ");
for (index1 = 0; (y = sentence[index1]) != '\0'; index1++)
{
while (( x = charactersUsed[index2]) != y)
index2++;
if (x == y)
printf("%c", codeUsed[index2]);
else
printf("error");
index2 = 0;
}
}
else if (number == DECODE)
{
printf("Enter your encoded sentence.\n");
gets(sentence);
gets(sentence);
printf("Your decoded message is > ");
for (index1 = 0; (y = sentence[index1]) != '\0'; index1++)
{
while (( x = codeUsed[index2]) != y)
index2++;
if (x == y)
printf("%c", charactersUsed[index2]);
else
printf("error");
index2 = 0;
}
}
printf("\nEnter 1 to encode and 2 to decode or 3 to return to main menu.\n");
scanf("%d", &number);
}
return;
}
A:
Since you asked about formatting and style, I'm surprised that nobody else has mentioned PEP 8 yet. It's nominally a guide for modules that want to be included in the standard library, but I find most of its guidance to be applicable pretty much everywhere.
A:
don't use bare excepts;
try:
with open(filename) as file:
plain, cypher = file.read().split('\n')
return plain, cypher
**except:**
with open(filename, 'w') as file:
file.write(BACKUP)
it is almost always wrong to use bare excepts, and in this case, it is wrong. Catch the exceptions that you want to catch only, in this case most likely is IOException and the error you might get if the file does not contain a '\n' and your tuple unpacking fails (hint: catch them in separate except clause). Also, you might be interested to check what happens if the user doesn't has write permission to filename.
Is there any reason why you're not using print and raw_input() here?
def get_character(prompt, choices):
"Gets a valid menu option and returns it."
while True:
sys.stdout.write(prompt)
sys.stdout.flush()
line = sys.stdin.readline()[:-1]
if not line:
sys.exit()
if line in choices:
return line
print(repr(line), 'is not a valid choice.')
you might want to use str.translate() for this:
sys.stdout.write(encode_map[char] if char in encode_map else char)
A:
In my opinion, the whole program is questionable. The choices of how things are divided into functions is kind of dopey, and it's documented like a class project, not like real system. The documentation kind of obscures the overall mediocre organization. The entire program shows a bias towards verbosity over clarity.
The construct '''\ is frequently seen. The point of the triple quote construct is that carriage returns and newlines work just fine. There is no need to \ escape the newline.
I will tackle functions I see specific problems in as examples:
Whether or not get_message should exist in that form is debatable. The entire function can be replaced by one line.
def get_message():
"Gets and returns text entered by the user (until EOF)."
return sys.stdin.read()
The way main, run_interface_loop, get_character and FUNC interact is confusing and not the best way to handle the problem. In particular, catching SystemExit isn't really a great way to signal your program's end in this case.
def main():
encode_map, decode_map = load_key(KEY_FILE)
run_interface_loop(encode_map, decode_map)
save_key(KEY_FILE, encode_map)
def run_interface_loop():
exit_picked = False
while not exit_picked:
print '''
MENU
====
(1) Encode
(2) Decode
(3) Custom
(4) Finish'''
choice = sys.stdin.readline()
if choice == '':
break # EOF was reached, no more asking the user for stuff
choice = choice.strip()
if choice == '1':
encode(encode_map, decode_map) # This reads until EOF
exit_picked = True # and so we might as well exit
elif choice == '2':
decode(encode_map, decode_map)
exit_picked = True # Same here
elif choice == '3':
encode_map, decode_map = custom()
elif choice == '4':
exit_picked = True
else:
print "%s isn't a valid choice, try again." % (choice,)
A:
Never call sys.exit() or raise SystemExit inside a function. Instead, raise other exceptions instead.
A:
Also look here for Google's Python coding guidelines. They're mostly in line with the PEP mentioned above but are a bit more restrictive in some areas.
Google Python Style Guide
| Best style for Python programs: what do you suggest? | A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program turned out (after adding my own requirements).
#! /usr/bin/env python
################################################################################
"""\
CLASS INFORMATION
-----------------
Program Name: Program 11
Programmer: Stephen Chappell
Instructor: Stephen Chappell for CS 999-0, Python
Due Date: 17 May 2010
DOCUMENTATION
-------------
This is a simple encryption program that can encode and decode messages."""
################################################################################
import sys
KEY_FILE = 'Key.txt'
BACKUP = '''\
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO\
PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
_@/6-UC'GzaV0%5Mo9g+yNh8b">Bi=<Lx [sQn#^R.D2Xc(\
Jm!4e${lAEWud&t7]H\`}pvPw)FY,Z~?qK|3SOfk*:1;jTrI''' #`
################################################################################
def main():
"Run the program: loads key, runs processing loop, and saves key."
encode_map, decode_map = load_key(KEY_FILE)
try:
run_interface_loop(encode_map, decode_map)
except SystemExit:
pass
save_key(KEY_FILE, encode_map)
def run_interface_loop(encode_map, decode_map):
"Shows the menu and runs the appropriate command."
print('This program handles encryption via a customizable key.')
while True:
print('''\
MENU
====
(1) Encode
(2) Decode
(3) Custom
(4) Finish''')
switch = get_character('Select: ', tuple('1234'))
FUNC[switch](encode_map, decode_map)
def get_character(prompt, choices):
"Gets a valid menu option and returns it."
while True:
sys.stdout.write(prompt)
sys.stdout.flush()
line = sys.stdin.readline()[:-1]
if not line:
sys.exit()
if line in choices:
return line
print(repr(line), 'is not a valid choice.')
################################################################################
def load_key(filename):
"Gets the key file data and returns encoding/decoding dictionaries."
plain, cypher = open_file(filename)
return dict(zip(plain, cypher)), dict(zip(cypher, plain))
def open_file(filename):
"Load the keys and tries to create it when not available."
while True:
try:
with open(filename) as file:
plain, cypher = file.read().split('\n')
return plain, cypher
except:
with open(filename, 'w') as file:
file.write(BACKUP)
def save_key(filename, encode_map):
"Dumps the map into two buffers and saves them to the key file."
plain = cypher = str()
for p, c in encode_map.items():
plain += p
cypher += c
with open(filename, 'w') as file:
file.write(plain + '\n' + cypher)
################################################################################
def encode(encode_map, decode_map):
"Encodes message for the user."
print('Enter your message to encode (EOF when finished).')
message = get_message()
for char in message:
sys.stdout.write(encode_map[char] if char in encode_map else char)
def decode(encode_map, decode_map):
"Decodes message for the user."
print('Enter your message to decode (EOF when finished).')
message = get_message()
for char in message:
sys.stdout.write(decode_map[char] if char in decode_map else char)
def custom(encode_map, decode_map):
"Allows user to edit the encoding/decoding dictionaries."
plain, cypher = get_new_mapping()
for p, c in zip(plain, cypher):
encode_map[p] = c
decode_map[c] = p
################################################################################
def get_message():
"Gets and returns text entered by the user (until EOF)."
buffer = []
while True:
line = sys.stdin.readline()
if line:
buffer.append(line)
else:
return ''.join(buffer)
def get_new_mapping():
"Prompts for strings to edit encoding/decoding maps."
while True:
plain = get_unique_chars('What do you want to encode from?')
cypher = get_unique_chars('What do you want to encode to?')
if len(plain) == len(cypher):
return plain, cypher
print('Both lines should have the same length.')
def get_unique_chars(prompt):
"Gets strings that only contain unique characters."
print(prompt)
while True:
line = input()
if len(line) == len(set(line)):
return line
print('There were duplicate characters: please try again.')
################################################################################
# This map is used for dispatching commands in the interface loop.
FUNC = {'1': encode, '2': decode, '3': custom, '4': lambda a, b: sys.exit()}
################################################################################
if __name__ == '__main__':
main()
For all those Python programmers out there, your help is being requested. How should the formatting (not necessarily the coding by altered to fit Python's style guide? My friend does not need to be learning things that are not correct. If you have suggestions on the code, feel free to post them to this wiki as well.
EDIT: For those interested, here is the original code source in C that my friend gave me for translation.
/******************************************************************************
CLASS INFORMATION
-----------------
Program Name: Program 11 - Encodes/Decodes
Programmer: Evgnto nAl.Wi a
Instructor: fsSP21 .C emgr2rCHoMal4 gyia ro-rm n ,
Date Due: MAY 4, 2010
PLEDGE STATEMENT
----------------
I pledge that all of the code in this program is my own _original_ work for
the spring 2010 semester. None of the code in this program has been copied
from anyone or anyplace unless I was specifically authorized to do so by my
CS 214 instructor. This program has been created using properly licensed
software.
Signed: ________________________________
DOCUMENTATION
-------------
This program Encodes and decodes a program. It also gives you the option of
making your own code.
******************************************************************************/
#include <stdio.h>
#define ENCODE 1
#define DECODE 2
#define OWNCODE 3
#define QUIT 4
void printPurpose();
void encode(char input[], char code1[]);
void decode(char input[], char code1[]);
void ownCode();
int main()
{
char charIn;
char code1[100] = "";
char input[100] = "";
int a;
int b;
int closeStatus;
int number;
a = 0;
b = 0;
FILE *code;
printPurpose();
if (!(code = fopen("code.txt", "r")))
{
printf("Error opening code.txt for reading");
return 100;
}
while ((charIn = fgetc(code)) != '\n')
{
input[a] = charIn;
a++;
}
while ((charIn = fgetc(code)) != EOF)
{
code1[b] = charIn;
b++;
}
scanf("%d", &number);
while (number != QUIT)
{
if (number == ENCODE)
encode(input, code1);
else if (number == DECODE)
decode(input, code1);
else if (number == OWNCODE)
ownCode();
printf("\n\n");
printPurpose();
scanf("%d", &number);
}
printf("Thank you for using my program Mr. Halsey!!!!!!!!\n");
closeStatus = fclose(code);
if (closeStatus == EOF)
{
printf("File close error.\n");
return 201;
}
else
printf("Exit successfully.\n");
return 0;
}
/******************************************************************************
Prints the purpose of the program
******************************************************************************/
void printPurpose()
{
printf("This program Encodes, Decodes, and allows you to make your own");
printf("code.\n");
printf("Enter a 1 to Encode\n");
printf("Enter a 2 to Decode\n");
printf("Enter a 3 to make your own code\n");
printf("Enter a 4 to Quit\n");
}
/******************************************************************************
Encodes the sentence entered
******************************************************************************/
void encode(char input[], char code1[])
{
char sentence[100] = "";
char x;
char y;
int index;
int index2;
index = 0;
printf("Enter your sentence\n");
gets(sentence);
gets(sentence);
printf("Your encoded message is >");
for (index2 = 0; (y = sentence[index2]) != '\0'; index2++)
{
while ((x = input[index]) != y)
index++;
if (x == y)
printf("%c", code1[index]);
else
printf("error");
index = 0;
}
return;
}
/******************************************************************************
Decodes the sentence entered
******************************************************************************/
void decode(char input[], char code1[])
{
char encodedMessage[100] = "";
char x;
char y;
int index1;
int index2;
index2 = 0;
printf("Enter encoded message\n");
gets(encodedMessage);
gets(encodedMessage);
printf("Your decoded message is >");
for (index1 = 0; (y = encodedMessage[index1]) != '\0'; index1++)
{
while (( x = code1[index2]) != y)
index2++;
if (x == y)
printf("%c", input[index2]);
else
printf("error");
index2 = 0;
}
return;
}
/******************************************************************************
Reads in your code and encodes / decodes
******************************************************************************/
void ownCode()
{
char charactersUsed[50] = "";
char codeUsed[50] = "";
char sentence[50] = "";
int index1;
int index2;
int number;
int x;
int y;
index2 = 0;
y = 0;
printf("Enter the characters you want to use.\n");
printf("Use less than 50 characters and DO NOT REPEAT the characters.\n");
gets(charactersUsed);
gets(charactersUsed);
printf("Enter the code for the characters.\n");
gets(codeUsed);
printf("\nEnter 1 to encode and 2 to decode or 3 to return to main menu.\n");
scanf("%d", &number);
while (number != OWNCODE)
{
if (number == ENCODE)
{
printf("Enter your sentence.\n");
gets(sentence);
gets(sentence);
printf("Your encoded message is > ");
for (index1 = 0; (y = sentence[index1]) != '\0'; index1++)
{
while (( x = charactersUsed[index2]) != y)
index2++;
if (x == y)
printf("%c", codeUsed[index2]);
else
printf("error");
index2 = 0;
}
}
else if (number == DECODE)
{
printf("Enter your encoded sentence.\n");
gets(sentence);
gets(sentence);
printf("Your decoded message is > ");
for (index1 = 0; (y = sentence[index1]) != '\0'; index1++)
{
while (( x = codeUsed[index2]) != y)
index2++;
if (x == y)
printf("%c", charactersUsed[index2]);
else
printf("error");
index2 = 0;
}
}
printf("\nEnter 1 to encode and 2 to decode or 3 to return to main menu.\n");
scanf("%d", &number);
}
return;
}
| [
"Since you asked about formatting and style, I'm surprised that nobody else has mentioned PEP 8 yet. It's nominally a guide for modules that want to be included in the standard library, but I find most of its guidance to be applicable pretty much everywhere.\n",
"don't use bare excepts;\ntry:\n with open(filename) as file:\n plain, cypher = file.read().split('\\n')\n return plain, cypher\n**except:**\n with open(filename, 'w') as file:\n file.write(BACKUP)\n\nit is almost always wrong to use bare excepts, and in this case, it is wrong. Catch the exceptions that you want to catch only, in this case most likely is IOException and the error you might get if the file does not contain a '\\n' and your tuple unpacking fails (hint: catch them in separate except clause). Also, you might be interested to check what happens if the user doesn't has write permission to filename.\nIs there any reason why you're not using print and raw_input() here?\ndef get_character(prompt, choices):\n \"Gets a valid menu option and returns it.\"\n while True:\n sys.stdout.write(prompt)\n sys.stdout.flush()\n line = sys.stdin.readline()[:-1]\n if not line:\n sys.exit()\n if line in choices:\n return line\n print(repr(line), 'is not a valid choice.')\n\nyou might want to use str.translate() for this:\n sys.stdout.write(encode_map[char] if char in encode_map else char)\n\n",
"In my opinion, the whole program is questionable. The choices of how things are divided into functions is kind of dopey, and it's documented like a class project, not like real system. The documentation kind of obscures the overall mediocre organization. The entire program shows a bias towards verbosity over clarity.\nThe construct '''\\ is frequently seen. The point of the triple quote construct is that carriage returns and newlines work just fine. There is no need to \\ escape the newline.\nI will tackle functions I see specific problems in as examples:\nWhether or not get_message should exist in that form is debatable. The entire function can be replaced by one line.\ndef get_message():\n \"Gets and returns text entered by the user (until EOF).\"\n return sys.stdin.read()\n\nThe way main, run_interface_loop, get_character and FUNC interact is confusing and not the best way to handle the problem. In particular, catching SystemExit isn't really a great way to signal your program's end in this case.\ndef main():\n encode_map, decode_map = load_key(KEY_FILE)\n run_interface_loop(encode_map, decode_map)\n save_key(KEY_FILE, encode_map)\n\ndef run_interface_loop():\n exit_picked = False\n while not exit_picked:\n print '''\nMENU\n====\n(1) Encode\n(2) Decode\n(3) Custom\n(4) Finish'''\n choice = sys.stdin.readline()\n if choice == '':\n break # EOF was reached, no more asking the user for stuff\n choice = choice.strip()\n if choice == '1':\n encode(encode_map, decode_map) # This reads until EOF\n exit_picked = True # and so we might as well exit\n elif choice == '2':\n decode(encode_map, decode_map)\n exit_picked = True # Same here\n elif choice == '3':\n encode_map, decode_map = custom()\n elif choice == '4':\n exit_picked = True\n else:\n print \"%s isn't a valid choice, try again.\" % (choice,)\n\n",
"Never call sys.exit() or raise SystemExit inside a function. Instead, raise other exceptions instead.\n",
"Also look here for Google's Python coding guidelines. They're mostly in line with the PEP mentioned above but are a bit more restrictive in some areas.\nGoogle Python Style Guide\n"
] | [
8,
6,
3,
2,
1
] | [] | [] | [
"coding_style",
"encryption",
"python"
] | stackoverflow_0003028961_coding_style_encryption_python.txt |
Q:
GUI not updated from another thread when using PyGtk
I am using PyGTK to build a GUI application. I want to update the textview widget from another thread but the widget is not getting updated everytime i try an update. What should i do to get a reliable GUI updating?
A:
GTK+ is not thread-safe, so you should not simply call GUI update methods from other threads. glib.idle_add (or gobject.idle_add in older PyGTK versions) can be used for this purpose.
Instead of writing:
label.set_text("foo")
you would write:
glib.idle_add(label.set_text, "foo")
which causes the function call to be queued in GTK+.
If you need to run multiple statements, it's often easier to wrap them in a function:
def idle():
label1.set_text("foo")
label2.set_text("bar")
glib.idle_add(idle)
Make sure that the function passed to idle_add does not return True; otherwise it will be queued again.
Edit: As Daniel pointed out, you need to call gtk.gdk.threads_init() anywhere in your program first.
A:
As stated in the previous answers, GTK is not "thread safe," but it is "thread-aware" - see this page on Threads: https://developer.gnome.org/gdk2/stable/gdk2-Threads.html
In order to modify GTK widgets from another thread you have to use GTK's locking. Call gtk.threads_init() immediately after importing the gtk module, and then you can update like so:
gtk.threads_enter()
# make changes...
gtk.threads_leave()
Note that the above will not work on Windows (see the link above). On Windows you must use gobject.idle_add() as explained above, though don't forget to put gobject.threads_init() directly after importing gobject in your code! The idle_add() function will execute the update itself in the main thread (the thread running gtk.main()).
| GUI not updated from another thread when using PyGtk | I am using PyGTK to build a GUI application. I want to update the textview widget from another thread but the widget is not getting updated everytime i try an update. What should i do to get a reliable GUI updating?
| [
"GTK+ is not thread-safe, so you should not simply call GUI update methods from other threads. glib.idle_add (or gobject.idle_add in older PyGTK versions) can be used for this purpose.\nInstead of writing:\nlabel.set_text(\"foo\")\n\nyou would write:\nglib.idle_add(label.set_text, \"foo\")\n\nwhich causes the function call to be queued in GTK+.\nIf you need to run multiple statements, it's often easier to wrap them in a function:\ndef idle():\n label1.set_text(\"foo\")\n label2.set_text(\"bar\")\nglib.idle_add(idle)\n\nMake sure that the function passed to idle_add does not return True; otherwise it will be queued again.\nEdit: As Daniel pointed out, you need to call gtk.gdk.threads_init() anywhere in your program first.\n",
"As stated in the previous answers, GTK is not \"thread safe,\" but it is \"thread-aware\" - see this page on Threads: https://developer.gnome.org/gdk2/stable/gdk2-Threads.html\nIn order to modify GTK widgets from another thread you have to use GTK's locking. Call gtk.threads_init() immediately after importing the gtk module, and then you can update like so:\ngtk.threads_enter()\n# make changes...\ngtk.threads_leave()\n\nNote that the above will not work on Windows (see the link above). On Windows you must use gobject.idle_add() as explained above, though don't forget to put gobject.threads_init() directly after importing gobject in your code! The idle_add() function will execute the update itself in the main thread (the thread running gtk.main()).\n"
] | [
15,
2
] | [
"the same may be achieved using gobject.idle_add method whose syntax is same as above,you have to import the module gobject\n",
"What Johannes said is correct, however since GTK is a wrapper for the glib and gobject things, you would actually want to use gtk.idle_add(). No need for the unnecessary imports.\n"
] | [
-1,
-1
] | [
"multithreading",
"pygtk",
"python"
] | stackoverflow_0002066767_multithreading_pygtk_python.txt |
Q:
PyQt WebKit CSS background image not showing
I'm making a Twitter client with PyQt, which uses WebKit to draw the tweet list. Now I'm trying to use CSS to set a background image in the WebKit widget - but the image won't show up. This is the relevant part of the CSS:
body
{
background-image: url("gradient2.jpg");
}
The file name is correctly spelled, and it is located in the same directory as the Python program, which is also where I start the program from (so the image file should be in PWD).
To check if WebKit somehow looks for the image in the wrong directory anyway, I ran my program through strace, which creates a log of all system calls made by the program. And surprisingly, the name of the image does not appear in the log - so it seems as if WebKit doesn't even try to find it.
To verify that my CSS is used at all by WebKit, I tried changing it to a solid background color instead of an image:
body
{
background: #CCFFCC;
}
And that works. So I know that the CSS is used, that's not the problem.
Could it be that WebKit refuses to use "ordinary" files in the filesystem, and that I somehow have to create some sort of "resource" file containing my image in Qt Designer?
A:
Try removing the quotes. Also, bear in mind that if you declare a "background:" shorthand rule after a "backround-image:" rule, the background-image will be overwritten. Also, the file path should be relative to the css file, not the source file.
A:
you could use the background-image like this:
body
{
background-image: url("qrc:///gradient2.jpg");
}
| PyQt WebKit CSS background image not showing | I'm making a Twitter client with PyQt, which uses WebKit to draw the tweet list. Now I'm trying to use CSS to set a background image in the WebKit widget - but the image won't show up. This is the relevant part of the CSS:
body
{
background-image: url("gradient2.jpg");
}
The file name is correctly spelled, and it is located in the same directory as the Python program, which is also where I start the program from (so the image file should be in PWD).
To check if WebKit somehow looks for the image in the wrong directory anyway, I ran my program through strace, which creates a log of all system calls made by the program. And surprisingly, the name of the image does not appear in the log - so it seems as if WebKit doesn't even try to find it.
To verify that my CSS is used at all by WebKit, I tried changing it to a solid background color instead of an image:
body
{
background: #CCFFCC;
}
And that works. So I know that the CSS is used, that's not the problem.
Could it be that WebKit refuses to use "ordinary" files in the filesystem, and that I somehow have to create some sort of "resource" file containing my image in Qt Designer?
| [
"Try removing the quotes. Also, bear in mind that if you declare a \"background:\" shorthand rule after a \"backround-image:\" rule, the background-image will be overwritten. Also, the file path should be relative to the css file, not the source file.\n",
"you could use the background-image like this:\nbody \n{ \n background-image: url(\"qrc:///gradient2.jpg\"); \n}\n\n"
] | [
2,
0
] | [] | [] | [
"css",
"pyqt",
"python",
"webkit"
] | stackoverflow_0002602880_css_pyqt_python_webkit.txt |
Q:
AttributeError HELP!
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
a = Account(1000.00)
a.deposit(550.23)
a.deposit(100)
a.withdraw(50)
print a.getbalance()
I get this error when I run this code.. AttributeError: Account instance has no attribute 'deposit'
A:
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
The way you defined them, they were local to the __init__ method, and thus useless.
A:
You've indented them too deep. They're inner functions of the __init__() method.
A:
So what the above answers mean is that instead your code should be like this - remember unlike other languages, indentation is serious business in Python:
class Account(object):
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance += amt
def withdraw(self, amt):
self.balance -= amt
def getbalance(self):
return self.balance
a = Account(1000.00)
a.deposit(550.23)
a.deposit(100)
a.withdraw(50)
print a.getbalance()
and now you'll get 1600.23 instead of an error.
A:
In addition to what others have remarked:
You have not correctly shown the code that you actually ran. What appears here has the def __init__ ... at the same level as the class statement; this would have caused a (compile time) SyntaxError, not a (run time) AttributeError.
| AttributeError HELP! | class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
a = Account(1000.00)
a.deposit(550.23)
a.deposit(100)
a.withdraw(50)
print a.getbalance()
I get this error when I run this code.. AttributeError: Account instance has no attribute 'deposit'
| [
"class Account:\n def __init__(self, initial):\n self.balance = initial\n def deposit(self, amt):\n self.balance = self.balance + amt\n def withdraw(self,amt):\n self.balance = self.balance - amt\n def getbalance(self):\n return self.balance\n\nThe way you defined them, they were local to the __init__ method, and thus useless.\n",
"You've indented them too deep. They're inner functions of the __init__() method.\n",
"So what the above answers mean is that instead your code should be like this - remember unlike other languages, indentation is serious business in Python:\nclass Account(object):\n\n def __init__(self, initial):\n self.balance = initial\n\n def deposit(self, amt):\n self.balance += amt\n\n def withdraw(self, amt):\n self.balance -= amt\n\n def getbalance(self):\n return self.balance\n\na = Account(1000.00)\na.deposit(550.23)\na.deposit(100)\na.withdraw(50)\n\nprint a.getbalance()\n\nand now you'll get 1600.23 instead of an error.\n",
"In addition to what others have remarked:\nYou have not correctly shown the code that you actually ran. What appears here has the def __init__ ... at the same level as the class statement; this would have caused a (compile time) SyntaxError, not a (run time) AttributeError.\n"
] | [
5,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003027048_python.txt |
Q:
why does text from socket server erase previously written text?
This is strange enough I'm not sure how to search for an answer. I have a program in Python that communicates via TCP/IP sockets to a telnet-based server. If I telnet in manually and type commands like this:
SET MDI G0 X0 Y0
the server will spit back a line like this:
SET MDI ACK
Pretty standard stuff. Here's the weird part. If, in my code, I precede my printing of each of these lines with some text, the returned line erases what I'm trying to print before it. So for example, if I write the code so it should look like this:
SENT: SET MDI G0 X0 Y0
READ: SET MDI ACK
What I get instead is:
SENT: SET MDI G0 X0 Y0
SET MDI ACK
Now, if I make the "READ: " text a bit longer, I can get a better idea of what's happening. Let's say I change READ: to 12345678901234567890, so that it should read as:
12345678901234567890: SET MDI ACK
What I get instead is:
SET MDI ACK234567890:
So it seems like whatever text I'm getting back from the server is somehow deleting what I'm trying to precede it with. I tried saving all of my saved lines in a list, and then printing them out at the end, but it does exactly the same thing.
Any ideas on what's going on, or even on how to debug this? Is there a way to get Python to show me any hidden chars in a string, for example?
thx!
A:
If you print repr(send) and repr(received) instead of just printing sent and received, you'll have a much clearer idea about exactly what you're sending and what you're getting back in return (so you can check if @theatrus' suggestion is correct, etc, etc, and at all times clearly see what you're doing).
This is close to one of my favorite pragmatical principles: whenever printing or logging a string that might possibly be in error, always print its repr (or %r instead of %s, if that's how you're doing the formatting), never just the plain string itself (or its %s, which does nothing to it).
Over and over again, if you don't use the repr, you'll waste substantial amounts of time debugging problems that you can't really see because the characters that snuck into the string by mistake and are therefore causing said problems aren't showing clearly in the logs (non-printing characters, control characters, and so on).
So, always use repr to display or log strings unless you're 100% certain that they are perfectly correct and predictable -- get into the habit, it isn't any harder than not doing it once you are in the habit, and over the years you will have many occasions to thank this little, simple principle.
A:
You probably have a stray carriage return without a newline. Try using raw strings in Python instead to see what's up.
A:
It is likely your telnet program is expecting CR-LF delineated new lines, and Python is doing on LF or CR feeds.
| why does text from socket server erase previously written text? | This is strange enough I'm not sure how to search for an answer. I have a program in Python that communicates via TCP/IP sockets to a telnet-based server. If I telnet in manually and type commands like this:
SET MDI G0 X0 Y0
the server will spit back a line like this:
SET MDI ACK
Pretty standard stuff. Here's the weird part. If, in my code, I precede my printing of each of these lines with some text, the returned line erases what I'm trying to print before it. So for example, if I write the code so it should look like this:
SENT: SET MDI G0 X0 Y0
READ: SET MDI ACK
What I get instead is:
SENT: SET MDI G0 X0 Y0
SET MDI ACK
Now, if I make the "READ: " text a bit longer, I can get a better idea of what's happening. Let's say I change READ: to 12345678901234567890, so that it should read as:
12345678901234567890: SET MDI ACK
What I get instead is:
SET MDI ACK234567890:
So it seems like whatever text I'm getting back from the server is somehow deleting what I'm trying to precede it with. I tried saving all of my saved lines in a list, and then printing them out at the end, but it does exactly the same thing.
Any ideas on what's going on, or even on how to debug this? Is there a way to get Python to show me any hidden chars in a string, for example?
thx!
| [
"If you print repr(send) and repr(received) instead of just printing sent and received, you'll have a much clearer idea about exactly what you're sending and what you're getting back in return (so you can check if @theatrus' suggestion is correct, etc, etc, and at all times clearly see what you're doing).\nThis is close to one of my favorite pragmatical principles: whenever printing or logging a string that might possibly be in error, always print its repr (or %r instead of %s, if that's how you're doing the formatting), never just the plain string itself (or its %s, which does nothing to it).\nOver and over again, if you don't use the repr, you'll waste substantial amounts of time debugging problems that you can't really see because the characters that snuck into the string by mistake and are therefore causing said problems aren't showing clearly in the logs (non-printing characters, control characters, and so on).\nSo, always use repr to display or log strings unless you're 100% certain that they are perfectly correct and predictable -- get into the habit, it isn't any harder than not doing it once you are in the habit, and over the years you will have many occasions to thank this little, simple principle.\n",
"You probably have a stray carriage return without a newline. Try using raw strings in Python instead to see what's up.\n",
"It is likely your telnet program is expecting CR-LF delineated new lines, and Python is doing on LF or CR feeds.\n"
] | [
3,
2,
1
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003030634_python_sockets.txt |
Q:
Is it possible to read path in JPEG image with python?
If you Save as > jpg in Adobe Photoshop a path (selection) is stored in the file.
Is it possible to read that path in python, for example to create a composition with PIL?
EDIT
Imagemagick seems to help, example
A:
This code (by /F AKA the effbot, author of PIL and generally wondrous Python contributor) shows how to walk through the 8BIM resource blocks (but it's looking for 0x0404, the IPTC/NAA data, so of course you'll need to edit it).
Per Tom Ruark's post to this thread, paths will have IDs of 2000 to 2999 (the latter gives the name of the clipping path, so it's different from the others) and the data's a series of 26-bytes "point records" (so the resource length is always a multiple of 26).
Read the rest in Tom's post in all the gory details -- it's a pesky and very detailed binary format that will take substantial experimentation (and skill with struct, bitwise manipulation, etc) to read and interpret just right (not helped by the fact that the fields can be big-endian or little-endian -- little-endian in Windows, if I read the post correctly).
A:
Are you sure the path is stored in the jpg? That seems unlikely. Paths would be stored in native photoshop format, but not the jpg.
Do you know of any other tools that can read the path? Can you try saving the item as a jpg, close photoshop, reopen only the jpg and see if you still have the path? I doubt it'd be there.
| Is it possible to read path in JPEG image with python? | If you Save as > jpg in Adobe Photoshop a path (selection) is stored in the file.
Is it possible to read that path in python, for example to create a composition with PIL?
EDIT
Imagemagick seems to help, example
| [
"This code (by /F AKA the effbot, author of PIL and generally wondrous Python contributor) shows how to walk through the 8BIM resource blocks (but it's looking for 0x0404, the IPTC/NAA data, so of course you'll need to edit it).\nPer Tom Ruark's post to this thread, paths will have IDs of 2000 to 2999 (the latter gives the name of the clipping path, so it's different from the others) and the data's a series of 26-bytes \"point records\" (so the resource length is always a multiple of 26).\nRead the rest in Tom's post in all the gory details -- it's a pesky and very detailed binary format that will take substantial experimentation (and skill with struct, bitwise manipulation, etc) to read and interpret just right (not helped by the fact that the fields can be big-endian or little-endian -- little-endian in Windows, if I read the post correctly).\n",
"Are you sure the path is stored in the jpg? That seems unlikely. Paths would be stored in native photoshop format, but not the jpg.\nDo you know of any other tools that can read the path? Can you try saving the item as a jpg, close photoshop, reopen only the jpg and see if you still have the path? I doubt it'd be there.\n"
] | [
1,
0
] | [] | [] | [
"image",
"jpeg",
"python"
] | stackoverflow_0003030577_image_jpeg_python.txt |
Q:
Finding the nth number of primes
I can not figure out why this won't work. Please help me
from math import sqrt
pN = 0
numPrimes = 0
num = 1
def checkPrime(x):
'''Check\'s whether a number is a prime or not'''
prime = True
if(x==2):
prime = True
elif(x%2==0):
prime=False
else:
root=int(sqrt(x))
for i in range(3,root,2):
if(x%i==0):
prime=False
break
return prime
n = int(input("Find n number of primes. N being:"))
while( numPrimes != n ):
if( checkPrime( num ) == True ):
numPrimes += 1
pN = num
print("{0}: {1}".format(numPrimes,pN))
num += 1
print("Prime {0} is: {1}".format(n,pN))
A:
You need to change
root=int(sqrt(x))
into
root=int(sqrt(x))+1
(Take 9 for instance, int(sqrt(9)) is 3, and range(3, 3, 2) is [], and you do really want to test dividing by 3!).
Technically, 1 is not a prime either. Add
if(x<=1):
prime = False
and you'll get the same result as http://www.rsok.com/~jrm/first100primes.html
A:
Differently from what @Braxton says in a comment, the Sieve of Eratosthenes algorithm can easily be adapted to generate unbounded primes (e.g. as a potentially-infinite generator, which can then be curtailed as desired e.g. by itertools.slict).
See this recipe for an unbounded Sieve in Python (and be sure to apply the enhancements shown in the comments, including mine;-) or see the same recipe as finally edited for the printed Cookbook here (unfortunately the discussion part is curtailed in this google books hit, but at least the Solution's code is all there;-).
| Finding the nth number of primes | I can not figure out why this won't work. Please help me
from math import sqrt
pN = 0
numPrimes = 0
num = 1
def checkPrime(x):
'''Check\'s whether a number is a prime or not'''
prime = True
if(x==2):
prime = True
elif(x%2==0):
prime=False
else:
root=int(sqrt(x))
for i in range(3,root,2):
if(x%i==0):
prime=False
break
return prime
n = int(input("Find n number of primes. N being:"))
while( numPrimes != n ):
if( checkPrime( num ) == True ):
numPrimes += 1
pN = num
print("{0}: {1}".format(numPrimes,pN))
num += 1
print("Prime {0} is: {1}".format(n,pN))
| [
"You need to change\nroot=int(sqrt(x))\n\ninto\nroot=int(sqrt(x))+1\n\n(Take 9 for instance, int(sqrt(9)) is 3, and range(3, 3, 2) is [], and you do really want to test dividing by 3!).\nTechnically, 1 is not a prime either. Add\nif(x<=1):\n prime = False\n\nand you'll get the same result as http://www.rsok.com/~jrm/first100primes.html\n",
"Differently from what @Braxton says in a comment, the Sieve of Eratosthenes algorithm can easily be adapted to generate unbounded primes (e.g. as a potentially-infinite generator, which can then be curtailed as desired e.g. by itertools.slict).\nSee this recipe for an unbounded Sieve in Python (and be sure to apply the enhancements shown in the comments, including mine;-) or see the same recipe as finally edited for the printed Cookbook here (unfortunately the discussion part is curtailed in this google books hit, but at least the Solution's code is all there;-).\n"
] | [
5,
1
] | [] | [] | [
"computer_science",
"math",
"primes",
"python"
] | stackoverflow_0003030226_computer_science_math_primes_python.txt |
Q:
how to detect an escape sequence in a string
Given a string named line whose raw version has this value:
\rRAWSTRING
how can I detect if it has the escape character \r? What I've tried is:
if repr(line).startswith('\r'):
blah...
but it doesn't catch it. I also tried find, such as:
if repr(line).find('\r') != -1:
blah
doesn't work either. What am I missing?
thx!
EDIT:
thanks for all the replies and the corrections re terminolgy and sorry for the confusion.
OK, if i do this
print repr(line)
then what it prints is:
'\rSET ENABLE ACK\n'
(including the single quotes). i have tried all the suggestions, including:
line.startswith(r'\r')
line.startswith('\\r')
each of which returns False. also tried:
line.find(r'\r')
line.find('\\r')
each of which returns -1
A:
If:
print repr(line)
Returns:
'\rSET ENABLE ACK\n'
Then:
line.find('\r')
line.startswith('\r')
'\r' in line
are what you are looking for. Example:
>>> line = '\rSET ENABLE ACK\n'
>>> print repr(line)
'\rSET ENABLE ACK\n'
>>> line.find('\r')
0
>>> line.startswith('\r')
True
>>> '\r' in line
True
repr() returns a display string. It actually contains the quotes and backslashes you see when you print the line:
>>> print line
SET ENABLE ACK
>>> print repr(line)
'\rSET ENABLE ACK\n'
>>> print len(line)
16
>>> print len(repr(line))
20
A:
Dude, seems you have tried everything but the simplest thing, lines.startswith('\r'):
>>> line = '\rSET ENABLE ACK\n'
>>> line.startswith('\r')
True
>>> '\rSET ENABLE ACK\n'.startswith('\r')
True
For now, just hold on on using repr(), \r and r'string' and go with the simplest thing to avoid confusion.
A:
You can try either:
if repr(line).startswith(r'\r'):
or
if line.startswith('\r'):
The latter is better: it seems like you are using repr only to get at the escaped character.
A:
It's not entirely clear what you're asking. You speak of a string, but also a "raw version", and your string contains "RAWSTRING", which seems to imply you are talking about raw strings.
None of these are quite the same thing.
If you have an ordinary string with the character represented by '\r' in it, then you can use any ordinary means to match:
>>> "\rastring".find('\r')
0
>>>
If you defined an actual "raw string", that won't work because what you put in was not the '\r' character, but the two characters '\' and 'r':
>>> r"\rastring".find('\r')
-1
>>>
In this case, or in the case of an ordinary string that happens to have the characters '\' and 'r', and you want to find those two characters, you'll need to search using a raw string:
>>> r"\rastring".find(r'\r')
0
>>>
Or you can search for the sequence by escaping the backslash itself:
>>> r"\rastring".find('\\r')
0
>>>
A:
if '\r' in line:
If that isn't what you mean, tell us PRECISELY what is in line. Do this:
print repr(line)
and copy/past the result into a edit of your question.
Re your subject: backslash is an escape character, "\r" is an escaped character.
A:
Simplest:
>>> s = r'\rRAWSTRING'
>>> s.startswith(r'\r')
True
Unless I badly misunderstand what you're saying, you need to look for r'\r' (or, equivalently but perhaps a tad less readably, '\\r'), the escape sequence, not for '\r', the carriage return character itself.
| how to detect an escape sequence in a string | Given a string named line whose raw version has this value:
\rRAWSTRING
how can I detect if it has the escape character \r? What I've tried is:
if repr(line).startswith('\r'):
blah...
but it doesn't catch it. I also tried find, such as:
if repr(line).find('\r') != -1:
blah
doesn't work either. What am I missing?
thx!
EDIT:
thanks for all the replies and the corrections re terminolgy and sorry for the confusion.
OK, if i do this
print repr(line)
then what it prints is:
'\rSET ENABLE ACK\n'
(including the single quotes). i have tried all the suggestions, including:
line.startswith(r'\r')
line.startswith('\\r')
each of which returns False. also tried:
line.find(r'\r')
line.find('\\r')
each of which returns -1
| [
"If:\nprint repr(line)\n\nReturns:\n'\\rSET ENABLE ACK\\n'\n\nThen:\nline.find('\\r')\nline.startswith('\\r')\n'\\r' in line\n\nare what you are looking for. Example:\n>>> line = '\\rSET ENABLE ACK\\n'\n>>> print repr(line)\n'\\rSET ENABLE ACK\\n'\n>>> line.find('\\r')\n0\n>>> line.startswith('\\r')\nTrue\n>>> '\\r' in line\nTrue\n\nrepr() returns a display string. It actually contains the quotes and backslashes you see when you print the line:\n>>> print line\nSET ENABLE ACK\n\n>>> print repr(line)\n'\\rSET ENABLE ACK\\n'\n>>> print len(line)\n16\n>>> print len(repr(line))\n20\n\n",
"Dude, seems you have tried everything but the simplest thing, lines.startswith('\\r'):\n>>> line = '\\rSET ENABLE ACK\\n'\n>>> line.startswith('\\r')\nTrue\n>>> '\\rSET ENABLE ACK\\n'.startswith('\\r')\nTrue\n\nFor now, just hold on on using repr(), \\r and r'string' and go with the simplest thing to avoid confusion.\n",
"You can try either:\nif repr(line).startswith(r'\\r'):\n\nor\nif line.startswith('\\r'):\n\nThe latter is better: it seems like you are using repr only to get at the escaped character.\n",
"It's not entirely clear what you're asking. You speak of a string, but also a \"raw version\", and your string contains \"RAWSTRING\", which seems to imply you are talking about raw strings.\nNone of these are quite the same thing.\nIf you have an ordinary string with the character represented by '\\r' in it, then you can use any ordinary means to match:\n>>> \"\\rastring\".find('\\r')\n0\n>>> \n\nIf you defined an actual \"raw string\", that won't work because what you put in was not the '\\r' character, but the two characters '\\' and 'r':\n>>> r\"\\rastring\".find('\\r')\n-1\n>>>\n\nIn this case, or in the case of an ordinary string that happens to have the characters '\\' and 'r', and you want to find those two characters, you'll need to search using a raw string:\n>>> r\"\\rastring\".find(r'\\r')\n0\n>>> \n\nOr you can search for the sequence by escaping the backslash itself:\n>>> r\"\\rastring\".find('\\\\r')\n0\n>>> \n\n",
"if '\\r' in line:\n\nIf that isn't what you mean, tell us PRECISELY what is in line. Do this:\nprint repr(line)\n\nand copy/past the result into a edit of your question.\nRe your subject: backslash is an escape character, \"\\r\" is an escaped character.\n",
"Simplest:\n>>> s = r'\\rRAWSTRING'\n>>> s.startswith(r'\\r')\nTrue\n\nUnless I badly misunderstand what you're saying, you need to look for r'\\r' (or, equivalently but perhaps a tad less readably, '\\\\r'), the escape sequence, not for '\\r', the carriage return character itself.\n"
] | [
4,
2,
1,
0,
0,
0
] | [] | [] | [
"escaping",
"parsing",
"python",
"string"
] | stackoverflow_0003030789_escaping_parsing_python_string.txt |
Q:
Serve external template in Django
I want to do something like
return render_to_response("http://docs.google.com/View?id=bla", args)
and serve an external page with django arguments. Django doesn't like this (it looks for templates in very particular places).
What's the easiest way make this work? Right now I'm thinking to use urllib to save the page to somewhere locally on my server and then serve with the templates pointing to there.
Note: I'm not looking for anything particularly scalable here, I realize my proposal above is a little dirty.
A:
Read the template in as a string and render it yourself.
| Serve external template in Django | I want to do something like
return render_to_response("http://docs.google.com/View?id=bla", args)
and serve an external page with django arguments. Django doesn't like this (it looks for templates in very particular places).
What's the easiest way make this work? Right now I'm thinking to use urllib to save the page to somewhere locally on my server and then serve with the templates pointing to there.
Note: I'm not looking for anything particularly scalable here, I realize my proposal above is a little dirty.
| [
"Read the template in as a string and render it yourself.\n"
] | [
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003031056_django_django_templates_python.txt |
Q:
word ladder in python
I'm trying to create a word ladder program in python. I'd like to generate words that are similar to a given word. In c++ or java, I would go through each valid index in the original string, and replace it with each letter in the english alphabet, and see if the result is a valid word. for example (pseudocode)
for (int i = 0; i < word.length(); i++) {
for (every character c in the alphabet) {
change the letter of word at index i to be c.
if the result is a valid word, store it in a list of similar words
}
}
.
However, this doesn't seem like a very "python" way of doing things. How would I approach this problem in python?
A:
A generator of similar words (taking a predicate, i.e. a function argument which returns true or false, to check whether a word is valid) seems a reasonable first step:
import string
def allsimilar(word, valid):
wl = list(word)
for i, c in enumerate(wl):
for x in string.ascii_lowercase:
if x == c: continue
wl[i] = x
nw = ''.join(wl)
if valid(nw): yield nw
wl[i] = c
If you want the list, list(allsimilar(word, valid)) will of course build it for you.
Alternatively, you could omit wl and build the new word directly as
nw = word[:i] + x + word[i+1:]
but, without having timed it carefully, I suspect that might be slower.
One small possible optimization would be to also import array and then use
wl = array.array('c', word)
instead of list(word).
| word ladder in python | I'm trying to create a word ladder program in python. I'd like to generate words that are similar to a given word. In c++ or java, I would go through each valid index in the original string, and replace it with each letter in the english alphabet, and see if the result is a valid word. for example (pseudocode)
for (int i = 0; i < word.length(); i++) {
for (every character c in the alphabet) {
change the letter of word at index i to be c.
if the result is a valid word, store it in a list of similar words
}
}
.
However, this doesn't seem like a very "python" way of doing things. How would I approach this problem in python?
| [
"A generator of similar words (taking a predicate, i.e. a function argument which returns true or false, to check whether a word is valid) seems a reasonable first step:\nimport string\n\ndef allsimilar(word, valid):\n wl = list(word)\n for i, c in enumerate(wl):\n for x in string.ascii_lowercase:\n if x == c: continue\n wl[i] = x\n nw = ''.join(wl)\n if valid(nw): yield nw\n wl[i] = c\n\nIf you want the list, list(allsimilar(word, valid)) will of course build it for you.\nAlternatively, you could omit wl and build the new word directly as\nnw = word[:i] + x + word[i+1:]\n\nbut, without having timed it carefully, I suspect that might be slower.\nOne small possible optimization would be to also import array and then use\n wl = array.array('c', word)\n\ninstead of list(word).\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003031094_python.txt |
Q:
Python - Bitmap won't draw/display on button
I have been working on this project for some time now - it was originally supposed to be a test to see if, using wxPython, I could build a button 'from scratch.' From scratch means: that i would have full control over all the aspects of the button (i.e. controlling the BMP's that are displayed... what the event handlers did... etc.)
I have run into several problems (as this is my first major python project.) Now, when the all the code is working for the life of me I can't get an image to display.
Basic code - not working
dc = wx.BufferedPaintDC(self)
dc.SetFont(self.GetFont())
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
dc.DrawBitmap(wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"), 100, 100)
self.Refresh()
self.Update()
Full Main.py
import wx
from Custom_Button import Custom_Button
from wxPython.wx import *
ID_ABOUT = 101
ID_EXIT = 102
class MyFrame(wx.Frame):
def __init__(self, parent, ID, title):
wxFrame.__init__(self, parent, ID, title,
wxDefaultPosition, wxSize(400, 400))
self.CreateStatusBar()
self.SetStatusText("Program testing custom button overlays")
menu = wxMenu()
menu.Append(ID_ABOUT, "&About", "More information about this program")
menu.AppendSeparator()
menu.Append(ID_EXIT, "E&xit", "Terminate the program")
menuBar = wxMenuBar()
menuBar.Append(menu, "&File");
self.SetMenuBar(menuBar)
# The call for the 'Experiential button'
self.Button1 = Custom_Button(parent, -1,
wx.Point(100, 100),
wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"),
wx.Bitmap("/home/wallter/Desktop/Normal.bmp"),
wx.Bitmap("/home/wallter/Desktop/Click.bmp"))
# The following three lines of code are in place to try to get the
# Button1 to display (trying to trigger the Paint event (the _onPaint.)
# Because that is where the 'draw' functions are.
self.Button1.Show(true)
self.Refresh()
self.Update()
# Because the Above three lines of code did not work, I added the
# following four lines to trigger the 'draw' functions to test if the
# '_onPaint' method actually worked.
# These lines do not work.
dc = wx.BufferedPaintDC(self)
dc.SetFont(self.GetFont())
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.DrawBitmap(wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"), 100, 100)
EVT_MENU(self, ID_ABOUT, self.OnAbout)
EVT_MENU(self, ID_EXIT, self.TimeToQuit)
def OnAbout(self, event):
dlg = wxMessageDialog(self, "Testing the functions of custom "
"buttons using pyDev and wxPython",
"About", wxOK | wxICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def TimeToQuit(self, event):
self.Close(true)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(NULL, -1, "wxPython | Buttons")
frame.Show(true)
self.SetTopWindow(frame)
return true
app = MyApp(0)
app.MainLoop()
Full CustomButton.py
import wx
from wxPython.wx import *
class Custom_Button(wx.PyControl):
def __init__(self, parent, id, Pos, Over_BMP, Norm_BMP, Push_BMP, **kwargs):
wx.PyControl.__init__(self,parent, id, **kwargs)
self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown)
self.Bind(wx.EVT_LEFT_UP, self._onMouseUp)
self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave)
self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter)
self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground)
self.Bind(wx.EVT_PAINT,self._onPaint)
self.pos = Pos
self.Over_bmp = Over_BMP
self.Norm_bmp = Norm_BMP
self.Push_bmp = Push_BMP
self._mouseIn = False
self._mouseDown = False
def _onMouseEnter(self, event):
self._mouseIn = True
def _onMouseLeave(self, event):
self._mouseIn = False
def _onMouseDown(self, event):
self._mouseDown = True
def _onMouseUp(self, event):
self._mouseDown = False
self.sendButtonEvent()
def sendButtonEvent(self):
event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())
event.SetInt(0)
event.SetEventObject(self)
self.GetEventHandler().ProcessEvent(event)
def _onEraseBackground(self,event):
# reduce flicker
pass
def Iz(self):
dc = wx.BufferedPaintDC(self)
dc.DrawBitmap(self.Norm_bmp, 100, 100)
def _onPaint(self, event):
# The printing functions, they should work... but don't.
dc = wx.BufferedPaintDC(self)
dc.SetFont(self.GetFont())
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
dc.DrawBitmap(self.Norm_bmp)
# This never printed... I don't know if that means if the EVT
# is triggering or what.
print '_onPaint'
# draw whatever you want to draw
# draw glossy bitmaps e.g. dc.DrawBitmap
if self._mouseIn: # If the Mouse is over the button
dc.DrawBitmap(self.Over_bmp, self.pos)
else: # Since the mouse isn't over it Print the normal one
# This is adding on the above code to draw the bmp
# in an attempt to get the bmp to display; to no avail.
dc.DrawBitmap(self.Norm_bmp, self.pos)
if self._mouseDown: # If the Mouse clicks the button
dc.DrawBitmap(self.Push_bmp, self.pos)
This code won't work? I get no BMP displayed why? How do i get one? I've gotten the staticBitmap(...) to display one, but it won't move, resize, or anything for that matter... - it's only in the top left corner of the frame?
Note: the frame is 400pxl X 400pxl - and the "/home/wallter/Desktop/Mouseover.bmp"
A:
Are your sure you code is working without exceptions because when I run it i get many errors, read the points below and you should have a button which at least draws correctly
When O run it it gives error because Custom_Button is passed NULL parent instead pass frame e.g. Custom_Button(self, ...)
Your drawBitmap call is also wrong, it throws exception, instead of dc.DrawBitmap(self.Norm_bmp) it should be dc.DrawBitmap(self.Norm_bmp, 0, 0)
dc.DrawBitmap(self.Over_bmp, self.pos) also throws error as pos should be x,y not a tuple so instead do dc.DrawBitmap(self.Over_bmp, *self.pos)
and lastly you do not need to do "from wxPython.wx import *" instead just do "from wx import *" and instead of wxXXX class names use wx.XXX, instead of true use True etc
here is my working code
from wx import *
ID_ABOUT = 101
ID_EXIT = 102
class Custom_Button(wx.PyControl):
def __init__(self, parent, id, Pos, Over_BMP, Norm_BMP, Push_BMP, **kwargs):
wx.PyControl.__init__(self,parent, id, **kwargs)
self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown)
self.Bind(wx.EVT_LEFT_UP, self._onMouseUp)
self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave)
self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter)
self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground)
self.Bind(wx.EVT_PAINT,self._onPaint)
self.pos = Pos
self.Over_bmp = Over_BMP
self.Norm_bmp = Norm_BMP
self.Push_bmp = Push_BMP
self._mouseIn = False
self._mouseDown = False
def _onMouseEnter(self, event):
self._mouseIn = True
def _onMouseLeave(self, event):
self._mouseIn = False
def _onMouseDown(self, event):
self._mouseDown = True
def _onMouseUp(self, event):
self._mouseDown = False
self.sendButtonEvent()
def sendButtonEvent(self):
event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())
event.SetInt(0)
event.SetEventObject(self)
self.GetEventHandler().ProcessEvent(event)
def _onEraseBackground(self,event):
# reduce flicker
pass
def Iz(self):
dc = wx.BufferedPaintDC(self)
dc.DrawBitmap(self.Norm_bmp, 100, 100)
def _onPaint(self, event):
# The printing functions, they should work... but don't.
dc = wx.BufferedPaintDC(self)
dc.SetFont(self.GetFont())
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
dc.DrawBitmap(self.Norm_bmp, 0, 0)
# This never printed... I don't know if that means if the EVT
# is triggering or what.
print '_onPaint'
# draw whatever you want to draw
# draw glossy bitmaps e.g. dc.DrawBitmap
if self._mouseIn: # If the Mouse is over the button
dc.DrawBitmap(self.Over_bmp, *self.pos)
else: # Since the mouse isn't over it Print the normal one
# This is adding on the above code to draw the bmp
# in an attempt to get the bmp to display; to no avail.
dc.DrawBitmap(self.Norm_bmp, *self.pos)
if self._mouseDown: # If the Mouse clicks the button
dc.DrawBitmap(self.Push_bmp, *self.pos)
class MyFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title,
wx.DefaultPosition, wx.Size(400, 400))
self.CreateStatusBar()
self.SetStatusText("Program testing custom button overlays")
menu = wx.Menu()
menu.Append(ID_ABOUT, "&About", "More information about this program")
menu.AppendSeparator()
menu.Append(ID_EXIT, "E&xit", "Terminate the program")
menuBar = wx.MenuBar()
menuBar.Append(menu, "&File");
self.SetMenuBar(menuBar)
# The call for the 'Experiential button'
s = r"D:\virtual_pc\mockup\mockupscreens\embed_images\toolbar\options.png"
self.Button1 = Custom_Button(self, -1,
wx.Point(100, 100),
wx.Bitmap(s),
wx.Bitmap(s),
wx.Bitmap(s))
self.Button1.Show(True)
EVT_MENU(self, ID_ABOUT, self.OnAbout)
EVT_MENU(self, ID_EXIT, self.TimeToQuit)
def OnAbout(self, event):
dlg = wxMessageDialog(self, "Testing the functions of custom "
"buttons using pyDev and wxPython",
"About", wxOK | wxICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def TimeToQuit(self, event):
self.Close(true)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, "wxPython | Buttons")
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
| Python - Bitmap won't draw/display on button | I have been working on this project for some time now - it was originally supposed to be a test to see if, using wxPython, I could build a button 'from scratch.' From scratch means: that i would have full control over all the aspects of the button (i.e. controlling the BMP's that are displayed... what the event handlers did... etc.)
I have run into several problems (as this is my first major python project.) Now, when the all the code is working for the life of me I can't get an image to display.
Basic code - not working
dc = wx.BufferedPaintDC(self)
dc.SetFont(self.GetFont())
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
dc.DrawBitmap(wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"), 100, 100)
self.Refresh()
self.Update()
Full Main.py
import wx
from Custom_Button import Custom_Button
from wxPython.wx import *
ID_ABOUT = 101
ID_EXIT = 102
class MyFrame(wx.Frame):
def __init__(self, parent, ID, title):
wxFrame.__init__(self, parent, ID, title,
wxDefaultPosition, wxSize(400, 400))
self.CreateStatusBar()
self.SetStatusText("Program testing custom button overlays")
menu = wxMenu()
menu.Append(ID_ABOUT, "&About", "More information about this program")
menu.AppendSeparator()
menu.Append(ID_EXIT, "E&xit", "Terminate the program")
menuBar = wxMenuBar()
menuBar.Append(menu, "&File");
self.SetMenuBar(menuBar)
# The call for the 'Experiential button'
self.Button1 = Custom_Button(parent, -1,
wx.Point(100, 100),
wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"),
wx.Bitmap("/home/wallter/Desktop/Normal.bmp"),
wx.Bitmap("/home/wallter/Desktop/Click.bmp"))
# The following three lines of code are in place to try to get the
# Button1 to display (trying to trigger the Paint event (the _onPaint.)
# Because that is where the 'draw' functions are.
self.Button1.Show(true)
self.Refresh()
self.Update()
# Because the Above three lines of code did not work, I added the
# following four lines to trigger the 'draw' functions to test if the
# '_onPaint' method actually worked.
# These lines do not work.
dc = wx.BufferedPaintDC(self)
dc.SetFont(self.GetFont())
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.DrawBitmap(wx.Bitmap("/home/wallter/Desktop/Mouseover.bmp"), 100, 100)
EVT_MENU(self, ID_ABOUT, self.OnAbout)
EVT_MENU(self, ID_EXIT, self.TimeToQuit)
def OnAbout(self, event):
dlg = wxMessageDialog(self, "Testing the functions of custom "
"buttons using pyDev and wxPython",
"About", wxOK | wxICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def TimeToQuit(self, event):
self.Close(true)
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(NULL, -1, "wxPython | Buttons")
frame.Show(true)
self.SetTopWindow(frame)
return true
app = MyApp(0)
app.MainLoop()
Full CustomButton.py
import wx
from wxPython.wx import *
class Custom_Button(wx.PyControl):
def __init__(self, parent, id, Pos, Over_BMP, Norm_BMP, Push_BMP, **kwargs):
wx.PyControl.__init__(self,parent, id, **kwargs)
self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown)
self.Bind(wx.EVT_LEFT_UP, self._onMouseUp)
self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave)
self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter)
self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground)
self.Bind(wx.EVT_PAINT,self._onPaint)
self.pos = Pos
self.Over_bmp = Over_BMP
self.Norm_bmp = Norm_BMP
self.Push_bmp = Push_BMP
self._mouseIn = False
self._mouseDown = False
def _onMouseEnter(self, event):
self._mouseIn = True
def _onMouseLeave(self, event):
self._mouseIn = False
def _onMouseDown(self, event):
self._mouseDown = True
def _onMouseUp(self, event):
self._mouseDown = False
self.sendButtonEvent()
def sendButtonEvent(self):
event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())
event.SetInt(0)
event.SetEventObject(self)
self.GetEventHandler().ProcessEvent(event)
def _onEraseBackground(self,event):
# reduce flicker
pass
def Iz(self):
dc = wx.BufferedPaintDC(self)
dc.DrawBitmap(self.Norm_bmp, 100, 100)
def _onPaint(self, event):
# The printing functions, they should work... but don't.
dc = wx.BufferedPaintDC(self)
dc.SetFont(self.GetFont())
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
dc.DrawBitmap(self.Norm_bmp)
# This never printed... I don't know if that means if the EVT
# is triggering or what.
print '_onPaint'
# draw whatever you want to draw
# draw glossy bitmaps e.g. dc.DrawBitmap
if self._mouseIn: # If the Mouse is over the button
dc.DrawBitmap(self.Over_bmp, self.pos)
else: # Since the mouse isn't over it Print the normal one
# This is adding on the above code to draw the bmp
# in an attempt to get the bmp to display; to no avail.
dc.DrawBitmap(self.Norm_bmp, self.pos)
if self._mouseDown: # If the Mouse clicks the button
dc.DrawBitmap(self.Push_bmp, self.pos)
This code won't work? I get no BMP displayed why? How do i get one? I've gotten the staticBitmap(...) to display one, but it won't move, resize, or anything for that matter... - it's only in the top left corner of the frame?
Note: the frame is 400pxl X 400pxl - and the "/home/wallter/Desktop/Mouseover.bmp"
| [
"Are your sure you code is working without exceptions because when I run it i get many errors, read the points below and you should have a button which at least draws correctly\n\nWhen O run it it gives error because Custom_Button is passed NULL parent instead pass frame e.g. Custom_Button(self, ...)\nYour drawBitmap call is also wrong, it throws exception, instead of dc.DrawBitmap(self.Norm_bmp) it should be dc.DrawBitmap(self.Norm_bmp, 0, 0)\ndc.DrawBitmap(self.Over_bmp, self.pos) also throws error as pos should be x,y not a tuple so instead do dc.DrawBitmap(self.Over_bmp, *self.pos)\nand lastly you do not need to do \"from wxPython.wx import *\" instead just do \"from wx import *\" and instead of wxXXX class names use wx.XXX, instead of true use True etc\n\nhere is my working code\nfrom wx import *\n\nID_ABOUT = 101\nID_EXIT = 102\n\n\nclass Custom_Button(wx.PyControl):\n\n def __init__(self, parent, id, Pos, Over_BMP, Norm_BMP, Push_BMP, **kwargs):\n wx.PyControl.__init__(self,parent, id, **kwargs)\n\n self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown)\n self.Bind(wx.EVT_LEFT_UP, self._onMouseUp)\n self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave)\n self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter)\n self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground)\n self.Bind(wx.EVT_PAINT,self._onPaint)\n\n self.pos = Pos\n\n self.Over_bmp = Over_BMP\n self.Norm_bmp = Norm_BMP\n self.Push_bmp = Push_BMP\n\n self._mouseIn = False\n self._mouseDown = False\n\n def _onMouseEnter(self, event):\n self._mouseIn = True\n\n def _onMouseLeave(self, event):\n self._mouseIn = False\n\n def _onMouseDown(self, event):\n self._mouseDown = True\n\n def _onMouseUp(self, event):\n self._mouseDown = False\n self.sendButtonEvent()\n\n def sendButtonEvent(self):\n event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId())\n event.SetInt(0)\n event.SetEventObject(self)\n self.GetEventHandler().ProcessEvent(event)\n\n def _onEraseBackground(self,event):\n # reduce flicker\n pass\n\n def Iz(self):\n dc = wx.BufferedPaintDC(self)\n dc.DrawBitmap(self.Norm_bmp, 100, 100)\n\n def _onPaint(self, event):\n # The printing functions, they should work... but don't.\n dc = wx.BufferedPaintDC(self)\n dc.SetFont(self.GetFont())\n dc.SetBackground(wx.Brush(self.GetBackgroundColour()))\n dc.Clear()\n dc.DrawBitmap(self.Norm_bmp, 0, 0)\n\n # This never printed... I don't know if that means if the EVT\n # is triggering or what.\n print '_onPaint'\n\n # draw whatever you want to draw\n # draw glossy bitmaps e.g. dc.DrawBitmap\n if self._mouseIn: # If the Mouse is over the button\n dc.DrawBitmap(self.Over_bmp, *self.pos)\n else: # Since the mouse isn't over it Print the normal one\n # This is adding on the above code to draw the bmp\n # in an attempt to get the bmp to display; to no avail.\n dc.DrawBitmap(self.Norm_bmp, *self.pos)\n if self._mouseDown: # If the Mouse clicks the button\n dc.DrawBitmap(self.Push_bmp, *self.pos)\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent, ID, title):\n wx.Frame.__init__(self, parent, ID, title,\n wx.DefaultPosition, wx.Size(400, 400))\n\n self.CreateStatusBar()\n self.SetStatusText(\"Program testing custom button overlays\")\n menu = wx.Menu()\n menu.Append(ID_ABOUT, \"&About\", \"More information about this program\")\n menu.AppendSeparator()\n menu.Append(ID_EXIT, \"E&xit\", \"Terminate the program\")\n menuBar = wx.MenuBar()\n menuBar.Append(menu, \"&File\");\n self.SetMenuBar(menuBar)\n\n # The call for the 'Experiential button' \n s = r\"D:\\virtual_pc\\mockup\\mockupscreens\\embed_images\\toolbar\\options.png\"\n self.Button1 = Custom_Button(self, -1, \n wx.Point(100, 100),\n wx.Bitmap(s),\n wx.Bitmap(s),\n wx.Bitmap(s))\n\n self.Button1.Show(True) \n\n EVT_MENU(self, ID_ABOUT, self.OnAbout)\n EVT_MENU(self, ID_EXIT, self.TimeToQuit)\n\n def OnAbout(self, event):\n dlg = wxMessageDialog(self, \"Testing the functions of custom \"\n \"buttons using pyDev and wxPython\",\n \"About\", wxOK | wxICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n\n def TimeToQuit(self, event):\n self.Close(true)\n\n\n\nclass MyApp(wx.App):\n def OnInit(self):\n frame = MyFrame(None, -1, \"wxPython | Buttons\")\n frame.Show(True)\n self.SetTopWindow(frame)\n return True\n\napp = MyApp(0)\napp.MainLoop()\n\n"
] | [
1
] | [] | [] | [
"custom_controls",
"python",
"wxpython"
] | stackoverflow_0003020704_custom_controls_python_wxpython.txt |
Q:
PGU HTML Renderer can't render most sites
I am trying to make a web browser using pygame. I am using PGU for html rendering. It works fine when I visit simple sites, like example.com, but when I try and load anything more complex that uses an html form, like google, I get this error:
UnboundLocalError: local variable 'e' referenced before assignment
I looked in the PGU html rendering file and found this code segment:
def start_input(self,attrs):
r = self.attrs_to_map(attrs)
params = self.map_to_params(r) #why bother
#params = {}
type_,name,value = r.get('type','text'),r.get('name',None),r.get('value',None)
f = self.form
if type_ == 'text':
e = gui.Input(**params)
self.map_to_connects(e,r)
self.item.add(e)
elif type_ == 'radio':
if name not in f.groups:
f.groups[name] = gui.Group(name=name)
g = f.groups[name]
del params['name']
e = gui.Radio(group=g,**params)
self.map_to_connects(e,r)
self.item.add(e)
if 'checked' in r: g.value = value
elif type_ == 'checkbox':
if name not in f.groups:
f.groups[name] = gui.Group(name=name)
g = f.groups[name]
del params['name']
e = gui.Checkbox(group=g,**params)
self.map_to_connects(e,r)
self.item.add(e)
if 'checked' in r: g.value = value
elif type_ == 'button':
e = gui.Button(**params)
self.map_to_connects(e,r)
self.item.add(e)
elif type_ == 'submit':
e = gui.Button(**params)
self.map_to_connects(e,r)
self.item.add(e)
elif type_ == 'file':
e = gui.Input(**params)
self.map_to_connects(e,r)
self.item.add(e)
b = gui.Button(value='Browse...')
self.item.add(b)
def _browse(value):
d = gui.FileDialog();
d.connect(gui.CHANGE,gui.action_setvalue,(d,e))
d.open();
b.connect(gui.CLICK,_browse,None)
self._locals[r.get('id',None)] = e
I got the error in the last line, because e wasn't defined. I am guessing the reason for this is that the if statement that checks the type of the input and creates the e variable didn't match anything. I added a line to print the _type variable and I got 'hidden' when i tried google and apple. Is there any way to render form items that have the type 'hidden' with PGU?
Edit:
If I added a section to the if statement to check if type_ was equal to 'hidden', what would I put in it?
Edit 2:
I have realized that the html rendering is not very good (it even shows javascript code) for PGU and so I would like to know if there is any other way of rendering html in a pygame window.
A:
I think it's possible to embed PyGame in a PyQT window. That's more of a work around than an elegant solution though.
| PGU HTML Renderer can't render most sites | I am trying to make a web browser using pygame. I am using PGU for html rendering. It works fine when I visit simple sites, like example.com, but when I try and load anything more complex that uses an html form, like google, I get this error:
UnboundLocalError: local variable 'e' referenced before assignment
I looked in the PGU html rendering file and found this code segment:
def start_input(self,attrs):
r = self.attrs_to_map(attrs)
params = self.map_to_params(r) #why bother
#params = {}
type_,name,value = r.get('type','text'),r.get('name',None),r.get('value',None)
f = self.form
if type_ == 'text':
e = gui.Input(**params)
self.map_to_connects(e,r)
self.item.add(e)
elif type_ == 'radio':
if name not in f.groups:
f.groups[name] = gui.Group(name=name)
g = f.groups[name]
del params['name']
e = gui.Radio(group=g,**params)
self.map_to_connects(e,r)
self.item.add(e)
if 'checked' in r: g.value = value
elif type_ == 'checkbox':
if name not in f.groups:
f.groups[name] = gui.Group(name=name)
g = f.groups[name]
del params['name']
e = gui.Checkbox(group=g,**params)
self.map_to_connects(e,r)
self.item.add(e)
if 'checked' in r: g.value = value
elif type_ == 'button':
e = gui.Button(**params)
self.map_to_connects(e,r)
self.item.add(e)
elif type_ == 'submit':
e = gui.Button(**params)
self.map_to_connects(e,r)
self.item.add(e)
elif type_ == 'file':
e = gui.Input(**params)
self.map_to_connects(e,r)
self.item.add(e)
b = gui.Button(value='Browse...')
self.item.add(b)
def _browse(value):
d = gui.FileDialog();
d.connect(gui.CHANGE,gui.action_setvalue,(d,e))
d.open();
b.connect(gui.CLICK,_browse,None)
self._locals[r.get('id',None)] = e
I got the error in the last line, because e wasn't defined. I am guessing the reason for this is that the if statement that checks the type of the input and creates the e variable didn't match anything. I added a line to print the _type variable and I got 'hidden' when i tried google and apple. Is there any way to render form items that have the type 'hidden' with PGU?
Edit:
If I added a section to the if statement to check if type_ was equal to 'hidden', what would I put in it?
Edit 2:
I have realized that the html rendering is not very good (it even shows javascript code) for PGU and so I would like to know if there is any other way of rendering html in a pygame window.
| [
"I think it's possible to embed PyGame in a PyQT window. That's more of a work around than an elegant solution though. \n"
] | [
1
] | [] | [] | [
"html_rendering",
"pygame",
"python"
] | stackoverflow_0002982016_html_rendering_pygame_python.txt |
Q:
How to update the text of a tag in XML using Elementree
Using elementree, the easiest way to read the text of a tag is to do the following:
import elementtree.ElementTree as ET
sKeyMap = ET.parse("KeyMaps/KeyMap_Checklist.xml")
host = sKeyMap.findtext("/BrowserInformation/BrowserSetup/host")
Now I want to update the text in the same file, hopefully without having to re-write it with something easy like:
host = "4444"
sKeyMap.replacetext("/BrowserInformation/BrowserSetup/host")
Any ideas?
Thx in advance
Christopher
A:
If you want to update the value of the <host> element in your text file you should get a handle to the element using find() rather than just reading the text using findtext(). Once you have the element you can easily get the text out using element.text. Since you have the element you can easily reset its value as shown below:
import elementtree.ElementTree as ET
sKeyMap = ET.parse("KeyMaps/KeyMap_Checklist.xml")
host_element = sKeyMap.find("/BrowserInformation/BrowserSetup/host")
host = host_element.text
print host
# Now reset the the text of the <host> element
host = "4444"
host_element.text = host
A:
building on Tendayi's example maybe try something like:
newXmlContent = ET.tostring(sKeyMap)
fileObject = open("KeyMaps/newKeyMap_Checklist.xml","w") #note I used a different filename for testing!
fileObject.write(newXmlContent)
fileObject.close()
| How to update the text of a tag in XML using Elementree | Using elementree, the easiest way to read the text of a tag is to do the following:
import elementtree.ElementTree as ET
sKeyMap = ET.parse("KeyMaps/KeyMap_Checklist.xml")
host = sKeyMap.findtext("/BrowserInformation/BrowserSetup/host")
Now I want to update the text in the same file, hopefully without having to re-write it with something easy like:
host = "4444"
sKeyMap.replacetext("/BrowserInformation/BrowserSetup/host")
Any ideas?
Thx in advance
Christopher
| [
"If you want to update the value of the <host> element in your text file you should get a handle to the element using find() rather than just reading the text using findtext(). Once you have the element you can easily get the text out using element.text. Since you have the element you can easily reset its value as shown below:\nimport elementtree.ElementTree as ET\nsKeyMap = ET.parse(\"KeyMaps/KeyMap_Checklist.xml\")\nhost_element = sKeyMap.find(\"/BrowserInformation/BrowserSetup/host\")\nhost = host_element.text\nprint host\n# Now reset the the text of the <host> element\nhost = \"4444\"\nhost_element.text = host\n\n",
"building on Tendayi's example maybe try something like:\nnewXmlContent = ET.tostring(sKeyMap)\nfileObject = open(\"KeyMaps/newKeyMap_Checklist.xml\",\"w\") #note I used a different filename for testing!\nfileObject.write(newXmlContent)\nfileObject.close()\n\n"
] | [
1,
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0003018763_elementtree_python_xml.txt |
Q:
Python Pickle: what can cause stack index out of range error?
I'm getting this error:
File "C:\Python26\lib\pickle.py", line 1374, in loads
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 1075, in load_obj
k = self.marker()
File "C:\Python26\lib\pickle.py", line 874, in marker
while stack[k] is not mark: k = k-1
IndexError: list index out of range
Why could this be happening?
A:
A "damaged file" is the general explanation; single most likely cause is that you forgot to open the file (in Windows) as 'rb' ("read binary") and the pickling was done with a binary protocol (i.e., any protocol except the old, slow default protocol 0, ascii only, that basically exists only for legacy purposes, makes larger files, and has several limitations).
A:
Answer: I was trying to call pickle.loads() on the uninitialized field of a Google App Engine model.
| Python Pickle: what can cause stack index out of range error? | I'm getting this error:
File "C:\Python26\lib\pickle.py", line 1374, in loads
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 1075, in load_obj
k = self.marker()
File "C:\Python26\lib\pickle.py", line 874, in marker
while stack[k] is not mark: k = k-1
IndexError: list index out of range
Why could this be happening?
| [
"A \"damaged file\" is the general explanation; single most likely cause is that you forgot to open the file (in Windows) as 'rb' (\"read binary\") and the pickling was done with a binary protocol (i.e., any protocol except the old, slow default protocol 0, ascii only, that basically exists only for legacy purposes, makes larger files, and has several limitations).\n",
"Answer: I was trying to call pickle.loads() on the uninitialized field of a Google App Engine model.\n"
] | [
1,
0
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0003030229_pickle_python.txt |
Q:
Appengine Model SelfReferenceProperty and parent child relationship
I have a scenario in which I need a self reference property as follow:
class Post(db.Model):
creator = db.UserProperty()
post_title = db.StringProperty(required=True)
post_status = db.StringProperty(required=True, choices=['draft', 'published'])
post_parent = db.SelfReferenceProperty()
Now, I want ensure that an entity shouldn't be its own parent and a child of an entity cannot be its parent. How can I ensure this kind of a relationship in the PostForm model form and the Post model.
A:
I would suggest using a ListProperty(db.Key) instead, storing the list of ancestors. That way, you can query more efficiently ('get every descendent of node x' is easier), and you can enforce the latter condition easily, like this:
def ancestor_list_validator(l):
if len(l) != len(set(l)):
raise Exception("Repeated values in ancestor list!")
class Post(db.Model):
# ...
ancestors = db.ListProperty(db.Key, validator=ancestor_list_validator)
Validating that the entity's own key isn't in the list is a little tougher, and will likely require writing a custom datastore property.
| Appengine Model SelfReferenceProperty and parent child relationship | I have a scenario in which I need a self reference property as follow:
class Post(db.Model):
creator = db.UserProperty()
post_title = db.StringProperty(required=True)
post_status = db.StringProperty(required=True, choices=['draft', 'published'])
post_parent = db.SelfReferenceProperty()
Now, I want ensure that an entity shouldn't be its own parent and a child of an entity cannot be its parent. How can I ensure this kind of a relationship in the PostForm model form and the Post model.
| [
"I would suggest using a ListProperty(db.Key) instead, storing the list of ancestors. That way, you can query more efficiently ('get every descendent of node x' is easier), and you can enforce the latter condition easily, like this:\ndef ancestor_list_validator(l):\n if len(l) != len(set(l)):\n raise Exception(\"Repeated values in ancestor list!\")\n\nclass Post(db.Model):\n # ...\n ancestors = db.ListProperty(db.Key, validator=ancestor_list_validator)\n\nValidating that the entity's own key isn't in the list is a little tougher, and will likely require writing a custom datastore property.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003031223_google_app_engine_python.txt |
Q:
is there any way to enforce the 30 seconds limit on local appengine dev server?
Hey, i was wondering if there is a way to enforce the 30 seconds limit that is being enforced online at the appengine production servers to the local dev server? its impossible to test if i reach the limit before going production.
maybe some django middlware?
A:
You could write (and insert in the WSGI stack) a useful piece of WSGI middleware which uses a threading.Timer which logs the fact that the transaction has exceeded 30 seconds (and of course calls cancel on the timer object on the way out, as there's nothing to log in that case).
I'd do it at WSGI level, not Django level, (a) because I'm more familiar with WSGI middleware and (b) because it's a more general solution (it can help a Django web app, but it can also help a web app using any other framework -- WSGI's use is guaranteed by App Engine, whatever framework you decide to lay on top of it).
You'll need to tweak the "30 seconds" a bit to calibrate, because of course the power, available RAM, disk speed, etc, of your development machine, can't just happen to be exactly identical to Google's, and also many subsystems (esp. the storage one) have very different implementations "locally on the SDK" versus "on Google's actual servers" and in any given case may happen to be substantially slower (or maybe faster!-).
Given the considerations in the previous paragraph it might actually be more helpful to have the middleware simply always log the transaction's total elapsed time -- this way you can watch for transactions that (while they may terminate within 30 seconds on your development server) are taking comparable time (say 15 or 20 seconds or more), especially if they have multiple storage transactions that might slow them down on the real production servers/
A:
It's possible, as Alex demonstrates, but it's not really a good idea: The performance characteristics of the development server are not the same as those of the production environment, so something that executes quickly locally may not be nearly as quick in production, and vice versa.
Also, your user facing tasks should definitely not be so slow as to approach the 30 second limit.
| is there any way to enforce the 30 seconds limit on local appengine dev server? | Hey, i was wondering if there is a way to enforce the 30 seconds limit that is being enforced online at the appengine production servers to the local dev server? its impossible to test if i reach the limit before going production.
maybe some django middlware?
| [
"You could write (and insert in the WSGI stack) a useful piece of WSGI middleware which uses a threading.Timer which logs the fact that the transaction has exceeded 30 seconds (and of course calls cancel on the timer object on the way out, as there's nothing to log in that case).\nI'd do it at WSGI level, not Django level, (a) because I'm more familiar with WSGI middleware and (b) because it's a more general solution (it can help a Django web app, but it can also help a web app using any other framework -- WSGI's use is guaranteed by App Engine, whatever framework you decide to lay on top of it).\nYou'll need to tweak the \"30 seconds\" a bit to calibrate, because of course the power, available RAM, disk speed, etc, of your development machine, can't just happen to be exactly identical to Google's, and also many subsystems (esp. the storage one) have very different implementations \"locally on the SDK\" versus \"on Google's actual servers\" and in any given case may happen to be substantially slower (or maybe faster!-).\nGiven the considerations in the previous paragraph it might actually be more helpful to have the middleware simply always log the transaction's total elapsed time -- this way you can watch for transactions that (while they may terminate within 30 seconds on your development server) are taking comparable time (say 15 or 20 seconds or more), especially if they have multiple storage transactions that might slow them down on the real production servers/\n",
"It's possible, as Alex demonstrates, but it's not really a good idea: The performance characteristics of the development server are not the same as those of the production environment, so something that executes quickly locally may not be nearly as quick in production, and vice versa.\nAlso, your user facing tasks should definitely not be so slow as to approach the 30 second limit.\n"
] | [
1,
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003030593_django_google_app_engine_python.txt |
Q:
How to pickle and unpickle objects with self-references and from a class with slots?
What is a correct way to pickle an object from a class with slots, when this object references itself through one of its attributes? Here is a simple example, with my current implementation, which I'm not sure is 100 % correct:
import weakref
import pickle
class my_class(object):
__slots__ = ('an_int', 'ref_to_self', '__weakref__')
def __init__(self):
self.an_int = 42
self.ref_to_self = weakref.WeakKeyDictionary({self: 1})
# How to best write __getstate__ and __setstate__?
def __getstate__(self):
obj_slot_values = dict((k, getattr(self, k)) for k in self.__slots__)
# Conversion to a usual dictionary:
obj_slot_values['ref_to_self'] = dict(obj_slot_values['ref_to_self'])
# Unpicklable weakref object:
del obj_slot_values['__weakref__']
return obj_slot_values
def __setstate__(self, data_dict):
# print data_dict
for (name, value) in data_dict.iteritems():
setattr(self, name, value)
# Conversion of the dict back to a WeakKeyDictionary:
self.ref_to_self = weakref.WeakKeyDictionary(
self.ref_to_self.iteritems())
This can be tested for instance with:
def test_pickling(obj):
"Pickles obj and unpickles it. Returns the unpickled object"
obj_pickled = pickle.dumps(obj)
obj_unpickled = pickle.loads(obj_pickled)
# Self-references should be kept:
print "OK?", obj_unpickled == obj_unpickled.ref_to_self.keys()[0]
print "OK?", isinstance(obj_unpickled.ref_to_self,
weakref.WeakKeyDictionary)
return obj_unpickled
if __name__ == '__main__':
obj = my_class()
obj_unpickled = test_pickling(obj)
obj_unpickled2 = test_pickling(obj_unpickled)
Is this a correct/robust implementation? how should __getstate__ and __setstate__ be written if my_class inherited from a class with __slots__? is there a memory leak inside __setstate__ because of the "circular" dict?
There is a remark in PEP 307 that makes me wonder whether pickling my_class objects is at all possible in a robust way:
The __getstate__ method should return a picklable value representing the object's state without referencing the object itself.
Does this clash with the fact that a reference to the object itself is pickled?
That's a lot of questions: any remark, comment, or advice would be much appreciated!
A:
It looks like what the original post suggests works well enough.
As for what PEP 307 reads:
The __getstate__ method should return a picklable value representing the object's state without referencing the object itself.
I understand that it only means that the __getstate__ method simply must return a representation that does not point to the (unpickleable) original object. Thus, returning an object that references itself is fine, as long as no reference to the original (unpickleable) object is made.
| How to pickle and unpickle objects with self-references and from a class with slots? | What is a correct way to pickle an object from a class with slots, when this object references itself through one of its attributes? Here is a simple example, with my current implementation, which I'm not sure is 100 % correct:
import weakref
import pickle
class my_class(object):
__slots__ = ('an_int', 'ref_to_self', '__weakref__')
def __init__(self):
self.an_int = 42
self.ref_to_self = weakref.WeakKeyDictionary({self: 1})
# How to best write __getstate__ and __setstate__?
def __getstate__(self):
obj_slot_values = dict((k, getattr(self, k)) for k in self.__slots__)
# Conversion to a usual dictionary:
obj_slot_values['ref_to_self'] = dict(obj_slot_values['ref_to_self'])
# Unpicklable weakref object:
del obj_slot_values['__weakref__']
return obj_slot_values
def __setstate__(self, data_dict):
# print data_dict
for (name, value) in data_dict.iteritems():
setattr(self, name, value)
# Conversion of the dict back to a WeakKeyDictionary:
self.ref_to_self = weakref.WeakKeyDictionary(
self.ref_to_self.iteritems())
This can be tested for instance with:
def test_pickling(obj):
"Pickles obj and unpickles it. Returns the unpickled object"
obj_pickled = pickle.dumps(obj)
obj_unpickled = pickle.loads(obj_pickled)
# Self-references should be kept:
print "OK?", obj_unpickled == obj_unpickled.ref_to_self.keys()[0]
print "OK?", isinstance(obj_unpickled.ref_to_self,
weakref.WeakKeyDictionary)
return obj_unpickled
if __name__ == '__main__':
obj = my_class()
obj_unpickled = test_pickling(obj)
obj_unpickled2 = test_pickling(obj_unpickled)
Is this a correct/robust implementation? how should __getstate__ and __setstate__ be written if my_class inherited from a class with __slots__? is there a memory leak inside __setstate__ because of the "circular" dict?
There is a remark in PEP 307 that makes me wonder whether pickling my_class objects is at all possible in a robust way:
The __getstate__ method should return a picklable value representing the object's state without referencing the object itself.
Does this clash with the fact that a reference to the object itself is pickled?
That's a lot of questions: any remark, comment, or advice would be much appreciated!
| [
"It looks like what the original post suggests works well enough.\nAs for what PEP 307 reads:\n\nThe __getstate__ method should return a picklable value representing the object's state without referencing the object itself.\n\nI understand that it only means that the __getstate__ method simply must return a representation that does not point to the (unpickleable) original object. Thus, returning an object that references itself is fine, as long as no reference to the original (unpickleable) object is made.\n"
] | [
6
] | [] | [] | [
"pickle",
"python",
"slots"
] | stackoverflow_0002922628_pickle_python_slots.txt |
Q:
Eclipse + Django: How to get bytecode output when python source files change?
Whenever I change my python source files in my Django project, the .pyc files become out of date. Of course that's because I need to recompile them in order to test them through my local Apache web server. I would like to get around this manual process by employing some automatic means of compiling them on save, or on build through Eclipse, or something like that. What's the best and proper way to do this?
A:
You shouldn't ever need to 'compile' your .pyc files manually. This is always done automatically at runtime by the Python interpreter.
In rare instances, such as when you delete an entire .py module, you may need to manually delete the corresponding .pyc. But there's no need to do any other manual compiling.
What makes you think you need to do this?
| Eclipse + Django: How to get bytecode output when python source files change? | Whenever I change my python source files in my Django project, the .pyc files become out of date. Of course that's because I need to recompile them in order to test them through my local Apache web server. I would like to get around this manual process by employing some automatic means of compiling them on save, or on build through Eclipse, or something like that. What's the best and proper way to do this?
| [
"You shouldn't ever need to 'compile' your .pyc files manually. This is always done automatically at runtime by the Python interpreter.\nIn rare instances, such as when you delete an entire .py module, you may need to manually delete the corresponding .pyc. But there's no need to do any other manual compiling.\nWhat makes you think you need to do this?\n"
] | [
2
] | [] | [] | [
"build",
"build_process",
"bytecode",
"django",
"python"
] | stackoverflow_0003031383_build_build_process_bytecode_django_python.txt |
Q:
Setting custom SQL in django admin
I'm trying to set up a proxy model in django admin. It will represent a subset of the original model. The code from models.py:
class MyManager(models.Manager):
def get_query_set(self):
return super(MyManager, self).get_query_set().filter(some_column='value')
class MyModel(OrigModel):
objects = MyManager()
class Meta:
proxy = True
Now instead of filter() I need to use a complex SELECT statement with JOINS. What's the proper way to inject it wholly to the custom manager?
A:
Django provides the extra() QuerySet modifier -- a hook for injecting specific clauses into the SQL generated by a QuerySet.
This can be used in complex cases, maybe with one or more additional queries.
A:
If you want to use the ORM further in MyModel.objects raw SQL is no solution. In the case of raw SQL an iterator is provided.
You are not able to do any chaining on MyModel().objects as filter, exclude etc.. If it is possible in admin, so for example filtering would not work in it. If you need this features, the only choice you have is not to use raw sql in your managers get_query_set method.
I do not know if Manager.raw is even possible in admin.
| Setting custom SQL in django admin | I'm trying to set up a proxy model in django admin. It will represent a subset of the original model. The code from models.py:
class MyManager(models.Manager):
def get_query_set(self):
return super(MyManager, self).get_query_set().filter(some_column='value')
class MyModel(OrigModel):
objects = MyManager()
class Meta:
proxy = True
Now instead of filter() I need to use a complex SELECT statement with JOINS. What's the proper way to inject it wholly to the custom manager?
| [
"Django provides the extra() QuerySet modifier -- a hook for injecting specific clauses into the SQL generated by a QuerySet.\nThis can be used in complex cases, maybe with one or more additional queries.\n",
"If you want to use the ORM further in MyModel.objects raw SQL is no solution. In the case of raw SQL an iterator is provided.\nYou are not able to do any chaining on MyModel().objects as filter, exclude etc.. If it is possible in admin, so for example filtering would not work in it. If you need this features, the only choice you have is not to use raw sql in your managers get_query_set method.\nI do not know if Manager.raw is even possible in admin.\n"
] | [
2,
1
] | [] | [] | [
"django_admin",
"python",
"sql"
] | stackoverflow_0003009826_django_admin_python_sql.txt |
Q:
How can I calculate new time zone in python?
Lets say I have a time 04:05 and the timezone is -0100 (GMT)
I want to calculate the new time which will be 03:05
Is there any function in python to do that calculcation ?
Thanks
A:
Try something like this:
>>> import datetime
>>> my_time = datetime.datetime.strptime('04:05', '%H:%M')
>>> my_time
datetime.datetime(1900, 1, 1, 4, 5)
>>> offset_str = '-0100'
>>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * (-1 if offset_str.startswith('-') else 1)
>>> offset
datetime.timedelta(-1, 82800)
>>> my_time + offset
datetime.datetime(1900, 1, 1, 3, 5)
>>> (my_time + offset).time()
datetime.time(3, 5)
In short:
>>> import datetime
>>> my_time = datetime.datetime.strptime('04:05', '%H:%M')
>>> offset_str = '-0100'
>>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * (-1 if offset_str.startswith('-') else 1)
>>> (my_time + offset).time()
datetime.time(3, 5)
A:
You can use "pytz" to accomplish this.Try:
from string import atoi
from datetime import datetime
import pytz # Available http://sourceforge.net/project/showfiles.php?group_id=79122
thedate = "20080518"
thetime = "2210"
europe_tz = pytz.timezone('Europe/Paris') # Note that your local install timezone should be settings.py
brazil_tz = pytz.timezone('America/Sao_Paulo')
server_tz = pytz.timezone('America/Los_Angeles')
stat_time = datetime(atoi(thedate[0:4]), atoi(thedate[4:6]), atoi(thedate[6:8]), atoi(thetime[0:2]), atoi(thetime[2:4]), 0, tzinfo=europe_tz)
stat_time.astimezone(brazil_tz) # returns time for brazil
stat_time.astimezone(server_tz) # returns server time
Source: http://menendez.com/blog/python-timezone-conversion-example-using-pytz/
| How can I calculate new time zone in python? | Lets say I have a time 04:05 and the timezone is -0100 (GMT)
I want to calculate the new time which will be 03:05
Is there any function in python to do that calculcation ?
Thanks
| [
"Try something like this:\n >>> import datetime\n >>> my_time = datetime.datetime.strptime('04:05', '%H:%M')\n >>> my_time\n datetime.datetime(1900, 1, 1, 4, 5)\n >>> offset_str = '-0100'\n >>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * (-1 if offset_str.startswith('-') else 1)\n >>> offset \n datetime.timedelta(-1, 82800)\n >>> my_time + offset\n datetime.datetime(1900, 1, 1, 3, 5)\n >>> (my_time + offset).time()\n datetime.time(3, 5)\n\nIn short:\n >>> import datetime\n >>> my_time = datetime.datetime.strptime('04:05', '%H:%M')\n >>> offset_str = '-0100'\n >>> offset = datetime.timedelta(hours=int(offset_str.lstrip('-')[:2]), minutes=int(offset_str.lstrip('-')[2:])) * (-1 if offset_str.startswith('-') else 1)\n >>> (my_time + offset).time()\n datetime.time(3, 5)\n\n",
"You can use \"pytz\" to accomplish this.Try:\nfrom string import atoi\nfrom datetime import datetime\nimport pytz # Available http://sourceforge.net/project/showfiles.php?group_id=79122\n\nthedate = \"20080518\"\nthetime = \"2210\"\n\neurope_tz = pytz.timezone('Europe/Paris') # Note that your local install timezone should be settings.py\nbrazil_tz = pytz.timezone('America/Sao_Paulo')\nserver_tz = pytz.timezone('America/Los_Angeles')\n\nstat_time = datetime(atoi(thedate[0:4]), atoi(thedate[4:6]), atoi(thedate[6:8]), atoi(thetime[0:2]), atoi(thetime[2:4]), 0, tzinfo=europe_tz)\n\nstat_time.astimezone(brazil_tz) # returns time for brazil\nstat_time.astimezone(server_tz) # returns server time\n\nSource: http://menendez.com/blog/python-timezone-conversion-example-using-pytz/\n"
] | [
1,
0
] | [] | [] | [
"datetime",
"gmt",
"python",
"time",
"timezone"
] | stackoverflow_0003031615_datetime_gmt_python_time_timezone.txt |
Q:
Comments on this assumption about running on dev server vs a real instance in app engine (python)?
I'm on an app engine project where I'd like to put in a link to a Javascript test runner that I'd like to only exist when running the development server. I've made some experiments on a local shell with configuration loaded using the technique found in NoseGAE versus live on the 'App Engine Console' [1] and it looks to me like a distinction btw real instance and dev server is the presence of the module google.appengine.tools. Which lead me to this utility function:
def is_dev():
"""
Tells us if we're running under the development server or not.
:return:
``True`` if the code is running under the development server.
"""
try:
from google.appengine import tools
return True
except ImportError:
return False
The question (finally!) would be: is this a bad idea? And in that case, can anyone suggest a better approach?
[1] http://con.appspot.com/console/ (try it! very handy indeed)
A:
The standard way to test for the development server is as follows:
DEBUG = os.environ['SERVER_SOFTWARE'].startswith("Dev")
Relying on the existence or nonexistence of a particular module - especially an undocumented one - is probably a bad idea.
A:
I'd recommend doing it this way:
import os
def onDevServer():
return os.environ['SERVER_SOFTWARE'].find('Development') >= 0
This looks at the environment you're running in, and returns true if you're running on the development server. However, its a much cleaner way than checking an import, in my opinion.
A:
I'm not a google app developer, but I wouldn't make this 100% dynamic, but also look at a value from a config file. I'm pretty sure you will be running into the problem, that you want to see this console on the prod system (google servers) or run your local version without the dev code (for testing).
To sum it up: Such a logic is fine for small stuff, like adding a debug link, but provide a way to overwrite it (e.g. by a configuration value)
| Comments on this assumption about running on dev server vs a real instance in app engine (python)? | I'm on an app engine project where I'd like to put in a link to a Javascript test runner that I'd like to only exist when running the development server. I've made some experiments on a local shell with configuration loaded using the technique found in NoseGAE versus live on the 'App Engine Console' [1] and it looks to me like a distinction btw real instance and dev server is the presence of the module google.appengine.tools. Which lead me to this utility function:
def is_dev():
"""
Tells us if we're running under the development server or not.
:return:
``True`` if the code is running under the development server.
"""
try:
from google.appengine import tools
return True
except ImportError:
return False
The question (finally!) would be: is this a bad idea? And in that case, can anyone suggest a better approach?
[1] http://con.appspot.com/console/ (try it! very handy indeed)
| [
"The standard way to test for the development server is as follows:\nDEBUG = os.environ['SERVER_SOFTWARE'].startswith(\"Dev\")\n\nRelying on the existence or nonexistence of a particular module - especially an undocumented one - is probably a bad idea.\n",
"I'd recommend doing it this way:\nimport os\ndef onDevServer():\n return os.environ['SERVER_SOFTWARE'].find('Development') >= 0\n\nThis looks at the environment you're running in, and returns true if you're running on the development server. However, its a much cleaner way than checking an import, in my opinion.\n",
"I'm not a google app developer, but I wouldn't make this 100% dynamic, but also look at a value from a config file. I'm pretty sure you will be running into the problem, that you want to see this console on the prod system (google servers) or run your local version without the dev code (for testing).\nTo sum it up: Such a logic is fine for small stuff, like adding a debug link, but provide a way to overwrite it (e.g. by a configuration value)\n"
] | [
6,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003031886_google_app_engine_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.