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:
From escaped html -> to regular html? - Python
I used BeautifulSoup to handle XML files that I have collected through a REST API.
The responses contain HTML code, but BeautifulSoup escapes all the HTML tags so it can be displayed nicely.
Unfortunately I need the HTML code.
How would I go on about transforming the escaped HTML into proper markup?
Help would be very much appreciated!
A:
I think you want xml.sax.saxutils.unescape from the Python standard library.
E.g.:
>>> from xml.sax import saxutils as su
>>> s = '<foo>bar</foo>'
>>> su.unescape(s)
'<foo>bar</foo>'
A:
You could try the urllib module?
It has a method unquote() that might suit your needs.
Edit: on second thought, (and more reading of your question) you might just want to just use string.replace()
Like so:
string.replace('<','<')
string.replace('>','>')
|
From escaped html -> to regular html? - Python
|
I used BeautifulSoup to handle XML files that I have collected through a REST API.
The responses contain HTML code, but BeautifulSoup escapes all the HTML tags so it can be displayed nicely.
Unfortunately I need the HTML code.
How would I go on about transforming the escaped HTML into proper markup?
Help would be very much appreciated!
|
[
"I think you want xml.sax.saxutils.unescape from the Python standard library.\nE.g.:\n>>> from xml.sax import saxutils as su\n>>> s = '<foo>bar</foo>'\n>>> su.unescape(s)\n'<foo>bar</foo>'\n\n",
"You could try the urllib module?\nIt has a method unquote() that might suit your needs.\nEdit: on second thought, (and more reading of your question) you might just want to just use string.replace()\nLike so:\nstring.replace('<','<')\nstring.replace('>','>')\n\n"
] |
[
19,
2
] |
[] |
[] |
[
"beautifulsoup",
"escaping",
"html",
"lxml",
"python"
] |
stackoverflow_0002474971_beautifulsoup_escaping_html_lxml_python.txt
|
Q:
Help me find an appropriate ruby/python parser generator
The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the tracing capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules.
The thing is, it has to be written in python or in ruby, and have a verbose mode/trace mode or very helpful debugging techniques.
Does anyone know such a parser generator ?
EDIT: when I said debugging, I wasn't referring to debugging python or ruby. I was referring to debugging the parser generator, see what it's doing at every step, see every char it's reading, rules it's trying to match. Hope you get the point.
BOUNTY EDIT: to win the bounty, please show a parser generator framework, and illustrate some of it's debugging features. I repeat, I'm not interested in pdb, but in parser's debugging framework. Also, please don't mention treetop. I'm not interested in it.
A:
Python is a pretty easy language to debug. You can just do import pdb pdb.settrace().
However, these parser generators supposedly come with good debugging facilities.
http://www.antlr.org/
http://www.dabeaz.com/ply/
http://pyparsing.wikispaces.com/
In response to bounty
Here is PLY debugging in action.
Source Code
tokens = (
'NAME','NUMBER',
)
literals = ['=','+','-','*','/', '(',')']
# Tokens
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
t_ignore = " \t"
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
import ply.lex as lex
lex.lex(debug=1)
# Parsing rules
precedence = (
('left','+','-'),
('left','*','/'),
('right','UMINUS'),
)
# dictionary of names
names = { }
def p_statement_assign(p):
'statement : NAME "=" expression'
names[p[1]] = p[3]
def p_statement_expr(p):
'statement : expression'
print(p[1])
def p_expression_binop(p):
'''expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression'''
if p[2] == '+' : p[0] = p[1] + p[3]
elif p[2] == '-': p[0] = p[1] - p[3]
elif p[2] == '*': p[0] = p[1] * p[3]
elif p[2] == '/': p[0] = p[1] / p[3]
def p_expression_uminus(p):
"expression : '-' expression %prec UMINUS"
p[0] = -p[2]
def p_expression_group(p):
"expression : '(' expression ')'"
p[0] = p[2]
def p_expression_number(p):
"expression : NUMBER"
p[0] = p[1]
def p_expression_name(p):
"expression : NAME"
try:
p[0] = names[p[1]]
except LookupError:
print("Undefined name '%s'" % p[1])
p[0] = 0
def p_error(p):
if p:
print("Syntax error at '%s'" % p.value)
else:
print("Syntax error at EOF")
import ply.yacc as yacc
yacc.yacc()
import logging
logging.basicConfig(
level=logging.INFO,
filename="parselog.txt"
)
while 1:
try:
s = raw_input('calc > ')
except EOFError:
break
if not s: continue
yacc.parse(s, debug=1)
Output
lex: tokens = ('NAME', 'NUMBER')
lex: literals = ['=', '+', '-', '*', '/', '(', ')']
lex: states = {'INITIAL': 'inclusive'}
lex: Adding rule t_NUMBER -> '\d+' (state 'INITIAL')
lex: Adding rule t_newline -> '\n+' (state 'INITIAL')
lex: Adding rule t_NAME -> '[a-zA-Z_][a-zA-Z0-9_]*' (state 'INITIAL')
lex: ==== MASTER REGEXS FOLLOW ====
lex: state 'INITIAL' : regex[0] = '(?P<t_NUMBER>\d+)|(?P<t_newline>\n+)|(?P<t_NAME>[a-zA-Z
_][a-zA-Z0-9_]*)'
calc > 2+3
PLY: PARSE DEBUG START
State : 0
Stack : . LexToken(NUMBER,2,1,0)
Action : Shift and goto state 3
State : 3
Stack : NUMBER . LexToken(+,'+',1,1)
Action : Reduce rule [expression -> NUMBER] with [2] and goto state 9
Result : <int @ 0x1a1896c> (2)
State : 6
Stack : expression . LexToken(+,'+',1,1)
Action : Shift and goto state 12
State : 12
Stack : expression + . LexToken(NUMBER,3,1,2)
Action : Shift and goto state 3
State : 3
Stack : expression + NUMBER . $end
Action : Reduce rule [expression -> NUMBER] with [3] and goto state 9
Result : <int @ 0x1a18960> (3)
State : 18
Stack : expression + expression . $end
Action : Reduce rule [expression -> expression + expression] with [2,'+',3] and goto state
3
Result : <int @ 0x1a18948> (5)
State : 6
Stack : expression . $end
Action : Reduce rule [statement -> expression] with [5] and goto state 2
5
Result : <NoneType @ 0x1e1ccef4> (None)
State : 4
Stack : statement . $end
Done : Returning <NoneType @ 0x1e1ccef4> (None)
PLY: PARSE DEBUG END
calc >
Parse Table generated at parser.out
Created by PLY version 3.2 (http://www.dabeaz.com/ply)
Grammar
Rule 0 S' -> statement
Rule 1 statement -> NAME = expression
Rule 2 statement -> expression
Rule 3 expression -> expression + expression
Rule 4 expression -> expression - expression
Rule 5 expression -> expression * expression
Rule 6 expression -> expression / expression
Rule 7 expression -> - expression
Rule 8 expression -> ( expression )
Rule 9 expression -> NUMBER
Rule 10 expression -> NAME
Terminals, with rules where they appear
( : 8
) : 8
* : 5
+ : 3
- : 4 7
/ : 6
= : 1
NAME : 1 10
NUMBER : 9
error :
Nonterminals, with rules where they appear
expression : 1 2 3 3 4 4 5 5 6 6 7 8
statement : 0
Parsing method: LALR
state 0
(0) S' -> . statement
(1) statement -> . NAME = expression
(2) statement -> . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
NAME shift and go to state 1
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
expression shift and go to state 6
statement shift and go to state 4
state 1
(1) statement -> NAME . = expression
(10) expression -> NAME .
= shift and go to state 7
+ reduce using rule 10 (expression -> NAME .)
- reduce using rule 10 (expression -> NAME .)
* reduce using rule 10 (expression -> NAME .)
/ reduce using rule 10 (expression -> NAME .)
$end reduce using rule 10 (expression -> NAME .)
state 2
(7) expression -> - . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 9
state 3
(9) expression -> NUMBER .
+ reduce using rule 9 (expression -> NUMBER .)
- reduce using rule 9 (expression -> NUMBER .)
* reduce using rule 9 (expression -> NUMBER .)
/ reduce using rule 9 (expression -> NUMBER .)
$end reduce using rule 9 (expression -> NUMBER .)
) reduce using rule 9 (expression -> NUMBER .)
state 4
(0) S' -> statement .
state 5
(8) expression -> ( . expression )
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 10
state 6
(2) statement -> expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
$end reduce using rule 2 (statement -> expression .)
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 7
(1) statement -> NAME = . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 15
state 8
(10) expression -> NAME .
+ reduce using rule 10 (expression -> NAME .)
- reduce using rule 10 (expression -> NAME .)
* reduce using rule 10 (expression -> NAME .)
/ reduce using rule 10 (expression -> NAME .)
$end reduce using rule 10 (expression -> NAME .)
) reduce using rule 10 (expression -> NAME .)
state 9
(7) expression -> - expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 7 (expression -> - expression .)
- reduce using rule 7 (expression -> - expression .)
* reduce using rule 7 (expression -> - expression .)
/ reduce using rule 7 (expression -> - expression .)
$end reduce using rule 7 (expression -> - expression .)
) reduce using rule 7 (expression -> - expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
state 10
(8) expression -> ( expression . )
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
) shift and go to state 16
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 11
(4) expression -> expression - . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 17
state 12
(3) expression -> expression + . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 18
state 13
(5) expression -> expression * . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 19
state 14
(6) expression -> expression / . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 20
state 15
(1) statement -> NAME = expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
$end reduce using rule 1 (statement -> NAME = expression .)
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 16
(8) expression -> ( expression ) .
+ reduce using rule 8 (expression -> ( expression ) .)
- reduce using rule 8 (expression -> ( expression ) .)
* reduce using rule 8 (expression -> ( expression ) .)
/ reduce using rule 8 (expression -> ( expression ) .)
$end reduce using rule 8 (expression -> ( expression ) .)
) reduce using rule 8 (expression -> ( expression ) .)
state 17
(4) expression -> expression - expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 4 (expression -> expression - expression .)
- reduce using rule 4 (expression -> expression - expression .)
$end reduce using rule 4 (expression -> expression - expression .)
) reduce using rule 4 (expression -> expression - expression .)
* shift and go to state 13
/ shift and go to state 14
! * [ reduce using rule 4 (expression -> expression - expression .) ]
! / [ reduce using rule 4 (expression -> expression - expression .) ]
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
state 18
(3) expression -> expression + expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 3 (expression -> expression + expression .)
- reduce using rule 3 (expression -> expression + expression .)
$end reduce using rule 3 (expression -> expression + expression .)
) reduce using rule 3 (expression -> expression + expression .)
* shift and go to state 13
/ shift and go to state 14
! * [ reduce using rule 3 (expression -> expression + expression .) ]
! / [ reduce using rule 3 (expression -> expression + expression .) ]
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
state 19
(5) expression -> expression * expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 5 (expression -> expression * expression .)
- reduce using rule 5 (expression -> expression * expression .)
* reduce using rule 5 (expression -> expression * expression .)
/ reduce using rule 5 (expression -> expression * expression .)
$end reduce using rule 5 (expression -> expression * expression .)
) reduce using rule 5 (expression -> expression * expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
state 20
(6) expression -> expression / expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 6 (expression -> expression / expression .)
- reduce using rule 6 (expression -> expression / expression .)
* reduce using rule 6 (expression -> expression / expression .)
/ reduce using rule 6 (expression -> expression / expression .)
$end reduce using rule 6 (expression -> expression / expression .)
) reduce using rule 6 (expression -> expression / expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
A:
I don't know anything about its debugging features, but I've heard good things about PyParsing.
http://pyparsing.wikispaces.com/
A:
I know the bounty has already been claimed, but here is an equivalent parser written in pyparsing (plus support for function calls with zero or more comma-delimted arguments):
from pyparsing import *
LPAR, RPAR = map(Suppress,"()")
EQ = Literal("=")
name = Word(alphas, alphanums+"_").setName("name")
number = Word(nums).setName("number")
expr = Forward()
operand = Optional('-') + (Group(name + LPAR +
Group(Optional(delimitedList(expr))) +
RPAR) |
name |
number |
Group(LPAR + expr + RPAR))
binop = oneOf("+ - * / **")
expr << (Group(operand + OneOrMore(binop + operand)) | operand)
assignment = name + EQ + expr
statement = assignment | expr
This test code runs the parser through its basic paces:
tests = """\
sin(pi/2)
y = mx+b
E = mc ** 2
F = m*a
x = x0 + v*t +a*t*t/2
1 - sqrt(sin(t)**2 + cos(t)**2)""".splitlines()
for t in tests:
print t.strip()
print statement.parseString(t).asList()
print
Gives this output:
sin(pi/2)
[['sin', [['pi', '/', '2']]]]
y = mx+b
['y', '=', ['mx', '+', 'b']]
E = mc ** 2
['E', '=', ['mc', '**', '2']]
F = m*a
['F', '=', ['m', '*', 'a']]
x = x0 + v*t +a*t*t/2
['x', '=', ['x0', '+', 'v', '*', 't', '+', 'a', '*', 't', '*', 't', '/', '2']]
1 - sqrt(sin(t)**2 + cos(t)**2)
[['1', '-', ['sqrt', [[['sin', ['t']], '**', '2', '+', ['cos', ['t']], '**', '2']]]]]
For debugging, we add this code:
# enable debugging for name and number expressions
name.setDebug()
number.setDebug()
And now we reparse the first test (displaying the input string and a simple column ruler):
t = tests[0]
print ("1234567890"*10)[:len(t)]
print t
statement.parseString(t)
print
Giving this output:
1234567890123
sin(pi/2)
Match name at loc 4(1,5)
Matched name -> ['sin']
Match name at loc 4(1,5)
Matched name -> ['sin']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match number at loc 11(1,12)
Matched number -> ['2']
Match name at loc 4(1,5)
Matched name -> ['sin']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match number at loc 11(1,12)
Matched number -> ['2']
Pyparsing also supports packrat parsing, a sort of parse-time memoization (read more about packratting here). Here is the same parsing sequence, but with packrat enabled:
same parse, but with packrat parsing enabled
1234567890123
sin(pi/2)
Match name at loc 4(1,5)
Matched name -> ['sin']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 8(1,9)
Matched name -> ['pi']
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match name at loc 11(1,12)
Exception raised:Expected name (at char 11), (line:1, col:12)
Match number at loc 11(1,12)
Matched number -> ['2']
This was an interesting exercise, and helpful to me to see debugging features from other parser libraries.
A:
ANTLR above has the advantage to generate human readable and understandable code,
since it is (a very sophisticated and powerful) top-down parser,
so you can step through it with a regular debugger
and see what it really is doing.
That's why it is my parser generator of choice.
Bottom up parser generators like PLY have the disadvantage
that for larger grammars it is almost impossible to understand
what the debugging output really means and why the
parsing table is like it is.
A:
Python wiki has a list of Language Parsers written in Python.
|
Help me find an appropriate ruby/python parser generator
|
The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the tracing capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules.
The thing is, it has to be written in python or in ruby, and have a verbose mode/trace mode or very helpful debugging techniques.
Does anyone know such a parser generator ?
EDIT: when I said debugging, I wasn't referring to debugging python or ruby. I was referring to debugging the parser generator, see what it's doing at every step, see every char it's reading, rules it's trying to match. Hope you get the point.
BOUNTY EDIT: to win the bounty, please show a parser generator framework, and illustrate some of it's debugging features. I repeat, I'm not interested in pdb, but in parser's debugging framework. Also, please don't mention treetop. I'm not interested in it.
|
[
"Python is a pretty easy language to debug. You can just do import pdb pdb.settrace().\nHowever, these parser generators supposedly come with good debugging facilities.\nhttp://www.antlr.org/\nhttp://www.dabeaz.com/ply/\nhttp://pyparsing.wikispaces.com/\nIn response to bounty\nHere is PLY debugging in action.\nSource Code\ntokens = (\n 'NAME','NUMBER',\n )\n\nliterals = ['=','+','-','*','/', '(',')']\n\n# Tokens\n\nt_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'\n\ndef t_NUMBER(t):\n r'\\d+'\n t.value = int(t.value)\n return t\n\nt_ignore = \" \\t\"\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += t.value.count(\"\\n\")\n\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n\n# Build the lexer\nimport ply.lex as lex\nlex.lex(debug=1)\n\n# Parsing rules\n\nprecedence = (\n ('left','+','-'),\n ('left','*','/'),\n ('right','UMINUS'),\n )\n\n# dictionary of names\nnames = { }\n\ndef p_statement_assign(p):\n 'statement : NAME \"=\" expression'\n names[p[1]] = p[3]\n\ndef p_statement_expr(p):\n 'statement : expression'\n print(p[1])\n\ndef p_expression_binop(p):\n '''expression : expression '+' expression\n | expression '-' expression\n | expression '*' expression\n | expression '/' expression'''\n if p[2] == '+' : p[0] = p[1] + p[3]\n elif p[2] == '-': p[0] = p[1] - p[3]\n elif p[2] == '*': p[0] = p[1] * p[3]\n elif p[2] == '/': p[0] = p[1] / p[3]\n\ndef p_expression_uminus(p):\n \"expression : '-' expression %prec UMINUS\"\n p[0] = -p[2]\n\ndef p_expression_group(p):\n \"expression : '(' expression ')'\"\n p[0] = p[2]\n\ndef p_expression_number(p):\n \"expression : NUMBER\"\n p[0] = p[1]\n\ndef p_expression_name(p):\n \"expression : NAME\"\n try:\n p[0] = names[p[1]]\n except LookupError:\n print(\"Undefined name '%s'\" % p[1])\n p[0] = 0\n\ndef p_error(p):\n if p:\n print(\"Syntax error at '%s'\" % p.value)\n else:\n print(\"Syntax error at EOF\")\n\nimport ply.yacc as yacc\nyacc.yacc()\n\nimport logging\nlogging.basicConfig(\n level=logging.INFO,\n filename=\"parselog.txt\"\n)\n\nwhile 1:\n try:\n s = raw_input('calc > ')\n except EOFError:\n break\n if not s: continue\n yacc.parse(s, debug=1)\n\nOutput\nlex: tokens = ('NAME', 'NUMBER')\nlex: literals = ['=', '+', '-', '*', '/', '(', ')']\nlex: states = {'INITIAL': 'inclusive'}\nlex: Adding rule t_NUMBER -> '\\d+' (state 'INITIAL')\nlex: Adding rule t_newline -> '\\n+' (state 'INITIAL')\nlex: Adding rule t_NAME -> '[a-zA-Z_][a-zA-Z0-9_]*' (state 'INITIAL')\nlex: ==== MASTER REGEXS FOLLOW ====\nlex: state 'INITIAL' : regex[0] = '(?P<t_NUMBER>\\d+)|(?P<t_newline>\\n+)|(?P<t_NAME>[a-zA-Z\n_][a-zA-Z0-9_]*)'\ncalc > 2+3\nPLY: PARSE DEBUG START\n\nState : 0\nStack : . LexToken(NUMBER,2,1,0)\nAction : Shift and goto state 3\n\nState : 3\nStack : NUMBER . LexToken(+,'+',1,1)\nAction : Reduce rule [expression -> NUMBER] with [2] and goto state 9\nResult : <int @ 0x1a1896c> (2)\n\nState : 6\nStack : expression . LexToken(+,'+',1,1)\nAction : Shift and goto state 12\n\nState : 12\nStack : expression + . LexToken(NUMBER,3,1,2)\nAction : Shift and goto state 3\n\nState : 3\nStack : expression + NUMBER . $end\nAction : Reduce rule [expression -> NUMBER] with [3] and goto state 9\nResult : <int @ 0x1a18960> (3)\n\nState : 18\nStack : expression + expression . $end\nAction : Reduce rule [expression -> expression + expression] with [2,'+',3] and goto state\n 3\nResult : <int @ 0x1a18948> (5)\n\nState : 6\nStack : expression . $end\nAction : Reduce rule [statement -> expression] with [5] and goto state 2\n5\nResult : <NoneType @ 0x1e1ccef4> (None)\n\nState : 4\nStack : statement . $end\nDone : Returning <NoneType @ 0x1e1ccef4> (None)\nPLY: PARSE DEBUG END\ncalc >\n\nParse Table generated at parser.out\nCreated by PLY version 3.2 (http://www.dabeaz.com/ply)\n\nGrammar\n\nRule 0 S' -> statement\nRule 1 statement -> NAME = expression\nRule 2 statement -> expression\nRule 3 expression -> expression + expression\nRule 4 expression -> expression - expression\nRule 5 expression -> expression * expression\nRule 6 expression -> expression / expression\nRule 7 expression -> - expression\nRule 8 expression -> ( expression )\nRule 9 expression -> NUMBER\nRule 10 expression -> NAME\n\nTerminals, with rules where they appear\n\n( : 8\n) : 8\n* : 5\n+ : 3\n- : 4 7\n/ : 6\n= : 1\nNAME : 1 10\nNUMBER : 9\nerror : \n\nNonterminals, with rules where they appear\n\nexpression : 1 2 3 3 4 4 5 5 6 6 7 8\nstatement : 0\n\nParsing method: LALR\n\nstate 0\n\n (0) S' -> . statement\n (1) statement -> . NAME = expression\n (2) statement -> . expression\n (3) expression -> . expression + expression\n (4) expression -> . expression - expression\n (5) expression -> . expression * expression\n (6) expression -> . expression / expression\n (7) expression -> . - expression\n (8) expression -> . ( expression )\n (9) expression -> . NUMBER\n (10) expression -> . NAME\n\n NAME shift and go to state 1\n - shift and go to state 2\n ( shift and go to state 5\n NUMBER shift and go to state 3\n\n expression shift and go to state 6\n statement shift and go to state 4\n\nstate 1\n\n (1) statement -> NAME . = expression\n (10) expression -> NAME .\n\n = shift and go to state 7\n + reduce using rule 10 (expression -> NAME .)\n - reduce using rule 10 (expression -> NAME .)\n * reduce using rule 10 (expression -> NAME .)\n / reduce using rule 10 (expression -> NAME .)\n $end reduce using rule 10 (expression -> NAME .)\n\n\nstate 2\n\n (7) expression -> - . expression\n (3) expression -> . expression + expression\n (4) expression -> . expression - expression\n (5) expression -> . expression * expression\n (6) expression -> . expression / expression\n (7) expression -> . - expression\n (8) expression -> . ( expression )\n (9) expression -> . NUMBER\n (10) expression -> . NAME\n\n - shift and go to state 2\n ( shift and go to state 5\n NUMBER shift and go to state 3\n NAME shift and go to state 8\n\n expression shift and go to state 9\n\nstate 3\n\n (9) expression -> NUMBER .\n\n + reduce using rule 9 (expression -> NUMBER .)\n - reduce using rule 9 (expression -> NUMBER .)\n * reduce using rule 9 (expression -> NUMBER .)\n / reduce using rule 9 (expression -> NUMBER .)\n $end reduce using rule 9 (expression -> NUMBER .)\n ) reduce using rule 9 (expression -> NUMBER .)\n\n\nstate 4\n\n (0) S' -> statement .\n\n\n\nstate 5\n\n (8) expression -> ( . expression )\n (3) expression -> . expression + expression\n (4) expression -> . expression - expression\n (5) expression -> . expression * expression\n (6) expression -> . expression / expression\n (7) expression -> . - expression\n (8) expression -> . ( expression )\n (9) expression -> . NUMBER\n (10) expression -> . NAME\n\n - shift and go to state 2\n ( shift and go to state 5\n NUMBER shift and go to state 3\n NAME shift and go to state 8\n\n expression shift and go to state 10\n\nstate 6\n\n (2) statement -> expression .\n (3) expression -> expression . + expression\n (4) expression -> expression . - expression\n (5) expression -> expression . * expression\n (6) expression -> expression . / expression\n\n $end reduce using rule 2 (statement -> expression .)\n + shift and go to state 12\n - shift and go to state 11\n * shift and go to state 13\n / shift and go to state 14\n\n\nstate 7\n\n (1) statement -> NAME = . expression\n (3) expression -> . expression + expression\n (4) expression -> . expression - expression\n (5) expression -> . expression * expression\n (6) expression -> . expression / expression\n (7) expression -> . - expression\n (8) expression -> . ( expression )\n (9) expression -> . NUMBER\n (10) expression -> . NAME\n\n - shift and go to state 2\n ( shift and go to state 5\n NUMBER shift and go to state 3\n NAME shift and go to state 8\n\n expression shift and go to state 15\n\nstate 8\n\n (10) expression -> NAME .\n\n + reduce using rule 10 (expression -> NAME .)\n - reduce using rule 10 (expression -> NAME .)\n * reduce using rule 10 (expression -> NAME .)\n / reduce using rule 10 (expression -> NAME .)\n $end reduce using rule 10 (expression -> NAME .)\n ) reduce using rule 10 (expression -> NAME .)\n\n\nstate 9\n\n (7) expression -> - expression .\n (3) expression -> expression . + expression\n (4) expression -> expression . - expression\n (5) expression -> expression . * expression\n (6) expression -> expression . / expression\n\n + reduce using rule 7 (expression -> - expression .)\n - reduce using rule 7 (expression -> - expression .)\n * reduce using rule 7 (expression -> - expression .)\n / reduce using rule 7 (expression -> - expression .)\n $end reduce using rule 7 (expression -> - expression .)\n ) reduce using rule 7 (expression -> - expression .)\n\n ! + [ shift and go to state 12 ]\n ! - [ shift and go to state 11 ]\n ! * [ shift and go to state 13 ]\n ! / [ shift and go to state 14 ]\n\n\nstate 10\n\n (8) expression -> ( expression . )\n (3) expression -> expression . + expression\n (4) expression -> expression . - expression\n (5) expression -> expression . * expression\n (6) expression -> expression . / expression\n\n ) shift and go to state 16\n + shift and go to state 12\n - shift and go to state 11\n * shift and go to state 13\n / shift and go to state 14\n\n\nstate 11\n\n (4) expression -> expression - . expression\n (3) expression -> . expression + expression\n (4) expression -> . expression - expression\n (5) expression -> . expression * expression\n (6) expression -> . expression / expression\n (7) expression -> . - expression\n (8) expression -> . ( expression )\n (9) expression -> . NUMBER\n (10) expression -> . NAME\n\n - shift and go to state 2\n ( shift and go to state 5\n NUMBER shift and go to state 3\n NAME shift and go to state 8\n\n expression shift and go to state 17\n\nstate 12\n\n (3) expression -> expression + . expression\n (3) expression -> . expression + expression\n (4) expression -> . expression - expression\n (5) expression -> . expression * expression\n (6) expression -> . expression / expression\n (7) expression -> . - expression\n (8) expression -> . ( expression )\n (9) expression -> . NUMBER\n (10) expression -> . NAME\n\n - shift and go to state 2\n ( shift and go to state 5\n NUMBER shift and go to state 3\n NAME shift and go to state 8\n\n expression shift and go to state 18\n\nstate 13\n\n (5) expression -> expression * . expression\n (3) expression -> . expression + expression\n (4) expression -> . expression - expression\n (5) expression -> . expression * expression\n (6) expression -> . expression / expression\n (7) expression -> . - expression\n (8) expression -> . ( expression )\n (9) expression -> . NUMBER\n (10) expression -> . NAME\n\n - shift and go to state 2\n ( shift and go to state 5\n NUMBER shift and go to state 3\n NAME shift and go to state 8\n\n expression shift and go to state 19\n\nstate 14\n\n (6) expression -> expression / . expression\n (3) expression -> . expression + expression\n (4) expression -> . expression - expression\n (5) expression -> . expression * expression\n (6) expression -> . expression / expression\n (7) expression -> . - expression\n (8) expression -> . ( expression )\n (9) expression -> . NUMBER\n (10) expression -> . NAME\n\n - shift and go to state 2\n ( shift and go to state 5\n NUMBER shift and go to state 3\n NAME shift and go to state 8\n\n expression shift and go to state 20\n\nstate 15\n\n (1) statement -> NAME = expression .\n (3) expression -> expression . + expression\n (4) expression -> expression . - expression\n (5) expression -> expression . * expression\n (6) expression -> expression . / expression\n\n $end reduce using rule 1 (statement -> NAME = expression .)\n + shift and go to state 12\n - shift and go to state 11\n * shift and go to state 13\n / shift and go to state 14\n\n\nstate 16\n\n (8) expression -> ( expression ) .\n\n + reduce using rule 8 (expression -> ( expression ) .)\n - reduce using rule 8 (expression -> ( expression ) .)\n * reduce using rule 8 (expression -> ( expression ) .)\n / reduce using rule 8 (expression -> ( expression ) .)\n $end reduce using rule 8 (expression -> ( expression ) .)\n ) reduce using rule 8 (expression -> ( expression ) .)\n\n\nstate 17\n\n (4) expression -> expression - expression .\n (3) expression -> expression . + expression\n (4) expression -> expression . - expression\n (5) expression -> expression . * expression\n (6) expression -> expression . / expression\n\n + reduce using rule 4 (expression -> expression - expression .)\n - reduce using rule 4 (expression -> expression - expression .)\n $end reduce using rule 4 (expression -> expression - expression .)\n ) reduce using rule 4 (expression -> expression - expression .)\n * shift and go to state 13\n / shift and go to state 14\n\n ! * [ reduce using rule 4 (expression -> expression - expression .) ]\n ! / [ reduce using rule 4 (expression -> expression - expression .) ]\n ! + [ shift and go to state 12 ]\n ! - [ shift and go to state 11 ]\n\n\nstate 18\n\n (3) expression -> expression + expression .\n (3) expression -> expression . + expression\n (4) expression -> expression . - expression\n (5) expression -> expression . * expression\n (6) expression -> expression . / expression\n\n + reduce using rule 3 (expression -> expression + expression .)\n - reduce using rule 3 (expression -> expression + expression .)\n $end reduce using rule 3 (expression -> expression + expression .)\n ) reduce using rule 3 (expression -> expression + expression .)\n * shift and go to state 13\n / shift and go to state 14\n\n ! * [ reduce using rule 3 (expression -> expression + expression .) ]\n ! / [ reduce using rule 3 (expression -> expression + expression .) ]\n ! + [ shift and go to state 12 ]\n ! - [ shift and go to state 11 ]\n\n\nstate 19\n\n (5) expression -> expression * expression .\n (3) expression -> expression . + expression\n (4) expression -> expression . - expression\n (5) expression -> expression . * expression\n (6) expression -> expression . / expression\n\n + reduce using rule 5 (expression -> expression * expression .)\n - reduce using rule 5 (expression -> expression * expression .)\n * reduce using rule 5 (expression -> expression * expression .)\n / reduce using rule 5 (expression -> expression * expression .)\n $end reduce using rule 5 (expression -> expression * expression .)\n ) reduce using rule 5 (expression -> expression * expression .)\n\n ! + [ shift and go to state 12 ]\n ! - [ shift and go to state 11 ]\n ! * [ shift and go to state 13 ]\n ! / [ shift and go to state 14 ]\n\n\nstate 20\n\n (6) expression -> expression / expression .\n (3) expression -> expression . + expression\n (4) expression -> expression . - expression\n (5) expression -> expression . * expression\n (6) expression -> expression . / expression\n\n + reduce using rule 6 (expression -> expression / expression .)\n - reduce using rule 6 (expression -> expression / expression .)\n * reduce using rule 6 (expression -> expression / expression .)\n / reduce using rule 6 (expression -> expression / expression .)\n $end reduce using rule 6 (expression -> expression / expression .)\n ) reduce using rule 6 (expression -> expression / expression .)\n\n ! + [ shift and go to state 12 ]\n ! - [ shift and go to state 11 ]\n ! * [ shift and go to state 13 ]\n ! / [ shift and go to state 14 ]\n\n",
"I don't know anything about its debugging features, but I've heard good things about PyParsing.\nhttp://pyparsing.wikispaces.com/\n",
"I know the bounty has already been claimed, but here is an equivalent parser written in pyparsing (plus support for function calls with zero or more comma-delimted arguments):\nfrom pyparsing import *\n\nLPAR, RPAR = map(Suppress,\"()\")\nEQ = Literal(\"=\")\nname = Word(alphas, alphanums+\"_\").setName(\"name\")\nnumber = Word(nums).setName(\"number\")\n\nexpr = Forward()\noperand = Optional('-') + (Group(name + LPAR + \n Group(Optional(delimitedList(expr))) +\n RPAR) |\n name | \n number | \n Group(LPAR + expr + RPAR))\nbinop = oneOf(\"+ - * / **\")\nexpr << (Group(operand + OneOrMore(binop + operand)) | operand)\n\nassignment = name + EQ + expr\nstatement = assignment | expr\n\nThis test code runs the parser through its basic paces:\ntests = \"\"\"\\\n sin(pi/2)\n y = mx+b\n E = mc ** 2\n F = m*a\n x = x0 + v*t +a*t*t/2\n 1 - sqrt(sin(t)**2 + cos(t)**2)\"\"\".splitlines()\n\nfor t in tests:\n print t.strip()\n print statement.parseString(t).asList()\n print\n\nGives this output:\nsin(pi/2)\n[['sin', [['pi', '/', '2']]]]\n\ny = mx+b\n['y', '=', ['mx', '+', 'b']]\n\nE = mc ** 2\n['E', '=', ['mc', '**', '2']]\n\nF = m*a\n['F', '=', ['m', '*', 'a']]\n\nx = x0 + v*t +a*t*t/2\n['x', '=', ['x0', '+', 'v', '*', 't', '+', 'a', '*', 't', '*', 't', '/', '2']]\n\n1 - sqrt(sin(t)**2 + cos(t)**2)\n[['1', '-', ['sqrt', [[['sin', ['t']], '**', '2', '+', ['cos', ['t']], '**', '2']]]]]\n\nFor debugging, we add this code:\n# enable debugging for name and number expressions\nname.setDebug()\nnumber.setDebug()\n\nAnd now we reparse the first test (displaying the input string and a simple column ruler):\nt = tests[0]\nprint (\"1234567890\"*10)[:len(t)]\nprint t\nstatement.parseString(t)\nprint\n\nGiving this output:\n1234567890123\n sin(pi/2)\nMatch name at loc 4(1,5)\nMatched name -> ['sin']\nMatch name at loc 4(1,5)\nMatched name -> ['sin']\nMatch name at loc 8(1,9)\nMatched name -> ['pi']\nMatch name at loc 8(1,9)\nMatched name -> ['pi']\nMatch name at loc 11(1,12)\nException raised:Expected name (at char 11), (line:1, col:12)\nMatch name at loc 11(1,12)\nException raised:Expected name (at char 11), (line:1, col:12)\nMatch number at loc 11(1,12)\nMatched number -> ['2']\nMatch name at loc 4(1,5)\nMatched name -> ['sin']\nMatch name at loc 8(1,9)\nMatched name -> ['pi']\nMatch name at loc 8(1,9)\nMatched name -> ['pi']\nMatch name at loc 11(1,12)\nException raised:Expected name (at char 11), (line:1, col:12)\nMatch name at loc 11(1,12)\nException raised:Expected name (at char 11), (line:1, col:12)\nMatch number at loc 11(1,12)\nMatched number -> ['2']\n\nPyparsing also supports packrat parsing, a sort of parse-time memoization (read more about packratting here). Here is the same parsing sequence, but with packrat enabled:\nsame parse, but with packrat parsing enabled\n1234567890123\n sin(pi/2)\nMatch name at loc 4(1,5)\nMatched name -> ['sin']\nMatch name at loc 8(1,9)\nMatched name -> ['pi']\nMatch name at loc 8(1,9)\nMatched name -> ['pi']\nMatch name at loc 11(1,12)\nException raised:Expected name (at char 11), (line:1, col:12)\nMatch name at loc 11(1,12)\nException raised:Expected name (at char 11), (line:1, col:12)\nMatch number at loc 11(1,12)\nMatched number -> ['2']\n\nThis was an interesting exercise, and helpful to me to see debugging features from other parser libraries.\n",
"ANTLR above has the advantage to generate human readable and understandable code,\nsince it is (a very sophisticated and powerful) top-down parser,\nso you can step through it with a regular debugger\nand see what it really is doing.\nThat's why it is my parser generator of choice.\nBottom up parser generators like PLY have the disadvantage\nthat for larger grammars it is almost impossible to understand\nwhat the debugging output really means and why the\nparsing table is like it is.\n",
"Python wiki has a list of Language Parsers written in Python.\n"
] |
[
6,
2,
2,
1,
0
] |
[] |
[] |
[
"debugging",
"parser_generator",
"python",
"ruby"
] |
stackoverflow_0000952648_debugging_parser_generator_python_ruby.txt
|
Q:
Extending Python and Objective-C
I'm a fan of clean code. I like my languages to be able to express what I'm trying to do, but I like the syntax to mirror that too.
For example, I work on a lot of programs in Objective-C for jailbroken iPhones, which patch other code using the method_setImplementation() function of the runtime. Or, in PyObjC, I have to use the syntax UIView.initWithFrame_(), which is also pretty awful and unreadable with the way the method names are structured. In both cases, the language does not support this in syntax. I've found three basic ways that this is done:
Insane macros. Take a look at this
"CaptainHook", it does what I'm
looking for in a usable way, but it
isn't quite clean and is a major
hack.
There's also "Logos", which
implements a very nice syntax, but is
written in Perl parsing my code with
a ton of regular expressions. This
scares me. I like the idea of adding
a %hook ClassName, but not by using
regular expressions to parse C or
Objective-C.
Finally, there is Cycript. This is an
extension to JavaScript which
interfaces with the Objective-C
runtime and allows you to use
Objective-C style code in your
JavaScript, and inject that into
other processes. This is likely the
cleanest as it actually uses a parser
for the JavaScript, but I'm not a
huge fan of that language in general.
Should, and how should, I create an extension to Python and Objective-C to allow me to do this? Is it worth writing a parser for my language to transform the syntax into something nicer, if it is only in a very specialized niche like this? Should I just live with the horrible syntax of the default Objective-C hooking or PyObjC?
A:
If you don't have any experience in compiler or interpreter design my answer is an emphatic NO, it is one of the biggest challenges in computer science.
If you do have experience my answer shifts to "that is a really dumb idea."
Do you envision this becoming a large mature product that other people will want to use? If you do than go ahead, otherwise it will just distract you from writing great applications.
A:
There are only two kinds of programming languages:, the truism goes, the ones every one complains about and the ones no one uses. People who want to make programs don't choose a language because it's beautiful or clean; they choose it because it is supported, available, and not so awful that you just can't use it.
When you see something you think you can improve, it can be very tempting to say I can fix that! and run right in, but in this case the cost is probably higher than is worth it. Programming languages that don't fill any bigger goal than being somewhat cleaner or a little more consistent tend not to catch on, as incremental advances in those areas aren't the things that you really, really need to improve the process of making software. Projects in obscure pet languages tend to die and not catch on, as the cost of contributing (learning someone's pet language that is new to you and that doesn't have broad support and documentation) is too high.
If you are interested in language design and tinkering, this could be interesting for you. It's harder than it may seem—the designers of all the major languages have had to deal with a lot of tradeoffs in designing them, often sacrificing beauty and purity for practicality and compatibility. If, on the other hand, you want to write software, deal with the imperfect tools you were dealt.
|
Extending Python and Objective-C
|
I'm a fan of clean code. I like my languages to be able to express what I'm trying to do, but I like the syntax to mirror that too.
For example, I work on a lot of programs in Objective-C for jailbroken iPhones, which patch other code using the method_setImplementation() function of the runtime. Or, in PyObjC, I have to use the syntax UIView.initWithFrame_(), which is also pretty awful and unreadable with the way the method names are structured. In both cases, the language does not support this in syntax. I've found three basic ways that this is done:
Insane macros. Take a look at this
"CaptainHook", it does what I'm
looking for in a usable way, but it
isn't quite clean and is a major
hack.
There's also "Logos", which
implements a very nice syntax, but is
written in Perl parsing my code with
a ton of regular expressions. This
scares me. I like the idea of adding
a %hook ClassName, but not by using
regular expressions to parse C or
Objective-C.
Finally, there is Cycript. This is an
extension to JavaScript which
interfaces with the Objective-C
runtime and allows you to use
Objective-C style code in your
JavaScript, and inject that into
other processes. This is likely the
cleanest as it actually uses a parser
for the JavaScript, but I'm not a
huge fan of that language in general.
Should, and how should, I create an extension to Python and Objective-C to allow me to do this? Is it worth writing a parser for my language to transform the syntax into something nicer, if it is only in a very specialized niche like this? Should I just live with the horrible syntax of the default Objective-C hooking or PyObjC?
|
[
"If you don't have any experience in compiler or interpreter design my answer is an emphatic NO, it is one of the biggest challenges in computer science.\nIf you do have experience my answer shifts to \"that is a really dumb idea.\"\nDo you envision this becoming a large mature product that other people will want to use? If you do than go ahead, otherwise it will just distract you from writing great applications.\n",
"There are only two kinds of programming languages:, the truism goes, the ones every one complains about and the ones no one uses. People who want to make programs don't choose a language because it's beautiful or clean; they choose it because it is supported, available, and not so awful that you just can't use it. \nWhen you see something you think you can improve, it can be very tempting to say I can fix that! and run right in, but in this case the cost is probably higher than is worth it. Programming languages that don't fill any bigger goal than being somewhat cleaner or a little more consistent tend not to catch on, as incremental advances in those areas aren't the things that you really, really need to improve the process of making software. Projects in obscure pet languages tend to die and not catch on, as the cost of contributing (learning someone's pet language that is new to you and that doesn't have broad support and documentation) is too high.\nIf you are interested in language design and tinkering, this could be interesting for you. It's harder than it may seem—the designers of all the major languages have had to deal with a lot of tradeoffs in designing them, often sacrificing beauty and purity for practicality and compatibility. If, on the other hand, you want to write software, deal with the imperfect tools you were dealt.\n"
] |
[
2,
1
] |
[] |
[] |
[
"objective_c",
"pyobjc",
"python"
] |
stackoverflow_0002474554_objective_c_pyobjc_python.txt
|
Q:
Python for a hobbyist programmer ( a few questions)
I'm a hobbyist programmer (only in TI-Basic before now), and after much, much, much debating with myself, I've decided to learn Python. I don't have a ton of free time to teach myself a hundred languages and all programming I do will be for personal use or for distributing to people who need them, so I decided that I needed one good, strong language to be good at. My questions:
Is python powerful enough to handle most things that a typical programmer might do in his off-time? I have in mind things like complex stat generators based on user input for tabletop games, making small games, automate install processes, and build interactive websites, but probably a hundred things along those lines
Does python handle networking tasks fairly well?
Can python source be obfuscated, or is it going to be open-source by nature? The reason I ask this is because if I make something cool and distribute it, I don't want some idiot script kiddie to edit his own name in and say he wrote it
And how popular is python, compared to other languages. Ideally, my language would be good and useful with help found online without extreme difficulty, but not so common that every idiot with computer knows python. I like the idea of knowing a slightly obscure language.
Thanks a ton for any help you can provide.
A:
Is python powerful enough to handle
most things?
Yes. Period. Study EveOnline game for more information. Look at pygame framework. Free free to use Google to find more.
Does python handle networking tasks
fairly well?
Yes. Look at the number of Python web frameworks plus the Twisted framework. Feel free to use Google to search for Python networking.
Can python source be obfuscated?
Not usefully. This isn't C.
And how popular is python, compared to
other languages?
Look at the TIOBE index.
A:
I think that Python is very powerful to do a lot of things, but just like Java and C++, it often depends on good third-party libraries. I come from a Java background but use Python for a lot of things, and it's been a fun ride. I've done things like statistics, and automation, not sure about the UI though that often depends on the toolkit more than the language.
Python networking works well. I don't know if I'd use it to build a fast algorithmic trading system or a VOIP application, but for most intents and purposes, especially at higher levels of abstraction, it's fine and easy to use. You would need external libraries for things like SSH or FTP.
Python is quite popular and has very good online support, active community, and major corporations (likeGoogle) that use it. I found the official online tutorial and reference to be excellent.
I have to say that I disagree with the "every idiot with a computer" line. There's a difference between knowing a language and using it right, and that's true about every language, even natural ones :) Python does have a lot of functional elements that are not as trivial to use for people coming from a procedural background, so there's always room for growth.
The one problem with Python compared to languages like C and Java is that it is not statically typed. This makes it much faster to write code, but also makes it *much easier) to make mistakes that can be quite nasty to debug. For instance, the same variable can contain a String reference at some point, and a reference to a list of strings at some other point.
A:
Absolutely.
What type of networking? It has socket, http, xml, smtp/pop, telnet, and much more built in.
Python obfuscation won't be nearly as good as a compiled language. Usually that isn't a problem.
It's the 9th most popular tag on stackoverflow, so there's plenty of help available.
A:
Is python powerful enough to handle most things that a typical programmer might do in his off-time? I have in mind things like complex stat generators based on user input for tabletop games, making small games, automate install processes, and build interactive websites, but probably a hundred things along those lines
Definitely. Python is a good tool for all of those except automating install processes, where it might be the right tool but more likely the right tool will likely be decided by what specifically you are automating.
Does python handle networking tasks fairly well?
Yes. You will want to look into Twisted.
Can python source be obfuscated, or is it going to be open-source by nature? The reason I ask this is because if I make something cool and distribute it, I don't want some idiot script kiddie to edit his own name in and say he wrote it
"Open source" refers to the licensing of your code, not the viewability of its source code. Hiding Python source code isn't especially possible, and the results of decompiling Python bytecode will result in much more readable code than the equivalent tools in languages like C. Don't worry about this! You can't prevent people from stealing your car or your computer if they are willing to break the law, and you can't do the same for your code in any language.
And how popular is python, compared to other languages. Ideally, my language would be good and useful with help found online without extreme difficulty, but not so common that every idiot with computer knows python. I like the idea of knowing a slightly obscure language.
This is an unanswerable question. Google will give you lots of conflicting results with different metrics, most of them useful. You're also being a bit silly ;)
As far as learning materials go, I recommend How to Think Like a Computer Scientist, which is a good text that does not presume any existing programming knowledge. It is available for free online, or you could buy a print copy if you prefer. (Don't bother learning 3.x yet. There is not enough library support to do much useful stuff like you want to do, and when there is picking it up will be a breeze; it's not very different than 2.5/6/7.)
A:
Probably yes. Maybe the stat crunching thing will be kinda slow, and maybe a game depending on what kind of game, but generally the performance is good enough, and you save a lot of time on the actual programming. If you REALLY need performance, you can make a module in C, but usually there is a library written to do what you want..
I haven't used it, but there's a framework called Twisted that seems to be pretty good.
No. Bytecode can be decompiled easily, and it only works on a specific version of Python, so your code isn't as portable.
Python is pretty popular, and the Python Package Index has a big list of third party libraries. It's not as widespread as, say, Java, but a lot of people use it and you can probably get answers for what you want.
A:
Points 1 and 2: HELL YEAH.
Point 4: kind of. Python is good at some network stuff. It's not Java or C++. Just use zlib (zip library) and pickle (serialization) for everything, and look at xmlrpclib if you need IPC.
Point 3: No. However, you can write C modules (for the performance critical, and hard-to-copy) parts of your code, and that would make it non-trivial to reverse-engineer.
A:
Python is up to the task (and better) for 1, 2 and 4.
The best solution for 3 from what you describe would probably be to make your programs really open-source with GPL or BSD like licence. This way people will edit your super-cool sources (but often experienced programmers, not just script kiddies) and build on then but leave your name in for posterity.
|
Python for a hobbyist programmer ( a few questions)
|
I'm a hobbyist programmer (only in TI-Basic before now), and after much, much, much debating with myself, I've decided to learn Python. I don't have a ton of free time to teach myself a hundred languages and all programming I do will be for personal use or for distributing to people who need them, so I decided that I needed one good, strong language to be good at. My questions:
Is python powerful enough to handle most things that a typical programmer might do in his off-time? I have in mind things like complex stat generators based on user input for tabletop games, making small games, automate install processes, and build interactive websites, but probably a hundred things along those lines
Does python handle networking tasks fairly well?
Can python source be obfuscated, or is it going to be open-source by nature? The reason I ask this is because if I make something cool and distribute it, I don't want some idiot script kiddie to edit his own name in and say he wrote it
And how popular is python, compared to other languages. Ideally, my language would be good and useful with help found online without extreme difficulty, but not so common that every idiot with computer knows python. I like the idea of knowing a slightly obscure language.
Thanks a ton for any help you can provide.
|
[
"\nIs python powerful enough to handle\n most things?\n\nYes. Period. Study EveOnline game for more information. Look at pygame framework. Free free to use Google to find more.\n\nDoes python handle networking tasks\n fairly well?\n\nYes. Look at the number of Python web frameworks plus the Twisted framework. Feel free to use Google to search for Python networking.\n\nCan python source be obfuscated?\n\nNot usefully. This isn't C.\n\nAnd how popular is python, compared to\n other languages?\n\nLook at the TIOBE index.\n",
"I think that Python is very powerful to do a lot of things, but just like Java and C++, it often depends on good third-party libraries. I come from a Java background but use Python for a lot of things, and it's been a fun ride. I've done things like statistics, and automation, not sure about the UI though that often depends on the toolkit more than the language. \nPython networking works well. I don't know if I'd use it to build a fast algorithmic trading system or a VOIP application, but for most intents and purposes, especially at higher levels of abstraction, it's fine and easy to use. You would need external libraries for things like SSH or FTP.\nPython is quite popular and has very good online support, active community, and major corporations (likeGoogle) that use it. I found the official online tutorial and reference to be excellent. \nI have to say that I disagree with the \"every idiot with a computer\" line. There's a difference between knowing a language and using it right, and that's true about every language, even natural ones :) Python does have a lot of functional elements that are not as trivial to use for people coming from a procedural background, so there's always room for growth. \nThe one problem with Python compared to languages like C and Java is that it is not statically typed. This makes it much faster to write code, but also makes it *much easier) to make mistakes that can be quite nasty to debug. For instance, the same variable can contain a String reference at some point, and a reference to a list of strings at some other point. \n",
"\nAbsolutely.\nWhat type of networking? It has socket, http, xml, smtp/pop, telnet, and much more built in.\nPython obfuscation won't be nearly as good as a compiled language. Usually that isn't a problem.\nIt's the 9th most popular tag on stackoverflow, so there's plenty of help available.\n\n",
"\nIs python powerful enough to handle most things that a typical programmer might do in his off-time? I have in mind things like complex stat generators based on user input for tabletop games, making small games, automate install processes, and build interactive websites, but probably a hundred things along those lines\n\nDefinitely. Python is a good tool for all of those except automating install processes, where it might be the right tool but more likely the right tool will likely be decided by what specifically you are automating.\n\nDoes python handle networking tasks fairly well?\n\nYes. You will want to look into Twisted.\n\nCan python source be obfuscated, or is it going to be open-source by nature? The reason I ask this is because if I make something cool and distribute it, I don't want some idiot script kiddie to edit his own name in and say he wrote it\n\n\"Open source\" refers to the licensing of your code, not the viewability of its source code. Hiding Python source code isn't especially possible, and the results of decompiling Python bytecode will result in much more readable code than the equivalent tools in languages like C. Don't worry about this! You can't prevent people from stealing your car or your computer if they are willing to break the law, and you can't do the same for your code in any language.\n\nAnd how popular is python, compared to other languages. Ideally, my language would be good and useful with help found online without extreme difficulty, but not so common that every idiot with computer knows python. I like the idea of knowing a slightly obscure language.\n\nThis is an unanswerable question. Google will give you lots of conflicting results with different metrics, most of them useful. You're also being a bit silly ;)\n\nAs far as learning materials go, I recommend How to Think Like a Computer Scientist, which is a good text that does not presume any existing programming knowledge. It is available for free online, or you could buy a print copy if you prefer. (Don't bother learning 3.x yet. There is not enough library support to do much useful stuff like you want to do, and when there is picking it up will be a breeze; it's not very different than 2.5/6/7.)\n",
"\nProbably yes. Maybe the stat crunching thing will be kinda slow, and maybe a game depending on what kind of game, but generally the performance is good enough, and you save a lot of time on the actual programming. If you REALLY need performance, you can make a module in C, but usually there is a library written to do what you want..\nI haven't used it, but there's a framework called Twisted that seems to be pretty good.\nNo. Bytecode can be decompiled easily, and it only works on a specific version of Python, so your code isn't as portable.\nPython is pretty popular, and the Python Package Index has a big list of third party libraries. It's not as widespread as, say, Java, but a lot of people use it and you can probably get answers for what you want.\n\n",
"Points 1 and 2: HELL YEAH.\nPoint 4: kind of. Python is good at some network stuff. It's not Java or C++. Just use zlib (zip library) and pickle (serialization) for everything, and look at xmlrpclib if you need IPC.\nPoint 3: No. However, you can write C modules (for the performance critical, and hard-to-copy) parts of your code, and that would make it non-trivial to reverse-engineer.\n",
"Python is up to the task (and better) for 1, 2 and 4.\nThe best solution for 3 from what you describe would probably be to make your programs really open-source with GPL or BSD like licence. This way people will edit your super-cool sources (but often experienced programmers, not just script kiddies) and build on then but leave your name in for posterity.\n"
] |
[
14,
6,
4,
3,
2,
0,
0
] |
[] |
[] |
[
"networking",
"programming_languages",
"python",
"robust"
] |
stackoverflow_0002474224_networking_programming_languages_python_robust.txt
|
Q:
How do I set prifix to django contrib tables names?
HI
One of my requirement is to have prefix on all the tables of the django based project (Because db is hosted on shared server). I have used db_table Meta option to set the prefix for the tables which I have created.
Now my query is how do I set the prefix for tables provided by django.contrib.
Instead of auth_group django should create prefix_auth_group.... How do I do that?
Thank you very much...
A:
From reading this ticket, I would say it is not possible without a hack.
|
How do I set prifix to django contrib tables names?
|
HI
One of my requirement is to have prefix on all the tables of the django based project (Because db is hosted on shared server). I have used db_table Meta option to set the prefix for the tables which I have created.
Now my query is how do I set the prefix for tables provided by django.contrib.
Instead of auth_group django should create prefix_auth_group.... How do I do that?
Thank you very much...
|
[
"From reading this ticket, I would say it is not possible without a hack.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002475215_django_django_models_python.txt
|
Q:
Modules for Python that can be used as a TFTP server
Are there any modules for Python, that can be used as a TFTP server? I tried Tftpy, but when I try to upload something, it says:
ERROR:tftpy:Write requests not implemented at this time.
In fact, that's the only function that I need.
A:
You may try tftpgui from http://code.google.com/p/tftpgui/ but it's GPL'ed.
UPD: uploading is available starting with TFTPy 0.5.0+
UPD2: I personally found PyPXE minimal hackish TFTP implementation sufficient for bootstrapping virtual machines. If your use case the same as mine - use that.
|
Modules for Python that can be used as a TFTP server
|
Are there any modules for Python, that can be used as a TFTP server? I tried Tftpy, but when I try to upload something, it says:
ERROR:tftpy:Write requests not implemented at this time.
In fact, that's the only function that I need.
|
[
"You may try tftpgui from http://code.google.com/p/tftpgui/ but it's GPL'ed.\nUPD: uploading is available starting with TFTPy 0.5.0+\nUPD2: I personally found PyPXE minimal hackish TFTP implementation sufficient for bootstrapping virtual machines. If your use case the same as mine - use that.\n"
] |
[
4
] |
[] |
[] |
[
"python",
"tftp"
] |
stackoverflow_0002469632_python_tftp.txt
|
Q:
construct graph from python set type
The short question, is there an off the self function to make a graph from a collection of python sets?
The longer question: I have several python sets. They each overlap or some are sub sets of others. I would like to make a graph (as in nodes and edges) nodes are the elements in the sets. The edges are intersection of the sets with weighted by number of elements in the intersection of the sets. There are several graphing packages for python. (NetworkX, igraph,...) I am not familiar with the use of any of them. Will any of them make a graph directly from a list of sets ie, MakeGraphfromSets(alistofsets)
If not do you know of an example of how to take the list of sets to define the edges. It actually looks like it might be straight forward but an example is always good to have.
A:
It's not too hard to code yourself:
def intersection_graph(sets):
adjacency_list = {}
for i, s1 in enumerate(sets):
for j, s2 in enumerate(sets):
if j == i:
continue
try:
lst = adjacency_list[i]
except KeyError:
adjacency_list[i] = lst = []
weight = len(s1.intersection(s2))
lst.append( (j, weight) )
return adjacency_list
This function numbers each set with its index within sets. We do this because dict keys must be immutable, which is true of integers but not sets.
Here's an example of how to use this function, and it's output:
>>> sets = [set([1,2,3]), set([2,3,4]), set([4,2])]
>>> intersection_graph(sets)
{0: [(1, 2), (2, 1)], 1: [(0, 2), (2, 2)], 2: [(0, 1), (1, 2)]}
A:
def MakeGraphfromSets(sets):
egs = []
l = len(sets)
for i in range(l):
for j in range(i,l):
w = sets[i].intersection(sets[j])
egs.append((i,j,len(w)))
return egs
# (source set index,destination set index,length of intersection)
sets = [set([1,2,3]), set([2,3,4]), set([4,2])]
edges = MakeGraphfromSets(sets)
for e in edges:
print e
OUTPUT:
(0, 0, 3)
(0, 1, 2)
(0, 2, 1)
(1, 1, 3)
(1, 2, 2)
(2, 2, 2)
|
construct graph from python set type
|
The short question, is there an off the self function to make a graph from a collection of python sets?
The longer question: I have several python sets. They each overlap or some are sub sets of others. I would like to make a graph (as in nodes and edges) nodes are the elements in the sets. The edges are intersection of the sets with weighted by number of elements in the intersection of the sets. There are several graphing packages for python. (NetworkX, igraph,...) I am not familiar with the use of any of them. Will any of them make a graph directly from a list of sets ie, MakeGraphfromSets(alistofsets)
If not do you know of an example of how to take the list of sets to define the edges. It actually looks like it might be straight forward but an example is always good to have.
|
[
"It's not too hard to code yourself:\ndef intersection_graph(sets):\n adjacency_list = {}\n for i, s1 in enumerate(sets):\n for j, s2 in enumerate(sets):\n if j == i:\n continue\n try:\n lst = adjacency_list[i]\n except KeyError:\n adjacency_list[i] = lst = []\n weight = len(s1.intersection(s2))\n lst.append( (j, weight) )\n return adjacency_list\n\nThis function numbers each set with its index within sets. We do this because dict keys must be immutable, which is true of integers but not sets.\nHere's an example of how to use this function, and it's output:\n>>> sets = [set([1,2,3]), set([2,3,4]), set([4,2])]\n>>> intersection_graph(sets)\n{0: [(1, 2), (2, 1)], 1: [(0, 2), (2, 2)], 2: [(0, 1), (1, 2)]}\n\n",
" \ndef MakeGraphfromSets(sets):\n egs = []\n l = len(sets)\n for i in range(l):\n for j in range(i,l):\n w = sets[i].intersection(sets[j])\n egs.append((i,j,len(w)))\n return egs\n\n# (source set index,destination set index,length of intersection)\n\nsets = [set([1,2,3]), set([2,3,4]), set([4,2])]\n\nedges = MakeGraphfromSets(sets)\n\nfor e in edges:\n print e\n\nOUTPUT:\n(0, 0, 3)\n(0, 1, 2)\n(0, 2, 1)\n(1, 1, 3)\n(1, 2, 2)\n(2, 2, 2)\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"edges",
"graph",
"nodes",
"python",
"set"
] |
stackoverflow_0002475176_edges_graph_nodes_python_set.txt
|
Q:
C/C++ for Core Logic Development of a Web Application?
Can C/C++ be choice of keeping all your logic (business/domain) for web application?
Why?
I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript.
We like to utilize our free time to work on our some good ideas we developed together. The ideas require knowledge of web application development. And I'm the only one who has it.
Is there a way they developed the core in C/C++ and I do the rest of scripting for front-end development?
Thanks.
A:
C/C++ and Python can be integrated fairly easily, but Python really should be a snap for anyone that knows C well to pick up in a week.
A:
I don't think you should use a compiled language (at least not c++) for web programming. I thought about doing this once too but remember that for any change you'll have to compile etc.
Facebook uses php and it's hip hop application changes php into c++. Maybe you should take a look at that.
Of course c++ (or any compiled language) will be faster than an interpreted language, but you also have to take in account the development time of the web site/app.
Hope this helps :)
A:
cython http://wwww.cython.org is a nice way to interface python and C/C++
|
C/C++ for Core Logic Development of a Web Application?
|
Can C/C++ be choice of keeping all your logic (business/domain) for web application?
Why?
I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript.
We like to utilize our free time to work on our some good ideas we developed together. The ideas require knowledge of web application development. And I'm the only one who has it.
Is there a way they developed the core in C/C++ and I do the rest of scripting for front-end development?
Thanks.
|
[
"C/C++ and Python can be integrated fairly easily, but Python really should be a snap for anyone that knows C well to pick up in a week.\n",
"I don't think you should use a compiled language (at least not c++) for web programming. I thought about doing this once too but remember that for any change you'll have to compile etc.\nFacebook uses php and it's hip hop application changes php into c++. Maybe you should take a look at that.\nOf course c++ (or any compiled language) will be faster than an interpreted language, but you also have to take in account the development time of the web site/app.\nHope this helps :)\n",
"cython http://wwww.cython.org is a nice way to interface python and C/C++\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"c",
"c++",
"python"
] |
stackoverflow_0002467807_c_c++_python.txt
|
Q:
What should I learn & use to become a pro in PHP & Python Web development?
I'll just show some code to show how I do web development in PHP.
<html>
<head>
<title>Example #3 TDavid's Very First PHP Script ever!</title>
</head>
<? print(Date("m/j/y"));
require_once("somefile.php");
$mysql_db = "DATABASE NAME";
$mysql_user = "YOUR MYSQL USERNAME";
$mysql_pass = "YOUR MYSQL PASSWORD";
$mysql_link = mysql_connect("localhost", $mysql_user, $mysql_pass);
mysql_select_db($mysql_db, $mysql_link);
$result = mysql_query("SELECT impressions from tds_counter where COUNT_ID='$cid'", $mysql_link);
if(mysql_num_rows($result)) {
mysql_query("UPDATE tds_counter set impressions=impressions+1 where COUNT_ID='$cid'", $mysql_link);
$row = mysql_fetch_row($result);
if(!$inv) {
print("$row[0]");
}
}
?>
<body>
</body>
</html>
Thats it. I write every file like this. Recently, I learnt OOP and started using classes & objects in PHP.
I hear that there are many frameworks there for PHP. They say that one must use these libraries. But I feel they are just making things complicated.
Anyway, this is how I've been doing my web development. Now, I want to improve this. and make it professional. Also I want to move to Python. I searched SO archives and found everyone suggesting Django. But, can any one give me some idea about how web development in Python works?
user (client) request for page --->
webserver(->embedded PHP interpreter)
----> Server side(PHP) Script ---> MySQL Server.
Now, is it that instead of PHP interpreter there is python interpreter & instead of php script there is python script, which contains both HTML & python (embedded in some kind of python tags). Python script connects to database server and fetches some data which will be printed as HTML. or is it different in python world?
Is this Django thing like frameworks for PHP? Can't one code in python without using Django. Because, I never encountered any post without django
Please give me some kick start.
A:
PHP was built for making web pages, so a lot of the infrastructure is already set up for you. Python was built more as a general-purpose scripting language so you need a bit of extra infrastructure to handle requests and produce web pages.
There are multiple frameworks for Python. Django is the most popular but Pylons is another good one. Have a look at this list of Web Frameworks for Python:
A web application may use a
combination of a base HTTP application
server, a storage mechanism such as a
database, a template engine, a request
dispatcher, an authentication module
and an AJAX toolkit. These can be
individual components or be provided
together in a high-level framework.
These are the most popular high-level
frameworks. Many of them include
components listed on the WebComponents
page.
Django (1.1 Released 2009-07-29) a
high-level Python Web framework that
encourages rapid development and
clean, pragmatic design
Grok (1.0 Released 2009-10-07) is
built on the existing Zope 3
libraries, but aims to provide an
easier learning curve and a more agile
development experience. It does this
by placing an emphasis on convention
over configuration and DRY (Don't
Repeat Yourself).
Pylons (0.9.7 Released 2009-02-23) a
lightweight Web framework emphasizing
flexibility and rapid development. It
combines the very best ideas from the
worlds of Ruby, Python and Perl,
providing a structured but extremely
flexible Python Web framework. It's
also one of the first projects to
leverage the emerging WSGI standard,
which allows extensive re-use and
flexibility but only if you need it.
Out of the box, Pylons aims to make
Web development fast, flexible and
easy. Pylons is built on top of Paste
(see below).
TurboGears (2.0 Released 2009-05-27)
the rapid Web development
megaframework you've been looking for.
Combines CherryPy, Kid, SQLAlchemy and
MochiKit. Create a database-driven,
ready-to-extend application in
minutes. All with designer friendly
templates, easy AJAX on the browser
side and on the server side, with an
incredibly powerful and flexible
Object Relational Mapper (ORM), and
with code that is as natural as
writing a function. After reviewing
the website check out: QuickStart
Manual
web2py (1.72.3 Released 2009-11-10)
All in one package with no further
dependencies. Development, deployment,
debugging, testing, database
administration and maintenance of
applications can be done via the
provided web interface. web2py has no
configuration files, requires no
installation, can be run off a USB
drive. web2py uses Python for the
Model, the Views and the Controllers,
has a built-in ticketing system to
manage errors, an internationalization
engine, works with MySQL, PostgreSQL,
SQLite , Oracle, MSSQL and the Google
App Engine via an ORM abstraction
layer. web2py includes libraries to
handle HTML/XML, RSS, ATOM, CSV, RTF,
JSON, AJAX, XMLRPC, WIKI markup.
Production ready, capable of
upload/download of very large files,
and always backward compatible.
Zope (2.10.7 Released 2008-10-25,
2.11.2 Released 2008-25-10, Zope 3.4.0 Released 2009-01-29) Being the
grandaddy of Python web frameworks,
Zope has grown into a family of
frameworks over the years. Zope 1 was
released in 1999. Zope 2 is both a web
framework and a general purpose
application server, today it is
primarily used by
ContentManagementSystems
A:
But, can any one give me some idea
about how web development in Python
works?
user (client) request for page ---> webserver(->embedded PHP interpreter) ----> Server side(PHP) Script ---> MySQL Server.
Now, is it that instead of PHP
interpreter there is python
interpreter & instead of php script
there is python script, which contains
both HTML & python (embedded in some
kind of python tags). Python script
connects to database server and
fetches some data which will be
printed as HTML. or is it different in
python world?
Here is how Django works:
User requests page.
Depending on the URL, the server calls a Python function (you configure this with regular expressions).
The Python function performs any work that needs to be done, typically fetching some data from a database.
It then calls a template, which basically is a HTML page with placeholders for actual data.
The template engine generates a HTML page from the template and the data.
This page is sent to the client.
As you can see, a main difference is that data logic and presentation are clearly separated (it's possible in PHP as well, but not enforced at all).
A:
One thing you could improve in your code sample: don't repeat yourself.
You say you do every file like the above? If so, then you have your database password in every file, and the code to create a connection is repeated over and over. That's clutter, and if your database password ever changes, you've got a lot of files to update!
This would be an improvement:
require_once("database_connection.php");
//Write function in above file that returns database connection.
//That will be the only place you need to give the database name and login.
//Use PDO so that you can use a different database type later if you like, and
//so you get better capabilities
$dbc = default_db_connection();
//If using PDO, you can use parameterized queries
$query = "INSERT INTO `ninjaturtles` (`name`, `weapon`, `color`) ";
$query .= "VALUES (:name, :weapon, :color)";
//OO style, tells database "I'm going to send a query that looks like the above;
//I'll tell you what data to plug in for those variables in a second."
$st = $dbc->prepare($query);
//Now you tell the database to plug in the following values and run the query.
//User-entered values are automatically escaped and can't possibly screw with
//the query structure - a huge security benefit - see bobby-tables.com
//Also, you can re-run this command by calling execute again with different
// values - faster than starting a new query from scratch
$st->execute(array(
':name' => $_POST['name'],
':weapon' => $_POST['weapon'],
':color' => $_POST['color']
));
PDO also gives you (I think) a nice syntax for simple queries:
$query = "SELECT `speed`, `tenacity` FROM `badgers`";
$st=$dbc->query($query);
foreach($st->fetchall() as $row){
echo 'Speed: ' . $row[`speed`] . '<br />';
echo 'Tenacity: ' . $row[`tenacity`] . '<br />';
}
A:
My recommendation and the book im actually reading http://books.google.com/books?id=uaZQAAAAMAAJ&q=advanced+php+programming&dq=advanced+php+programming&hl=es&ei=Nk2jS8H_EZHx4gb196n4CQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CC4Q6AEwAA
A:
There are many PHP frameworks resembling Django. I suggest you try one of them.
Like Zend or CodeIgniter.
|
What should I learn & use to become a pro in PHP & Python Web development?
|
I'll just show some code to show how I do web development in PHP.
<html>
<head>
<title>Example #3 TDavid's Very First PHP Script ever!</title>
</head>
<? print(Date("m/j/y"));
require_once("somefile.php");
$mysql_db = "DATABASE NAME";
$mysql_user = "YOUR MYSQL USERNAME";
$mysql_pass = "YOUR MYSQL PASSWORD";
$mysql_link = mysql_connect("localhost", $mysql_user, $mysql_pass);
mysql_select_db($mysql_db, $mysql_link);
$result = mysql_query("SELECT impressions from tds_counter where COUNT_ID='$cid'", $mysql_link);
if(mysql_num_rows($result)) {
mysql_query("UPDATE tds_counter set impressions=impressions+1 where COUNT_ID='$cid'", $mysql_link);
$row = mysql_fetch_row($result);
if(!$inv) {
print("$row[0]");
}
}
?>
<body>
</body>
</html>
Thats it. I write every file like this. Recently, I learnt OOP and started using classes & objects in PHP.
I hear that there are many frameworks there for PHP. They say that one must use these libraries. But I feel they are just making things complicated.
Anyway, this is how I've been doing my web development. Now, I want to improve this. and make it professional. Also I want to move to Python. I searched SO archives and found everyone suggesting Django. But, can any one give me some idea about how web development in Python works?
user (client) request for page --->
webserver(->embedded PHP interpreter)
----> Server side(PHP) Script ---> MySQL Server.
Now, is it that instead of PHP interpreter there is python interpreter & instead of php script there is python script, which contains both HTML & python (embedded in some kind of python tags). Python script connects to database server and fetches some data which will be printed as HTML. or is it different in python world?
Is this Django thing like frameworks for PHP? Can't one code in python without using Django. Because, I never encountered any post without django
Please give me some kick start.
|
[
"PHP was built for making web pages, so a lot of the infrastructure is already set up for you. Python was built more as a general-purpose scripting language so you need a bit of extra infrastructure to handle requests and produce web pages.\nThere are multiple frameworks for Python. Django is the most popular but Pylons is another good one. Have a look at this list of Web Frameworks for Python:\n\nA web application may use a\n combination of a base HTTP application\n server, a storage mechanism such as a\n database, a template engine, a request\n dispatcher, an authentication module\n and an AJAX toolkit. These can be\n individual components or be provided\n together in a high-level framework.\nThese are the most popular high-level\n frameworks. Many of them include\n components listed on the WebComponents\n page.\n\nDjango (1.1 Released 2009-07-29) a\n high-level Python Web framework that\n encourages rapid development and\n clean, pragmatic design\nGrok (1.0 Released 2009-10-07) is\n built on the existing Zope 3\n libraries, but aims to provide an\n easier learning curve and a more agile\n development experience. It does this\n by placing an emphasis on convention\n over configuration and DRY (Don't\n Repeat Yourself).\nPylons (0.9.7 Released 2009-02-23) a\n lightweight Web framework emphasizing\n flexibility and rapid development. It\n combines the very best ideas from the\n worlds of Ruby, Python and Perl,\n providing a structured but extremely\n flexible Python Web framework. It's\n also one of the first projects to\n leverage the emerging WSGI standard,\n which allows extensive re-use and\n flexibility but only if you need it.\n Out of the box, Pylons aims to make\n Web development fast, flexible and\n easy. Pylons is built on top of Paste\n (see below).\nTurboGears (2.0 Released 2009-05-27)\n the rapid Web development\n megaframework you've been looking for.\n Combines CherryPy, Kid, SQLAlchemy and\n MochiKit. Create a database-driven,\n ready-to-extend application in\n minutes. All with designer friendly\n templates, easy AJAX on the browser\n side and on the server side, with an\n incredibly powerful and flexible\n Object Relational Mapper (ORM), and\n with code that is as natural as\n writing a function. After reviewing\n the website check out: QuickStart\n Manual\nweb2py (1.72.3 Released 2009-11-10)\n All in one package with no further\n dependencies. Development, deployment,\n debugging, testing, database\n administration and maintenance of\n applications can be done via the\n provided web interface. web2py has no\n configuration files, requires no\n installation, can be run off a USB\n drive. web2py uses Python for the\n Model, the Views and the Controllers,\n has a built-in ticketing system to\n manage errors, an internationalization\n engine, works with MySQL, PostgreSQL,\n SQLite , Oracle, MSSQL and the Google\n App Engine via an ORM abstraction\n layer. web2py includes libraries to\n handle HTML/XML, RSS, ATOM, CSV, RTF,\n JSON, AJAX, XMLRPC, WIKI markup.\n Production ready, capable of\n upload/download of very large files,\n and always backward compatible.\nZope (2.10.7 Released 2008-10-25,\n 2.11.2 Released 2008-25-10, Zope 3.4.0 Released 2009-01-29) Being the\n grandaddy of Python web frameworks,\n Zope has grown into a family of\n frameworks over the years. Zope 1 was\n released in 1999. Zope 2 is both a web\n framework and a general purpose\n application server, today it is\n primarily used by\n ContentManagementSystems\n\n\n",
"\nBut, can any one give me some idea\nabout how web development in Python\nworks?\n\nuser (client) request for page ---> webserver(->embedded PHP interpreter) ----> Server side(PHP) Script ---> MySQL Server.\n\nNow, is it that instead of PHP\ninterpreter there is python\ninterpreter & instead of php script\nthere is python script, which contains\nboth HTML & python (embedded in some\nkind of python tags). Python script\nconnects to database server and\nfetches some data which will be\nprinted as HTML. or is it different in\npython world?\n\nHere is how Django works:\n\nUser requests page.\nDepending on the URL, the server calls a Python function (you configure this with regular expressions).\nThe Python function performs any work that needs to be done, typically fetching some data from a database.\nIt then calls a template, which basically is a HTML page with placeholders for actual data.\nThe template engine generates a HTML page from the template and the data.\nThis page is sent to the client.\n\nAs you can see, a main difference is that data logic and presentation are clearly separated (it's possible in PHP as well, but not enforced at all).\n",
"One thing you could improve in your code sample: don't repeat yourself.\nYou say you do every file like the above? If so, then you have your database password in every file, and the code to create a connection is repeated over and over. That's clutter, and if your database password ever changes, you've got a lot of files to update!\nThis would be an improvement:\nrequire_once(\"database_connection.php\");\n//Write function in above file that returns database connection.\n//That will be the only place you need to give the database name and login.\n//Use PDO so that you can use a different database type later if you like, and\n//so you get better capabilities\n$dbc = default_db_connection();\n//If using PDO, you can use parameterized queries \n$query = \"INSERT INTO `ninjaturtles` (`name`, `weapon`, `color`) \";\n$query .= \"VALUES (:name, :weapon, :color)\";\n//OO style, tells database \"I'm going to send a query that looks like the above;\n//I'll tell you what data to plug in for those variables in a second.\"\n$st = $dbc->prepare($query);\n//Now you tell the database to plug in the following values and run the query.\n//User-entered values are automatically escaped and can't possibly screw with\n//the query structure - a huge security benefit - see bobby-tables.com\n//Also, you can re-run this command by calling execute again with different\n// values - faster than starting a new query from scratch\n$st->execute(array(\n ':name' => $_POST['name'],\n ':weapon' => $_POST['weapon'],\n ':color' => $_POST['color']\n ));\n\nPDO also gives you (I think) a nice syntax for simple queries:\n$query = \"SELECT `speed`, `tenacity` FROM `badgers`\";\n$st=$dbc->query($query);\nforeach($st->fetchall() as $row){\n echo 'Speed: ' . $row[`speed`] . '<br />';\n echo 'Tenacity: ' . $row[`tenacity`] . '<br />';\n}\n\n",
"My recommendation and the book im actually reading http://books.google.com/books?id=uaZQAAAAMAAJ&q=advanced+php+programming&dq=advanced+php+programming&hl=es&ei=Nk2jS8H_EZHx4gb196n4CQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CC4Q6AEwAA\n",
"There are many PHP frameworks resembling Django. I suggest you try one of them.\nLike Zend or CodeIgniter.\n"
] |
[
3,
2,
1,
0,
0
] |
[] |
[] |
[
"php",
"python"
] |
stackoverflow_0002476335_php_python.txt
|
Q:
python Illegal instruction on AIX5.2
I run my python script functions like this:
read from a text file, and store the data as dict. But when in the loop, an Illegal instruction occurs. why this happens?
the code is like this:
d={}
datafile=open('a.txt') # a big text file
for line in datafile:
line=line.rstrip('\n')
for token in line.split():
print("Parsing line %d." % token[0])
d[(int(token[0]))]=token[1:]
then the message is like this:
Parsing line 1.
Parsing line 2.
............
Parsing line 1064
Parsing line 1065
Illegal instruction
what's the problem? my platform is python 2.6.2 on AIX 5.2.
please help me, thanks!
A:
This looks very wrong. token is a string in an array of strings returned by line.split(). So token[0] is the first character of that string. Therefore I don't believe that you'll ever get anything like Parsing line 1065 in your output. As Mark wrote, you'd see a TypeError.
Please post
the real code
the real data (an excerpt of the first few lines and line 1065/1066 would suffice)
the real error message.
Otherwise there's no way to help you.
|
python Illegal instruction on AIX5.2
|
I run my python script functions like this:
read from a text file, and store the data as dict. But when in the loop, an Illegal instruction occurs. why this happens?
the code is like this:
d={}
datafile=open('a.txt') # a big text file
for line in datafile:
line=line.rstrip('\n')
for token in line.split():
print("Parsing line %d." % token[0])
d[(int(token[0]))]=token[1:]
then the message is like this:
Parsing line 1.
Parsing line 2.
............
Parsing line 1064
Parsing line 1065
Illegal instruction
what's the problem? my platform is python 2.6.2 on AIX 5.2.
please help me, thanks!
|
[
"This looks very wrong. token is a string in an array of strings returned by line.split(). So token[0] is the first character of that string. Therefore I don't believe that you'll ever get anything like Parsing line 1065 in your output. As Mark wrote, you'd see a TypeError. \nPlease post \n\nthe real code\nthe real data (an excerpt of the first few lines and line 1065/1066 would suffice)\nthe real error message.\n\nOtherwise there's no way to help you.\n"
] |
[
3
] |
[] |
[] |
[
"aix",
"python"
] |
stackoverflow_0002476881_aix_python.txt
|
Q:
Python app engine put(self):
I am using this middleware to make my app restful, but it looks like my form parameters are not coming through:
from google.appengine.ext import webapp
class RestHTTPMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
method = webapp.Request(environ).get('_method')
request = Request(environ)
environ['wsgi.input'] = StringIO.StringIO(request.body)
if method:
environ['REQUEST_METHOD'] = method.upper()
return self.app(environ, start_response)
when I submit a form and the debug it using:
def put(self):
logging.debug(self.request.get('description'))
the logger is empty. The put(self) method is being called, I have tested it using the logger and my debug message is shown.
2nd revision:
from google.appengine.ext import webapp
from webob import Request
import logging
import StringIO
class RestHTTPMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
request = Request(environ)
environ['wsgi.input'] = StringIO.StringIO(request.body)
method = webapp.Request(environ).get('_method')
if method:
environ['REQUEST_METHOD'] = method.upper()
return self.app(environ, start_response)
Latest changes:
from google.appengine.ext import webapp
from webob import Request
import logging
import StringIO
class RestHTTPMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
request = Request(environ)
body = StringIO.StringIO(request.body)
method = webapp.Request(environ).get('_method', None)
if method:
environ['REQUEST_METHOD'] = method.upper()
environ['wsgi.input'] = body
return self.app(environ, start_response)
A:
Instantiating webapp.Request and calling .get on it causes it to read the request body and parse form parameters in it. When your actual webapp starts later, it instantiates another request object, and once again tries to read the request body - but it's already been read, so nothing is returned.
You could modify your middleware to store a copy of the request body and put it back in the WSGI environment. There are other options:
If the _method arg will always be a query string parameter instead of a posted form parameter, you can use webapp.Request(environ).GET.get('method'), which won't read the request body.
You could override WSGIApplication.call to change how it does dispatch.
You could subclass WSGIApplication and supply a custom REQUEST_CLASS, being a function that builds a real request object, then modifies the environment that was passed in to suit you (hack!).
You could define a custom webapp RequestHandler base class that implements initialize(), reaching in to the request object's WSGI dict and changing the method (hack!).
|
Python app engine put(self):
|
I am using this middleware to make my app restful, but it looks like my form parameters are not coming through:
from google.appengine.ext import webapp
class RestHTTPMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
method = webapp.Request(environ).get('_method')
request = Request(environ)
environ['wsgi.input'] = StringIO.StringIO(request.body)
if method:
environ['REQUEST_METHOD'] = method.upper()
return self.app(environ, start_response)
when I submit a form and the debug it using:
def put(self):
logging.debug(self.request.get('description'))
the logger is empty. The put(self) method is being called, I have tested it using the logger and my debug message is shown.
2nd revision:
from google.appengine.ext import webapp
from webob import Request
import logging
import StringIO
class RestHTTPMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
request = Request(environ)
environ['wsgi.input'] = StringIO.StringIO(request.body)
method = webapp.Request(environ).get('_method')
if method:
environ['REQUEST_METHOD'] = method.upper()
return self.app(environ, start_response)
Latest changes:
from google.appengine.ext import webapp
from webob import Request
import logging
import StringIO
class RestHTTPMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
request = Request(environ)
body = StringIO.StringIO(request.body)
method = webapp.Request(environ).get('_method', None)
if method:
environ['REQUEST_METHOD'] = method.upper()
environ['wsgi.input'] = body
return self.app(environ, start_response)
|
[
"Instantiating webapp.Request and calling .get on it causes it to read the request body and parse form parameters in it. When your actual webapp starts later, it instantiates another request object, and once again tries to read the request body - but it's already been read, so nothing is returned.\nYou could modify your middleware to store a copy of the request body and put it back in the WSGI environment. There are other options:\n\nIf the _method arg will always be a query string parameter instead of a posted form parameter, you can use webapp.Request(environ).GET.get('method'), which won't read the request body.\nYou could override WSGIApplication.call to change how it does dispatch.\nYou could subclass WSGIApplication and supply a custom REQUEST_CLASS, being a function that builds a real request object, then modifies the environment that was passed in to suit you (hack!).\nYou could define a custom webapp RequestHandler base class that implements initialize(), reaching in to the request object's WSGI dict and changing the method (hack!).\n\n"
] |
[
4
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002460431_google_app_engine_python.txt
|
Q:
Game cross-compiling and packaging
Some friends and I wanted to develop a game. Any language will do. I've been programming in C for years, but never wrote a game before. One of us knows SDL a little bit. It would also be a nice excuse to learn Python+pygame.
We wish our game to be 'standalone'. By standalone, I mean most users (at least Linux, Mac and Windows) will not have to manually download and install anything else apart from a package. It is ok if the installation automatically handles missing dependencies. If the packages contain binaries, we wish to be able to generate them using cross-compilation from Linux.
How should we package and structure the project, and what language is best suited?
A:
If you haven't programmed a game before, I'd recommend that you start with Python and Pygame. Python itself is very easy to learn if you're already a programmer, so that won't be too much of a leap for you.
With Pygame, you spend almost no time writing "glue" or dealing with mundane low-level details like window management and sound setup - you'll almost immediately be programming game logic and in no time you'll be bliting left and right. What's more, it'll be very easy to get a prototype of your game running so you can start experimenting with the mechanics - I've programmed a simple little side-scrolling platformer in a matter of hours.
Performance
The performance of Python with Pygame is normally decent for simple games, though "smooth-scrolling" games can show poor performance, especially on Linux (in my experience, at least - pygame.display.update() literally took 15-30ms per frame on Linux, and 4-5 on Windows with cheapo Intel graphics, though this was two years ago and the Linux Intel driver has improved of late). In addition, if you have physics/math-heavy code Psyco can give you huge speedups (20% - 200% in some cases), though you'll be limited to 32 bit Python on x86 computers.
Once you get most of the game logic worked out, if performance is still unsatisfactory, you could switch to C and SDL. Since you've already written the game logic, you'll just have to focus on dealing directly with SDL. Even that should be fairly easy - Pygame internally uses SDL, so the translation should be relatively straightforward.
OpenGL
Unfortunately, the above is only true if you're writing a 2D game - Pygame gives you basically no help for OpenGL. However, I would not recommend starting game programming with OpenGL. It can be pretty difficult to understand at first, so you'd be presenting yourself with two problems at once - first, you're trying to figure out how to get the game logic/physics/ai/etc. working, and then you're struggling to understand OpenGL. It is worth it to learn OpenGL eventually, but not to start with - better to start with the basics and go from there.
Cross-Platform Considerations
As far as cross-platform concerns - py2exe (for Windows) and py2app (for Mac) allow you to build individual executable files that include your dependencies (including the Python interpreter and Pygame); however, I do not think you'd be able to build your executables from a Linux environment (you'd have to be able to borrow a Windows/Mac computer for a few minutes, probably). For Linux, you'd probably just distribute a .deb that lists Pygame as a Dependency (and Psyco as a Recommends or Suggests if necessary).
A:
Have a look at Ogre; it's the engine behind Torchlight. It supports Windows, Ubuntu, MacOS and iPhone.
You may also want to read Gamasutra: their articles, interviews, in-depth and post-mortem analisys provide a very interesting insight in the game development process.
A:
It greatly depends if you want to build a whole game including the engine, or just building upon an established game engine. Although building a whole engine includes much more overhead and hard work, it gives you tons of experience.
Now if you want to create a game engine, the language for the job is C++ (C can also work, I just like C++ better)
For a build management tool, I have found that using CMake is a great option, it manages your build for you on several different platforms, and it can also even create the installers, and install any required libraries.
As for libraries go, most of your problems will be solved by SDL, it is not particularly pleasant to work with, but It manages the headaches of cross platform interfacing with video(OpenGL), Windowing, Input and Audio. You will still need to learn OpenGL to use it in your game, SDL only handles the initialization and setup.
Now for using Python, I would not recommend it, unless your game is simple (2D, or simple 3D without heavy physics usage), because the ammount of overhead incurred by Python will start to eat into your framerate. For a light, scripting language, Lua is definitely the best, it is simple, flexible, and fast. To integrate it, if you want a simple solution, use LuaBind, but beware! Be very selective on where you use it, for it can utterly KILL your compile times!
A:
i would suggest that you develop it On QT... QT will handle most of the portability issues itself... so you don't have to worry about it, plus it supports most of the platform including mobiles... and QT also has very good native support for gaming (Graphics,UI,Sound Controls.. )
Please see application Built in QT
A:
I presume that your game is a 3D one. If yes, than you need OpenGL. It's C, so you'll be familiar with the syntax, but the approach is a bit different, due to the fact that OpenGL is a finite state machine. More on this topic here.
OpenGL is basically built-in on every platform, so you would only need to initiate a single full screen window and let OpenGL handle the drawing. For cross compilation, I would recommend wxWidgets that is C++. It will allow you to write a single code for the window initialization of your application that compiles on each platform.
wxWidgets also have a python binding if you decide to go for python in which case you would also need PyOpenGL.
A:
For casual gaming I would recommend Flash
|
Game cross-compiling and packaging
|
Some friends and I wanted to develop a game. Any language will do. I've been programming in C for years, but never wrote a game before. One of us knows SDL a little bit. It would also be a nice excuse to learn Python+pygame.
We wish our game to be 'standalone'. By standalone, I mean most users (at least Linux, Mac and Windows) will not have to manually download and install anything else apart from a package. It is ok if the installation automatically handles missing dependencies. If the packages contain binaries, we wish to be able to generate them using cross-compilation from Linux.
How should we package and structure the project, and what language is best suited?
|
[
"If you haven't programmed a game before, I'd recommend that you start with Python and Pygame. Python itself is very easy to learn if you're already a programmer, so that won't be too much of a leap for you.\nWith Pygame, you spend almost no time writing \"glue\" or dealing with mundane low-level details like window management and sound setup - you'll almost immediately be programming game logic and in no time you'll be bliting left and right. What's more, it'll be very easy to get a prototype of your game running so you can start experimenting with the mechanics - I've programmed a simple little side-scrolling platformer in a matter of hours.\nPerformance\nThe performance of Python with Pygame is normally decent for simple games, though \"smooth-scrolling\" games can show poor performance, especially on Linux (in my experience, at least - pygame.display.update() literally took 15-30ms per frame on Linux, and 4-5 on Windows with cheapo Intel graphics, though this was two years ago and the Linux Intel driver has improved of late). In addition, if you have physics/math-heavy code Psyco can give you huge speedups (20% - 200% in some cases), though you'll be limited to 32 bit Python on x86 computers.\nOnce you get most of the game logic worked out, if performance is still unsatisfactory, you could switch to C and SDL. Since you've already written the game logic, you'll just have to focus on dealing directly with SDL. Even that should be fairly easy - Pygame internally uses SDL, so the translation should be relatively straightforward.\nOpenGL\nUnfortunately, the above is only true if you're writing a 2D game - Pygame gives you basically no help for OpenGL. However, I would not recommend starting game programming with OpenGL. It can be pretty difficult to understand at first, so you'd be presenting yourself with two problems at once - first, you're trying to figure out how to get the game logic/physics/ai/etc. working, and then you're struggling to understand OpenGL. It is worth it to learn OpenGL eventually, but not to start with - better to start with the basics and go from there.\nCross-Platform Considerations\nAs far as cross-platform concerns - py2exe (for Windows) and py2app (for Mac) allow you to build individual executable files that include your dependencies (including the Python interpreter and Pygame); however, I do not think you'd be able to build your executables from a Linux environment (you'd have to be able to borrow a Windows/Mac computer for a few minutes, probably). For Linux, you'd probably just distribute a .deb that lists Pygame as a Dependency (and Psyco as a Recommends or Suggests if necessary).\n",
"Have a look at Ogre; it's the engine behind Torchlight. It supports Windows, Ubuntu, MacOS and iPhone. \nYou may also want to read Gamasutra: their articles, interviews, in-depth and post-mortem analisys provide a very interesting insight in the game development process.\n",
"It greatly depends if you want to build a whole game including the engine, or just building upon an established game engine. Although building a whole engine includes much more overhead and hard work, it gives you tons of experience.\nNow if you want to create a game engine, the language for the job is C++ (C can also work, I just like C++ better)\nFor a build management tool, I have found that using CMake is a great option, it manages your build for you on several different platforms, and it can also even create the installers, and install any required libraries.\nAs for libraries go, most of your problems will be solved by SDL, it is not particularly pleasant to work with, but It manages the headaches of cross platform interfacing with video(OpenGL), Windowing, Input and Audio. You will still need to learn OpenGL to use it in your game, SDL only handles the initialization and setup.\nNow for using Python, I would not recommend it, unless your game is simple (2D, or simple 3D without heavy physics usage), because the ammount of overhead incurred by Python will start to eat into your framerate. For a light, scripting language, Lua is definitely the best, it is simple, flexible, and fast. To integrate it, if you want a simple solution, use LuaBind, but beware! Be very selective on where you use it, for it can utterly KILL your compile times!\n",
"i would suggest that you develop it On QT... QT will handle most of the portability issues itself... so you don't have to worry about it, plus it supports most of the platform including mobiles... and QT also has very good native support for gaming (Graphics,UI,Sound Controls.. ) \nPlease see application Built in QT \n",
"I presume that your game is a 3D one. If yes, than you need OpenGL. It's C, so you'll be familiar with the syntax, but the approach is a bit different, due to the fact that OpenGL is a finite state machine. More on this topic here.\nOpenGL is basically built-in on every platform, so you would only need to initiate a single full screen window and let OpenGL handle the drawing. For cross compilation, I would recommend wxWidgets that is C++. It will allow you to write a single code for the window initialization of your application that compiles on each platform.\nwxWidgets also have a python binding if you decide to go for python in which case you would also need PyOpenGL.\n",
"For casual gaming I would recommend Flash\n"
] |
[
9,
4,
3,
1,
0,
0
] |
[] |
[] |
[
"c",
"cross_compiling",
"cross_platform",
"packaging",
"python"
] |
stackoverflow_0002401599_c_cross_compiling_cross_platform_packaging_python.txt
|
Q:
Storing and Retrieving Images from Database using Python
I want to store the images related to a each person's profile in the DB and retrieve them
when requested and save it as .jpg file - and display it to the users.
How could I render the image data stored in the DB as an image and store it locally??
A:
This StackOverflow Question is a good one to start with when figuring out whether to store images in a DB or on a filesystem
Storing Images in DB - Yea or Nay?
I have also written about the issues on my blog
http://www.atalasoft.com/cs/blogs/loufranco/archive/2007/12/03/images-in-databases-part-i-what-to-store.aspx
http://www.atalasoft.com/cs/blogs/loufranco/archive/2007/12/04/images-in-databases-part-ii-web-images-are-random-access.aspx
http://www.atalasoft.com/cs/blogs/loufranco/archive/2009/04/28/document-storage-database-blobs-or-the-filesystem.aspx
The short answer is: if the images are small and there aren't a lot of them -- a blob in the DB is probably fine (easier to backup, control access, transactions, etc). But the performance is bad compared to the filesystem -- it's a tradeoff. Most real applications (and especially big websites) use the filesystem, but it's perfectly reasonable to use blobs in some cases.
The blob (or file) is just going to be the encoded data (JPG) -- it's the exact same stream of bytes. In a web app, you would use an img tag -- if you are building a desktop GUI, look at what components it has for displaying images.
If you are using a blob, and need to display in a web app, the src of the img tag will be set to a script/view/etc that returns a content-type set to the mime-type of the image (e.g. image/jpeg) and the content of the blob.
A:
The standard approach is to convert image to JPG only once, when it is get uploaded. Then save it as a regular file on file system. Use DB just to store relative path to saved image.
When you want to render it just use HTML:
<img src="/images/relative/path/to/my/image.jpg" />
and setup your web-server (nginx, lighttpd, whatever) to serve directory you save images to under virtual directory /images
A:
Why don't you simply store the images on the file system, and only store their references on the database. That's a lot more elegant, and won't consume loads of your database.
Also, you won't have to use any kind of binary functions to read them from the DB, saving memory and loading time.
Is there a very specific reason why you wanna store it on the DB?
Cheers
|
Storing and Retrieving Images from Database using Python
|
I want to store the images related to a each person's profile in the DB and retrieve them
when requested and save it as .jpg file - and display it to the users.
How could I render the image data stored in the DB as an image and store it locally??
|
[
"This StackOverflow Question is a good one to start with when figuring out whether to store images in a DB or on a filesystem\nStoring Images in DB - Yea or Nay?\nI have also written about the issues on my blog\nhttp://www.atalasoft.com/cs/blogs/loufranco/archive/2007/12/03/images-in-databases-part-i-what-to-store.aspx\nhttp://www.atalasoft.com/cs/blogs/loufranco/archive/2007/12/04/images-in-databases-part-ii-web-images-are-random-access.aspx\nhttp://www.atalasoft.com/cs/blogs/loufranco/archive/2009/04/28/document-storage-database-blobs-or-the-filesystem.aspx\nThe short answer is: if the images are small and there aren't a lot of them -- a blob in the DB is probably fine (easier to backup, control access, transactions, etc). But the performance is bad compared to the filesystem -- it's a tradeoff. Most real applications (and especially big websites) use the filesystem, but it's perfectly reasonable to use blobs in some cases.\nThe blob (or file) is just going to be the encoded data (JPG) -- it's the exact same stream of bytes. In a web app, you would use an img tag -- if you are building a desktop GUI, look at what components it has for displaying images.\nIf you are using a blob, and need to display in a web app, the src of the img tag will be set to a script/view/etc that returns a content-type set to the mime-type of the image (e.g. image/jpeg) and the content of the blob.\n",
"The standard approach is to convert image to JPG only once, when it is get uploaded. Then save it as a regular file on file system. Use DB just to store relative path to saved image.\nWhen you want to render it just use HTML: \n<img src=\"/images/relative/path/to/my/image.jpg\" />\n\nand setup your web-server (nginx, lighttpd, whatever) to serve directory you save images to under virtual directory /images\n",
"Why don't you simply store the images on the file system, and only store their references on the database. That's a lot more elegant, and won't consume loads of your database.\nAlso, you won't have to use any kind of binary functions to read them from the DB, saving memory and loading time.\nIs there a very specific reason why you wanna store it on the DB?\nCheers\n"
] |
[
9,
2,
1
] |
[] |
[] |
[
"image_manipulation",
"python"
] |
stackoverflow_0002477045_image_manipulation_python.txt
|
Q:
write special characters into excel table by python package pyExcelerator/xlwt
Task:
I generate formated excel tables from csv-files by using the python package pyExcelerator (comparable with xlwt). I need to be able to write less-than-or-equal-to (≤) and greater-than-or-equal-to (≥) signs.
So far:
I can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in my text editor, by adding the following line to my python source code:
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
Problem:
However, there is no option to choose UTF-8 as font in pyExcelerator's Font class. The only options are:
CHARSET_ANSI_LATIN = 0x00
CHARSET_SYS_DEFAULT = 0x01
CHARSET_SYMBOL = 0x02
CHARSET_APPLE_ROMAN = 0x4D
CHARSET_ANSI_JAP_SHIFT_JIS = 0x80
CHARSET_ANSI_KOR_HANGUL = 0x81
CHARSET_ANSI_KOR_JOHAB = 0x82
CHARSET_ANSI_CHINESE_GBK = 0x86
CHARSET_ANSI_CHINESE_BIG5 = 0x88
CHARSET_ANSI_GREEK = 0xA1
CHARSET_ANSI_TURKISH = 0xA2
CHARSET_ANSI_VIETNAMESE = 0xA3
CHARSET_ANSI_HEBREW = 0xB1
CHARSET_ANSI_ARABIC = 0xB2
CHARSET_ANSI_BALTIC = 0xBA
CHARSET_ANSI_CYRILLIC = 0xCC
CHARSET_ANSI_THAI = 0xDE
CHARSET_ANSI_LATIN_II = 0xEE
CHARSET_OEM_LATIN_I = 0xFF
Do any of these character sets contain the less-than-or-equal-to and greater-than-or-equal-to signs? If so, which on?
Which python encoding name corresponds to these sets?
Is there another way for generating these special characters?
A:
This should help with writing UTF-8 chars using pyexcelerator or xlwt:
wb = xlwt.Workbook(**encoding='utf-8'**)
edit:
Seems it's not working for pyexcelerator, but I havent confirmed it.
A:
You may be overthinking the problem. The font shouldn't play into the matter, although character encoding might.
In any case, I was able to use xlwt to create an excel spreadsheet with less-than-equal and greater-than-equal signs with the following script:
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('Test Sheet')
lte = u'\u2264'
gte = u'\u2265'
ws.write(0,0,lte+gte)
wb.save('foo.xls')
Note that -- coding: utf-8 -- is not required because the special characters are encoded with their unicode numeric indices. In general, I recommend using unicode where possible.
It's also possible to use utf-8 and type the characters directly into the Python code. This would be exactly the same except for how the characters are entered:
#-*- coding: utf-8 -*-
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('Test Sheet')
lte = u'≤'
gte = u'≥'
ws.write(0,0,lte+gte)
wb.save('foo.xls')
Note, however, that you must be using an editor that is aware that you are saving the Python code as UTF-8. If your editor encodes the file in any other way, the special characters will not be parsed properly when loaded by the Python interpreter.
A:
(1) Re: """
I can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in my text editor, by adding the following line to my python source code:
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Being able to write a file with characters encoded in UTF-8 is NOT dependant on what encoding is used in the source of the program that writes the file!
(2) UTF-8 is an encoding, not a font. Those charsets in an Excel FONT record are a blast from the past AFAIK. I've not heard from any xlwt user who ever thought it necessary to use other than the default for the charset. Just feed unicode objects to xlwt as demonstrated by Jason ... if you have an appropriate font on your system (see if you can display the characters in OpenOffice Calc), you should be OK.
(3) Any particular reason for using pyExcelerator instead of xlwt?
|
write special characters into excel table by python package pyExcelerator/xlwt
|
Task:
I generate formated excel tables from csv-files by using the python package pyExcelerator (comparable with xlwt). I need to be able to write less-than-or-equal-to (≤) and greater-than-or-equal-to (≥) signs.
So far:
I can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in my text editor, by adding the following line to my python source code:
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
Problem:
However, there is no option to choose UTF-8 as font in pyExcelerator's Font class. The only options are:
CHARSET_ANSI_LATIN = 0x00
CHARSET_SYS_DEFAULT = 0x01
CHARSET_SYMBOL = 0x02
CHARSET_APPLE_ROMAN = 0x4D
CHARSET_ANSI_JAP_SHIFT_JIS = 0x80
CHARSET_ANSI_KOR_HANGUL = 0x81
CHARSET_ANSI_KOR_JOHAB = 0x82
CHARSET_ANSI_CHINESE_GBK = 0x86
CHARSET_ANSI_CHINESE_BIG5 = 0x88
CHARSET_ANSI_GREEK = 0xA1
CHARSET_ANSI_TURKISH = 0xA2
CHARSET_ANSI_VIETNAMESE = 0xA3
CHARSET_ANSI_HEBREW = 0xB1
CHARSET_ANSI_ARABIC = 0xB2
CHARSET_ANSI_BALTIC = 0xBA
CHARSET_ANSI_CYRILLIC = 0xCC
CHARSET_ANSI_THAI = 0xDE
CHARSET_ANSI_LATIN_II = 0xEE
CHARSET_OEM_LATIN_I = 0xFF
Do any of these character sets contain the less-than-or-equal-to and greater-than-or-equal-to signs? If so, which on?
Which python encoding name corresponds to these sets?
Is there another way for generating these special characters?
|
[
"This should help with writing UTF-8 chars using pyexcelerator or xlwt:\nwb = xlwt.Workbook(**encoding='utf-8'**)\n\nedit:\nSeems it's not working for pyexcelerator, but I havent confirmed it.\n",
"You may be overthinking the problem. The font shouldn't play into the matter, although character encoding might.\nIn any case, I was able to use xlwt to create an excel spreadsheet with less-than-equal and greater-than-equal signs with the following script:\nimport xlwt\nwb = xlwt.Workbook()\nws = wb.add_sheet('Test Sheet')\nlte = u'\\u2264'\ngte = u'\\u2265'\nws.write(0,0,lte+gte)\nwb.save('foo.xls')\n\nNote that -- coding: utf-8 -- is not required because the special characters are encoded with their unicode numeric indices. In general, I recommend using unicode where possible.\nIt's also possible to use utf-8 and type the characters directly into the Python code. This would be exactly the same except for how the characters are entered:\n#-*- coding: utf-8 -*- \nimport xlwt\nwb = xlwt.Workbook()\nws = wb.add_sheet('Test Sheet')\nlte = u'≤'\ngte = u'≥'\nws.write(0,0,lte+gte)\nwb.save('foo.xls')\n\nNote, however, that you must be using an editor that is aware that you are saving the Python code as UTF-8. If your editor encodes the file in any other way, the special characters will not be parsed properly when loaded by the Python interpreter.\n",
"(1) Re: \"\"\"\nI can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in my text editor, by adding the following line to my python source code:\n#! /usr/bin/env python\n# -*- coding: UTF-8 -*-\n\"\"\"\nBeing able to write a file with characters encoded in UTF-8 is NOT dependant on what encoding is used in the source of the program that writes the file!\n(2) UTF-8 is an encoding, not a font. Those charsets in an Excel FONT record are a blast from the past AFAIK. I've not heard from any xlwt user who ever thought it necessary to use other than the default for the charset. Just feed unicode objects to xlwt as demonstrated by Jason ... if you have an appropriate font on your system (see if you can display the characters in OpenOffice Calc), you should be OK.\n(3) Any particular reason for using pyExcelerator instead of xlwt?\n"
] |
[
5,
4,
1
] |
[] |
[] |
[
"character_encoding",
"excel",
"python",
"special_characters",
"xlwt"
] |
stackoverflow_0001342402_character_encoding_excel_python_special_characters_xlwt.txt
|
Q:
Is this the right way of handling command line arguments?
ask_username = True
ask_password = True
ask_message = True
ask_number = True
def Usage():
print '\t-h, --help: View help'
print '\t-u, --username: Username'
print '\t-p, --password: Password'
print '\t-n, --number: numbber to send the sms'
print '\t-m, --message: Message to send'
sys.exit(1)
opts, args = getopt(sys.argv[1:], 'u:p:m:n:h',["username=","password=","message=","number=","help"])
print opts, args
for o,v in opts:
if o in ("-h", "--help"):
Usage()
elif o in ("-u", "--username"):
username = v
ask_username = False
elif o in ("-p", "--password"):
passwd = v
ask_password = False
elif o in ("-m", "--message"):
message = v
ask_message = False
elif o in ("-n", "--number"):
number = v
ask_number = False
#Credentials taken here
if ask_username: username = raw_input("Enter USERNAME: ")
if ask_password: passwd = getpass()
if ask_message: message = raw_input("Enter Message: ")
if ask_number: number = raw_input("Enter Mobile number: ")
I dont think it is, because I am using 4 objects just for checking if command line argument was provided...
Guide me with the best way of doing
it..
A:
You might find that the optparse module is useful -- it allows you to specify which options you want and their types and help text, then to parse the options and get all the results back.
It also auto-generates the help output for you, so you only have to maintain your options in one place.
A:
argparse is another option if optparse does not cover all your needs
optparse vs argparse
A:
While the right thing is to use optparse, some comments on the code -- as presented -- are in order.
The four condition flags (ask_username, ask_password, ask_message, ask_number) are useless.
Consider your post-condition for any one of these four items (they're all the same)
(in_args AND variable_set) OR (not in_args AND prompt AND variable_set)
You're really doing something like this.
username= None
# Pre Condition: username is not set to a useful value
# ... use `optparse` to parse options ...
username = options.username
# Post Condition: username may be None if no option provided
# or username may be set if an option was provided.
if username is None: # it's not set to a useful value
# ... prompt to get a value for username ...
assert username is not None
You don't need any flags when you have default values that are more useful.
A:
So far optparse has fitted all my needs.
|
Is this the right way of handling command line arguments?
|
ask_username = True
ask_password = True
ask_message = True
ask_number = True
def Usage():
print '\t-h, --help: View help'
print '\t-u, --username: Username'
print '\t-p, --password: Password'
print '\t-n, --number: numbber to send the sms'
print '\t-m, --message: Message to send'
sys.exit(1)
opts, args = getopt(sys.argv[1:], 'u:p:m:n:h',["username=","password=","message=","number=","help"])
print opts, args
for o,v in opts:
if o in ("-h", "--help"):
Usage()
elif o in ("-u", "--username"):
username = v
ask_username = False
elif o in ("-p", "--password"):
passwd = v
ask_password = False
elif o in ("-m", "--message"):
message = v
ask_message = False
elif o in ("-n", "--number"):
number = v
ask_number = False
#Credentials taken here
if ask_username: username = raw_input("Enter USERNAME: ")
if ask_password: passwd = getpass()
if ask_message: message = raw_input("Enter Message: ")
if ask_number: number = raw_input("Enter Mobile number: ")
I dont think it is, because I am using 4 objects just for checking if command line argument was provided...
Guide me with the best way of doing
it..
|
[
"You might find that the optparse module is useful -- it allows you to specify which options you want and their types and help text, then to parse the options and get all the results back.\nIt also auto-generates the help output for you, so you only have to maintain your options in one place.\n",
"argparse is another option if optparse does not cover all your needs\noptparse vs argparse\n",
"While the right thing is to use optparse, some comments on the code -- as presented -- are in order.\nThe four condition flags (ask_username, ask_password, ask_message, ask_number) are useless.\nConsider your post-condition for any one of these four items (they're all the same)\n(in_args AND variable_set) OR (not in_args AND prompt AND variable_set)\n\nYou're really doing something like this.\nusername= None \n\n# Pre Condition: username is not set to a useful value\n\n# ... use `optparse` to parse options ... \nusername = options.username \n\n# Post Condition: username may be None if no option provided\n# or username may be set if an option was provided.\n\nif username is None: # it's not set to a useful value\n # ... prompt to get a value for username ... \n\nassert username is not None\n\nYou don't need any flags when you have default values that are more useful.\n",
"So far optparse has fitted all my needs.\n"
] |
[
16,
1,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002476344_python.txt
|
Q:
Python code that needs some overview
im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.
Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)
import random
dez = ['0', '1', '2', '3', '4', '5', '6']
uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
sort = []
while len(sort) <= 5:
random.shuffle(dez)
random.shuffle(uni)
w = random.choice(dez)
z = random.choice(uni)
chosen = str(w) + str(z)
if chosen != "00" and chosen not in sort:
sort.append(chosen)
print chosen
I'm also in doubt how to make the code stop at "60".
A:
You do realize you can write the exact same code in 1 line, right? It is easy using randint:
>>> [random.randint(1,60) for _ in range(6)]
[22, 29, 48, 18, 20, 22]
This will give you a list of 6 random integers between 1 and 60. In your code you are creating strings that have these numbers. If you are deliberately creating them as strings, however, you then can do this:
>>> [str(random.randint(1,60)) for _ in range(6)]
['55', '54', '15', '46', '42', '37']
A:
You can just use
random.randrange(1,60)
A:
To get 6 unique random integers in the range from 1 to 59:
sample = random.sample(xrange(1, 60), 6)
# -> [8, 34, 16, 28, 46, 39]
To get strings:
['%02d' % i for i in sample]
# -> ['08', '34', '16', '28', '46', '39']
A:
you will get no real benefit by shuffling on each loop. Do it once before the loop.
choosen isn't a word
|
Python code that needs some overview
|
im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.
Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)
import random
dez = ['0', '1', '2', '3', '4', '5', '6']
uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
sort = []
while len(sort) <= 5:
random.shuffle(dez)
random.shuffle(uni)
w = random.choice(dez)
z = random.choice(uni)
chosen = str(w) + str(z)
if chosen != "00" and chosen not in sort:
sort.append(chosen)
print chosen
I'm also in doubt how to make the code stop at "60".
|
[
"You do realize you can write the exact same code in 1 line, right? It is easy using randint:\n>>> [random.randint(1,60) for _ in range(6)]\n[22, 29, 48, 18, 20, 22]\n\nThis will give you a list of 6 random integers between 1 and 60. In your code you are creating strings that have these numbers. If you are deliberately creating them as strings, however, you then can do this:\n>>> [str(random.randint(1,60)) for _ in range(6)]\n['55', '54', '15', '46', '42', '37']\n\n",
"You can just use \nrandom.randrange(1,60)\n\n",
"To get 6 unique random integers in the range from 1 to 59:\nsample = random.sample(xrange(1, 60), 6)\n# -> [8, 34, 16, 28, 46, 39]\n\nTo get strings:\n['%02d' % i for i in sample]\n# -> ['08', '34', '16', '28', '46', '39']\n\n",
"you will get no real benefit by shuffling on each loop. Do it once before the loop.\nchoosen isn't a word\n"
] |
[
4,
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000909279_python.txt
|
Q:
Easy way to find "not enough arguments..." in python logging library
Do you know any easy way to find a logging call that throws "not enough argumenst for format string".
On my workstation I've modified logging/__init__.py to print the msg so I can easily find the line in the source.
But do you have any idea what to do on the testing environment where you can't change python standard library nor run pdb easily?
Note: The traceback is meaningless, and it is caugth by the logging library.
Here is an traceback:
File "/usr/lib/python2.6/logging/handlers.py", line 71, in emit
if self.shouldRollover(record):
File "/usr/lib/python2.6/logging/handlers.py", line 144, in shouldRollover
msg = "%s\n" % self.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 648, in format
return fmt.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 436, in format
record.message = record.getMessage()
File "/usr/lib/python2.6/logging/__init__.py", line 306, in getMessage
msg = msg % self.args
TypeError: not enough arguments for format string
And here is the code in standard library that catch the error
try:
if self.shouldRollover(record):
self.doRollover()
logging.FileHandler.emit(self, record)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
Solution as suggested by Alex:
I've wrapped the getMessage to print the msg and args. Here is the code:
def print_log_record_on_error(func):
def wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except:
import sys
print >>sys.stderr, "Unable to create log message msg=%r, args=%r " % (
getattr(self, 'msg', '?'), getattr(self, 'args', '?'))
raise
return wrap
import logging
logging.LogRecord.getMessage = print_log_record_on_error(logging.LogRecord.getMessage)
A:
Generally, the best way to catch an exception (including the one you mention) is to put the suspect code in the try clause of a try/except statement; in the except clause you can use the traceback module or other ways to pinpoint the errant statement.
Otherwise-uncaught exceptions end up in sys.excepthook, which is another way you can use to get a traceback if needed.
However, I don't think the logging module has an architected way to tell it "let exceptions propagate" -- in which case your best bet, dirty as it may be, is probably monkey-patching. In other words, you generally can "change the Python standard library" at runtime -- by setting identifiers therein to your own functions / classes / etc wrapping the standard ones. For example, if you know the problem is with a logging.warning call, a "proof of concept" monkeypatch might be:
import logging, traceback
orgwarn = logging.warning
def mywarn(msg, *a):
try: res = msg % a
except TypeError:
traceback.print_exc()
return orgwarn(msg, *a)
logging.warning = mywarn
There are cleaner ways, but they may be somewhat cumbersome (e.g., make your own logger class and set it as the root logger). Monkey-patching is not a good way to operate in a production environment (it's fragile to system upgrades, can be hard to understand and maintain, etc), but it can be acceptable for debugging and testing purposes.
A:
To find a logging call that throws "not enough argumenst for format string".
I grep the source for all logging calls. There aren't that many: .info(, .warn(, .debug(, .error(, .critical(, .exception(, .log(.
One of those methods has a format without enough arguments. It's generally easy to spot, since the message will have "%" formatting operators.
If your application is consistent in calling all loggers logger is makes it even easier, since you can more simply grep for logger..
|
Easy way to find "not enough arguments..." in python logging library
|
Do you know any easy way to find a logging call that throws "not enough argumenst for format string".
On my workstation I've modified logging/__init__.py to print the msg so I can easily find the line in the source.
But do you have any idea what to do on the testing environment where you can't change python standard library nor run pdb easily?
Note: The traceback is meaningless, and it is caugth by the logging library.
Here is an traceback:
File "/usr/lib/python2.6/logging/handlers.py", line 71, in emit
if self.shouldRollover(record):
File "/usr/lib/python2.6/logging/handlers.py", line 144, in shouldRollover
msg = "%s\n" % self.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 648, in format
return fmt.format(record)
File "/usr/lib/python2.6/logging/__init__.py", line 436, in format
record.message = record.getMessage()
File "/usr/lib/python2.6/logging/__init__.py", line 306, in getMessage
msg = msg % self.args
TypeError: not enough arguments for format string
And here is the code in standard library that catch the error
try:
if self.shouldRollover(record):
self.doRollover()
logging.FileHandler.emit(self, record)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
Solution as suggested by Alex:
I've wrapped the getMessage to print the msg and args. Here is the code:
def print_log_record_on_error(func):
def wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except:
import sys
print >>sys.stderr, "Unable to create log message msg=%r, args=%r " % (
getattr(self, 'msg', '?'), getattr(self, 'args', '?'))
raise
return wrap
import logging
logging.LogRecord.getMessage = print_log_record_on_error(logging.LogRecord.getMessage)
|
[
"Generally, the best way to catch an exception (including the one you mention) is to put the suspect code in the try clause of a try/except statement; in the except clause you can use the traceback module or other ways to pinpoint the errant statement.\nOtherwise-uncaught exceptions end up in sys.excepthook, which is another way you can use to get a traceback if needed.\nHowever, I don't think the logging module has an architected way to tell it \"let exceptions propagate\" -- in which case your best bet, dirty as it may be, is probably monkey-patching. In other words, you generally can \"change the Python standard library\" at runtime -- by setting identifiers therein to your own functions / classes / etc wrapping the standard ones. For example, if you know the problem is with a logging.warning call, a \"proof of concept\" monkeypatch might be:\nimport logging, traceback\n\norgwarn = logging.warning\ndef mywarn(msg, *a):\n try: res = msg % a\n except TypeError:\n traceback.print_exc()\n return orgwarn(msg, *a)\nlogging.warning = mywarn\n\nThere are cleaner ways, but they may be somewhat cumbersome (e.g., make your own logger class and set it as the root logger). Monkey-patching is not a good way to operate in a production environment (it's fragile to system upgrades, can be hard to understand and maintain, etc), but it can be acceptable for debugging and testing purposes.\n",
"To find a logging call that throws \"not enough argumenst for format string\".\nI grep the source for all logging calls. There aren't that many: .info(, .warn(, .debug(, .error(, .critical(, .exception(, .log(.\nOne of those methods has a format without enough arguments. It's generally easy to spot, since the message will have \"%\" formatting operators.\nIf your application is consistent in calling all loggers logger is makes it even easier, since you can more simply grep for logger..\n"
] |
[
2,
0
] |
[] |
[] |
[
"debugging",
"python"
] |
stackoverflow_0002477934_debugging_python.txt
|
Q:
Python | How to append elements to a list randomly
Is there a way to append elements to a list randomly, built in function
ex:
def random_append():
lst = ['a']
lst.append('b')
lst.append('c')
lst.append('d')
lst.append('e')
return print lst
this will out put ['a', 'b', 'c', 'd', 'e']
But I want it to add elements randomly and out put something like this:
['b', 'd', 'b', 'e', 'c']
And yes there's a function random.shuffle() but it shuffles a list at once which I don't require, I just want to perform random inserts only.
A:
If you need to perform single insert in a random position then the already given trivial example works:
from random import randrange
def random_insert(lst, item):
lst.insert(randrange(len(lst)+1), item)
However if you need to insert k items to a list of length n then using the previously given function is O(n*k + k**2) complexity. However inserting multiple items can be done in linear time O(n+k) if you calculate the target positions ahead of time and rewrite the input list in one go:
from random import sample
def random_insert_seq(lst, seq):
insert_locations = sample(xrange(len(lst) + len(seq)), len(seq))
inserts = dict(zip(insert_locations, seq))
input = iter(lst)
lst[:] = [inserts[pos] if pos in inserts else next(input)
for pos in xrange(len(lst) + len(seq))]
A:
If there is supposed to be exactly one of each item
>>> from random import randint
>>> a=[]
>>> for x in "abcde":
... a.insert(randint(0,len(a)),x)
...
>>> a
['b', 'a', 'd', 'c', 'e']
If you are allowing duplicates (as the output indicates)
>>> from random import choice
>>> a=[choice("abcde") for x in range(5)]
>>> a
['a', 'b', 'd', 'b', 'a']
A:
random.shuffle is probably the best tool for the job. It is simple, obvious, and well-named—it's probably more readable than the other suggestions you will get. Additionally, using it is O(n), but using insert (an O(n) operation) n times is quadratic.
A:
from random import choice
n=10
seq=['a','b','c','d']
rstr=[choice(seq) for i in range(n)]
|
Python | How to append elements to a list randomly
|
Is there a way to append elements to a list randomly, built in function
ex:
def random_append():
lst = ['a']
lst.append('b')
lst.append('c')
lst.append('d')
lst.append('e')
return print lst
this will out put ['a', 'b', 'c', 'd', 'e']
But I want it to add elements randomly and out put something like this:
['b', 'd', 'b', 'e', 'c']
And yes there's a function random.shuffle() but it shuffles a list at once which I don't require, I just want to perform random inserts only.
|
[
"If you need to perform single insert in a random position then the already given trivial example works:\nfrom random import randrange\n\ndef random_insert(lst, item):\n lst.insert(randrange(len(lst)+1), item)\n\nHowever if you need to insert k items to a list of length n then using the previously given function is O(n*k + k**2) complexity. However inserting multiple items can be done in linear time O(n+k) if you calculate the target positions ahead of time and rewrite the input list in one go:\nfrom random import sample\ndef random_insert_seq(lst, seq):\n insert_locations = sample(xrange(len(lst) + len(seq)), len(seq))\n inserts = dict(zip(insert_locations, seq))\n input = iter(lst)\n lst[:] = [inserts[pos] if pos in inserts else next(input)\n for pos in xrange(len(lst) + len(seq))]\n\n",
"If there is supposed to be exactly one of each item\n>>> from random import randint\n>>> a=[]\n>>> for x in \"abcde\":\n... a.insert(randint(0,len(a)),x)\n... \n>>> a\n['b', 'a', 'd', 'c', 'e']\n\nIf you are allowing duplicates (as the output indicates)\n>>> from random import choice\n>>> a=[choice(\"abcde\") for x in range(5)]\n>>> a\n['a', 'b', 'd', 'b', 'a']\n\n",
"random.shuffle is probably the best tool for the job. It is simple, obvious, and well-named—it's probably more readable than the other suggestions you will get. Additionally, using it is O(n), but using insert (an O(n) operation) n times is quadratic.\n",
"from random import choice\n\nn=10\nseq=['a','b','c','d']\nrstr=[choice(seq) for i in range(n)]\n\n"
] |
[
12,
11,
6,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002475518_python.txt
|
Q:
How do I parse a VCard to a Python dictionary?
I'm trying to figure out how to parse a VCard to a Python dictionary using VObject.
vobj=vobject.readOne(string)
print vobj.behavior.knownChildren
This is all I get:
{'CATEGORIES': (0, None, None), 'ADR': (0, None, None), 'UID': (0, None, None), 'PHOTO': (0, None, None), 'LABEL': (0, None, None), 'VERSION': (1, 1, None), 'FN': (1, 1, None), 'ORG': (0, None, None), 'N': (1, 1, None), 'PRODID': (0, 1, None)}
How can I populate the dictionary with my VCard data?
A:
You don't want to look at the behavior, you want to look at vobj itself. The behavior is a data structure describing what children are required/expected, and how to translate those children into appropriate Python data structures.
The vobj object is a vobject Component. Its contents attribute is a dictionary of vobject ContentLines and possibly Components, so
vobject.contents
will give you a dictionary of objects.
If you want a more human readable view of what was parsed, do:
vobj.prettyPrint()
To access individual children, do, for instance:
vobj.adr
|
How do I parse a VCard to a Python dictionary?
|
I'm trying to figure out how to parse a VCard to a Python dictionary using VObject.
vobj=vobject.readOne(string)
print vobj.behavior.knownChildren
This is all I get:
{'CATEGORIES': (0, None, None), 'ADR': (0, None, None), 'UID': (0, None, None), 'PHOTO': (0, None, None), 'LABEL': (0, None, None), 'VERSION': (1, 1, None), 'FN': (1, 1, None), 'ORG': (0, None, None), 'N': (1, 1, None), 'PRODID': (0, 1, None)}
How can I populate the dictionary with my VCard data?
|
[
"You don't want to look at the behavior, you want to look at vobj itself. The behavior is a data structure describing what children are required/expected, and how to translate those children into appropriate Python data structures.\nThe vobj object is a vobject Component. Its contents attribute is a dictionary of vobject ContentLines and possibly Components, so\nvobject.contents\n\nwill give you a dictionary of objects.\nIf you want a more human readable view of what was parsed, do:\nvobj.prettyPrint()\n\nTo access individual children, do, for instance:\nvobj.adr\n\n"
] |
[
9
] |
[] |
[] |
[
"python",
"vcf_vcard"
] |
stackoverflow_0002478027_python_vcf_vcard.txt
|
Q:
Writing 'bits' to C++ file streams
How can I write 'one bit' into a file stream or file structure each time?
Is it possible to write to a queue and then flush it?
Is it possible with C# or Java?
This was needed when trying to implement an instance of Huffman coding. I can't write bits into files, so write them to a bitset and then (when compression was completed) write 8-bit piece of it each time (exclude last one).
A:
Buffering the individual bits until you've accumulated a whole byte seems like a good idea:
byte b;
int s;
void WriteBit(bool x)
{
b |= (x ? 1 : 0) << s;
s++;
if (s == 8)
{
WriteByte(b);
b = 0;
s = 0;
}
}
You just have to deal with the case when the number of bits to be written is not a multiple of eight.
A:
You can use boost::dynamic_bitset along with std::ostream_iterator to achieve the desired result in a concise manner:
#include <fstream>
#include <iterator>
#include <boost/dynamic_bitset.hpp>
typedef boost::dynamic_bitset<unsigned char> Bitset;
// To help populate the bitset with literals */
Bitset& operator<<(Bitset& lhs, bool val) {lhs.push_back(val); return lhs;}
int main()
{
Bitset bitset;
bitset<<0<<1<<0<<1<<0<<1<<0<<1
<<1<<0<<1<<0;
std::ofstream os("data.dat", std::ios::binary);
std::ostream_iterator<char> osit(os);
boost::to_block_range(bitset, osit);
return 0;
}
I made the block size of my dynamic_bitset 8 bits by specifying unsigned char as the template parameter. You can make the block size bigger by specifying a larger integer type.
boost::to_block_range dumps the bitset in blocks to the given output iterator. If there are empty remainder bits in the last block, they'll be padded with zero.
When I open data.dat in a hex editor I see: AA 05. This is on a little endian platform (x64).
A:
Which filesystem are you using?
Most likely it stores the length of the file in bytes (are there any that don't?), so it's impossible to have a physical file that is not a whole number of bytes.
So if you are writing to the file as a stream of bits, you either have to truncate the last few bits when you are finished, or write out the final byte with what ammounts to junk in the remaining bits.
Here's some Python code to get you started
class BitFile(file):
def __init__(self, filename, mode):
super(BitFile, self).__init__(filename, mode)
self.bitCount=0
self.byte = 0
def write(self, bit):
self.bitCount+=1
self.byte = self.byte*2+bit
if self.bitCount%8==0:
super(BitFile, self).write(chr(self.byte))
self.byte=0
def close(self):
if self.bitCount%8!=0:
super(BitFile, self).write(chr(self.byte))
super(BitFile, self).close()
with BitFile("bitfile.bin","w") as bf:
bf.write(1)
bf.write(1)
bf.write(1)
bf.write(0)
bf.write(0)
bf.write(0)
bf.write(0)
bf.write(0)
bf.write(1)
A:
You can't really. I'm pretty sure the problem is not with the language or the filesystem, but a hardware issue. Processors are designed to work with bytes. Probably the closest you can do is write your last byte over and over again, right padded with zeros, changing them as you go, one at a time.
so to write bits '11011', you could do the following (python example, but any language should have facilities to do this:
f.write(chr(0b10000000))
f.flush()
f.seek(-1)
f.write(chr(0b11000000))
f.flush()
f.seek(-1)
f.write(chr(0b11000000))
f.flush()
f.seek(-1)
f.write(chr(0b11010000))
f.flush()
f.seek(-1)
f.write(chr(0b11011000))
f.flush()
You weren't hoping to get some sort of performance gain from this were you?
A:
I would recommend allocating a rather large buffer (4096 bytes at least) and flush that off to disk whenever it fills up. Using a one-byte buffer usually causes bad performance.
A:
I did this once for huffman decoding and ended up writing the bits as chars and thus handling everything internally as a plain old C string.
That way you don't have to worry about the trailing byte and it's human readable as well. Also checking bits is is easier since its just a matter of addressing the char array (binbuf[123] == '1') instead of having to fiddle with bits. Not the most optimized solution, but it solved my problem neatly.
The obvious drawback is that this representation uses more memory.
A:
The issue here is that many platforms do not have direct bit access. They group bits into a minimal package, often times the byte or word. Also, the protocol for stream devices does not facilitate transmission of individual bits.
The common method to deal with individual bits is to pack them into the smallest portable and (addressable) accessible unit. The unused bits are usually set to zero. This can be accomplished with binary arithmetic operations (OR, AND, EXCLUSIVE-OR, NOT, etc.).
With modern processors, bit twiddling slows down the machine and the performance. Memory is cheap and with large addressing spaces, justification for bit packing has become more difficult. Generally, bit packing is reserved for hardware oriented operations (and also transmission protocols). For example, if a processor's word capacity is 16 bits, the processor can probably handle 16 words faster than 16 bit manipulations in one word.
Also, keep in mind that writing to and from memory is often faster than I/O from streams. Efficient systems buffer data in memory before transmitting the data. You may want to consider this technique in your designs. Reducing I/O operations will improve the performance of your program.
|
Writing 'bits' to C++ file streams
|
How can I write 'one bit' into a file stream or file structure each time?
Is it possible to write to a queue and then flush it?
Is it possible with C# or Java?
This was needed when trying to implement an instance of Huffman coding. I can't write bits into files, so write them to a bitset and then (when compression was completed) write 8-bit piece of it each time (exclude last one).
|
[
"Buffering the individual bits until you've accumulated a whole byte seems like a good idea:\nbyte b;\nint s;\n\nvoid WriteBit(bool x)\n{\n b |= (x ? 1 : 0) << s;\n s++;\n\n if (s == 8)\n {\n WriteByte(b);\n b = 0;\n s = 0;\n }\n}\n\nYou just have to deal with the case when the number of bits to be written is not a multiple of eight.\n",
"You can use boost::dynamic_bitset along with std::ostream_iterator to achieve the desired result in a concise manner:\n#include <fstream>\n#include <iterator>\n#include <boost/dynamic_bitset.hpp>\n\ntypedef boost::dynamic_bitset<unsigned char> Bitset;\n\n// To help populate the bitset with literals */\nBitset& operator<<(Bitset& lhs, bool val) {lhs.push_back(val); return lhs;}\n\nint main()\n{\n Bitset bitset;\n bitset<<0<<1<<0<<1<<0<<1<<0<<1\n <<1<<0<<1<<0;\n\n std::ofstream os(\"data.dat\", std::ios::binary);\n std::ostream_iterator<char> osit(os);\n boost::to_block_range(bitset, osit);\n\n return 0;\n}\n\nI made the block size of my dynamic_bitset 8 bits by specifying unsigned char as the template parameter. You can make the block size bigger by specifying a larger integer type.\nboost::to_block_range dumps the bitset in blocks to the given output iterator. If there are empty remainder bits in the last block, they'll be padded with zero.\nWhen I open data.dat in a hex editor I see: AA 05. This is on a little endian platform (x64).\n",
"Which filesystem are you using?\nMost likely it stores the length of the file in bytes (are there any that don't?), so it's impossible to have a physical file that is not a whole number of bytes.\nSo if you are writing to the file as a stream of bits, you either have to truncate the last few bits when you are finished, or write out the final byte with what ammounts to junk in the remaining bits.\nHere's some Python code to get you started\nclass BitFile(file):\n def __init__(self, filename, mode):\n super(BitFile, self).__init__(filename, mode)\n self.bitCount=0\n self.byte = 0\n\n def write(self, bit):\n self.bitCount+=1\n self.byte = self.byte*2+bit\n if self.bitCount%8==0:\n super(BitFile, self).write(chr(self.byte))\n self.byte=0\n\n def close(self):\n if self.bitCount%8!=0:\n super(BitFile, self).write(chr(self.byte))\n super(BitFile, self).close() \n\nwith BitFile(\"bitfile.bin\",\"w\") as bf:\n bf.write(1)\n bf.write(1)\n bf.write(1)\n bf.write(0)\n bf.write(0)\n bf.write(0)\n bf.write(0)\n bf.write(0)\n bf.write(1)\n\n",
"You can't really. I'm pretty sure the problem is not with the language or the filesystem, but a hardware issue. Processors are designed to work with bytes. Probably the closest you can do is write your last byte over and over again, right padded with zeros, changing them as you go, one at a time.\nso to write bits '11011', you could do the following (python example, but any language should have facilities to do this:\nf.write(chr(0b10000000))\nf.flush()\nf.seek(-1)\nf.write(chr(0b11000000))\nf.flush()\nf.seek(-1)\nf.write(chr(0b11000000))\nf.flush()\nf.seek(-1)\nf.write(chr(0b11010000))\nf.flush()\nf.seek(-1)\nf.write(chr(0b11011000)) \nf.flush()\n\nYou weren't hoping to get some sort of performance gain from this were you?\n",
"I would recommend allocating a rather large buffer (4096 bytes at least) and flush that off to disk whenever it fills up. Using a one-byte buffer usually causes bad performance.\n",
"I did this once for huffman decoding and ended up writing the bits as chars and thus handling everything internally as a plain old C string. \nThat way you don't have to worry about the trailing byte and it's human readable as well. Also checking bits is is easier since its just a matter of addressing the char array (binbuf[123] == '1') instead of having to fiddle with bits. Not the most optimized solution, but it solved my problem neatly.\nThe obvious drawback is that this representation uses more memory.\n",
"The issue here is that many platforms do not have direct bit access. They group bits into a minimal package, often times the byte or word. Also, the protocol for stream devices does not facilitate transmission of individual bits. \nThe common method to deal with individual bits is to pack them into the smallest portable and (addressable) accessible unit. The unused bits are usually set to zero. This can be accomplished with binary arithmetic operations (OR, AND, EXCLUSIVE-OR, NOT, etc.).\nWith modern processors, bit twiddling slows down the machine and the performance. Memory is cheap and with large addressing spaces, justification for bit packing has become more difficult. Generally, bit packing is reserved for hardware oriented operations (and also transmission protocols). For example, if a processor's word capacity is 16 bits, the processor can probably handle 16 words faster than 16 bit manipulations in one word. \nAlso, keep in mind that writing to and from memory is often faster than I/O from streams. Efficient systems buffer data in memory before transmitting the data. You may want to consider this technique in your designs. Reducing I/O operations will improve the performance of your program.\n"
] |
[
13,
8,
3,
0,
0,
0,
0
] |
[] |
[] |
[
"bit_manipulation",
"c#",
"c++",
"java",
"python"
] |
stackoverflow_0002476748_bit_manipulation_c#_c++_java_python.txt
|
Q:
Why does my buffered GraphicsContext application have a flickering problem?
import wx
class MainFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=DoubleBufferTest(self,-1)
self.Show(True)
class DoubleBufferTest(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id,style=wx.FULL_REPAINT_ON_RESIZE)
self.SetBackgroundColour("#FFFFFF")
self.timer = wx.Timer(self)
self.timer.Start(100)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self,event):
event.Skip()
dc = wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(640, 480))
gc = wx.GraphicsContext.Create(dc)
gc.PushState()
gc.SetBrush(wx.Brush("#CFCFCF"))
bgRect=gc.CreatePath()
bgRect.AddRectangle(0,0,640,480)
gc.FillPath(bgRect)
gc.PopState()
dc2=wx.PaintDC(self)
dc2.Blit(0,0,640,480,dc,0,0)
def update(self,event):
self.Refresh()
app = wx.App(False)
f=MainFrame(None,"Test")
app.MainLoop()
I've come up with this code to draw double buffered GraphicsContext content onto a panel, but there's a constant flickering across the window. I've tried different kinds of paths, like lines and curves but it's still there and I don't know what's causing it.
A:
You get flicker because each Refresh() causes the background to get erased before calling onPaint. You need to bind to EVT_ERASE_BACKGROUND and make it a no-op.
class DoubleBufferTest(wx.Panel):
def __init__(self,parent=None,id=-1):
# ... existing code ...
self.Bind(wx.EVT_ERASE_BACKGROUND, self.onErase)
def onErase(self, event):
pass
# ... existing code ...
A:
If you're using a relatively modern wxWidgets, you can use wx.BufferedPaintDC and avoid having to muck around with the memory DC and painting and blitting on your own. Also, on windows, FULL_REPAINT_ON_RESIZE often causes flickering even when you're not resizing the window due to funny things going on under the covers - if you don't need it, going with NO_FULL_REPAINT_ON_RESIZE may help. Otherwise, you'll want to simplify your code some to make sure you can get the simplest thing to work, and perhaps take a look at the DoubleBufferedDrawing wiki page at wxpython.org.
|
Why does my buffered GraphicsContext application have a flickering problem?
|
import wx
class MainFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=DoubleBufferTest(self,-1)
self.Show(True)
class DoubleBufferTest(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id,style=wx.FULL_REPAINT_ON_RESIZE)
self.SetBackgroundColour("#FFFFFF")
self.timer = wx.Timer(self)
self.timer.Start(100)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self,event):
event.Skip()
dc = wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(640, 480))
gc = wx.GraphicsContext.Create(dc)
gc.PushState()
gc.SetBrush(wx.Brush("#CFCFCF"))
bgRect=gc.CreatePath()
bgRect.AddRectangle(0,0,640,480)
gc.FillPath(bgRect)
gc.PopState()
dc2=wx.PaintDC(self)
dc2.Blit(0,0,640,480,dc,0,0)
def update(self,event):
self.Refresh()
app = wx.App(False)
f=MainFrame(None,"Test")
app.MainLoop()
I've come up with this code to draw double buffered GraphicsContext content onto a panel, but there's a constant flickering across the window. I've tried different kinds of paths, like lines and curves but it's still there and I don't know what's causing it.
|
[
"You get flicker because each Refresh() causes the background to get erased before calling onPaint. You need to bind to EVT_ERASE_BACKGROUND and make it a no-op.\nclass DoubleBufferTest(wx.Panel):\n def __init__(self,parent=None,id=-1):\n # ... existing code ...\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.onErase)\n def onErase(self, event):\n pass\n # ... existing code ...\n\n",
"If you're using a relatively modern wxWidgets, you can use wx.BufferedPaintDC and avoid having to muck around with the memory DC and painting and blitting on your own. Also, on windows, FULL_REPAINT_ON_RESIZE often causes flickering even when you're not resizing the window due to funny things going on under the covers - if you don't need it, going with NO_FULL_REPAINT_ON_RESIZE may help. Otherwise, you'll want to simplify your code some to make sure you can get the simplest thing to work, and perhaps take a look at the DoubleBufferedDrawing wiki page at wxpython.org.\n"
] |
[
2,
1
] |
[] |
[] |
[
"graphicscontext",
"python",
"wxpython"
] |
stackoverflow_0002452012_graphicscontext_python_wxpython.txt
|
Q:
Python (Twisted) - reading from fifo and sending read data to multiple protocols
Im trying to write some kind of multi protocol bot (jabber/irc) that would read messages from fifo file (one liners mostly) and then send them to irc channel and jabber contacts. So far, I managed to create two factories to connect to jabber and irc, and they seem to be working.
However, I've problem with reading the fifo file - I have no idea how to read it in a loop (open file, read line, close file, jump to open file and so on) outside of reactor loop to get the data I need to send, and then get that data to reactor loop for sending in both protocols. I've been looking for information on how to do it in best way, but Im totally lost in the dark. Any suggestion/help would be highly appreciated.
Thanks in advance!
A:
You can read/write on a file descriptor without blocking the reactor as you do with sockets, by the way doesn't sockets use file descriptors?
In your case create a class that implements twisted.internet.interfaces.IReadDescriptor and add to reactor using twisted.internet.interfaces.IReactorFDSet.addReader. For an example of IReadDescriptor implementation look at twisted.internet.tcp.Connection.
I cannot be more specific because i never did by my self, but i hope this could be a start point.
A:
The fifo is the problem. Read from a socket instead. This will fit info the Twisted event-driven model much better. Trying to do things outside the control of the reactor is usually the wrong approach.
---- update based on feedback that the fifo is an external constraint, not avoidable ----
OK, the central issue is that you can not write code in the main (and only) thread of your Twisted app that makes blocking read calls to a fifo. That will cause the whole app to stall if there is nothing to read. So you're either looking at reading the fifo asynchronously, creating a separate thread to read it, or splitting the app in two.
The last option is the simplest - modify the Twisted app so that it listens on a socket and write a separate little "forwarder" app that runs in a simple loop, reading the fifo and writing everything it hears to the socket.
|
Python (Twisted) - reading from fifo and sending read data to multiple protocols
|
Im trying to write some kind of multi protocol bot (jabber/irc) that would read messages from fifo file (one liners mostly) and then send them to irc channel and jabber contacts. So far, I managed to create two factories to connect to jabber and irc, and they seem to be working.
However, I've problem with reading the fifo file - I have no idea how to read it in a loop (open file, read line, close file, jump to open file and so on) outside of reactor loop to get the data I need to send, and then get that data to reactor loop for sending in both protocols. I've been looking for information on how to do it in best way, but Im totally lost in the dark. Any suggestion/help would be highly appreciated.
Thanks in advance!
|
[
"You can read/write on a file descriptor without blocking the reactor as you do with sockets, by the way doesn't sockets use file descriptors?\nIn your case create a class that implements twisted.internet.interfaces.IReadDescriptor and add to reactor using twisted.internet.interfaces.IReactorFDSet.addReader. For an example of IReadDescriptor implementation look at twisted.internet.tcp.Connection.\nI cannot be more specific because i never did by my self, but i hope this could be a start point.\n",
"The fifo is the problem. Read from a socket instead. This will fit info the Twisted event-driven model much better. Trying to do things outside the control of the reactor is usually the wrong approach.\n---- update based on feedback that the fifo is an external constraint, not avoidable ----\nOK, the central issue is that you can not write code in the main (and only) thread of your Twisted app that makes blocking read calls to a fifo. That will cause the whole app to stall if there is nothing to read. So you're either looking at reading the fifo asynchronously, creating a separate thread to read it, or splitting the app in two.\nThe last option is the simplest - modify the Twisted app so that it listens on a socket and write a separate little \"forwarder\" app that runs in a simple loop, reading the fifo and writing everything it hears to the socket.\n"
] |
[
3,
1
] |
[] |
[] |
[
"fifo",
"irc",
"python",
"twisted",
"xmpp"
] |
stackoverflow_0002476234_fifo_irc_python_twisted_xmpp.txt
|
Q:
Python: Check if all dictionaries in list are empty
I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line.
Is there a single line way to do the following (not including the print)?
l = [{},{},{}] # this list is generated elsewhere...
all_empty = True
for i in l:
if i:
all_empty = False
print all_empty
Somewhat new to python... I don't know if there is a shorthand built-in way to check this. Thanks in advance.
A:
all(not d for d in l)
A:
not any(d for d in l) could be shortened to just not any(l) in this case.
A:
not any(d for d in l) is equivalent by De Morgan's Law to all(not d for d in l), but applies just one not operator. The short-circuiting behavior is also equivalent.
Edit 1: the inner genexp is actually (innocuous but) redundant: not any(l) is faster and more concise.
Edit 2: a comment claims that all(not d for d in l) is "more what you want to express" than not any(l), and I strongly disagree: even in natural language, "all items of the list are unpopulated" isn't any more normal, direct or clear than "no item of the list is populated" -- beyond the absolute logical equivalence by the laws of logic, the two ways of expression are very close and roughly equivalent in terms of human psychology, too.
|
Python: Check if all dictionaries in list are empty
|
I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line.
Is there a single line way to do the following (not including the print)?
l = [{},{},{}] # this list is generated elsewhere...
all_empty = True
for i in l:
if i:
all_empty = False
print all_empty
Somewhat new to python... I don't know if there is a shorthand built-in way to check this. Thanks in advance.
|
[
"all(not d for d in l)\n\n",
"not any(d for d in l) could be shortened to just not any(l) in this case.\n",
"not any(d for d in l) is equivalent by De Morgan's Law to all(not d for d in l), but applies just one not operator. The short-circuiting behavior is also equivalent.\nEdit 1: the inner genexp is actually (innocuous but) redundant: not any(l) is faster and more concise.\nEdit 2: a comment claims that all(not d for d in l) is \"more what you want to express\" than not any(l), and I strongly disagree: even in natural language, \"all items of the list are unpopulated\" isn't any more normal, direct or clear than \"no item of the list is populated\" -- beyond the absolute logical equivalence by the laws of logic, the two ways of expression are very close and roughly equivalent in terms of human psychology, too.\n"
] |
[
26,
10,
9
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002479472_python.txt
|
Q:
Segfault in multithreaded python extension in C
I have a very trimmed down example that creates a segfault that I can't seem to get rid of. Python script calls a C function in an extension, which creates a new thread using pthreads. I use PyGILState_Ensure and PyGILState_Release around my python call (PyRun_SimpleString) in the new thread, but perhaps I'm not using them correctly or have missed some other step. Commenting out the python calls in the receive_audio function, the segfault no longer happens. Any ideas?
Output:
python lib/test.py
(Main Thread) initmodule complete
(Main Thread) Calling run_thread()
(Main Thread) Creating thread
(New Thread) In receive_audio() - acquiring GIL
(New Thread) python print!
(New Thread) In receive_audio() - released GIL
(New Thread) Looping 0
Segmentation fault
C Code as follows:
PyMODINIT_FUNC streamaudio() {
PyObject *m = Py_InitModule("streamaudio", methods);
PyEval_InitThreads();
mainThreadState = PyThreadState_Get();
PyEval_ReleaseLock();
printf("(Main Thread) initmodule complete\n");
}
static PyObject* run_thread(PyObject* self, PyObject* args)
{
int ok, stream_id;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
ok = PyArg_ParseTuple(args, "i", &stream_id);
PyRun_SimpleString("print '(Main Thread) Creating thread'\n");
int rc = pthread_create(&thread, NULL, receive_audio, (void*)stream_id);
PyRun_SimpleString("print '(Main Thread) Thread created'\n");
PyGILState_Release(gstate);
return Py_BuildValue("i", rc);
}
void* receive_audio(void *x)
{
printf("(New Thread) In receive_audio() - acquiring GIL\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyRun_SimpleString("print '(New Thread) python print!'\n");
PyGILState_Release(gstate);
printf("(New Thread) In receive_audio() - released GIL\n");
int i;
for (i = 0; i < 100; i++) {
printf("(New Thread) Looping %d\n", i);
sleep(1);
}
}
A:
I'm not positive that this will be relevant to your question, but one thing that looks suspicious is the PyEval_ReleaseLock() call in your module initializer function. I doubt that Python expects your module initializer to release the GIL out from underneath it, and a quick look at some example code here doesn't show anything along these lines. Could you try removing that PyEval_ReleaseLock() call and tell us what happens?
BTW, I agree that the PyGILState_*() calls within run_thread() should have no effect; you should be able to just remove them.
|
Segfault in multithreaded python extension in C
|
I have a very trimmed down example that creates a segfault that I can't seem to get rid of. Python script calls a C function in an extension, which creates a new thread using pthreads. I use PyGILState_Ensure and PyGILState_Release around my python call (PyRun_SimpleString) in the new thread, but perhaps I'm not using them correctly or have missed some other step. Commenting out the python calls in the receive_audio function, the segfault no longer happens. Any ideas?
Output:
python lib/test.py
(Main Thread) initmodule complete
(Main Thread) Calling run_thread()
(Main Thread) Creating thread
(New Thread) In receive_audio() - acquiring GIL
(New Thread) python print!
(New Thread) In receive_audio() - released GIL
(New Thread) Looping 0
Segmentation fault
C Code as follows:
PyMODINIT_FUNC streamaudio() {
PyObject *m = Py_InitModule("streamaudio", methods);
PyEval_InitThreads();
mainThreadState = PyThreadState_Get();
PyEval_ReleaseLock();
printf("(Main Thread) initmodule complete\n");
}
static PyObject* run_thread(PyObject* self, PyObject* args)
{
int ok, stream_id;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
ok = PyArg_ParseTuple(args, "i", &stream_id);
PyRun_SimpleString("print '(Main Thread) Creating thread'\n");
int rc = pthread_create(&thread, NULL, receive_audio, (void*)stream_id);
PyRun_SimpleString("print '(Main Thread) Thread created'\n");
PyGILState_Release(gstate);
return Py_BuildValue("i", rc);
}
void* receive_audio(void *x)
{
printf("(New Thread) In receive_audio() - acquiring GIL\n");
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyRun_SimpleString("print '(New Thread) python print!'\n");
PyGILState_Release(gstate);
printf("(New Thread) In receive_audio() - released GIL\n");
int i;
for (i = 0; i < 100; i++) {
printf("(New Thread) Looping %d\n", i);
sleep(1);
}
}
|
[
"I'm not positive that this will be relevant to your question, but one thing that looks suspicious is the PyEval_ReleaseLock() call in your module initializer function. I doubt that Python expects your module initializer to release the GIL out from underneath it, and a quick look at some example code here doesn't show anything along these lines. Could you try removing that PyEval_ReleaseLock() call and tell us what happens?\nBTW, I agree that the PyGILState_*() calls within run_thread() should have no effect; you should be able to just remove them.\n"
] |
[
3
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0002478939_multithreading_python.txt
|
Q:
Does python import all the listed libraries?
I'm just wondering, I often have really long python files and imports tend to stack quite quickly.
PEP8 says that the imports should always be written at the beginning of the file.
Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary libraries get called?
Does it make sense to worry about this? Is there no reason to import libraries within the functions or classes that need them?
A:
Every time Python hits an import statement, it checks to see if that module has already been imported, and if not, imports it. So the imports at the top of your file will happen as soon as your file is run or imported by another module.
There is some overhead to this, so it's generally best to keep imports at the top of your file so that cost gets taken care of up front.
A:
The best place for imports is at the top of your file. That documents the dependencies in one place and makes errors from their absence appear earlier. The import itself actually occurs at the time of the import statement, but this seldom matters much.
It is not typical that you have anything to gain by not importing a library until you are in a function or method that needs it. (There is never anything to gain by doing so inside the body of a class.) It is rare that you want optional dependencies and even rarer that this is the right technique to get them, though. Perhaps you can share a compelling use case?
A:
Does it make sense to worry about
this?
No
There no reason to import libraries within the functions or classes that need them.
It's just slow because the import statement has to check to see if it's been imported once, and realize that it has been imported.
If you put this in a function that's called frequently, you can waste some time with all the import checking.
A:
Imports happen when the module that contains the imports gets executed or imported, not when the functions are called.
Ordinarily, I wouldn't worry about it. If you are encountering slowdowns, you might profile to see if your problem is related to this. If it is, you can check to see if your module can divided up into smaller modules.
But if all the files are getting used by the same program, you'll just end up importing everything anyway.
A:
If a function inside a module is the only one to import a given other module (say you have a function sending tweets, only if some configuration option is on), then it makes sense to import that specific module in the function.
Unless I see some profiling data proving otherwise, my guess is that the overhead of an import statement in a function is completely negligible.
|
Does python import all the listed libraries?
|
I'm just wondering, I often have really long python files and imports tend to stack quite quickly.
PEP8 says that the imports should always be written at the beginning of the file.
Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary libraries get called?
Does it make sense to worry about this? Is there no reason to import libraries within the functions or classes that need them?
|
[
"Every time Python hits an import statement, it checks to see if that module has already been imported, and if not, imports it. So the imports at the top of your file will happen as soon as your file is run or imported by another module.\nThere is some overhead to this, so it's generally best to keep imports at the top of your file so that cost gets taken care of up front.\n",
"The best place for imports is at the top of your file. That documents the dependencies in one place and makes errors from their absence appear earlier. The import itself actually occurs at the time of the import statement, but this seldom matters much.\nIt is not typical that you have anything to gain by not importing a library until you are in a function or method that needs it. (There is never anything to gain by doing so inside the body of a class.) It is rare that you want optional dependencies and even rarer that this is the right technique to get them, though. Perhaps you can share a compelling use case?\n",
"\nDoes it make sense to worry about\n this?\n\nNo\nThere no reason to import libraries within the functions or classes that need them.\nIt's just slow because the import statement has to check to see if it's been imported once, and realize that it has been imported.\nIf you put this in a function that's called frequently, you can waste some time with all the import checking.\n",
"Imports happen when the module that contains the imports gets executed or imported, not when the functions are called.\nOrdinarily, I wouldn't worry about it. If you are encountering slowdowns, you might profile to see if your problem is related to this. If it is, you can check to see if your module can divided up into smaller modules.\nBut if all the files are getting used by the same program, you'll just end up importing everything anyway.\n",
"If a function inside a module is the only one to import a given other module (say you have a function sending tweets, only if some configuration option is on), then it makes sense to import that specific module in the function.\nUnless I see some profiling data proving otherwise, my guess is that the overhead of an import statement in a function is completely negligible.\n"
] |
[
3,
2,
1,
0,
0
] |
[] |
[] |
[
"import",
"libraries",
"pep8",
"python"
] |
stackoverflow_0002479902_import_libraries_pep8_python.txt
|
Q:
How do I go about setting up an application so that it has a persistent process in memory and does not have to re-initialize to run?
I'm not sure what's the appropriate terminology here, but I'd like to have an application running passively that is ready to accept commands without having to reinitialize the whole thing.
The precise application is a machine learning system written in Python that takes a somewhat long time to train a classifier or to load a cached classifier. Once the classifier is loaded into memory, test cases or predictions made by the classifier happen very quickly.
I want to have to speed advantage of having the classifier already loaded into memory without having to reclassify/reload so that I can access the classifier quickly through other interfaces (command line, PHP, etc.).
This reminds me of asynchrony in Javascript, and I imagine some of the same underlying concepts are used here.
What's the best way to go about doing this?
A:
Depending on your implementation this is known as a server process, a daemon, a Windows service etc.
A typical implementation will run and accept incoming network connections and service those for clients (e.g. an HTTP server). Some threading or other asynchronous mechanism will exist to allow servicing of multiple clients simultaneously (you may not need this, depending on your requirements).
|
How do I go about setting up an application so that it has a persistent process in memory and does not have to re-initialize to run?
|
I'm not sure what's the appropriate terminology here, but I'd like to have an application running passively that is ready to accept commands without having to reinitialize the whole thing.
The precise application is a machine learning system written in Python that takes a somewhat long time to train a classifier or to load a cached classifier. Once the classifier is loaded into memory, test cases or predictions made by the classifier happen very quickly.
I want to have to speed advantage of having the classifier already loaded into memory without having to reclassify/reload so that I can access the classifier quickly through other interfaces (command line, PHP, etc.).
This reminds me of asynchrony in Javascript, and I imagine some of the same underlying concepts are used here.
What's the best way to go about doing this?
|
[
"Depending on your implementation this is known as a server process, a daemon, a Windows service etc.\nA typical implementation will run and accept incoming network connections and service those for clients (e.g. an HTTP server). Some threading or other asynchronous mechanism will exist to allow servicing of multiple clients simultaneously (you may not need this, depending on your requirements).\n"
] |
[
2
] |
[] |
[] |
[
"asynchronous",
"command_line",
"machine_learning",
"php",
"python"
] |
stackoverflow_0002480363_asynchronous_command_line_machine_learning_php_python.txt
|
Q:
Directory layout for a Python project with C extension modules
We have numerous projects in our organization that are mixed Python/C. Currently we're trying to standardize on a directory layout for our projects and are trying to come up with a convenient scheme. One point of contention is where to put C extension modules in the tree.
We're tossing around a couple of options (relative to project root):
./src/package/subpackage/module.c
or alongside the python modules in the package tree:
./package/subpackage/module.c
or in a src directory in the subpackage:
./package/subpackage/src/module.c
One reason for keeping them out of the package directories could be because it will lead to clutter, especially if there are other .c and .h files which aren't themselves modules but still need to be compiled. Also in the "integrated" scheme, what do you do with headers and files that are used by more than one module? Put them in a common top-level directory?
I'd be interested to know what other people are using, or if there are any established best practices for this.
A:
I think the layout of the Python standard library is a reasonable example: under trunk, which is basically the root for the SVN repo (net of branches &c), the Modules directory has a lot of .c and .h files, the Lib directory a lot of .py files.
In my own projects I tend to divide sources up similarly (and actually if I have Cython or Pyrex ones, or SWIG etc, I tend to have other directories yet for subdivision), though with different directory names (I confess I don't have a consistent rule for the directory names themselves, nor have I ever heard of good guidelines for such names).
|
Directory layout for a Python project with C extension modules
|
We have numerous projects in our organization that are mixed Python/C. Currently we're trying to standardize on a directory layout for our projects and are trying to come up with a convenient scheme. One point of contention is where to put C extension modules in the tree.
We're tossing around a couple of options (relative to project root):
./src/package/subpackage/module.c
or alongside the python modules in the package tree:
./package/subpackage/module.c
or in a src directory in the subpackage:
./package/subpackage/src/module.c
One reason for keeping them out of the package directories could be because it will lead to clutter, especially if there are other .c and .h files which aren't themselves modules but still need to be compiled. Also in the "integrated" scheme, what do you do with headers and files that are used by more than one module? Put them in a common top-level directory?
I'd be interested to know what other people are using, or if there are any established best practices for this.
|
[
"I think the layout of the Python standard library is a reasonable example: under trunk, which is basically the root for the SVN repo (net of branches &c), the Modules directory has a lot of .c and .h files, the Lib directory a lot of .py files.\nIn my own projects I tend to divide sources up similarly (and actually if I have Cython or Pyrex ones, or SWIG etc, I tend to have other directories yet for subdivision), though with different directory names (I confess I don't have a consistent rule for the directory names themselves, nor have I ever heard of good guidelines for such names).\n"
] |
[
1
] |
[] |
[] |
[
"c",
"module",
"python"
] |
stackoverflow_0002480565_c_module_python.txt
|
Q:
How can I optimize this code?
I'm developing a logger daemon to squid to grab the logs on a mongodb database. But I'm experiencing too much cpu utilization. How can I optimize this code?
from sys import stdin
from pymongo import Connection
connection = Connection()
db = connection.squid
logs = db.logs
buffer = []
a = 'timestamp'
b = 'resp_time'
c = 'src_ip'
d = 'cache_status'
e = 'reply_size'
f = 'req_method'
g = 'req_url'
h = 'username'
i = 'dst_ip'
j = 'mime_type'
L = 'L'
while True:
l = stdin.readline()
if l[0] == L:
l = l[1:].split()
buffer.append({
a: float(l[0]),
b: int(l[1]),
c: l[2],
d: l[3],
e: int(l[4]),
f: l[5],
g: l[6],
h: l[7],
i: l[8],
j: l[9]
}
)
if len(buffer) == 1000:
logs.insert(buffer)
buffer = []
if not l:
break
connection.disconnect()
A:
This might be a better question for a python profiler. There's a few builtin Python profiling modules such as cProfile; you can read more about it here.
A:
I'd suspect it might actually be readline() causing cpu utilization. Try running the same code with the readline replaced with just looking at some constant buffer provided by you. And try running with the database inserts commented out. Establish which one of these is the culprit.
A:
The cpu usage is given by that active loop While True.
How many lines / minute do you have? put the
if len(buffer) == 1000:
logs.insert(buffer)
buffer = []
check after the buffer.append
I will tell you more after you tell me how many insertions you get so far
|
How can I optimize this code?
|
I'm developing a logger daemon to squid to grab the logs on a mongodb database. But I'm experiencing too much cpu utilization. How can I optimize this code?
from sys import stdin
from pymongo import Connection
connection = Connection()
db = connection.squid
logs = db.logs
buffer = []
a = 'timestamp'
b = 'resp_time'
c = 'src_ip'
d = 'cache_status'
e = 'reply_size'
f = 'req_method'
g = 'req_url'
h = 'username'
i = 'dst_ip'
j = 'mime_type'
L = 'L'
while True:
l = stdin.readline()
if l[0] == L:
l = l[1:].split()
buffer.append({
a: float(l[0]),
b: int(l[1]),
c: l[2],
d: l[3],
e: int(l[4]),
f: l[5],
g: l[6],
h: l[7],
i: l[8],
j: l[9]
}
)
if len(buffer) == 1000:
logs.insert(buffer)
buffer = []
if not l:
break
connection.disconnect()
|
[
"This might be a better question for a python profiler. There's a few builtin Python profiling modules such as cProfile; you can read more about it here.\n",
"I'd suspect it might actually be readline() causing cpu utilization. Try running the same code with the readline replaced with just looking at some constant buffer provided by you. And try running with the database inserts commented out. Establish which one of these is the culprit. \n",
"The cpu usage is given by that active loop While True. \nHow many lines / minute do you have? put the\nif len(buffer) == 1000: \n logs.insert(buffer)\n buffer = []\n\ncheck after the buffer.append\nI will tell you more after you tell me how many insertions you get so far\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"mongodb",
"python"
] |
stackoverflow_0002480729_mongodb_python.txt
|
Q:
In Python, how do I do a string replacement AND retrive the replaced substring?
In Perl, I would write:
$x = "abbbc";
$x =~ s/(b+)/z/;
print "Replaced $1 and ended up with $x\n";
# "Replaced bbb and ended up with azc"
How do I do this in Python -- do a regular-expression string replacement and record what it was that got replaced?
A:
Python does not simultaneously return a match and a substitution. Calling group(0) on a returned Match object will find the matched substring:
>>> r=re.compile('(b+)')
>>> r.search('abbbc')
<_sre.SRE_Match object at 0x7f04af497af8>
>>> r.search('abbbc').group(0)
'bbb'
>>> r.sub('z', 'abbbc')
'azc'
|
In Python, how do I do a string replacement AND retrive the replaced substring?
|
In Perl, I would write:
$x = "abbbc";
$x =~ s/(b+)/z/;
print "Replaced $1 and ended up with $x\n";
# "Replaced bbb and ended up with azc"
How do I do this in Python -- do a regular-expression string replacement and record what it was that got replaced?
|
[
"Python does not simultaneously return a match and a substitution. Calling group(0) on a returned Match object will find the matched substring:\n>>> r=re.compile('(b+)')\n>>> r.search('abbbc')\n<_sre.SRE_Match object at 0x7f04af497af8>\n>>> r.search('abbbc').group(0)\n'bbb'\n>>> r.sub('z', 'abbbc')\n'azc'\n\n"
] |
[
6
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002480841_python_regex.txt
|
Q:
Export list as .txt (Python)
My Python module has a list that contains all the data I want to save as a .txt file somewhere. The list contains several tuples like so:
list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
How do I print the list so each tuple item is separated by a tab and each tuple is separated by a newline?
Thanks
A:
You can solve it, as other answers suggest by just joining lines but better way would be to just use python csv module, so that later on you can easily change delimter or add header etc and read it back too, looks like you want tab delimited file
import sys
import csv
csv_writer = csv.writer(sys.stdout, delimiter='\t')
rows = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
csv_writer.writerows(rows)
output:
one two three
four five six
A:
print '\n'.join('\t'.join(x) for x in L)
A:
Try this
"\n".join(map("\t".join,l))
Test
>>> l = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
>>> print "\n".join(map("\t".join,l))
one two three
four five six
>>>
A:
open("data.txt", "w").write("\n".join(("\t".join(item)) for item in list))
A:
The most idiomatic way, IMHO, is to use a list comprehension and a join:
print '\n'.join('\t'.join(i) for i in l)
A:
You don't have to join the list in advance:
with open("output.txt", "w") as fp:
fp.writelines('%s\n' % '\t'.join(items) for items in a_list)
|
Export list as .txt (Python)
|
My Python module has a list that contains all the data I want to save as a .txt file somewhere. The list contains several tuples like so:
list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
How do I print the list so each tuple item is separated by a tab and each tuple is separated by a newline?
Thanks
|
[
"You can solve it, as other answers suggest by just joining lines but better way would be to just use python csv module, so that later on you can easily change delimter or add header etc and read it back too, looks like you want tab delimited file\nimport sys\nimport csv\n\ncsv_writer = csv.writer(sys.stdout, delimiter='\\t')\nrows = [ ('one', 'two', 'three'), ('four', 'five', 'six')]\ncsv_writer.writerows(rows)\n\noutput:\none two three\nfour five six\n\n",
"print '\\n'.join('\\t'.join(x) for x in L)\n\n",
"Try this\n\"\\n\".join(map(\"\\t\".join,l))\n\nTest\n>>> l = [ ('one', 'two', 'three'), ('four', 'five', 'six')]\n>>> print \"\\n\".join(map(\"\\t\".join,l))\none two three\nfour five six\n>>>\n\n",
"open(\"data.txt\", \"w\").write(\"\\n\".join((\"\\t\".join(item)) for item in list))\n\n",
"The most idiomatic way, IMHO, is to use a list comprehension and a join:\nprint '\\n'.join('\\t'.join(i) for i in l)\n\n",
"You don't have to join the list in advance:\nwith open(\"output.txt\", \"w\") as fp:\n fp.writelines('%s\\n' % '\\t'.join(items) for items in a_list)\n\n"
] |
[
9,
8,
2,
2,
1,
0
] |
[] |
[] |
[
"csv",
"export",
"list",
"python",
"tuples"
] |
stackoverflow_0002308883_csv_export_list_python_tuples.txt
|
Q:
ctypes buffer modification
I need to call a c library from my python code. The c library does a lot of image manipulation, so I am passing it image buffers allocated using create_string_buffer.
The problem is that I also need to manipulate and change these buffers. What is the best way to reach in and twiddle individual values in my buffers? The buffers are all uint8 buffers.
A:
You mean, something like...:
>>> import ctypes
>>> x = ctypes.create_string_buffer('howdy!')
>>> x.value
'howdy!'
>>> x[0] = 'C'
>>> x.value
'Cowdy!'
...?
A:
You may find that Cython is a lot nicer then the ctypes module for melding C libraries with Python code.
|
ctypes buffer modification
|
I need to call a c library from my python code. The c library does a lot of image manipulation, so I am passing it image buffers allocated using create_string_buffer.
The problem is that I also need to manipulate and change these buffers. What is the best way to reach in and twiddle individual values in my buffers? The buffers are all uint8 buffers.
|
[
"You mean, something like...:\n>>> import ctypes\n>>> x = ctypes.create_string_buffer('howdy!')\n>>> x.value\n'howdy!'\n>>> x[0] = 'C'\n>>> x.value\n'Cowdy!'\n\n...?\n",
"You may find that Cython is a lot nicer then the ctypes module for melding C libraries with Python code.\n"
] |
[
2,
1
] |
[] |
[] |
[
"ctypes",
"python"
] |
stackoverflow_0002480197_ctypes_python.txt
|
Q:
Is it inefficient to access a python class member container in a loop statement?
I'm trying to adopt some best practices to keep my python code efficient. I've heard that accessing a member variable inside of a loop can incur a dictionary lookup for every iteration of the loop, so I cache these in local variables to use inside the loop.
My question is about the loop statement itself... if I have the following class:
class A(object):
def __init__(self)
self.myList = [ 'a','b','c', 'd', 'e' ]
Does the following code in a member function incur one, or one-per-loop-iteration (5) dictionary lookups?
for letter in self.myList:
print letter
IE, should I adopt the following pattern, if I am concerned about efficiency...
localList = self.myList
for letter in localList:
print letter
or is that actually LESS efficient due to the local variable assign?
Note, I am aware that early optimization is a dangerous pitfall if I'm concerned about the overall efficiency of code development. Here I am specifically asking about the efficiency of the code, not the coding.
A:
An iterator is created from self.myList, and that iterator is used. No other extra lookups are done on self for the iteration.
|
Is it inefficient to access a python class member container in a loop statement?
|
I'm trying to adopt some best practices to keep my python code efficient. I've heard that accessing a member variable inside of a loop can incur a dictionary lookup for every iteration of the loop, so I cache these in local variables to use inside the loop.
My question is about the loop statement itself... if I have the following class:
class A(object):
def __init__(self)
self.myList = [ 'a','b','c', 'd', 'e' ]
Does the following code in a member function incur one, or one-per-loop-iteration (5) dictionary lookups?
for letter in self.myList:
print letter
IE, should I adopt the following pattern, if I am concerned about efficiency...
localList = self.myList
for letter in localList:
print letter
or is that actually LESS efficient due to the local variable assign?
Note, I am aware that early optimization is a dangerous pitfall if I'm concerned about the overall efficiency of code development. Here I am specifically asking about the efficiency of the code, not the coding.
|
[
"An iterator is created from self.myList, and that iterator is used. No other extra lookups are done on self for the iteration.\n"
] |
[
6
] |
[] |
[] |
[
"language_features",
"performance",
"python"
] |
stackoverflow_0002481254_language_features_performance_python.txt
|
Q:
Python: Creating directories
I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:
import os
os.mkdir('~/Desktop/downloaded/')
A:
You can't simply use ~ You must use os.path.expanduser to replace the ~ with a proper path.
A:
Use
import os
os.mkdir(os.path.expanduser("~/Desktop/downloaded"))
The ~ character is a POSIX shell convention that represents the contents of the HOME environment variable. So, when you type in a shell:
$ mkdir ~/Desktop/downloaded
it's the same as typing
$ mkdir $HOME/Desktop/downloaded
Try changing the HOME environment variable to verify what I say.
Since it's a shell convention, it's something that neither the kernel treats specially, nor Python, and the python os.mkdir function is just a wrapper around the kernel mkdir(2) system call. As a conveniency, Python provides the os.path.expanduser function to replace the tilde with the contents of the HOME env var.
$ HOME=/tmp # it is already exported
$ python
Python 2.6.4 (r264:75706, Mar 2 2010, 00:28:19)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.expanduser("~/dada")
'/tmp/dada'
A:
another way, use os.environ
import os
home=os.environ["HOME"]
path=os.path.join(home,"Desktop","download")
try:
os.mkdir(path)
except IOError,e:
print e
else:
print "Successful"
|
Python: Creating directories
|
I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:
import os
os.mkdir('~/Desktop/downloaded/')
|
[
"You can't simply use ~ You must use os.path.expanduser to replace the ~ with a proper path.\n",
"Use\nimport os\nos.mkdir(os.path.expanduser(\"~/Desktop/downloaded\"))\n\nThe ~ character is a POSIX shell convention that represents the contents of the HOME environment variable. So, when you type in a shell:\n$ mkdir ~/Desktop/downloaded\n\nit's the same as typing\n$ mkdir $HOME/Desktop/downloaded\n\nTry changing the HOME environment variable to verify what I say.\nSince it's a shell convention, it's something that neither the kernel treats specially, nor Python, and the python os.mkdir function is just a wrapper around the kernel mkdir(2) system call. As a conveniency, Python provides the os.path.expanduser function to replace the tilde with the contents of the HOME env var.\n$ HOME=/tmp # it is already exported\n$ python\nPython 2.6.4 (r264:75706, Mar 2 2010, 00:28:19) \n[GCC 4.3.4] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os\n>>> os.path.expanduser(\"~/dada\")\n'/tmp/dada'\n\n",
"another way, use os.environ\nimport os\nhome=os.environ[\"HOME\"]\npath=os.path.join(home,\"Desktop\",\"download\")\ntry:\n os.mkdir(path)\nexcept IOError,e:\n print e\nelse:\n print \"Successful\"\n\n"
] |
[
15,
10,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002480936_python.txt
|
Q:
Why does socket.inet_ntoa returns packed format in python
Why does socket.inet_aton returns packed format in python?
If I am storing the IP as integer in Database (mysql), do I have to always extract the integer value or is there any easier way out?
A:
inet_aton is clearly documented to perform exactly this task, and the "why" is even very explicitly explained...:
Convert an IPv4 address from
dotted-quad string format (for
example, ‘123.45.67.89’) to 32-bit
packed binary format, as a string four
characters in length. This is useful
when conversing with a program that
uses the standard C library and needs
objects of type struct in_addr, which
is the C type for the 32-bit packed
binary this function returns.
To convert from a 4-byte string to an integer and vice versa, see the struct module.
|
Why does socket.inet_ntoa returns packed format in python
|
Why does socket.inet_aton returns packed format in python?
If I am storing the IP as integer in Database (mysql), do I have to always extract the integer value or is there any easier way out?
|
[
"inet_aton is clearly documented to perform exactly this task, and the \"why\" is even very explicitly explained...:\n\nConvert an IPv4 address from\n dotted-quad string format (for\n example, ‘123.45.67.89’) to 32-bit\n packed binary format, as a string four\n characters in length. This is useful\n when conversing with a program that\n uses the standard C library and needs\n objects of type struct in_addr, which\n is the C type for the 32-bit packed\n binary this function returns.\n\nTo convert from a 4-byte string to an integer and vice versa, see the struct module.\n"
] |
[
1
] |
[] |
[] |
[
"ip_address",
"python"
] |
stackoverflow_0002481413_ip_address_python.txt
|
Q:
Start Python from Twisted
I have learnt Python for about a month as a one year's PHPer.And I started from Twisted as I'm working in a corporation supplying webservice.I have finished some simple application such as data transferring service,page images-fetch service etc.But the problem is ,I don't understand the struture of codes I wrote in the programs quite well .Every time I have to write codes by watching an example.And my question is ,should I just try to remember the example code's strutures?Or try to understand them?Suggestions would be very appreciated.
Regards
A:
Just "remembering" the code structure isn't all that much extra value with respect to simply looking it up (just make yourself a handy repository of the examples you're using) -- rote memorization, while once a popular thing to force students to do, isn't all that useful.
Understanding is, of course, much better... but, I know no "royal road" to it, either in general or for Twisted in particular. Maybe try Fettig's book -- not a masterpiece, it has three stars on Amazon and it may deserve about 3.5 or so -- but quite a reasonable investment of your money and time, IMHO. To get better understanding of Python -- quite apart from Twisted -- you're better placed -- Dive into Python is a masterpiece, and you can freely download it (if you really love paper books you can also buy the paper edition). Has 4.5 stars on Amazon and deserves them!
|
Start Python from Twisted
|
I have learnt Python for about a month as a one year's PHPer.And I started from Twisted as I'm working in a corporation supplying webservice.I have finished some simple application such as data transferring service,page images-fetch service etc.But the problem is ,I don't understand the struture of codes I wrote in the programs quite well .Every time I have to write codes by watching an example.And my question is ,should I just try to remember the example code's strutures?Or try to understand them?Suggestions would be very appreciated.
Regards
|
[
"Just \"remembering\" the code structure isn't all that much extra value with respect to simply looking it up (just make yourself a handy repository of the examples you're using) -- rote memorization, while once a popular thing to force students to do, isn't all that useful.\nUnderstanding is, of course, much better... but, I know no \"royal road\" to it, either in general or for Twisted in particular. Maybe try Fettig's book -- not a masterpiece, it has three stars on Amazon and it may deserve about 3.5 or so -- but quite a reasonable investment of your money and time, IMHO. To get better understanding of Python -- quite apart from Twisted -- you're better placed -- Dive into Python is a masterpiece, and you can freely download it (if you really love paper books you can also buy the paper edition). Has 4.5 stars on Amazon and deserves them!\n"
] |
[
3
] |
[] |
[] |
[
"python",
"twisted"
] |
stackoverflow_0002481779_python_twisted.txt
|
Q:
pygtk - dynamically update the widgets taking input from the gtk combo box
On selecting value from 1 to 10 from gtk combox box it should populate the checkbox by taking combo box value as an input. Say for example if i select 5 then 5 checkbox will be generated.
It works.. But the issue is after i selected 5 now im selecting next value as 3 from combo box then there 8 checkboxes are displayed. The old 5 checkbox didnt get replaced. Is there any way to refresh the vbox(which has the checkboxes) or update to a new value.
Enviroment : FC10 , Glade 2 , Python 2.5 , GTK.
A:
Add this to your code right before you add your comboboxes:
for widget in myVBox.get_children():
myVBox.remove(widget)
|
pygtk - dynamically update the widgets taking input from the gtk combo box
|
On selecting value from 1 to 10 from gtk combox box it should populate the checkbox by taking combo box value as an input. Say for example if i select 5 then 5 checkbox will be generated.
It works.. But the issue is after i selected 5 now im selecting next value as 3 from combo box then there 8 checkboxes are displayed. The old 5 checkbox didnt get replaced. Is there any way to refresh the vbox(which has the checkboxes) or update to a new value.
Enviroment : FC10 , Glade 2 , Python 2.5 , GTK.
|
[
"Add this to your code right before you add your comboboxes:\nfor widget in myVBox.get_children():\n myVBox.remove(widget)\n\n"
] |
[
2
] |
[] |
[] |
[
"glade",
"gtk",
"pygtk",
"python"
] |
stackoverflow_0002475872_glade_gtk_pygtk_python.txt
|
Q:
Convert the mysql table details to an Excel (.xls) or comma separated file (.csv) using Python
I want to convert the mysql database table contents to an Excel(.xls) or comma separated file(csv) using python script... Is it possible? Any one can help me?
Thanks in advance,
Nimmy
A:
With third-party project mysqldb installed you can easily read that table, e.g:
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM thetable")
while True:
row = cursor.fetchone()
if row is None: break
# here: do something with the row
You can of course write each row to a csv file with Python's standard library csv module -- you'll just need an import csv at the start of your code. Then, after the cursor.execute, you can use code such as:
with open('thefile.csv', 'w') as f:
writer = csv.writer(f)
while True:
row = cursor.fetchone()
if row is None: break
writer.writerow(row)
If you want to write to an .xls file instead of a .csv, see third-party module xlwt.
|
Convert the mysql table details to an Excel (.xls) or comma separated file (.csv) using Python
|
I want to convert the mysql database table contents to an Excel(.xls) or comma separated file(csv) using python script... Is it possible? Any one can help me?
Thanks in advance,
Nimmy
|
[
"With third-party project mysqldb installed you can easily read that table, e.g:\nimport MySQLdb\nconn = MySQLdb.connect (host = \"localhost\",\n user = \"testuser\",\n passwd = \"testpass\",\n db = \"test\")\ncursor = conn.cursor()\ncursor.execute(\"SELECT * FROM thetable\")\nwhile True:\n row = cursor.fetchone()\n if row is None: break\n # here: do something with the row\n\nYou can of course write each row to a csv file with Python's standard library csv module -- you'll just need an import csv at the start of your code. Then, after the cursor.execute, you can use code such as:\nwith open('thefile.csv', 'w') as f:\n writer = csv.writer(f)\n while True:\n row = cursor.fetchone()\n if row is None: break\n writer.writerow(row)\n\nIf you want to write to an .xls file instead of a .csv, see third-party module xlwt.\n"
] |
[
1
] |
[] |
[] |
[
"csv",
"file",
"mysql",
"python",
"xlwt"
] |
stackoverflow_0002482024_csv_file_mysql_python_xlwt.txt
|
Q:
python metaprogramming
I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming.
I want to have a module locations with function get_location(name), which returns a class defined in a folder locations/ in the file with the name passed to function. Name of a class is something like NameLocation.
So, my folder structure:
program.py
locations/
__init__.py
first.py
second.py
program.py will be smth with with:
from locations import get_location
location = get_location('first')
and the location is a class defined in first.py smth like this:
from locations import Location # base class for all locations, defined in __init__ (?)
class FirstLocation(Location):
pass
etc.
Okay, I've tried a lot of import and getattribute statements but now I'm bored and surrender. How to archive such behaviour?
I don't know why, but this code
def get_location(name):
module = __import__(__name__ + '.' + name)
#return getattr(module, titlecase(name) + 'Location')
return module
returns
>>> locations.get_location( 'first')
<module 'locations' from 'locations/__init__.py'>
the locations module! why?!
A:
You do need to __import__ the module; after that, getting an attr from it is not hard.
import sys
def get_location(name):
fullpath = 'locations.' + name
package = __import__(fullpath)
module = sys.modules[fullpath]
return getattr(module, name.title() + 'Location')
Edit: __import__ returns the package, so you need one more getattr, see the docs (and read all the section carefully -- "do as I say not as I do";-).
A:
I think you're looking for:
location = __import__('first')
|
python metaprogramming
|
I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming.
I want to have a module locations with function get_location(name), which returns a class defined in a folder locations/ in the file with the name passed to function. Name of a class is something like NameLocation.
So, my folder structure:
program.py
locations/
__init__.py
first.py
second.py
program.py will be smth with with:
from locations import get_location
location = get_location('first')
and the location is a class defined in first.py smth like this:
from locations import Location # base class for all locations, defined in __init__ (?)
class FirstLocation(Location):
pass
etc.
Okay, I've tried a lot of import and getattribute statements but now I'm bored and surrender. How to archive such behaviour?
I don't know why, but this code
def get_location(name):
module = __import__(__name__ + '.' + name)
#return getattr(module, titlecase(name) + 'Location')
return module
returns
>>> locations.get_location( 'first')
<module 'locations' from 'locations/__init__.py'>
the locations module! why?!
|
[
"You do need to __import__ the module; after that, getting an attr from it is not hard.\nimport sys\n\ndef get_location(name):\n fullpath = 'locations.' + name\n package = __import__(fullpath)\n module = sys.modules[fullpath]\n return getattr(module, name.title() + 'Location')\n\nEdit: __import__ returns the package, so you need one more getattr, see the docs (and read all the section carefully -- \"do as I say not as I do\";-).\n",
"I think you're looking for:\nlocation = __import__('first')\n\n"
] |
[
6,
1
] |
[] |
[] |
[
"metaprogramming",
"python",
"python_module"
] |
stackoverflow_0002482060_metaprogramming_python_python_module.txt
|
Q:
GetLastInputInfo equivalent in Linux to detect last input time
Is there a GetLastInputInfo() equivalent that can be used in Linux?
The intention is to detect the last input time (keyboard or mouse) of the user.
Am using python to script the program.
A:
XScreenSaverQueryInfo
The idle field specifies the number of milliseconds since the last input was received from the user on any of the input devices.
The event-mask field specifies which, if any, screen saver events this client has requested using ScreenSaverSelectInput.
|
GetLastInputInfo equivalent in Linux to detect last input time
|
Is there a GetLastInputInfo() equivalent that can be used in Linux?
The intention is to detect the last input time (keyboard or mouse) of the user.
Am using python to script the program.
|
[
"XScreenSaverQueryInfo\n\nThe idle field specifies the number of milliseconds since the last input was received from the user on any of the input devices.\n The event-mask field specifies which, if any, screen saver events this client has requested using ScreenSaverSelectInput.\n\n"
] |
[
4
] |
[] |
[] |
[
"input",
"linux",
"python",
"time"
] |
stackoverflow_0002482103_input_linux_python_time.txt
|
Q:
Search backward through a string using a regex (in Python)?
Context
I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.
Current Approach
import re
function_re = re.compile(
r"\/\*\*(.+)\*\/\s*void\s+(\w+)\s*::\s*function_name\s*\(\s*\)\s*")
function_match = function_re.search(file_string)
if function_match:
function_doc_str = update_match.group(2)
Problem with Current Approach
The current approach matches doxygen from earlier functions, giving me a result that is the wrong doxygen comment.
Question
Is there a way to search backward through a string using the Python Regex library?
It seems like my problem is that the more restrictive (less frequently occurring part) is the function signature, "void function()"
Possible better question
Is there a better (easier) approach that I'm missing?
A:
simplest way is to just use a group, you don't need to go backwards...
(commentRegex)functionRegex
Then just extract group 1. You will need to run in multi-line mode to get it working, i don't know python so i can't be more helpful.
It's also possible with lookahead assertions, but this way is simpler.
A:
I think you should use a regex that only matches doxymentation that's immediately before the function. Maybe something like this (simplified example):
import re
test = """
/**
@doxygen comment
*/
void function()
{
}
"""
doxygenRegex = r"(?P<comment>/\*\*(?:[^/]|/(?!\*\*))*\*/)"
functionRegex = r"(?P<function>\s\w+\s+(?P<functionName>\w+)\s*\()"
match = re.search(doxygenRegex + functionRegex, test)
print match.groupdict()
As long as this matches something, you can loop the regex matching - but starting the search at test[match.end():] next time. Hope that makes sense to you...
BTW if you only want to extract the comment and nothing about the function, you can use lookahead - just replace functionRegex with r"(?=\s\w+\s+\w+\s*\()".
A:
This can be achived using a single reg-ex.
The key is to capture the comment just before the desired function.
The easy way to do this is to use non-greedy qualifier.
For example: /\*\*(.*?)\*/ with MULTILINE flag;
however, in Python, non-greedy and MULTILINE do not work together (at least on my environment).
So, you need a little trick like this:
/\*\*((?:[^\*]|\*(?!/))*)\*/.
This is to match:
1: the comment begin /**.
2: everything that is not * OR * that does not follows by /
3: the comment end */.
From this idea the code you want is:
function_name = "function2"
regex_comment = "/\*\*((?:[^\*]|\*(?!/))*)\*/"
regex_static = "(?:(\w+)\s*::\s*)?"
regex_function = "(\w+)\s+"+regex_static+"(?:"+function_name+")\s*\([^\)]*\)"
regex = re.compile(regex_comment+"\s*"+regex_function, re.MULTILINE)
text = """
/**
@doxygen comment1
*/
void test::function1()
{
}
/**
@doxygen comment2
*/
void test::function2()
{
}
"""
match = regex.search(text)
if (match == None): print "None"
else: print match.group(1)
When run, you got:
@doxygen comment2
Variation:
If you want to capture /** and */ too, use regex_comment = "(/\*\*(?:[^\*]|\*(?!/))*\*/)".
Hope this helps.
A:
Note that C isn't a regular language, so it cannot be parsed by regular expressions. Have you considered leveraging doxygen itself to parse this file?
A:
You can do look-behind assertions with (?<=...) or (?<!...), but in general you can only match forwards.
A:
The question is why are these comments not inside the function, so you can use doc.
But there is no easy way with regex.
A:
here's a non regex approach, split on */ and find if the function you are looking for is at the next item. eg
test = """
/**
@doxygen comment
*/
void function()
{
}
"""
t=test.split("*/")
for n,comm in enumerate(t):
try:
if "void" in t[n+1]:
print t[n]
except IndexError: pass
|
Search backward through a string using a regex (in Python)?
|
Context
I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.
Current Approach
import re
function_re = re.compile(
r"\/\*\*(.+)\*\/\s*void\s+(\w+)\s*::\s*function_name\s*\(\s*\)\s*")
function_match = function_re.search(file_string)
if function_match:
function_doc_str = update_match.group(2)
Problem with Current Approach
The current approach matches doxygen from earlier functions, giving me a result that is the wrong doxygen comment.
Question
Is there a way to search backward through a string using the Python Regex library?
It seems like my problem is that the more restrictive (less frequently occurring part) is the function signature, "void function()"
Possible better question
Is there a better (easier) approach that I'm missing?
|
[
"simplest way is to just use a group, you don't need to go backwards...\n (commentRegex)functionRegex\n\nThen just extract group 1. You will need to run in multi-line mode to get it working, i don't know python so i can't be more helpful.\nIt's also possible with lookahead assertions, but this way is simpler.\n",
"I think you should use a regex that only matches doxymentation that's immediately before the function. Maybe something like this (simplified example):\nimport re\n\ntest = \"\"\"\n\n/**\n @doxygen comment\n*/\nvoid function()\n{\n}\n\n\"\"\"\n\ndoxygenRegex = r\"(?P<comment>/\\*\\*(?:[^/]|/(?!\\*\\*))*\\*/)\"\nfunctionRegex = r\"(?P<function>\\s\\w+\\s+(?P<functionName>\\w+)\\s*\\()\"\n\nmatch = re.search(doxygenRegex + functionRegex, test)\nprint match.groupdict()\n\nAs long as this matches something, you can loop the regex matching - but starting the search at test[match.end():] next time. Hope that makes sense to you...\nBTW if you only want to extract the comment and nothing about the function, you can use lookahead - just replace functionRegex with r\"(?=\\s\\w+\\s+\\w+\\s*\\()\".\n",
"This can be achived using a single reg-ex.\nThe key is to capture the comment just before the desired function.\nThe easy way to do this is to use non-greedy qualifier.\nFor example: /\\*\\*(.*?)\\*/ with MULTILINE flag;\nhowever, in Python, non-greedy and MULTILINE do not work together (at least on my environment).\nSo, you need a little trick like this:\n/\\*\\*((?:[^\\*]|\\*(?!/))*)\\*/.\nThis is to match:\n1: the comment begin /**.\n2: everything that is not * OR * that does not follows by /\n3: the comment end */.\nFrom this idea the code you want is:\nfunction_name = \"function2\"\nregex_comment = \"/\\*\\*((?:[^\\*]|\\*(?!/))*)\\*/\"\nregex_static = \"(?:(\\w+)\\s*::\\s*)?\"\nregex_function = \"(\\w+)\\s+\"+regex_static+\"(?:\"+function_name+\")\\s*\\([^\\)]*\\)\"\nregex = re.compile(regex_comment+\"\\s*\"+regex_function, re.MULTILINE)\ntext = \"\"\"\n/**\n @doxygen comment1\n*/\nvoid test::function1()\n{\n}\n\n/**\n @doxygen comment2\n*/\nvoid test::function2()\n{\n}\n\"\"\"\nmatch = regex.search(text)\nif (match == None): print \"None\"\nelse: print match.group(1)\n\nWhen run, you got:\n\n @doxygen comment2\n\n\nVariation:\nIf you want to capture /** and */ too, use regex_comment = \"(/\\*\\*(?:[^\\*]|\\*(?!/))*\\*/)\".\nHope this helps.\n",
"Note that C isn't a regular language, so it cannot be parsed by regular expressions. Have you considered leveraging doxygen itself to parse this file?\n",
"You can do look-behind assertions with (?<=...) or (?<!...), but in general you can only match forwards.\n",
"The question is why are these comments not inside the function, so you can use doc.\nBut there is no easy way with regex.\n",
"here's a non regex approach, split on */ and find if the function you are looking for is at the next item. eg\ntest = \"\"\"\n\n/**\n @doxygen comment\n*/\nvoid function()\n{\n}\n\n\"\"\"\n\nt=test.split(\"*/\")\nfor n,comm in enumerate(t):\n try:\n if \"void\" in t[n+1]:\n print t[n]\n except IndexError: pass\n\n"
] |
[
2,
2,
2,
1,
0,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002480808_python_regex.txt
|
Q:
Send an email using python script
Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need.
import smtplib
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["user@example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
But when I tried to run the program, I got the following error message:
Traceback (most recent call last):
File "C:/Python26/email.py", line 1, in <module>
import smtplib
File "C:\Python26\lib\smtplib.py", line 46, in <module>
import email.utils
File "C:/Python26/email.py", line 24, in <module>
server = smtplib.SMTP(SERVER)
AttributeError: 'module' object has no attribute 'SMTP'
How can i solve this problem? Any one can help me?
Thanks in advance,
Nimmy.
changed the name to emailsendin .py. But I got the following error
Traceback (most recent call last):
File "C:\Python26\emailsending.py", line 24, in <module>
server = smtplib.SMTP(SERVER)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10061] No connection could be made because the target machine actively refused it
A:
You've named your module the same as one of Python's internal modules. When you import smtplib, it tries to import email, and finds your module instead of the internal one. When two modules import one another, only the variables in each module visible before the both import statements will be visible to one another. Renaming your module will fix the problem.
You can see this, although it's slightly obscure, in the stack trace. The import email.utils line from smtplib.py is calling your module, in "c:/Python26/email.py".
Another note: it's probably not a great idea to use your Python install directory as your working directory for Python code.
A:
Did you name your script email.py?
If so, rename to something else and the naming conflict you're encountering should be solved.
A:
You have managed to shadow the stdlib email module by calling your script email.py. Rename your script to something not in the stdlib and try again.
A:
Does your computer also have an open mail server listening on the default port?
smptlib provides methods to connect to an smtp mail server, but if your computer is not currently running one, then you cannot send mail to it.
|
Send an email using python script
|
Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need.
import smtplib
SERVER = "localhost"
FROM = "sender@example.com"
TO = ["user@example.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
But when I tried to run the program, I got the following error message:
Traceback (most recent call last):
File "C:/Python26/email.py", line 1, in <module>
import smtplib
File "C:\Python26\lib\smtplib.py", line 46, in <module>
import email.utils
File "C:/Python26/email.py", line 24, in <module>
server = smtplib.SMTP(SERVER)
AttributeError: 'module' object has no attribute 'SMTP'
How can i solve this problem? Any one can help me?
Thanks in advance,
Nimmy.
changed the name to emailsendin .py. But I got the following error
Traceback (most recent call last):
File "C:\Python26\emailsending.py", line 24, in <module>
server = smtplib.SMTP(SERVER)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10061] No connection could be made because the target machine actively refused it
|
[
"You've named your module the same as one of Python's internal modules. When you import smtplib, it tries to import email, and finds your module instead of the internal one. When two modules import one another, only the variables in each module visible before the both import statements will be visible to one another. Renaming your module will fix the problem.\nYou can see this, although it's slightly obscure, in the stack trace. The import email.utils line from smtplib.py is calling your module, in \"c:/Python26/email.py\".\nAnother note: it's probably not a great idea to use your Python install directory as your working directory for Python code.\n",
"Did you name your script email.py?\nIf so, rename to something else and the naming conflict you're encountering should be solved.\n",
"You have managed to shadow the stdlib email module by calling your script email.py. Rename your script to something not in the stdlib and try again.\n",
"Does your computer also have an open mail server listening on the default port?\nsmptlib provides methods to connect to an smtp mail server, but if your computer is not currently running one, then you cannot send mail to it.\n"
] |
[
14,
5,
3,
1
] |
[] |
[] |
[
"email",
"python"
] |
stackoverflow_0002482160_email_python.txt
|
Q:
Trac default language
How can I set default language for trac. There's nothing about i18n in trac.ini
A:
Trac will use the locale provided by your http server by default. Easiest thing to do is just change the locale Apache is running under.
Or if you are running trac under mod_python you can modify the TracLocale option:
SetHandler mod_python
PythonOption TracLocale "de_DE.UTF-8"
...
For more info:
http://trac.edgewall.org/wiki/TracFaq#how-do-i-change-the-format-used-for-displaying-date-and-time
A:
The stable release of trac, 0.11.X does not have support for localization. It is added in the upcoming 0.12 which is currently under development. Do you have 0.12 or did you download "latest stable" which is 0.11? In that case you will have to upgrade to get localization support.
The trac site itself appears to be running 0.12 as it is localized.
|
Trac default language
|
How can I set default language for trac. There's nothing about i18n in trac.ini
|
[
"Trac will use the locale provided by your http server by default. Easiest thing to do is just change the locale Apache is running under.\nOr if you are running trac under mod_python you can modify the TracLocale option:\n\n SetHandler mod_python\n PythonOption TracLocale \"de_DE.UTF-8\"\n ...\n \nFor more info:\nhttp://trac.edgewall.org/wiki/TracFaq#how-do-i-change-the-format-used-for-displaying-date-and-time\n",
"The stable release of trac, 0.11.X does not have support for localization. It is added in the upcoming 0.12 which is currently under development. Do you have 0.12 or did you download \"latest stable\" which is 0.11? In that case you will have to upgrade to get localization support.\nThe trac site itself appears to be running 0.12 as it is localized.\n"
] |
[
1,
0
] |
[] |
[] |
[
"internationalization",
"python",
"trac"
] |
stackoverflow_0002482399_internationalization_python_trac.txt
|
Q:
How to check the read/write status of storage media in python?
How can i check the read/ write permission of the file storing media? ie assume i have to write some file inside a directory and that directory may be available on read only media like (cd or dvd)or etc. So how can i check that storing media ( cd, hard disk) having a read only or read write both permission.
I am using windows xp os.
Thanks.
A:
Use the os.access(path, mode) function. It should be much more portable than the win32api function. Though, I have no experience with it on non-POSIX systems.
On the other hand, why don't you just try to write the file and handle exception appropriately?
A:
import os
from stat import *
if S_IMODE(os.stat(dir_name)) & S_IWRITE != 0:
is more portable, if not necessarily more readable.
A:
Use the win32api.GetFileAttributes method.
P.S. also see this SO question
|
How to check the read/write status of storage media in python?
|
How can i check the read/ write permission of the file storing media? ie assume i have to write some file inside a directory and that directory may be available on read only media like (cd or dvd)or etc. So how can i check that storing media ( cd, hard disk) having a read only or read write both permission.
I am using windows xp os.
Thanks.
|
[
"Use the os.access(path, mode) function. It should be much more portable than the win32api function. Though, I have no experience with it on non-POSIX systems.\nOn the other hand, why don't you just try to write the file and handle exception appropriately?\n",
"import os\nfrom stat import *\n\nif S_IMODE(os.stat(dir_name)) & S_IWRITE != 0:\n\nis more portable, if not necessarily more readable.\n",
"Use the win32api.GetFileAttributes method.\nP.S. also see this SO question\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"filesystems",
"python",
"windows_xp"
] |
stackoverflow_0002482701_filesystems_python_windows_xp.txt
|
Q:
Seeking enlightenment - global variables in AppEngine (aeoid.get_current_user())
This may be a 'Python Web Programming 101' question, but I'm confused about some code in the aeoid project (http://github.com/Arachnid/aeoid). here's the code:
_current_user = None
def get_current_user():
"""Returns the currently logged in user, or None if no user is logged in."""
global _current_user
if not _current_user and 'aeoid.user' in os.environ:
_current_user = User(None, _from_model_key=os.environ['aeoid.user'])
return _current_user
But my understanding was that global variables were, ehm, global! And so different requests from different users could (potentially) access and update the same value, hence the need for sessions, in order to store per-user, non-global variables. So, in the code above, what prevents one request from believing the current user is the user set by another request? Sorry if this is basic, it's just not how i thought things worked.
Thanks
A:
The App Engine Python runtime is single-threaded - only a single request is processed, per runtime instance, at a time. As a result, you can use globals for request-specific parameters, so long as you take care to reset them at the beginning of each request, so they don't leak data from one request to another.
A:
You are not the only one confused about globals on appengine. But I know the os.environ is unique to each request, so I think that could explain this code working right. If not, it might be so that the module this is in gets forced reloaded somehow, a trick I'm looking in too for dynamic settings in my project.
|
Seeking enlightenment - global variables in AppEngine (aeoid.get_current_user())
|
This may be a 'Python Web Programming 101' question, but I'm confused about some code in the aeoid project (http://github.com/Arachnid/aeoid). here's the code:
_current_user = None
def get_current_user():
"""Returns the currently logged in user, or None if no user is logged in."""
global _current_user
if not _current_user and 'aeoid.user' in os.environ:
_current_user = User(None, _from_model_key=os.environ['aeoid.user'])
return _current_user
But my understanding was that global variables were, ehm, global! And so different requests from different users could (potentially) access and update the same value, hence the need for sessions, in order to store per-user, non-global variables. So, in the code above, what prevents one request from believing the current user is the user set by another request? Sorry if this is basic, it's just not how i thought things worked.
Thanks
|
[
"The App Engine Python runtime is single-threaded - only a single request is processed, per runtime instance, at a time. As a result, you can use globals for request-specific parameters, so long as you take care to reset them at the beginning of each request, so they don't leak data from one request to another.\n",
"You are not the only one confused about globals on appengine. But I know the os.environ is unique to each request, so I think that could explain this code working right. If not, it might be so that the module this is in gets forced reloaded somehow, a trick I'm looking in too for dynamic settings in my project.\n"
] |
[
2,
0
] |
[] |
[] |
[
"global_variables",
"google_app_engine",
"python",
"session"
] |
stackoverflow_0002482224_global_variables_google_app_engine_python_session.txt
|
Q:
Pass by reference in Boost::Python
Consider something like:
struct Parameter
{
int a;
Parameter(){a = 0;}
void setA(int newA){a = newA;}
};
struct MyClass
{
void changeParameter(Parameter &p){ p.setA(-1);}
};
Well, let's fast forward, and imagine I already wrapped those classes, exposing everything to python, and imagine also I instantiate an object of Parameter in the C++ code, which I pass to the python script, and that python script uses a MyClass object to modify the instance of Parameter I created at the beginning in the C++ code.
After that code executes, in C++ Parameter instance is unchanged!!! This means it was passed by value (or something alike :S), not by reference. But I thought I declared it to be passed by reference...
I can't seem to find Boost::Python documentation about passing by reference (although there seems to be enough doc about returning by reference...). Can anyone give some hint or pointer please?
A:
Python doesn't have references, so when you pass reference to python boost::python calls copy-ctor of your object.
In this case you have two choices: Replace references with pointers (or smart-pointers) or pass into python your own 'smart-reference' object/wrapper.
|
Pass by reference in Boost::Python
|
Consider something like:
struct Parameter
{
int a;
Parameter(){a = 0;}
void setA(int newA){a = newA;}
};
struct MyClass
{
void changeParameter(Parameter &p){ p.setA(-1);}
};
Well, let's fast forward, and imagine I already wrapped those classes, exposing everything to python, and imagine also I instantiate an object of Parameter in the C++ code, which I pass to the python script, and that python script uses a MyClass object to modify the instance of Parameter I created at the beginning in the C++ code.
After that code executes, in C++ Parameter instance is unchanged!!! This means it was passed by value (or something alike :S), not by reference. But I thought I declared it to be passed by reference...
I can't seem to find Boost::Python documentation about passing by reference (although there seems to be enough doc about returning by reference...). Can anyone give some hint or pointer please?
|
[
"Python doesn't have references, so when you pass reference to python boost::python calls copy-ctor of your object.\nIn this case you have two choices: Replace references with pointers (or smart-pointers) or pass into python your own 'smart-reference' object/wrapper.\n"
] |
[
2
] |
[] |
[] |
[
"boost_python",
"c++",
"python",
"scripting"
] |
stackoverflow_0002459588_boost_python_c++_python_scripting.txt
|
Q:
Python - retrieving info from a syslog file
I have been asked to write a program using python for an assignment.
I have been given a syslog file and I have to find things out about it
How do I find out how many attempts were made to login to the root account?
Any advice would be highly appreciated as I am very new to python and completely lost!
A:
You want /var/log/auth.log, not syslog.
It'll contain lines like like this:
Mar 20 10:47:24 Opus su[15918]: pam_unix(su:auth): authentication failure; logname=lfaraone uid=1000 euid=0 tty=/dev/pts/25 ruser=lfaraone rhost= user=root
Basic, naive code to accomplish the problem would be as follows:
loginattempts = {"root": 0,
"someuser": 0,} # Usernames you want to check
with open('/var/log/auth.log', 'r') as authlog:
for line in authlog:
if "authentication failure" in line:
username = line.split('=')[-1] # split the string into an array,
# using '=' as the delimiter
if username in loginattempts: # is the username one we care about?
loginattempts[username] += 1
Like user calmh suggested, it will probably be better long-term to parse with regular expressions, but if you don't know them already, it can be non-trivial to learn.
A:
You probably need to read the file, parsing each line. When you find a line that matches what you're interested in (failed root login, for example), you increment a counter.
Take a look at how to read files and possibly how to use regular expressions.
If you are going to do this check against a "live" log file, say every five minutes, you need to keep track of how much of the file you have already processed so you don't read it all every time. This is slightly more complicated, because you need to remember state (file size) between executions. In that case, look at the shelve module.
A:
something like this
#open the file , can be /var/log/messages, /var/log/maillog etc as defined in your system
f=open("mysyslogfile")
count=0
#go through the file
for line in f:
if "<unique pattern for checking root account login>" in line:
count+=1
#close the file
f.close()
print "total count: " ,count
|
Python - retrieving info from a syslog file
|
I have been asked to write a program using python for an assignment.
I have been given a syslog file and I have to find things out about it
How do I find out how many attempts were made to login to the root account?
Any advice would be highly appreciated as I am very new to python and completely lost!
|
[
"You want /var/log/auth.log, not syslog. \nIt'll contain lines like like this: \nMar 20 10:47:24 Opus su[15918]: pam_unix(su:auth): authentication failure; logname=lfaraone uid=1000 euid=0 tty=/dev/pts/25 ruser=lfaraone rhost= user=root\n\nBasic, naive code to accomplish the problem would be as follows:\nloginattempts = {\"root\": 0,\n \"someuser\": 0,} # Usernames you want to check\nwith open('/var/log/auth.log', 'r') as authlog:\n for line in authlog:\n if \"authentication failure\" in line:\n username = line.split('=')[-1] # split the string into an array, \n # using '=' as the delimiter\n if username in loginattempts: # is the username one we care about?\n loginattempts[username] += 1\n\nLike user calmh suggested, it will probably be better long-term to parse with regular expressions, but if you don't know them already, it can be non-trivial to learn. \n",
"You probably need to read the file, parsing each line. When you find a line that matches what you're interested in (failed root login, for example), you increment a counter.\nTake a look at how to read files and possibly how to use regular expressions.\nIf you are going to do this check against a \"live\" log file, say every five minutes, you need to keep track of how much of the file you have already processed so you don't read it all every time. This is slightly more complicated, because you need to remember state (file size) between executions. In that case, look at the shelve module.\n",
"something like this\n#open the file , can be /var/log/messages, /var/log/maillog etc as defined in your system\nf=open(\"mysyslogfile\")\ncount=0 \n#go through the file\nfor line in f:\n if \"<unique pattern for checking root account login>\" in line:\n count+=1\n#close the file\nf.close()\nprint \"total count: \" ,count\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"authentication",
"count",
"python",
"syslog"
] |
stackoverflow_0002483421_authentication_count_python_syslog.txt
|
Q:
Should I use fork or threads?
In my script, I have a function foo which basically uses pynotify to notify user about something repeatedly after a time interval say 15 minutes.
def foo:
while True:
"""Does something"""
time.sleep(900)
My main script has to interact with user & does all other things so I just cant call the foo() function. directly.
Whats the better way of doing it and why?
Using fork or threads?
A:
I won't tell you which one to use, but here are some of the advantages of each:
Threads can start more quickly than processes, and threads use fewer operating system resources than processes, including memory, file handles, etc. Threads also give you the option of communicating through shared variables (although many would say this is more of a disadvantage than an advantage - See below).
Processes each have their own separate memory and variables, which means that processes generally communicate by sending messages to each other. This is much easier to do correctly than having threads communicate via shared memory. Processes can also run truly concurrently, so that if you have multiple CPU cores, you can keep all of them busy using processes. In Python*, the global interpreter lock prevents threads from making much use of more than a single core.
* - That is, CPython, which the implementation of Python that you get if you go to http://python.org and download Python. Other Python implementations (such as Jython) do not necessarily prohibit Python from running threads on multiple CPUs simultaneously. Thanks to @EOL for the clarification.
A:
For these kinds of problems, neither threads nor forked processes seem the right approach. If all you want to do is to once every 15 minutes notify the user of something, why not use an event loop like GLib's or Twisted's reactor ? This allows you to schedule operations that should run once in a while, and get on with the rest of your program.
A:
Using multiple processes lets you exploit multiple CPU cores at the same time, while, in CPython, using threads doesn't (threads take turns using a single CPU core) -- so, if you have CPU intensive work and absolutely want to use threads, you should consider Jython or IronPython; with CPython, this consideration is often enough to sway the choice towards the multiprocessing module and away from the threading one (they offer pretty similar interfaces, because multiprocessing was designed to be easily put in place in lieu of threading).
Net of this crucial consideration, threads might often be a better choice (performance-wise) on Windows (where making a new process is a heavy task), but less often on Unix variants (Linux, BSD versions, OpenSolaris, MacOSX, ...), since making a new process is faster there (but if you're using IronPython or Jython, you should check, on the platforms you care about, that this still applies in the virtual machines in question -- CLR with either .NET or Mono for IronPython, your JVM of choice for Jython).
A:
Processes are much simpler. Just turn them loose and let the OS handle it.
Also, processes are often much more efficient. Processes do not share a common pool of I/O resources; they are completely independent.
Python's subprocess.Popen handles everything.
A:
If by fork you mean os.fork then I would avoid using that. It is not cross platform and too low level - you would need to implement communication between the processes yourself.
If you want to use a separate process then use either the subprocess module or if you are on Python 2.6 or later the new multiprocessing module. This has a very similar API to the threading module, so you could start off using threads and then easily switch to processes, or vice-versa.
For what you want to do I think I would use threads, unless """does something""" is CPU intensive and you want to take advantage of multiple cores, which I doubt in this particular case.
|
Should I use fork or threads?
|
In my script, I have a function foo which basically uses pynotify to notify user about something repeatedly after a time interval say 15 minutes.
def foo:
while True:
"""Does something"""
time.sleep(900)
My main script has to interact with user & does all other things so I just cant call the foo() function. directly.
Whats the better way of doing it and why?
Using fork or threads?
|
[
"I won't tell you which one to use, but here are some of the advantages of each:\nThreads can start more quickly than processes, and threads use fewer operating system resources than processes, including memory, file handles, etc. Threads also give you the option of communicating through shared variables (although many would say this is more of a disadvantage than an advantage - See below).\nProcesses each have their own separate memory and variables, which means that processes generally communicate by sending messages to each other. This is much easier to do correctly than having threads communicate via shared memory. Processes can also run truly concurrently, so that if you have multiple CPU cores, you can keep all of them busy using processes. In Python*, the global interpreter lock prevents threads from making much use of more than a single core.\n\n* - That is, CPython, which the implementation of Python that you get if you go to http://python.org and download Python. Other Python implementations (such as Jython) do not necessarily prohibit Python from running threads on multiple CPUs simultaneously. Thanks to @EOL for the clarification.\n",
"For these kinds of problems, neither threads nor forked processes seem the right approach. If all you want to do is to once every 15 minutes notify the user of something, why not use an event loop like GLib's or Twisted's reactor ? This allows you to schedule operations that should run once in a while, and get on with the rest of your program.\n",
"Using multiple processes lets you exploit multiple CPU cores at the same time, while, in CPython, using threads doesn't (threads take turns using a single CPU core) -- so, if you have CPU intensive work and absolutely want to use threads, you should consider Jython or IronPython; with CPython, this consideration is often enough to sway the choice towards the multiprocessing module and away from the threading one (they offer pretty similar interfaces, because multiprocessing was designed to be easily put in place in lieu of threading).\nNet of this crucial consideration, threads might often be a better choice (performance-wise) on Windows (where making a new process is a heavy task), but less often on Unix variants (Linux, BSD versions, OpenSolaris, MacOSX, ...), since making a new process is faster there (but if you're using IronPython or Jython, you should check, on the platforms you care about, that this still applies in the virtual machines in question -- CLR with either .NET or Mono for IronPython, your JVM of choice for Jython).\n",
"Processes are much simpler. Just turn them loose and let the OS handle it. \nAlso, processes are often much more efficient. Processes do not share a common pool of I/O resources; they are completely independent. \nPython's subprocess.Popen handles everything.\n",
"If by fork you mean os.fork then I would avoid using that. It is not cross platform and too low level - you would need to implement communication between the processes yourself.\nIf you want to use a separate process then use either the subprocess module or if you are on Python 2.6 or later the new multiprocessing module. This has a very similar API to the threading module, so you could start off using threads and then easily switch to processes, or vice-versa.\nFor what you want to do I think I would use threads, unless \"\"\"does something\"\"\" is CPU intensive and you want to take advantage of multiple cores, which I doubt in this particular case.\n"
] |
[
9,
4,
4,
3,
1
] |
[] |
[] |
[
"coding_style",
"python"
] |
stackoverflow_0002482926_coding_style_python.txt
|
Q:
MySQL UTC Date format
I am pulling data from Twitter's API and the return date is UTC in the following form:
Sat Jan 24 22:14:29 +0000 2009
Can MySQL handle this format specifically or do I need to transform it? I am pulling the data using Python.
A:
Yes, if you are not willing to transform it in Python, MySQL can handle this with the STR_TO_DATE() function, as in the following example:
INSERT INTO
your_table
VALUES (
STR_TO_DATE('Sat Jan 24 22:14:29 +0000 2009', '%a %b %d %H:%i:%s +0000 %Y')
);
You may also want to check the full list of possible format specifiers: MySQL: DATE_FORMAT.
|
MySQL UTC Date format
|
I am pulling data from Twitter's API and the return date is UTC in the following form:
Sat Jan 24 22:14:29 +0000 2009
Can MySQL handle this format specifically or do I need to transform it? I am pulling the data using Python.
|
[
"Yes, if you are not willing to transform it in Python, MySQL can handle this with the STR_TO_DATE() function, as in the following example:\nINSERT INTO\n your_table\nVALUES ( \n STR_TO_DATE('Sat Jan 24 22:14:29 +0000 2009', '%a %b %d %H:%i:%s +0000 %Y')\n);\n\nYou may also want to check the full list of possible format specifiers: MySQL: DATE_FORMAT.\n"
] |
[
3
] |
[] |
[] |
[
"mysql",
"python",
"twitter",
"utc"
] |
stackoverflow_0002483569_mysql_python_twitter_utc.txt
|
Q:
How to give extra arguments for the Python itertools.ifilter function?
In python I have the following function:
def is_a_nice_element(element, parameter):
#do something
return True or False
Now I would like to filter a list with this function as predicate, giving a fixed parameter. Python has the itertools.ifilter function, but I can't figure out how to pass the parameter. Is this possible? If not, how can I solve this problem?
A:
I like functools.partial much better than lambda.
itertools.ifilter( partial(is_a_nice_element, parameter=X), iterable )
A:
Wrap it in a lambda:
itertools.ifilter(lambda e: is_a_nice_element(e, 42), iterable)
42 is your extra argument, or whatever else you want it to be.
A:
The solutions use lambda and functools.partial are quite correct and directly answer your question, but I don't think they are really the ideal solution.
Using filter/itertools.ifilter/map/itertools.imap with an anonymous function is prettymuch always going to be less clear than using a generator expression or list comprehension. For example, in this case I would write the generator expression
(item for item in iterable if is_a_nice_element(item, constant))
instead of using ifilter. In this case the ifilter solution is still fairly readable, but in many cases trying to go through lots of trouble to define just the right function is not going to be as worth while as just performing the operation.
|
How to give extra arguments for the Python itertools.ifilter function?
|
In python I have the following function:
def is_a_nice_element(element, parameter):
#do something
return True or False
Now I would like to filter a list with this function as predicate, giving a fixed parameter. Python has the itertools.ifilter function, but I can't figure out how to pass the parameter. Is this possible? If not, how can I solve this problem?
|
[
"I like functools.partial much better than lambda.\nitertools.ifilter( partial(is_a_nice_element, parameter=X), iterable )\n\n",
"Wrap it in a lambda:\nitertools.ifilter(lambda e: is_a_nice_element(e, 42), iterable)\n\n42 is your extra argument, or whatever else you want it to be.\n",
"The solutions use lambda and functools.partial are quite correct and directly answer your question, but I don't think they are really the ideal solution.\nUsing filter/itertools.ifilter/map/itertools.imap with an anonymous function is prettymuch always going to be less clear than using a generator expression or list comprehension. For example, in this case I would write the generator expression\n(item for item in iterable if is_a_nice_element(item, constant))\n\ninstead of using ifilter. In this case the ifilter solution is still fairly readable, but in many cases trying to go through lots of trouble to define just the right function is not going to be as worth while as just performing the operation.\n"
] |
[
5,
3,
1
] |
[
"If you are using ifilter then parameter would need to be constant in which case you could use a default argument parameter=something. If you want parameter to vary, you'd need to use another method to take a dyadic predicate.\nIf you already have the list in hand, ifilter is a bit of overkill relative to the built-in filter.\nDescribing what you want to accomplish would help in making a more concrete answer.\n"
] |
[
-1
] |
[
"ifilter",
"python",
"python_itertools"
] |
stackoverflow_0002483118_ifilter_python_python_itertools.txt
|
Q:
Python method to remove iterability
Suppose I have a function which can either take an iterable/iterator or a non-iterable as an argument. Iterability is checked with try: iter(arg).
Depending whether the input is an iterable or not, the outcome of the method will be different. Not when I want to pass a non-iterable as iterable input, it is easy to do: I’ll just wrap it with a tuple.
What do I do when I want to pass an iterable (a string for example) but want the function to take it as if it’s non-iterable? E.g. make that iter(str) fails.
Edit – my original intention:
I wanted to generalise the zip function in that it can zip iterables with non-iterables. The non-iterable would then repeat itself as often as the other iterables haven’t finished.
The only general solution fo me seems now to be, that I shouldn’t check inside the general_zip function (because of the string issues); but that instead I’ll have to add the repeat iterator to the argument before calling zip. (This actually saves me from inventing the general_zip function — although I still might because with a non-iterable as an input it would be unambiguous without the extra repeat.)
A:
The more I think about it, it seems like it’s not possible to do without type checking or passing argments to the function.
However, depending on the intention of the function, one way to handle it could be:
from itertools import repeat
func(repeat(string_iterable))
func still sees an iterable but it won’t iterate through the charaters of the string itself. And effectively, the argument works as if it’s a constant non-iterable.
A:
Whoo! It appears you want to be able to pass iterables as iterables, iterables as noniterables, noniterables as iterables, and noniterables as noniterables.
Since you want to be able to handle every possibility, and the computer can not (yet) read minds, you are going to have to tell the function how you want the argument to be handled:
def foo_iterable(iterable):
...
def foo_noniterable(noniterable):
...
def foo(thing,isiterable=True):
if isiterable:
foo_iterable(thing)
else:
foo_noniterable(thing)
Apply foo to an iterable
foo(iterable)
Apply foo to an iterable as a non-iterable:
foo_noniterable(iterable) # or
foo(iterable, isiterable=False)
Apply foo to a noniterable as a noniterable:
foo_noniterable(noniterable) # or
foo(noniterable,isiterable=False)
Apply foo to a noniterable as an iterable:
foo((noniterable,))
PS. I'm a believer in small functions that do a single job well. They are easier to debug and unit-test. In general I would advise avoiding monolithic functions that behave differently depending on type. Yes, it puts a little extra burden on the developer to call exactly the function that is intended, but I think the advantages in terms of debugging and unit-testing more than make up for it.
A:
Specialize it.
def can_iter(arg):
if isinstance(arg, str):
return False
try:
...
A:
Well, one approach to tell the function how you would like to treat its arguments is to have sensible defaults (making the function treat everything by its original type by default), while being able to specify any tweaks you like with comfort (i.e. with a short and absent-by-default fmt string), like:
def smart_func(*args, **kw):
"""If 'kw' contains an 'fmt' parameter,
it must be a list containing positions of arguments,
that should be treated as if they were of opposite 'kind'
(i.e. iterables will be treated as non-iterables and vise-versa)
The 'kind' of a positional argument (i.e. whether it as an iterable)
is inferred by trying to call 'iter()' on the argument.
"""
fmt = kw.get('fmt', [])
def is_iter(it):
try:
iter(it)
return True
except TypeError:
return False
for i,arg in enumerate(args):
arg_is_iterable = is_iter(arg)
treat_arg_as_iterable = ((not arg_is_iterable)
if (i in fmt) else arg_is_iterable)
print arg, arg_is_iterable, treat_arg_as_iterable
This gives:
>>> smart_func()
>>> smart_func(1, 2, [])
1 False False
2 False False
[] True True
>>> smart_func(1, 2, [], fmt=[])
1 False False
2 False False
[] True True
>>> smart_func(1, 2, [], fmt=[0])
1 False True
2 False False
[] True True
>>> smart_func(1, 2, [], fmt=[0,2])
1 False True
2 False False
[] True False
Expanding this function (finding the length of the longest iterable, etc), one can construct a smart-zip you are talking about.
[P.s.]
Another way will be to call the function in the following way:
smart_func(s='abc', 1, arr=[0,1], [1,2], fmt={'s':'non-iter','some_arr':'iter'})
and have the function match the argument names you supplied ('s' and 'arr', note, there are no such names in the functions signature as it is the same as above) to the 'fmt' "type-hints" (i.e. 'iter' makes an argument considered as an iterable, and 'non-iter' as a non-iterable). This approach can, of course, be combined with the above "toggle-type" one.
A:
Don't check for iterability. It is a mistake to have a function check things about its elements types/capabilities in order to have a single function perform different tasks. If you want to do two different things, make two different functions.
It sounds like you have come to this conclusion yourself and are providing a consistent API, where you do
from itertools import repeat
zip([1, 2, 3], repeat(5), "bar")
Note that it's almost always useless to do this since you could just do
five = 5
for number, letter in zip([1, 2, 3], "bar")
# Just use five here since it never changes
Unless of course you are feeding this to something that already uses zip.
|
Python method to remove iterability
|
Suppose I have a function which can either take an iterable/iterator or a non-iterable as an argument. Iterability is checked with try: iter(arg).
Depending whether the input is an iterable or not, the outcome of the method will be different. Not when I want to pass a non-iterable as iterable input, it is easy to do: I’ll just wrap it with a tuple.
What do I do when I want to pass an iterable (a string for example) but want the function to take it as if it’s non-iterable? E.g. make that iter(str) fails.
Edit – my original intention:
I wanted to generalise the zip function in that it can zip iterables with non-iterables. The non-iterable would then repeat itself as often as the other iterables haven’t finished.
The only general solution fo me seems now to be, that I shouldn’t check inside the general_zip function (because of the string issues); but that instead I’ll have to add the repeat iterator to the argument before calling zip. (This actually saves me from inventing the general_zip function — although I still might because with a non-iterable as an input it would be unambiguous without the extra repeat.)
|
[
"The more I think about it, it seems like it’s not possible to do without type checking or passing argments to the function.\nHowever, depending on the intention of the function, one way to handle it could be:\nfrom itertools import repeat\nfunc(repeat(string_iterable))\n\nfunc still sees an iterable but it won’t iterate through the charaters of the string itself. And effectively, the argument works as if it’s a constant non-iterable.\n",
"Whoo! It appears you want to be able to pass iterables as iterables, iterables as noniterables, noniterables as iterables, and noniterables as noniterables. \nSince you want to be able to handle every possibility, and the computer can not (yet) read minds, you are going to have to tell the function how you want the argument to be handled:\ndef foo_iterable(iterable):\n ...\ndef foo_noniterable(noniterable):\n ...\n\ndef foo(thing,isiterable=True):\n if isiterable:\n foo_iterable(thing)\n else:\n foo_noniterable(thing)\n\nApply foo to an iterable \nfoo(iterable)\n\nApply foo to an iterable as a non-iterable:\nfoo_noniterable(iterable) # or\nfoo(iterable, isiterable=False)\n\nApply foo to a noniterable as a noniterable:\nfoo_noniterable(noniterable) # or\nfoo(noniterable,isiterable=False)\n\nApply foo to a noniterable as an iterable:\nfoo((noniterable,))\n\nPS. I'm a believer in small functions that do a single job well. They are easier to debug and unit-test. In general I would advise avoiding monolithic functions that behave differently depending on type. Yes, it puts a little extra burden on the developer to call exactly the function that is intended, but I think the advantages in terms of debugging and unit-testing more than make up for it. \n",
"Specialize it.\ndef can_iter(arg):\n if isinstance(arg, str):\n return False\n try:\n ...\n\n",
"Well, one approach to tell the function how you would like to treat its arguments is to have sensible defaults (making the function treat everything by its original type by default), while being able to specify any tweaks you like with comfort (i.e. with a short and absent-by-default fmt string), like:\ndef smart_func(*args, **kw):\n \"\"\"If 'kw' contains an 'fmt' parameter,\n it must be a list containing positions of arguments,\n that should be treated as if they were of opposite 'kind'\n (i.e. iterables will be treated as non-iterables and vise-versa)\n\n The 'kind' of a positional argument (i.e. whether it as an iterable)\n is inferred by trying to call 'iter()' on the argument.\n \"\"\"\n\n fmt = kw.get('fmt', [])\n\n def is_iter(it):\n try:\n iter(it)\n return True\n except TypeError:\n return False\n\n for i,arg in enumerate(args):\n arg_is_iterable = is_iter(arg)\n treat_arg_as_iterable = ((not arg_is_iterable)\n if (i in fmt) else arg_is_iterable)\n print arg, arg_is_iterable, treat_arg_as_iterable\n\nThis gives:\n>>> smart_func()\n>>> smart_func(1, 2, [])\n1 False False\n2 False False\n[] True True\n>>> smart_func(1, 2, [], fmt=[])\n1 False False\n2 False False\n[] True True\n>>> smart_func(1, 2, [], fmt=[0])\n1 False True\n2 False False\n[] True True\n>>> smart_func(1, 2, [], fmt=[0,2])\n1 False True\n2 False False\n[] True False\n\nExpanding this function (finding the length of the longest iterable, etc), one can construct a smart-zip you are talking about.\n[P.s.]\nAnother way will be to call the function in the following way: \nsmart_func(s='abc', 1, arr=[0,1], [1,2], fmt={'s':'non-iter','some_arr':'iter'})\n\nand have the function match the argument names you supplied ('s' and 'arr', note, there are no such names in the functions signature as it is the same as above) to the 'fmt' \"type-hints\" (i.e. 'iter' makes an argument considered as an iterable, and 'non-iter' as a non-iterable). This approach can, of course, be combined with the above \"toggle-type\" one.\n",
"Don't check for iterability. It is a mistake to have a function check things about its elements types/capabilities in order to have a single function perform different tasks. If you want to do two different things, make two different functions.\nIt sounds like you have come to this conclusion yourself and are providing a consistent API, where you do\nfrom itertools import repeat\nzip([1, 2, 3], repeat(5), \"bar\")\n\nNote that it's almost always useless to do this since you could just do\nfive = 5\nfor number, letter in zip([1, 2, 3], \"bar\")\n # Just use five here since it never changes\n\nUnless of course you are feeding this to something that already uses zip.\n"
] |
[
3,
2,
0,
0,
0
] |
[] |
[] |
[
"data_structures",
"iterator",
"python",
"string"
] |
stackoverflow_0002482996_data_structures_iterator_python_string.txt
|
Q:
Django logs: any tutorial to log to a file
I am working with a django project, I haven't started. The developed working on the project left. During the knowledge transfer, it was told to me that all the events are logged to the database. I don't find the database interface useful to search for logs and sometimes they don't even log(I might be wrong). I want to know, if there is an easy tutorial that explains how to enable logging in Django with minimal configuration changes.
Thank you
Bala
A:
If you are talking about the Django admin log (the one that shows on the right side of the main page of the admin interface), you could just enable an admin model for the log itself.
Open the admin.py for one of your django apps and add this:
from django.contrib.admin.models import LogEntry
class LogEntryAdmin(admin.ModelAdmin):
list_display = ('content_type', 'user', 'action_time')
admin.site.register(LogEntry, LogEntryAdmin)
It will give you a barebones interface for looking at the log.
Remember that log is only logging whatever happens through the admin interface itself.
|
Django logs: any tutorial to log to a file
|
I am working with a django project, I haven't started. The developed working on the project left. During the knowledge transfer, it was told to me that all the events are logged to the database. I don't find the database interface useful to search for logs and sometimes they don't even log(I might be wrong). I want to know, if there is an easy tutorial that explains how to enable logging in Django with minimal configuration changes.
Thank you
Bala
|
[
"If you are talking about the Django admin log (the one that shows on the right side of the main page of the admin interface), you could just enable an admin model for the log itself.\nOpen the admin.py for one of your django apps and add this:\nfrom django.contrib.admin.models import LogEntry\n\nclass LogEntryAdmin(admin.ModelAdmin):\n list_display = ('content_type', 'user', 'action_time')\n\nadmin.site.register(LogEntry, LogEntryAdmin)\n\nIt will give you a barebones interface for looking at the log. \nRemember that log is only logging whatever happens through the admin interface itself.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"logging",
"mod_python",
"python"
] |
stackoverflow_0002479858_django_logging_mod_python_python.txt
|
Q:
How to set the size of a wx.aui.AuiManager Pane that is centered?
I have three panes with the InfoPane center option.
I want to know how to set their size.
Using this code:
import wx
import wx.aui
class MyFrame(wx.Frame):
def __init__(self, parent, id=-1, title='wx.aui Test',
pos=wx.DefaultPosition, size=(800, 600),
style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self._mgr = wx.aui.AuiManager(self)
# create several text controls
text1 = wx.TextCtrl(self, -1, 'Pane 1 - sample text',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
text2 = wx.TextCtrl(self, -1, 'Pane 2 - sample text',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
text3 = wx.TextCtrl(self, -1, 'Main content window',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
# add the panes to the manager
self._mgr.AddPane(text1, wx.CENTER)
self._mgr.AddPane(text2, wx.CENTER)
self._mgr.AddPane(text3, wx.CENTER)
# tell the manager to 'commit' all the changes just made
self._mgr.Update()
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnClose(self, event):
# deinitialize the frame manager
self._mgr.UnInit()
# delete the frame
self.Destroy()
app = wx.App()
frame = MyFrame(None)
frame.Show()
app.MainLoop()
I want to know what is called when we change the size of the panes.
If you tell me that, I can do the rest by myself :)
A:
I've discovered what I want.
It was the wx.aui.AuiPaneInfo.dock_proportion property :)
|
How to set the size of a wx.aui.AuiManager Pane that is centered?
|
I have three panes with the InfoPane center option.
I want to know how to set their size.
Using this code:
import wx
import wx.aui
class MyFrame(wx.Frame):
def __init__(self, parent, id=-1, title='wx.aui Test',
pos=wx.DefaultPosition, size=(800, 600),
style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self._mgr = wx.aui.AuiManager(self)
# create several text controls
text1 = wx.TextCtrl(self, -1, 'Pane 1 - sample text',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
text2 = wx.TextCtrl(self, -1, 'Pane 2 - sample text',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
text3 = wx.TextCtrl(self, -1, 'Main content window',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
# add the panes to the manager
self._mgr.AddPane(text1, wx.CENTER)
self._mgr.AddPane(text2, wx.CENTER)
self._mgr.AddPane(text3, wx.CENTER)
# tell the manager to 'commit' all the changes just made
self._mgr.Update()
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnClose(self, event):
# deinitialize the frame manager
self._mgr.UnInit()
# delete the frame
self.Destroy()
app = wx.App()
frame = MyFrame(None)
frame.Show()
app.MainLoop()
I want to know what is called when we change the size of the panes.
If you tell me that, I can do the rest by myself :)
|
[
"I've discovered what I want.\nIt was the wx.aui.AuiPaneInfo.dock_proportion property :)\n"
] |
[
1
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002482914_python_wxpython.txt
|
Q:
Python: Does one of these examples waste more memory?
In a Django view function which uses manual transaction committing, I have:
context = RequestContext(request, data)
transaction.commit()
return render_to_response('basic.html', data, context) # Returns a Django ``HttpResponse`` object which is similar to a dictionary.
I think it is a better idea to do this:
context = RequestContext(request, data)
response = render_to_response('basic.html', data, context)
transaction.commit()
return response
If the page isn't rendered correctly in the second version, the transaction is rolled back. This seems like the logical way of doing it albeit there won't likely be many exceptions at that point in the function when the application is in production.
But... I fear that this might cost more and this will be replete through a number of functions since the application is heavy with custom transaction handling, so now is the time to figure out.
If the HttpResponse instance is in memory already (at the point of render_to_response()), then what does another reference cost? When the function ends, doesn't the reference (response variable) go away so that when Django is done converting the HttpResponse into a string for output Python can immediately garbage collect it?
Is there any reason I would want to use the first version (other than "It's 1 less line of code.")?
A:
You say, "there won't likely be many exceptions at that point in the function". This may not be true. Keep in mind that querysets are lazily fetched from the db, so in fact, a lot of your db activity could be inside the render_to_response call.
I'd use the second style. It's more correct in the sense that if something goes wrong in render_to_response, you want the transaction rolled back.
References cost almost nothing. Don't try to optimize them. Correctness is more important than absolute minimum memory footprint.
|
Python: Does one of these examples waste more memory?
|
In a Django view function which uses manual transaction committing, I have:
context = RequestContext(request, data)
transaction.commit()
return render_to_response('basic.html', data, context) # Returns a Django ``HttpResponse`` object which is similar to a dictionary.
I think it is a better idea to do this:
context = RequestContext(request, data)
response = render_to_response('basic.html', data, context)
transaction.commit()
return response
If the page isn't rendered correctly in the second version, the transaction is rolled back. This seems like the logical way of doing it albeit there won't likely be many exceptions at that point in the function when the application is in production.
But... I fear that this might cost more and this will be replete through a number of functions since the application is heavy with custom transaction handling, so now is the time to figure out.
If the HttpResponse instance is in memory already (at the point of render_to_response()), then what does another reference cost? When the function ends, doesn't the reference (response variable) go away so that when Django is done converting the HttpResponse into a string for output Python can immediately garbage collect it?
Is there any reason I would want to use the first version (other than "It's 1 less line of code.")?
|
[
"You say, \"there won't likely be many exceptions at that point in the function\". This may not be true. Keep in mind that querysets are lazily fetched from the db, so in fact, a lot of your db activity could be inside the render_to_response call. \nI'd use the second style. It's more correct in the sense that if something goes wrong in render_to_response, you want the transaction rolled back.\nReferences cost almost nothing. Don't try to optimize them. Correctness is more important than absolute minimum memory footprint.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"memory_management",
"python"
] |
stackoverflow_0002483761_django_memory_management_python.txt
|
Q:
Python - Filter by Date
How do I count how many logins were done per day on a system using the log file in Python?
A:
You don't need Python, the shell will do:
grep "Login succeeded_or_whatever_the_log_says" logfile | wc -l
If you really insist on using Python, try
print(sum(
1 for line in open('logfile')
if 'Login succeeded_or_whatever_the_log_says' in line))
If the login suceeded message spans multiple lines:
print(open('logfile').read().count('login\nsucceeded'))
You don't need to worry about closing the file handle; Python does that automatically when GCing a file handle:
$ touch x
$ python -c 'import time; open("x"); time.sleep(2)' & sleep 1 && fuser x
[1] 23232
$
but
$ python -c 'import time; f=open("x"); time.sleep(2)' & sleep 1 && fuser x
[1] 23265
x: 23265
$
|
Python - Filter by Date
|
How do I count how many logins were done per day on a system using the log file in Python?
|
[
"You don't need Python, the shell will do:\ngrep \"Login succeeded_or_whatever_the_log_says\" logfile | wc -l\n\nIf you really insist on using Python, try\nprint(sum(\n 1 for line in open('logfile')\n if 'Login succeeded_or_whatever_the_log_says' in line))\n\nIf the login suceeded message spans multiple lines:\nprint(open('logfile').read().count('login\\nsucceeded'))\n\nYou don't need to worry about closing the file handle; Python does that automatically when GCing a file handle:\n$ touch x\n$ python -c 'import time; open(\"x\"); time.sleep(2)' & sleep 1 && fuser x\n[1] 23232\n$\n\nbut\n$ python -c 'import time; f=open(\"x\"); time.sleep(2)' & sleep 1 && fuser x\n[1] 23265\nx: 23265\n$\n\n"
] |
[
1
] |
[
"You can create dictionary with day as a key, and login count as a value.\nThen read file line by line, extract date from each line and increase login count for that day.\nI think something like this should work:\nlogin_cnts = {}\n\ndef get_date(line):\n \"\"\"extract date from line, in this example line starts with YYYY-MM-DD (10 chars)\"\"\"\n if line and len(line) > 10:\n return line[:10]\n return None\n\n\nfor line in open(fname):\n date_str = get_date(line)\n if date_str:\n try:\n login_cnts[date_str] += 1\n except KeyError:\n login_cnts[date_str] = 1\n\ndays = login_cnts.keys()\ndays.sort()\nfor d in days:\n print(\"%s: %d\" % (d, login_cnts[d]))\n\n"
] |
[
-1
] |
[
"authentication",
"python"
] |
stackoverflow_0002483822_authentication_python.txt
|
Q:
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.
Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?
Thought about web for a second but it would not work for business reasons.
A:
You can get Windows executables in all three languages.
As usual with Perl, there's more than one way to do it:
PAR Packer (free/open-source)
perl2exe (shareware)
PerlApp (part of the Perl Dev Kit from ActiveState, commercial)
Python
py2exe
PyInstaller
Ruby
RubyScript2Exe
OCRA
A:
You can use Perl Archive Toolkit to bring a minimal perl core + needed modules + your Perl program with you.
And you can even convert it using PAR Packer to a windows exe file that will run just like any other program, from an end user's perspective.
A:
Using PAR, the Perl Aachiver has already been mentioned in other answers, and is an excellent solution. There's a short tutorial on building executables using PAR that was published as a Perl Tip last year.
In most cases, if you have PAR::Packer already installed on your build system, you can create a stand-alone executable with no external dependencies or requirements with:
pp -o example.exe example.pl
In most cases PAR will do all the hard work of determining your module dependencies for you, but if it gets anything wrong there are additional command line options you can use to ensure they get included. See the pp documentation for more details.
All the best,
Paul
A:
Are you sure there is a headache? ActivePerl and Strawberry Perl are dead easy to install on Windows with just a couple of mouse clicks. Python is just as easy to install from what I hear.
Have you tried installing any of those to see how easy it is? If those are hard for your customer, I don't see how giving them a script to run is going to be easier.
Or, maybe you can use something like a Docker image for Perl or provide it as a web service instead of an application.
A:
You could convert the script to an executable. In Python and Windows you can easily do that with py2exe. There are similar solutions for Perl and Ruby, but I believe py2exe is both free and reliable.
A:
A non-technical audience? You'll also want some sort of basic user interface, probably of the `graphical' type. You might try wxPython, which can be packaged into a Windows executable with py2exe and into a Mac application with py2app.
A:
Shoes can make exe's, and binaries for other platforms as well, and you get an integrated GUI.
A:
Ruby has the OCRA program that packages everything up into a nice neat .EXE file. The RubyScript2EXE program is no longer maintained, so this would be the better solution.
A:
"installing Perl on Windows would not be worth it for them" Really? It's that complex?
Python has a simple .MSI that neatly installs itself with no muss or fuss.
A simple application program is just a few .py files, so, I don't see a big pain factor there.
You know your customers best.
I find that the following isn't so bad. And it's much easier to support, since your upgrades will just be a single .MSI with simple, easy-to-live with source.
1) double click this .MSI file to install Python (or Perl or whatever)
2) double click this other .MSI to install the good stuff
|
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
|
I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.
Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?
Thought about web for a second but it would not work for business reasons.
|
[
"You can get Windows executables in all three languages. \n\nAs usual with Perl, there's more than one way to do it:\n\n\nPAR Packer (free/open-source)\nperl2exe (shareware)\nPerlApp (part of the Perl Dev Kit from ActiveState, commercial)\n\nPython \n\n\npy2exe\nPyInstaller\n\nRuby \n\n\nRubyScript2Exe\nOCRA\n\n\n",
"You can use Perl Archive Toolkit to bring a minimal perl core + needed modules + your Perl program with you.\nAnd you can even convert it using PAR Packer to a windows exe file that will run just like any other program, from an end user's perspective.\n",
"Using PAR, the Perl Aachiver has already been mentioned in other answers, and is an excellent solution. There's a short tutorial on building executables using PAR that was published as a Perl Tip last year.\nIn most cases, if you have PAR::Packer already installed on your build system, you can create a stand-alone executable with no external dependencies or requirements with:\npp -o example.exe example.pl\n\nIn most cases PAR will do all the hard work of determining your module dependencies for you, but if it gets anything wrong there are additional command line options you can use to ensure they get included. See the pp documentation for more details.\nAll the best,\nPaul\n",
"Are you sure there is a headache? ActivePerl and Strawberry Perl are dead easy to install on Windows with just a couple of mouse clicks. Python is just as easy to install from what I hear. \nHave you tried installing any of those to see how easy it is? If those are hard for your customer, I don't see how giving them a script to run is going to be easier.\nOr, maybe you can use something like a Docker image for Perl or provide it as a web service instead of an application.\n",
"You could convert the script to an executable. In Python and Windows you can easily do that with py2exe. There are similar solutions for Perl and Ruby, but I believe py2exe is both free and reliable.\n",
"A non-technical audience? You'll also want some sort of basic user interface, probably of the `graphical' type. You might try wxPython, which can be packaged into a Windows executable with py2exe and into a Mac application with py2app.\n",
"Shoes can make exe's, and binaries for other platforms as well, and you get an integrated GUI.\n",
"Ruby has the OCRA program that packages everything up into a nice neat .EXE file. The RubyScript2EXE program is no longer maintained, so this would be the better solution.\n",
"\"installing Perl on Windows would not be worth it for them\" Really? It's that complex?\nPython has a simple .MSI that neatly installs itself with no muss or fuss.\nA simple application program is just a few .py files, so, I don't see a big pain factor there.\nYou know your customers best.\nI find that the following isn't so bad. And it's much easier to support, since your upgrades will just be a single .MSI with simple, easy-to-live with source.\n1) double click this .MSI file to install Python (or Perl or whatever)\n2) double click this other .MSI to install the good stuff \n"
] |
[
31,
23,
8,
6,
3,
2,
1,
1,
0
] |
[] |
[] |
[
"perl",
"python",
"ruby"
] |
stackoverflow_0000446685_perl_python_ruby.txt
|
Q:
Testing variable types in Python
I'm creating an initialising function for the class 'Room', and found that the program wouldn't accept the tests I was doing on the input variables.
Why is this?
def __init__(self, code, name, type, size, description, objects, exits):
self.code = code
self.name = name
self.type = type
self.size = size
self.description = description
self.objects = objects
self.exits = exits
#Check for input errors:
if type(self.code) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 110'
elif type(self.name) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 111'
elif type(self.type) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 112'
elif type(self.size) != type(int()):
print 'Error found in module rooms.py!'
print 'Error number: 113'
elif type(self.description) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 114'
elif type(self.objects) != type(list()):
print 'Error found in module rooms.py!'
print 'Error number: 115'
elif type(self.exits) != type(tuple()):
print 'Error found in module rooms.py!'
print 'Error number: 116'
When I run this I get this error:
Traceback (most recent call last):
File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 148, in <module>
myRoom = Room(101, 'myRoom', 'Basic Room', 5, '<insert description>', myObjects, myExits)
File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 29, in __init__
if type(self.code) != type(str()):
TypeError: 'str' object is not callable
---- Thanks for help, but: -----
does this apply for isinstance(item, list) or isinstance(item, tuple)?
A:
Not answering the "why", but
str itself is a type already. You can use type(self.code) != str
But a better way is to use isinstance(self.code, str).
A:
Python is a dynamic language. It bad idea to test the types explicitly. In fact the code you write should in itself be such that you dont ever need to test the types of variables.
If you are coming from C/C++/Java then takes some time to get over that.
A:
Couple of things:
You have an incoming parameter named "type". This is masking the "type" built-in because it is a global, and locals trump globals. I assume this exception occurs because "type" has a string value.
Why are you printing error messages? The correct way to report an error is to raise an exception.
Overall I concur with the other answers that type-checking in general is a python anti-pattern. It it needed only in rare cases.
A:
Beside the ideas presented before you might want to check out decorator based type checking and contracts.
Historically there has been some interest in integrating optional typing to the language.
There are specific extension languages, such as Cython and Pyrex, that pretty much force you to type to some extent in order. The cool thing is that these languages allow you to generate high performance C extensions to use with your regular Python code.
A:
In general don't type-check, but if it's a genuine precondition for the arguments then verify them using assert rather than printing errors to stdout.
assert isinstance(code, str)
assert isinstance(name, str)
...
A:
It's not a good idea testing for types like this. However, if you must, do:
if isinstance(item, str):
# do your thing
|
Testing variable types in Python
|
I'm creating an initialising function for the class 'Room', and found that the program wouldn't accept the tests I was doing on the input variables.
Why is this?
def __init__(self, code, name, type, size, description, objects, exits):
self.code = code
self.name = name
self.type = type
self.size = size
self.description = description
self.objects = objects
self.exits = exits
#Check for input errors:
if type(self.code) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 110'
elif type(self.name) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 111'
elif type(self.type) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 112'
elif type(self.size) != type(int()):
print 'Error found in module rooms.py!'
print 'Error number: 113'
elif type(self.description) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 114'
elif type(self.objects) != type(list()):
print 'Error found in module rooms.py!'
print 'Error number: 115'
elif type(self.exits) != type(tuple()):
print 'Error found in module rooms.py!'
print 'Error number: 116'
When I run this I get this error:
Traceback (most recent call last):
File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 148, in <module>
myRoom = Room(101, 'myRoom', 'Basic Room', 5, '<insert description>', myObjects, myExits)
File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 29, in __init__
if type(self.code) != type(str()):
TypeError: 'str' object is not callable
---- Thanks for help, but: -----
does this apply for isinstance(item, list) or isinstance(item, tuple)?
|
[
"Not answering the \"why\", but \n\nstr itself is a type already. You can use type(self.code) != str\nBut a better way is to use isinstance(self.code, str).\n\n",
"Python is a dynamic language. It bad idea to test the types explicitly. In fact the code you write should in itself be such that you dont ever need to test the types of variables.\nIf you are coming from C/C++/Java then takes some time to get over that.\n",
"Couple of things:\n\nYou have an incoming parameter named \"type\". This is masking the \"type\" built-in because it is a global, and locals trump globals. I assume this exception occurs because \"type\" has a string value.\nWhy are you printing error messages? The correct way to report an error is to raise an exception.\n\nOverall I concur with the other answers that type-checking in general is a python anti-pattern. It it needed only in rare cases.\n",
"Beside the ideas presented before you might want to check out decorator based type checking and contracts.\nHistorically there has been some interest in integrating optional typing to the language.\nThere are specific extension languages, such as Cython and Pyrex, that pretty much force you to type to some extent in order. The cool thing is that these languages allow you to generate high performance C extensions to use with your regular Python code.\n",
"In general don't type-check, but if it's a genuine precondition for the arguments then verify them using assert rather than printing errors to stdout.\nassert isinstance(code, str)\nassert isinstance(name, str)\n...\n\n",
"It's not a good idea testing for types like this. However, if you must, do:\nif isinstance(item, str):\n # do your thing\n\n"
] |
[
13,
8,
3,
2,
2,
0
] |
[
"in python you just use the variables as if they where the type you want. \nif for some reason you have a function you call with different types, you can wrap your code in a try/catch.\ndef addOne(a):\n ''' \n increments a with 1 if a is a number. \n if a is a string, append '.' to it. \n '''\n try:\n return a + 1\n except TypeError:\n return a + \".\"\n\nbut you generally dont want to do that.\nfor the case above use to different functions\n"
] |
[
-1
] |
[
"python",
"testing",
"variables"
] |
stackoverflow_0002482230_python_testing_variables.txt
|
Q:
How do you subclass the file type in Python?
I'm trying to subclass the built-in file class in Python to add some extra features to stdin and stdout. Here's the code I have so far:
class TeeWithTimestamp(file):
"""
Class used to tee the output of a stream (such as stdout or stderr) into
another stream, and to add a timestamp to each message printed.
"""
def __init__(self, file1, file2):
"""Initializes the TeeWithTimestamp"""
self.file1 = file1
self.file2 = file2
self.at_start_of_line = True
def write(self, text):
"""Writes text to both files, prefixed with a timestamp"""
if len(text):
# Add timestamp if at the start of a line; also add [STDERR]
# for stderr
if self.at_start_of_line:
now = datetime.datetime.now()
prefix = now.strftime('[%H:%M:%S] ')
if self.file1 == sys.__stderr__:
prefix += '[STDERR] '
text = prefix + text
self.file1.write(text)
self.file2.write(text)
self.at_start_of_line = (text[-1] == '\n')
The purpose is to add a timestamp to the beginning of each message, and to log everything to a log file. However, the problem I run into is that if I do this:
# log_file has already been opened
sys.stdout = TeeWithTimestamp(sys.stdout, log_file)
Then when I try to do print 'foo', I get a ValueError: I/O operation on closed file. I can't meaningfully call file.__init__() in my __init__(), since I don't want to open a new file, and I can't assign self.closed = False either, since it's a read-only attribute.
How can I modify this so that I can do print 'foo', and so that it supports all of the standard file attributes and methods?
A:
Calling file.__init__ is quite feasible (e.g., on '/dev/null') but no real use because your attempted override of write doesn't "take" for the purposes of print statements -- the latter internally calls the real file.write when it sees that sys.stdout is an actual instance of file (and by inheriting you've made it so).
print doesn't really need any other method except write, so making your class inherit from object instead of file will work.
If you need other file methods (i.e., print is not all you're doing), you're best advised to implement them yourself.
A:
You can as well avoid using super :
class SuperFile(file):
def __init__(self, *args, **kwargs):
file.__init__(self, *args, **kwargs)
You'll be able to write with it.
|
How do you subclass the file type in Python?
|
I'm trying to subclass the built-in file class in Python to add some extra features to stdin and stdout. Here's the code I have so far:
class TeeWithTimestamp(file):
"""
Class used to tee the output of a stream (such as stdout or stderr) into
another stream, and to add a timestamp to each message printed.
"""
def __init__(self, file1, file2):
"""Initializes the TeeWithTimestamp"""
self.file1 = file1
self.file2 = file2
self.at_start_of_line = True
def write(self, text):
"""Writes text to both files, prefixed with a timestamp"""
if len(text):
# Add timestamp if at the start of a line; also add [STDERR]
# for stderr
if self.at_start_of_line:
now = datetime.datetime.now()
prefix = now.strftime('[%H:%M:%S] ')
if self.file1 == sys.__stderr__:
prefix += '[STDERR] '
text = prefix + text
self.file1.write(text)
self.file2.write(text)
self.at_start_of_line = (text[-1] == '\n')
The purpose is to add a timestamp to the beginning of each message, and to log everything to a log file. However, the problem I run into is that if I do this:
# log_file has already been opened
sys.stdout = TeeWithTimestamp(sys.stdout, log_file)
Then when I try to do print 'foo', I get a ValueError: I/O operation on closed file. I can't meaningfully call file.__init__() in my __init__(), since I don't want to open a new file, and I can't assign self.closed = False either, since it's a read-only attribute.
How can I modify this so that I can do print 'foo', and so that it supports all of the standard file attributes and methods?
|
[
"Calling file.__init__ is quite feasible (e.g., on '/dev/null') but no real use because your attempted override of write doesn't \"take\" for the purposes of print statements -- the latter internally calls the real file.write when it sees that sys.stdout is an actual instance of file (and by inheriting you've made it so).\nprint doesn't really need any other method except write, so making your class inherit from object instead of file will work.\nIf you need other file methods (i.e., print is not all you're doing), you're best advised to implement them yourself.\n",
"You can as well avoid using super :\nclass SuperFile(file):\n\n def __init__(self, *args, **kwargs):\n file.__init__(self, *args, **kwargs)\n\nYou'll be able to write with it.\n"
] |
[
12,
3
] |
[] |
[] |
[
"file",
"python",
"subclass"
] |
stackoverflow_0001082801_file_python_subclass.txt
|
Q:
How do I override a parent class's functions in python?
I have a private method def __pickSide(self): in a parent class that I would like to override in the child class. However, the child class still calls the inherited def __pickSide(self):. How can I override the function? The child class's function name is exactly the same as the parent's function name.
A:
Let's look at the easiest example:
from dis import dis
class A(object):
def __pick(self):
print "1"
def doitinA(self):
self.__pick()
class B(A):
def __pick(self):
print "2"
def doitinB(self):
self.__pick()
b = B()
b.doitinA() # prints 1
b.doitinB() # prints 2
dis(A.doitinA)
print
dis(B.doitinB)
The disassembly is as follows:
8 0 LOAD_FAST 0 (self)
3 LOAD_ATTR 0 (_A__pick)
6 CALL_FUNCTION 0
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
15 0 LOAD_FAST 0 (self)
3 LOAD_ATTR 0 (_B__pick)
6 CALL_FUNCTION 0
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
As you can see, Python mangles function names that begin with two underscores (and accesses to such names!!) to a name that includes the class name - in this case _A__pick and _B__pick). That means that the class in which a function is defined determines which of the __pick methods is called.
The solution is simple, avoid pseudo-private methods by removing the double underscores. For example, use _pick instead of __pick.
A:
The problem you're seeing is that the double underscores mangle the function name even in calls. This prevents polymorphism from working properly since the name it is mangled to is based on the name of the class the method is defined in, and not the name of the class of the object that is being referenced. Replacing the double underscores with something else will solve this.
A:
Using __foo names mangles the name of the method to make it more hassle to access it when you need to. I would recommend never using them, which makes things like testing go more smoothly.
There is no private in Python, and if there was, it would prevent you from doing this anyhow. (This is the point of private stuff in languages that have it.)
The common convention to indicate that an attribute is not part of the public interface of a class it to use a single leading underscore, like _foo. This is sufficient for making your code clear separating your internal details from your public API.
|
How do I override a parent class's functions in python?
|
I have a private method def __pickSide(self): in a parent class that I would like to override in the child class. However, the child class still calls the inherited def __pickSide(self):. How can I override the function? The child class's function name is exactly the same as the parent's function name.
|
[
"Let's look at the easiest example:\nfrom dis import dis\n\nclass A(object):\n def __pick(self):\n print \"1\"\n\n def doitinA(self):\n self.__pick()\n\nclass B(A):\n def __pick(self):\n print \"2\"\n\n def doitinB(self):\n self.__pick()\n\nb = B()\nb.doitinA() # prints 1\nb.doitinB() # prints 2\n\ndis(A.doitinA)\nprint\ndis(B.doitinB)\n\nThe disassembly is as follows:\n 8 0 LOAD_FAST 0 (self)\n 3 LOAD_ATTR 0 (_A__pick)\n 6 CALL_FUNCTION 0\n 9 POP_TOP\n 10 LOAD_CONST 0 (None)\n 13 RETURN_VALUE\n\n 15 0 LOAD_FAST 0 (self)\n 3 LOAD_ATTR 0 (_B__pick)\n 6 CALL_FUNCTION 0\n 9 POP_TOP\n 10 LOAD_CONST 0 (None)\n 13 RETURN_VALUE\n\nAs you can see, Python mangles function names that begin with two underscores (and accesses to such names!!) to a name that includes the class name - in this case _A__pick and _B__pick). That means that the class in which a function is defined determines which of the __pick methods is called.\nThe solution is simple, avoid pseudo-private methods by removing the double underscores. For example, use _pick instead of __pick.\n",
"The problem you're seeing is that the double underscores mangle the function name even in calls. This prevents polymorphism from working properly since the name it is mangled to is based on the name of the class the method is defined in, and not the name of the class of the object that is being referenced. Replacing the double underscores with something else will solve this.\n",
"\nUsing __foo names mangles the name of the method to make it more hassle to access it when you need to. I would recommend never using them, which makes things like testing go more smoothly.\nThere is no private in Python, and if there was, it would prevent you from doing this anyhow. (This is the point of private stuff in languages that have it.)\nThe common convention to indicate that an attribute is not part of the public interface of a class it to use a single leading underscore, like _foo. This is sufficient for making your code clear separating your internal details from your public API.\n\n"
] |
[
35,
5,
4
] |
[] |
[] |
[
"inheritance",
"overriding",
"parent",
"python"
] |
stackoverflow_0002484215_inheritance_overriding_parent_python.txt
|
Q:
PyLab - changing text color and background fill color of text box
I'm using PyLab to make some graphs in Python. I want to make a text box that is colored magenta with black text, but cannot get the text to be black.
text(x, y, 'Summary', backgroundcolor = 'm', color = 'k')
This gives me a magenta background and then text that is almost just as pink. Any ideas what I'm doing wrong?
Many thanks!
A:
it doesn't appear as though you're doing anything wrong:
In [23]: pylab.text(0.25, 0.5, 'test', backgroundcolor='m', color='r')
In [24]: pylab.text(0.5, 0.5, 'test', backgroundcolor='m', color='k')
In [25]: pylab.text(0.75, 0.5, 'test', backgroundcolor='m', color='b')
alt text http://student.physics.ucdavis.edu/~rjames/test.png
perhaps somewhere else in your code (or matplotlib installation) the mapping from strings to colors has been corrupted?
|
PyLab - changing text color and background fill color of text box
|
I'm using PyLab to make some graphs in Python. I want to make a text box that is colored magenta with black text, but cannot get the text to be black.
text(x, y, 'Summary', backgroundcolor = 'm', color = 'k')
This gives me a magenta background and then text that is almost just as pink. Any ideas what I'm doing wrong?
Many thanks!
|
[
"it doesn't appear as though you're doing anything wrong:\nIn [23]: pylab.text(0.25, 0.5, 'test', backgroundcolor='m', color='r')\nIn [24]: pylab.text(0.5, 0.5, 'test', backgroundcolor='m', color='k')\nIn [25]: pylab.text(0.75, 0.5, 'test', backgroundcolor='m', color='b')\n\nalt text http://student.physics.ucdavis.edu/~rjames/test.png\nperhaps somewhere else in your code (or matplotlib installation) the mapping from strings to colors has been corrupted?\n"
] |
[
5
] |
[] |
[] |
[
"matplotlib",
"python"
] |
stackoverflow_0002484256_matplotlib_python.txt
|
Q:
Would it be possible to integrate Python or Perl with Ruby?
Would it be possible to integrate Python (and/or Perl) and Ruby? I've looked at http://www.goto.info.waseda.ac.jp/~fukusima/ruby/python/doc/ and http://code.google.com/p/ruby-perl/ , but they both seem rather outdated.
Has someone generated a Ruby interface for Python's C API?
Edit: Python can be integrated with many other languages according to http://wiki.python.org/moin/IntegratingPythonWithOtherLanguages . However, that list doesn't include Ruby.
A:
My school (Georgia Tech), along with Bryn Mawr and Microsoft Research, are doing a project right now called Pyjama. Basically, it uses the Microsoft DLR to allow you to freely mix Python and Ruby. I haven't tried it, but it sounds pretty cool.
Here's an example from the website. You enter the class in "Python mode". Then it gets compiled, and you run the command in "Ruby mode".
class PythonClass:
def hello(self, value):
print "Python says hello to", value
pc = python_class().new
pc.hello "Ruby"
Which produces "Python says hello to Ruby".
A:
Integrating dynamic languages is one of the goals of the Parrot project. It's a virtual machine that dynamic language compilers target. Once compiled to the same virtual machine, you should be able to used the "object" form in any of the languages no matter the object's source.
The issue at the moment, however, is stabilizing the virtual machine and finishing off the mostly done compilers. However, that's been the state for a long time. :)
A:
It might by possible, but not very practical. It would be significantly easier to port whatever modules you need from one to the other than it would be to embed one of the interpreters within the other.
If you absolutely have to use both languages in a project, your best option would probably the combination of Jython and Jruby, or IronPython and IronRuby. I'm not sure if you could get them to talk to each other, but at the very least you could host them on the same virtual machine.
A:
For a research project I wanted to use the fabulous matplotlib that's available for Python. I also found that library that you referred to. However, it doesn't look like something popular and well tested. So I decided to write the script that generated graphs using pure Python and called it from Ruby via popen. That worked very well for me.
A:
You can write extensions for Ruby in C.
So, if Python has a C API, you can write a C extension for Ruby which uses this API.
I know nothing about the Python API or how large of a piece you want to integrate with, but if it is not too big, this could (possibly) give you a way to run Python code from Ruby.
A:
Another strategy, as used by Facebook, is to expose APIs via Thrift. You define lightweight service APIs and the RPCs are inter-process.
|
Would it be possible to integrate Python or Perl with Ruby?
|
Would it be possible to integrate Python (and/or Perl) and Ruby? I've looked at http://www.goto.info.waseda.ac.jp/~fukusima/ruby/python/doc/ and http://code.google.com/p/ruby-perl/ , but they both seem rather outdated.
Has someone generated a Ruby interface for Python's C API?
Edit: Python can be integrated with many other languages according to http://wiki.python.org/moin/IntegratingPythonWithOtherLanguages . However, that list doesn't include Ruby.
|
[
"My school (Georgia Tech), along with Bryn Mawr and Microsoft Research, are doing a project right now called Pyjama. Basically, it uses the Microsoft DLR to allow you to freely mix Python and Ruby. I haven't tried it, but it sounds pretty cool.\nHere's an example from the website. You enter the class in \"Python mode\". Then it gets compiled, and you run the command in \"Ruby mode\".\nclass PythonClass:\n def hello(self, value):\n print \"Python says hello to\", value\n\npc = python_class().new\npc.hello \"Ruby\"\n\nWhich produces \"Python says hello to Ruby\".\n",
"Integrating dynamic languages is one of the goals of the Parrot project. It's a virtual machine that dynamic language compilers target. Once compiled to the same virtual machine, you should be able to used the \"object\" form in any of the languages no matter the object's source.\nThe issue at the moment, however, is stabilizing the virtual machine and finishing off the mostly done compilers. However, that's been the state for a long time. :)\n",
"It might by possible, but not very practical. It would be significantly easier to port whatever modules you need from one to the other than it would be to embed one of the interpreters within the other.\nIf you absolutely have to use both languages in a project, your best option would probably the combination of Jython and Jruby, or IronPython and IronRuby. I'm not sure if you could get them to talk to each other, but at the very least you could host them on the same virtual machine.\n",
"For a research project I wanted to use the fabulous matplotlib that's available for Python. I also found that library that you referred to. However, it doesn't look like something popular and well tested. So I decided to write the script that generated graphs using pure Python and called it from Ruby via popen. That worked very well for me.\n",
"You can write extensions for Ruby in C. \nSo, if Python has a C API, you can write a C extension for Ruby which uses this API. \nI know nothing about the Python API or how large of a piece you want to integrate with, but if it is not too big, this could (possibly) give you a way to run Python code from Ruby. \n",
"Another strategy, as used by Facebook, is to expose APIs via Thrift. You define lightweight service APIs and the RPCs are inter-process.\n"
] |
[
7,
5,
2,
2,
2,
1
] |
[] |
[] |
[
"perl",
"python",
"ruby"
] |
stackoverflow_0002413878_perl_python_ruby.txt
|
Q:
Euclidian Distances between points
I have an array of points in numpy:
points = rand(dim, n_points)
And I want to:
Calculate all the l2 norm (euclidian distance) between a certain point and all other points
Calculate all pairwise distances.
and preferably all numpy and no for's. How can one do it?
A:
If you're willing to use SciPy, the scipy.spatial.distance module (the functions cdist and/or pdist) do exactly what you want, with all the looping done in C. You can do it with broadcasting too but there's some extra memory overhead.
A:
This might help with the second part:
import numpy as np
from numpy import *
p=rand(3,4) # this is column-wise so each vector has length 3
sqrt(sum((p[:,np.newaxis,:]-p[:,:,np.newaxis])**2 ,axis=0) )
which gives
array([[ 0. , 0.37355868, 0.64896708, 1.14974483],
[ 0.37355868, 0. , 0.6277216 , 1.19625254],
[ 0.64896708, 0.6277216 , 0. , 0.77465192],
[ 1.14974483, 1.19625254, 0.77465192, 0. ]])
if p was
array([[ 0.46193242, 0.11934744, 0.3836483 , 0.84897951],
[ 0.19102709, 0.33050367, 0.36382587, 0.96880535],
[ 0.84963349, 0.79740414, 0.22901247, 0.09652746]])
and you can check one of the entries via
sqrt(sum ((p[:,0]-p[:,2] )**2 ))
0.64896708223796884
The trick is to put newaxis and then do broadcasting.
Good luck!
|
Euclidian Distances between points
|
I have an array of points in numpy:
points = rand(dim, n_points)
And I want to:
Calculate all the l2 norm (euclidian distance) between a certain point and all other points
Calculate all pairwise distances.
and preferably all numpy and no for's. How can one do it?
|
[
"If you're willing to use SciPy, the scipy.spatial.distance module (the functions cdist and/or pdist) do exactly what you want, with all the looping done in C. You can do it with broadcasting too but there's some extra memory overhead.\n",
"This might help with the second part:\nimport numpy as np\nfrom numpy import *\np=rand(3,4) # this is column-wise so each vector has length 3\nsqrt(sum((p[:,np.newaxis,:]-p[:,:,np.newaxis])**2 ,axis=0) )\n\nwhich gives\narray([[ 0. , 0.37355868, 0.64896708, 1.14974483],\n [ 0.37355868, 0. , 0.6277216 , 1.19625254],\n [ 0.64896708, 0.6277216 , 0. , 0.77465192],\n [ 1.14974483, 1.19625254, 0.77465192, 0. ]])\n\nif p was\narray([[ 0.46193242, 0.11934744, 0.3836483 , 0.84897951],\n [ 0.19102709, 0.33050367, 0.36382587, 0.96880535],\n [ 0.84963349, 0.79740414, 0.22901247, 0.09652746]])\n\nand you can check one of the entries via\nsqrt(sum ((p[:,0]-p[:,2] )**2 ))\n0.64896708223796884\n\nThe trick is to put newaxis and then do broadcasting.\nGood luck!\n"
] |
[
4,
1
] |
[] |
[] |
[
"euclidean_distance",
"numpy",
"python"
] |
stackoverflow_0002483100_euclidean_distance_numpy_python.txt
|
Q:
How can I access the "through" object of a Django ManyToManyField?
I have the following models in my Django app. How can I from the Team model find all the User objects who have accepted as True in the Membership model? I know I need to use Team.objects.filter(), but I'm not sure how to check the value of the accepted field.
from django.contrib.auth.models import User
class Team(models.Model):
members = models.ManyToManyField(User, through="Membership")
class Membership(models.Model):
user = models.ForeignKey(User)
team = models.ForeignKey(Team)
accepted = models.BooleanField(default=False)
A:
Accepted members of a team:
team_42.members.filter(membership__accepted=True)
Teams user alice has been accepted by:
alice.team_set.filter(membership__accepted=True)
I believe you want to get the set of Team or User objects and not the set of intermediate Membership objects. You answered the question yourself but with an answer that gives the set of Membership objects.
|
How can I access the "through" object of a Django ManyToManyField?
|
I have the following models in my Django app. How can I from the Team model find all the User objects who have accepted as True in the Membership model? I know I need to use Team.objects.filter(), but I'm not sure how to check the value of the accepted field.
from django.contrib.auth.models import User
class Team(models.Model):
members = models.ManyToManyField(User, through="Membership")
class Membership(models.Model):
user = models.ForeignKey(User)
team = models.ForeignKey(Team)
accepted = models.BooleanField(default=False)
|
[
"Accepted members of a team:\nteam_42.members.filter(membership__accepted=True)\n\nTeams user alice has been accepted by:\nalice.team_set.filter(membership__accepted=True)\n\nI believe you want to get the set of Team or User objects and not the set of intermediate Membership objects. You answered the question yourself but with an answer that gives the set of Membership objects.\n"
] |
[
1
] |
[
"Team.objects.filter(members__accepted__exact=True)\nTake a look at this. It has a lot of great examples and explanations.\n"
] |
[
-1
] |
[
"django",
"python"
] |
stackoverflow_0002483948_django_python.txt
|
Q:
Prevent python from printing newline
I have this code in Python
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
that outputs
Enter in something: something
Input is something
, including the return
I am not sure what is happening; if I use variables that don't depend on user input, I do not get the newline after formatting with the variable. I suspect Python might be taking in the newline as input when I hit return.
How can I make it so that the input does not include any newlines so that I may compare it to other strings/characters? (e.g. something == 'a')
A:
You are correct - a newline is included in inputted. To remove it, you can just call strip("\r\n") to remove the newline from the end:
print("Input is {0}, including the return".format(inputted.strip("\r\n")))
This won't cause any issues if inputted does not have a newline at the end, but will remove any that are there, so you can use this whether inputted is user input or not.
If you don't want any newlines in the text at all, you can use inputted.replace("\r\n", "") to remove all newlines.
A:
Your problem is actually Eclipse. Assuming that you use PyDev, I was able to reproduce the problem. When entering something in the Eclipse console, the problem occurs as described in your question. But when directly executing the very same script with the Python 3.1.1 interpreter, inputted does not include a newline character.
I investigated the Python source code and found out input() uses GNU readline if stdin is interactive (i.e. a TTY or prompt, however you want to call it), but falls back to the .readline() method of the stdin object if necessary. Then, if the result of readline ends with \n, that character is removed. Note: No CR-LF or LF-CR handling here (in the fallback case)!
So I wrote this little script to see what actually happens:
import sys
from io import StringIO
for stdin in [sys.stdin, StringIO("test\r\ntest\r\n")]:
sys.stdin = stdin
print("readline returns this: " + repr(sys.stdin.readline()))
inputted = input("Enter in something: ")
print("inputted: " + repr(inputted))
print("inputted is printed like this: --> {0} <--".format(inputted))
It first executes the code with the normal stdin (console or Eclipse console) and then with a prepared stdin containing the text test\r\ntest\r\n.
Try and run the script in Eclipse - you must enter a string twice. The conclusion: Pressing Enter in the Eclipse console will produce CR-LF ("\r\n"). Printing "\r" in the Eclipse console will jump to the next line.
On the other side, running it in the Windows console will produce the expected output: input() returns a string without a newline at the end because (I guess) GNU readline is used. With the prepared stdin StringIO("test\r\n"), the input() result is "test\r" as in Eclipse (although not printed as newline).
Hope this all makes sense... but what I still don't know is if that is expected behavior of Eclipse.
A:
If you only want to stript the last line endings, you could use rstrip.
inputted.rstrip ("\r\n")
A:
inputted = inputted.strip()
Edit: As noted, this will kill all whitespace at the start and end. A way to get rid of only the trailing newline is:
import re
inputted = re.sub("[\n\r]+$", "", inputted)
|
Prevent python from printing newline
|
I have this code in Python
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
that outputs
Enter in something: something
Input is something
, including the return
I am not sure what is happening; if I use variables that don't depend on user input, I do not get the newline after formatting with the variable. I suspect Python might be taking in the newline as input when I hit return.
How can I make it so that the input does not include any newlines so that I may compare it to other strings/characters? (e.g. something == 'a')
|
[
"You are correct - a newline is included in inputted. To remove it, you can just call strip(\"\\r\\n\") to remove the newline from the end:\nprint(\"Input is {0}, including the return\".format(inputted.strip(\"\\r\\n\")))\n\nThis won't cause any issues if inputted does not have a newline at the end, but will remove any that are there, so you can use this whether inputted is user input or not.\nIf you don't want any newlines in the text at all, you can use inputted.replace(\"\\r\\n\", \"\") to remove all newlines.\n",
"Your problem is actually Eclipse. Assuming that you use PyDev, I was able to reproduce the problem. When entering something in the Eclipse console, the problem occurs as described in your question. But when directly executing the very same script with the Python 3.1.1 interpreter, inputted does not include a newline character.\nI investigated the Python source code and found out input() uses GNU readline if stdin is interactive (i.e. a TTY or prompt, however you want to call it), but falls back to the .readline() method of the stdin object if necessary. Then, if the result of readline ends with \\n, that character is removed. Note: No CR-LF or LF-CR handling here (in the fallback case)!\nSo I wrote this little script to see what actually happens:\nimport sys\nfrom io import StringIO\n\nfor stdin in [sys.stdin, StringIO(\"test\\r\\ntest\\r\\n\")]:\n sys.stdin = stdin \n\n print(\"readline returns this: \" + repr(sys.stdin.readline()))\n\n inputted = input(\"Enter in something: \")\n print(\"inputted: \" + repr(inputted))\n\n print(\"inputted is printed like this: --> {0} <--\".format(inputted))\n\nIt first executes the code with the normal stdin (console or Eclipse console) and then with a prepared stdin containing the text test\\r\\ntest\\r\\n.\nTry and run the script in Eclipse - you must enter a string twice. The conclusion: Pressing Enter in the Eclipse console will produce CR-LF (\"\\r\\n\"). Printing \"\\r\" in the Eclipse console will jump to the next line.\nOn the other side, running it in the Windows console will produce the expected output: input() returns a string without a newline at the end because (I guess) GNU readline is used. With the prepared stdin StringIO(\"test\\r\\n\"), the input() result is \"test\\r\" as in Eclipse (although not printed as newline).\nHope this all makes sense... but what I still don't know is if that is expected behavior of Eclipse.\n",
"If you only want to stript the last line endings, you could use rstrip.\n\ninputted.rstrip (\"\\r\\n\")\n\n",
"inputted = inputted.strip()\n\nEdit: As noted, this will kill all whitespace at the start and end. A way to get rid of only the trailing newline is:\nimport re\ninputted = re.sub(\"[\\n\\r]+$\", \"\", inputted)\n\n"
] |
[
7,
4,
3,
2
] |
[] |
[] |
[
"input",
"newline",
"python",
"user_input"
] |
stackoverflow_0002484420_input_newline_python_user_input.txt
|
Q:
Which dynamic language can easily use libraries from other languages?
Tell why you think Python, Perl, Ruby, etc is easiest for plugging in modules from other languages with minimal thought.
To clarify, an example: I want to write business logic in Python, but use functionality that conveniently exists as a Perl module.
In other words, which language "just works" with the most modules?
A:
Perl has very good support for other languages via the Inline set of modules.
Inline::Python allows you to import Python modules, classes and functions into your Perl code and call them from Perl as if they were native - see Importing Functions.
Inline::Ruby works virtually the same way.
A:
The Parrot VM looks like the way to go for this purpose, since
Parrot currently hosts a variety of
language implementations in various
stages of completion, including Tcl,
Javascript, Ruby, Lua, Scheme, PHP,
Python, Perl 6, APL, and a .NET
bytecode translator
It matters less, I think, which of these languages you use as the "main driver" and which one just as "guests" for this module or that -- just check that you pick one whose Parrot implementation is complete and mature (since Parrot's a rather new project, and so are some of these language implementations on top of it).
A:
If you want to plug in a Perl module, the language which is best suited for this is Perl. Perl is able to represent the semantics and capabilities of code written in Perl correctly. This really shouldn't be a shock.
If you have a self-contained program you want to call from another program in its own process, not constantly interacting, any of these languages can do that with programs written in whatever language. At that point, you aren't really using other languages inside a program but just calling other problems.
There are several projects to combine various pairs and projects (like Parrot) that seek to provide a platform for a large range of languages for compatibility and projects (like .NET) that almost accidentally provide compatibility among previously-incompatible languages. However, I do not think most of these are as robust, mature, and suited for combining normal code as you would hope.
A:
all 3 languages have very good, clear facilities for just calling any executable in a subprocess (including executables like python somethingelse.py or ruby somethingelse.rb).
use what you know best.
A:
I'm going to answer on a more architectural level here. The question is what are you trying to do... do you want to write your business logic in Python and call a Perl function from Python? Or are you looking to execute a script? If so, how will the two communicate?
I suspect, but don't know, that Parrot VM might allow you to do that, but as Mike points out, there are difficulties. Cross-language work is hard just like IPC across programs is hard unless you use some form of loose coupling (not so tied to the language). To that end, you might consider setting up the controller in one language and having everyone else talk via a dbus queue, or whatever mechanism you prefer for whichever platform you're on. It doesn't really matter how you do it (cue a debate on the best mechanism) but properly designed it makes talking across languages and building plug-ins very easy. For example, you might have a queue for process_new_user, for example. Any script who registers in that queue gets access to the data so a new developer can easily add functionality for their part of the program. Interpret that as: you can easily use a different scripting language to implement that bit.
A:
The Dynamic Language Runtime was specifically designed to allow one dynamic language to use objects and functions defined in another dynamic language. Currently Python and Ruby have DLR implementations, but I haven't heard anything about Perl.
To use the DLR you need either .NET or Mono.
A:
Most scripting languages can handle this kind of thing (by running external programs written in other languages,) but it seems as if your best bet might be shell scripting of some kind (Windows users call this "batch scripting," but the DOS syntax is horrible and not recommended.) UNIX programmers have been freely mixing languages in this way for a long time. On Windows, you can install Cygwin to get a fully functional BASH shell.
The shell was originally intended as a user interface, used to launch other programs or combine them in interesting ways. However, many shells (notably the Bourne shell or its modern descendant, BASH) are also fully-fledged programming languages. Each of your "modules" can be created as separate, standalone programs which will be run by the shell script.
|
Which dynamic language can easily use libraries from other languages?
|
Tell why you think Python, Perl, Ruby, etc is easiest for plugging in modules from other languages with minimal thought.
To clarify, an example: I want to write business logic in Python, but use functionality that conveniently exists as a Perl module.
In other words, which language "just works" with the most modules?
|
[
"Perl has very good support for other languages via the Inline set of modules.\nInline::Python allows you to import Python modules, classes and functions into your Perl code and call them from Perl as if they were native - see Importing Functions.\nInline::Ruby works virtually the same way.\n",
"The Parrot VM looks like the way to go for this purpose, since\n\nParrot currently hosts a variety of\n language implementations in various\n stages of completion, including Tcl,\n Javascript, Ruby, Lua, Scheme, PHP,\n Python, Perl 6, APL, and a .NET\n bytecode translator\n\nIt matters less, I think, which of these languages you use as the \"main driver\" and which one just as \"guests\" for this module or that -- just check that you pick one whose Parrot implementation is complete and mature (since Parrot's a rather new project, and so are some of these language implementations on top of it).\n",
"If you want to plug in a Perl module, the language which is best suited for this is Perl. Perl is able to represent the semantics and capabilities of code written in Perl correctly. This really shouldn't be a shock.\nIf you have a self-contained program you want to call from another program in its own process, not constantly interacting, any of these languages can do that with programs written in whatever language. At that point, you aren't really using other languages inside a program but just calling other problems.\nThere are several projects to combine various pairs and projects (like Parrot) that seek to provide a platform for a large range of languages for compatibility and projects (like .NET) that almost accidentally provide compatibility among previously-incompatible languages. However, I do not think most of these are as robust, mature, and suited for combining normal code as you would hope.\n",
"all 3 languages have very good, clear facilities for just calling any executable in a subprocess (including executables like python somethingelse.py or ruby somethingelse.rb).\nuse what you know best.\n",
"I'm going to answer on a more architectural level here. The question is what are you trying to do... do you want to write your business logic in Python and call a Perl function from Python? Or are you looking to execute a script? If so, how will the two communicate?\nI suspect, but don't know, that Parrot VM might allow you to do that, but as Mike points out, there are difficulties. Cross-language work is hard just like IPC across programs is hard unless you use some form of loose coupling (not so tied to the language). To that end, you might consider setting up the controller in one language and having everyone else talk via a dbus queue, or whatever mechanism you prefer for whichever platform you're on. It doesn't really matter how you do it (cue a debate on the best mechanism) but properly designed it makes talking across languages and building plug-ins very easy. For example, you might have a queue for process_new_user, for example. Any script who registers in that queue gets access to the data so a new developer can easily add functionality for their part of the program. Interpret that as: you can easily use a different scripting language to implement that bit.\n",
"The Dynamic Language Runtime was specifically designed to allow one dynamic language to use objects and functions defined in another dynamic language. Currently Python and Ruby have DLR implementations, but I haven't heard anything about Perl.\nTo use the DLR you need either .NET or Mono.\n",
"Most scripting languages can handle this kind of thing (by running external programs written in other languages,) but it seems as if your best bet might be shell scripting of some kind (Windows users call this \"batch scripting,\" but the DOS syntax is horrible and not recommended.) UNIX programmers have been freely mixing languages in this way for a long time. On Windows, you can install Cygwin to get a fully functional BASH shell. \nThe shell was originally intended as a user interface, used to launch other programs or combine them in interesting ways. However, many shells (notably the Bourne shell or its modern descendant, BASH) are also fully-fledged programming languages. Each of your \"modules\" can be created as separate, standalone programs which will be run by the shell script. \n"
] |
[
9,
6,
3,
0,
0,
0,
0
] |
[] |
[] |
[
"dynamic_languages",
"module",
"perl",
"python",
"ruby"
] |
stackoverflow_0002483924_dynamic_languages_module_perl_python_ruby.txt
|
Q:
What's the Ruby equivalent of Python's output[:-1]?
In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
A:
I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing "StackOverflow"[0..-2] you can do "StackOverflow"[0...-1] for the same result.
In Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string slicing, the three dots is a bit more close to Python's syntax.
A:
Your current Ruby doesn't do what you describe: it cuts off the last character, but it also reverses the string.
The closest equivalent to the Python snippet would be
output = 'stackoverflow'
puts output[0...-1]
You originally used .. instead of ... (which would work if you did output[0..-2]); the former being closed–closed the latter being closed–open. Slices—and most everything else—in Python are closed–open.
A:
"stackoverflow"[0..-2] will return "stackoverflo"
A:
If all you want to do is remove the last character of the string, you can use the 'chop' method as well:
puts output.chop
or
puts output.chop!
A:
If you only want to remove the last character, you can also do
output.chop
|
What's the Ruby equivalent of Python's output[:-1]?
|
In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
|
[
"I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing \"StackOverflow\"[0..-2] you can do \"StackOverflow\"[0...-1] for the same result.\nIn Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string slicing, the three dots is a bit more close to Python's syntax.\n",
"Your current Ruby doesn't do what you describe: it cuts off the last character, but it also reverses the string.\nThe closest equivalent to the Python snippet would be\noutput = 'stackoverflow'\nputs output[0...-1]\n\nYou originally used .. instead of ... (which would work if you did output[0..-2]); the former being closed–closed the latter being closed–open. Slices—and most everything else—in Python are closed–open.\n",
"\"stackoverflow\"[0..-2] will return \"stackoverflo\"\n",
"If all you want to do is remove the last character of the string, you can use the 'chop' method as well:\nputs output.chop\n\nor\nputs output.chop!\n\n",
"If you only want to remove the last character, you can also do\noutput.chop\n\n"
] |
[
11,
4,
2,
1,
1
] |
[] |
[] |
[
"python",
"ruby"
] |
stackoverflow_0002484863_python_ruby.txt
|
Q:
Aggregation over a few models - Django
I'm trying to compute the average of a field over various subsets of a queryset.
Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level'))
This works perfectly!
But... if I try to compute it for the top 50 players it does not work.
Player.objects.order_by('-score').filter(sex='male')[:50].aggregate(Avg('level'))
This last one returns the exact same result as the query above it, which is wrong.
What am I doing wrong?
Help would be very much appreciated!
A:
topfifty = Player.objects.order_by('-score')[:50]
Player.objects.filter(sex='male',pk__in=topfifty).aggregate(avglevel=Avg('level'))
edit: i haven't tested this, but i think you get the idea of where i'm going.
topfifty = Player.objects.order_by('-score')[:50]
ids = []
for t in topfifty:
ids += [t.id]
Player.objects.filter(sex='male',pk__in=ids).aggregate(avglevel=Avg('level'))
it's kind of hackish but the best i can think of. perhaps consider filtering for male and taking the top 50 males instead of this which takes the top fifty and then filters out the males.
A:
Break the problem up into two logical steps; figure out the target set, perform the aggregate calculation.
top50_male_players = Player.objects.filter(sex='male').order_by('-score')[:50]
result = Player.objects.filter(pk__in=top50_male_players).aggregate(Avg('level'))
Thanks to lazy evaluation of the QuerySet it will be performed in a single DB operation. You can play with this in the shell to verify the query counts.
> from django.db import connection
> connection.queries = []
> top50_male_players = Player.objects.filter(sex='male').order_by('-score')[:50]
> len(connection.queries)
0
> result = Player.objects.filter(pk__in=top50_male_players).aggregate(Avg('level'))
> len(connection.queries)
1
> result
{'level__avg': <some number>}
> len(connection.queries)
1
|
Aggregation over a few models - Django
|
I'm trying to compute the average of a field over various subsets of a queryset.
Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level'))
This works perfectly!
But... if I try to compute it for the top 50 players it does not work.
Player.objects.order_by('-score').filter(sex='male')[:50].aggregate(Avg('level'))
This last one returns the exact same result as the query above it, which is wrong.
What am I doing wrong?
Help would be very much appreciated!
|
[
"topfifty = Player.objects.order_by('-score')[:50]\nPlayer.objects.filter(sex='male',pk__in=topfifty).aggregate(avglevel=Avg('level'))\n\nedit: i haven't tested this, but i think you get the idea of where i'm going.\ntopfifty = Player.objects.order_by('-score')[:50]\nids = []\nfor t in topfifty:\n ids += [t.id]\n\nPlayer.objects.filter(sex='male',pk__in=ids).aggregate(avglevel=Avg('level'))\n\nit's kind of hackish but the best i can think of. perhaps consider filtering for male and taking the top 50 males instead of this which takes the top fifty and then filters out the males.\n",
"Break the problem up into two logical steps; figure out the target set, perform the aggregate calculation.\ntop50_male_players = Player.objects.filter(sex='male').order_by('-score')[:50]\nresult = Player.objects.filter(pk__in=top50_male_players).aggregate(Avg('level'))\n\nThanks to lazy evaluation of the QuerySet it will be performed in a single DB operation. You can play with this in the shell to verify the query counts.\n> from django.db import connection\n> connection.queries = []\n> top50_male_players = Player.objects.filter(sex='male').order_by('-score')[:50]\n> len(connection.queries)\n0\n> result = Player.objects.filter(pk__in=top50_male_players).aggregate(Avg('level'))\n> len(connection.queries)\n1\n> result\n{'level__avg': <some number>}\n> len(connection.queries)\n1\n\n"
] |
[
4,
3
] |
[
"Hmm. The docs say\n\"Slicing. As explained in Limiting QuerySets, a QuerySet can be sliced, using Python's array-slicing syntax. Usually slicing a QuerySet returns another (unevaluated) QuerySet, but Django will execute the database query if you use the \"step\" parameter of slice syntax.\" http://docs.djangoproject.com/en/dev/ref/models/querysets/\nSo I'd try\nPlayer.objects.order_by('-score').filter(sex='male')[0:50:1].aggregate(Avg('level'))\n\n"
] |
[
-1
] |
[
"database",
"django",
"django_models",
"python"
] |
stackoverflow_0002481839_database_django_django_models_python.txt
|
Q:
Modify Django settings variables in a middleware
I set a variable MAX_REQUEST = 100 in settings.py
I write a middleware which may lower this value for request origining from a proxy ip address by the following code:
settings.MAX_REQUEST = 10
However, looks like the above modification affects all legitimate users.
Is it normal?
A:
Yes. settings is a module referenced all over by Django (and probably your code too). Modifying any variable in settings is like modifying a global variable and alters the behaviour of your whole web app.
A:
Django settings are global. They affect the whole process.
A:
If you want 'per user' variables, I suggest you look at How to use sessions.
|
Modify Django settings variables in a middleware
|
I set a variable MAX_REQUEST = 100 in settings.py
I write a middleware which may lower this value for request origining from a proxy ip address by the following code:
settings.MAX_REQUEST = 10
However, looks like the above modification affects all legitimate users.
Is it normal?
|
[
"Yes. settings is a module referenced all over by Django (and probably your code too). Modifying any variable in settings is like modifying a global variable and alters the behaviour of your whole web app.\n",
"Django settings are global. They affect the whole process.\n",
"If you want 'per user' variables, I suggest you look at How to use sessions.\n"
] |
[
6,
0,
0
] |
[] |
[] |
[
"django",
"middleware",
"python",
"settings"
] |
stackoverflow_0002485274_django_middleware_python_settings.txt
|
Q:
Learning Python and trying to get first two letters and last two letters of a string
Here's my code:
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
if len(s) <= 2:
return ""
else:
return s[0] + s[1] + s[len(s)-2] + s[len(s-1)]
# +++your code here+++
return
Unfortunately my program doesn't run. :( I'm sure I'm overlooking something since I'm a newbie with Python.
Here's the error:
> Traceback (most recent call last):
File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 120, in <module>
main()
File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 97, in main
test(both_ends('spring'), 'spng')
File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 44, in both_ends
return s[0] + s[1] + s[len(s)-2] + s[len(s-1)]
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Thanks for the help guys. :D
A:
Misplaced parenthesis:
return s[0] + s[1] + s[len(s)-2] + s[len(s)-1]
By the way:
return s[0] + s[1] + s[-2] + s[-1]
or
return s[:2] + s[-2:]
A:
Your immediate problem is s[len(s-1)] instead of s[len(s)-1] .
You can probably simplify to s[:2] + s[-2:] as well.
A:
There is an error in the last part:
return s[0] + s[1] + s[len(s)-2] + s[len(s)-1]
You can think about rewriting it in a more pythonic way:
return s[0] + s[1] + s[-2] + s[-1]
|
Learning Python and trying to get first two letters and last two letters of a string
|
Here's my code:
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
if len(s) <= 2:
return ""
else:
return s[0] + s[1] + s[len(s)-2] + s[len(s-1)]
# +++your code here+++
return
Unfortunately my program doesn't run. :( I'm sure I'm overlooking something since I'm a newbie with Python.
Here's the error:
> Traceback (most recent call last):
File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 120, in <module>
main()
File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 97, in main
test(both_ends('spring'), 'spng')
File "C:\Users\Sergio\Desktop\google-python-exercises\google-python-exercises\basic\string1.py", line 44, in both_ends
return s[0] + s[1] + s[len(s)-2] + s[len(s-1)]
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Thanks for the help guys. :D
|
[
"Misplaced parenthesis:\nreturn s[0] + s[1] + s[len(s)-2] + s[len(s)-1]\n\nBy the way:\nreturn s[0] + s[1] + s[-2] + s[-1]\n\nor\nreturn s[:2] + s[-2:]\n\n",
"Your immediate problem is s[len(s-1)] instead of s[len(s)-1] .\nYou can probably simplify to s[:2] + s[-2:] as well.\n",
"There is an error in the last part:\nreturn s[0] + s[1] + s[len(s)-2] + s[len(s)-1]\n\nYou can think about rewriting it in a more pythonic way:\nreturn s[0] + s[1] + s[-2] + s[-1]\n\n"
] |
[
4,
4,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002485300_python.txt
|
Q:
Which implementation of OrderedDict should be used in python2.6?
As some of you may know in python2.7/3.2 we'll get OrderedDict with PEP372 however one of the reason the PEP existed was because everyone did their own implementation and they were all sightly incompatible.
So which one of the 8 current implementations in the PEP is backwards compatible with the 2.7 odict from python 2.7 in a way we can start using that now and depend on 2.7 in a couple of months?
A:
This package (for Python 2.4 or better) claims to be "A drop-in substitute for Py2.7's new collections.OrderedDict that works in Python 2.4-2.6.", but I have not checked that claim.
|
Which implementation of OrderedDict should be used in python2.6?
|
As some of you may know in python2.7/3.2 we'll get OrderedDict with PEP372 however one of the reason the PEP existed was because everyone did their own implementation and they were all sightly incompatible.
So which one of the 8 current implementations in the PEP is backwards compatible with the 2.7 odict from python 2.7 in a way we can start using that now and depend on 2.7 in a couple of months?
|
[
"This package (for Python 2.4 or better) claims to be \"A drop-in substitute for Py2.7's new collections.OrderedDict that works in Python 2.4-2.6.\", but I have not checked that claim.\n"
] |
[
3
] |
[] |
[] |
[
"dictionary",
"pep",
"python"
] |
stackoverflow_0002484046_dictionary_pep_python.txt
|
Q:
Python mistaking float for string
I receive
TypeError: Can't convert 'float' object to str implicitly
while using
Gambler.pot += round(self.bet + self.money * 0.1)
where pot, bet, and money are all doubles (or at least are supposed to be). I'm not sure if this is yet another Eclipse thing, but how do I get the line to compile?
Code where bet and money are initialized:
class Gambler:
money = 0
bet = 0
Test case:
number = 0
print("Here, the number is a {0}".format(type(number)))
number = input("Enter in something: ")
print("But now, it has turned into a {0}".format(type(number)))
Output from test case:
Here, the number is a <class 'int'>
Enter in something: 1
But now, it has turned into a <class 'str'>
Apparently, input() is changing it to a string.
EDIT: Finally fixed the problem (I think) with
self.bet = int(self.bet.strip())
after the user inputs the value. Though I dunno if that's the best way to fix the problem :)
A better solution by Daniel G.:
self.bet = float(input("How much would you like to bet? $"))
A:
input() in 3.x only returns strings. It is the programmer's job to pass it to a numeric constructor in order to turn it into a number.
A:
Are you initializing pot? Have you tried storing intermediate results to track down here the problem is coming from? And finally, do you know about pdb? That may be a big help.
class Gambler:
pot = 0.0
def __init__(self, money=0.0)
self.pot = 0.0
self.bet = 0.0
self.money = money
def update_pot(self):
import pdb; pdb.set_trace()
to_pot = self.bet + self.money * 0.1
to_pot = round(to_pot)
Gambler.pot = Gambler.pot + to_pot
You will get a prompt when the set_trace() line is executed. Try looking at the current values when you get there.
(Pdb) h # help
(Pdb) n # go to next statement
(Pdb) l # list source code
...
(Pdb) to_pot
...
(Pdb) self.bet
...
(Pdb) self.money
...
(Pdb) Gambler.pot
...
(Pdb) c # continue
A:
If any of Gambler.pot, self.bet or self.money have somehow become strings (because they were set to a string at some point), + will be taken to mean string concatenation which causes the error message you see.
A:
Python3.2 (py3k:77602) gives these error messages:
>>> "1.2" * 0.1 #1
Traceback (most recent call last):
File "", line 1, in
TypeError: can't multiply sequence by non-int of type 'float'
>>> "3.4" + 1.2 * 0.1 #2
Traceback (most recent call last):
File "", line 1, in
TypeError: Can't convert 'float' object to str implicitly
>>> n = "42"
>>> n += round(3.4 + 1.2 * 0.1) #3
Traceback (most recent call last):
File "", line 1, in
TypeError: Can't convert 'int' object to str implicitly
I suspect your error message is because one of your actual values is a string instead of the expected float in a scenario similar to #2, which is an exact match for your exception.
If you could write a test case, that would be a big help.
Remember that Py3.x's input is identical to Py2.x's raw_input, and Py2.x's input is gone (it's equivalent to using evai, which you don't want to do). Because of this, input in 3.x will always return a string. Use int to convert:
n = int(input("Enter a number: "))
If you want to handle input errors, then catch ValueError, which is what int raises on errors:
try:
n = int(input("Enter a number: "))
except ValueError:
print("invalid input")
else:
print("squared:", n*n)
A:
In Python 3.x, input() replaces Python 2.x's raw_input(). Therefore, the function input() returns the exact string that the user input (as raw_input() did in previous versions).
To get Python 2.x behavior, you can just do
number = eval(input("Please enter a number: "))
However, I wouldn't recommend using "eval" since the user can put any line of Python they want in there, which is probably not what you want. If you know you want a float, just tell Python that's what you want:
number = float(input("Please enter a number: "))
A:
As was said in a comment, what you've shown is initializing local variables to 0. Instead try something like:
class Gambler:
def __init__(self):
self.bet = 0.0
self.money = 0.0
def calc_pot(self):
self.pot = round(self.bet + self.money * 0.1)
g = Gambler()
g.bet = 2.0
g.money = 5.0
g.calc_pot()
print "Pot = %f" % (g.pot)
Also, make sure there's nothing that might be turning those members into strings.
|
Python mistaking float for string
|
I receive
TypeError: Can't convert 'float' object to str implicitly
while using
Gambler.pot += round(self.bet + self.money * 0.1)
where pot, bet, and money are all doubles (or at least are supposed to be). I'm not sure if this is yet another Eclipse thing, but how do I get the line to compile?
Code where bet and money are initialized:
class Gambler:
money = 0
bet = 0
Test case:
number = 0
print("Here, the number is a {0}".format(type(number)))
number = input("Enter in something: ")
print("But now, it has turned into a {0}".format(type(number)))
Output from test case:
Here, the number is a <class 'int'>
Enter in something: 1
But now, it has turned into a <class 'str'>
Apparently, input() is changing it to a string.
EDIT: Finally fixed the problem (I think) with
self.bet = int(self.bet.strip())
after the user inputs the value. Though I dunno if that's the best way to fix the problem :)
A better solution by Daniel G.:
self.bet = float(input("How much would you like to bet? $"))
|
[
"input() in 3.x only returns strings. It is the programmer's job to pass it to a numeric constructor in order to turn it into a number.\n",
"Are you initializing pot? Have you tried storing intermediate results to track down here the problem is coming from? And finally, do you know about pdb? That may be a big help.\nclass Gambler:\n pot = 0.0\n def __init__(self, money=0.0)\n self.pot = 0.0\n self.bet = 0.0\n self.money = money\n\n def update_pot(self):\n import pdb; pdb.set_trace()\n to_pot = self.bet + self.money * 0.1\n to_pot = round(to_pot)\n Gambler.pot = Gambler.pot + to_pot\n\nYou will get a prompt when the set_trace() line is executed. Try looking at the current values when you get there.\n(Pdb) h # help\n(Pdb) n # go to next statement\n(Pdb) l # list source code\n...\n(Pdb) to_pot\n...\n(Pdb) self.bet\n...\n(Pdb) self.money\n...\n(Pdb) Gambler.pot\n...\n(Pdb) c # continue\n\n",
"If any of Gambler.pot, self.bet or self.money have somehow become strings (because they were set to a string at some point), + will be taken to mean string concatenation which causes the error message you see. \n",
"Python3.2 (py3k:77602) gives these error messages:\n\n>>> \"1.2\" * 0.1 #1\nTraceback (most recent call last):\n File \"\", line 1, in \nTypeError: can't multiply sequence by non-int of type 'float'\n>>> \"3.4\" + 1.2 * 0.1 #2\nTraceback (most recent call last):\n File \"\", line 1, in \nTypeError: Can't convert 'float' object to str implicitly\n>>> n = \"42\"\n>>> n += round(3.4 + 1.2 * 0.1) #3\nTraceback (most recent call last):\n File \"\", line 1, in \nTypeError: Can't convert 'int' object to str implicitly\n\nI suspect your error message is because one of your actual values is a string instead of the expected float in a scenario similar to #2, which is an exact match for your exception.\nIf you could write a test case, that would be a big help.\n\nRemember that Py3.x's input is identical to Py2.x's raw_input, and Py2.x's input is gone (it's equivalent to using evai, which you don't want to do). Because of this, input in 3.x will always return a string. Use int to convert:\nn = int(input(\"Enter a number: \"))\n\nIf you want to handle input errors, then catch ValueError, which is what int raises on errors:\ntry:\n n = int(input(\"Enter a number: \"))\nexcept ValueError:\n print(\"invalid input\")\nelse:\n print(\"squared:\", n*n)\n\n",
"In Python 3.x, input() replaces Python 2.x's raw_input(). Therefore, the function input() returns the exact string that the user input (as raw_input() did in previous versions).\nTo get Python 2.x behavior, you can just do\nnumber = eval(input(\"Please enter a number: \"))\n\nHowever, I wouldn't recommend using \"eval\" since the user can put any line of Python they want in there, which is probably not what you want. If you know you want a float, just tell Python that's what you want:\nnumber = float(input(\"Please enter a number: \"))\n\n",
"As was said in a comment, what you've shown is initializing local variables to 0. Instead try something like:\nclass Gambler:\n def __init__(self):\n self.bet = 0.0\n self.money = 0.0\n\n def calc_pot(self):\n self.pot = round(self.bet + self.money * 0.1)\n\ng = Gambler()\ng.bet = 2.0\ng.money = 5.0\ng.calc_pot()\n\nprint \"Pot = %f\" % (g.pot)\n\nAlso, make sure there's nothing that might be turning those members into strings.\n"
] |
[
6,
4,
3,
3,
2,
0
] |
[] |
[] |
[
"floating_point",
"python",
"python_3.x",
"string"
] |
stackoverflow_0002485521_floating_point_python_python_3.x_string.txt
|
Q:
Django model: Reference foreign key table in __unicode__ function for admin
Example models:
class Parent(models.Model):
name = models.CharField()
def __unicode__(self):
return self.name
class Child(models.Model):
parent = models.ForeignKey(Parent)
def __unicode__(self):
return self.parent.name # Would reference name above
I'm wanting the Child.unicode to refer to Parent.name, mostly for the admin section so I don't end up with "Child object" or similar, I'd prefer to display it more like "Child of ". Is this possible? Most of what I've tried hasn't worked unfortunately.
A:
return u'Child of %s' % unicode(self.parent)
Obviously you've defined a __unicode__() method in the parent that makes sense, right?
|
Django model: Reference foreign key table in __unicode__ function for admin
|
Example models:
class Parent(models.Model):
name = models.CharField()
def __unicode__(self):
return self.name
class Child(models.Model):
parent = models.ForeignKey(Parent)
def __unicode__(self):
return self.parent.name # Would reference name above
I'm wanting the Child.unicode to refer to Parent.name, mostly for the admin section so I don't end up with "Child object" or similar, I'd prefer to display it more like "Child of ". Is this possible? Most of what I've tried hasn't worked unfortunately.
|
[
"return u'Child of %s' % unicode(self.parent)\n\nObviously you've defined a __unicode__() method in the parent that makes sense, right?\n"
] |
[
3
] |
[] |
[] |
[
"admin",
"django",
"python"
] |
stackoverflow_0002485766_admin_django_python.txt
|
Q:
Clever way of building a tag cloud? - Python
I've built a content aggregator and would like to add a tag cloud representing the current trends.
Unfortunately this is quite complex, as I have to look for keywords that represent the context of each article.
For example words such as I, was, the, amazing, nice have no relation to context.
Help would be much appreciated! :)
A:
Use NLTK, and in particular its Stopwords corpus:
Besides regular content words, there
is another class of words called stop
words that perform important
grammatical functions, but are
unlikely to be interesting by
themselves. These include
prepositions, complementizers, and
determiners. NLTK comes bundled with
the Stopwords corpus, a list of 2400
stop words across 11 different
languages (including English).
A:
NLTK can help you analyze the content in order to pick out relevant terms.
|
Clever way of building a tag cloud? - Python
|
I've built a content aggregator and would like to add a tag cloud representing the current trends.
Unfortunately this is quite complex, as I have to look for keywords that represent the context of each article.
For example words such as I, was, the, amazing, nice have no relation to context.
Help would be much appreciated! :)
|
[
"Use NLTK, and in particular its Stopwords corpus:\n\nBesides regular content words, there\n is another class of words called stop\n words that perform important\n grammatical functions, but are\n unlikely to be interesting by\n themselves. These include\n prepositions, complementizers, and\n determiners. NLTK comes bundled with\n the Stopwords corpus, a list of 2400\n stop words across 11 different\n languages (including English).\n\n",
"NLTK can help you analyze the content in order to pick out relevant terms.\n"
] |
[
9,
2
] |
[] |
[] |
[
"data_mining",
"django",
"indexing",
"keyword",
"python"
] |
stackoverflow_0002485800_data_mining_django_indexing_keyword_python.txt
|
Q:
very quickly getting total size of folder
I want to quickly find the total size of any folder using python.
import os
from os.path import join, getsize, isfile, isdir, splitext
def GetFolderSize(path):
TotalSize = 0
for item in os.walk(path):
for file in item[2]:
try:
TotalSize = TotalSize + getsize(join(item[0], file))
except:
print("error with file: " + join(item[0], file))
return TotalSize
print(float(GetFolderSize("C:\\")) /1024 /1024 /1024)
That's the simple script I wrote to get the total size of the folder, it took around 60 seconds (+-5 seconds). By using multiprocessing I got it down to 23 seconds on a quad core machine.
Using the Windows file explorer it takes only ~3 seconds (Right click-> properties to see for yourself). So is there a faster way of finding the total size of a folder close to the speed that windows can do it?
Windows 7, python 2.6 (Did searches but most of the time people used a very similar method to my own)
Thanks in advance.
A:
You are at a disadvantage.
Windows Explorer almost certainly uses FindFirstFile/FindNextFile to both traverse the directory structure and collect size information (through lpFindFileData) in one pass, making what is essentially a single system call per file.
Python is unfortunately not your friend in this case. Thus,
os.walk first calls os.listdir (which internally calls FindFirstFile/FindNextFile)
any additional system calls made from this point onward can only make you slower than Windows Explorer
os.walk then calls isdir for each file returned by os.listdir (which internally calls GetFileAttributesEx -- or, prior to Win2k, a GetFileAttributes+FindFirstFile combo) to redetermine whether to recurse or not
os.walk and os.listdir will perform additional memory allocation, string and array operations etc. to fill out their return value
you then call getsize for each file returned by os.walk (which again calls GetFileAttributesEx)
That is 3x more system calls per file than Windows Explorer, plus memory allocation and manipulation overhead.
You can either use Anurag's solution, or try to call FindFirstFile/FindNextFile directly and recursively (which should be comparable to the performance of a cygwin or other win32 port du -s some_directory.)
Refer to os.py for the implementation of os.walk, posixmodule.c for the implementation of listdir and win32_stat (invoked by both isdir and getsize.)
Note that Python's os.walk is suboptimal on all platforms (Windows and *nices), up to and including Python3.1. On both Windows and *nices os.walk could achieve traversal in a single pass without calling isdir since both FindFirst/FindNext (Windows) and opendir/readdir (*nix) already return file type via lpFindFileData->dwFileAttributes (Windows) and dirent::d_type (*nix).
Perhaps counterintuitively, on most modern configurations (e.g. Win7 and NTFS, and even some SMB implementations) GetFileAttributesEx is twice as slow as FindFirstFile of a single file (possibly even slower than iterating over a directory with FindNextFile.)
Update: Python 3.5 includes the new PEP 471 os.scandir() function that solves this problem by returning file attributes along with the filename. This new function is used to speed up the built-in os.walk() (on both Windows and Linux). You can use the scandir module on PyPI to get this behavior for older Python versions, including 2.x.
A:
If you want same speed as explorer, why not use the windows scripting to access same functionality using pythoncom e.g.
import win32com.client as com
folderPath = r"D:\Software\Downloads"
fso = com.Dispatch("Scripting.FileSystemObject")
folder = fso.GetFolder(folderPath)
MB = 1024 * 1024.0
print("%.2f MB" % (folder.Size / MB))
It will work same as explorer, you can read more about Scripting runtime at http://msdn.microsoft.com/en-us/library/bstcxhf7(VS.85).aspx.
A:
I compared the performance of the Python code against a 15k directory tree containing 190k files and compared it against the du(1) command which presumably goes about as fast as the OS. The Python code took 3.3 seconds compared to du which took 0.8 seconds. This was on Linux.
I'm not sure there is much to squeeze out of the Python code. Note too that the first run of du took 45 seconds which was obviously before the relevant i-nodes were in the block cache; therefore this performance is heavily dependent upon how well the system is managing its store. It wouldn't surprise me if either or both:
os.path.getsize is sub-optimal on Windows
Windows caches directory contents size once calculated
|
very quickly getting total size of folder
|
I want to quickly find the total size of any folder using python.
import os
from os.path import join, getsize, isfile, isdir, splitext
def GetFolderSize(path):
TotalSize = 0
for item in os.walk(path):
for file in item[2]:
try:
TotalSize = TotalSize + getsize(join(item[0], file))
except:
print("error with file: " + join(item[0], file))
return TotalSize
print(float(GetFolderSize("C:\\")) /1024 /1024 /1024)
That's the simple script I wrote to get the total size of the folder, it took around 60 seconds (+-5 seconds). By using multiprocessing I got it down to 23 seconds on a quad core machine.
Using the Windows file explorer it takes only ~3 seconds (Right click-> properties to see for yourself). So is there a faster way of finding the total size of a folder close to the speed that windows can do it?
Windows 7, python 2.6 (Did searches but most of the time people used a very similar method to my own)
Thanks in advance.
|
[
"You are at a disadvantage.\nWindows Explorer almost certainly uses FindFirstFile/FindNextFile to both traverse the directory structure and collect size information (through lpFindFileData) in one pass, making what is essentially a single system call per file.\nPython is unfortunately not your friend in this case. Thus,\n\nos.walk first calls os.listdir (which internally calls FindFirstFile/FindNextFile)\n\n\nany additional system calls made from this point onward can only make you slower than Windows Explorer\n\nos.walk then calls isdir for each file returned by os.listdir (which internally calls GetFileAttributesEx -- or, prior to Win2k, a GetFileAttributes+FindFirstFile combo) to redetermine whether to recurse or not\nos.walk and os.listdir will perform additional memory allocation, string and array operations etc. to fill out their return value\nyou then call getsize for each file returned by os.walk (which again calls GetFileAttributesEx)\n\nThat is 3x more system calls per file than Windows Explorer, plus memory allocation and manipulation overhead.\nYou can either use Anurag's solution, or try to call FindFirstFile/FindNextFile directly and recursively (which should be comparable to the performance of a cygwin or other win32 port du -s some_directory.)\nRefer to os.py for the implementation of os.walk, posixmodule.c for the implementation of listdir and win32_stat (invoked by both isdir and getsize.)\nNote that Python's os.walk is suboptimal on all platforms (Windows and *nices), up to and including Python3.1. On both Windows and *nices os.walk could achieve traversal in a single pass without calling isdir since both FindFirst/FindNext (Windows) and opendir/readdir (*nix) already return file type via lpFindFileData->dwFileAttributes (Windows) and dirent::d_type (*nix). \nPerhaps counterintuitively, on most modern configurations (e.g. Win7 and NTFS, and even some SMB implementations) GetFileAttributesEx is twice as slow as FindFirstFile of a single file (possibly even slower than iterating over a directory with FindNextFile.)\nUpdate: Python 3.5 includes the new PEP 471 os.scandir() function that solves this problem by returning file attributes along with the filename. This new function is used to speed up the built-in os.walk() (on both Windows and Linux). You can use the scandir module on PyPI to get this behavior for older Python versions, including 2.x.\n",
"If you want same speed as explorer, why not use the windows scripting to access same functionality using pythoncom e.g.\nimport win32com.client as com\n\nfolderPath = r\"D:\\Software\\Downloads\"\nfso = com.Dispatch(\"Scripting.FileSystemObject\")\nfolder = fso.GetFolder(folderPath)\nMB = 1024 * 1024.0\nprint(\"%.2f MB\" % (folder.Size / MB))\n\nIt will work same as explorer, you can read more about Scripting runtime at http://msdn.microsoft.com/en-us/library/bstcxhf7(VS.85).aspx.\n",
"I compared the performance of the Python code against a 15k directory tree containing 190k files and compared it against the du(1) command which presumably goes about as fast as the OS. The Python code took 3.3 seconds compared to du which took 0.8 seconds. This was on Linux.\nI'm not sure there is much to squeeze out of the Python code. Note too that the first run of du took 45 seconds which was obviously before the relevant i-nodes were in the block cache; therefore this performance is heavily dependent upon how well the system is managing its store. It wouldn't surprise me if either or both:\n\nos.path.getsize is sub-optimal on Windows\nWindows caches directory contents size once calculated\n\n"
] |
[
82,
22,
5
] |
[] |
[] |
[
"directory",
"optimization",
"python"
] |
stackoverflow_0002485719_directory_optimization_python.txt
|
Q:
How to import modules that are used in both the main code and a module correctly?
Let's assume I have a main script, main.py, that imports another python file with import coolfunctions and another: import chores
Now, suppose coolfunctions also uses stuff from chores, hence I declare import chores inside coolfunctions.
Since both main.py, and coolfunctions import chores ~ is this redundant? Is there any other way of doing this? Am I doing it correctly?
I'm confused about how python projects should be structured in general. I have a "conf.py" file, that I import for a bunch of variables ~ is this a module or not? I load this conf file in multiple places as well.
A:
If two modules want to use chores, then each one must import chores (or some equivalent import). Each import creates a name binding only in the namespace of the module that does the import; that is, import's namespace effect is local to a module's namespace.
This is good, because by looking at a module's code you can (barring pathological cases) know where each name is bound to by the import statements that explicitly bind modules or module attributes to names. Imports made in other modules won't affect this module's namespace.
A:
No, this isn't redundant - it's fine to import chores in both the main module and coolfunctions.
The exact import mechanics of Python are complex (for example, module imports are only done once, meaning in your case that the actual parsing and loading of the chores module will only happen once, which is a nice optimization) but in general you shouldn't worry about it because it just works.
Each Python file is a module, so your conf.py is also a module.
A:
Each module X should import all (and only) the modules Y, Z, T, ... whose functionality it requires, without any worry about what other modules Fee, Fie, Foo ... (if any) may have already done part or all of those imports, or may be going to do so in the future.
It would make a module extremely fragile (indeed, it would be the very opposite of modularity!) if each module had to worry about such subtle, "covert-channel" effects.
What other modules Y, Z, T, ..., each module X chooses to import (if any) is part of X's implementation details, and shouldn't concern anybody except the developers who are coding, testing, or maintaining X.
In order to ensure that this is the case, and that this clearly-best strategy of decoupling can and will fully be followed by sane code, Python "caches" modules as they get imported: a module is "loaded" only once per run of a program, the first time anybody imports it (or anything from inside it) -- all other imports use the same object obtained by that first loading, which Python keeps in a cache (which is specified as being the dict sys.modules, but you need to know that detail only for somewhat-advanced programming techniques... don't worry about it, 98.7% of the time -- just remember that "import is cheap"!-).
Sure, a conf.py that you use from several other modules via import conf is definitely a module (you may think you're loading it multiple times, but you aren't unless you're using pretty advanced and deliberate techniques indeed for the purpose) -- why shouldn't it be?
A:
It is always the best practice to import all necessary modules in the file that uses them. Take for example:
A.py contains: import coolfunctions
B.py contains: import A
Main.py contains: import B and uses functions that are defined in A.py (this is possible because by importing B, Main.py has imported everything that B imports)
If in the future, you change B.py to function without needing to import A.py and therefore remove the import A, then your Main.py will suffer the loss of not having imported A.
|
How to import modules that are used in both the main code and a module correctly?
|
Let's assume I have a main script, main.py, that imports another python file with import coolfunctions and another: import chores
Now, suppose coolfunctions also uses stuff from chores, hence I declare import chores inside coolfunctions.
Since both main.py, and coolfunctions import chores ~ is this redundant? Is there any other way of doing this? Am I doing it correctly?
I'm confused about how python projects should be structured in general. I have a "conf.py" file, that I import for a bunch of variables ~ is this a module or not? I load this conf file in multiple places as well.
|
[
"If two modules want to use chores, then each one must import chores (or some equivalent import). Each import creates a name binding only in the namespace of the module that does the import; that is, import's namespace effect is local to a module's namespace.\nThis is good, because by looking at a module's code you can (barring pathological cases) know where each name is bound to by the import statements that explicitly bind modules or module attributes to names. Imports made in other modules won't affect this module's namespace.\n",
"No, this isn't redundant - it's fine to import chores in both the main module and coolfunctions.\nThe exact import mechanics of Python are complex (for example, module imports are only done once, meaning in your case that the actual parsing and loading of the chores module will only happen once, which is a nice optimization) but in general you shouldn't worry about it because it just works.\nEach Python file is a module, so your conf.py is also a module. \n",
"Each module X should import all (and only) the modules Y, Z, T, ... whose functionality it requires, without any worry about what other modules Fee, Fie, Foo ... (if any) may have already done part or all of those imports, or may be going to do so in the future.\nIt would make a module extremely fragile (indeed, it would be the very opposite of modularity!) if each module had to worry about such subtle, \"covert-channel\" effects.\nWhat other modules Y, Z, T, ..., each module X chooses to import (if any) is part of X's implementation details, and shouldn't concern anybody except the developers who are coding, testing, or maintaining X.\nIn order to ensure that this is the case, and that this clearly-best strategy of decoupling can and will fully be followed by sane code, Python \"caches\" modules as they get imported: a module is \"loaded\" only once per run of a program, the first time anybody imports it (or anything from inside it) -- all other imports use the same object obtained by that first loading, which Python keeps in a cache (which is specified as being the dict sys.modules, but you need to know that detail only for somewhat-advanced programming techniques... don't worry about it, 98.7% of the time -- just remember that \"import is cheap\"!-).\nSure, a conf.py that you use from several other modules via import conf is definitely a module (you may think you're loading it multiple times, but you aren't unless you're using pretty advanced and deliberate techniques indeed for the purpose) -- why shouldn't it be?\n",
"It is always the best practice to import all necessary modules in the file that uses them. Take for example:\nA.py contains: import coolfunctions\nB.py contains: import A\nMain.py contains: import B and uses functions that are defined in A.py (this is possible because by importing B, Main.py has imported everything that B imports)\nIf in the future, you change B.py to function without needing to import A.py and therefore remove the import A, then your Main.py will suffer the loss of not having imported A.\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"file",
"import",
"module",
"python"
] |
stackoverflow_0002485901_file_import_module_python.txt
|
Q:
Calling gawk from Python
I am trying to call gawk (the GNU implementation of AWK) from Python in this manner.
import os
import string
import codecs
ligand_file=open( "2WTKA_ab.txt", "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( string.strip, ligand_lines )
ligand_file.close()
for i in ligand_lines:
os.system ( " gawk %s %s"%( "'{if ($2==""i"") print $0}'", 'unique_count_a_from_ac.txt' ) )
My problem is that "i" is not being replaced by the value it represent. The value "i" represents is an integer and not a string. How can I fix this problem?
A:
That's a non-portable and messy way to check if something is in a file. Imagine you have 1000 lines, you will be making system call to gawk 1000 times. It's super inefficient. You are using Python, so do them in Python.
....
ligand_file=open( "2WTKA_ab.txt", "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( str.strip, ligand_lines )
ligand_file.close()
for line in open("unique_count_a_from_ac.txt"):
sline=line.strip().split()
if sline[1] in ligand_lines:
print line.rstrip()
Or you can also use this one liner if Python is not a must.
gawk 'FNR==NR{a[$0]; next}($2 in a)' 2WTKA_ab.txt unique_count_a_from_ac.txt
A:
Your problem is in the quoting, in python something like "some test "" with quotes" will not give you a quote. Try this instead:
os.system('''gawk '{if ($2=="%s") print $0}' unique_count_a_from_ac.txt''' % i)
|
Calling gawk from Python
|
I am trying to call gawk (the GNU implementation of AWK) from Python in this manner.
import os
import string
import codecs
ligand_file=open( "2WTKA_ab.txt", "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( string.strip, ligand_lines )
ligand_file.close()
for i in ligand_lines:
os.system ( " gawk %s %s"%( "'{if ($2==""i"") print $0}'", 'unique_count_a_from_ac.txt' ) )
My problem is that "i" is not being replaced by the value it represent. The value "i" represents is an integer and not a string. How can I fix this problem?
|
[
"That's a non-portable and messy way to check if something is in a file. Imagine you have 1000 lines, you will be making system call to gawk 1000 times. It's super inefficient. You are using Python, so do them in Python. \n....\nligand_file=open( \"2WTKA_ab.txt\", \"r\" ) #Open the receptor.txt file\nligand_lines=ligand_file.readlines() # Read all the lines into the array\nligand_lines=map( str.strip, ligand_lines ) \nligand_file.close()\nfor line in open(\"unique_count_a_from_ac.txt\"):\n sline=line.strip().split()\n if sline[1] in ligand_lines:\n print line.rstrip()\n\nOr you can also use this one liner if Python is not a must.\ngawk 'FNR==NR{a[$0]; next}($2 in a)' 2WTKA_ab.txt unique_count_a_from_ac.txt\n\n",
"Your problem is in the quoting, in python something like \"some test \"\" with quotes\" will not give you a quote. Try this instead:\nos.system('''gawk '{if ($2==\"%s\") print $0}' unique_count_a_from_ac.txt''' % i)\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"gawk",
"python"
] |
stackoverflow_0002485362_gawk_python.txt
|
Q:
Python: Script works, but seems to deadlock after some time
I have the following script, which is working for the most part Link to PasteBin The script's job is to start a number of threads which in turn each start a subprocess with Popen. The output from each subprocess is as follows:
1
2
3
.
.
.
n
Done
Bascially the subprocess is transferring 10M records from tables in one database to different tables in another db with a lot of data massaging/manipulation in between because of the different schemas. If the subprocess fails at any time in it's execution (bad records, duplicate primary keys, etc), or it completes successfully, it will output "Done\n". If there are no more records to select against for transfer then it will output "NO DATA\n"
My intent was to create my script "tableTransfer.py" which would spawn a number of these processes, read their output, and in turn output information such as number of updates completed, time remaining, time elapsed, and number of transfers per second.
I started running the process last night and checked in this morning to see it had deadlocked. There were not subprocceses running, there are still records to be updated, and the script had not exited. It was simply sitting there, no longer outputting the current information because no subprocces were running to update the total number complete which is what controls updates to the output. This is running on OS X.
I am looking for three things:
I would like to get rid of the possibility of this deadlock occurring so I don't need to check in on it as frequently. Is there some issue with locking?
Am I doing this in a bad way (gThreading variable to control looping of spawning additional thread... etc.) I would appreciate some suggestions for improving my overall methodology.
How should I handle ctrl-c exit? Right now I need to kill the process, but assume I should be able to use the signal module or other to catch the signal and kill the threads, is that right?
I am not sure whether I should be pasting my entire script here, since I usually just paste snippets. Let me know if I should paste it here as well.
A:
You have a few places in your script where you return without releasing your locks. This could cause a problem - lines: 97 and 99 - this is where try: finally: blocks can help you a lot as you can then ensure that the release is called properly.
|
Python: Script works, but seems to deadlock after some time
|
I have the following script, which is working for the most part Link to PasteBin The script's job is to start a number of threads which in turn each start a subprocess with Popen. The output from each subprocess is as follows:
1
2
3
.
.
.
n
Done
Bascially the subprocess is transferring 10M records from tables in one database to different tables in another db with a lot of data massaging/manipulation in between because of the different schemas. If the subprocess fails at any time in it's execution (bad records, duplicate primary keys, etc), or it completes successfully, it will output "Done\n". If there are no more records to select against for transfer then it will output "NO DATA\n"
My intent was to create my script "tableTransfer.py" which would spawn a number of these processes, read their output, and in turn output information such as number of updates completed, time remaining, time elapsed, and number of transfers per second.
I started running the process last night and checked in this morning to see it had deadlocked. There were not subprocceses running, there are still records to be updated, and the script had not exited. It was simply sitting there, no longer outputting the current information because no subprocces were running to update the total number complete which is what controls updates to the output. This is running on OS X.
I am looking for three things:
I would like to get rid of the possibility of this deadlock occurring so I don't need to check in on it as frequently. Is there some issue with locking?
Am I doing this in a bad way (gThreading variable to control looping of spawning additional thread... etc.) I would appreciate some suggestions for improving my overall methodology.
How should I handle ctrl-c exit? Right now I need to kill the process, but assume I should be able to use the signal module or other to catch the signal and kill the threads, is that right?
I am not sure whether I should be pasting my entire script here, since I usually just paste snippets. Let me know if I should paste it here as well.
|
[
"You have a few places in your script where you return without releasing your locks. This could cause a problem - lines: 97 and 99 - this is where try: finally: blocks can help you a lot as you can then ensure that the release is called properly.\n"
] |
[
0
] |
[] |
[] |
[
"multithreading",
"python",
"signals",
"subprocess"
] |
stackoverflow_0002483840_multithreading_python_signals_subprocess.txt
|
Q:
How to display a QGraphicsScene?
I've got the following code and I'm not sure how to add the QGraphicsScene to my layout..
class MainForm(QDialog):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.scene = QGraphicsScene(self)
self.scene.setSceneRect(0, 0, 500, 500)
self.view = QGraphicsView()
self.view.setRenderHint(QPainter.Antialiasing)
self.view.setScene(self.scene)
self.view.setFocusPolicy(Qt.NoFocus)
zoomSlider = QSlider(Qt.Horizontal)
zoomSlider.setRange(5, 200)
zoomSlider.setValue(100)
self.pauseButton = QPushButton("Pause")
quitButton = QPushButton("Quit")
layout = QVBoxLayout()
layout.addWidget(zoomSlider)
self.setLayout(layout)
self.startTimer(10)
How can I get my QGraphicsScene running? I'm new to Qt. Am I even supposed to be adding a QGraphicsScene to a layout/
A:
You'll have to do something like this:
...
layout = QVBoxLayout()
layout.addWidget(zoomSlider)
layout.addWidget(view)
self.setLayout(layout)
...
A:
You have added a scene to view, and it's enough. But you should add the view to your MainForm and Layout. View is a kind of widget that can be displayed by your application, while scene is not a widget and cannot be added to layout, it's a component of view. In addition, you may need to add some graphics items(e.g. rectangle, image) to scene and see how it works.
|
How to display a QGraphicsScene?
|
I've got the following code and I'm not sure how to add the QGraphicsScene to my layout..
class MainForm(QDialog):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.scene = QGraphicsScene(self)
self.scene.setSceneRect(0, 0, 500, 500)
self.view = QGraphicsView()
self.view.setRenderHint(QPainter.Antialiasing)
self.view.setScene(self.scene)
self.view.setFocusPolicy(Qt.NoFocus)
zoomSlider = QSlider(Qt.Horizontal)
zoomSlider.setRange(5, 200)
zoomSlider.setValue(100)
self.pauseButton = QPushButton("Pause")
quitButton = QPushButton("Quit")
layout = QVBoxLayout()
layout.addWidget(zoomSlider)
self.setLayout(layout)
self.startTimer(10)
How can I get my QGraphicsScene running? I'm new to Qt. Am I even supposed to be adding a QGraphicsScene to a layout/
|
[
"You'll have to do something like this:\n...\nlayout = QVBoxLayout()\nlayout.addWidget(zoomSlider)\nlayout.addWidget(view)\nself.setLayout(layout)\n...\n\n",
"You have added a scene to view, and it's enough. But you should add the view to your MainForm and Layout. View is a kind of widget that can be displayed by your application, while scene is not a widget and cannot be added to layout, it's a component of view. In addition, you may need to add some graphics items(e.g. rectangle, image) to scene and see how it works.\n"
] |
[
2,
0
] |
[] |
[] |
[
"pyqt",
"python",
"qt"
] |
stackoverflow_0002484461_pyqt_python_qt.txt
|
Q:
How to get Eclipse + PyDev + App Engine + Unit testing to work?
I want to run my unit tests for a Python Google App Engine project using
Run As => Python unit-test
But when I try that all my Model tests bail with the error message:
BadArgumentError: app must not be empty.
Anyone got this to work?
NB: The tests runs fine using Nose --with-gae. But I want the PyDev integration with hyperlinking of resources and such.
A:
Pasting the answer I got from the Fabioz (the PyDev creator) himself over at the PyDev forums on SF: https://sourceforge.net/projects/pydev/forums/forum/293649/topic/3618848
There's no such option right now... please enter a feature request for that. Note that you can run nose itself from inside of pydev (with the --with-gae option) -- which at least would give you hyperlinking inside of pydev -- to do that just create a custom run where nose is the main script.
Indeed, that's what I did and it works as advertised. I also entered that feature request. You can help by pushing your support behind the request: https://sourceforge.net/tracker/?func=detail&aid=2974043&group_id=85796&atid=577332
|
How to get Eclipse + PyDev + App Engine + Unit testing to work?
|
I want to run my unit tests for a Python Google App Engine project using
Run As => Python unit-test
But when I try that all my Model tests bail with the error message:
BadArgumentError: app must not be empty.
Anyone got this to work?
NB: The tests runs fine using Nose --with-gae. But I want the PyDev integration with hyperlinking of resources and such.
|
[
"Pasting the answer I got from the Fabioz (the PyDev creator) himself over at the PyDev forums on SF: https://sourceforge.net/projects/pydev/forums/forum/293649/topic/3618848\n\nThere's no such option right now... please enter a feature request for that. Note that you can run nose itself from inside of pydev (with the --with-gae option) -- which at least would give you hyperlinking inside of pydev -- to do that just create a custom run where nose is the main script.\n\nIndeed, that's what I did and it works as advertised. I also entered that feature request. You can help by pushing your support behind the request: https://sourceforge.net/tracker/?func=detail&aid=2974043&group_id=85796&atid=577332\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"pydev",
"python",
"unit_testing"
] |
stackoverflow_0002473467_google_app_engine_pydev_python_unit_testing.txt
|
Q:
Convert python script to binary executable
I wrote a number crunching python code. The calculations involved can take hours. Is it possible somehow to compile it to binary?
Thanks
A:
Not in any useful (for you) way, but moving the calculations into NumPy or Cython will speed them up.
A:
First you can try psyco, that may give you a speed up as much as 10x, but 2x is more typical
If you can post the code up somewhere, perhaps someone can point out how to leverage numpy.
If your task doesn't map well only numpy then cython is a good choice to convert a intensive function or two into C code just by adding a few cdefs.
If you can show us the code (even just the hot spots) we can probably give you better advice.
Perhaps you can modify your algorithm
A:
Shedskin might be worth a try.
From their front page blurb:
Shed Skin is an experimental compiler,
that can translate pure, but
implicitly statically typed Python
programs into optimized C++. It can
generate stand-alone programs or
extension modules that can be imported
and used in larger Python programs.
Besides the typing restriction,
programs cannot freely use the Python
standard library (although about 20
common modules, such as random and re,
are currently supported). Also, not
all Python features, such as nested
functions and variable numbers of
arguments, are supported (see the
tutorial for details).
For a set of 44 non-trivial test
programs (at over 10,000 lines in
total (sloccount)), measurements show
a typical speedup of 2-40 times over
Psyco, and 2-220 times over CPython.
Because Shed Skin is still in an early
stage of development, however, many
other programs will not compile
out-of-the-box.
|
Convert python script to binary executable
|
I wrote a number crunching python code. The calculations involved can take hours. Is it possible somehow to compile it to binary?
Thanks
|
[
"Not in any useful (for you) way, but moving the calculations into NumPy or Cython will speed them up.\n",
"First you can try psyco, that may give you a speed up as much as 10x, but 2x is more typical\nIf you can post the code up somewhere, perhaps someone can point out how to leverage numpy.\nIf your task doesn't map well only numpy then cython is a good choice to convert a intensive function or two into C code just by adding a few cdefs.\nIf you can show us the code (even just the hot spots) we can probably give you better advice.\nPerhaps you can modify your algorithm\n",
"Shedskin might be worth a try.\nFrom their front page blurb:\n\nShed Skin is an experimental compiler,\n that can translate pure, but\n implicitly statically typed Python\n programs into optimized C++. It can\n generate stand-alone programs or\n extension modules that can be imported\n and used in larger Python programs.\nBesides the typing restriction,\n programs cannot freely use the Python\n standard library (although about 20\n common modules, such as random and re,\n are currently supported). Also, not\n all Python features, such as nested\n functions and variable numbers of\n arguments, are supported (see the\n tutorial for details).\nFor a set of 44 non-trivial test\n programs (at over 10,000 lines in\n total (sloccount)), measurements show\n a typical speedup of 2-40 times over\n Psyco, and 2-220 times over CPython.\n Because Shed Skin is still in an early\n stage of development, however, many\n other programs will not compile\n out-of-the-box.\n\n"
] |
[
5,
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002486737_python.txt
|
Q:
Need help with re for matching and getting the value python
Need help regarding re.
file = 'file No.WR79050107006 from files'
So what I am trying to do is validate if file string contains WR + 11 digit.
result = re.match('^(\S| )*(?P<sr>(\d){11})(\S| )*', file)
Its validate only 11 digit but not WR before it.
How can I do that?
Using re after matching how can I get the match value ( WR79050107006)
I can do string find
index = file.find('file No.')
and then get the value of next 13 char.
thanks
A:
If by "validate if file string contains WR + 11 digit" you mean "exactly 11, not 12+",
mo = re.search(r'WR(\d{11})(\D|$)', thestring)
should do. If you actually mean "11 or more", there's no need for the (\D|$) part (or equivalent negative lookahead, etc).
Edit: as the OP now says in a comment that there might be whitespace between the WR and the digits, this can change to
mo = re.search(r'WR\s*(\d{11})(\D|$)', thestring)
the difference, of course, is in the \s* which means "0 or more whitespace characters here".
mo is None if thestring has no such match; otherwise, mo.group(1) gives you the 11-digits substring of interest.
A:
Try this:
result = re.search("No.WR\d{11}", file)
A:
>>> file = 'file No.WR79050107006 from files'
>>> for item in file.split():
... if "No.WR" in item:
... d=item.replace("No.WR","")
... if d.isdigit() and len(d) == 11:
... print "ok"
...
ok
A:
It's not clear from your comment on Alex's answer. Is the record valid if there is a space between the WR and the 11 digits?
Hopefully one of these examples help. Otherwise add the other variations and expected results to your question, and you should get answers that are straight to the point.
>>> import re
>>> re.findall(r'(WR\d{11})(?:\D|$)', 'file No.WR79050107006 from files')
['WR79050107006']
>>> re.findall(r'(WR)(\d{11})(?:\D|$)', 'file No.WR79050107006 from files')
[('WR', '79050107006')]
Whitespace between the WR and the 11 digits
>>> re.findall(r'(WR)(\d{11})(?:\D|$)', 'file No.WR 79050107006 from files')
[]
>>> re.findall(r'(WR)\s*(\d{11})(?:\D|$)', 'file No.WR 79050107006 from files')
[('WR', '79050107006')]
>>>
Anything between WR and the 11 digits
>>> re.findall(r'(WR).*(\d{11})(?:\D|$)', 'file No.WR!@#$%79050107006 from files')
[('WR', '79050107006')]
|
Need help with re for matching and getting the value python
|
Need help regarding re.
file = 'file No.WR79050107006 from files'
So what I am trying to do is validate if file string contains WR + 11 digit.
result = re.match('^(\S| )*(?P<sr>(\d){11})(\S| )*', file)
Its validate only 11 digit but not WR before it.
How can I do that?
Using re after matching how can I get the match value ( WR79050107006)
I can do string find
index = file.find('file No.')
and then get the value of next 13 char.
thanks
|
[
"If by \"validate if file string contains WR + 11 digit\" you mean \"exactly 11, not 12+\",\nmo = re.search(r'WR(\\d{11})(\\D|$)', thestring)\n\nshould do. If you actually mean \"11 or more\", there's no need for the (\\D|$) part (or equivalent negative lookahead, etc).\nEdit: as the OP now says in a comment that there might be whitespace between the WR and the digits, this can change to\nmo = re.search(r'WR\\s*(\\d{11})(\\D|$)', thestring)\n\nthe difference, of course, is in the \\s* which means \"0 or more whitespace characters here\".\nmo is None if thestring has no such match; otherwise, mo.group(1) gives you the 11-digits substring of interest.\n",
"Try this:\nresult = re.search(\"No.WR\\d{11}\", file)\n\n",
">>> file = 'file No.WR79050107006 from files'\n>>> for item in file.split():\n... if \"No.WR\" in item:\n... d=item.replace(\"No.WR\",\"\")\n... if d.isdigit() and len(d) == 11:\n... print \"ok\"\n...\nok\n\n",
"It's not clear from your comment on Alex's answer. Is the record valid if there is a space between the WR and the 11 digits?\nHopefully one of these examples help. Otherwise add the other variations and expected results to your question, and you should get answers that are straight to the point.\n>>> import re\n>>> re.findall(r'(WR\\d{11})(?:\\D|$)', 'file No.WR79050107006 from files')\n['WR79050107006']\n>>> re.findall(r'(WR)(\\d{11})(?:\\D|$)', 'file No.WR79050107006 from files')\n[('WR', '79050107006')]\n\nWhitespace between the WR and the 11 digits\n>>> re.findall(r'(WR)(\\d{11})(?:\\D|$)', 'file No.WR 79050107006 from files')\n[]\n>>> re.findall(r'(WR)\\s*(\\d{11})(?:\\D|$)', 'file No.WR 79050107006 from files')\n[('WR', '79050107006')]\n>>> \n\nAnything between WR and the 11 digits\n>>> re.findall(r'(WR).*(\\d{11})(?:\\D|$)', 'file No.WR!@#$%79050107006 from files')\n[('WR', '79050107006')]\n\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002486150_python.txt
|
Q:
Python: date, time formatting
I need to generate a local timestamp in a form of YYYYMMDDHHmmSSOHH'mm'. That OHH'mm' is one of +, -, Z and then there are hourhs and minutes followed by '.
Please, how do I get such a timestamp, denoting both local time zone and possible daylight saving?
A:
import time
localtime = time.localtime()
timeString = time.strftime("%Y%m%d%H%M%S", localtime)
# is DST in effect?
timezone = -(time.altzone if localtime.tm_isdst else time.timezone)
timeString += "Z" if timezone == 0 else "+" if timezone > 0 else "-"
timeString += time.strftime("%H'%M'", time.gmtime(abs(timezone)))
A:
time.strftime will do for that,
And in linux, %z will just give you -HHMM format if environment variable is properly set.
>>> os.environ['TZ'] = 'EST'
>>> time.strftime('%x %X %z')
'03/21/10 08:16:33 -0500'
|
Python: date, time formatting
|
I need to generate a local timestamp in a form of YYYYMMDDHHmmSSOHH'mm'. That OHH'mm' is one of +, -, Z and then there are hourhs and minutes followed by '.
Please, how do I get such a timestamp, denoting both local time zone and possible daylight saving?
|
[
"import time\n\nlocaltime = time.localtime()\ntimeString = time.strftime(\"%Y%m%d%H%M%S\", localtime)\n\n# is DST in effect?\ntimezone = -(time.altzone if localtime.tm_isdst else time.timezone)\ntimeString += \"Z\" if timezone == 0 else \"+\" if timezone > 0 else \"-\"\ntimeString += time.strftime(\"%H'%M'\", time.gmtime(abs(timezone)))\n\n",
"time.strftime will do for that,\nAnd in linux, %z will just give you -HHMM format if environment variable is properly set.\n>>> os.environ['TZ'] = 'EST'\n>>> time.strftime('%x %X %z')\n'03/21/10 08:16:33 -0500'\n\n"
] |
[
32,
8
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0002487109_datetime_python.txt
|
Q:
diffstrings.py : how do you specify path arguments?
I am trying to use diffstrings.py from Three20 on my iPhone project, and I can't find the proper format for the path arguments (as in "Usage: diffstrings.py [options] path1 path2 ...").
For example, when I run the script in my Xcode project directory like this
~/py/diffstrings.py -b
it analyzes just the main.m and finds 0 strings to localize,
then it diffs against existing fr.lproj and others, and finds that thes contain "obsolete strings".
Can anyone post examples of successful comand line invocations of diffstrings.py, for options -b, -d and -m?
A:
Taking a quick look at the code here http://github.com/facebook/three20/blob/master/diffstrings.py I see that if you don't specify any command line options, it assumes you mean the directory wherever the script lives in. So the option is to either copy .py file to where your .m files are, or simple use the command
~py/diffstrings.py -b .
That is, give the current directory (.) as the path argument.
|
diffstrings.py : how do you specify path arguments?
|
I am trying to use diffstrings.py from Three20 on my iPhone project, and I can't find the proper format for the path arguments (as in "Usage: diffstrings.py [options] path1 path2 ...").
For example, when I run the script in my Xcode project directory like this
~/py/diffstrings.py -b
it analyzes just the main.m and finds 0 strings to localize,
then it diffs against existing fr.lproj and others, and finds that thes contain "obsolete strings".
Can anyone post examples of successful comand line invocations of diffstrings.py, for options -b, -d and -m?
|
[
"Taking a quick look at the code here http://github.com/facebook/three20/blob/master/diffstrings.py I see that if you don't specify any command line options, it assumes you mean the directory wherever the script lives in. So the option is to either copy .py file to where your .m files are, or simple use the command\n ~py/diffstrings.py -b .\n\nThat is, give the current directory (.) as the path argument.\n"
] |
[
0
] |
[] |
[] |
[
"iphone",
"localization",
"python"
] |
stackoverflow_0002486822_iphone_localization_python.txt
|
Q:
How to set cookies with redirect in Pylons
In light of the cookie-handling bugs affecting Safari and Chrome (see this thread), and Pylons implementation of redirect_to as an exception, is it possible to reliably set a tracking cookie and redirect at the same time? Is the META refresh method looked down upon?
A:
Drilling down a bit, the webkit folks say it's not their problem, so the possible solutions aren't as pretty. One possible ugly solution: setting the tracking information in the beaker session (if you're using beaker?) and retrieving it from the page that you're redirecting to, setting a cookie at that later stage.
|
How to set cookies with redirect in Pylons
|
In light of the cookie-handling bugs affecting Safari and Chrome (see this thread), and Pylons implementation of redirect_to as an exception, is it possible to reliably set a tracking cookie and redirect at the same time? Is the META refresh method looked down upon?
|
[
"Drilling down a bit, the webkit folks say it's not their problem, so the possible solutions aren't as pretty. One possible ugly solution: setting the tracking information in the beaker session (if you're using beaker?) and retrieving it from the page that you're redirecting to, setting a cookie at that later stage. \n"
] |
[
1
] |
[] |
[] |
[
"cookies",
"pylons",
"python",
"redirect"
] |
stackoverflow_0002292881_cookies_pylons_python_redirect.txt
|
Q:
programming language implemented in pure python
i am creating ( researching possibility of ) a highly customizable python client and would like to allow users to actually edit the code in another language to customize the running of program. ( analogous to browser which itself coded in c/c++ and run another language html/js ). so my question is , is there any programming language implemented in pure python which i can see as a reference ( or use directly ? ) -- i need simple language ( simple statements and ifs can do )
edit: sorry if i did not make myself clear but what i want is "a language to customize the running of program" , even though pypi seems a great option, what i am looking for is more simple which i can study and extend myself if need arise. my google searches pointing towards xml based langagues. ( BMEL , XForms etc ).
A:
The question isn't completely clear on scope, but I have a hunch that PyPy, embedding other full languages, and similar solutions might be overkill. It sounds like iamgopal may really be interested in something more like Interpreter Pattern or Little Language.
If the language you want to support is really small (see the Interpreter Pattern link), then hand-coding this yourself in Python won't be too hard. You can write a simple parser (Google around; here's one example), then walk the AST and evaluate user expressions.
However, if you expect this to be used for a long time or by many people, it may be worth throwing a real language at the problem. (I'd recommend Python itself if your users are already familiar with basic Python syntax).
A:
Ren'Py is a modification to Python syntax built on top of Python itself, using the language tools in the stdlib.
A:
For your user's sake, don't use an XML based language - XML is an awful basis for a programming language and your users will hate you for it.
Here is a suggestion. Use a strict subset of Python for your language. Use the compiler module to convert their code into an abstract syntax tree and walk the tree to to validate that the code conforms to your subset before converting the AST into python bytecode.
N.B. I just checked the docs and see that the compiler package is deprecated in 2.6 and removed in Python 3.x. Does anyone know why that is?
A:
Why not Python itself? With some care you can use eval to run user code.
One of the good thing about interpreted scripting languages is that you don't need another extra scripting language!
A:
PLY (Python Lex-Yacc)
is something of your interest.
A:
Numerous template languages such as Cheetah, Django templates, Genshi, Mako, Mighty might serve as an example.
A:
Possibly Common Lisp (or any other Lisp) will be the best choice for that task. Because Lisp make it possible to easily extend host language with powerful macroses and construct DSL (domain specific language).
A:
If all you need is simple if statements and expressions, I'm sure it wouldn't be an awful task to parse each line. Something like
if some flag
activate some feature
deactivate some feature
elif some other flag
activate some feature
activate some feature
else
logout
Just write a class which, while parsing takes the first word, checks if it's "if, elif, else," etc, and if so, check a flag and set a flag saying you either are or are not executing until the next conditional. If it's not a conditional, call a function based on the first keyword that would modify the program state in some way.
The class could store some local execution state (are we in an if statement? If so are we executing this branch?) and have another class containing some global application state (flags that are checkable by if statements, etc).
This is probably the wrong thing to do in your situation (it's very prone to bugs, it's dangerous if you don't treat the data in the scripts correctly), but it's at least a start if you do decide to interpret your own mini-language.
Seriously though, if you try this, be very, very, srs careful. Don't give the scripts any functionality that they don't definitely need, because you are almost certainly opening security holes by doing something like this.
Don't say I didn't warn you.
|
programming language implemented in pure python
|
i am creating ( researching possibility of ) a highly customizable python client and would like to allow users to actually edit the code in another language to customize the running of program. ( analogous to browser which itself coded in c/c++ and run another language html/js ). so my question is , is there any programming language implemented in pure python which i can see as a reference ( or use directly ? ) -- i need simple language ( simple statements and ifs can do )
edit: sorry if i did not make myself clear but what i want is "a language to customize the running of program" , even though pypi seems a great option, what i am looking for is more simple which i can study and extend myself if need arise. my google searches pointing towards xml based langagues. ( BMEL , XForms etc ).
|
[
"The question isn't completely clear on scope, but I have a hunch that PyPy, embedding other full languages, and similar solutions might be overkill. It sounds like iamgopal may really be interested in something more like Interpreter Pattern or Little Language.\nIf the language you want to support is really small (see the Interpreter Pattern link), then hand-coding this yourself in Python won't be too hard. You can write a simple parser (Google around; here's one example), then walk the AST and evaluate user expressions.\nHowever, if you expect this to be used for a long time or by many people, it may be worth throwing a real language at the problem. (I'd recommend Python itself if your users are already familiar with basic Python syntax).\n",
"Ren'Py is a modification to Python syntax built on top of Python itself, using the language tools in the stdlib.\n",
"For your user's sake, don't use an XML based language - XML is an awful basis for a programming language and your users will hate you for it.\nHere is a suggestion. Use a strict subset of Python for your language. Use the compiler module to convert their code into an abstract syntax tree and walk the tree to to validate that the code conforms to your subset before converting the AST into python bytecode.\nN.B. I just checked the docs and see that the compiler package is deprecated in 2.6 and removed in Python 3.x. Does anyone know why that is?\n",
"Why not Python itself? With some care you can use eval to run user code.\nOne of the good thing about interpreted scripting languages is that you don't need another extra scripting language!\n",
"PLY (Python Lex-Yacc)\n is something of your interest.\n",
"Numerous template languages such as Cheetah, Django templates, Genshi, Mako, Mighty might serve as an example.\n",
"Possibly Common Lisp (or any other Lisp) will be the best choice for that task. Because Lisp make it possible to easily extend host language with powerful macroses and construct DSL (domain specific language).\n",
"If all you need is simple if statements and expressions, I'm sure it wouldn't be an awful task to parse each line. Something like\nif some flag\n activate some feature\n deactivate some feature\nelif some other flag\n activate some feature\n activate some feature\nelse\n logout\n\nJust write a class which, while parsing takes the first word, checks if it's \"if, elif, else,\" etc, and if so, check a flag and set a flag saying you either are or are not executing until the next conditional. If it's not a conditional, call a function based on the first keyword that would modify the program state in some way.\nThe class could store some local execution state (are we in an if statement? If so are we executing this branch?) and have another class containing some global application state (flags that are checkable by if statements, etc).\nThis is probably the wrong thing to do in your situation (it's very prone to bugs, it's dangerous if you don't treat the data in the scripts correctly), but it's at least a start if you do decide to interpret your own mini-language.\nSeriously though, if you try this, be very, very, srs careful. Don't give the scripts any functionality that they don't definitely need, because you are almost certainly opening security holes by doing something like this.\nDon't say I didn't warn you.\n"
] |
[
4,
3,
3,
1,
1,
1,
0,
0
] |
[] |
[] |
[
"interpreter",
"programming_languages",
"python"
] |
stackoverflow_0002486348_interpreter_programming_languages_python.txt
|
Q:
Using ManagementClass.Getinstances() from IronPython
I have an IronPython script that looks for current running processes using WMI. The code looks like this:
import clr
clr.AddReference('System.Management')
from System.Management import ManagementClass
from System import Array
mc = ManagementClass('Win32_Processes')
procs = mc.GetInstances()
That last line where I call the GetInstances() method raises the following error:
Traceback (most recent call first):
File "<stdin>", line 1, in <module>
SystemError: Not Found
I am not understanding what's not being found?!? I believe that I may need to pass an instance of ManagementOperationObserver and of EnumerationOptions to GetInstance() however, I don't understand why that is, since the method with the signature Getinstance() is available in ManagementClass.
A:
I think the only problem is that 'Win32_Processes' is a typo for 'Win32_Process'. This seems to work:
>>> mc = ManagementClass('Win32_Process')
>>> procs = mc.GetInstances()
>>> for p in procs:
... print p['Name']
...
System Idle Process
System
smss.exe
(etc)
|
Using ManagementClass.Getinstances() from IronPython
|
I have an IronPython script that looks for current running processes using WMI. The code looks like this:
import clr
clr.AddReference('System.Management')
from System.Management import ManagementClass
from System import Array
mc = ManagementClass('Win32_Processes')
procs = mc.GetInstances()
That last line where I call the GetInstances() method raises the following error:
Traceback (most recent call first):
File "<stdin>", line 1, in <module>
SystemError: Not Found
I am not understanding what's not being found?!? I believe that I may need to pass an instance of ManagementOperationObserver and of EnumerationOptions to GetInstance() however, I don't understand why that is, since the method with the signature Getinstance() is available in ManagementClass.
|
[
"I think the only problem is that 'Win32_Processes' is a typo for 'Win32_Process'. This seems to work:\n>>> mc = ManagementClass('Win32_Process')\n>>> procs = mc.GetInstances()\n>>> for p in procs:\n... print p['Name']\n... \nSystem Idle Process\nSystem\nsmss.exe\n(etc)\n\n"
] |
[
1
] |
[] |
[] |
[
"ironpython",
"python",
"wmi"
] |
stackoverflow_0002487475_ironpython_python_wmi.txt
|
Q:
How to clear wxpython frame content when dragging a panel?
I have 3 panels and I want to make drags on them.
The problem is that when I do a drag on one this happens:
http://img41.yfrog.com/img41/9043/soundlog.png http://img41.yfrog.com/img41/9043/soundlog.png
How can I refresh the frame to happear its color when the panel is no longer there?
This is the code that I have to make the drag:
def onMouseMove(self, event):
(self.pointWidth, self.pointHeight) = event.GetPosition()
(self.width, self.height) = self.GetSizeTuple()
if (self.pointWidth>100 and self.pointWidth<(self.width-100) and self.pointHeight < 15) or self.parent.dragging:
self.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))
"""implement dragging"""
if not event.Dragging():
self.w = 0
self.h = 0
return
self.CaptureMouse()
if self.w == 0 and self.h == 0:
(self.w, self.h) = event.GetPosition()
else:
(posw, posh) = event.GetPosition()
displacement = self.h - posh
self.SetPosition( self.GetPosition() - (0, displacement))
else:
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
def onDraggingDown(self, event):
if self.pointWidth>100 and self.pointWidth<(self.width-100) and self.pointHeight < 15:
self.parent.dragging = 1
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
self.SetBackgroundColour('BLUE')
self.parent.SetTransparent(220)
self.Refresh()
def onDraggingUp(self, event):
self.parent.dragging = 0
self.parent.SetTransparent(255)
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
and this are the binds for this events:
self.Bind(wx.EVT_MOTION, self.onMouseMove)
self.Bind(wx.EVT_LEFT_DOWN, self.onDraggingDown)
self.Bind(wx.EVT_LEFT_UP, self.onDraggingUp)
With this, if I click on the top of the panel, and move down or up, the panel position changes (I drag the panel) to the position of the mouse.
A:
To refresh the parent on every repositioning of self, you could add
self.parent.Refresh()
right after your existing call to self.SetPosition in your def onMouseMove method. Right now you're refreshing the frame only in the def onDraggingDown method, i.e., the first time the mouse left button is clicked and held down, not every time the mouse is moved while said button is held down (i.e., the "dragging" action itself).
I was unable to download your code for testing purposes, due to the rather "spammy peculiar" site you chose to upload it to -- the site keeps bombarding me with ads, no clear way for me to just do the download, occasionally complaining that it doesn't support my machine (I use a Mac and Google Chrome, the site at some spots insists on Windows with IE or Firefox...), etc etc. I'm sure you can find other sites, more usable than that one, for people who are trying to help you out!-)
|
How to clear wxpython frame content when dragging a panel?
|
I have 3 panels and I want to make drags on them.
The problem is that when I do a drag on one this happens:
http://img41.yfrog.com/img41/9043/soundlog.png http://img41.yfrog.com/img41/9043/soundlog.png
How can I refresh the frame to happear its color when the panel is no longer there?
This is the code that I have to make the drag:
def onMouseMove(self, event):
(self.pointWidth, self.pointHeight) = event.GetPosition()
(self.width, self.height) = self.GetSizeTuple()
if (self.pointWidth>100 and self.pointWidth<(self.width-100) and self.pointHeight < 15) or self.parent.dragging:
self.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))
"""implement dragging"""
if not event.Dragging():
self.w = 0
self.h = 0
return
self.CaptureMouse()
if self.w == 0 and self.h == 0:
(self.w, self.h) = event.GetPosition()
else:
(posw, posh) = event.GetPosition()
displacement = self.h - posh
self.SetPosition( self.GetPosition() - (0, displacement))
else:
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
def onDraggingDown(self, event):
if self.pointWidth>100 and self.pointWidth<(self.width-100) and self.pointHeight < 15:
self.parent.dragging = 1
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
self.SetBackgroundColour('BLUE')
self.parent.SetTransparent(220)
self.Refresh()
def onDraggingUp(self, event):
self.parent.dragging = 0
self.parent.SetTransparent(255)
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
and this are the binds for this events:
self.Bind(wx.EVT_MOTION, self.onMouseMove)
self.Bind(wx.EVT_LEFT_DOWN, self.onDraggingDown)
self.Bind(wx.EVT_LEFT_UP, self.onDraggingUp)
With this, if I click on the top of the panel, and move down or up, the panel position changes (I drag the panel) to the position of the mouse.
|
[
"To refresh the parent on every repositioning of self, you could add\nself.parent.Refresh()\n\nright after your existing call to self.SetPosition in your def onMouseMove method. Right now you're refreshing the frame only in the def onDraggingDown method, i.e., the first time the mouse left button is clicked and held down, not every time the mouse is moved while said button is held down (i.e., the \"dragging\" action itself).\nI was unable to download your code for testing purposes, due to the rather \"spammy peculiar\" site you chose to upload it to -- the site keeps bombarding me with ads, no clear way for me to just do the download, occasionally complaining that it doesn't support my machine (I use a Mac and Google Chrome, the site at some spots insists on Windows with IE or Firefox...), etc etc. I'm sure you can find other sites, more usable than that one, for people who are trying to help you out!-)\n"
] |
[
1
] |
[] |
[] |
[
"panel",
"python",
"refresh",
"wxpython"
] |
stackoverflow_0002437818_panel_python_refresh_wxpython.txt
|
Q:
Hidden line removal in JavaScript or Python?
I have the following task:
Input:
A 3D scene comprised of a set of cuboids. Could be broken down to a set of triangles.
A description of a camera: position, direction, focal length.
Output: 2D wire frame projection of the scene as a set of lines. Important: Hidden lines removal should have been applied.
Platform: Web app running on Google App Engine for Python.
Any idea if there is a JavaScript or Python library that does this?
A:
Maybe the Python Nacrisse interface is useful?
|
Hidden line removal in JavaScript or Python?
|
I have the following task:
Input:
A 3D scene comprised of a set of cuboids. Could be broken down to a set of triangles.
A description of a camera: position, direction, focal length.
Output: 2D wire frame projection of the scene as a set of lines. Important: Hidden lines removal should have been applied.
Platform: Web app running on Google App Engine for Python.
Any idea if there is a JavaScript or Python library that does this?
|
[
"Maybe the Python Nacrisse interface is useful?\n"
] |
[
0
] |
[] |
[] |
[
"3d",
"hidden",
"javascript",
"lines",
"python"
] |
stackoverflow_0002487235_3d_hidden_javascript_lines_python.txt
|
Q:
Pypcap for mac on python 2.6?
How do you end up running pypcap for python 2.6 on a mac? It seems that there hasn't been any new releases since 2.5 or am I just looking in the wrong places?
I seem to be unable to install the 2.5 binary with the following error: You cannot install pcap 1.1 on this volume. pcap requires System Python 2.5 to install.
A:
Python 2.5 code should run fine unaltered on Python 2.6 (you'll just occasionaly get a DeprecationWarning for features which are changing in Python 3.x).
|
Pypcap for mac on python 2.6?
|
How do you end up running pypcap for python 2.6 on a mac? It seems that there hasn't been any new releases since 2.5 or am I just looking in the wrong places?
I seem to be unable to install the 2.5 binary with the following error: You cannot install pcap 1.1 on this volume. pcap requires System Python 2.5 to install.
|
[
"Python 2.5 code should run fine unaltered on Python 2.6 (you'll just occasionaly get a DeprecationWarning for features which are changing in Python 3.x).\n"
] |
[
1
] |
[] |
[] |
[
"packet_sniffers",
"pcap",
"python"
] |
stackoverflow_0002488185_packet_sniffers_pcap_python.txt
|
Q:
django image upload forms
I am having problems with django forms and image uploads. I have googled, read the documentations and even questions ere, but cant figure out the issue. Here are my files
my models
class UserProfile(User):
"""user with app settings. """
DESIGNATION_CHOICES=(
('ADM', 'Administrator'),
('OFF', 'Club Official'),
('MEM', 'Ordinary Member'),
)
onames = models.CharField(max_length=30, blank=True)
phoneNumber = models.CharField(max_length=15)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True)
course = models.CharField(max_length=30, blank=True, null=True)
timezone = models.CharField(max_length=50, default='Africa/Nairobi')
smsCom = models.BooleanField()
mailCom = models.BooleanField()
fbCom = models.BooleanField()
objects = UserManager()
#def __unicode__(self):
# return '%s %s ' % (User.Username, User.is_staff)
def get_absolute_url(self):
return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id)
def get_download_url(self):
return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name)
...
class reports(models.Model):
repID = models.AutoField(primary_key=True)
repSubject = models.CharField(max_length=100)
repRecepients = models.ManyToManyField(UserProfile)
repPoster = models.ForeignKey(UserProfile,related_name='repposter')
repDescription = models.TextField()
repPubAccess = models.BooleanField()
repDate = models.DateField()
report = models.FileField(max_length=200,upload_to='files/%Y/%m/%d' )
deleted = models.BooleanField()
def __unicode__(self):
return u'%s ' % (self.repSubject)
my forms
from django import forms
from django.http import HttpResponse
from cms.models import *
from django.contrib.sessions.models import Session
from django.forms.extras.widgets import SelectDateWidget
class UserProfileForm(forms.ModelForm):
class Meta:
model= UserProfile
exclude = ('designation','password','is_staff', 'is_active','is_superuser','last_login','date_joined','user_permissions','groups')
...
class reportsForm(forms.ModelForm):
repPoster = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput())
repDescription = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Report Description here')
repDate = forms.DateField(widget=SelectDateWidget())
class Meta:
model = reports
exclude = ('deleted')
my views
@login_required
def reports_media(request):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
if request.user.is_staff== True:
repmedform = reportsForm(request.POST, request.FILES)
if repmedform.is_valid():
repmedform.save()
repmedform = reportsForm(initial = {'repPoster':user.id,})
else:
repmedform = reportsForm(initial = {'repPoster':user.id,})
return render_to_response('staffrepmedia.html', {'repfrm':repmedform, 'rep_media': reports.objects.all()})
else:
return render_to_response('reports_&_media.html', {'rep_media': reports.objects.all()})
...
@login_required
def settingchng(request):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
form = UserProfileForm(instance = user)
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance = user)
if form.is_valid():
form.save()
return HttpResponseRedirect('/settings/')
else:
form = UserProfileForm(instance = user)
if request.user.is_staff== True:
return render_to_response('staffsettingschange.html', {'form': form})
else:
return render_to_response('settingschange.html', {'form': form})
...
@login_required
def useradd(request):
if request.method == 'POST':
form = UserAddForm(request.POST,request.FILES )
if form.is_valid():
password = request.POST['password']
request.POST['password'] = set_password(password)
form.save()
else:
form = UserAddForm()
return render_to_response('staffadduser.html', {'form':form})
Example of my templates
{% if form.errors %}
<ol>
{% for field in form %}
<H3 class="title">
<p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p>
</H3>
{% endfor %}
</ol>
{% endif %}
<form method="post" id="form" action="" enctype="multipart/form-data" class="infotabs accfrm">
{{ repfrm.as_p }}
<input type="submit" value="Submit" />
</form>
A:
the issue was actually that this line
<form method="post" id="form" action="" enctype="multipart/form-data" class="infotabs accfrm">
appeared as
<form method="post" id="form" action="" enctype="multipart/form
-data" class="infotabs accfrm">
hence the forms were not uploading. And to think I have had this issue for 2 weeks. If its ok with you guys, i will delete this question.
|
django image upload forms
|
I am having problems with django forms and image uploads. I have googled, read the documentations and even questions ere, but cant figure out the issue. Here are my files
my models
class UserProfile(User):
"""user with app settings. """
DESIGNATION_CHOICES=(
('ADM', 'Administrator'),
('OFF', 'Club Official'),
('MEM', 'Ordinary Member'),
)
onames = models.CharField(max_length=30, blank=True)
phoneNumber = models.CharField(max_length=15)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True)
course = models.CharField(max_length=30, blank=True, null=True)
timezone = models.CharField(max_length=50, default='Africa/Nairobi')
smsCom = models.BooleanField()
mailCom = models.BooleanField()
fbCom = models.BooleanField()
objects = UserManager()
#def __unicode__(self):
# return '%s %s ' % (User.Username, User.is_staff)
def get_absolute_url(self):
return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id)
def get_download_url(self):
return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name)
...
class reports(models.Model):
repID = models.AutoField(primary_key=True)
repSubject = models.CharField(max_length=100)
repRecepients = models.ManyToManyField(UserProfile)
repPoster = models.ForeignKey(UserProfile,related_name='repposter')
repDescription = models.TextField()
repPubAccess = models.BooleanField()
repDate = models.DateField()
report = models.FileField(max_length=200,upload_to='files/%Y/%m/%d' )
deleted = models.BooleanField()
def __unicode__(self):
return u'%s ' % (self.repSubject)
my forms
from django import forms
from django.http import HttpResponse
from cms.models import *
from django.contrib.sessions.models import Session
from django.forms.extras.widgets import SelectDateWidget
class UserProfileForm(forms.ModelForm):
class Meta:
model= UserProfile
exclude = ('designation','password','is_staff', 'is_active','is_superuser','last_login','date_joined','user_permissions','groups')
...
class reportsForm(forms.ModelForm):
repPoster = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput())
repDescription = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Report Description here')
repDate = forms.DateField(widget=SelectDateWidget())
class Meta:
model = reports
exclude = ('deleted')
my views
@login_required
def reports_media(request):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
if request.user.is_staff== True:
repmedform = reportsForm(request.POST, request.FILES)
if repmedform.is_valid():
repmedform.save()
repmedform = reportsForm(initial = {'repPoster':user.id,})
else:
repmedform = reportsForm(initial = {'repPoster':user.id,})
return render_to_response('staffrepmedia.html', {'repfrm':repmedform, 'rep_media': reports.objects.all()})
else:
return render_to_response('reports_&_media.html', {'rep_media': reports.objects.all()})
...
@login_required
def settingchng(request):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
form = UserProfileForm(instance = user)
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance = user)
if form.is_valid():
form.save()
return HttpResponseRedirect('/settings/')
else:
form = UserProfileForm(instance = user)
if request.user.is_staff== True:
return render_to_response('staffsettingschange.html', {'form': form})
else:
return render_to_response('settingschange.html', {'form': form})
...
@login_required
def useradd(request):
if request.method == 'POST':
form = UserAddForm(request.POST,request.FILES )
if form.is_valid():
password = request.POST['password']
request.POST['password'] = set_password(password)
form.save()
else:
form = UserAddForm()
return render_to_response('staffadduser.html', {'form':form})
Example of my templates
{% if form.errors %}
<ol>
{% for field in form %}
<H3 class="title">
<p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p>
</H3>
{% endfor %}
</ol>
{% endif %}
<form method="post" id="form" action="" enctype="multipart/form-data" class="infotabs accfrm">
{{ repfrm.as_p }}
<input type="submit" value="Submit" />
</form>
|
[
"the issue was actually that this line \n<form method=\"post\" id=\"form\" action=\"\" enctype=\"multipart/form-data\" class=\"infotabs accfrm\">\n\nappeared as \n<form method=\"post\" id=\"form\" action=\"\" enctype=\"multipart/form\n-data\" class=\"infotabs accfrm\">\n\nhence the forms were not uploading. And to think I have had this issue for 2 weeks. If its ok with you guys, i will delete this question. \n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0002487521_django_django_forms_python.txt
|
Q:
Newbie Python programmer tangling with Lists
Here's what I've got so far:
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
counter = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
counter += counter
return counter
# +++your code here+++
return
I'm following the Google Python Class, so this isn't homework, but me just learning and improving myself; so please no negative comments about 'not doing my homework'. :P
What do you guys think I'm doing wrong here?
Here's the result:
match_ends
X got: 0 expected: 3
X got: 0 expected: 2
X got: 0 expected: 1
I'm really loving Python, so I just know that I'll get better at it. :)
A:
You should do:
counter += 1
instead of
counter += counter
which stays at 0 for all ages.
A:
counter += 1
you add 0 to 0
|
Newbie Python programmer tangling with Lists
|
Here's what I've got so far:
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
counter = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
counter += counter
return counter
# +++your code here+++
return
I'm following the Google Python Class, so this isn't homework, but me just learning and improving myself; so please no negative comments about 'not doing my homework'. :P
What do you guys think I'm doing wrong here?
Here's the result:
match_ends
X got: 0 expected: 3
X got: 0 expected: 2
X got: 0 expected: 1
I'm really loving Python, so I just know that I'll get better at it. :)
|
[
"You should do:\ncounter += 1\n\ninstead of\ncounter += counter\n\nwhich stays at 0 for all ages.\n",
"counter += 1\n\nyou add 0 to 0\n"
] |
[
2,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002488447_list_python.txt
|
Q:
Djangobb problem
I've installed Djangobb app on my server (Debian, mod_python) by cloning original source. The only things I've changed is database options in settings.py. All needed components are installed - syncdb query was executed right.
But, when I'm trying to enter on my forum, it returns me error:
ImproperlyConfigured: Error importing middleware django_authopenid.middleware: "No module named djangobb_forum.subscription"
I've checked - djangobb_forum/subscription.py exist, so I don't know what can be wrong.
Maybe someone had problems like that and know how to fix it?
Sorry for my english.
A:
There are two obvious reasons to why this might happen:
djangobb_forum is not on your Python path
There is no __init__.py in the djangobb_forum folder
If the code says from djangobb_forum import ... then you need to have the parent folder of djangobb_forum on your Python path.
|
Djangobb problem
|
I've installed Djangobb app on my server (Debian, mod_python) by cloning original source. The only things I've changed is database options in settings.py. All needed components are installed - syncdb query was executed right.
But, when I'm trying to enter on my forum, it returns me error:
ImproperlyConfigured: Error importing middleware django_authopenid.middleware: "No module named djangobb_forum.subscription"
I've checked - djangobb_forum/subscription.py exist, so I don't know what can be wrong.
Maybe someone had problems like that and know how to fix it?
Sorry for my english.
|
[
"There are two obvious reasons to why this might happen:\n\ndjangobb_forum is not on your Python path\nThere is no __init__.py in the djangobb_forum folder\n\nIf the code says from djangobb_forum import ... then you need to have the parent folder of djangobb_forum on your Python path.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"mod_python",
"python"
] |
stackoverflow_0002488142_django_mod_python_python.txt
|
Q:
Python: Inheritance of a class attribute (list)
inheriting a class attribute from a super class and later changing the value for the subclass works fine:
class Unit(object):
value = 10
class Archer(Unit):
pass
print Unit.value
print Archer.value
Archer.value = 5
print Unit.value
print Archer.value
leads to the output:
10
10
10
5
which is just fine: Archer inherits the value from Unit, but when I change Archer's value, Unit's value remains untouched.
Now, if the inherited value is a list, the shallow copy effect strikes and the value of the superclass is also affected:
class Unit(object):
listvalue = [10]
class Archer(Unit):
pass
print Unit.listvalue
print Archer.listvalue
Archer.listvalue[0] = 5
print Unit.listvalue
print Archer.listvalue
Output:
10
10
5
5
Is there a way to "deep copy" a list when inheriting it from the super class?
Many thanks
Sano
A:
It is not a matter of shallow or deep copies, it is a matter of references and assignments.
It the first case Unit.value and Archer.value are two variables which reference the same value. When you do Archer.value = 5, you are assigning a new reference to Acher.value.
To solve your problem you need to assign a new list value to the Archer.list.
If these values are only going to be accessed by class methods, then the simplest solution is to do the assignment when the class is initialized.
A:
Michael's answer is nice and simple, but if you wish to avoid having to add that line to each Unit subclass - maybe you have a bunch of other lists like that one, a metaclass is an easy way to solve the problem
class UnitMeta(type):
def __init__(self, *args):
super(UnitMeta, self).__init__(*args)
self.listvalue = [10]
class Unit(object):
__metaclass__ = UnitMeta
pass
class Archer(Unit):
pass
print Unit.listvalue
print Archer.listvalue
Archer.listvalue[0] = 5
print Unit.listvalue
print Archer.listvalue
output:
[10]
[10]
[10]
[5]
You can also extend this same idea to automatically find and copy up lists (and dicts) defined in Unit
class UnitMeta(type):
def __init__(self, *args):
super(UnitMeta, self).__init__(*args)
for superclass in self.__mro__:
for k,v in vars(superclass).items():
if isinstance(v, (list, dict, )):
setattr(self, k, type(v)(v))
class Unit(object):
__metaclass__ = UnitMeta
listvalue = [10]
class Archer(Unit):
pass
A:
You coud copy the list in the definition of Archer:
class Archer(Unit):
listvalue = Unit.listvalue[:]
|
Python: Inheritance of a class attribute (list)
|
inheriting a class attribute from a super class and later changing the value for the subclass works fine:
class Unit(object):
value = 10
class Archer(Unit):
pass
print Unit.value
print Archer.value
Archer.value = 5
print Unit.value
print Archer.value
leads to the output:
10
10
10
5
which is just fine: Archer inherits the value from Unit, but when I change Archer's value, Unit's value remains untouched.
Now, if the inherited value is a list, the shallow copy effect strikes and the value of the superclass is also affected:
class Unit(object):
listvalue = [10]
class Archer(Unit):
pass
print Unit.listvalue
print Archer.listvalue
Archer.listvalue[0] = 5
print Unit.listvalue
print Archer.listvalue
Output:
10
10
5
5
Is there a way to "deep copy" a list when inheriting it from the super class?
Many thanks
Sano
|
[
"It is not a matter of shallow or deep copies, it is a matter of references and assignments.\nIt the first case Unit.value and Archer.value are two variables which reference the same value. When you do Archer.value = 5, you are assigning a new reference to Acher.value.\nTo solve your problem you need to assign a new list value to the Archer.list.\nIf these values are only going to be accessed by class methods, then the simplest solution is to do the assignment when the class is initialized.\n",
"Michael's answer is nice and simple, but if you wish to avoid having to add that line to each Unit subclass - maybe you have a bunch of other lists like that one, a metaclass is an easy way to solve the problem\nclass UnitMeta(type):\n def __init__(self, *args):\n super(UnitMeta, self).__init__(*args)\n self.listvalue = [10]\n\nclass Unit(object):\n __metaclass__ = UnitMeta\n pass\n\nclass Archer(Unit):\n pass\n\nprint Unit.listvalue\nprint Archer.listvalue\n\nArcher.listvalue[0] = 5\n\nprint Unit.listvalue\nprint Archer.listvalue\n\noutput:\n[10]\n[10]\n[10]\n[5]\n\nYou can also extend this same idea to automatically find and copy up lists (and dicts) defined in Unit\nclass UnitMeta(type):\n def __init__(self, *args):\n super(UnitMeta, self).__init__(*args)\n for superclass in self.__mro__:\n for k,v in vars(superclass).items():\n if isinstance(v, (list, dict, )):\n setattr(self, k, type(v)(v))\n\nclass Unit(object):\n __metaclass__ = UnitMeta\n listvalue = [10]\n\nclass Archer(Unit):\n pass\n\n",
"You coud copy the list in the definition of Archer:\nclass Archer(Unit):\n listvalue = Unit.listvalue[:]\n\n"
] |
[
16,
10,
0
] |
[] |
[] |
[
"class_attributes",
"deep_copy",
"inheritance",
"list",
"python"
] |
stackoverflow_0002488306_class_attributes_deep_copy_inheritance_list_python.txt
|
Q:
ping ip's / hostname in app engine
I'm trying to ping an ip address and telnet to some port from an app hosted on app engine. I've tried using http://svn.pylucid.net/pylucid/CodeSnippets/ping.py but for some reason it failing
Thanks
A:
GAE does not support ICMP nor Telnet.
For communication with outside hosts at the moment only mail/xmpp/http(s) work through the specific API calls.
A:
Note that ICMP messages can only be
sent from processes running as root.
Your app on GAE is not running as root. Why bother pinging when you want to telnet anyway?
|
ping ip's / hostname in app engine
|
I'm trying to ping an ip address and telnet to some port from an app hosted on app engine. I've tried using http://svn.pylucid.net/pylucid/CodeSnippets/ping.py but for some reason it failing
Thanks
|
[
"GAE does not support ICMP nor Telnet.\nFor communication with outside hosts at the moment only mail/xmpp/http(s) work through the specific API calls. \n",
"\nNote that ICMP messages can only be\n sent from processes running as root.\n\nYour app on GAE is not running as root. Why bother pinging when you want to telnet anyway?\n"
] |
[
2,
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002488430_google_app_engine_python.txt
|
Q:
Read more numbers in a line in Python
Let say i want to read the integers a, b and c from stdin (in one line, do not need to press return after each number). In c++, i would just do:
cin >> a >>b >> c;
How to do this in Python ?
A:
for string
a,b,c=raw_input().split()
for int
a,b,c=map(int,raw_input().split())
A:
values = raw_input()
# 1 3 15
a, b, c = values.split()
a will be '1', b will be '3' and c will be '15'.
If you want to be extra short and get ints try this:
a, b, c = [int(_) for _ in raw_input().split()]
|
Read more numbers in a line in Python
|
Let say i want to read the integers a, b and c from stdin (in one line, do not need to press return after each number). In c++, i would just do:
cin >> a >>b >> c;
How to do this in Python ?
|
[
"for string\na,b,c=raw_input().split()\n\nfor int\na,b,c=map(int,raw_input().split())\n\n",
"values = raw_input()\n# 1 3 15\na, b, c = values.split()\n\na will be '1', b will be '3' and c will be '15'.\n\nIf you want to be extra short and get ints try this:\na, b, c = [int(_) for _ in raw_input().split()]\n\n"
] |
[
3,
3
] |
[] |
[] |
[
"python",
"user_input"
] |
stackoverflow_0002488769_python_user_input.txt
|
Q:
django admin - adding fields on the fly
Basically I am writing a simple shopping cart. Each item can have multiple prices. (i.e. shirts where each size is priced differently). I would like to have a single price field in my admin panel, where when the first price is entered, an additional price field pops up. However I am kind of at a loss as to how to do this. What would be the best way to do this?
A:
Sounds like you want two related models - Item and Option. Item would contain the name of the item, and Option would contain the option - eg size - and the price of that option. You would then set up your admin to use an inline form for Option.
A:
You probably want inlines and some javascript.
A:
You might try checking out the Satchmo codebase. It has something similar that may provide some inspiration. http://satchmoproject.com
|
django admin - adding fields on the fly
|
Basically I am writing a simple shopping cart. Each item can have multiple prices. (i.e. shirts where each size is priced differently). I would like to have a single price field in my admin panel, where when the first price is entered, an additional price field pops up. However I am kind of at a loss as to how to do this. What would be the best way to do this?
|
[
"Sounds like you want two related models - Item and Option. Item would contain the name of the item, and Option would contain the option - eg size - and the price of that option. You would then set up your admin to use an inline form for Option.\n",
"You probably want inlines and some javascript.\n",
"You might try checking out the Satchmo codebase. It has something similar that may provide some inspiration. http://satchmoproject.com\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"django_admin",
"django_nonrel",
"python",
"shopping_cart"
] |
stackoverflow_0002488710_django_django_admin_django_nonrel_python_shopping_cart.txt
|
Q:
Trouble with this Python newbie exercise. Using Lists and finding if two adjacent elements are the same
Here's what I got:
# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
for number in nums:
numberHolder = number
# +++your code here+++
return
I'm kind of stuck here. What can I do?
A:
>>> import itertools
>>> [i[0] for i in itertools.groupby([1,2,2,3,3,3,2,2])]
[1, 2, 3, 2]
Or:
>>> def f(l):
... r = []
... last = None
... for i in l:
... if i != last:
... r.append(i)
... last = i
... return r
...
>>> f([1,2,2,3,3,3,4,4,2,2])
[1, 2, 3, 4, 2]
A:
try this:
def remove_adjacent(nums):
removed_list = []
numberHolder = None
for number in nums:
if number != numberHolder:
removed_list.append(number)
numberHolder = number
return removed_list
A:
Compare the current number with the previous number. If it's not the same then append it to a new list. Then save it so that the next loop can use it.
A:
This is another solution based on filter(). It's not just for adyacent and equal elements but for equal elements:
def remove_repeated_items(collection):
uniques = []
def not_already_added(item):
if item in uniques:
return False
else:
uniques.append(item)
return True
return filter(not_already_added, collection)
And then:
repeated = [1,2,2,3,3]
print remove_repeated_items(repeated)
|
Trouble with this Python newbie exercise. Using Lists and finding if two adjacent elements are the same
|
Here's what I got:
# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
for number in nums:
numberHolder = number
# +++your code here+++
return
I'm kind of stuck here. What can I do?
|
[
">>> import itertools\n>>> [i[0] for i in itertools.groupby([1,2,2,3,3,3,2,2])]\n[1, 2, 3, 2]\n\nOr:\n>>> def f(l):\n... r = []\n... last = None\n... for i in l:\n... if i != last:\n... r.append(i)\n... last = i\n... return r \n... \n>>> f([1,2,2,3,3,3,4,4,2,2])\n[1, 2, 3, 4, 2]\n\n",
"try this:\ndef remove_adjacent(nums):\n removed_list = []\n numberHolder = None\n for number in nums:\n if number != numberHolder:\n removed_list.append(number)\n numberHolder = number\n return removed_list\n\n",
"Compare the current number with the previous number. If it's not the same then append it to a new list. Then save it so that the next loop can use it.\n",
"This is another solution based on filter(). It's not just for adyacent and equal elements but for equal elements:\ndef remove_repeated_items(collection):\n uniques = []\n def not_already_added(item):\n if item in uniques:\n return False\n else:\n uniques.append(item)\n return True\n return filter(not_already_added, collection)\n\nAnd then:\nrepeated = [1,2,2,3,3]\nprint remove_repeated_items(repeated)\n\n"
] |
[
5,
1,
0,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002488651_list_python.txt
|
Q:
Python performance: iteration and operations on nested lists
Problem Hey folks. I'm looking for some advice on python performance. Some background on my problem:
Given:
A (x,y) mesh of nodes each with a value (0...255) starting at 0
A list of N input coordinates each at a specified location within the range (0...x, 0...y)
A value Z that defines the "neighborhood" in count of nodes
Increment the value of the node at the input coordinate and the node's neighbors. Neighbors beyond the mesh edge are ignored. (No wrapping)
BASE CASE: A mesh of size 1024x1024 nodes, with 400 input coordinates and a range Z of 75 nodes.
Processing should be O(x*y*Z*N). I expect x, y and Z to remain roughly around the values in the base case, but the number of input coordinates N could increase up to 100,000. My goal is to minimize processing time.
Current results Between my start and the comments below, we've got several implementations.
Running speed on my 2.26 GHz Intel Core 2 Duo with Python 2.6.1:
f1: 2.819s
f2: 1.567s
f3: 1.593s
f: 1.579s
f3b: 1.526s
f4: 0.978s
f1 is the initial naive implementation: three nested for loops.
f2 is replaces the inner for loop with a list comprehension.
f3 is based on Andrei's suggestion in the comments and replaces the outer for with map()
f is Chris's suggestion in the answers below
f3b is kriss's take on f3
f4 is Alex's contribution.
Code is included below for your perusal.
Question How can I further reduce the processing time? I'd prefer sub-1.0s for the test parameters.
Please, keep the recommendations to native Python. I know I can move to a third-party package such as numpy, but I'm trying to avoid any third party packages. Also, I've generated random input coordinates, and simplified the definition of the node value updates to keep our discussion simple. The specifics have to change slightly and are outside the scope of my question.
thanks much!
**`f1` is the initial naive implementation: three nested `for` loops.**
def f1(x,y,n,z):
rows = [[0]*x for i in xrange(y)]
for i in range(n):
inputX, inputY = (int(x*random.random()), int(y*random.random()))
topleft = (inputX - z, inputY - z)
for i in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)):
for j in xrange(max(0, topleft[1]), min(topleft[1]+(z*2), y)):
if rows[i][j] <= 255: rows[i][j] += 1
f2 is replaces the inner for loop with a list comprehension.
def f2(x,y,n,z):
rows = [[0]*x for i in xrange(y)]
for i in range(n):
inputX, inputY = (int(x*random.random()), int(y*random.random()))
topleft = (inputX - z, inputY - z)
for i in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)):
l = max(0, topleft[1])
r = min(topleft[1]+(z*2), y)
rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]]
UPDATE: f3 is based on Andrei's suggestion in the comments and replaces the outer for with map(). My first hack at this requires several out-of-local-scope lookups, specifically recommended against by Guido: local variable lookups are much faster than global or built-in variable lookups I hardcoded all but the reference to the main data structure itself to minimize that overhead.
rows = [[0]*x for i in xrange(y)]
def f3(x,y,n,z):
inputs = [(int(x*random.random()), int(y*random.random())) for i in range(n)]
rows = map(g, inputs)
def g(input):
inputX, inputY = input
topleft = (inputX - 75, inputY - 75)
for i in xrange(max(0, topleft[0]), min(topleft[0]+(75*2), 1024)):
l = max(0, topleft[1])
r = min(topleft[1]+(75*2), 1024)
rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]]
UPDATE3: ChristopeD also pointed out a couple improvements.
def f(x,y,n,z):
rows = [[0] * y for i in xrange(x)]
rn = random.random
for i in xrange(n):
topleft = (int(x*rn()) - z, int(y*rn()) - z)
l = max(0, topleft[1])
r = min(topleft[1]+(z*2), y)
for u in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)):
rows[u][l:r] = [j+(j<255) for j in rows[u][l:r]]
UPDATE4: kriss added a few improvements to f3, replacing min/max with the new ternary operator syntax.
def f3b(x,y,n,z):
rn = random.random
rows = [g1(x, y, z) for x, y in [(int(x*rn()), int(y*rn())) for i in xrange(n)]]
def g1(x, y, z):
l = y - z if y - z > 0 else 0
r = y + z if y + z < 1024 else 1024
for i in xrange(x - z if x - z > 0 else 0, x + z if x + z < 1024 else 1024 ):
rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]]
UPDATE5: Alex weighed in with his substantive revision, adding a separate map() operation to cap the values at 255 and removing all non-local-scope lookups. The perf differences are non-trivial.
def f4(x,y,n,z):
rows = [[0]*y for i in range(x)]
rr = random.randrange
inc = (1).__add__
sat = (0xff).__and__
for i in range(n):
inputX, inputY = rr(x), rr(y)
b = max(0, inputX - z)
t = min(inputX + z, x)
l = max(0, inputY - z)
r = min(inputY + z, y)
for i in range(b, t):
rows[i][l:r] = map(inc, rows[i][l:r])
for i in range(x):
rows[i] = map(sat, rows[i])
Also, since we all seem to be hacking around with variations, here's my test harness to compare speeds: (improved by ChristopheD)
def timing(f,x,y,z,n):
fn = "%s(%d,%d,%d,%d)" % (f.__name__, x, y, z, n)
ctx = "from __main__ import %s" % f.__name__
results = timeit.Timer(fn, ctx).timeit(10)
return "%4.4s: %.3f" % (f.__name__, results / 10.0)
if __name__ == "__main__":
print timing(f, 1024, 1024, 400, 75)
#add more here.
A:
1. A (smaller) speedup could definitely be the initialization of your rows...
Replace
rows = []
for i in range(x):
rows.append([0 for i in xrange(y)])
with
rows = [[0] * y for i in xrange(x)]
2. You can also avoid some lookups by moving random.random out of the loops (saves a little).
3. EDIT: after corrections -- you could arrive at something like this:
def f(x,y,n,z):
rows = [[0] * y for i in xrange(x)]
rn = random.random
for i in xrange(n):
topleft = (int(x*rn()) - z, int(y*rn()) - z)
l = max(0, topleft[1])
r = min(topleft[1]+(z*2), y)
for u in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)):
rows[u][l:r] = [j+(j<255) for j in rows[u][l:r]]
EDIT: some new timings with timeit (10 runs) -- seems this provides only minor speedups:
import timeit
print timeit.Timer("f1(1024,1024,400,75)", "from __main__ import f1").timeit(10)
print timeit.Timer("f2(1024,1024,400,75)", "from __main__ import f2").timeit(10)
print timeit.Timer("f(1024,1024,400,75)", "from __main__ import f3").timeit(10)
f1 21.1669280529
f2 12.9376120567
f 11.1249599457
A:
On my (slow-ish;-) first-day Macbook Air, 1.6GHz Core 2 Duo, system Python 2.5 on MacOSX 10.5, after saving your code in op.py I see the following timings:
$ python -mtimeit -s'import op' 'op.f1()'
10 loops, best of 3: 5.58 sec per loop
$ python -mtimeit -s'import op' 'op.f2()'
10 loops, best of 3: 3.15 sec per loop
So, my machine is slower than yours by a factor of a bit more than 1.9.
The fastest code I have for this task is:
def f3(x=x,y=y,n=n,z=z):
rows = [[0]*y for i in range(x)]
rr = random.randrange
inc = (1).__add__
sat = (0xff).__and__
for i in range(n):
inputX, inputY = rr(x), rr(y)
b = max(0, inputX - z)
t = min(inputX + z, x)
l = max(0, inputY - z)
r = min(inputY + z, y)
for i in range(b, t):
rows[i][l:r] = map(inc, rows[i][l:r])
for i in range(x):
rows[i] = map(sat, rows[i])
which times as:
$ python -mtimeit -s'import op' 'op.f3()'
10 loops, best of 3: 3 sec per loop
so, a very modest speedup, projecting to more than 1.5 seconds on your machine - well above the 1.0 you're aiming for:-(.
With a simple C-coded extensions, exte.c...:
#include "Python.h"
static PyObject*
dopoint(PyObject* self, PyObject* args)
{
int x, y, z, px, py;
int b, t, l, r;
int i, j;
PyObject* rows;
if(!PyArg_ParseTuple(args, "iiiiiO",
&x, &y, &z, &px, &py, &rows
))
return 0;
b = px - z;
if (b < 0) b = 0;
t = px + z;
if (t > x) t = x;
l = py - z;
if (l < 0) l = 0;
r = py + z;
if (r > y) r = y;
for(i = b; i < t; ++i) {
PyObject* row = PyList_GetItem(rows, i);
for(j = l; j < r; ++j) {
PyObject* pyitem = PyList_GetItem(row, j);
long item = PyInt_AsLong(pyitem);
if (item < 255) {
PyObject* newitem = PyInt_FromLong(item + 1);
PyList_SetItem(row, j, newitem);
}
}
}
Py_RETURN_NONE;
}
static PyMethodDef exteMethods[] = {
{"dopoint", dopoint, METH_VARARGS, "process a point"},
{0}
};
void
initexte()
{
Py_InitModule("exte", exteMethods);
}
(note: I haven't checked it carefully -- I think it doesn't leak memory due to the correct interplay of reference stealing and borrowing, but it should be code inspected very carefully before being put in production;-), we could do
import exte
def f4(x=x,y=y,n=n,z=z):
rows = [[0]*y for i in range(x)]
rr = random.randrange
for i in range(n):
inputX, inputY = rr(x), rr(y)
exte.dopoint(x, y, z, inputX, inputY, rows)
and the timing
$ python -mtimeit -s'import op' 'op.f4()'
10 loops, best of 3: 345 msec per loop
shows an acceleration of 8-9 times, which should put you in the ballpark you desire. I've seen a comment saying you don't want any third-party extension, but, well, this tiny extension you could make entirely your own;-). ((Not sure what licensing conditions apply to code on Stack Overflow, but I'll be glad to re-release this under the Apache 2 license or the like, if you need that;-)).
A:
in your f3 rewrite, g can be simplified. (Can also be applied to f4)
You have the following code inside a for loop.
l = max(0, topleft[1])
r = min(topleft[1]+(75*2), 1024)
However, it appears that those values never change inside the for loop. So calculate them once, outside the loop instead.
A:
Based on your f3 version I played with the code. As l and r are constants you can avoid to compute them in g1 loop. Also using new ternary if instead of min and max seems to be consistently faster. Also simplified expression with topleft. On my system it appears to be about 20% faster using with the code below.
def f3b(x,y,n,z):
rows = [g1(x, y, z) for x, y in [(int(x*random.random()), int(y*random.random())) for i in range(n)]]
def g1(x, y, z):
l = y - z if y - z > 0 else 0
r = y + z if y + z < 1024 else 1024
for i in xrange(x - z if x - z > 0 else 0, x + z if x + z < 1024 else 1024 ):
rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]]
A:
You can create your own Python module in C, and control the performance as you want:
http://docs.python.org/extending/
|
Python performance: iteration and operations on nested lists
|
Problem Hey folks. I'm looking for some advice on python performance. Some background on my problem:
Given:
A (x,y) mesh of nodes each with a value (0...255) starting at 0
A list of N input coordinates each at a specified location within the range (0...x, 0...y)
A value Z that defines the "neighborhood" in count of nodes
Increment the value of the node at the input coordinate and the node's neighbors. Neighbors beyond the mesh edge are ignored. (No wrapping)
BASE CASE: A mesh of size 1024x1024 nodes, with 400 input coordinates and a range Z of 75 nodes.
Processing should be O(x*y*Z*N). I expect x, y and Z to remain roughly around the values in the base case, but the number of input coordinates N could increase up to 100,000. My goal is to minimize processing time.
Current results Between my start and the comments below, we've got several implementations.
Running speed on my 2.26 GHz Intel Core 2 Duo with Python 2.6.1:
f1: 2.819s
f2: 1.567s
f3: 1.593s
f: 1.579s
f3b: 1.526s
f4: 0.978s
f1 is the initial naive implementation: three nested for loops.
f2 is replaces the inner for loop with a list comprehension.
f3 is based on Andrei's suggestion in the comments and replaces the outer for with map()
f is Chris's suggestion in the answers below
f3b is kriss's take on f3
f4 is Alex's contribution.
Code is included below for your perusal.
Question How can I further reduce the processing time? I'd prefer sub-1.0s for the test parameters.
Please, keep the recommendations to native Python. I know I can move to a third-party package such as numpy, but I'm trying to avoid any third party packages. Also, I've generated random input coordinates, and simplified the definition of the node value updates to keep our discussion simple. The specifics have to change slightly and are outside the scope of my question.
thanks much!
**`f1` is the initial naive implementation: three nested `for` loops.**
def f1(x,y,n,z):
rows = [[0]*x for i in xrange(y)]
for i in range(n):
inputX, inputY = (int(x*random.random()), int(y*random.random()))
topleft = (inputX - z, inputY - z)
for i in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)):
for j in xrange(max(0, topleft[1]), min(topleft[1]+(z*2), y)):
if rows[i][j] <= 255: rows[i][j] += 1
f2 is replaces the inner for loop with a list comprehension.
def f2(x,y,n,z):
rows = [[0]*x for i in xrange(y)]
for i in range(n):
inputX, inputY = (int(x*random.random()), int(y*random.random()))
topleft = (inputX - z, inputY - z)
for i in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)):
l = max(0, topleft[1])
r = min(topleft[1]+(z*2), y)
rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]]
UPDATE: f3 is based on Andrei's suggestion in the comments and replaces the outer for with map(). My first hack at this requires several out-of-local-scope lookups, specifically recommended against by Guido: local variable lookups are much faster than global or built-in variable lookups I hardcoded all but the reference to the main data structure itself to minimize that overhead.
rows = [[0]*x for i in xrange(y)]
def f3(x,y,n,z):
inputs = [(int(x*random.random()), int(y*random.random())) for i in range(n)]
rows = map(g, inputs)
def g(input):
inputX, inputY = input
topleft = (inputX - 75, inputY - 75)
for i in xrange(max(0, topleft[0]), min(topleft[0]+(75*2), 1024)):
l = max(0, topleft[1])
r = min(topleft[1]+(75*2), 1024)
rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]]
UPDATE3: ChristopeD also pointed out a couple improvements.
def f(x,y,n,z):
rows = [[0] * y for i in xrange(x)]
rn = random.random
for i in xrange(n):
topleft = (int(x*rn()) - z, int(y*rn()) - z)
l = max(0, topleft[1])
r = min(topleft[1]+(z*2), y)
for u in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)):
rows[u][l:r] = [j+(j<255) for j in rows[u][l:r]]
UPDATE4: kriss added a few improvements to f3, replacing min/max with the new ternary operator syntax.
def f3b(x,y,n,z):
rn = random.random
rows = [g1(x, y, z) for x, y in [(int(x*rn()), int(y*rn())) for i in xrange(n)]]
def g1(x, y, z):
l = y - z if y - z > 0 else 0
r = y + z if y + z < 1024 else 1024
for i in xrange(x - z if x - z > 0 else 0, x + z if x + z < 1024 else 1024 ):
rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]]
UPDATE5: Alex weighed in with his substantive revision, adding a separate map() operation to cap the values at 255 and removing all non-local-scope lookups. The perf differences are non-trivial.
def f4(x,y,n,z):
rows = [[0]*y for i in range(x)]
rr = random.randrange
inc = (1).__add__
sat = (0xff).__and__
for i in range(n):
inputX, inputY = rr(x), rr(y)
b = max(0, inputX - z)
t = min(inputX + z, x)
l = max(0, inputY - z)
r = min(inputY + z, y)
for i in range(b, t):
rows[i][l:r] = map(inc, rows[i][l:r])
for i in range(x):
rows[i] = map(sat, rows[i])
Also, since we all seem to be hacking around with variations, here's my test harness to compare speeds: (improved by ChristopheD)
def timing(f,x,y,z,n):
fn = "%s(%d,%d,%d,%d)" % (f.__name__, x, y, z, n)
ctx = "from __main__ import %s" % f.__name__
results = timeit.Timer(fn, ctx).timeit(10)
return "%4.4s: %.3f" % (f.__name__, results / 10.0)
if __name__ == "__main__":
print timing(f, 1024, 1024, 400, 75)
#add more here.
|
[
"1. A (smaller) speedup could definitely be the initialization of your rows...\nReplace\nrows = []\nfor i in range(x):\n rows.append([0 for i in xrange(y)])\n\nwith\nrows = [[0] * y for i in xrange(x)]\n\n2. You can also avoid some lookups by moving random.random out of the loops (saves a little).\n3. EDIT: after corrections -- you could arrive at something like this:\ndef f(x,y,n,z):\n rows = [[0] * y for i in xrange(x)]\n rn = random.random\n for i in xrange(n):\n topleft = (int(x*rn()) - z, int(y*rn()) - z)\n l = max(0, topleft[1])\n r = min(topleft[1]+(z*2), y)\n for u in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)):\n rows[u][l:r] = [j+(j<255) for j in rows[u][l:r]]\n\nEDIT: some new timings with timeit (10 runs) -- seems this provides only minor speedups:\nimport timeit\nprint timeit.Timer(\"f1(1024,1024,400,75)\", \"from __main__ import f1\").timeit(10)\nprint timeit.Timer(\"f2(1024,1024,400,75)\", \"from __main__ import f2\").timeit(10)\nprint timeit.Timer(\"f(1024,1024,400,75)\", \"from __main__ import f3\").timeit(10)\n\n\nf1 21.1669280529\nf2 12.9376120567\nf 11.1249599457\n\n",
"On my (slow-ish;-) first-day Macbook Air, 1.6GHz Core 2 Duo, system Python 2.5 on MacOSX 10.5, after saving your code in op.py I see the following timings:\n$ python -mtimeit -s'import op' 'op.f1()'\n10 loops, best of 3: 5.58 sec per loop\n$ python -mtimeit -s'import op' 'op.f2()'\n10 loops, best of 3: 3.15 sec per loop\n\nSo, my machine is slower than yours by a factor of a bit more than 1.9.\nThe fastest code I have for this task is:\ndef f3(x=x,y=y,n=n,z=z):\n rows = [[0]*y for i in range(x)]\n rr = random.randrange\n inc = (1).__add__\n sat = (0xff).__and__\n\n for i in range(n):\n inputX, inputY = rr(x), rr(y)\n b = max(0, inputX - z)\n t = min(inputX + z, x)\n l = max(0, inputY - z)\n r = min(inputY + z, y)\n for i in range(b, t):\n rows[i][l:r] = map(inc, rows[i][l:r])\n for i in range(x):\n rows[i] = map(sat, rows[i])\n\nwhich times as:\n$ python -mtimeit -s'import op' 'op.f3()'\n10 loops, best of 3: 3 sec per loop\n\nso, a very modest speedup, projecting to more than 1.5 seconds on your machine - well above the 1.0 you're aiming for:-(.\nWith a simple C-coded extensions, exte.c...:\n#include \"Python.h\"\n\nstatic PyObject*\ndopoint(PyObject* self, PyObject* args)\n{\n int x, y, z, px, py;\n int b, t, l, r;\n int i, j;\n PyObject* rows;\n\n if(!PyArg_ParseTuple(args, \"iiiiiO\",\n &x, &y, &z, &px, &py, &rows\n ))\n return 0;\n\n b = px - z;\n if (b < 0) b = 0;\n t = px + z;\n if (t > x) t = x;\n l = py - z;\n if (l < 0) l = 0;\n r = py + z;\n if (r > y) r = y;\n\n for(i = b; i < t; ++i) {\n PyObject* row = PyList_GetItem(rows, i);\n for(j = l; j < r; ++j) {\n PyObject* pyitem = PyList_GetItem(row, j);\n long item = PyInt_AsLong(pyitem);\n if (item < 255) {\n PyObject* newitem = PyInt_FromLong(item + 1);\n PyList_SetItem(row, j, newitem);\n }\n }\n }\n\n Py_RETURN_NONE;\n}\n\nstatic PyMethodDef exteMethods[] = {\n {\"dopoint\", dopoint, METH_VARARGS, \"process a point\"},\n {0}\n};\n\nvoid\ninitexte()\n{\n Py_InitModule(\"exte\", exteMethods);\n}\n\n(note: I haven't checked it carefully -- I think it doesn't leak memory due to the correct interplay of reference stealing and borrowing, but it should be code inspected very carefully before being put in production;-), we could do\nimport exte\ndef f4(x=x,y=y,n=n,z=z):\n rows = [[0]*y for i in range(x)]\n rr = random.randrange\n\n for i in range(n):\n inputX, inputY = rr(x), rr(y)\n exte.dopoint(x, y, z, inputX, inputY, rows)\n\nand the timing\n$ python -mtimeit -s'import op' 'op.f4()'\n10 loops, best of 3: 345 msec per loop\n\nshows an acceleration of 8-9 times, which should put you in the ballpark you desire. I've seen a comment saying you don't want any third-party extension, but, well, this tiny extension you could make entirely your own;-). ((Not sure what licensing conditions apply to code on Stack Overflow, but I'll be glad to re-release this under the Apache 2 license or the like, if you need that;-)).\n",
"in your f3 rewrite, g can be simplified. (Can also be applied to f4)\nYou have the following code inside a for loop.\nl = max(0, topleft[1])\nr = min(topleft[1]+(75*2), 1024)\n\nHowever, it appears that those values never change inside the for loop. So calculate them once, outside the loop instead.\n",
"Based on your f3 version I played with the code. As l and r are constants you can avoid to compute them in g1 loop. Also using new ternary if instead of min and max seems to be consistently faster. Also simplified expression with topleft. On my system it appears to be about 20% faster using with the code below.\ndef f3b(x,y,n,z):\n rows = [g1(x, y, z) for x, y in [(int(x*random.random()), int(y*random.random())) for i in range(n)]]\n\ndef g1(x, y, z):\n l = y - z if y - z > 0 else 0\n r = y + z if y + z < 1024 else 1024\n for i in xrange(x - z if x - z > 0 else 0, x + z if x + z < 1024 else 1024 ):\n rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]]\n\n",
"You can create your own Python module in C, and control the performance as you want:\nhttp://docs.python.org/extending/\n"
] |
[
2,
2,
1,
1,
0
] |
[] |
[] |
[
"performance",
"python"
] |
stackoverflow_0002488654_performance_python.txt
|
Q:
python, wrapping class returning the average of the wrapped members
The title isn't very clear but I'll try to explain.
Having this class:
class Wrapped(object):
def method_a(self):
# do some operations
return n
def method_b(self):
# also do some operations
return n
I want to have a class that performs the same way as this one:
class Wrapper(object):
def __init__(self):
self.ws = [Wrapped(1),Wrapped(2),Wrapped(3)]
def method_a(self):
results=[Wrapped.method_a(w) for w in self.ws]
sum_ = sum(results,0.0)
average = sum_/len(self.ws)
return average
def method_b(self):
results=[Wrapped.method_b(w) for w in self.ws]
sum_ = sum(results,0.0)
average = sum_/len(self.ws)
return average
Obviously this is not the actual problem at hand (it is not only two methods), and this code is also incomplete (only included the minimum to explain the problem).
So, what i am looking for is a way to obtain this behavior. Meaning, whichever method is called in the wrapper class, call that method for all the Wrapped class objects and return the average of their results.
Can it be done? How?
Thanks in advance.
Edit
Thanks for the answers... after seeing them the solution it all seems obvious :) I have chosen Alex Martelli's answer because it explained the solution well. The other answers where also useful, that's why I also voted them up.
A:
While quite doable, it's just a little bit tricky because the getting of a method (or other attribute) and the calling thereof are separate operations. Here's a solution:
class Wrapper(object):
def __init__(self):
self.ws = [Wrapped(1),Wrapped(2),Wrapped(3)]
def __getattr__(self, n):
meth = getattr(Wrapped, n)
def caller():
results = [meth(w) for w in self.ws]
sum_ = sum(results,0.0)
average = sum_/len(self.ws)
return average
return caller
It's a bit simplistic (assumes no change in self.ws between the getting and the calling -- one could of course "snapshot" self.ws at the moment of the getting, if that's the desired semantics; doesn't use @functools.wraps so doesn't preserve the docstring &c if those need preserving), but should be mostly workable for your purposes.
A:
You can to this (call an 'arbitary' method on an object) with getattr:
Consider this as example:
# this fetches you references to the 'method_a' methods for objects in self.ws
funcs = [getattr(wrapped_obj, "method_a") for wrapped_obj in self.ws]
# now execute them to get the results
results = [func() for func in funcs]
The rest of your code would stay the same.
A:
You could do this by implementing a __getattr__ method in your Wrapper which returns a function which forwards the call to all wrapped objects. Here's an example of a basic implementation simply returning the results:
import functools
class Wrapper(object):
def __init__(self, *args):
self._targets = args
def _broadcast(self, name, *args, **kwargs):
return [getattr(t, name)(*args, **kwargs) for t in self._targets]
def __getattr__(self, name):
return functools.partial(self._broadcast, name)
Note that __getattr__ will only be called when an attribute is not found, so all method names that you define in Wrapper won't be forwarded (such as _broadcast in above example).
A:
You could do this using the special getattr method.
|
python, wrapping class returning the average of the wrapped members
|
The title isn't very clear but I'll try to explain.
Having this class:
class Wrapped(object):
def method_a(self):
# do some operations
return n
def method_b(self):
# also do some operations
return n
I want to have a class that performs the same way as this one:
class Wrapper(object):
def __init__(self):
self.ws = [Wrapped(1),Wrapped(2),Wrapped(3)]
def method_a(self):
results=[Wrapped.method_a(w) for w in self.ws]
sum_ = sum(results,0.0)
average = sum_/len(self.ws)
return average
def method_b(self):
results=[Wrapped.method_b(w) for w in self.ws]
sum_ = sum(results,0.0)
average = sum_/len(self.ws)
return average
Obviously this is not the actual problem at hand (it is not only two methods), and this code is also incomplete (only included the minimum to explain the problem).
So, what i am looking for is a way to obtain this behavior. Meaning, whichever method is called in the wrapper class, call that method for all the Wrapped class objects and return the average of their results.
Can it be done? How?
Thanks in advance.
Edit
Thanks for the answers... after seeing them the solution it all seems obvious :) I have chosen Alex Martelli's answer because it explained the solution well. The other answers where also useful, that's why I also voted them up.
|
[
"While quite doable, it's just a little bit tricky because the getting of a method (or other attribute) and the calling thereof are separate operations. Here's a solution:\nclass Wrapper(object):\n def __init__(self):\n self.ws = [Wrapped(1),Wrapped(2),Wrapped(3)]\n\n def __getattr__(self, n):\n meth = getattr(Wrapped, n)\n def caller():\n results = [meth(w) for w in self.ws]\n sum_ = sum(results,0.0)\n average = sum_/len(self.ws)\n return average\n return caller\n\nIt's a bit simplistic (assumes no change in self.ws between the getting and the calling -- one could of course \"snapshot\" self.ws at the moment of the getting, if that's the desired semantics; doesn't use @functools.wraps so doesn't preserve the docstring &c if those need preserving), but should be mostly workable for your purposes.\n",
"You can to this (call an 'arbitary' method on an object) with getattr: \nConsider this as example:\n# this fetches you references to the 'method_a' methods for objects in self.ws\nfuncs = [getattr(wrapped_obj, \"method_a\") for wrapped_obj in self.ws]\n# now execute them to get the results\nresults = [func() for func in funcs]\n\nThe rest of your code would stay the same.\n",
"You could do this by implementing a __getattr__ method in your Wrapper which returns a function which forwards the call to all wrapped objects. Here's an example of a basic implementation simply returning the results:\nimport functools\n\nclass Wrapper(object):\n def __init__(self, *args):\n self._targets = args\n\n def _broadcast(self, name, *args, **kwargs):\n return [getattr(t, name)(*args, **kwargs) for t in self._targets]\n\n def __getattr__(self, name):\n return functools.partial(self._broadcast, name)\n\nNote that __getattr__ will only be called when an attribute is not found, so all method names that you define in Wrapper won't be forwarded (such as _broadcast in above example).\n",
"You could do this using the special getattr method.\n"
] |
[
3,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002489133_python.txt
|
Q:
importing same module more than once
So after a few hours, I discovered the cause of a bug in my application. My app's source is structured like:
main/
__init__.py
folderA/
__init__.py
fileA.py
fileB.py
Really, there are about 50 more files. But that's not the point. In main/__init__.py, I have this code: from folderA.fileA import *
in folderA/__init__.py I have this code:
sys.path.append(pathToFolderA)
in folderA/fileB.py I have this code:
from fileA import *
The problem is that fileA gets imported twice. However, I only want to import it once.
The obvious way to fix this (to me atleast) is to change certain paths from path to folderA.path
But I feel like Python should not even have this error in the first place. What other workarounds are there that don't require each file to know its absolute location?
A:
Don't modify sys.path this way, as it provides two ways (names) to access your modules, leading to your problem.
Use absolute or unambiguous-relative imports instead. (The ambiguous-relative imports can be used as a last resort with older Python versions.)
folderA/fileB.py
from main.folderA.fileA import * # absolute
from .fileA import * # unambiguous-relative
from fileA import * # ambiguous-relative
Of course, you should be using specific names in place of that star.
A:
Modifying sys.path isn't something you do in a real program. It hurts modularity and portability with no gain over setting PYTHONPATH permanently or putting your module in a place Python can find it.
Never ever ever ever use import *. It pollutes your namespace and makes your code unpredictable.
You don't want folderA on sys.path. It is a subpackage of main and should always be treated as such. Always use absolute imports going to top-level packages: import main.folderA rather than import folderA or anything else; it will make your code a lot easier to follow and move around and install.
|
importing same module more than once
|
So after a few hours, I discovered the cause of a bug in my application. My app's source is structured like:
main/
__init__.py
folderA/
__init__.py
fileA.py
fileB.py
Really, there are about 50 more files. But that's not the point. In main/__init__.py, I have this code: from folderA.fileA import *
in folderA/__init__.py I have this code:
sys.path.append(pathToFolderA)
in folderA/fileB.py I have this code:
from fileA import *
The problem is that fileA gets imported twice. However, I only want to import it once.
The obvious way to fix this (to me atleast) is to change certain paths from path to folderA.path
But I feel like Python should not even have this error in the first place. What other workarounds are there that don't require each file to know its absolute location?
|
[
"Don't modify sys.path this way, as it provides two ways (names) to access your modules, leading to your problem.\nUse absolute or unambiguous-relative imports instead. (The ambiguous-relative imports can be used as a last resort with older Python versions.)\nfolderA/fileB.py\nfrom main.folderA.fileA import * # absolute\nfrom .fileA import * # unambiguous-relative\nfrom fileA import * # ambiguous-relative\n\nOf course, you should be using specific names in place of that star.\n",
"\nModifying sys.path isn't something you do in a real program. It hurts modularity and portability with no gain over setting PYTHONPATH permanently or putting your module in a place Python can find it.\nNever ever ever ever use import *. It pollutes your namespace and makes your code unpredictable.\nYou don't want folderA on sys.path. It is a subpackage of main and should always be treated as such. Always use absolute imports going to top-level packages: import main.folderA rather than import folderA or anything else; it will make your code a lot easier to follow and move around and install.\n\n"
] |
[
5,
5
] |
[] |
[] |
[
"import",
"import_hooks",
"python"
] |
stackoverflow_0002489601_import_import_hooks_python.txt
|
Q:
python parallel computing: split keyspace to give each node a range to work on
My question is rather complicated for me to explain, as i'm not really good at maths, but i'll try to be as clear as possible.
I'm trying to code a cluster in python, which will generate words given a charset (i.e. with lowercase: aaaa, aaab, aaac, ..., zzzz) and make various operations on them.
I'm searching how to calculate, given the charset and the number of nodes, what range each node should work on (i.e.: node1: aaaa-azzz, node2: baaa-czzz, node3: daaa-ezzz, ...). Is it possible to make an algorithm that could compute this, and if it is, how could i implement this in python?
I really don't know how to do that, so any help would be much appreciated
A:
Any way that you could compute a small integer from the string would be fine for clustering. For example, compute a hash with md5, and look at a byte of it:
import hashlib
s = "aaac"
num_nodes = 5 # or whatever
m = hashlib.md5(s)
node = ord(m.digest()[0]) % num_nodes
print node # prints 2
This won't guarantee to evenly distribute all the strings, but it will be close.
A:
You should be able to treat your words as numerals in a strange base. For example, let's say you have a..z as your charset (26 characters), 4 character strings, and you want to distribute among equally 10 machines. Then there are a total of 26^4 strings, so each machine gets 26^4/10 strings. The first machine will get strings 0 through 26^4/10, the next 26^4/10 through 26^4/5, etc.
To convert the numbers to strings, just write the number in base 26 using your charset as the numbers. So 0 is 'aaaa' and 26^4/10 = 2*26^3 + 15*26^2 + 15*26 +15 is 'cppp'.
|
python parallel computing: split keyspace to give each node a range to work on
|
My question is rather complicated for me to explain, as i'm not really good at maths, but i'll try to be as clear as possible.
I'm trying to code a cluster in python, which will generate words given a charset (i.e. with lowercase: aaaa, aaab, aaac, ..., zzzz) and make various operations on them.
I'm searching how to calculate, given the charset and the number of nodes, what range each node should work on (i.e.: node1: aaaa-azzz, node2: baaa-czzz, node3: daaa-ezzz, ...). Is it possible to make an algorithm that could compute this, and if it is, how could i implement this in python?
I really don't know how to do that, so any help would be much appreciated
|
[
"Any way that you could compute a small integer from the string would be fine for clustering. For example, compute a hash with md5, and look at a byte of it:\nimport hashlib\n\ns = \"aaac\"\nnum_nodes = 5 # or whatever\nm = hashlib.md5(s)\nnode = ord(m.digest()[0]) % num_nodes\n\nprint node # prints 2\n\nThis won't guarantee to evenly distribute all the strings, but it will be close.\n",
"You should be able to treat your words as numerals in a strange base. For example, let's say you have a..z as your charset (26 characters), 4 character strings, and you want to distribute among equally 10 machines. Then there are a total of 26^4 strings, so each machine gets 26^4/10 strings. The first machine will get strings 0 through 26^4/10, the next 26^4/10 through 26^4/5, etc.\nTo convert the numbers to strings, just write the number in base 26 using your charset as the numbers. So 0 is 'aaaa' and 26^4/10 = 2*26^3 + 15*26^2 + 15*26 +15 is 'cppp'.\n"
] |
[
1,
1
] |
[] |
[] |
[
"algorithm",
"character_encoding",
"cluster_analysis",
"python"
] |
stackoverflow_0002488670_algorithm_character_encoding_cluster_analysis_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.