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:
Specified edge lengths on networkx/igraph (Python)
I wanted to visualize a network with the data I have and would like to graph them with specific edge lengths. I use Python, and I've tried networkx and igraph to plot but all seem to assign fixed edge lengths.
a.) I wonder if I did the codes wrong or the packages aren't really capable. How do you properly implement specified edge lengths for networkx or igraph?
b.) If networkx and igraph can't do it, what package could you possibly suggest? (Preferably one that can carry over 80 thousand nodes.)
Thanks!
A:
This should work:
import networkx as NX
import pygraphviz as PG
G = PG.AGraph()
nlist = "A B C D E".split()
a, b = "A A B", "B C D"
elist = zip(a.split(), b.split())
G.add_nodes_from(nlist)
G.add_edges_from(elist)
G.node_attr.update(color="red", style="filled")
G.edge_attr.update(color="blue", len="2.0", width="2.0")
print(G.edge_attr)
# returns {'color': 'red', 'width': '', 'len': '2.0'}
# add new edge with custom length (all others have length=2.0):
G.add_edge("C", "E", len="3.0", color="blue", width="2.0")
edge = G.get_edge("C", "E")
print(edge_attr)
# returns {'color': 'blue', 'width': '2.0', 'len': '3.0'}
# and you can confirm that introspection by drawing & printing this graph:
G.draw('somefolderandfilename.png', format='png', prog='neato')
Most graph drawing algorithms use some version of SMACOF, which of course varies the edge length; however, the graphviz layout engine 'neato' (supplied as the 2nd argument to 'draw' above) ought to preserve, if at all possible, user-set edge lengths.
The library i used here is certainly sturdy enough to handle 80,000 nodes.
|
Specified edge lengths on networkx/igraph (Python)
|
I wanted to visualize a network with the data I have and would like to graph them with specific edge lengths. I use Python, and I've tried networkx and igraph to plot but all seem to assign fixed edge lengths.
a.) I wonder if I did the codes wrong or the packages aren't really capable. How do you properly implement specified edge lengths for networkx or igraph?
b.) If networkx and igraph can't do it, what package could you possibly suggest? (Preferably one that can carry over 80 thousand nodes.)
Thanks!
|
[
"This should work:\nimport networkx as NX\nimport pygraphviz as PG\n\nG = PG.AGraph()\nnlist = \"A B C D E\".split()\na, b = \"A A B\", \"B C D\"\nelist = zip(a.split(), b.split())\n\nG.add_nodes_from(nlist)\nG.add_edges_from(elist)\nG.node_attr.update(color=\"red\", style=\"filled\")\nG.edge_attr.update(color=\"blue\", len=\"2.0\", width=\"2.0\")\n\nprint(G.edge_attr)\n# returns {'color': 'red', 'width': '', 'len': '2.0'}\n\n# add new edge with custom length (all others have length=2.0):\nG.add_edge(\"C\", \"E\", len=\"3.0\", color=\"blue\", width=\"2.0\")\n\nedge = G.get_edge(\"C\", \"E\")\nprint(edge_attr)\n# returns {'color': 'blue', 'width': '2.0', 'len': '3.0'}\n\n# and you can confirm that introspection by drawing & printing this graph:\nG.draw('somefolderandfilename.png', format='png', prog='neato')\n\nMost graph drawing algorithms use some version of SMACOF, which of course varies the edge length; however, the graphviz layout engine 'neato' (supplied as the 2nd argument to 'draw' above) ought to preserve, if at all possible, user-set edge lengths.\nThe library i used here is certainly sturdy enough to handle 80,000 nodes. \n"
] |
[
8
] |
[] |
[] |
[
"graphviz",
"igraph",
"networkx",
"python"
] |
stackoverflow_0001851296_graphviz_igraph_networkx_python.txt
|
Q:
Twisted ignoring data sent from MUD Clients?
I have the following code (almost an exact copy of the Chat server example listed here:
import twisted.scripts.twistd
from twisted.protocols import basic
from twisted.internet import protocol, reactor
from twisted.application import service, internet
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
if __name__ == "__main__":
print "Building reactor...."
reactor.listenTCP(50000, factory)
print "Running ractor...."
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(50000, factory).setServiceParent(application)
The server runs without error, and if I connect to it via Telnet, I can send data and the server prints to the console and relays it to all clients (as is expected). However, if I connect to it via a different tool (a MUD client), it never gets the data.
I have ensured that the client is sending the data (Traced the packets with Wireshark, and they're going across the wire), but the server either never receives it, or is choosing to ignore it for some reason.
I have tried this with two MUD clients, gmud, and JMC. If it is important, I am running Windows 7 x64.
Does anyone have any idea why this could be happening?
Thanks,
Mike
EDIT:
Thanks to the hints provided by Maiku Mori, I tried adding another method that was specified in the Twisted API Docs, dataReceived. Once this was added, the MUD clients worked perfectly, but Telnet is now sending every character as it's own set of data, instead of waiting for the user to press Enter.
Here's a snipped of the new code:
def dataReceived(self, data):
print "Dreceived", repr(data)
for c in self.factory.clients:
c.message(data)
# def lineReceived(self, line):
# print "received", repr(line)
# for c in self.factory.clients:
# c.message(line)
Has anyone experiences this before, and if so, how do you get around it? Ideally, I would like Telnet and MUD clients to work with this application.
Thanks again.
A:
In case anyone stumbles across this question with similar problems, I'm leaving my findings as the accepted answer so that people don't have to hunt the way I did.
I fixed the issue by changing the delimiter value from in my Twisted protocol from "\r\n" (default), to just "\n" (which is what my MUD clients send. This means that in Telnet, when you enter the string:
Hello, World
Your application will receive it as:
Hello, World\r
You may need to do data sanitation on the server side to keep things in order. My final code was as follows:
import twisted.scripts.twistd
from twisted.protocols import basic
from twisted.internet import protocol, reactor
from twisted.application import service, internet
class MyChat(basic.LineReceiver):
def __init__(self):
self.delimiter = "\n"
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
if __name__ == "__main__":
print "Building reactor...."
reactor.listenTCP(50000, factory)
print "Running ractor...."
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(50000, factory).setServiceParent(application)
Thanks for all the help.
A:
Are you sure that the MUD clients send line ending chars after each line? The lineReceived will only be called after line ending char has been sent.
EDIT:
Here I found API docs for LineReceiver. You could play around with dataReceived method to see if you are actually getting any kind of data. If I recall you can use it just like lineReceived.
|
Twisted ignoring data sent from MUD Clients?
|
I have the following code (almost an exact copy of the Chat server example listed here:
import twisted.scripts.twistd
from twisted.protocols import basic
from twisted.internet import protocol, reactor
from twisted.application import service, internet
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
if __name__ == "__main__":
print "Building reactor...."
reactor.listenTCP(50000, factory)
print "Running ractor...."
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(50000, factory).setServiceParent(application)
The server runs without error, and if I connect to it via Telnet, I can send data and the server prints to the console and relays it to all clients (as is expected). However, if I connect to it via a different tool (a MUD client), it never gets the data.
I have ensured that the client is sending the data (Traced the packets with Wireshark, and they're going across the wire), but the server either never receives it, or is choosing to ignore it for some reason.
I have tried this with two MUD clients, gmud, and JMC. If it is important, I am running Windows 7 x64.
Does anyone have any idea why this could be happening?
Thanks,
Mike
EDIT:
Thanks to the hints provided by Maiku Mori, I tried adding another method that was specified in the Twisted API Docs, dataReceived. Once this was added, the MUD clients worked perfectly, but Telnet is now sending every character as it's own set of data, instead of waiting for the user to press Enter.
Here's a snipped of the new code:
def dataReceived(self, data):
print "Dreceived", repr(data)
for c in self.factory.clients:
c.message(data)
# def lineReceived(self, line):
# print "received", repr(line)
# for c in self.factory.clients:
# c.message(line)
Has anyone experiences this before, and if so, how do you get around it? Ideally, I would like Telnet and MUD clients to work with this application.
Thanks again.
|
[
"In case anyone stumbles across this question with similar problems, I'm leaving my findings as the accepted answer so that people don't have to hunt the way I did.\nI fixed the issue by changing the delimiter value from in my Twisted protocol from \"\\r\\n\" (default), to just \"\\n\" (which is what my MUD clients send. This means that in Telnet, when you enter the string:\nHello, World\n\nYour application will receive it as:\nHello, World\\r\n\nYou may need to do data sanitation on the server side to keep things in order. My final code was as follows:\nimport twisted.scripts.twistd\nfrom twisted.protocols import basic\nfrom twisted.internet import protocol, reactor\nfrom twisted.application import service, internet\nclass MyChat(basic.LineReceiver):\n def __init__(self):\n self.delimiter = \"\\n\"\n\n def connectionMade(self):\n print \"Got new client!\"\n self.factory.clients.append(self)\n\n def connectionLost(self, reason):\n print \"Lost a client!\"\n self.factory.clients.remove(self)\n\n def lineReceived(self, line):\n print \"received\", repr(line)\n for c in self.factory.clients:\n c.message(line)\n\n def message(self, message):\n self.transport.write(message + '\\n')\n\nfactory = protocol.ServerFactory()\nfactory.protocol = MyChat\nfactory.clients = []\n\nif __name__ == \"__main__\":\n print \"Building reactor....\"\n reactor.listenTCP(50000, factory)\n print \"Running ractor....\"\n reactor.run()\nelse:\n application = service.Application(\"chatserver\")\n internet.TCPServer(50000, factory).setServiceParent(application)\n\nThanks for all the help.\n",
"Are you sure that the MUD clients send line ending chars after each line? The lineReceived will only be called after line ending char has been sent.\nEDIT:\nHere I found API docs for LineReceiver. You could play around with dataReceived method to see if you are actually getting any kind of data. If I recall you can use it just like lineReceived.\n"
] |
[
3,
1
] |
[] |
[] |
[
"networking",
"python",
"sockets",
"tcp",
"twisted"
] |
stackoverflow_0001898411_networking_python_sockets_tcp_twisted.txt
|
Q:
Problem opening registry key on Windows 7
This code used to work on Vista (and Windows XP) but after an upgrade to Windows 7 it now fails with the error shown:
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
>>> import _winreg
>>> h1 = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
>>> key = r'SOFTWARE\Python\PythonCore\2.6\InstallPath'
>>> h2 = _winreg.OpenKey(h1, key, 0, _winreg.KEY_ALL_ACCESS)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 5] Access is denied
I'm fairly sure this is the result of changes in the security model in Windows 7, but various searches I tried have turned up nothing I can use as an answer so far.
(Not that it should be relevant, but to stave off "why would you do that?" responses, this is for a developer's utility which can switch the registry between multiple installations of Python, for use in a multi-project environment where we need more control over which version of Python is in use, and what packages are available, than things like virtualenv can provide.)
Edit: The logged-in user is an Administrator. Also, I've turned off the UAC (User Access Control) stuff as completely as one can (not true... see next edit), as was previously the case before the upgrade from Vista to Windows 7.
Edit 2: As noted in my own answer below, I hadn't rebooted after turning off UAC, so it was still set to the default. Apparently this results in the Access denied error (as I confirmed by testing with UAC set to Default and to Never).
A:
This was a user mistake, compounded or triggered by changes in Windows 7 to how the UAC feature is implemented.
In Vista, the much-detested User Access Control feature was binary, either on or off. On Windows 7 that has been changed to provide four levels of granularity:
Always Notify (when either programs or user tries to change settings)
Default (notify only when programs try to make changes, and dim screen)
Notify without dimming (same as default but don't dim screen when notifying)
Never notify (for either programs or user changes)
My mistake was in not rebooting after dropping the UAC feature down to the Never Notify level. (Vista was aggressive about requesting that you reboot, while Windows 7 seems to be slightly more passive.)
A:
I think you have an access right problem.
Try to open the key with a less demanding access right (e.g. KEY_QUERY_VALUE) and check if it works.
Of course, with that change you will not be able to change the registry, but it would be only for pinpointing the issue.
As an alternative, try to execute the utility from a user with higher privileges - and by the way this would be the only solution I could see for a problem involving access rights.
|
Problem opening registry key on Windows 7
|
This code used to work on Vista (and Windows XP) but after an upgrade to Windows 7 it now fails with the error shown:
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
>>> import _winreg
>>> h1 = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
>>> key = r'SOFTWARE\Python\PythonCore\2.6\InstallPath'
>>> h2 = _winreg.OpenKey(h1, key, 0, _winreg.KEY_ALL_ACCESS)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 5] Access is denied
I'm fairly sure this is the result of changes in the security model in Windows 7, but various searches I tried have turned up nothing I can use as an answer so far.
(Not that it should be relevant, but to stave off "why would you do that?" responses, this is for a developer's utility which can switch the registry between multiple installations of Python, for use in a multi-project environment where we need more control over which version of Python is in use, and what packages are available, than things like virtualenv can provide.)
Edit: The logged-in user is an Administrator. Also, I've turned off the UAC (User Access Control) stuff as completely as one can (not true... see next edit), as was previously the case before the upgrade from Vista to Windows 7.
Edit 2: As noted in my own answer below, I hadn't rebooted after turning off UAC, so it was still set to the default. Apparently this results in the Access denied error (as I confirmed by testing with UAC set to Default and to Never).
|
[
"This was a user mistake, compounded or triggered by changes in Windows 7 to how the UAC feature is implemented. \nIn Vista, the much-detested User Access Control feature was binary, either on or off. On Windows 7 that has been changed to provide four levels of granularity:\n\nAlways Notify (when either programs or user tries to change settings)\nDefault (notify only when programs try to make changes, and dim screen)\nNotify without dimming (same as default but don't dim screen when notifying) \nNever notify (for either programs or user changes)\n\nMy mistake was in not rebooting after dropping the UAC feature down to the Never Notify level. (Vista was aggressive about requesting that you reboot, while Windows 7 seems to be slightly more passive.)\n",
"I think you have an access right problem.\nTry to open the key with a less demanding access right (e.g. KEY_QUERY_VALUE) and check if it works.\nOf course, with that change you will not be able to change the registry, but it would be only for pinpointing the issue.\nAs an alternative, try to execute the utility from a user with higher privileges - and by the way this would be the only solution I could see for a problem involving access rights.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"registry",
"windows_7"
] |
stackoverflow_0001897324_python_registry_windows_7.txt
|
Q:
Using Python Yacc\Lex as a formula parser
At the moment i'm working on using the python implementation of Yacc/Lex to build a formula parser for converting strings of formulae into a set of class defined operands. So far i've been mostly successful but i've come to an empasse in defining the parsing rules due to ambiguity with parentheses and several shift/reduce errors.
The Backus Naur Form for the formulae ive been working on is
phi ::= p ; !p ; phi_0 & phi_1 ; phi_0 | phi_1 ; AX phi ; AF phi ; AG phi ; AU phi_0 U phi_1.
Also i've been trying to allow arbitrary matched parentheses but this is also where a lot of the confusion is coming from and i'm thinking where the shift reduce errors are coming from. Its fairly necessary for the task i'm applying it to that parentheses are there to force specific evaluations on formulas, so I have to work that out.
Currently my parser is defined inside a class which builds its lexical analyser with
tokens = (
'NEGATION',
'FUTURE',
'GLOBAL',
'NEXT',
'CONJUNCTION',
'DISJUNCTION',
'EQUIVALENCE',
'IMPLICATION',
'PROPOSITION',
'LPAREN',
'RPAREN',
'TRUE',
'FALSE',
)
# regex in order of parsing precedence
t_NEGATION = r'[\s]*\![\s]*'
t_FUTURE = r'[\s]*AF[\s]*'
t_GLOBAL = r'[\s]*AG[\s]*'
t_NEXT = r'[\s]*AX[\s]*'
t_CONJUNCTION = r'[\s]*\&[\s]*'
t_DISJUNCTION = r'[\s]*\|[\s]*'
t_EQUIVALENCE = r'[\s]*\<\-\>[\s]*'
t_IMPLICATION = r'[\s]*[^<]\-\>[\s]*'
t_LPAREN = r'[\s]*\([\s]*'
t_RPAREN = r'[\s]*\)[\s]*'
t_PROPOSITION = r'[\s]*[a-z]+[-\w\._]*[\s]*'
t_TRUE = r'[\s]*TRUE[\s]*'
t_FALSE = r'[\s]*FALSE[\s]*'
precedence = (
('left', 'ASSIGNMENT'),
('left', 'NEGATION'),
('left', 'GLOBAL','NEXT','FUTURE'),
('left', 'CONJUNCTION'),
('left', 'DISJUNCTION'),
('left', 'EQUIVALENCE'),
('left', 'IMPLICATION'),
('left', 'AUB', 'AUM'),
('left', 'LPAREN', 'RPAREN', 'TRUE', 'FALSE'),
)
lexer = lex.lex()
lexer.input(formula)
And the parsing rules as
def p_double_neg_paren(p):
'''formula : NEGATION LPAREN NEGATION LPAREN PROPOSITION RPAREN RPAREN
'''
stack.append(p[5].strip())
def p_double_neg(p):
'''formula : NEGATION NEGATION PROPOSITION
'''
stack.append(p[3].strip())
def p_double_neg_inner_paren(p):
'''formula : NEGATION NEGATION LPAREN PROPOSITION RPAREN
'''
stack.append(p[4].strip())
def p_double_neg_mid_paren(p):
'''formula : NEGATION LPAREN NEGATION PROPOSITION RPAREN
'''
stack.append(p[4].strip())
def p_groupAssignment(p):
'''formula : PROPOSITION ASSIGNMENT ASSIGNVAL
'''
stack.append(p[1].strip() + p[2].strip() + p[3].strip())
def p_neg_paren_take_outer_token(p):
'''formula : NEGATION LPAREN PROPOSITION RPAREN
| NEGATION LPAREN TRUE RPAREN
| NEGATION LPAREN FALSE RPAREN
'''
stack.append(Neg(p[3]))
def p_neg_take_outer_token(p):
'''formula : NEGATION PROPOSITION
| NEGATION TRUE
| NEGATION FALSE
'''
stack.append(Neg(p[2].strip()))
def p_neg_take_outer_token_paren(p):
'''formula : LPAREN NEGATION PROPOSITION RPAREN
| LPAREN NEGATION TRUE RPAREN
| LPAREN NEGATION FALSE RPAREN
'''
stack.append(Neg(p[3].strip()))
def p_unary_paren_nest_take_outer_token(p):
'''formula : GLOBAL LPAREN LPAREN NEGATION formula RPAREN RPAREN
| NEXT LPAREN LPAREN NEGATION formula RPAREN RPAREN
| FUTURE LPAREN LPAREN NEGATION formula RPAREN RPAREN
'''
if len(stack) >= 1:
if p[1].strip() == 'AG':
stack.append(['AG', ['!', stack.pop()]])
elif p[1].strip() == 'AF':
stack.append(['AF', ['!', stack.pop()]])
elif p[1].strip() == 'AX':
stack.append(['AX', ['!', stack.pop()]])
def p_unary_paren_take_outer_token(p):
'''formula : GLOBAL LPAREN formula RPAREN
| NEXT LPAREN formula RPAREN
| FUTURE LPAREN formula RPAREN
'''
if len(stack) >= 1:
if p[1].strip() == "AG":
stack.append(AG(stack.pop()))
elif p[1].strip() == "AF":
stack.append(AF(stack.pop()))
elif p[1].strip() == "AX":
stack.append(AX(stack.pop()))
def p_unary_take_outer_token(p):
'''formula : GLOBAL formula
| NEXT formula
| FUTURE formula
'''
if len(stack) >= 1:
if p[1].strip() == "AG":
stack.append(AG(stack.pop()))
elif p[1].strip() == "AF":
stack.append(AF(stack.pop()))
elif p[1].strip() == "AX":
stack.append(AX(stack.pop()))
def p_unary_take_outer_token_prop(p):
'''formula : GLOBAL PROPOSITION
| NEXT PROPOSITION
| FUTURE PROPOSITION
'''
if len(stack) >= 1:
if p[1].strip() == "AG":
stack.append(AG(stack.pop()))
elif p[1].strip() == "AF":
stack.append(AF(stack.pop()))
elif p[1].strip() == "AX":
stack.append(AX(stack.pop()))
def p_binary_take_outer_token(p):
'''formula : formula CONJUNCTION formula
| formula DISJUNCTION formula
| formula EQUIVALENCE formula
| formula IMPLICATION formula
'''
if len(stack) >= 2:
a, b = stack.pop(), stack.pop()
if self.IMPLICATION.search(p[2].strip()) and not self.EQUIVALENCE.search(p[2].strip()):
stack.append(Or(a, Neg(b)))
elif self.EQUIVALENCE.search(p[2].strip()):
stack.append(And(Or(Neg(a), b), Or(Neg(b), a)))
else:
if p[2].strip() == "|":
stack.append(Or(b, a))
elif p[2].strip() == "&":
stack.append(And(b, a))
def p_binary_paren_take_outer_token(p):
'''formula : LPAREN formula RPAREN CONJUNCTION LPAREN formula RPAREN
| LPAREN formula RPAREN DISJUNCTION LPAREN formula RPAREN
| LPAREN formula RPAREN EQUIVALENCE LPAREN formula RPAREN
| LPAREN formula RPAREN IMPLICATION LPAREN formula RPAREN
'''
if len(stack) >= 2:
a, b = stack.pop(), stack.pop()
if self.IMPLICATION.search(p[4].strip()) and not self.EQUIVALENCE.search(p[4].strip()):
stack.append(Or(a, Neg(b)))
elif self.EQUIVALENCE.search(p[4].strip()):
stack.append(And(Or(Neg(a), b), Or(Neg(b), a)))
else:
if p[4].strip() == "|":
stack.append(Or(b, a))
elif p[4].strip() == "&":
stack.append(And(b, a))
def p_binary_lparen_take_outer_token(p):
'''formula : LPAREN formula RPAREN CONJUNCTION formula
| LPAREN formula RPAREN DISJUNCTION formula
| LPAREN formula RPAREN EQUIVALENCE formula
| LPAREN formula RPAREN IMPLICATION formula
'''
if len(stack) >= 2:
a = stack.pop()
b = stack.pop()
if self.IMPLICATION.search(p[4].strip()) and not self.EQUIVALENCE.search(p[4].strip()):
stack.append(Or(a, Neg(b)))
elif self.EQUIVALENCE.search(p[4].strip()):
stack.append(And(Or(Neg(a), b), Or(Neg(b), a)))
else:
if p[4].strip() == "|":
stack.append(Or(b, a))
elif p[4].strip() == "&":
stack.append(And(b, a))
def p_binary_rparen_take_outer_token(p):
'''formula : formula CONJUNCTION LPAREN formula RPAREN
| formula DISJUNCTION LPAREN formula RPAREN
| formula EQUIVALENCE LPAREN formula RPAREN
| formula IMPLICATION LPAREN formula RPAREN
'''
if len(stack) >= 2:
a = stack.pop()
b = stack.pop()
if self.IMPLICATION.search(p[4].strip()) and not self.EQUIVALENCE.search(p[4].strip()):
stack.append(Or(a, Neg(b)))
elif self.EQUIVALENCE.search(p[4].strip()):
stack.append(And(Or(Neg(a), b), Or(Neg(b), a)))
else:
if p[4].strip() == "|":
stack.append(Or(b, a))
elif p[4].strip() == "&":
stack.append(And(b, a))
def p_proposition_take_token_paren(p):
'''formula : LPAREN formula RPAREN
'''
stack.append(p[2].strip())
def p_proposition_take_token_atom(p):
'''formula : LPAREN PROPOSITION RPAREN
'''
stack.append(p[2].strip())
def p_proposition_take_token(p):
'''formula : PROPOSITION
'''
stack.append(p[1].strip())
def p_true_take_token(p):
'''formula : TRUE
'''
stack.append(p[1].strip())
def p_false_take_token(p):
'''formula : FALSE
'''
stack.append(p[1].strip())
# Error rule for syntax errors
def p_error(p):
print "Syntax error in input!: " + str(p)
os.system("pause")
return 0
I can see the lex\yacc rules are fairly messy, i've removed much of the debugging code in each rule for brevity and tidiness but can anyone see where i'm going wrong here? Should I move handling of parentheses to another method or can it be done with what I have now? Is there some other way I can process these formula strings into the predefined class operations without getting all the shift/reduce errors?
Sorry for airing all my dirty code online but I could really use some help on something thats been bugging me for months. Thanks.
A:
START SMALL!!! Regardless of the parser library you end up using, try doing just a simple binary operation like expr & expr, and get that working. Then add support for '|'. Now you have two different operators, and you have enough to represent precedence of operations, and parentheses actually play a part. This BNF would look something like:
atom := TRUE | FALSE | '(' expr ')'
and_op := atom '&' atom
or_op := and_op '|' and_op
expr = or_op
Do you see how this works? No explicit "take left paren", "pop right paren" stuff. Figure out what your precedence of your other operations is going to be, and then extend this recursive infix notation parser to reflect them. But DON'T DO ANYTHING ELSE until you get this minimal bit working first. Otherwise, you are just trying to solve too much at once.
A:
Parsers are frustrating, and your notation is a non-trivial one. Creating a parser for infix notation takes a certain mind set. But if this is a core part of your system, you'll have to get it working some time. I'm not sure what was your confusion with lepl, I believe it is fairly similar in concept to pyparsing. In the spirit of SO, maybe I can post a pyparsing starter for you.
Your BNF didn't really match your lexing code, as your code includes references to '<->', and '->' operators, an assignment statement, and a proposition which I assume is basically a lowercase identifier. I looked for an online reference for this language, but didn't find one. Also, you didn't post any test cases. So I took a best guess at what your language BNF is supposed to be.
"""
phi ::= p
!p
phi_0 & phi_1
phi_0 | phi_1
AX phi
AF phi
AG phi
AU phi_0 U phi_1
"""
from pyparsing import *
LPAR,RPAR = map(Suppress,"()")
NOT = Literal("!")
TRUE = Keyword("TRUE")
FALSE = Keyword("FALSE")
AX, AF, AG, AU, U = map(Keyword, "AX AF AG AU U".split())
AND_OP = "&"
OR_OP = "|"
ident = Word(alphas.lower())
phi = Forward()
p = Optional(NOT) + (TRUE | FALSE | ident | Group(LPAR + phi + RPAR) )
binand = p + ZeroOrMore(AND_OP + p)
binor = binand + ZeroOrMore(OR_OP + binand)
phi << (
Group(AX + phi) |
Group(AF + phi) |
Group(AG + phi) |
Group(AU + phi + U + phi) |
binor)
assign = ident + "=" + Group(phi)
equiv = Group(phi) + "<->" + Group(phi)
implicate = Group(phi) + "->" + Group(phi)
statement = assign | equiv | implicate
tests = """\
a=TRUE
b = FALSE
c = !TRUE
d <-> b & !c
AG b & d -> !e""".splitlines()
for t in tests:
print statement.parseString(t).asList()
Prints:
['a', '=', ['TRUE']]
['b', '=', ['FALSE']]
['c', '=', ['!', 'TRUE']]
[['d'], '<->', ['b', '&', '!', 'c']]
[[['AG', 'b', '&', 'd']], '->', ['!', 'e']]
The Group classes help structure the results into a quasi-AST. There are a number of examples on the pyparsing wiki that will help you take it from here. I would recommend looking at the simpleBool.py example on how to have the parser produce an evaluator.
|
Using Python Yacc\Lex as a formula parser
|
At the moment i'm working on using the python implementation of Yacc/Lex to build a formula parser for converting strings of formulae into a set of class defined operands. So far i've been mostly successful but i've come to an empasse in defining the parsing rules due to ambiguity with parentheses and several shift/reduce errors.
The Backus Naur Form for the formulae ive been working on is
phi ::= p ; !p ; phi_0 & phi_1 ; phi_0 | phi_1 ; AX phi ; AF phi ; AG phi ; AU phi_0 U phi_1.
Also i've been trying to allow arbitrary matched parentheses but this is also where a lot of the confusion is coming from and i'm thinking where the shift reduce errors are coming from. Its fairly necessary for the task i'm applying it to that parentheses are there to force specific evaluations on formulas, so I have to work that out.
Currently my parser is defined inside a class which builds its lexical analyser with
tokens = (
'NEGATION',
'FUTURE',
'GLOBAL',
'NEXT',
'CONJUNCTION',
'DISJUNCTION',
'EQUIVALENCE',
'IMPLICATION',
'PROPOSITION',
'LPAREN',
'RPAREN',
'TRUE',
'FALSE',
)
# regex in order of parsing precedence
t_NEGATION = r'[\s]*\![\s]*'
t_FUTURE = r'[\s]*AF[\s]*'
t_GLOBAL = r'[\s]*AG[\s]*'
t_NEXT = r'[\s]*AX[\s]*'
t_CONJUNCTION = r'[\s]*\&[\s]*'
t_DISJUNCTION = r'[\s]*\|[\s]*'
t_EQUIVALENCE = r'[\s]*\<\-\>[\s]*'
t_IMPLICATION = r'[\s]*[^<]\-\>[\s]*'
t_LPAREN = r'[\s]*\([\s]*'
t_RPAREN = r'[\s]*\)[\s]*'
t_PROPOSITION = r'[\s]*[a-z]+[-\w\._]*[\s]*'
t_TRUE = r'[\s]*TRUE[\s]*'
t_FALSE = r'[\s]*FALSE[\s]*'
precedence = (
('left', 'ASSIGNMENT'),
('left', 'NEGATION'),
('left', 'GLOBAL','NEXT','FUTURE'),
('left', 'CONJUNCTION'),
('left', 'DISJUNCTION'),
('left', 'EQUIVALENCE'),
('left', 'IMPLICATION'),
('left', 'AUB', 'AUM'),
('left', 'LPAREN', 'RPAREN', 'TRUE', 'FALSE'),
)
lexer = lex.lex()
lexer.input(formula)
And the parsing rules as
def p_double_neg_paren(p):
'''formula : NEGATION LPAREN NEGATION LPAREN PROPOSITION RPAREN RPAREN
'''
stack.append(p[5].strip())
def p_double_neg(p):
'''formula : NEGATION NEGATION PROPOSITION
'''
stack.append(p[3].strip())
def p_double_neg_inner_paren(p):
'''formula : NEGATION NEGATION LPAREN PROPOSITION RPAREN
'''
stack.append(p[4].strip())
def p_double_neg_mid_paren(p):
'''formula : NEGATION LPAREN NEGATION PROPOSITION RPAREN
'''
stack.append(p[4].strip())
def p_groupAssignment(p):
'''formula : PROPOSITION ASSIGNMENT ASSIGNVAL
'''
stack.append(p[1].strip() + p[2].strip() + p[3].strip())
def p_neg_paren_take_outer_token(p):
'''formula : NEGATION LPAREN PROPOSITION RPAREN
| NEGATION LPAREN TRUE RPAREN
| NEGATION LPAREN FALSE RPAREN
'''
stack.append(Neg(p[3]))
def p_neg_take_outer_token(p):
'''formula : NEGATION PROPOSITION
| NEGATION TRUE
| NEGATION FALSE
'''
stack.append(Neg(p[2].strip()))
def p_neg_take_outer_token_paren(p):
'''formula : LPAREN NEGATION PROPOSITION RPAREN
| LPAREN NEGATION TRUE RPAREN
| LPAREN NEGATION FALSE RPAREN
'''
stack.append(Neg(p[3].strip()))
def p_unary_paren_nest_take_outer_token(p):
'''formula : GLOBAL LPAREN LPAREN NEGATION formula RPAREN RPAREN
| NEXT LPAREN LPAREN NEGATION formula RPAREN RPAREN
| FUTURE LPAREN LPAREN NEGATION formula RPAREN RPAREN
'''
if len(stack) >= 1:
if p[1].strip() == 'AG':
stack.append(['AG', ['!', stack.pop()]])
elif p[1].strip() == 'AF':
stack.append(['AF', ['!', stack.pop()]])
elif p[1].strip() == 'AX':
stack.append(['AX', ['!', stack.pop()]])
def p_unary_paren_take_outer_token(p):
'''formula : GLOBAL LPAREN formula RPAREN
| NEXT LPAREN formula RPAREN
| FUTURE LPAREN formula RPAREN
'''
if len(stack) >= 1:
if p[1].strip() == "AG":
stack.append(AG(stack.pop()))
elif p[1].strip() == "AF":
stack.append(AF(stack.pop()))
elif p[1].strip() == "AX":
stack.append(AX(stack.pop()))
def p_unary_take_outer_token(p):
'''formula : GLOBAL formula
| NEXT formula
| FUTURE formula
'''
if len(stack) >= 1:
if p[1].strip() == "AG":
stack.append(AG(stack.pop()))
elif p[1].strip() == "AF":
stack.append(AF(stack.pop()))
elif p[1].strip() == "AX":
stack.append(AX(stack.pop()))
def p_unary_take_outer_token_prop(p):
'''formula : GLOBAL PROPOSITION
| NEXT PROPOSITION
| FUTURE PROPOSITION
'''
if len(stack) >= 1:
if p[1].strip() == "AG":
stack.append(AG(stack.pop()))
elif p[1].strip() == "AF":
stack.append(AF(stack.pop()))
elif p[1].strip() == "AX":
stack.append(AX(stack.pop()))
def p_binary_take_outer_token(p):
'''formula : formula CONJUNCTION formula
| formula DISJUNCTION formula
| formula EQUIVALENCE formula
| formula IMPLICATION formula
'''
if len(stack) >= 2:
a, b = stack.pop(), stack.pop()
if self.IMPLICATION.search(p[2].strip()) and not self.EQUIVALENCE.search(p[2].strip()):
stack.append(Or(a, Neg(b)))
elif self.EQUIVALENCE.search(p[2].strip()):
stack.append(And(Or(Neg(a), b), Or(Neg(b), a)))
else:
if p[2].strip() == "|":
stack.append(Or(b, a))
elif p[2].strip() == "&":
stack.append(And(b, a))
def p_binary_paren_take_outer_token(p):
'''formula : LPAREN formula RPAREN CONJUNCTION LPAREN formula RPAREN
| LPAREN formula RPAREN DISJUNCTION LPAREN formula RPAREN
| LPAREN formula RPAREN EQUIVALENCE LPAREN formula RPAREN
| LPAREN formula RPAREN IMPLICATION LPAREN formula RPAREN
'''
if len(stack) >= 2:
a, b = stack.pop(), stack.pop()
if self.IMPLICATION.search(p[4].strip()) and not self.EQUIVALENCE.search(p[4].strip()):
stack.append(Or(a, Neg(b)))
elif self.EQUIVALENCE.search(p[4].strip()):
stack.append(And(Or(Neg(a), b), Or(Neg(b), a)))
else:
if p[4].strip() == "|":
stack.append(Or(b, a))
elif p[4].strip() == "&":
stack.append(And(b, a))
def p_binary_lparen_take_outer_token(p):
'''formula : LPAREN formula RPAREN CONJUNCTION formula
| LPAREN formula RPAREN DISJUNCTION formula
| LPAREN formula RPAREN EQUIVALENCE formula
| LPAREN formula RPAREN IMPLICATION formula
'''
if len(stack) >= 2:
a = stack.pop()
b = stack.pop()
if self.IMPLICATION.search(p[4].strip()) and not self.EQUIVALENCE.search(p[4].strip()):
stack.append(Or(a, Neg(b)))
elif self.EQUIVALENCE.search(p[4].strip()):
stack.append(And(Or(Neg(a), b), Or(Neg(b), a)))
else:
if p[4].strip() == "|":
stack.append(Or(b, a))
elif p[4].strip() == "&":
stack.append(And(b, a))
def p_binary_rparen_take_outer_token(p):
'''formula : formula CONJUNCTION LPAREN formula RPAREN
| formula DISJUNCTION LPAREN formula RPAREN
| formula EQUIVALENCE LPAREN formula RPAREN
| formula IMPLICATION LPAREN formula RPAREN
'''
if len(stack) >= 2:
a = stack.pop()
b = stack.pop()
if self.IMPLICATION.search(p[4].strip()) and not self.EQUIVALENCE.search(p[4].strip()):
stack.append(Or(a, Neg(b)))
elif self.EQUIVALENCE.search(p[4].strip()):
stack.append(And(Or(Neg(a), b), Or(Neg(b), a)))
else:
if p[4].strip() == "|":
stack.append(Or(b, a))
elif p[4].strip() == "&":
stack.append(And(b, a))
def p_proposition_take_token_paren(p):
'''formula : LPAREN formula RPAREN
'''
stack.append(p[2].strip())
def p_proposition_take_token_atom(p):
'''formula : LPAREN PROPOSITION RPAREN
'''
stack.append(p[2].strip())
def p_proposition_take_token(p):
'''formula : PROPOSITION
'''
stack.append(p[1].strip())
def p_true_take_token(p):
'''formula : TRUE
'''
stack.append(p[1].strip())
def p_false_take_token(p):
'''formula : FALSE
'''
stack.append(p[1].strip())
# Error rule for syntax errors
def p_error(p):
print "Syntax error in input!: " + str(p)
os.system("pause")
return 0
I can see the lex\yacc rules are fairly messy, i've removed much of the debugging code in each rule for brevity and tidiness but can anyone see where i'm going wrong here? Should I move handling of parentheses to another method or can it be done with what I have now? Is there some other way I can process these formula strings into the predefined class operations without getting all the shift/reduce errors?
Sorry for airing all my dirty code online but I could really use some help on something thats been bugging me for months. Thanks.
|
[
"START SMALL!!! Regardless of the parser library you end up using, try doing just a simple binary operation like expr & expr, and get that working. Then add support for '|'. Now you have two different operators, and you have enough to represent precedence of operations, and parentheses actually play a part. This BNF would look something like:\natom := TRUE | FALSE | '(' expr ')'\nand_op := atom '&' atom\nor_op := and_op '|' and_op\nexpr = or_op\n\nDo you see how this works? No explicit \"take left paren\", \"pop right paren\" stuff. Figure out what your precedence of your other operations is going to be, and then extend this recursive infix notation parser to reflect them. But DON'T DO ANYTHING ELSE until you get this minimal bit working first. Otherwise, you are just trying to solve too much at once.\n",
"Parsers are frustrating, and your notation is a non-trivial one. Creating a parser for infix notation takes a certain mind set. But if this is a core part of your system, you'll have to get it working some time. I'm not sure what was your confusion with lepl, I believe it is fairly similar in concept to pyparsing. In the spirit of SO, maybe I can post a pyparsing starter for you.\nYour BNF didn't really match your lexing code, as your code includes references to '<->', and '->' operators, an assignment statement, and a proposition which I assume is basically a lowercase identifier. I looked for an online reference for this language, but didn't find one. Also, you didn't post any test cases. So I took a best guess at what your language BNF is supposed to be.\n\"\"\"\nphi ::= p \n !p \n phi_0 & phi_1 \n phi_0 | phi_1 \n AX phi \n AF phi \n AG phi \n AU phi_0 U phi_1\n\"\"\"\n\nfrom pyparsing import *\n\nLPAR,RPAR = map(Suppress,\"()\")\nNOT = Literal(\"!\")\nTRUE = Keyword(\"TRUE\")\nFALSE = Keyword(\"FALSE\")\nAX, AF, AG, AU, U = map(Keyword, \"AX AF AG AU U\".split())\nAND_OP = \"&\"\nOR_OP = \"|\"\nident = Word(alphas.lower())\n\nphi = Forward()\np = Optional(NOT) + (TRUE | FALSE | ident | Group(LPAR + phi + RPAR) )\nbinand = p + ZeroOrMore(AND_OP + p)\nbinor = binand + ZeroOrMore(OR_OP + binand)\nphi << (\n Group(AX + phi) |\n Group(AF + phi) |\n Group(AG + phi) |\n Group(AU + phi + U + phi) |\n binor)\n\nassign = ident + \"=\" + Group(phi)\nequiv = Group(phi) + \"<->\" + Group(phi)\nimplicate = Group(phi) + \"->\" + Group(phi)\n\nstatement = assign | equiv | implicate\n\ntests = \"\"\"\\\na=TRUE\nb = FALSE\nc = !TRUE\nd <-> b & !c\nAG b & d -> !e\"\"\".splitlines()\n\nfor t in tests:\n print statement.parseString(t).asList()\n\nPrints:\n['a', '=', ['TRUE']]\n['b', '=', ['FALSE']]\n['c', '=', ['!', 'TRUE']]\n[['d'], '<->', ['b', '&', '!', 'c']]\n[[['AG', 'b', '&', 'd']], '->', ['!', 'e']]\n\nThe Group classes help structure the results into a quasi-AST. There are a number of examples on the pyparsing wiki that will help you take it from here. I would recommend looking at the simpleBool.py example on how to have the parser produce an evaluator.\n"
] |
[
2,
2
] |
[] |
[] |
[
"python",
"yacc"
] |
stackoverflow_0001863824_python_yacc.txt
|
Q:
Simple DB query on Google App Engine taking a lot of CPU time
I'm fairly new to Google App Engine and Python, but I did just release my first real-world site with it. But now I'm getting problems with one path that is using significantly more CPU (and API CPU) time than the other paths. I've narrowed it down to a single datastore fetch that's causing the problem: Carvings.all().fetch(1000)
Under the App Engine dashboard it's reporting "1040cpu_ms 846api_cpu_ms" pretty reliably for each request to that path. It has seemed like this may be the source to some unresponsiveness that my client has experienced with the site in general.
So I can't figure out what is so expensive about this query. Here is the related data model:
class Carving(db.Model):
title = db.StringProperty(required=True)
reference_number = db.StringProperty()
main_category = db.StringProperty()
sub_category = db.StringProperty()
image = db.ReferenceProperty(CarvingImage)
description = db.TextProperty()
price = db.FloatProperty()
size = db.StringProperty()
material = db.StringProperty()
added_at = db.DateTimeProperty(auto_now_add=True)
modified_at = db.DateTimeProperty(auto_now=True)
In other places in the app when I pull this model from the datastore I do more filtering and I guess that's why they aren't causing any troubles. But the total number of entities for this model is just above 90 and I just can't imagine why this is so expensive.
A:
Memcache, if you haven't already, and especially if the same carvings are going to be fetched again and again. If you only have 90 total, I would imagine they would all be in the cache pretty quickly, and then you should be golden.
Do you need all the properties of the Carvings? For example, if you're just displaying a list of carvings, you could have a separate Entity that was something like CarvingSummary that only had a few properties. This would mean your schema was denormalized, but sometimes that's the price you pay for speed.
Also, I'm assuming this is not the first page the user will always hit? If that were the case it could be the cloud spinning up a a new instance.
A:
Sometimes you'll get better performance if you do an indexed query, rather than a query of "all" elements in the model.
Also, consider using memcache.
A:
Do you actually need 1000 entities? CPU time goes up more or less linearly with the number of results retrieved, so if you don't actually need all the results, you may be wasting a lot of time fetching and decoding them.
A:
It could be the image (and/or Text property) that is taking time to load & marshall into objects, depending on how big those properties are.
First prize: just use the memcache as others say. Then the overhead is incurred only on the first hit.
Second prize: I'm not sure how often your images are being changed and how many you might have, but you could consider uploading them as static files and simply linking to them in your HTML. Then it'd be just an HTTP GET from the browser - much lower overhead.
|
Simple DB query on Google App Engine taking a lot of CPU time
|
I'm fairly new to Google App Engine and Python, but I did just release my first real-world site with it. But now I'm getting problems with one path that is using significantly more CPU (and API CPU) time than the other paths. I've narrowed it down to a single datastore fetch that's causing the problem: Carvings.all().fetch(1000)
Under the App Engine dashboard it's reporting "1040cpu_ms 846api_cpu_ms" pretty reliably for each request to that path. It has seemed like this may be the source to some unresponsiveness that my client has experienced with the site in general.
So I can't figure out what is so expensive about this query. Here is the related data model:
class Carving(db.Model):
title = db.StringProperty(required=True)
reference_number = db.StringProperty()
main_category = db.StringProperty()
sub_category = db.StringProperty()
image = db.ReferenceProperty(CarvingImage)
description = db.TextProperty()
price = db.FloatProperty()
size = db.StringProperty()
material = db.StringProperty()
added_at = db.DateTimeProperty(auto_now_add=True)
modified_at = db.DateTimeProperty(auto_now=True)
In other places in the app when I pull this model from the datastore I do more filtering and I guess that's why they aren't causing any troubles. But the total number of entities for this model is just above 90 and I just can't imagine why this is so expensive.
|
[
"\nMemcache, if you haven't already, and especially if the same carvings are going to be fetched again and again. If you only have 90 total, I would imagine they would all be in the cache pretty quickly, and then you should be golden.\nDo you need all the properties of the Carvings? For example, if you're just displaying a list of carvings, you could have a separate Entity that was something like CarvingSummary that only had a few properties. This would mean your schema was denormalized, but sometimes that's the price you pay for speed.\n\nAlso, I'm assuming this is not the first page the user will always hit? If that were the case it could be the cloud spinning up a a new instance.\n",
"Sometimes you'll get better performance if you do an indexed query, rather than a query of \"all\" elements in the model.\nAlso, consider using memcache.\n",
"Do you actually need 1000 entities? CPU time goes up more or less linearly with the number of results retrieved, so if you don't actually need all the results, you may be wasting a lot of time fetching and decoding them.\n",
"It could be the image (and/or Text property) that is taking time to load & marshall into objects, depending on how big those properties are.\nFirst prize: just use the memcache as others say. Then the overhead is incurred only on the first hit.\nSecond prize: I'm not sure how often your images are being changed and how many you might have, but you could consider uploading them as static files and simply linking to them in your HTML. Then it'd be just an HTTP GET from the browser - much lower overhead.\n"
] |
[
2,
0,
0,
0
] |
[] |
[] |
[
"cpu_usage",
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0001892325_cpu_usage_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Python login script
I have the following script to logon to a url,but on submit in the webpage i call
<input type=button value="go" onclick="Search()";>
How to do the same in the following script instead of submit......
import urllib, urllib2, time
username = "sumname"
password = "test"
interval = 10
data = {"username":username,"password":password,"submit":"sign in"}
value = urllib.urlencode(data)
request = urllib2.Request("http://127.0.0.1/accounts/login/",value)
print "request="%request
#while (1):
open = urllib2.urlopen(request)
response = open.read()
response=str(response)
print response
Thanks...
A:
urllib and urllib2 are not the best ways to simulate browser interaction! You should rather be looking at mechanize (which does plug into urllib2). It's possible to simulate such interaction on "bare" urllib2, but it's just too much work and fragility to bother;-).
|
Python login script
|
I have the following script to logon to a url,but on submit in the webpage i call
<input type=button value="go" onclick="Search()";>
How to do the same in the following script instead of submit......
import urllib, urllib2, time
username = "sumname"
password = "test"
interval = 10
data = {"username":username,"password":password,"submit":"sign in"}
value = urllib.urlencode(data)
request = urllib2.Request("http://127.0.0.1/accounts/login/",value)
print "request="%request
#while (1):
open = urllib2.urlopen(request)
response = open.read()
response=str(response)
print response
Thanks...
|
[
"urllib and urllib2 are not the best ways to simulate browser interaction! You should rather be looking at mechanize (which does plug into urllib2). It's possible to simulate such interaction on \"bare\" urllib2, but it's just too much work and fragility to bother;-).\n"
] |
[
2
] |
[] |
[] |
[
"python",
"scripting"
] |
stackoverflow_0001899174_python_scripting.txt
|
Q:
How should I store state for a long-running process invoked from Django?
I am working on a Django application which allows a user to upload files. I need to perform some server-side processing on these files before sending them on to Amazon S3. After reading the responses to this question and this blog post I decided that the best manner in which to handle this is to have my view handler invoke a method on Pyro remote object to perform the processing asynchronously and then immediately return an Http 200 to the client. I have this prototyped and it seems to work well, however, I would also like to store the state of the processing so that the client can poll the application to see if the file has been processed and uploaded to S3.
I can handle the polling easily enough, but I am not sure where the appropriate location is to store the process state. It needs to be writable by the Pyro process and readable by my polling view.
I am hesitant to add columns to the database for data which should really only persist for 30 to 60 seconds.
I have considered using Django's low-level cache API and using a file id as the key, however, I don't believe this is really what the cache framework is designed for and I'm not sure what unforeseen problems there might be with going this route.
Lastly, I have considered storing state in the Pyro object doing the processing, but then it still seems like I would need to add a boolean "processing_complete" database column so that the view knows whether or not to query state from the Pyro object.
Of course, there are also some data integrity concerns with decoupling state from the database (what happens if the server goes down and all this data is in-memory?). I am to hear how more seasoned web application developers would handle this sort of stateful processing.
A:
We do this by having a "Request" table in the database.
When the upload arrives, we create the uploaded File object, and create a Request.
We start the background batch processor.
We return a 200 "we're working on it" page -- it shows the Requests and their status.
Our batch processor uses the Django ORM. When it finishes, it updates the Request object. We can (but don't) send an email notification. Mostly, we just update the status so that the user can log in again and see that processing has completed.
Batch Server Architecture notes.
It's a WSGI server that waits on a port for a batch processing request. The request is a REST POST with an ID number; the batch processor looks this up in the database and processes it.
The server is started automagically by our REST interface. If it isn't running, we spawn it. This makes a user transaction appear slow, but, oh well. It's not supposed to crash.
Also, we have a simple crontab to check that it's running. At most, it will be down for 30 minutes between "are you alive?" checks. We don't have a formal startup script (we run under Apache with mod_wsgi), but we may create a "restart" script that touches the WSGI file and then does a POST to a URL that does a health-check (and starts the batch processor).
When the batch server starts, there may be unprocessed requests for which it has never gotten a POST. So, the default startup is to pull ALL work out of the Request queue -- assuming it may have missed something.
A:
I know this is an old question but someone may find my answer useful even after all this time, so here goes.
You can of course use database as queue but there are solutions developed exactly for that purpose.
AMQP is made just for that. Together with Celery or Carrot and a broker server like RabbitMQ or ZeroMQ.
That's what we are using in our latest project and it is working great.
For your problem Celery and RabbitMQ seems like a best fit. RabbitMQ provides persistency of your messages, and Celery exposes easy views for polling to check the status of processes run in parallel.
You may also be interested in octopy.
A:
So, it's a job queue that you need. For your case, I would absolutely go with the DB to save state, even if those states are short lived. It sounds like that will meet all of your requirements, and isn't terribly difficult to implement since you already have all of the moving parts there, available to you. Keep it simple unless you need something more complex.
If you need something more powerful or more sophisticated, I'd look at something like Gearman.
|
How should I store state for a long-running process invoked from Django?
|
I am working on a Django application which allows a user to upload files. I need to perform some server-side processing on these files before sending them on to Amazon S3. After reading the responses to this question and this blog post I decided that the best manner in which to handle this is to have my view handler invoke a method on Pyro remote object to perform the processing asynchronously and then immediately return an Http 200 to the client. I have this prototyped and it seems to work well, however, I would also like to store the state of the processing so that the client can poll the application to see if the file has been processed and uploaded to S3.
I can handle the polling easily enough, but I am not sure where the appropriate location is to store the process state. It needs to be writable by the Pyro process and readable by my polling view.
I am hesitant to add columns to the database for data which should really only persist for 30 to 60 seconds.
I have considered using Django's low-level cache API and using a file id as the key, however, I don't believe this is really what the cache framework is designed for and I'm not sure what unforeseen problems there might be with going this route.
Lastly, I have considered storing state in the Pyro object doing the processing, but then it still seems like I would need to add a boolean "processing_complete" database column so that the view knows whether or not to query state from the Pyro object.
Of course, there are also some data integrity concerns with decoupling state from the database (what happens if the server goes down and all this data is in-memory?). I am to hear how more seasoned web application developers would handle this sort of stateful processing.
|
[
"We do this by having a \"Request\" table in the database.\nWhen the upload arrives, we create the uploaded File object, and create a Request.\nWe start the background batch processor.\nWe return a 200 \"we're working on it\" page -- it shows the Requests and their status.\nOur batch processor uses the Django ORM. When it finishes, it updates the Request object. We can (but don't) send an email notification. Mostly, we just update the status so that the user can log in again and see that processing has completed.\n\nBatch Server Architecture notes.\nIt's a WSGI server that waits on a port for a batch processing request. The request is a REST POST with an ID number; the batch processor looks this up in the database and processes it.\nThe server is started automagically by our REST interface. If it isn't running, we spawn it. This makes a user transaction appear slow, but, oh well. It's not supposed to crash. \nAlso, we have a simple crontab to check that it's running. At most, it will be down for 30 minutes between \"are you alive?\" checks. We don't have a formal startup script (we run under Apache with mod_wsgi), but we may create a \"restart\" script that touches the WSGI file and then does a POST to a URL that does a health-check (and starts the batch processor).\nWhen the batch server starts, there may be unprocessed requests for which it has never gotten a POST. So, the default startup is to pull ALL work out of the Request queue -- assuming it may have missed something. \n",
"I know this is an old question but someone may find my answer useful even after all this time, so here goes.\nYou can of course use database as queue but there are solutions developed exactly for that purpose.\nAMQP is made just for that. Together with Celery or Carrot and a broker server like RabbitMQ or ZeroMQ.\nThat's what we are using in our latest project and it is working great.\nFor your problem Celery and RabbitMQ seems like a best fit. RabbitMQ provides persistency of your messages, and Celery exposes easy views for polling to check the status of processes run in parallel.\nYou may also be interested in octopy.\n",
"So, it's a job queue that you need. For your case, I would absolutely go with the DB to save state, even if those states are short lived. It sounds like that will meet all of your requirements, and isn't terribly difficult to implement since you already have all of the moving parts there, available to you. Keep it simple unless you need something more complex.\nIf you need something more powerful or more sophisticated, I'd look at something like Gearman.\n"
] |
[
6,
5,
1
] |
[] |
[] |
[
"amazon_s3",
"asynchronous",
"django",
"pyro",
"python"
] |
stackoverflow_0000853421_amazon_s3_asynchronous_django_pyro_python.txt
|
Q:
How can I pass my ID and my password to a website in Python using Google App Engine?
Here is a piece of code that I use to fetch a web page HTML source (code) by its URL using Google App Engine:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
print "content-type: text/plain"
print
print result.content
Everything is fine here, but sometimes I need to get an HTML source of a page from a site where I am registered and can only get an access to that page if I firstly pass my ID and password. (It can be any site, actually, like any mail-account-providing site like Yahoo: https://login.yahoo.com/config/mail?.src=ym&.intl=us or any other site where users get free accounts by firstly getting registered there).
Can I somehow do it in Python (trough "Google App Engine")?
A:
You can check for an HTTP status code of 401, "authorization required", and provide the kind of HTTP authorization (basic, digest, whatever) that the site is asking for -- see e.g. here for more details (there's not much that's GAE specific here -- it's a matter of learning HTTP details and obeying them!-).
A:
As Alex said you can check for status code and see what type of autorization it wants, but you can not generalize it as some sites will not give any hint or only allow login thru a non standard form, in those cases you may have to automate the login process using forms, for that you can use library like twill (http://twill.idyll.org/)
or code a specific form submit for each site.
|
How can I pass my ID and my password to a website in Python using Google App Engine?
|
Here is a piece of code that I use to fetch a web page HTML source (code) by its URL using Google App Engine:
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
print "content-type: text/plain"
print
print result.content
Everything is fine here, but sometimes I need to get an HTML source of a page from a site where I am registered and can only get an access to that page if I firstly pass my ID and password. (It can be any site, actually, like any mail-account-providing site like Yahoo: https://login.yahoo.com/config/mail?.src=ym&.intl=us or any other site where users get free accounts by firstly getting registered there).
Can I somehow do it in Python (trough "Google App Engine")?
|
[
"You can check for an HTTP status code of 401, \"authorization required\", and provide the kind of HTTP authorization (basic, digest, whatever) that the site is asking for -- see e.g. here for more details (there's not much that's GAE specific here -- it's a matter of learning HTTP details and obeying them!-).\n",
"As Alex said you can check for status code and see what type of autorization it wants, but you can not generalize it as some sites will not give any hint or only allow login thru a non standard form, in those cases you may have to automate the login process using forms, for that you can use library like twill (http://twill.idyll.org/)\nor code a specific form submit for each site.\n"
] |
[
3,
1
] |
[] |
[] |
[
"google_app_engine",
"passwords",
"python"
] |
stackoverflow_0001899259_google_app_engine_passwords_python.txt
|
Q:
Why program functionally in Python?
At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency? I am just trying to understand what I get if I start using more of Python's functional features.
A:
Edit: I've been taken to task in the comments (in part, it seems, by fanatics of FP in Python, but not exclusively) for not providing more explanations/examples, so, expanding the answer to supply some.
lambda, even more so map (and filter), and most especially reduce, are hardly ever the right tool for the job in Python, which is a strongly multi-paradigm language.
lambda main advantage (?) compared to the normal def statement is that it makes an anonymous function, while def gives the function a name -- and for that very dubious advantage you pay an enormous price (the function's body is limited to one expression, the resulting function object is not pickleable, the very lack of a name sometimes makes it much harder to understand a stack trace or otherwise debug a problem -- need I go on?!-).
Consider what's probably the single most idiotic idiom you sometimes see used in "Python" (Python with "scare quotes", because it's obviously not idiomatic Python -- it's a bad transliteration from idiomatic Scheme or the like, just like the more frequent overuse of OOP in Python is a bad transliteration from Java or the like):
inc = lambda x: x + 1
by assigning the lambda to a name, this approach immediately throws away the above-mentioned "advantage" -- and doesn't lose any of the DISadvantages! For example, inc doesn't know its name -- inc.__name__ is the useless string '<lambda>' -- good luck understanding a stack trace with a few of these;-). The proper Python way to achieve the desired semantics in this simple case is, of course:
def inc(x): return x + 1
Now inc.__name__ is the string 'inc', as it clearly should be, and the object is pickleable -- the semantics are otherwise identical (in this simple case where the desired functionality fits comfortably in a simple expression -- def also makes it trivially easy to refactor if you need to temporarily or permanently insert statements such as print or raise, of course).
lambda is (part of) an expression while def is (part of) a statement -- that's the one bit of syntax sugar that makes people use lambda sometimes. Many FP enthusiasts (just as many OOP and procedural fans) dislike Python's reasonably strong distinction between expressions and statements (part of a general stance towards Command-Query Separation). Me, I think that when you use a language you're best off using it "with the grain" -- the way it was designed to be used -- rather than fighting against it; so I program Python in a Pythonic way, Scheme in a Schematic (;-) way, Fortran in a Fortesque (?) way, and so on:-).
Moving on to reduce -- one comment claims that reduce is the best way to compute the product of a list. Oh, really? Let's see...:
$ python -mtimeit -s'L=range(12,52)' 'reduce(lambda x,y: x*y, L, 1)'
100000 loops, best of 3: 18.3 usec per loop
$ python -mtimeit -s'L=range(12,52)' 'p=1' 'for x in L: p*=x'
100000 loops, best of 3: 10.5 usec per loop
so the simple, elementary, trivial loop is about twice as fast (as well as more concise) than the "best way" to perform the task?-) I guess the advantages of speed and conciseness must therefore make the trivial loop the "bestest" way, right?-)
By further sacrificing compactness and readability...:
$ python -mtimeit -s'import operator; L=range(12,52)' 'reduce(operator.mul, L, 1)'
100000 loops, best of 3: 10.7 usec per loop
...we can get almost back to the easily obtained performance of the simplest and most obvious, compact, and readable approach (the simple, elementary, trivial loop). This points out another problem with lambda, actually: performance! For sufficiently simple operations, such as multiplication, the overhead of a function call is quite significant compared to the actual operation being performed -- reduce (and map and filter) often forces you to insert such a function call where simple loops, list comprehensions, and generator expressions, allow the readability, compactness, and speed of in-line operations.
Perhaps even worse than the above-berated "assign a lambda to a name" anti-idiom is actually the following anti-idiom, e.g. to sort a list of strings by their lengths:
thelist.sort(key=lambda s: len(s))
instead of the obvious, readable, compact, speedier
thelist.sort(key=len)
Here, the use of lambda is doing nothing but inserting a level of indirection -- with no good effect whatsoever, and plenty of bad ones.
The motivation for using lambda is often to allow the use of map and filter instead of a vastly preferable loop or list comprehension that would let you do plain, normal computations in line; you still pay that "level of indirection", of course. It's not Pythonic to have to wonder "should I use a listcomp or a map here": just always use listcomps, when both appear applicable and you don't know which one to choose, on the basis of "there should be one, and preferably only one, obvious way to do something". You'll often write listcomps that could not be sensibly translated to a map (nested loops, if clauses, etc), while there's no call to map that can't be sensibly rewritten as a listcomp.
Perfectly proper functional approaches in Python often include list comprehensions, generator expressions, itertools, higher-order functions, first-order functions in various guises, closures, generators (and occasionally other kinds of iterators).
itertools, as a commenter pointed out, does include imap and ifilter: the difference is that, like all of itertools, these are stream-based (like map and filter builtins in Python 3, but differently from those builtins in Python 2). itertools offers a set of building blocks that compose well with each other, and splendid performance: especially if you find yourself potentially dealing with very long (or even unbounded!-) sequences, you owe it to yourself to become familiar with itertools -- their whole chapter in the docs makes for good reading, and the recipes in particular are quite instructive.
Writing your own higher-order functions is often useful, especially when they're suitable for use as decorators (both function decorators, as explained in that part of the docs, and class decorators, introduced in Python 2.6). Do remember to use functools.wraps on your function decorators (to keep the metadata of the function getting wrapped)!
So, summarizing...: anything you can code with lambda, map, and filter, you can code (more often than not advantageously) with def (named functions) and listcomps -- and usually moving up one notch to generators, generator expressions, or itertools, is even better. reduce meets the legal definition of "attractive nuisance"...: it's hardly ever the right tool for the job (that's why it's not a built-in any more in Python 3, at long last!-).
A:
FP is important not only for concurrency; in fact, there's virtually no concurrency in the canonical Python implementation (maybe 3.x changes that?). in any case, FP lends itself well to concurrency because it leads to programs with no or fewer (explicit) states. states are troublesome for a few reasons. one is that they make distributing the computation hard(er) (that's the concurrency argument), another, far more important in most cases, is the tendency to inflict bugs. the biggest source of bugs in contemporary software is variables (there's a close relationship between variables and states). FP may reduce the number of variables in a program: bugs squashed!
see how many bugs can you introduce by mixing the variables up in these versions:
def imperative(seq):
p = 1
for x in seq:
p *= x
return p
versus (warning, my.reduce's parameter list differs from that of python's reduce; rationale given later)
import operator as ops
def functional(seq):
return my.reduce(ops.mul, 1, seq)
as you can see, it's a matter of fact that FP gives you fewer opportunities to shoot yourself in the foot with a variables-related bug.
also, readability: it may take a bit of training, but functional is way easier to read than imperative: you see reduce ("ok, it's reducing a sequence to a single value"), mul ("by multiplication"). wherease imperative has the generic form of a for cycle, peppered with variables and assignments. these for cycles all look the same, so to get an idea of what's going on in imperative, you need to read almost all of it.
then there's succintness and flexibility. you give me imperative and I tell you I like it, but want something to sum sequences as well. no problem, you say, and off you go, copy-pasting:
def imperative(seq):
p = 1
for x in seq:
p *= x
return p
def imperative2(seq):
p = 0
for x in seq:
p += x
return p
what can you do to reduce the duplication? well, if operators were values, you could do something like
def reduce(op, seq, init):
rv = init
for x in seq:
rv = op(rv, x)
return rv
def imperative(seq):
return reduce(*, 1, seq)
def imperative2(seq):
return reduce(+, 0, seq)
oh wait! operators provides operators that are values! but.. Alex Martelli condemned reduce already... looks like if you want to stay within the boundaries he suggests, you're doomed to copy-pasting plumbing code.
is the FP version any better? surely you'd need to copy-paste as well?
import operator as ops
def functional(seq):
return my.reduce(ops.mul, 1, seq)
def functional2(seq):
return my.reduce(ops.add, 0, seq)
well, that's just an artifact of the half-assed approach! abandoning the imperative def, you can contract both versions to
import functools as func, operator as ops
functional = func.partial(my.reduce, ops.mul, 1)
functional2 = func.partial(my.reduce, ops.add, 0)
or even
import functools as func, operator as ops
reducer = func.partial(func.partial, my.reduce)
functional = reducer(ops.mul, 1)
functional2 = reducer(ops.add, 0)
(func.partial is the reason for my.reduce)
what about runtime speed? yes, using FP in a language like Python will incur some overhead. here i'll just parrot what a few professors have to say about this:
premature optimization is the root of all evil.
most programs spend 80% of their runtime in 20% percent of their code.
profile, don't speculate!
I'm not very good at explaining things. Don't let me muddy the water too much, read the first half of the speech John Backus gave on the occasion of receiving the Turing Award in 1977. Quote:
5.1 A von Neumann Program for Inner Product
c := 0
for i := I step 1 until n do
c := c + a[i] * b[i]
Several properties of this program are
worth noting:
Its statements operate on an invisible "state" according to complex
rules.
It is not hierarchical. Except for the right side of the assignment
statement, it does not construct
complex entities from simpler ones.
(Larger programs, however, often do.)
It is dynamic and repetitive. One must mentally execute it to
understand it.
It computes word-at-a-time by repetition (of the assignment) and by
modification (of variable i).
Part of the data, n, is in the program; thus it lacks generality and
works only for vectors of length n.
It names its arguments; it can only be used for vectors a and b.
To become general, it requires a
procedure declaration. These involve
complex issues (e.g., call-by-name
versus call-by-value).
Its "housekeeping" operations are represented by symbols in
scattered places (in the for statement
and the subscripts in the assignment).
This makes it impossible to
consolidate housekeeping operations,
the most common of all, into single,
powerful, widely useful operators.
Thus in programming those operations
one must always start again at square
one, writing "for i := ..." and
"for j := ..." followed by
assignment statements sprinkled with
i's and j's.
A:
I program in Python everyday, and I have to say that too much 'bandwagoning' toward OO or functional could lead toward missing elegant solutions. I believe that both paradigms have their advantages to certain problems - and I think that's when you know what approach to use. Use a functional approach when it leaves you with a clean, readable, and efficient solution. Same goes for OO.
And that's one of the reasons I love Python - the fact that it is multi-paradigm and lets the developer choose how to solve his/her problem.
A:
This answer is completely re-worked. It incorporates a lot of observations from the other answers.
As you can see, there is a lot of strong feelings surrounding the use of functional programming constructs in Python. There are three major groups of ideas here.
First, almost everybody but the people who are most wedded to the purest expression of the functional paradigm agree that list and generator comprehensions are better and clearer than using map or filter. Your colleagues should be avoiding the use of map and filter if you are targeting a version of Python new enough to support list comprehensions. And you should be avoiding itertools.imap and itertools.ifilter if your version of Python is new enough for generator comprehensions.
Secondly, there is a lot of ambivalence in the community as a whole about lambda. A lot of people are really annoyed by a syntax in addition to def for declaring functions, especially one that involves a keyword like lambda that has a rather strange name. And people are also annoyed that these small anonymous functions are missing any of the nice meta-data that describes any other kind of function. It makes debugging harder. Lastly the small functions declared by lambda are often not terribly efficient as they require the overhead of a Python function call each time they are invoked, which is frequently in an inner loop.
Lastly, most (meaning > 50%, but most likely not 90%) people think that reduce is a little strange and obscure. I myself admit to having print reduce.__doc__ whenever I want to use it, which isn't all that often. Though when I see it used, the nature of the arguments (i.e. function, list or iterator, scalar) speak for themselves.
As for myself, I fall in the camp of people who think the functional style is often very useful. But balancing that thought is the fact that Python is not at heart a functional language. And overuse of functional constructs can make programs seem strangely contorted and difficult for people to understand.
To understand when and where the functional style is very helpful and improves readability, consider this function in C++:
unsigned int factorial(unsigned int x)
{
int fact = 1;
for (int i = 2; i <= n; ++i) {
fact *= i;
}
return fact
}
This loop seems very simple and easy to understand. And in this case it is. But its seeming simplicity is a trap for the unwary. Consider this alternate means of writing the loop:
unsigned int factorial(unsigned int n)
{
int fact = 1;
for (int i = 2; i <= n; i += 2) {
fact *= i--;
}
return fact;
}
Suddenly, the loop control variable no longer varies in an obvious way. You are reduced to looking through the code and reasoning carefully about what happens with the loop control variable. Now this example is a bit pathological, but there are real-world examples that are not. And the problem is with the fact that the idea is repeated assignment to an existing variable. You can't trust the variable's value is the same throughout the entire body of the loop.
This is a long recognized problem, and in Python writing a loop like this is fairly unnatural. You have to use a while loop, and it just looks wrong. Instead, in Python you would write something like this:
def factorial(n):
fact = 1
for i in xrange(2, n):
fact = fact * i;
return fact
As you can see, the way you talk about the loop control variable in Python is not amenable to fooling with it inside the loop. This eliminates a lot of the problems with 'clever' loops in other imperative languages. Unfortunately, it's an idea that's semi-borrowed from functional languages.
Even this lends itself to strange fiddling. For example, this loop:
c = 1
for i in xrange(0, min(len(a), len(b))):
c = c * (a[i] + b[i])
if i < len(a):
a[i + 1] = a[a + 1] + 1
Oops, we again have a loop that is difficult to understand. It superficially resembles a really simple and obvious loop, and you have to read it carefully to realize that one of the variables used in the loop's computation is being messed with in a way that will effect future runs of the loop.
Again, a more functional approach to the rescue:
from itertools import izip
c = 1
for ai, bi in izip(a, b):
c = c * (ai + bi)
Now by looking at the code we have some strong indication (partly by the fact that the person is using this functional style) that the lists a and b are not modified during the execution of the loop. One less thing to think about.
The last thing to be worried about is c being modified in strange ways. Perhaps it is a global variable and is being modified by some roundabout function call. To rescue us from this mental worry, here is a purely function approach:
from itertools import izip
c = reduce(lambda x, ab: x * (ab[0] + ab[1]), izip(a, b), 1)
Very concise, and the structure tells us that x is purely an accumulator. It is a local variable everywhere it appear. The final result is unambiguously assigned to c. Now there is much less to worry about. The structure of the code removes several classes of possible error.
That is why people might choose a functional style. It is concise and clear, at least if you understand what reduce and lambda do. There are large classes of problems that could afflict a program written in a more imperative style that you know won't afflict your functional style program.
In the case of factorial, there is a very simple and clear way to write this function in Python in a functional style:
import operator
def factorial(n):
return reduce(operator.mul, xrange(2, n+1), 1)
A:
The question, which seems to be mostly ignored here:
does programming Python functionally really help with concurrency?
No. The value FP brings to concurrency is in eliminating state in computation, which is ultimately responsible for the hard-to-grasp nastiness of unintended errors in concurrent computation. But it depends on the concurrent programming idioms not themselves being stateful, something that doesn't apply to Twisted. If there are concurrency idioms for Python that leverage stateless programming, I don't know of them.
A:
Here's a short summary of positive answers when/why to program functionally.
List comprehensions were imported from Haskell, a FP language. They are Pythonic. I'd prefer to write
y = [i*2 for i in k if i % 3 == 0]
than to use an imperative construct (loop).
I'd use lambda when giving a complicated key to sort, like list.sort(key=lambda x: x.value.estimate())
It's cleaner to use higher-order functions than to write code using OOP's design patterns like visitor or abstract factory
People say that you should program Python in Python, C++ in C++ etc. That's true, but certainly you should be able to think in different ways at the same thing. If while writing a loop you know that you're really doing reducing (folding), then you'll be able to think on a higher level. That cleans your mind and helps to organize. Of course lower-level thinking is important too.
You should NOT overuse those features - there are many traps, see Alex Martelli's post. I'd subjectively say the most serious danger is that excessive use of those features will destroy readability of your code, which is a core attribute of Python.
A:
The standard functions filter(), map() and reduce() are used for various operations on a list and all of the three functions expect two arguments: A function and a list
We could define a separate function and use it as an argument to filter() etc., and its probably a good idea if that function is used several times, or if the function is too complex to be written in a single line. However, if it's needed only once and it's quite simple, it's more convenient to use a lambda construct to generate a (temporary) anonymous function and pass it to filter().
This helps in readability and compact code.
Using these function, would also turn out to be efficient, because the looping on the elements of the list is done in C, which is a little bit faster than looping in python.
And object oriented way is forcibly needed when states are to be maintained, apart from abstraction, grouping, etc., If the requirement is pretty simple, I would stick with functional than to Object Oriented programming.
A:
Map and Filter have their place in OO programming. Right next to list comprehensions and generator functions.
Reduce less so. The algorithm for reduce can rapidly suck down more time than it deserves; with a tiny bit of thinking, a manually-written reduce-loop will be more efficient than a reduce which applies a poorly-thought-out looping function to a sequence.
Lambda never. Lambda is useless. One can make the argument that it actually does something, so it's not completely useless. First: Lambda is not syntactic "sugar"; it makes things bigger and uglier. Second: the one time in 10,000 lines of code that think you need an "anonymous" function turns into two times in 20,000 lines of code, which removes the value of anonymity, making it into a maintenance liability.
However.
The functional style of no-object-state-change programming is still OO in nature. You just do more object creation and fewer object updates. Once you start using generator functions, much OO programming drifts in a functional direction.
Each state change appears to translate into a generator function that builds a new object in the new state from old object(s). It's an interesting world view because reasoning about the algorithm is much, much simpler.
But that's no call to use reduce or lambda.
|
Why program functionally in Python?
|
At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency? I am just trying to understand what I get if I start using more of Python's functional features.
|
[
"Edit: I've been taken to task in the comments (in part, it seems, by fanatics of FP in Python, but not exclusively) for not providing more explanations/examples, so, expanding the answer to supply some.\nlambda, even more so map (and filter), and most especially reduce, are hardly ever the right tool for the job in Python, which is a strongly multi-paradigm language.\nlambda main advantage (?) compared to the normal def statement is that it makes an anonymous function, while def gives the function a name -- and for that very dubious advantage you pay an enormous price (the function's body is limited to one expression, the resulting function object is not pickleable, the very lack of a name sometimes makes it much harder to understand a stack trace or otherwise debug a problem -- need I go on?!-).\nConsider what's probably the single most idiotic idiom you sometimes see used in \"Python\" (Python with \"scare quotes\", because it's obviously not idiomatic Python -- it's a bad transliteration from idiomatic Scheme or the like, just like the more frequent overuse of OOP in Python is a bad transliteration from Java or the like):\ninc = lambda x: x + 1\n\nby assigning the lambda to a name, this approach immediately throws away the above-mentioned \"advantage\" -- and doesn't lose any of the DISadvantages! For example, inc doesn't know its name -- inc.__name__ is the useless string '<lambda>' -- good luck understanding a stack trace with a few of these;-). The proper Python way to achieve the desired semantics in this simple case is, of course:\ndef inc(x): return x + 1\n\nNow inc.__name__ is the string 'inc', as it clearly should be, and the object is pickleable -- the semantics are otherwise identical (in this simple case where the desired functionality fits comfortably in a simple expression -- def also makes it trivially easy to refactor if you need to temporarily or permanently insert statements such as print or raise, of course).\nlambda is (part of) an expression while def is (part of) a statement -- that's the one bit of syntax sugar that makes people use lambda sometimes. Many FP enthusiasts (just as many OOP and procedural fans) dislike Python's reasonably strong distinction between expressions and statements (part of a general stance towards Command-Query Separation). Me, I think that when you use a language you're best off using it \"with the grain\" -- the way it was designed to be used -- rather than fighting against it; so I program Python in a Pythonic way, Scheme in a Schematic (;-) way, Fortran in a Fortesque (?) way, and so on:-).\nMoving on to reduce -- one comment claims that reduce is the best way to compute the product of a list. Oh, really? Let's see...:\n$ python -mtimeit -s'L=range(12,52)' 'reduce(lambda x,y: x*y, L, 1)'\n100000 loops, best of 3: 18.3 usec per loop\n$ python -mtimeit -s'L=range(12,52)' 'p=1' 'for x in L: p*=x'\n100000 loops, best of 3: 10.5 usec per loop\n\nso the simple, elementary, trivial loop is about twice as fast (as well as more concise) than the \"best way\" to perform the task?-) I guess the advantages of speed and conciseness must therefore make the trivial loop the \"bestest\" way, right?-)\nBy further sacrificing compactness and readability...:\n$ python -mtimeit -s'import operator; L=range(12,52)' 'reduce(operator.mul, L, 1)'\n100000 loops, best of 3: 10.7 usec per loop\n\n...we can get almost back to the easily obtained performance of the simplest and most obvious, compact, and readable approach (the simple, elementary, trivial loop). This points out another problem with lambda, actually: performance! For sufficiently simple operations, such as multiplication, the overhead of a function call is quite significant compared to the actual operation being performed -- reduce (and map and filter) often forces you to insert such a function call where simple loops, list comprehensions, and generator expressions, allow the readability, compactness, and speed of in-line operations.\nPerhaps even worse than the above-berated \"assign a lambda to a name\" anti-idiom is actually the following anti-idiom, e.g. to sort a list of strings by their lengths:\nthelist.sort(key=lambda s: len(s))\n\ninstead of the obvious, readable, compact, speedier\nthelist.sort(key=len)\n\nHere, the use of lambda is doing nothing but inserting a level of indirection -- with no good effect whatsoever, and plenty of bad ones.\nThe motivation for using lambda is often to allow the use of map and filter instead of a vastly preferable loop or list comprehension that would let you do plain, normal computations in line; you still pay that \"level of indirection\", of course. It's not Pythonic to have to wonder \"should I use a listcomp or a map here\": just always use listcomps, when both appear applicable and you don't know which one to choose, on the basis of \"there should be one, and preferably only one, obvious way to do something\". You'll often write listcomps that could not be sensibly translated to a map (nested loops, if clauses, etc), while there's no call to map that can't be sensibly rewritten as a listcomp.\nPerfectly proper functional approaches in Python often include list comprehensions, generator expressions, itertools, higher-order functions, first-order functions in various guises, closures, generators (and occasionally other kinds of iterators).\nitertools, as a commenter pointed out, does include imap and ifilter: the difference is that, like all of itertools, these are stream-based (like map and filter builtins in Python 3, but differently from those builtins in Python 2). itertools offers a set of building blocks that compose well with each other, and splendid performance: especially if you find yourself potentially dealing with very long (or even unbounded!-) sequences, you owe it to yourself to become familiar with itertools -- their whole chapter in the docs makes for good reading, and the recipes in particular are quite instructive.\nWriting your own higher-order functions is often useful, especially when they're suitable for use as decorators (both function decorators, as explained in that part of the docs, and class decorators, introduced in Python 2.6). Do remember to use functools.wraps on your function decorators (to keep the metadata of the function getting wrapped)!\nSo, summarizing...: anything you can code with lambda, map, and filter, you can code (more often than not advantageously) with def (named functions) and listcomps -- and usually moving up one notch to generators, generator expressions, or itertools, is even better. reduce meets the legal definition of \"attractive nuisance\"...: it's hardly ever the right tool for the job (that's why it's not a built-in any more in Python 3, at long last!-).\n",
"FP is important not only for concurrency; in fact, there's virtually no concurrency in the canonical Python implementation (maybe 3.x changes that?). in any case, FP lends itself well to concurrency because it leads to programs with no or fewer (explicit) states. states are troublesome for a few reasons. one is that they make distributing the computation hard(er) (that's the concurrency argument), another, far more important in most cases, is the tendency to inflict bugs. the biggest source of bugs in contemporary software is variables (there's a close relationship between variables and states). FP may reduce the number of variables in a program: bugs squashed!\nsee how many bugs can you introduce by mixing the variables up in these versions:\ndef imperative(seq):\n p = 1\n for x in seq:\n p *= x\n return p\n\nversus (warning, my.reduce's parameter list differs from that of python's reduce; rationale given later)\nimport operator as ops\n\ndef functional(seq):\n return my.reduce(ops.mul, 1, seq)\n\nas you can see, it's a matter of fact that FP gives you fewer opportunities to shoot yourself in the foot with a variables-related bug.\nalso, readability: it may take a bit of training, but functional is way easier to read than imperative: you see reduce (\"ok, it's reducing a sequence to a single value\"), mul (\"by multiplication\"). wherease imperative has the generic form of a for cycle, peppered with variables and assignments. these for cycles all look the same, so to get an idea of what's going on in imperative, you need to read almost all of it.\nthen there's succintness and flexibility. you give me imperative and I tell you I like it, but want something to sum sequences as well. no problem, you say, and off you go, copy-pasting:\ndef imperative(seq):\n p = 1\n for x in seq:\n p *= x\n return p\n\ndef imperative2(seq):\n p = 0\n for x in seq:\n p += x\n return p\n\nwhat can you do to reduce the duplication? well, if operators were values, you could do something like\ndef reduce(op, seq, init):\n rv = init\n for x in seq:\n rv = op(rv, x)\n return rv\n\ndef imperative(seq):\n return reduce(*, 1, seq)\n\ndef imperative2(seq):\n return reduce(+, 0, seq)\n\noh wait! operators provides operators that are values! but.. Alex Martelli condemned reduce already... looks like if you want to stay within the boundaries he suggests, you're doomed to copy-pasting plumbing code. \nis the FP version any better? surely you'd need to copy-paste as well?\nimport operator as ops\n\ndef functional(seq):\n return my.reduce(ops.mul, 1, seq)\n\ndef functional2(seq):\n return my.reduce(ops.add, 0, seq)\n\nwell, that's just an artifact of the half-assed approach! abandoning the imperative def, you can contract both versions to\nimport functools as func, operator as ops\n\nfunctional = func.partial(my.reduce, ops.mul, 1)\nfunctional2 = func.partial(my.reduce, ops.add, 0)\n\nor even\nimport functools as func, operator as ops\n\nreducer = func.partial(func.partial, my.reduce)\nfunctional = reducer(ops.mul, 1)\nfunctional2 = reducer(ops.add, 0)\n\n(func.partial is the reason for my.reduce)\nwhat about runtime speed? yes, using FP in a language like Python will incur some overhead. here i'll just parrot what a few professors have to say about this:\n\npremature optimization is the root of all evil.\nmost programs spend 80% of their runtime in 20% percent of their code.\nprofile, don't speculate!\n\nI'm not very good at explaining things. Don't let me muddy the water too much, read the first half of the speech John Backus gave on the occasion of receiving the Turing Award in 1977. Quote:\n\n5.1 A von Neumann Program for Inner Product\nc := 0\nfor i := I step 1 until n do\n c := c + a[i] * b[i]\n\nSeveral properties of this program are\n worth noting:\n\nIts statements operate on an invisible \"state\" according to complex\n rules.\nIt is not hierarchical. Except for the right side of the assignment\n statement, it does not construct\n complex entities from simpler ones.\n (Larger programs, however, often do.)\nIt is dynamic and repetitive. One must mentally execute it to\n understand it.\nIt computes word-at-a-time by repetition (of the assignment) and by\n modification (of variable i).\nPart of the data, n, is in the program; thus it lacks generality and\n works only for vectors of length n.\nIt names its arguments; it can only be used for vectors a and b.\n To become general, it requires a\n procedure declaration. These involve\n complex issues (e.g., call-by-name\n versus call-by-value).\nIts \"housekeeping\" operations are represented by symbols in\n scattered places (in the for statement\n and the subscripts in the assignment).\n This makes it impossible to\n consolidate housekeeping operations,\n the most common of all, into single,\n powerful, widely useful operators. \n Thus in programming those operations\n one must always start again at square\n one, writing \"for i := ...\" and\n \"for j := ...\" followed by\n assignment statements sprinkled with\n i's and j's.\n\n\n",
"I program in Python everyday, and I have to say that too much 'bandwagoning' toward OO or functional could lead toward missing elegant solutions. I believe that both paradigms have their advantages to certain problems - and I think that's when you know what approach to use. Use a functional approach when it leaves you with a clean, readable, and efficient solution. Same goes for OO.\nAnd that's one of the reasons I love Python - the fact that it is multi-paradigm and lets the developer choose how to solve his/her problem.\n",
"This answer is completely re-worked. It incorporates a lot of observations from the other answers.\nAs you can see, there is a lot of strong feelings surrounding the use of functional programming constructs in Python. There are three major groups of ideas here.\nFirst, almost everybody but the people who are most wedded to the purest expression of the functional paradigm agree that list and generator comprehensions are better and clearer than using map or filter. Your colleagues should be avoiding the use of map and filter if you are targeting a version of Python new enough to support list comprehensions. And you should be avoiding itertools.imap and itertools.ifilter if your version of Python is new enough for generator comprehensions.\nSecondly, there is a lot of ambivalence in the community as a whole about lambda. A lot of people are really annoyed by a syntax in addition to def for declaring functions, especially one that involves a keyword like lambda that has a rather strange name. And people are also annoyed that these small anonymous functions are missing any of the nice meta-data that describes any other kind of function. It makes debugging harder. Lastly the small functions declared by lambda are often not terribly efficient as they require the overhead of a Python function call each time they are invoked, which is frequently in an inner loop.\nLastly, most (meaning > 50%, but most likely not 90%) people think that reduce is a little strange and obscure. I myself admit to having print reduce.__doc__ whenever I want to use it, which isn't all that often. Though when I see it used, the nature of the arguments (i.e. function, list or iterator, scalar) speak for themselves.\nAs for myself, I fall in the camp of people who think the functional style is often very useful. But balancing that thought is the fact that Python is not at heart a functional language. And overuse of functional constructs can make programs seem strangely contorted and difficult for people to understand.\nTo understand when and where the functional style is very helpful and improves readability, consider this function in C++:\nunsigned int factorial(unsigned int x)\n{\n int fact = 1;\n for (int i = 2; i <= n; ++i) {\n fact *= i;\n }\n return fact\n }\n\nThis loop seems very simple and easy to understand. And in this case it is. But its seeming simplicity is a trap for the unwary. Consider this alternate means of writing the loop:\nunsigned int factorial(unsigned int n)\n{\n int fact = 1;\n for (int i = 2; i <= n; i += 2) {\n fact *= i--;\n }\n return fact;\n }\n\nSuddenly, the loop control variable no longer varies in an obvious way. You are reduced to looking through the code and reasoning carefully about what happens with the loop control variable. Now this example is a bit pathological, but there are real-world examples that are not. And the problem is with the fact that the idea is repeated assignment to an existing variable. You can't trust the variable's value is the same throughout the entire body of the loop.\nThis is a long recognized problem, and in Python writing a loop like this is fairly unnatural. You have to use a while loop, and it just looks wrong. Instead, in Python you would write something like this:\ndef factorial(n):\n fact = 1\n for i in xrange(2, n):\n fact = fact * i;\n return fact\n\nAs you can see, the way you talk about the loop control variable in Python is not amenable to fooling with it inside the loop. This eliminates a lot of the problems with 'clever' loops in other imperative languages. Unfortunately, it's an idea that's semi-borrowed from functional languages.\nEven this lends itself to strange fiddling. For example, this loop:\nc = 1\nfor i in xrange(0, min(len(a), len(b))):\n c = c * (a[i] + b[i])\n if i < len(a):\n a[i + 1] = a[a + 1] + 1\n\nOops, we again have a loop that is difficult to understand. It superficially resembles a really simple and obvious loop, and you have to read it carefully to realize that one of the variables used in the loop's computation is being messed with in a way that will effect future runs of the loop.\nAgain, a more functional approach to the rescue:\nfrom itertools import izip\nc = 1\nfor ai, bi in izip(a, b):\n c = c * (ai + bi)\n\nNow by looking at the code we have some strong indication (partly by the fact that the person is using this functional style) that the lists a and b are not modified during the execution of the loop. One less thing to think about.\nThe last thing to be worried about is c being modified in strange ways. Perhaps it is a global variable and is being modified by some roundabout function call. To rescue us from this mental worry, here is a purely function approach:\nfrom itertools import izip\nc = reduce(lambda x, ab: x * (ab[0] + ab[1]), izip(a, b), 1)\n\nVery concise, and the structure tells us that x is purely an accumulator. It is a local variable everywhere it appear. The final result is unambiguously assigned to c. Now there is much less to worry about. The structure of the code removes several classes of possible error.\nThat is why people might choose a functional style. It is concise and clear, at least if you understand what reduce and lambda do. There are large classes of problems that could afflict a program written in a more imperative style that you know won't afflict your functional style program.\nIn the case of factorial, there is a very simple and clear way to write this function in Python in a functional style:\nimport operator\ndef factorial(n):\n return reduce(operator.mul, xrange(2, n+1), 1)\n\n",
"The question, which seems to be mostly ignored here: \n\ndoes programming Python functionally really help with concurrency?\n\nNo. The value FP brings to concurrency is in eliminating state in computation, which is ultimately responsible for the hard-to-grasp nastiness of unintended errors in concurrent computation. But it depends on the concurrent programming idioms not themselves being stateful, something that doesn't apply to Twisted. If there are concurrency idioms for Python that leverage stateless programming, I don't know of them.\n",
"Here's a short summary of positive answers when/why to program functionally.\n\nList comprehensions were imported from Haskell, a FP language. They are Pythonic. I'd prefer to write\n\n\ny = [i*2 for i in k if i % 3 == 0]\n\n\nthan to use an imperative construct (loop).\n\nI'd use lambda when giving a complicated key to sort, like list.sort(key=lambda x: x.value.estimate())\nIt's cleaner to use higher-order functions than to write code using OOP's design patterns like visitor or abstract factory\nPeople say that you should program Python in Python, C++ in C++ etc. That's true, but certainly you should be able to think in different ways at the same thing. If while writing a loop you know that you're really doing reducing (folding), then you'll be able to think on a higher level. That cleans your mind and helps to organize. Of course lower-level thinking is important too.\n\nYou should NOT overuse those features - there are many traps, see Alex Martelli's post. I'd subjectively say the most serious danger is that excessive use of those features will destroy readability of your code, which is a core attribute of Python.\n",
"The standard functions filter(), map() and reduce() are used for various operations on a list and all of the three functions expect two arguments: A function and a list\nWe could define a separate function and use it as an argument to filter() etc., and its probably a good idea if that function is used several times, or if the function is too complex to be written in a single line. However, if it's needed only once and it's quite simple, it's more convenient to use a lambda construct to generate a (temporary) anonymous function and pass it to filter().\nThis helps in readability and compact code.\nUsing these function, would also turn out to be efficient, because the looping on the elements of the list is done in C, which is a little bit faster than looping in python.\nAnd object oriented way is forcibly needed when states are to be maintained, apart from abstraction, grouping, etc., If the requirement is pretty simple, I would stick with functional than to Object Oriented programming.\n",
"Map and Filter have their place in OO programming. Right next to list comprehensions and generator functions.\nReduce less so. The algorithm for reduce can rapidly suck down more time than it deserves; with a tiny bit of thinking, a manually-written reduce-loop will be more efficient than a reduce which applies a poorly-thought-out looping function to a sequence. \nLambda never. Lambda is useless. One can make the argument that it actually does something, so it's not completely useless. First: Lambda is not syntactic \"sugar\"; it makes things bigger and uglier. Second: the one time in 10,000 lines of code that think you need an \"anonymous\" function turns into two times in 20,000 lines of code, which removes the value of anonymity, making it into a maintenance liability.\nHowever.\nThe functional style of no-object-state-change programming is still OO in nature. You just do more object creation and fewer object updates. Once you start using generator functions, much OO programming drifts in a functional direction.\nEach state change appears to translate into a generator function that builds a new object in the new state from old object(s). It's an interesting world view because reasoning about the algorithm is much, much simpler.\nBut that's no call to use reduce or lambda.\n"
] |
[
72,
25,
19,
16,
9,
7,
2,
1
] |
[] |
[] |
[
"functional_programming",
"python"
] |
stackoverflow_0001892324_functional_programming_python.txt
|
Q:
wxPython - How to get the ID of a widget when you passed in -1?
I'm doing a little wxPython work today and I've got this piece of code (I've stripped out the irrelevant parts):
def CreateRowOne(self, pan):
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
hbox1.Add(wx.Button(pan, -1, "250 Words"), 1, wx.EXPAND | wx.ALL)
hbox1.Add(wx.Button(pan, -1, "500 Words"), 1, wx.EXPAND | wx.ALL)
hbox1.Add(wx.Button(pan, -1, "750 Words"), 1, wx.EXPAND | wx.ALL)
return hbox1
How do you get the ID of the buttons that were created, so I can bind them to a handler? Normally, I'd do this:
button1 = wx.Button(...)
button2 = wx.Button(...)
...
self.Bind(wx.EVT_BUTTON, self.Blah, button1.GetID())
self.Bind(wx.EVT_BUTTON, self.Blah2, button2.GetID())
but I didn't give an identifier to any of the buttons. Am I going to have to manually assign the ID numbers?
A:
Am I going to have to manually assign the ID numbers?
No, putting -1 or using wx.NewId() will give you autogenerated ID.
and You can always get id with button1.GetID() or button1.Id back anytime.
--
UPDATE:
ID_BUTTON1 = wx.NewId()
hbox1.Add(wx.Button(pan, ID_BUTTON1, "250 Words"), 1, wx.EXPAND | wx.ALL)
self.Bind(wx.EVT_BUTTON, self.Blah, ID_BUTTON1)
A:
You can get id by control.GetID() but you do not need to get ID to bind, you can just do this
self.btn.Bind(wx.EVT_BUTTON, self._onBtnClick)
It is preferable(id should be implementation detail) and short e.g. in this sample
import wx
app = wx.PySimpleApp()
frame = wx.Frame(None)
btn = wx.Button(frame, -1, "anurag")
btn.Bind(wx.EVT_BUTTON, lambda e:wx.MessageBox("Wow it works"))
frame.Show()
app.SetTopWindow(frame)
app.MainLoop()
A:
I recommend not doing "sizer.Add(wx.Button(...))". It's better to separate widget creation and layout. Is there a compelling reason to write your code the way you have? Why not write it like this:
button1=wx.Button(pan, wx.ID_ANY, ...)
button2=wx.Button(pan, wx.ID_ANY, ...)
...
hbox1.Add(button1)
hbox1.Add(button2)
...
self.Bind(wx.EVT_BUTTON, self.Blah, button1.GetID())
self.Bind(wx.EVT_BUTTON, self.Blah2, button2.GetID())
There's simply no gain in combining button creation and adding it to a sizer in one line.
Personally I see even greater value in assigning IDs, but that can be onerous for a large number of widgets. I generally only do that for "significant" widgets -- widgets I refer to in other parts of the code. My code typically looks like:
ID_BUTTON1 = wx.NewID()
IO_BUTTON2 = wx.NewID()
class ...:
...
button1 = wx.Button(self, ID_BUTTON1, ...)
...
self.Bind(wx.EVT_BUTTON, ID_BUTTON1, ...)
...
I think this makes the code easier to understand and easier to maintain over time.
|
wxPython - How to get the ID of a widget when you passed in -1?
|
I'm doing a little wxPython work today and I've got this piece of code (I've stripped out the irrelevant parts):
def CreateRowOne(self, pan):
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
hbox1.Add(wx.Button(pan, -1, "250 Words"), 1, wx.EXPAND | wx.ALL)
hbox1.Add(wx.Button(pan, -1, "500 Words"), 1, wx.EXPAND | wx.ALL)
hbox1.Add(wx.Button(pan, -1, "750 Words"), 1, wx.EXPAND | wx.ALL)
return hbox1
How do you get the ID of the buttons that were created, so I can bind them to a handler? Normally, I'd do this:
button1 = wx.Button(...)
button2 = wx.Button(...)
...
self.Bind(wx.EVT_BUTTON, self.Blah, button1.GetID())
self.Bind(wx.EVT_BUTTON, self.Blah2, button2.GetID())
but I didn't give an identifier to any of the buttons. Am I going to have to manually assign the ID numbers?
|
[
"\n\nAm I going to have to manually assign the ID numbers?\n\n\nNo, putting -1 or using wx.NewId() will give you autogenerated ID.\nand You can always get id with button1.GetID() or button1.Id back anytime.\n--\nUPDATE:\nID_BUTTON1 = wx.NewId()\n\nhbox1.Add(wx.Button(pan, ID_BUTTON1, \"250 Words\"), 1, wx.EXPAND | wx.ALL)\n\nself.Bind(wx.EVT_BUTTON, self.Blah, ID_BUTTON1)\n\n",
"You can get id by control.GetID() but you do not need to get ID to bind, you can just do this\nself.btn.Bind(wx.EVT_BUTTON, self._onBtnClick)\n\nIt is preferable(id should be implementation detail) and short e.g. in this sample\nimport wx\n\napp = wx.PySimpleApp()\nframe = wx.Frame(None)\nbtn = wx.Button(frame, -1, \"anurag\")\nbtn.Bind(wx.EVT_BUTTON, lambda e:wx.MessageBox(\"Wow it works\"))\nframe.Show()\napp.SetTopWindow(frame)\napp.MainLoop()\n\n",
"I recommend not doing \"sizer.Add(wx.Button(...))\". It's better to separate widget creation and layout. Is there a compelling reason to write your code the way you have? Why not write it like this:\nbutton1=wx.Button(pan, wx.ID_ANY, ...)\nbutton2=wx.Button(pan, wx.ID_ANY, ...)\n...\nhbox1.Add(button1)\nhbox1.Add(button2)\n...\nself.Bind(wx.EVT_BUTTON, self.Blah, button1.GetID())\nself.Bind(wx.EVT_BUTTON, self.Blah2, button2.GetID())\n\nThere's simply no gain in combining button creation and adding it to a sizer in one line.\nPersonally I see even greater value in assigning IDs, but that can be onerous for a large number of widgets. I generally only do that for \"significant\" widgets -- widgets I refer to in other parts of the code. My code typically looks like:\nID_BUTTON1 = wx.NewID()\nIO_BUTTON2 = wx.NewID()\n\nclass ...:\n ...\n button1 = wx.Button(self, ID_BUTTON1, ...)\n ...\n self.Bind(wx.EVT_BUTTON, ID_BUTTON1, ...)\n ...\n\nI think this makes the code easier to understand and easier to maintain over time.\n"
] |
[
3,
3,
1
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0001879694_python_wxpython.txt
|
Q:
Python: Amount of wall time a process has been running
I want to do something like this:
try:
pid = int(file(lock_file, "r").read())
print "%s exists with pid: %s" % (lock_file, pid)
if not check_pid(pid):
print "%s not running. Phantom lock file? Continuing anyways" % pid
elif wall_time(pid) > 60 * 5:
print "%s has been running for more than 5 minutes. Killing it" % pid
os.kill(pid)
else:
print "Exiting"
sys.exit()
except IOError:
pass
lock = file(lock_file, "w")
lock.write("%s" % os.getpid())
lock.close()
How do I implement wall_time? Do I have to read from /proc or is there a better way?
A:
Perhaps you could look at the creation time of the lock file. This wouldn't be guaranteed correct, but it would be correct in most cases (and the consequences of getting it wrong are minimal).
A:
If you do not want to use the modify time of the lockfile for some reason, you could just write it down in the file:
pid, start_time = map(int, file(lock_file, "r").read().split())
...
lock.write("%s %d" % (os.getpid(), time.time()))
|
Python: Amount of wall time a process has been running
|
I want to do something like this:
try:
pid = int(file(lock_file, "r").read())
print "%s exists with pid: %s" % (lock_file, pid)
if not check_pid(pid):
print "%s not running. Phantom lock file? Continuing anyways" % pid
elif wall_time(pid) > 60 * 5:
print "%s has been running for more than 5 minutes. Killing it" % pid
os.kill(pid)
else:
print "Exiting"
sys.exit()
except IOError:
pass
lock = file(lock_file, "w")
lock.write("%s" % os.getpid())
lock.close()
How do I implement wall_time? Do I have to read from /proc or is there a better way?
|
[
"Perhaps you could look at the creation time of the lock file. This wouldn't be guaranteed correct, but it would be correct in most cases (and the consequences of getting it wrong are minimal).\n",
"If you do not want to use the modify time of the lockfile for some reason, you could just write it down in the file:\npid, start_time = map(int, file(lock_file, \"r\").read().split())\n...\nlock.write(\"%s %d\" % (os.getpid(), time.time()))\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"process",
"python"
] |
stackoverflow_0001899922_process_python.txt
|
Q:
Getting every odd variable in a list?
If I make a list in Python and want to write a function that would return only odd numbers from a range 1 to x how would I do that?
For example, if I have list [1, 2, 3, 4] from 1 to 4 (4 ix my x), I want to return [1, 3].
A:
If you want to start with an arbitrary list:
[item for item in yourlist if item % 2]
but if you're always starting with range, range(1, x, 2) is better!-)
For example:
$ python -mtimeit -s'x=99' 'filter(lambda(t): t % 2 == 1, range(1, x))'
10000 loops, best of 3: 38.5 usec per loop
$ python -mtimeit -s'x=99' 'range(1, x, 2)'
1000000 loops, best of 3: 1.38 usec per loop
so the right approach is about 28 times (!) faster than a somewhat-typical wrong one, in this case.
The "more general than you need if that's all you need" solution:
$ python -mtimeit -s'yourlist=range(1,99)' '[item for item in yourlist if item % 2]'
10000 loops, best of 3: 21.6 usec per loop
is only about twice as fast as the sample wrong one, but still over 15 times slower than the "just right" one!-)
A:
What's wrong with:
def getodds(lst):
return lst[1::2]
....???
(Assuming you want every other element from some arbitrary sequence ... all those which have odd indexes).
Alternatively if you want all items from a list of numbers where the value of that element is odd:
def oddonly(lst):
return [x for x in lst if x % 2]
[Update: 2017]
You could use "lazy evaluation" to yield these from generators:
def get_elements_at_odd_indices(sequence):
for index, item in enumerate(sequence):
if index % 2:
yield item
else:
continue
For getting odd elements (rather than elements at each odd offset from the start of the sequence) you could use the even simpler:
def get_odd_elements(sequence):
for item in sequence:
if item % 2:
yield item
else:
continue
This should work for any sequence or iterable object types. (Obviously the latter only works for those sequences or iterables which yield numbers ... or other types for which % 2 evaluates to a meaningfully "odd" result).
Also note that, if we want to efficiently operate on Pandas series or dataframe columns, or the underlying NumPy then we could get the elements at odd indexes using the [1::2] slice notation, and we can get each of the elements containing odd values using NumPy's "fancy indexing"
For example:
import numpy as nd
arr = nd.arange(1000)
odds = arr[arr%2!=0]
I show the "fancy index" as arr[arr%2!=0] because that will generalize better to filtering out every third, fourth or other nth element; but you can use much more elaborate expressions.
Note that the syntax arr[arr%2!=0] may look a bit odd. It's magic in the way that NumPy over-rides various arithmetic and bitwise operators and augmented assignment operations. The point is that NumPy evaluates such operations into machine code which can be efficiently vectorized over NumPy arrays ... using SIMD wherever the underlying CPU supports. For example on typical laptop and desktop systems today NumPy can evaluate many arithmetic operations into SSE operations.
A:
To have a range of odd/even numbers up to and possibly including a number n, you can:
def odd_numbers(n):
return range(1, n+1, 2)
def even_numbers(n):
return range(0, n+1, 2)
If you want a generic algorithm that will take the items with odd indexes from a sequence, you can do the following:
import itertools
def odd_indexes(sequence):
return itertools.islice(sequence, 1, None, 2)
def even_indexes(sequence):
return itertools.islice(sequence, 0, None, 2)
|
Getting every odd variable in a list?
|
If I make a list in Python and want to write a function that would return only odd numbers from a range 1 to x how would I do that?
For example, if I have list [1, 2, 3, 4] from 1 to 4 (4 ix my x), I want to return [1, 3].
|
[
"If you want to start with an arbitrary list:\n[item for item in yourlist if item % 2]\n\nbut if you're always starting with range, range(1, x, 2) is better!-)\nFor example:\n$ python -mtimeit -s'x=99' 'filter(lambda(t): t % 2 == 1, range(1, x))'\n10000 loops, best of 3: 38.5 usec per loop\n$ python -mtimeit -s'x=99' 'range(1, x, 2)'\n1000000 loops, best of 3: 1.38 usec per loop\n\nso the right approach is about 28 times (!) faster than a somewhat-typical wrong one, in this case.\nThe \"more general than you need if that's all you need\" solution:\n$ python -mtimeit -s'yourlist=range(1,99)' '[item for item in yourlist if item % 2]'\n10000 loops, best of 3: 21.6 usec per loop\n\nis only about twice as fast as the sample wrong one, but still over 15 times slower than the \"just right\" one!-)\n",
"What's wrong with:\ndef getodds(lst):\n return lst[1::2]\n\n....???\n(Assuming you want every other element from some arbitrary sequence ... all those which have odd indexes).\nAlternatively if you want all items from a list of numbers where the value of that element is odd:\ndef oddonly(lst):\n return [x for x in lst if x % 2]\n\n[Update: 2017]\nYou could use \"lazy evaluation\" to yield these from generators:\ndef get_elements_at_odd_indices(sequence):\n for index, item in enumerate(sequence):\n if index % 2:\n yield item\n else:\n continue\n\nFor getting odd elements (rather than elements at each odd offset from the start of the sequence) you could use the even simpler:\ndef get_odd_elements(sequence):\n for item in sequence:\n if item % 2:\n yield item\n else:\n continue\n\nThis should work for any sequence or iterable object types. (Obviously the latter only works for those sequences or iterables which yield numbers ... or other types for which % 2 evaluates to a meaningfully \"odd\" result).\nAlso note that, if we want to efficiently operate on Pandas series or dataframe columns, or the underlying NumPy then we could get the elements at odd indexes using the [1::2] slice notation, and we can get each of the elements containing odd values using NumPy's \"fancy indexing\"\nFor example:\nimport numpy as nd\narr = nd.arange(1000)\nodds = arr[arr%2!=0]\n\nI show the \"fancy index\" as arr[arr%2!=0] because that will generalize better to filtering out every third, fourth or other nth element; but you can use much more elaborate expressions.\nNote that the syntax arr[arr%2!=0] may look a bit odd. It's magic in the way that NumPy over-rides various arithmetic and bitwise operators and augmented assignment operations. The point is that NumPy evaluates such operations into machine code which can be efficiently vectorized over NumPy arrays ... using SIMD wherever the underlying CPU supports. For example on typical laptop and desktop systems today NumPy can evaluate many arithmetic operations into SSE operations.\n",
"To have a range of odd/even numbers up to and possibly including a number n, you can:\ndef odd_numbers(n):\n return range(1, n+1, 2)\ndef even_numbers(n):\n return range(0, n+1, 2)\n\nIf you want a generic algorithm that will take the items with odd indexes from a sequence, you can do the following:\nimport itertools\ndef odd_indexes(sequence):\n return itertools.islice(sequence, 1, None, 2)\ndef even_indexes(sequence):\n return itertools.islice(sequence, 0, None, 2)\n\n"
] |
[
14,
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001780763_python.txt
|
Q:
Remove whitespace in Python using string.whitespace
Python's string.whitespace is great:
>>> string.whitespace
'\t\n\x0b\x0c\r '
How do I use this with a string without resorting to manually typing in '\t|\n|... etc for regex?
For example, it should be able to turn:
"Please \n don't \t hurt \x0b me."
into
"Please don't hurt me."
I'd probably want to keep the single spaces, but it'd be easy enough to just go string.whitespace[:-1] I suppose.
A:
There is a special-case shortcut for exactly this use case!
If you call str.split without an argument, it splits on runs of whitespace instead of single characters. So:
>>> ' '.join("Please \n don't \t hurt \x0b me.".split())
"Please don't hurt me."
A:
What's wrong with the \s character class?
>>> import re
>>> pattern = re.compile(r'\s+')
>>> re.sub(pattern, ' ', "Please \n don't \t hurt \x0b me.")
"Please don't hurt me."
A:
Let's make some reasonable assumptions:
(1) You really want to replace any run of whitespace characters with a single space (a run is of length 1 or greater).
(2) You would like the same code to work with minimal changes under Python 2.X with unicode objects.
(3) You don't want your code to assume things that are not guaranteed in the docs
(4) You would like the same code to work with minimal changes with Python 3.X str objects.
The currently selected answer has these problems:
(a) changes " " * 3 to " " * 2 i.e. it removes duplicate spaces but not triplicate, quadruplicate, etc spaces. [fails requirement 1]
(b) changes "foo\tbar\tzot" to "foobarzot" [fails requirement 1]
(c) when fed a unicode object, gets TypeError: translate() takes exactly one argument (2 given) [fails requirement 2]
(d) uses string.whitespace[:-1] [fails requirement 3; order of characters in string.whitespace is not guaranteed]
(e) uses string.whitespace[:-1] [fails requirement 4; in Python 2.X, string.whitespace is '\t\n\x0b\x0c\r '; in Python 3.X, it is ' \t\n\r\x0b\x0c']
The " ".join(s.split()) answer and the re.sub(r"\s+", " ", s) answer don't have these problems.
A:
You could use the translate method
import string
s = "Please \n don't \t hurt \x0b me."
s = s.translate(None, string.whitespace[:-1]) # python 2.6 and up
s = s.translate(string.maketrans('',''), string.whitespace[:-1]) # python 2.5, dunno further down
>>> s
"Please don't hurt me."
And then remove duplicate whitespace
s.replace(' ', ' ')
>>> s
"Please don't hurt me."
A:
a starting point .. (although it's not shorter than manually assembling the whitespace circus) ..
>>> from string import whitespace as ws
>>> import re
>>> p = re.compile('(%s)' % ('|'.join([c for c in ws])))
>>> s = "Please \n don't \t hurt \x0b me."
>>> p.sub('', s)
"Pleasedon'thurtme."
Or if you want to reduce whitespace to a maximum of one:
>>> p1 = re.compile('(%s)' % ('|'.join([c for c in ws if not c == ' '])))
>>> p2 = re.compile(' +')
>>> s = "Please \n don't \t hurt \x0b me."
>>> p2.sub(' ', p1.sub('', s))
"Please don't hurt me."
Third way, more compact:
>>> import string
>>> s = "Please \n don't \t hurt \x0b me."
>>> s.translate(None, string.whitespace[])
"Pleasedon'thurtme."
>>> s.translate(None, string.whitespace[:5])
"Please don't hurt me."
>>> ' '.join(s.translate(None, string.whitespace[:5]).split())
"Please don't hurt me."
|
Remove whitespace in Python using string.whitespace
|
Python's string.whitespace is great:
>>> string.whitespace
'\t\n\x0b\x0c\r '
How do I use this with a string without resorting to manually typing in '\t|\n|... etc for regex?
For example, it should be able to turn:
"Please \n don't \t hurt \x0b me."
into
"Please don't hurt me."
I'd probably want to keep the single spaces, but it'd be easy enough to just go string.whitespace[:-1] I suppose.
|
[
"There is a special-case shortcut for exactly this use case!\nIf you call str.split without an argument, it splits on runs of whitespace instead of single characters. So:\n>>> ' '.join(\"Please \\n don't \\t hurt \\x0b me.\".split())\n\"Please don't hurt me.\"\n\n",
"What's wrong with the \\s character class?\n>>> import re\n\n>>> pattern = re.compile(r'\\s+')\n>>> re.sub(pattern, ' ', \"Please \\n don't \\t hurt \\x0b me.\")\n\"Please don't hurt me.\"\n\n",
"Let's make some reasonable assumptions:\n(1) You really want to replace any run of whitespace characters with a single space (a run is of length 1 or greater).\n(2) You would like the same code to work with minimal changes under Python 2.X with unicode objects.\n(3) You don't want your code to assume things that are not guaranteed in the docs\n(4) You would like the same code to work with minimal changes with Python 3.X str objects.\nThe currently selected answer has these problems:\n(a) changes \" \" * 3 to \" \" * 2 i.e. it removes duplicate spaces but not triplicate, quadruplicate, etc spaces. [fails requirement 1]\n(b) changes \"foo\\tbar\\tzot\" to \"foobarzot\" [fails requirement 1]\n(c) when fed a unicode object, gets TypeError: translate() takes exactly one argument (2 given) [fails requirement 2]\n(d) uses string.whitespace[:-1] [fails requirement 3; order of characters in string.whitespace is not guaranteed]\n(e) uses string.whitespace[:-1] [fails requirement 4; in Python 2.X, string.whitespace is '\\t\\n\\x0b\\x0c\\r '; in Python 3.X, it is ' \\t\\n\\r\\x0b\\x0c']\nThe \" \".join(s.split()) answer and the re.sub(r\"\\s+\", \" \", s) answer don't have these problems.\n",
"You could use the translate method\nimport string\n\ns = \"Please \\n don't \\t hurt \\x0b me.\"\ns = s.translate(None, string.whitespace[:-1]) # python 2.6 and up\ns = s.translate(string.maketrans('',''), string.whitespace[:-1]) # python 2.5, dunno further down\n>>> s\n\"Please don't hurt me.\"\n\nAnd then remove duplicate whitespace\ns.replace(' ', ' ')\n>>> s\n\"Please don't hurt me.\"\n\n",
"a starting point .. (although it's not shorter than manually assembling the whitespace circus) ..\n>>> from string import whitespace as ws\n>>> import re\n\n>>> p = re.compile('(%s)' % ('|'.join([c for c in ws])))\n>>> s = \"Please \\n don't \\t hurt \\x0b me.\"\n\n>>> p.sub('', s)\n\"Pleasedon'thurtme.\"\n\nOr if you want to reduce whitespace to a maximum of one:\n>>> p1 = re.compile('(%s)' % ('|'.join([c for c in ws if not c == ' '])))\n>>> p2 = re.compile(' +')\n>>> s = \"Please \\n don't \\t hurt \\x0b me.\"\n\n>>> p2.sub(' ', p1.sub('', s))\n\"Please don't hurt me.\"\n\nThird way, more compact:\n>>> import string\n\n>>> s = \"Please \\n don't \\t hurt \\x0b me.\"\n>>> s.translate(None, string.whitespace[])\n\"Pleasedon'thurtme.\"\n\n>>> s.translate(None, string.whitespace[:5])\n\"Please don't hurt me.\"\n\n>>> ' '.join(s.translate(None, string.whitespace[:5]).split())\n\"Please don't hurt me.\"\n\n"
] |
[
146,
14,
9,
2,
1
] |
[] |
[] |
[
"python",
"string",
"whitespace"
] |
stackoverflow_0001898656_python_string_whitespace.txt
|
Q:
Tree Transformations Using Visitor Pattern
(Disclaimer: these examples are given in the context of building a compiler, but this question is all about the Visitor pattern and does not require any knowledge of compiler theory.) I'm going through Andrew Appel's Modern Compiler Implementation in Java to try to teach myself compiler theory (so no, this isn't homework) and I'm having trouble understanding how he wants to use the Visitor pattern to transform an AST to an IR tree. (Note: I'm doing this in Python so I can learn Python also, which is why the upcoming examples are not in Java.) As I understand it, the visit and accept methods in the Visitor pattern are void-typed by design, so if I have something like
class PlusExp(Exp):
def __init__(self, exp_left, exp_right):
self.exp_left = exp_left
self.exp_right = exp_right
def accept(self, v):
v.visit_plus_exp(self)
then I would like to be able to write a visitor method like
def visit_plus_exp(self, plus_exp):
return BINOP(BinOp.PLUS,
plus_exp.exp_left.accept(self),
plus_exp.exp_right.accept(self))
which would translate the two child expressions into IR and then link them up with the BINOP representing the plus expression. Of course, this isn't possible unless I modify all the accept functions to return extra info, and that is also messy because sometimes you just want a print visitor that doesn't return anything. Yet, this text insists that a visitor is the right way to go, and in Java at that, which means it can be done without the flexibility of Python. I can't think of any solutions that aren't incredibly hacky - can anyone enlighten me as to the intended design?
A:
A SAX parser is a kind of visitor. To avoid adding a return value to the method, you can use a stack:
class Visitor {
Stack<Node> stack = new Stack<Node>();
// . . .
void visitPlus(PlusExp pe) {
pe.left.accept(this);
pe.right.accept(this);
Node b = stack.pop();
Node a = stack.pop();
stack.push(new BinOp(BinOp.PLUS, a, b));
}
A:
Look at source code of THIS compiler. I think that the guy has used Visitor pattern.
A:
Caveat: I haven't read that book.
The method may be void-typed, but in Java (which the book was written for) it is also part of an object. So, the visitor method can build up the structure in a local member variable, thus maintaining the necessary context between calls.
So, for instance, your print visitor would be appending to a StringBuilder that is held as a member variable (or as a final local variable in a method that created the visitor object -- this is fairly common in Java, where creating small anonymous-inner-class objects is a common habit).
In python, you could similarly let the visitor method access a non-method-local variable to maintain context and build the structure. Eg, closure, or a small object.
Update -- small bit of code added as example from comment below
result = new Node();
result.left.add(n1.accept(this));
result.right.add(n2.accept(this));
return result;
or
result = new Node();
this.nextLoc.add(result);
this.nextLoc = result.left;
n1.accept(this);
this.nextLoc = result.right;
n2.accept(this);
The first is prettier (though still crappy comment example code), but the second would let you keep the void return type if you really needed to.
|
Tree Transformations Using Visitor Pattern
|
(Disclaimer: these examples are given in the context of building a compiler, but this question is all about the Visitor pattern and does not require any knowledge of compiler theory.) I'm going through Andrew Appel's Modern Compiler Implementation in Java to try to teach myself compiler theory (so no, this isn't homework) and I'm having trouble understanding how he wants to use the Visitor pattern to transform an AST to an IR tree. (Note: I'm doing this in Python so I can learn Python also, which is why the upcoming examples are not in Java.) As I understand it, the visit and accept methods in the Visitor pattern are void-typed by design, so if I have something like
class PlusExp(Exp):
def __init__(self, exp_left, exp_right):
self.exp_left = exp_left
self.exp_right = exp_right
def accept(self, v):
v.visit_plus_exp(self)
then I would like to be able to write a visitor method like
def visit_plus_exp(self, plus_exp):
return BINOP(BinOp.PLUS,
plus_exp.exp_left.accept(self),
plus_exp.exp_right.accept(self))
which would translate the two child expressions into IR and then link them up with the BINOP representing the plus expression. Of course, this isn't possible unless I modify all the accept functions to return extra info, and that is also messy because sometimes you just want a print visitor that doesn't return anything. Yet, this text insists that a visitor is the right way to go, and in Java at that, which means it can be done without the flexibility of Python. I can't think of any solutions that aren't incredibly hacky - can anyone enlighten me as to the intended design?
|
[
"A SAX parser is a kind of visitor. To avoid adding a return value to the method, you can use a stack:\nclass Visitor {\n Stack<Node> stack = new Stack<Node>();\n\n// . . .\n\n void visitPlus(PlusExp pe) {\n pe.left.accept(this);\n pe.right.accept(this);\n Node b = stack.pop();\n Node a = stack.pop();\n stack.push(new BinOp(BinOp.PLUS, a, b));\n }\n\n",
"Look at source code of THIS compiler. I think that the guy has used Visitor pattern.\n",
"Caveat: I haven't read that book.\nThe method may be void-typed, but in Java (which the book was written for) it is also part of an object. So, the visitor method can build up the structure in a local member variable, thus maintaining the necessary context between calls.\nSo, for instance, your print visitor would be appending to a StringBuilder that is held as a member variable (or as a final local variable in a method that created the visitor object -- this is fairly common in Java, where creating small anonymous-inner-class objects is a common habit).\nIn python, you could similarly let the visitor method access a non-method-local variable to maintain context and build the structure. Eg, closure, or a small object.\nUpdate -- small bit of code added as example from comment below\nresult = new Node();\nresult.left.add(n1.accept(this)); \nresult.right.add(n2.accept(this)); \nreturn result;\n\nor \nresult = new Node(); \nthis.nextLoc.add(result); \nthis.nextLoc = result.left; \nn1.accept(this); \nthis.nextLoc = result.right; \nn2.accept(this); \n\nThe first is prettier (though still crappy comment example code), but the second would let you keep the void return type if you really needed to.\n"
] |
[
11,
1,
0
] |
[] |
[] |
[
"abstract_syntax_tree",
"java",
"python",
"tree",
"visitor_pattern"
] |
stackoverflow_0001898967_abstract_syntax_tree_java_python_tree_visitor_pattern.txt
|
Q:
How can I get the target platform info of a dll with Python 3.1.1?
I have many dll files and I would like to select them into two different folders (PC and PPC).
For this I need to know the target platform of the dll file or any other details about its platform.
I use Python 3.1.1. I have tried the win32api which does not compatible with this Python version. So, I tried to use the ctypes.windll with try-except method where the try is true the loaded-in dll is "PC" and if not, unable to load the dll that is "PPC". But, I have a problem with this idea.
There are some dll files which I know that "PC" dll but unable to load in memory. The try-except does not work with them. So, I need to request info from the dll file about the target platform of itself.
Do you have any idea about this problem?
Many thanks.
A:
I found a solution based on the dll file structure. Here is the part of my code:
def DLLIdentifier( self ):
'''
Microsoft Portable Executable and Common Object File Format Specification
http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
After the MS DOS stub, at the file offset specified at offset 0x3c,
is a 4-byte signature that identifies the file as a PE format image file.
This signature is "PE\0\0" (the letters "P" and "E" followed by two null bytes).
At the beginning of an object file, or immediately after the signature of an image file,
is a standard COFF file header in the following format.
Note that the Windows loader limits the number of sections to 96.
The Machine field has one of the following values that specifies its CPU type.
An image file can be run only on the specified machine or on a system that emulates the specified machine.
'''
Platform = 'UNKNOWN'
for Row in codecs.open( os.path.join( self.Root, self.File ), 'rb' ):
if b'\x00PE\x00\x00' in Row:
# IMAGE_FILE_MACHINE_UNKNOWN 0x0 The contents of this field are assumed to be applicable to any machine type
if b'\x00PE\x00\x00\x00\x00' in Row:
Platform = 'UNKNOWN'
break
# IMAGE_FILE_MACHINE_AM33 0x1d3 Matsushita AM33
elif b'\x00PE\x00\x00\xD3\x01' in Row:
Platform = 'AM33'
break
# IMAGE_FILE_MACHINE_AMD64 0x8664 x64
elif b'\x00PE\x00\x00\x664\x08' in Row:
Platform = 'AMD64'
break
# IMAGE_FILE_MACHINE_ARM 0x1c0 ARM little endian
elif b'\x00PE\x00\x00\xC0\x01' in Row:
Platform = 'ARM'
break
# IMAGE_FILE_MACHINE_EBC 0xebc EFI byte code
elif b'\x00PE\x00\x00\xBC\x0E' in Row:
Platform = 'EBC'
break
# IMAGE_FILE_MACHINE_I386 0x14c Intel 386 or later processors and compatible processors
elif b'\x00PE\x00\x00\x4C\x01' in Row:
Platform = 'I386'
break
# IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family
elif b'\x00PE\x00\x00\x00\x02' in Row:
Platform = 'IA64'
break
# IMAGE_FILE_MACHINE_M32R 0x9041 Mitsubishi M32R little endian
elif b'\x00PE\x00\x00\x041\x09' in Row:
Platform = 'M32R'
break
# IMAGE_FILE_MACHINE_MIPS16 0x266 MIPS16
elif b'\x00PE\x00\x00\x66\x02' in Row:
Platform = 'MIPS16'
break
# IMAGE_FILE_MACHINE_MIPSFPU 0x366 MIPS with FPU
elif b'\x00PE\x00\x00\x66\x03' in Row:
Platform = 'MIPSFPU'
break
# IMAGE_FILE_MACHINE_MIPSFPU16 0x466 MIPS16 with FPU
elif b'\x00PE\x00\x00\x66\x04' in Row:
Platform = 'MIPSFPU16'
break
# IMAGE_FILE_MACHINE_POWERPC 0x1f0 Power PC little endian
elif b'\x00PE\x00\x00\xF0\x01' in Row:
Platform = 'POWERPC'
break
# IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 Power PC with floating point support
elif b'\x00PE\x00\x00\xF1\x01' in Row:
Platform = 'POWERPCFP'
break
# IMAGE_FILE_MACHINE_R4000 0x166 MIPS little endian
elif b'\x00PE\x00\x00\x66\x01' in Row:
Platform = 'R4000'
break
# IMAGE_FILE_MACHINE_SH3 0x1a2 Hitachi SH3
elif b'\x00PE\x00\x00\xA2\x01' in Row:
Platform = 'SH3'
break
# IMAGE_FILE_MACHINE_SH3DSP 0x1a3 Hitachi SH3 DSP
elif b'\x00PE\x00\x00\xA3\x01' in Row:
Platform = 'SH3DSP'
break
# IMAGE_FILE_MACHINE_SH4 0x1a6 Hitachi SH4
elif b'\x00PE\x00\x00\xA6\x01' in Row:
Platform = 'SH4'
break
# IMAGE_FILE_MACHINE_SH5 0x1a8 Hitachi SH5
elif b'\x00PE\x00\x00\xA8\x01' in Row:
Platform = 'SH5'
break
# IMAGE_FILE_MACHINE_THUMB 0x1c2 Thumb
elif b'\x00PE\x00\x00\xC2\x01' in Row:
Platform = 'THUMB'
break
# IMAGE_FILE_MACHINE_WCEMIPSV2 0x169 MIPS little - endian WCE v2
elif b'\x00PE\x00\x00\x69\x01' in Row:
Platform = 'WCEMIPSV2'
break
else:
StartIndex = Row.find( b'\x00PE\x00\x00' )
EndIndex = StartIndex + 7
PlatformCode = Row[StartIndex:EndIndex]
self.ErrorState = False
self.oLogger.critical( 'The unknown platform code is "{}".'.format( PlatformCode ) )
assert Platform != 'UNKNOWN', 'Unknown .dll file "{}" at\n{}'.format( self.File, os.path.join( self.Root, self.File ) )
if Platform == 'I386':
self.PlatformType = 'PC'
elif Platform in ( 'ARM', 'THUMB' ):
self.PlatformType = 'PPC'
else:
self.ErrorState = False
self.oLogger.critical( 'The unknown dll file with "{}" platform code.'.format( Platform ) )
|
How can I get the target platform info of a dll with Python 3.1.1?
|
I have many dll files and I would like to select them into two different folders (PC and PPC).
For this I need to know the target platform of the dll file or any other details about its platform.
I use Python 3.1.1. I have tried the win32api which does not compatible with this Python version. So, I tried to use the ctypes.windll with try-except method where the try is true the loaded-in dll is "PC" and if not, unable to load the dll that is "PPC". But, I have a problem with this idea.
There are some dll files which I know that "PC" dll but unable to load in memory. The try-except does not work with them. So, I need to request info from the dll file about the target platform of itself.
Do you have any idea about this problem?
Many thanks.
|
[
"I found a solution based on the dll file structure. Here is the part of my code:\ndef DLLIdentifier( self ):\n '''\n Microsoft Portable Executable and Common Object File Format Specification\n http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx \n\n After the MS DOS stub, at the file offset specified at offset 0x3c, \n is a 4-byte signature that identifies the file as a PE format image file. \n This signature is \"PE\\0\\0\" (the letters \"P\" and \"E\" followed by two null bytes).\n At the beginning of an object file, or immediately after the signature of an image file, \n is a standard COFF file header in the following format. \n Note that the Windows loader limits the number of sections to 96.\n The Machine field has one of the following values that specifies its CPU type. \n An image file can be run only on the specified machine or on a system that emulates the specified machine.\n '''\n Platform = 'UNKNOWN'\n for Row in codecs.open( os.path.join( self.Root, self.File ), 'rb' ):\n if b'\\x00PE\\x00\\x00' in Row:\n # IMAGE_FILE_MACHINE_UNKNOWN 0x0 The contents of this field are assumed to be applicable to any machine type\n if b'\\x00PE\\x00\\x00\\x00\\x00' in Row:\n Platform = 'UNKNOWN'\n break\n # IMAGE_FILE_MACHINE_AM33 0x1d3 Matsushita AM33\n elif b'\\x00PE\\x00\\x00\\xD3\\x01' in Row:\n Platform = 'AM33'\n break\n # IMAGE_FILE_MACHINE_AMD64 0x8664 x64\n elif b'\\x00PE\\x00\\x00\\x664\\x08' in Row:\n Platform = 'AMD64'\n break\n # IMAGE_FILE_MACHINE_ARM 0x1c0 ARM little endian\n elif b'\\x00PE\\x00\\x00\\xC0\\x01' in Row:\n Platform = 'ARM'\n break\n # IMAGE_FILE_MACHINE_EBC 0xebc EFI byte code\n elif b'\\x00PE\\x00\\x00\\xBC\\x0E' in Row:\n Platform = 'EBC'\n break\n # IMAGE_FILE_MACHINE_I386 0x14c Intel 386 or later processors and compatible processors\n elif b'\\x00PE\\x00\\x00\\x4C\\x01' in Row:\n Platform = 'I386'\n break\n # IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family\n elif b'\\x00PE\\x00\\x00\\x00\\x02' in Row:\n Platform = 'IA64'\n break\n # IMAGE_FILE_MACHINE_M32R 0x9041 Mitsubishi M32R little endian\n elif b'\\x00PE\\x00\\x00\\x041\\x09' in Row:\n Platform = 'M32R'\n break\n # IMAGE_FILE_MACHINE_MIPS16 0x266 MIPS16\n elif b'\\x00PE\\x00\\x00\\x66\\x02' in Row:\n Platform = 'MIPS16'\n break\n # IMAGE_FILE_MACHINE_MIPSFPU 0x366 MIPS with FPU\n elif b'\\x00PE\\x00\\x00\\x66\\x03' in Row:\n Platform = 'MIPSFPU'\n break\n # IMAGE_FILE_MACHINE_MIPSFPU16 0x466 MIPS16 with FPU\n elif b'\\x00PE\\x00\\x00\\x66\\x04' in Row:\n Platform = 'MIPSFPU16'\n break\n # IMAGE_FILE_MACHINE_POWERPC 0x1f0 Power PC little endian\n elif b'\\x00PE\\x00\\x00\\xF0\\x01' in Row:\n Platform = 'POWERPC'\n break\n # IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 Power PC with floating point support\n elif b'\\x00PE\\x00\\x00\\xF1\\x01' in Row:\n Platform = 'POWERPCFP'\n break\n # IMAGE_FILE_MACHINE_R4000 0x166 MIPS little endian\n elif b'\\x00PE\\x00\\x00\\x66\\x01' in Row:\n Platform = 'R4000'\n break\n # IMAGE_FILE_MACHINE_SH3 0x1a2 Hitachi SH3\n elif b'\\x00PE\\x00\\x00\\xA2\\x01' in Row:\n Platform = 'SH3'\n break\n # IMAGE_FILE_MACHINE_SH3DSP 0x1a3 Hitachi SH3 DSP\n elif b'\\x00PE\\x00\\x00\\xA3\\x01' in Row:\n Platform = 'SH3DSP'\n break\n # IMAGE_FILE_MACHINE_SH4 0x1a6 Hitachi SH4\n elif b'\\x00PE\\x00\\x00\\xA6\\x01' in Row:\n Platform = 'SH4'\n break\n # IMAGE_FILE_MACHINE_SH5 0x1a8 Hitachi SH5\n elif b'\\x00PE\\x00\\x00\\xA8\\x01' in Row:\n Platform = 'SH5'\n break\n # IMAGE_FILE_MACHINE_THUMB 0x1c2 Thumb\n elif b'\\x00PE\\x00\\x00\\xC2\\x01' in Row:\n Platform = 'THUMB'\n break\n # IMAGE_FILE_MACHINE_WCEMIPSV2 0x169 MIPS little - endian WCE v2\n elif b'\\x00PE\\x00\\x00\\x69\\x01' in Row:\n Platform = 'WCEMIPSV2'\n break\n else:\n StartIndex = Row.find( b'\\x00PE\\x00\\x00' )\n EndIndex = StartIndex + 7\n PlatformCode = Row[StartIndex:EndIndex]\n self.ErrorState = False\n self.oLogger.critical( 'The unknown platform code is \"{}\".'.format( PlatformCode ) )\n\n assert Platform != 'UNKNOWN', 'Unknown .dll file \"{}\" at\\n{}'.format( self.File, os.path.join( self.Root, self.File ) )\n\n if Platform == 'I386':\n self.PlatformType = 'PC'\n elif Platform in ( 'ARM', 'THUMB' ):\n self.PlatformType = 'PPC'\n else:\n self.ErrorState = False\n self.oLogger.critical( 'The unknown dll file with \"{}\" platform code.'.format( Platform ) )\n\n"
] |
[
1
] |
[] |
[] |
[
"api",
"dll",
"platform",
"python",
"winapi"
] |
stackoverflow_0001889694_api_dll_platform_python_winapi.txt
|
Q:
Why is SQLAlchemy/associationproxy duplicating my tags?
I'm trying to use association proxy for tags, in a very similar scenario to the example in the docs. Here is a subset of my schema (it's a blog), using declarative:
class Tag(Base):
__tablename__ = 'tags'
id = Column(Integer, primary_key=True)
tag = Column(Unicode(255), unique=True, nullable=False)
class EntryTag(Base):
__tablename__ = 'entrytags'
entry_id = Column(Integer, ForeignKey('entries.id'), key='entry', primary_key=True)
tag_id = Column(Integer, ForeignKey('tags.id'), key='tag', primary_key=True)
class Entry(Base):
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
subject = Column(Unicode(255), nullable=False)
# some other fields here
_tags = relation('Tag', backref='entries', secondary=EntryTag.__table__)
tags = association_proxy('_tags','tag')
Here's how I'm trying to use it:
>>> e = db.query(Entry).first()
>>> e.tags
[u'foo']
>>> e.tags = [u'foo', u'bar'] # really this is from a comma-separated input
db.commit()
Traceback (most recent call last):
[...]
sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates unique constraint "tags_tag_key"
'INSERT INTO tags (id, tag) VALUES (%(id)s, %(tag)s)' {'tag': 'bar', 'id': 11L}
>>> map(lambda t:(t.id,t.tag), db.query(Tag).all())
[(1, u'foo'), (2, u'bar'), (3, u'baz')]
The tag u'bar' already existed with id 2; why didn't SQLAlchemy just attach that one instead of trying to create it? Is my schema wrong somehow?
A:
Disclaimer: it's been ages since I used SQLAlchemy so this is more of a guess than anything.
It looks like you're expecting SQLAlchemy to magically take the string 'bar' and look up the relevant Tag for it when performing the insert on the many-to-many table. I expect this is invalid, because the field in question ('tag') is not a primary key.
Imagine a similar situation where your Tag table is actually Comment, also with an id and a text field. You'd expect to be able to add Comments to an Entry with the same e.comments = ['u'Foo', 'u'Bar'] syntax that you've used above, but you'd want it to just perform INSERTs, not check for existing comments with the same content.
So that is probably what it's doing here, but it hits the uniqueness constraint on your tag name and fails, assuming that you're attempting to do the wrong thing.
How to fix it? Making tags.tag the primary key is arguably the correct thing to do, although I don't know how efficient that is nor how well SQLAlchemy handles it. Failing that, try querying for Tag objects by name before assigning them to the entry. You may have to write a little utility function that takes a unicode string and either returns an existing Tag or creates a new one for you.
A:
I've never used SQLAlchemy 0.5 yet (my last app using it was 0.4 based) but I can see one quirk in your code: you should modify the association_proxy object, not reassign it.
Try doing something like:
e.tags.append(u"bar")
Instead of
e.tags = ...
If that doesn't work, try pasting a complete working example for those tables (including the imports, please!) and I'll give you some more advice.
|
Why is SQLAlchemy/associationproxy duplicating my tags?
|
I'm trying to use association proxy for tags, in a very similar scenario to the example in the docs. Here is a subset of my schema (it's a blog), using declarative:
class Tag(Base):
__tablename__ = 'tags'
id = Column(Integer, primary_key=True)
tag = Column(Unicode(255), unique=True, nullable=False)
class EntryTag(Base):
__tablename__ = 'entrytags'
entry_id = Column(Integer, ForeignKey('entries.id'), key='entry', primary_key=True)
tag_id = Column(Integer, ForeignKey('tags.id'), key='tag', primary_key=True)
class Entry(Base):
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
subject = Column(Unicode(255), nullable=False)
# some other fields here
_tags = relation('Tag', backref='entries', secondary=EntryTag.__table__)
tags = association_proxy('_tags','tag')
Here's how I'm trying to use it:
>>> e = db.query(Entry).first()
>>> e.tags
[u'foo']
>>> e.tags = [u'foo', u'bar'] # really this is from a comma-separated input
db.commit()
Traceback (most recent call last):
[...]
sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates unique constraint "tags_tag_key"
'INSERT INTO tags (id, tag) VALUES (%(id)s, %(tag)s)' {'tag': 'bar', 'id': 11L}
>>> map(lambda t:(t.id,t.tag), db.query(Tag).all())
[(1, u'foo'), (2, u'bar'), (3, u'baz')]
The tag u'bar' already existed with id 2; why didn't SQLAlchemy just attach that one instead of trying to create it? Is my schema wrong somehow?
|
[
"Disclaimer: it's been ages since I used SQLAlchemy so this is more of a guess than anything.\nIt looks like you're expecting SQLAlchemy to magically take the string 'bar' and look up the relevant Tag for it when performing the insert on the many-to-many table. I expect this is invalid, because the field in question ('tag') is not a primary key.\nImagine a similar situation where your Tag table is actually Comment, also with an id and a text field. You'd expect to be able to add Comments to an Entry with the same e.comments = ['u'Foo', 'u'Bar'] syntax that you've used above, but you'd want it to just perform INSERTs, not check for existing comments with the same content.\nSo that is probably what it's doing here, but it hits the uniqueness constraint on your tag name and fails, assuming that you're attempting to do the wrong thing.\nHow to fix it? Making tags.tag the primary key is arguably the correct thing to do, although I don't know how efficient that is nor how well SQLAlchemy handles it. Failing that, try querying for Tag objects by name before assigning them to the entry. You may have to write a little utility function that takes a unicode string and either returns an existing Tag or creates a new one for you.\n",
"I've never used SQLAlchemy 0.5 yet (my last app using it was 0.4 based) but I can see one quirk in your code: you should modify the association_proxy object, not reassign it.\nTry doing something like:\ne.tags.append(u\"bar\")\n\nInstead of\ne.tags = ...\n\nIf that doesn't work, try pasting a complete working example for those tables (including the imports, please!) and I'll give you some more advice.\n"
] |
[
3,
0
] |
[] |
[] |
[
"declarative",
"orm",
"python",
"sqlalchemy",
"tags"
] |
stackoverflow_0001899984_declarative_orm_python_sqlalchemy_tags.txt
|
Q:
Is there a function that gives me a file name without path?
I want to turn C:\abc.bmp into abc.bmp, or even better, if possible, in abc. That is easy to do with .NET as there are functions for both goals. Is there anything similar in python?
A:
>>> os.path.basename(r'C:\abc.txt')
'abc.txt'
for basename only:
>>> base, ext = os.path.splitext(os.path.basename(r'C:\abc.txt'))
>>> base
'abc'
A:
Try os.path.basename().
|
Is there a function that gives me a file name without path?
|
I want to turn C:\abc.bmp into abc.bmp, or even better, if possible, in abc. That is easy to do with .NET as there are functions for both goals. Is there anything similar in python?
|
[
">>> os.path.basename(r'C:\\abc.txt')\n'abc.txt'\n\nfor basename only:\n>>> base, ext = os.path.splitext(os.path.basename(r'C:\\abc.txt'))\n>>> base\n'abc'\n\n",
"Try os.path.basename().\n"
] |
[
11,
3
] |
[] |
[] |
[
"path",
"python"
] |
stackoverflow_0001900216_path_python.txt
|
Q:
Django Model returning NoneType
I have a model Product
it has two fields size & colours among others
colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
In my view I have
current_product = Product.objects.get(slug=title)
if len(current_product.size) != 0 :
current_product.size = current_product.size.split(",")
and get this error:
object of type 'NoneType' has no len()
What is NoneType and how can I test for it?
A:
NoneType is the type that the None value has. You want to change the second snippet to
if current_product.size: # This will evaluate as false if size is None or len(size) == 0.
blah blah
A:
NoneType is Pythons NULL-Type, meaning "nothing", "undefined". It has only one value: "None". When creating a new model object, its attributes are usually initialized to None, you can check that by comparing:
if someobject.someattr is None:
# Not set yet
A:
I can best explain the NoneType error with this example of erroneous code:
def test():
s = list([1,'',2,3,4,'',5])
try:
s = s.remove('') # <-- THIS WRONG because it turns s in to a NoneType
except:
pass
print(str(s))
s.remove() returns nothing also known as NoneType. The correct way
def test2()
s = list([1,'',2,3,4,'',5])
try:
s.remove('') # <-- CORRECTED
except:
pass
print(str(s))
|
Django Model returning NoneType
|
I have a model Product
it has two fields size & colours among others
colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
In my view I have
current_product = Product.objects.get(slug=title)
if len(current_product.size) != 0 :
current_product.size = current_product.size.split(",")
and get this error:
object of type 'NoneType' has no len()
What is NoneType and how can I test for it?
|
[
"NoneType is the type that the None value has. You want to change the second snippet to\nif current_product.size: # This will evaluate as false if size is None or len(size) == 0.\n blah blah\n\n",
"NoneType is Pythons NULL-Type, meaning \"nothing\", \"undefined\". It has only one value: \"None\". When creating a new model object, its attributes are usually initialized to None, you can check that by comparing:\nif someobject.someattr is None:\n # Not set yet\n\n",
"I can best explain the NoneType error with this example of erroneous code: \ndef test(): \n s = list([1,'',2,3,4,'',5]) \n try: \n s = s.remove('') # <-- THIS WRONG because it turns s in to a NoneType \n except: \n pass \n print(str(s)) \n\ns.remove() returns nothing also known as NoneType. The correct way \ndef test2() \n s = list([1,'',2,3,4,'',5]) \n try: \n s.remove('') # <-- CORRECTED \n except: \n pass \n print(str(s)) \n\n"
] |
[
8,
1,
0
] |
[
"I don't know Django, but I assume that some kind of ORM is involved when you do this:\ncurrent_product = Product.objects.get(slug=title)\n\nAt that point you should always check whether you get None back ('None' is the same as 'null' in Java or 'nil' in Lisp with the subtle difference that 'None' is an object in Python). This is usually the way ORMs map the empty set to the programming language.\nEDIT:\nGee, I just see that it's current_product.size that's None not current_product. As said, I'm not familiar with Django's ORM, but this seems strange nevertheless: I'd either expect current_product to be None or size having a numerical value.\n"
] |
[
-1
] |
[
"django",
"django_views",
"python"
] |
stackoverflow_0000552521_django_django_views_python.txt
|
Q:
Need example/help with GtkTextBuffer (of GtkTextView) serialize/deserialize
I am trying to save user's bold/italic/font/etc tags in a GtkTextView.
Using GtkTextBuffer.get_text() does not return the tags.
The best documentation I have found on this is:
http://www.pygtk.org/docs/pygtk/class-gtktextbuffer.html#method-gtktextbuffer--register-serialize-format
However, I do not understand the function arguments.
It would be infinitely handy to have an example of how these are used to save/load a textview with tags in it.
Edit: I would like to clarify what I am trying to accomplish. Basically I want to save/load the textview's text+tags. I have no desire to do anything more complicated than that. I am using pickle as the file format, so I dont need any help here on how to save it or in what format. Just need a way to pull/push the data so that the user loses nothing that he/she sees on screen. Thank you.
A:
If you need to save the tags because you just want to copy the text into another text buffer, you can use gtk.TextBuffer.insert_range().
If you need to save the text with tags into another format readable by other programs, I once wrote a library with a GTK text buffer serializer to and from RTF. It doesn't have any Python bindings though. But in any case the code is a good example of how to use the serializer facility. Link: Osxcart
A:
I haven't worked with GtkTextBuffer's serialization. Reading the documentation you linked, I would suggest trying the default serializer, by calling
textbuffer.register_serialize_tagset()
This gives you GTK+'s built-in proprietary serializer. Being proprietary here means that it doesn't serialize into some well-known format; but if all you need is the ability to save out the text buffer's contents and load them back, this should be fine.
Of course the source code is available inside GTK+ if you really want to figure out how it works; I would recommend against trying to implement e.g. a stand-alone de-serializer though, since there are probably no guarantees made by GTK+ that the format will remain as-is.
|
Need example/help with GtkTextBuffer (of GtkTextView) serialize/deserialize
|
I am trying to save user's bold/italic/font/etc tags in a GtkTextView.
Using GtkTextBuffer.get_text() does not return the tags.
The best documentation I have found on this is:
http://www.pygtk.org/docs/pygtk/class-gtktextbuffer.html#method-gtktextbuffer--register-serialize-format
However, I do not understand the function arguments.
It would be infinitely handy to have an example of how these are used to save/load a textview with tags in it.
Edit: I would like to clarify what I am trying to accomplish. Basically I want to save/load the textview's text+tags. I have no desire to do anything more complicated than that. I am using pickle as the file format, so I dont need any help here on how to save it or in what format. Just need a way to pull/push the data so that the user loses nothing that he/she sees on screen. Thank you.
|
[
"If you need to save the tags because you just want to copy the text into another text buffer, you can use gtk.TextBuffer.insert_range().\nIf you need to save the text with tags into another format readable by other programs, I once wrote a library with a GTK text buffer serializer to and from RTF. It doesn't have any Python bindings though. But in any case the code is a good example of how to use the serializer facility. Link: Osxcart\n",
"I haven't worked with GtkTextBuffer's serialization. Reading the documentation you linked, I would suggest trying the default serializer, by calling\ntextbuffer.register_serialize_tagset()\n\nThis gives you GTK+'s built-in proprietary serializer. Being proprietary here means that it doesn't serialize into some well-known format; but if all you need is the ability to save out the text buffer's contents and load them back, this should be fine.\nOf course the source code is available inside GTK+ if you really want to figure out how it works; I would recommend against trying to implement e.g. a stand-alone de-serializer though, since there are probably no guarantees made by GTK+ that the format will remain as-is.\n"
] |
[
3,
1
] |
[] |
[] |
[
"gtk",
"gtk2",
"pygtk",
"python"
] |
stackoverflow_0001885552_gtk_gtk2_pygtk_python.txt
|
Q:
How to access a standard-library module in Python when there is a local module with the same name?
How can a standard-library module (say math) be accessed when a file prog.py is placed in the same directory as a local module with the same name (math.py)?
I'm asking this question because I would like to create a package uncertainties that one can use as
import uncertainties
from uncertainties.math import *
Thus, there is a local math module inside the uncertainties directory. The problem is that I want to access the standard library math module from uncertainties/__init__.py.
I prefer not to rename uncertainties.math because this module is precisely intended to replace functions from the math module (with equivalents that handle numerical uncertainties).
PS: this question pertains to the module I wrote for performing calculations with uncertainties while taking into account correlations between variables.
A:
You are looking for Absolute/Relative imports from PEP 328, available with 2.5 and upward.
In Python 2.5, you can switch import‘s behaviour to absolute imports using a from __future__ import absolute_import directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import math will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing from pkg import string in your code.
Relative imports are still possible by adding a leading period to the module name when using the from ... import form:
from __future__ import absolute_import
# Import uncertainties.math
from . import math as local_math
import math as sys_math
A:
Why can't you rename your local module again?
Clearly, it's not a "total" replacement, if you still need things from the installed uncertainties.
Since it's a partial replacement, you should not give it the same name.
What's different? What's the same? Pick a better name based on that.
|
How to access a standard-library module in Python when there is a local module with the same name?
|
How can a standard-library module (say math) be accessed when a file prog.py is placed in the same directory as a local module with the same name (math.py)?
I'm asking this question because I would like to create a package uncertainties that one can use as
import uncertainties
from uncertainties.math import *
Thus, there is a local math module inside the uncertainties directory. The problem is that I want to access the standard library math module from uncertainties/__init__.py.
I prefer not to rename uncertainties.math because this module is precisely intended to replace functions from the math module (with equivalents that handle numerical uncertainties).
PS: this question pertains to the module I wrote for performing calculations with uncertainties while taking into account correlations between variables.
|
[
"You are looking for Absolute/Relative imports from PEP 328, available with 2.5 and upward.\nIn Python 2.5, you can switch import‘s behaviour to absolute imports using a from __future__ import absolute_import directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import math will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing from pkg import string in your code.\n\n\nRelative imports are still possible by adding a leading period to the module name when using the from ... import form:\nfrom __future__ import absolute_import\n# Import uncertainties.math\nfrom . import math as local_math\nimport math as sys_math\n\n",
"Why can't you rename your local module again? \nClearly, it's not a \"total\" replacement, if you still need things from the installed uncertainties. \nSince it's a partial replacement, you should not give it the same name. \nWhat's different? What's the same? Pick a better name based on that.\n"
] |
[
22,
4
] |
[] |
[] |
[
"import",
"module",
"python",
"standard_library"
] |
stackoverflow_0001900189_import_module_python_standard_library.txt
|
Q:
ORM library for automatically mapping foreign keys in Python or Ruby
A frequent task I run into at work is writing scripts against pre-existing databases. Sometimes I'm connecting to Oracle, other times it might be MySql or even sql server.
What I would like is a tool which would reverse-engineer the database's tables and foreign keys and allow me to write OO-style scripts against the database. This could be in any language really, but python or ruby would be preferred.
For example - this is my ideal ruby script: (assuming the manager and employee tables already exist with foreign keys)
DB = Database.connect(connect_string)
DB.managers.each do |manager|
puts manager.name
manager.employees.each do |employee|
puts employee.name
end
end
Does this type of library exist? If so, it would save me so much time!
Edit - the main feature I would like is for it to automatically discover foreign key associations from the database metadata without explicitly mapping them - I have tried ActiveRecord, SQLAlchemy, Sequel, and DataMapper, and from what I can tell, none of them can do this.
A:
You should take a look at the SQLSoup extension in SQLAlchemy. It claims to do all this for you (including foreign keys). I haven't tested it myself.
A:
Serious Ruby ORMs don't do this for a reason: it's inflexible, not explicit enough and too much magic.
If you really want this in your project, try coding it yourself in Ruby. Here's what I've done in 5 minutes on top of ActiveRecord:
require 'active_record'
class ActiveRecord::Base
def self.magic!
connection.tables.map { |table|
klass = Class.new(self)
Object.send(:const_set, table.singularize.camelize, klass)
}.each { |model|
model.column_names.grep(/_id$/).each { |foreign_key|
name = foreign_key.sub(/_id$/, '')
model.belongs_to(name)
name.camelize.constantize.has_many(model.name.tableize)
}
}
end
end
Let's set up our database tables and have magic! analyze them:
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
ActiveRecord::Schema.define do
create_table "managers" do |t|
t.string "name"
end
create_table "employees" do |t|
t.string "name"
t.belongs_to "manager"
end
end
# it happens!
ActiveRecord::Base.magic!
Create some test records and use it in the way you wanted:
mislav = Manager.create :name => "Mislav"
mislav.employees.create(:name => "Josh")
mislav.employees.create(:name => "Mike")
Manager.all.each do |manager|
puts manager.name
manager.employees.each do |employee|
puts employee.name
end
end
Full code available on this Gist.
This only works with belongs_to and has_many associations. If you need a real library that does this and much more, check out Dr Nic's Magic Models.
A:
Try the sqlautocode module for SQLAlchemy. It will generate the ORM classes by reflecting the database.
|
ORM library for automatically mapping foreign keys in Python or Ruby
|
A frequent task I run into at work is writing scripts against pre-existing databases. Sometimes I'm connecting to Oracle, other times it might be MySql or even sql server.
What I would like is a tool which would reverse-engineer the database's tables and foreign keys and allow me to write OO-style scripts against the database. This could be in any language really, but python or ruby would be preferred.
For example - this is my ideal ruby script: (assuming the manager and employee tables already exist with foreign keys)
DB = Database.connect(connect_string)
DB.managers.each do |manager|
puts manager.name
manager.employees.each do |employee|
puts employee.name
end
end
Does this type of library exist? If so, it would save me so much time!
Edit - the main feature I would like is for it to automatically discover foreign key associations from the database metadata without explicitly mapping them - I have tried ActiveRecord, SQLAlchemy, Sequel, and DataMapper, and from what I can tell, none of them can do this.
|
[
"You should take a look at the SQLSoup extension in SQLAlchemy. It claims to do all this for you (including foreign keys). I haven't tested it myself.\n",
"Serious Ruby ORMs don't do this for a reason: it's inflexible, not explicit enough and too much magic.\nIf you really want this in your project, try coding it yourself in Ruby. Here's what I've done in 5 minutes on top of ActiveRecord:\nrequire 'active_record'\n\nclass ActiveRecord::Base\n def self.magic!\n connection.tables.map { |table|\n klass = Class.new(self)\n Object.send(:const_set, table.singularize.camelize, klass)\n }.each { |model|\n model.column_names.grep(/_id$/).each { |foreign_key|\n name = foreign_key.sub(/_id$/, '')\n model.belongs_to(name)\n name.camelize.constantize.has_many(model.name.tableize)\n }\n }\n end\nend\n\nLet's set up our database tables and have magic! analyze them:\nActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')\n\nActiveRecord::Schema.define do\n create_table \"managers\" do |t|\n t.string \"name\"\n end\n create_table \"employees\" do |t|\n t.string \"name\"\n t.belongs_to \"manager\"\n end\nend\n\n# it happens!\nActiveRecord::Base.magic!\n\nCreate some test records and use it in the way you wanted:\nmislav = Manager.create :name => \"Mislav\"\nmislav.employees.create(:name => \"Josh\")\nmislav.employees.create(:name => \"Mike\")\n\nManager.all.each do |manager|\n puts manager.name\n manager.employees.each do |employee|\n puts employee.name\n end\nend\n\nFull code available on this Gist.\nThis only works with belongs_to and has_many associations. If you need a real library that does this and much more, check out Dr Nic's Magic Models.\n",
"Try the sqlautocode module for SQLAlchemy. It will generate the ORM classes by reflecting the database.\n"
] |
[
4,
3,
0
] |
[
"In Ruby there are several ORMs like ActiveRecord, DataMapper or even Sequel.\nFor example using ActiveRecord you would do:\n##################################\n#mysql conection\n##################################\nbegin\n ActiveRecord::Base.establish_connection(\n :adapter => DBAdapter,\n :host => DBHost,\n :username => DBUserName,\n :password => DBPass,\n :database => DBDatabase,\n :encoding=> DBEncoding,\n :socket=> DBSocket #drop this option for windows machines \n )\nrescue Exception => ex\n fout.puts \"Error connecting to mysql : #{ex}\"\n puts \"Migration was terminated due to connection error , check out the log file\"\n break\nend\n\n######################\n# Define models\n######################\n\nclass Employee < ActiveRecord::Base\n belongs_to :manager\nend \n\nclass Manager < ActiveRecord::Base\n has_many :employees\nend \n\n"
] |
[
-2
] |
[
"database",
"orm",
"python",
"ruby"
] |
stackoverflow_0001897465_database_orm_python_ruby.txt
|
Q:
Compile a string to Ruby bytecode for better performance -- like compile() in Python
I have a string (authenticated, trusted, etc.) containing source code intended to run within a Ruby loop, quickly. In Python, I would compile the string into an abstract syntax tree and eval() or exec() it later:
# Python 3 example
given_code = 'n % 2 == 1'
pred = compile(given_code, '<given>', 'eval')
print("Passed:", [n for n in range(10) if eval(pred)])
# Outputs: Passing members: [1, 3, 5, 7, 9]
Ruby does not have a compile function, so what is the best way to achieve this?
A:
Based on the solution of jhs, but directly using the lambda as the loop body (the & calls to_proc on the lambda and passes it as block to the select function).
given_code = 'n % 2 == 1'
pred = eval "lambda { |n| #{given_code} }"
p all = (1..10).select(&pred)
A:
I wrap the whole string in a lambda (still as a string), eval that, and then call the resultant Proc object.
# XXX: Only runs on Ruby 1.8.7 and up.
given_code = 'n % 2 == 1'
pred = eval "lambda { |n| #{given_code} }"
puts 1.upto(10).select { |x| pred.call(x) } .inspect # Or (1..10).select for Ruby <= 1.8.6
# Output: [1, 3, 5, 7, 9]
|
Compile a string to Ruby bytecode for better performance -- like compile() in Python
|
I have a string (authenticated, trusted, etc.) containing source code intended to run within a Ruby loop, quickly. In Python, I would compile the string into an abstract syntax tree and eval() or exec() it later:
# Python 3 example
given_code = 'n % 2 == 1'
pred = compile(given_code, '<given>', 'eval')
print("Passed:", [n for n in range(10) if eval(pred)])
# Outputs: Passing members: [1, 3, 5, 7, 9]
Ruby does not have a compile function, so what is the best way to achieve this?
|
[
"Based on the solution of jhs, but directly using the lambda as the loop body (the & calls to_proc on the lambda and passes it as block to the select function).\ngiven_code = 'n % 2 == 1'\npred = eval \"lambda { |n| #{given_code} }\"\np all = (1..10).select(&pred)\n\n",
"I wrap the whole string in a lambda (still as a string), eval that, and then call the resultant Proc object.\n# XXX: Only runs on Ruby 1.8.7 and up.\ngiven_code = 'n % 2 == 1'\npred = eval \"lambda { |n| #{given_code} }\"\nputs 1.upto(10).select { |x| pred.call(x) } .inspect # Or (1..10).select for Ruby <= 1.8.6\n# Output: [1, 3, 5, 7, 9]\n\n"
] |
[
7,
1
] |
[] |
[] |
[
"compilation",
"eval",
"python",
"ruby"
] |
stackoverflow_0001900327_compilation_eval_python_ruby.txt
|
Q:
can NLTK/pyNLTK work "per language" (i.e. non-english), and how?
How can I tell NLTK to treat the text in a particular language?
Once in a while I write a specialized NLP routine to do POS tagging, tokenizing and etc. on a non-english (but still hindo-European) text domain.
This question seem to address only different corpora, not the change in code/settings:
POS tagging in German
Alternatively,are there any specialized Hebrew/Spanish/Polish NLP modules for python?
A:
I'm not sure what you're referring to as the changes in code/settings. NLTK mostly relies on machine learning and the "settings" are usually extracted from the training data.
When it comes to POS tagging the results and tagging will be dependant on the tagger you use/train. Should you train your own you'll of course need some spanish / polish training data. The reason these might be hard to find is the lack of gold standard material publicly available. There are tools out there to do that do this, but this one isn't for python (http://www.ims.uni-stuttgart.de/projekte/corplex/TreeTagger/).
The nltk.tokenize.punkt.PunktSentenceTokenizer tokenizer will tokenize sentences according to multilingual sentence boundaries the details of which can be found in this paper (http://www.mitpressjournals.org/doi/abs/10.1162/coli.2006.32.4.485).
|
can NLTK/pyNLTK work "per language" (i.e. non-english), and how?
|
How can I tell NLTK to treat the text in a particular language?
Once in a while I write a specialized NLP routine to do POS tagging, tokenizing and etc. on a non-english (but still hindo-European) text domain.
This question seem to address only different corpora, not the change in code/settings:
POS tagging in German
Alternatively,are there any specialized Hebrew/Spanish/Polish NLP modules for python?
|
[
"I'm not sure what you're referring to as the changes in code/settings. NLTK mostly relies on machine learning and the \"settings\" are usually extracted from the training data.\nWhen it comes to POS tagging the results and tagging will be dependant on the tagger you use/train. Should you train your own you'll of course need some spanish / polish training data. The reason these might be hard to find is the lack of gold standard material publicly available. There are tools out there to do that do this, but this one isn't for python (http://www.ims.uni-stuttgart.de/projekte/corplex/TreeTagger/). \nThe nltk.tokenize.punkt.PunktSentenceTokenizer tokenizer will tokenize sentences according to multilingual sentence boundaries the details of which can be found in this paper (http://www.mitpressjournals.org/doi/abs/10.1162/coli.2006.32.4.485).\n"
] |
[
9
] |
[] |
[] |
[
"nlp",
"nltk",
"python"
] |
stackoverflow_0001795410_nlp_nltk_python.txt
|
Q:
[GAE]How to set `inline` if in template
Coming from PHP world, I used to create select box like this:
<select>
<?php foreach($arrField as $idx=>$val){?>
<option <?php echo ($fieldVal == $idx ? "selected='selected'" : ''); ?>><?php echo $val; ?></option>
<?php } ?>
</select>
However, I can't do that in python. Here's my snippet:
<select name='type'>
<option value='normal' {% if id = 'normal' %} selected="selected"{% endif %}>1-Normal</option>
<option value='image' {% if id = 'image' %} selected="selected"{% endif %}>2-Image</option>
</select>
I got this error:
TemplateSyntaxError: 'if' statement improperly formatted
Is there a way to do this?
A:
You will need to use (if you are using Django):
{% ifequal id "something"%}selected='selected'{% endifequal %}
You will also need to make sure "id" is a variable you pass into templates.Render()
P
|
[GAE]How to set `inline` if in template
|
Coming from PHP world, I used to create select box like this:
<select>
<?php foreach($arrField as $idx=>$val){?>
<option <?php echo ($fieldVal == $idx ? "selected='selected'" : ''); ?>><?php echo $val; ?></option>
<?php } ?>
</select>
However, I can't do that in python. Here's my snippet:
<select name='type'>
<option value='normal' {% if id = 'normal' %} selected="selected"{% endif %}>1-Normal</option>
<option value='image' {% if id = 'image' %} selected="selected"{% endif %}>2-Image</option>
</select>
I got this error:
TemplateSyntaxError: 'if' statement improperly formatted
Is there a way to do this?
|
[
"You will need to use (if you are using Django):\n{% ifequal id \"something\"%}selected='selected'{% endifequal %}\n\nYou will also need to make sure \"id\" is a variable you pass into templates.Render()\nP\n"
] |
[
2
] |
[] |
[] |
[
"google_app_engine",
"python",
"templates",
"web_applications"
] |
stackoverflow_0001900175_google_app_engine_python_templates_web_applications.txt
|
Q:
django urlencode filter
I have a problem with encoding urls using build-in django urlencode filter. When I use it on default django server everything is fine. But on apache2 it doesn`t work, ie. i have a tag called C#. On localhost my url is encoded to ...tags/C%23/ but on apache2 it is tags/C/
What should I do?
A:
I guess this is a bug with apache, simplest solution would be do url encoding twice or do a base64 encoding.
|
django urlencode filter
|
I have a problem with encoding urls using build-in django urlencode filter. When I use it on default django server everything is fine. But on apache2 it doesn`t work, ie. i have a tag called C#. On localhost my url is encoded to ...tags/C%23/ but on apache2 it is tags/C/
What should I do?
|
[
"I guess this is a bug with apache, simplest solution would be do url encoding twice or do a base64 encoding. \n"
] |
[
0
] |
[] |
[] |
[
"django",
"python",
"urlencode"
] |
stackoverflow_0001899407_django_python_urlencode.txt
|
Q:
How to avoid multiple instances of a program?
I need to find a right way to prevent two running instances of my (Python) program.
I am currently using the following method.
On Windows,
os.popen('wmic process get caption,processid | findstr `programname.exe`')
On Linux,
os.popen('ps x | grep `programname`')
It seems to work fine for now. Is this method correct?
Can someone suggest to me a better way?
edit: Thanks for the reply guys,
Is anything wrong with the above methods?
I tried the pid file way for linux. What if the pid file gets deleted somehow?
A:
There are numerous ways:
have an "instance file" in /var/run or similar (cross-platform)
use a fixed socket (cross-platform)
use DBus to register a name (linux)
What you need is a service (external to your application) that manages a namespace where unique ids are available & enforced.
A:
on Linux, I used to write a pidfile, roughly:
if (pidfile already exists)
read pidfile content
if (/proc/<pid>/exec == my executable)
already running, exit
else
it´s a stale pidfile, delete it
write my own pid to pidfile
start the 'real' work
lately, i´ve heard of the flock(1) tool. it´s easier to use in bash scripts:
( flock -n 200 || exit
# ... commands executed under lock ...
) 200>/var/lock/mylockfile
and not too hard to use from 'real' programming languages, just open a file and try to get a flock(2) on it.
A:
For linux, see the answer from jldupont.
For windows, use the CreateMutex-method, to create a named mutex. See:
http://msdn.microsoft.com/en-us/library/ms686927%28VS.85%29.aspx
|
How to avoid multiple instances of a program?
|
I need to find a right way to prevent two running instances of my (Python) program.
I am currently using the following method.
On Windows,
os.popen('wmic process get caption,processid | findstr `programname.exe`')
On Linux,
os.popen('ps x | grep `programname`')
It seems to work fine for now. Is this method correct?
Can someone suggest to me a better way?
edit: Thanks for the reply guys,
Is anything wrong with the above methods?
I tried the pid file way for linux. What if the pid file gets deleted somehow?
|
[
"There are numerous ways:\n\nhave an \"instance file\" in /var/run or similar (cross-platform)\nuse a fixed socket (cross-platform)\nuse DBus to register a name (linux)\n\nWhat you need is a service (external to your application) that manages a namespace where unique ids are available & enforced.\n",
"on Linux, I used to write a pidfile, roughly:\nif (pidfile already exists)\n read pidfile content\n if (/proc/<pid>/exec == my executable)\n already running, exit\n else\n it´s a stale pidfile, delete it\nwrite my own pid to pidfile\nstart the 'real' work\n\nlately, i´ve heard of the flock(1) tool. it´s easier to use in bash scripts:\n( flock -n 200 || exit\n # ... commands executed under lock ...\n) 200>/var/lock/mylockfile\n\nand not too hard to use from 'real' programming languages, just open a file and try to get a flock(2) on it.\n",
"For linux, see the answer from jldupont.\nFor windows, use the CreateMutex-method, to create a named mutex. See:\nhttp://msdn.microsoft.com/en-us/library/ms686927%28VS.85%29.aspx\n"
] |
[
5,
2,
1
] |
[] |
[] |
[
"instance",
"python"
] |
stackoverflow_0001900979_instance_python.txt
|
Q:
What's a neater, more pythonic way to do the following enumeration?
for row, instrument in enumerate(instruments):
for col, value in enumerate(instrument):
self.table.SetValue(row, col, value)
A:
What you are calling row is not a row, it is a row index. instrument is a row. Apart from that:
If the only tool that you have is a SetValue(row_index, column_index, value) method and that method does more than help replicate the structure of instruments laboriously, and the instruments collection is as your code describes, then there is no better way. It is already much better than
#WARNING: BAD PRACTICE! DON'T USE THIS CODE!
for row_index in xrange(len(instruments)):
instrument = instruments[row_index]
for column_index in xrange(len(instrument)):
self.table.SetValue(row_index, column_index, instrument[column_index])
or any perversion thereof.
Otherwise you may be interested in import copy; self.table = copy.copy(instruments) or even (as SilentGhost has suggested) self.table = instruments
A:
The fundamental question is not regarding this loop.
The fundamental questions are these:
1) Where does this instruments structure come from, and why do you need to reorganize it?
2) What is this self.table structure on which you're calling SetValue?
3) What are you going to do with this self.table structure?
Until you answer these questions, your sample Python code has no context in which it can be evaluated. It's just code.
A:
You've mentioned in the comments that this loop is a part of asynchronous function (in terms of twisted framework). In this case you don't want to block for a long time:
from twisted.internet import task
for i, row in enumerate(instruments):
task.coiterate(self.table.SetValue(i, j, v) for j, v in enumerate(row))
Thus all rows are assigned in parallel.
NOTE:
Watch out for late binding for i and row. Use (lambda i=i, row=row: ...)() in that case.
task.coiterate() uses global object therefore there could be multiple table updates simultaneously (it might not be what you want).
Here's @SilentGhost' answer (deleted):
self.table = instruments
Because that's what you seem to be
doing.
And the comment by @[Ben Hughes] I'm referring to:
I need to explicity call SetValue (its
on a PyGridTableBase) for each value -
as this code is invoked via a twisted
deferred method - my brain is not much
good at looping/enumeration in a neat
way..... – Ben Hughes
|
What's a neater, more pythonic way to do the following enumeration?
|
for row, instrument in enumerate(instruments):
for col, value in enumerate(instrument):
self.table.SetValue(row, col, value)
|
[
"What you are calling row is not a row, it is a row index. instrument is a row. Apart from that:\nIf the only tool that you have is a SetValue(row_index, column_index, value) method and that method does more than help replicate the structure of instruments laboriously, and the instruments collection is as your code describes, then there is no better way. It is already much better than\n#WARNING: BAD PRACTICE! DON'T USE THIS CODE!\nfor row_index in xrange(len(instruments)):\n instrument = instruments[row_index]\n for column_index in xrange(len(instrument)):\n self.table.SetValue(row_index, column_index, instrument[column_index])\n\nor any perversion thereof.\nOtherwise you may be interested in import copy; self.table = copy.copy(instruments) or even (as SilentGhost has suggested) self.table = instruments\n",
"The fundamental question is not regarding this loop.\nThe fundamental questions are these:\n1) Where does this instruments structure come from, and why do you need to reorganize it?\n2) What is this self.table structure on which you're calling SetValue?\n3) What are you going to do with this self.table structure?\nUntil you answer these questions, your sample Python code has no context in which it can be evaluated. It's just code. \n",
"You've mentioned in the comments that this loop is a part of asynchronous function (in terms of twisted framework). In this case you don't want to block for a long time:\nfrom twisted.internet import task\n\nfor i, row in enumerate(instruments):\n task.coiterate(self.table.SetValue(i, j, v) for j, v in enumerate(row))\n\nThus all rows are assigned in parallel.\nNOTE: \n\nWatch out for late binding for i and row. Use (lambda i=i, row=row: ...)() in that case.\ntask.coiterate() uses global object therefore there could be multiple table updates simultaneously (it might not be what you want).\n\n\nHere's @SilentGhost' answer (deleted):\n\nself.table = instruments\nBecause that's what you seem to be\n doing.\n\nAnd the comment by @[Ben Hughes] I'm referring to:\n\nI need to explicity call SetValue (its\n on a PyGridTableBase) for each value -\n as this code is invoked via a twisted\n deferred method - my brain is not much\n good at looping/enumeration in a neat\n way..... – Ben Hughes\n\n"
] |
[
4,
2,
2
] |
[
"One option is using a list comprehension:\n[self.table.setValue(row, col, value) \n for row, instrument in enumerate(instruments) \n for col, value in enumerate(instrument)]\n\nNot sure if it is any neater or more pythonic... But it is another way of expressing the loop.\nOne could argue that the list comprehension is clearer, since the \"action\" part (setValue) is placed first/at the top. Instead of being buried inside the loop.\nEDIT:\nYet another way, using a helper function and a generator expression:\ndef loop(iterator):\n for item in iterator: pass\n\nloop(self.table.setValue(row, col, value) \n for row, instrument in enumerate(instruments) \n for col, value in enumerate(instrument))\n\nThe helper function can be the built-in any() if you know for certain that the loop body will never evaluate to True in a boolean context (any() will stop the iteration on the first True).\n"
] |
[
-3
] |
[
"enumeration",
"python"
] |
stackoverflow_0001900195_enumeration_python.txt
|
Q:
Get the executing file's path from an installed package?
If one installs a python package using setuptools, then executes a method in that package from a standard python script, is it possible to get the file path of the calling/executing file?
For instance, the file I'm executing is /usr/foo/bar.py, which looks like this:
import baz
baz.get_current_path()
# should print /usr/foo/bar.py
and the package baz has been installed using setuptools and is located in that magical place all python packages are installed when they've been good little packages.
Both __file__ and import inspect; inspect.currentframe().f_code.co_filename return the path of the package'd file.
Is this possible?
A:
Use inspect.getouterframes() or inspect.stack(), then get the filename from the calling frame.
|
Get the executing file's path from an installed package?
|
If one installs a python package using setuptools, then executes a method in that package from a standard python script, is it possible to get the file path of the calling/executing file?
For instance, the file I'm executing is /usr/foo/bar.py, which looks like this:
import baz
baz.get_current_path()
# should print /usr/foo/bar.py
and the package baz has been installed using setuptools and is located in that magical place all python packages are installed when they've been good little packages.
Both __file__ and import inspect; inspect.currentframe().f_code.co_filename return the path of the package'd file.
Is this possible?
|
[
"Use inspect.getouterframes() or inspect.stack(), then get the filename from the calling frame.\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001901407_python.txt
|
Q:
Emacs Python-Mode: Sending statements to a subprocess does not lead to REPL-style evaluation
After selecting 1 + 1 and issuing python-send-region, my subprocess buffer shows no results. I have to evaluate print 1 + 1, instead.
How can I force the python-send-* commands to print the value of the respective statements rather than echoing their stdout?
A:
It sounds like you need print; use print.
emacs is launching a python process and getting text from its standard output, not a python value.
|
Emacs Python-Mode: Sending statements to a subprocess does not lead to REPL-style evaluation
|
After selecting 1 + 1 and issuing python-send-region, my subprocess buffer shows no results. I have to evaluate print 1 + 1, instead.
How can I force the python-send-* commands to print the value of the respective statements rather than echoing their stdout?
|
[
"It sounds like you need print; use print.\nemacs is launching a python process and getting text from its standard output, not a python value.\n"
] |
[
2
] |
[] |
[] |
[
"emacs",
"python"
] |
stackoverflow_0001901354_emacs_python.txt
|
Q:
The following code in python (and why)
I am learning python because it looks very nice and i know a bit of ruby and perl.
The following is a C program to plot 3d points onto the screen. I used this as an example because it uses arrays, structures and function calls. I left out classes because i believe that sort of (OOP) thing is used simularly in all languages (correct me if im wrong). Understand that i do know how to write the following in python (with a bit of help from google), but i would like to know what sort of methods you would use and why.
Please dont feel the need to answer if you don't have the time or don't enjoy this kind of thing!
#include <stdlib.h>
int screenWidth = 10;
int screenHeight = 10;
char *buf;
inline void draw3dPoint(int *i3dPoint) {
buf[
(((i3dPoint[1] / i3dPoint[2]) + (screenHeight/2)) * screenWidth) +
(i3dPoint[0] / i3dPoint[2]) + (screenWidth/2)] = 1;
}
main() {
int x, y;
buf = malloc(sizeof(char)*screenWidth*screenHeight);
for(x = 0; x < screenWidth * screenHeight; x++)
buf[x] =0;
int *i3dPoint = malloc(sizeof(int)*3);
i3dPoint[0] = 3; i3dPoint[1] = 0; i3dPoint[2] = 5;
draw3dPoint(i3dPoint);
i3dPoint[0] = 0; i3dPoint[1] = 4; i3dPoint[2] = 2;
draw3dPoint(i3dPoint);
i3dPoint[0] = -3; i3dPoint[1] = -4; i3dPoint[2] = 3;
draw3dPoint(i3dPoint);
for(y = 0; y < screenHeight; y++) {
for(x = 0; x < screenWidth; x++)
if(buf[(y*screenWidth)+x])
printf("#");
else
printf(" ");
printf(".\n");
}
free(buf);
free(i3dPoint);
return 0;
}
A:
Here's a direct port, only works in python3 due to the print thing combined with x-if-a-else-y
screenWidth = 10
screenHeight = 10
buf = [False] * screenWidth * screenHeight
def draw3dpoint(x,y,z):
pt = int((((y / z) + (screenHeight/2)) * screenWidth) + (x / z) + (screenWidth/2))
buf[pt] = True
draw3dpoint(3,0,5)
draw3dpoint(0,4,2)
draw3dpoint(-3,-4,3)
for y in range(screenHeight):
for x in range(screenWidth):
print(('#' if buf[y * screenWidth + x] else ' '), end='')
print()
If you want the print to work in python below 3.0, do the following (note that the output is different due to weird division behavour, as pointed out in the first comment to this answer). Also thanks to the third comment I could refine this piece a little.
for y in range(screenHeight):
for x in range(screenWidth):
print (buf[y * screenWidth + x] and '#' or ' '),
print ''
A:
If this is for plotting (scientific) data, i would use numpy and matplotlib, combined in the scipy package. More information can be find on the SciPy page, and its 3D plotting examples.
WHY: provides easy math and plotting functionality, similar to matlab.
If you're using OpenGL, you can probably port your code quite literally with the python OpenGL bindings.
WHY: since it doesn't require you to adopt an extra framework, plus you can reuse most knowledge of C-style OpenGL that you already have.
A:
OK, I realise you're giving a custom example, but I feel that perhaps learning graphics concepts would help you easily translate from one language to another.
Quite simply, start with http://pyopengl.sourceforge.net/.
OpenGL is a standardised library of graphics functions. It's what is used in many games, rendering kits, phones and more. It's simple, it's powerful and it's been ported to almost every popular language out there.
If you're wanting to learn a graphics kit - OpenGL is a great place to start. It's also helpful that many examples can easily be ported between C and Python or Java or whatever else takes your fancy, and there are countless examples all over the net from people who love to use it and code in it.
One of the best tutorials is the NeHe tutorials - tens of tutorials from a simple box up to smoke engines and more in OpenGL. For every example, they include downloadable projects or code for the tutorial in tens of languages - including both C and Python, so this should be a great place for you to start your learning. It's where I learnt OpenGL, and can highly recommend it. It's not just the code, it's the theory and maths behind the graphics as well!
|
The following code in python (and why)
|
I am learning python because it looks very nice and i know a bit of ruby and perl.
The following is a C program to plot 3d points onto the screen. I used this as an example because it uses arrays, structures and function calls. I left out classes because i believe that sort of (OOP) thing is used simularly in all languages (correct me if im wrong). Understand that i do know how to write the following in python (with a bit of help from google), but i would like to know what sort of methods you would use and why.
Please dont feel the need to answer if you don't have the time or don't enjoy this kind of thing!
#include <stdlib.h>
int screenWidth = 10;
int screenHeight = 10;
char *buf;
inline void draw3dPoint(int *i3dPoint) {
buf[
(((i3dPoint[1] / i3dPoint[2]) + (screenHeight/2)) * screenWidth) +
(i3dPoint[0] / i3dPoint[2]) + (screenWidth/2)] = 1;
}
main() {
int x, y;
buf = malloc(sizeof(char)*screenWidth*screenHeight);
for(x = 0; x < screenWidth * screenHeight; x++)
buf[x] =0;
int *i3dPoint = malloc(sizeof(int)*3);
i3dPoint[0] = 3; i3dPoint[1] = 0; i3dPoint[2] = 5;
draw3dPoint(i3dPoint);
i3dPoint[0] = 0; i3dPoint[1] = 4; i3dPoint[2] = 2;
draw3dPoint(i3dPoint);
i3dPoint[0] = -3; i3dPoint[1] = -4; i3dPoint[2] = 3;
draw3dPoint(i3dPoint);
for(y = 0; y < screenHeight; y++) {
for(x = 0; x < screenWidth; x++)
if(buf[(y*screenWidth)+x])
printf("#");
else
printf(" ");
printf(".\n");
}
free(buf);
free(i3dPoint);
return 0;
}
|
[
"Here's a direct port, only works in python3 due to the print thing combined with x-if-a-else-y\nscreenWidth = 10\nscreenHeight = 10\n\nbuf = [False] * screenWidth * screenHeight\ndef draw3dpoint(x,y,z):\n pt = int((((y / z) + (screenHeight/2)) * screenWidth) + (x / z) + (screenWidth/2))\n buf[pt] = True\n\ndraw3dpoint(3,0,5)\ndraw3dpoint(0,4,2)\ndraw3dpoint(-3,-4,3)\n\nfor y in range(screenHeight):\n for x in range(screenWidth):\n print(('#' if buf[y * screenWidth + x] else ' '), end='')\n print()\n\nIf you want the print to work in python below 3.0, do the following (note that the output is different due to weird division behavour, as pointed out in the first comment to this answer). Also thanks to the third comment I could refine this piece a little.\nfor y in range(screenHeight):\n for x in range(screenWidth):\n print (buf[y * screenWidth + x] and '#' or ' '),\n print ''\n\n",
"\nIf this is for plotting (scientific) data, i would use numpy and matplotlib, combined in the scipy package. More information can be find on the SciPy page, and its 3D plotting examples.\n\nWHY: provides easy math and plotting functionality, similar to matlab.\n\nIf you're using OpenGL, you can probably port your code quite literally with the python OpenGL bindings.\n\nWHY: since it doesn't require you to adopt an extra framework, plus you can reuse most knowledge of C-style OpenGL that you already have.\n",
"OK, I realise you're giving a custom example, but I feel that perhaps learning graphics concepts would help you easily translate from one language to another.\nQuite simply, start with http://pyopengl.sourceforge.net/.\nOpenGL is a standardised library of graphics functions. It's what is used in many games, rendering kits, phones and more. It's simple, it's powerful and it's been ported to almost every popular language out there.\nIf you're wanting to learn a graphics kit - OpenGL is a great place to start. It's also helpful that many examples can easily be ported between C and Python or Java or whatever else takes your fancy, and there are countless examples all over the net from people who love to use it and code in it.\nOne of the best tutorials is the NeHe tutorials - tens of tutorials from a simple box up to smoke engines and more in OpenGL. For every example, they include downloadable projects or code for the tutorial in tens of languages - including both C and Python, so this should be a great place for you to start your learning. It's where I learnt OpenGL, and can highly recommend it. It's not just the code, it's the theory and maths behind the graphics as well!\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"c",
"python"
] |
stackoverflow_0001901518_c_python.txt
|
Q:
Overlapping partially transparent shapes
If I draw any shape onto a surface (with SRCALPHA flag on) in a partially transparent colour it completely replaces what was underneath it, instead of overlapping like you would expect in image editors.
How can I make the shapes overlap properly?
A:
You could use blit with appropriate BLEND_* values (keeping the shapes as separate surfaces, for integrity and editing, and only blitting them for display purposes).
A:
As noted, the draw functions in PyGame don't actually do blending the way you might expect. From the PyGame documentation:
Most of the arguments accept a color argument that is an RGB triplet. These can also accept an RGBA quadruplet. The alpha value will be written directly into the Surface if it contains pixel alphas, but the draw function will not draw transparently.
What you'll probably want to do is essentially what Alex Martelli said--create an intermediate software surface with an alpha channel, draw your shape onto that surface, then blit with blending onto the final surface. If you've used PyGame's font rendering, notice that it works roughly the same, except that Font.render creates the temporary surface for you.
I'm a bit rusty with Python and PyGame these days, but here's a quick example that hopefully doesn't have too many mistakes:
# returns a surface with the circle drawn onto it
def render_transparent_circle(color, radius, width=0):
size = radius * 2
temp_surf = pygame.Surface((size, size), SRCALPHA)
temp_surf.fill(Color(0, 0, 0, 0))
pygame.draw.circle(temp_surf, color, (radius, radius), radius, width)
return temp_surf
# draw a half-opaque blue circle of radius 30 to the display at point (50, 100)
def test():
transp_blue = Color(0, 0, 255, 128)
screen = pygame.display.get_surface()
circle = render_transparent_circle(transp_blue, 30)
screen.blit(circle, (50, 100))
p.s. -- If you're going to display the same shape multiple times, you may want to consider caching the intermediate surface (but don't forget to profile to find out if it helps).
A:
Alpha on its own is just an extra 'value' that can serve a purpose. It just so happens that the purpose is typically (but not always) transparency (other uses include reflectance, specular highlighting and even an approach for faking HDR).
You need to specify that you want it to blend (and the equation it should use to do it). A simple Google search for "pygame blend mode" shows a few good resources.
As Alex has pointed out, blit takes a Blending mode as a parameter. This StackOverflow question provides more information.
|
Overlapping partially transparent shapes
|
If I draw any shape onto a surface (with SRCALPHA flag on) in a partially transparent colour it completely replaces what was underneath it, instead of overlapping like you would expect in image editors.
How can I make the shapes overlap properly?
|
[
"You could use blit with appropriate BLEND_* values (keeping the shapes as separate surfaces, for integrity and editing, and only blitting them for display purposes).\n",
"As noted, the draw functions in PyGame don't actually do blending the way you might expect. From the PyGame documentation:\n\nMost of the arguments accept a color argument that is an RGB triplet. These can also accept an RGBA quadruplet. The alpha value will be written directly into the Surface if it contains pixel alphas, but the draw function will not draw transparently.\n\nWhat you'll probably want to do is essentially what Alex Martelli said--create an intermediate software surface with an alpha channel, draw your shape onto that surface, then blit with blending onto the final surface. If you've used PyGame's font rendering, notice that it works roughly the same, except that Font.render creates the temporary surface for you.\nI'm a bit rusty with Python and PyGame these days, but here's a quick example that hopefully doesn't have too many mistakes:\n# returns a surface with the circle drawn onto it\ndef render_transparent_circle(color, radius, width=0):\n size = radius * 2\n temp_surf = pygame.Surface((size, size), SRCALPHA)\n temp_surf.fill(Color(0, 0, 0, 0))\n pygame.draw.circle(temp_surf, color, (radius, radius), radius, width)\n return temp_surf\n\n# draw a half-opaque blue circle of radius 30 to the display at point (50, 100)\ndef test():\n transp_blue = Color(0, 0, 255, 128)\n screen = pygame.display.get_surface()\n circle = render_transparent_circle(transp_blue, 30)\n screen.blit(circle, (50, 100))\n\np.s. -- If you're going to display the same shape multiple times, you may want to consider caching the intermediate surface (but don't forget to profile to find out if it helps).\n",
"Alpha on its own is just an extra 'value' that can serve a purpose. It just so happens that the purpose is typically (but not always) transparency (other uses include reflectance, specular highlighting and even an approach for faking HDR).\nYou need to specify that you want it to blend (and the equation it should use to do it). A simple Google search for \"pygame blend mode\" shows a few good resources.\nAs Alex has pointed out, blit takes a Blending mode as a parameter. This StackOverflow question provides more information.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"alpha",
"pygame",
"python"
] |
stackoverflow_0001894564_alpha_pygame_python.txt
|
Q:
What is the standard sort order for Python release/version numbers?
Python's pip and easy_install follow some rules to sort packages by their release numbers. What are the rules for numbering beta/release/bugfix releases so these tools will know which is the newest?
A:
This is a sore point for many folks. setuptools and easy_install have some rather bizarre rules in an attempt to play nice with everybody. You can read the full rules in setuptools's parse_version method, but here's the summary:
Version numbers are broken up by dots into a tuple of that many segments. 4.5.6.7 is parsed into a tuple equal to ("4", "5", "6", "7").
Trailing zeroes between dashes or alphanumerics are suppressed. 2.4.0 is the same as 2.4; 2.4.05 is the same as 2.4.5.
Alphanumeric parts are downcased. 2.4.a5 is equal to 2.4.A5.
Strings that come before "final" alphabetically are assumed to be pre-release versions, so 2.4.5b comes before, not after, 2.4.5.
Finally, "pre", "preview", and "rc" are treated as if they were "c". The word "dev" is replaced with "@", so that it comes before anything else with the same version. That is, x.y.z-dev is guaranteed to come before any other x.y.z version.
There are a number of proposals to organize things a bit more, of which the most popular is probably PEP 386.
A:
See the documentation or look at the source: doc string in pkg_resources.py function parse_version().
A:
Use 1.0a1 and 1.0b2 before 1.0.
The upcoming standard:
http://www.python.org/dev/peps/pep-0386/#the-new-versioning-algorithm
http://tarekziade.wordpress.com/2009/11/18/distutils-and-distribute-status-part-1/
http://bitbucket.org/tarek/distutilsversion/
Current setuptools:
http://peak.telecommunity.com/DevCenter/setuptools#specifying-your-project-s-version
|
What is the standard sort order for Python release/version numbers?
|
Python's pip and easy_install follow some rules to sort packages by their release numbers. What are the rules for numbering beta/release/bugfix releases so these tools will know which is the newest?
|
[
"This is a sore point for many folks. setuptools and easy_install have some rather bizarre rules in an attempt to play nice with everybody. You can read the full rules in setuptools's parse_version method, but here's the summary:\n\nVersion numbers are broken up by dots into a tuple of that many segments. 4.5.6.7 is parsed into a tuple equal to (\"4\", \"5\", \"6\", \"7\").\nTrailing zeroes between dashes or alphanumerics are suppressed. 2.4.0 is the same as 2.4; 2.4.05 is the same as 2.4.5.\nAlphanumeric parts are downcased. 2.4.a5 is equal to 2.4.A5.\nStrings that come before \"final\" alphabetically are assumed to be pre-release versions, so 2.4.5b comes before, not after, 2.4.5.\nFinally, \"pre\", \"preview\", and \"rc\" are treated as if they were \"c\". The word \"dev\" is replaced with \"@\", so that it comes before anything else with the same version. That is, x.y.z-dev is guaranteed to come before any other x.y.z version.\n\nThere are a number of proposals to organize things a bit more, of which the most popular is probably PEP 386.\n",
"See the documentation or look at the source: doc string in pkg_resources.py function parse_version().\n",
"Use 1.0a1 and 1.0b2 before 1.0.\nThe upcoming standard:\n\nhttp://www.python.org/dev/peps/pep-0386/#the-new-versioning-algorithm\nhttp://tarekziade.wordpress.com/2009/11/18/distutils-and-distribute-status-part-1/\nhttp://bitbucket.org/tarek/distutilsversion/\n\nCurrent setuptools:\nhttp://peak.telecommunity.com/DevCenter/setuptools#specifying-your-project-s-version\n"
] |
[
9,
2,
2
] |
[] |
[] |
[
"easy_install",
"pip",
"python"
] |
stackoverflow_0001901612_easy_install_pip_python.txt
|
Q:
A function callback every time a key is pressed (regardless of which window has focus)?
I want to write a programme (in python) on Linux (Ubuntu Linux 9.10) that will keep track of how many key presses per second/minute I make. This includes normal letter keys, and control/shift/space/etc.
Is there some way to hook into X so that I can say "when a key is pressed call this function?". Since I want to have this running in the background while I work normally, this function call will have to be able to be aware of all key presses for all programmes. I suppose it's a bit like a keylogger.
This is only a personal thing, so I don't care about making it work on Windows/OSX, and I don't care about when people have fancy remote X sessions etc.
A:
Take a look at what others have done already. You can take a look on how this pykeylogger code handles Linux in its backend, and see if that works for you.
A:
I'd recommend that you look at the StackOverflow question: Is there a cross-platform python low-level API to capture or generate keyboard events?
You could also look at the Simple Python Keylogger.
While not written in Python, you could also look at the LKL Linux KeyLogger. WEB-NES-BAY has instructions for using the LKL Linux KeyLogger.
|
A function callback every time a key is pressed (regardless of which window has focus)?
|
I want to write a programme (in python) on Linux (Ubuntu Linux 9.10) that will keep track of how many key presses per second/minute I make. This includes normal letter keys, and control/shift/space/etc.
Is there some way to hook into X so that I can say "when a key is pressed call this function?". Since I want to have this running in the background while I work normally, this function call will have to be able to be aware of all key presses for all programmes. I suppose it's a bit like a keylogger.
This is only a personal thing, so I don't care about making it work on Windows/OSX, and I don't care about when people have fancy remote X sessions etc.
|
[
"Take a look at what others have done already. You can take a look on how this pykeylogger code handles Linux in its backend, and see if that works for you.\n",
"I'd recommend that you look at the StackOverflow question: Is there a cross-platform python low-level API to capture or generate keyboard events?\nYou could also look at the Simple Python Keylogger.\nWhile not written in Python, you could also look at the LKL Linux KeyLogger. WEB-NES-BAY has instructions for using the LKL Linux KeyLogger.\n"
] |
[
5,
5
] |
[] |
[] |
[
"keylogger",
"keypress",
"linux",
"python",
"xorg"
] |
stackoverflow_0001901850_keylogger_keypress_linux_python_xorg.txt
|
Q:
How to disable screen update in matplotlib
I have a loop that is adding a line to a plot on each iteration. Right now this is horribly slow as it seems to redraw the the whole graph each time. Is it possible to disable screen updates for a graph while it is being set up then re-enable them afterwards.
Here's the code:
for rr,dd in zip(angles,dists):
if dd == inf:
pass
else:
lineend = (array([cos(rr), sin(rr)]) * dd)+origin;
plot([origin[0], lineend[0]], [origin[1], lineend[1]],'-b');
I know I should just combine this all into one call to plot and I'll probably do it for this example. But there are other bits where that would be more of a problem so a general solution would be really helpful.
Thanks!
A:
It sounds like you have the interactive mode on, so you should just set it to off using the command
ioff()
Note that when interactive mode is off, you'll need to use the command show() to display the plots.
|
How to disable screen update in matplotlib
|
I have a loop that is adding a line to a plot on each iteration. Right now this is horribly slow as it seems to redraw the the whole graph each time. Is it possible to disable screen updates for a graph while it is being set up then re-enable them afterwards.
Here's the code:
for rr,dd in zip(angles,dists):
if dd == inf:
pass
else:
lineend = (array([cos(rr), sin(rr)]) * dd)+origin;
plot([origin[0], lineend[0]], [origin[1], lineend[1]],'-b');
I know I should just combine this all into one call to plot and I'll probably do it for this example. But there are other bits where that would be more of a problem so a general solution would be really helpful.
Thanks!
|
[
"It sounds like you have the interactive mode on, so you should just set it to off using the command\nioff()\n\nNote that when interactive mode is off, you'll need to use the command show() to display the plots.\n"
] |
[
3
] |
[] |
[] |
[
"matplotlib",
"python",
"scipy"
] |
stackoverflow_0001901461_matplotlib_python_scipy.txt
|
Q:
For Loop, os.listdir() not working correctly
I am creating a script to create new folder hierarchies for a friend of mine. There are around a thousand clients, so a script would save a ton of time. I have everything almost working, the part I don't have is this.
yearList = os.listdir(driveLetter + clientName)
for year in yearList:
os.chdir(year)
os.mkdir('Folder One')
os.mkdir('Folder Two')
os.mkdir('Folder Three')
Under this, are creations for sub folders, like so:
# Create folders under 'Folder One'
os.chdir(driveLetter + clientName + '\\' + year + '\Folder One')
os.mkdir('Sub Folder One')
os.mkdir('Sub Folder Two')
2005 is the first element in the list of yearList. This runs fine for 2005, but I get this error:
WindowsError: [Error 2] The system cannot find the file specified: '2006'
This would really help my friend out, so I am pretty motivated to do it (And pretty[read: very] new to programming)
Thanks for any assistance that can be provided
A:
In the for year in yearList loop you change to the year's subdirectory, but probably never leave it again. So in the first iteration you enter the "2005" subdirectory and in the second iteration you are still in that subdirectory. Then you get the error that there is no "2006" directory (in the current "2005" directory).
You can work around that by leaving the subdirectory again at the end of the loop:
for year in yearList:
os.chdir(year)
...
os.chdir('..')
A:
After you do a chdir, the current directory changes to the subdirectory, so you can't move to another subdirectory (a sibling of the first one) later using just its name. Using an absolute path will fix your problem.
Try
os.chdir(os.path.join(driveLetter, clientName, year))
Moving back to the parent directory os.chdir("..") before moving to a sibling also works.
As a side note, better use os.path.join(driveLetter, clientName, year, "Folder One") instead of driveLetter + clientName + '\\' + year + '\Folder One'. It will make your code work on other operating systems too. And a bit more readable I would argue.
A:
I haven't tested this on windows, but os.listdir(...) returns a list containing the names of every item in the given directory (which, in your case, is folders). Keep in mind that this is not an absolute path, so when you switch into the subdirectory you can't just os.chdir() with the next item to get back. You need to either go up a directory, as follows:
os.chdir('..')
or use a different function to keep track of absolute paths.
Also, in this line:
os.chdir(driveLetter + clientName + '\\' + year + '\Folder One')
shouldn't you be escaping the \ in '\Folder One'?
A:
There's a context manager that you can use to temporarily store the cwd in that question:
How do I write a decorator that restores the cwd?
|
For Loop, os.listdir() not working correctly
|
I am creating a script to create new folder hierarchies for a friend of mine. There are around a thousand clients, so a script would save a ton of time. I have everything almost working, the part I don't have is this.
yearList = os.listdir(driveLetter + clientName)
for year in yearList:
os.chdir(year)
os.mkdir('Folder One')
os.mkdir('Folder Two')
os.mkdir('Folder Three')
Under this, are creations for sub folders, like so:
# Create folders under 'Folder One'
os.chdir(driveLetter + clientName + '\\' + year + '\Folder One')
os.mkdir('Sub Folder One')
os.mkdir('Sub Folder Two')
2005 is the first element in the list of yearList. This runs fine for 2005, but I get this error:
WindowsError: [Error 2] The system cannot find the file specified: '2006'
This would really help my friend out, so I am pretty motivated to do it (And pretty[read: very] new to programming)
Thanks for any assistance that can be provided
|
[
"In the for year in yearList loop you change to the year's subdirectory, but probably never leave it again. So in the first iteration you enter the \"2005\" subdirectory and in the second iteration you are still in that subdirectory. Then you get the error that there is no \"2006\" directory (in the current \"2005\" directory).\nYou can work around that by leaving the subdirectory again at the end of the loop:\nfor year in yearList:\n os.chdir(year)\n ...\n os.chdir('..')\n\n",
"After you do a chdir, the current directory changes to the subdirectory, so you can't move to another subdirectory (a sibling of the first one) later using just its name. Using an absolute path will fix your problem.\nTry\nos.chdir(os.path.join(driveLetter, clientName, year))\n\nMoving back to the parent directory os.chdir(\"..\") before moving to a sibling also works.\nAs a side note, better use os.path.join(driveLetter, clientName, year, \"Folder One\") instead of driveLetter + clientName + '\\\\' + year + '\\Folder One'. It will make your code work on other operating systems too. And a bit more readable I would argue.\n",
"I haven't tested this on windows, but os.listdir(...) returns a list containing the names of every item in the given directory (which, in your case, is folders). Keep in mind that this is not an absolute path, so when you switch into the subdirectory you can't just os.chdir() with the next item to get back. You need to either go up a directory, as follows:\nos.chdir('..')\n\nor use a different function to keep track of absolute paths.\nAlso, in this line:\nos.chdir(driveLetter + clientName + '\\\\' + year + '\\Folder One')\n\nshouldn't you be escaping the \\ in '\\Folder One'?\n",
"There's a context manager that you can use to temporarily store the cwd in that question:\nHow do I write a decorator that restores the cwd?\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"directory",
"python"
] |
stackoverflow_0001895538_directory_python.txt
|
Q:
How do I disable Nagle's algorithm for sockets?
I'm writing some python and are stuck at the moment.
I think this "Nagle algoritm" is the problem since my packages are delayed some time for some reason to the client.
I've tried this on both client and server but it doesn't seems to work (or there's another problem causing it):
socketobj.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
Any ideas?
EDIT: A full explanation of my problem can be found here:
http://www.gamedev.net/community/forums/topic.asp?topic_id=554172&whichpage=1�
A:
I'm not familiar with Python's sockets, but does it have a flush method? Even with Nagle's disabled, most socket implementations will buffer if you don't write X number of bytes. However, if you call flush, the bytes should be sent immediately.
|
How do I disable Nagle's algorithm for sockets?
|
I'm writing some python and are stuck at the moment.
I think this "Nagle algoritm" is the problem since my packages are delayed some time for some reason to the client.
I've tried this on both client and server but it doesn't seems to work (or there's another problem causing it):
socketobj.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
Any ideas?
EDIT: A full explanation of my problem can be found here:
http://www.gamedev.net/community/forums/topic.asp?topic_id=554172&whichpage=1�
|
[
"I'm not familiar with Python's sockets, but does it have a flush method? Even with Nagle's disabled, most socket implementations will buffer if you don't write X number of bytes. However, if you call flush, the bytes should be sent immediately.\n"
] |
[
0
] |
[] |
[] |
[
"networking",
"python",
"sockets"
] |
stackoverflow_0001902325_networking_python_sockets.txt
|
Q:
How do i make Pydev + jython to startup faster when running a script?
i'm working with pydev + jython.great ide , but quite slow when i try to run a jython program.
this is probably something due to libraries load time.
What can i do to speed it up ?
Thanks ,
yaniv
A:
Jython startup time is slow ... there's a lot to bootup!
Everytime you run a Jython script from scratch, it will incur the same Jython startup time cost.
Hence, the reason Jython, Java, and Python are not great for CGI invocations. Hence, the reason for mod_python in Apache.
The key is to start-up Jython once and reuse it. But this is not always possible especially during development because your modules are always changing and Jython does not recognize these changes automatically.
Jython needs a way to know which modules have changed for automatic reloads. This is not built into Jython and you'll have to rely on some other third party library to help with this. The concept is to remove from 'sys.modules' the modules which have changed. A simple solution is to just clear all the modules from sys.modules - which will cause all modules to be reloaded. This is obviously, not the most efficient solution.
Another tip is to only import modules that your module needs at the time that it 'really' needs them. If you import every module at the top of your modules, that will increase your module import cost. So, refactor imports to within methods/functions where they are needed and where it 'makes sense'. Of course, if your method/function is computation heavy and is used frequently, it does not make sence to import modules within that method/function.
Hopefully, that helps you out!
A:
If you have a machine with more than one processor you could try starting eclipse/pydev with the options -vmargs -XX:+UseParallelGC You could also try different JVMs to see if any of them give better performance.
|
How do i make Pydev + jython to startup faster when running a script?
|
i'm working with pydev + jython.great ide , but quite slow when i try to run a jython program.
this is probably something due to libraries load time.
What can i do to speed it up ?
Thanks ,
yaniv
|
[
"Jython startup time is slow ... there's a lot to bootup!\nEverytime you run a Jython script from scratch, it will incur the same Jython startup time cost.\nHence, the reason Jython, Java, and Python are not great for CGI invocations. Hence, the reason for mod_python in Apache.\nThe key is to start-up Jython once and reuse it. But this is not always possible especially during development because your modules are always changing and Jython does not recognize these changes automatically.\nJython needs a way to know which modules have changed for automatic reloads. This is not built into Jython and you'll have to rely on some other third party library to help with this. The concept is to remove from 'sys.modules' the modules which have changed. A simple solution is to just clear all the modules from sys.modules - which will cause all modules to be reloaded. This is obviously, not the most efficient solution.\nAnother tip is to only import modules that your module needs at the time that it 'really' needs them. If you import every module at the top of your modules, that will increase your module import cost. So, refactor imports to within methods/functions where they are needed and where it 'makes sense'. Of course, if your method/function is computation heavy and is used frequently, it does not make sence to import modules within that method/function.\nHopefully, that helps you out!\n",
"If you have a machine with more than one processor you could try starting eclipse/pydev with the options -vmargs -XX:+UseParallelGC You could also try different JVMs to see if any of them give better performance.\n"
] |
[
2,
1
] |
[] |
[] |
[
"jython",
"pydev",
"python"
] |
stackoverflow_0001467827_jython_pydev_python.txt
|
Q:
Javascript communication with Selenium (RC)
My Application has a lot of calculation being done in JavaScript according to how and when the user acts on the application. The project prints out valuable information (through console calls) as to how this calculation is going on, and so we can easily spot any NaNs creeping in.
We are planning to integrate Selenium (RC with python) to test or project, but if we could get the console output messages in the python test case, we can identify any NaNs or even any miscalculations.
So, is there a way that Selenium can absorb these outputs (preferably in a console-less environment)?
If not, I would like to know if I can divert the console calls, may be by rebinding the console variable to something else, so that selenium can get that output and notify the python side. Or if not console, is there any other way that I can achieve this.
I know selenium has commands like waitForElementPresent etc., but I don't want to show these intermediate calculations on the application, or is it the only way?
Any help appreciated.
Thank you.
A:
There is GetEval() call that returns the result of a JavaScript call to the page. If you have the JavaScript on the page then you can do something like
self.assertEqual(selenium.GetEval("this.browserbot.getUserWindow().functionUnderTest().isNaN();"),"false","There was a NaN detected")
The browserbot access allows you to call the javascript functions on the page and get the result. The isNaN() will return false if you get a decent result
A:
If you are purely testing that the JavaScript functions are performing the correct calculations with the given inputs, I would suggest separating your JavaScript from your page and use a JavaScript testing framework to test the functionality. Testing low level code using Selenium is a lot of unnecessary overhead. If you're going against the fully rendered page, this would require your application to be running to a server, which should not be a dependency of testing raw JavaScript.
We recently converted our application from using jsUnit to use YUI Test and it has been promising so far. We run about 150 tests in both FireFox and IE in less than three minutes. Our testing still isn't ideal - we still test a lot of JavaScript the hard way using Selenium. However, moving some of the UI tests to YUI Test has saved us a lot of time in our Continuous Integration environment.
|
Javascript communication with Selenium (RC)
|
My Application has a lot of calculation being done in JavaScript according to how and when the user acts on the application. The project prints out valuable information (through console calls) as to how this calculation is going on, and so we can easily spot any NaNs creeping in.
We are planning to integrate Selenium (RC with python) to test or project, but if we could get the console output messages in the python test case, we can identify any NaNs or even any miscalculations.
So, is there a way that Selenium can absorb these outputs (preferably in a console-less environment)?
If not, I would like to know if I can divert the console calls, may be by rebinding the console variable to something else, so that selenium can get that output and notify the python side. Or if not console, is there any other way that I can achieve this.
I know selenium has commands like waitForElementPresent etc., but I don't want to show these intermediate calculations on the application, or is it the only way?
Any help appreciated.
Thank you.
|
[
"There is GetEval() call that returns the result of a JavaScript call to the page. If you have the JavaScript on the page then you can do something like \nself.assertEqual(selenium.GetEval(\"this.browserbot.getUserWindow().functionUnderTest().isNaN();\"),\"false\",\"There was a NaN detected\")\n\nThe browserbot access allows you to call the javascript functions on the page and get the result. The isNaN() will return false if you get a decent result\n",
"If you are purely testing that the JavaScript functions are performing the correct calculations with the given inputs, I would suggest separating your JavaScript from your page and use a JavaScript testing framework to test the functionality. Testing low level code using Selenium is a lot of unnecessary overhead. If you're going against the fully rendered page, this would require your application to be running to a server, which should not be a dependency of testing raw JavaScript.\nWe recently converted our application from using jsUnit to use YUI Test and it has been promising so far. We run about 150 tests in both FireFox and IE in less than three minutes. Our testing still isn't ideal - we still test a lot of JavaScript the hard way using Selenium. However, moving some of the UI tests to YUI Test has saved us a lot of time in our Continuous Integration environment.\n"
] |
[
4,
1
] |
[] |
[] |
[
"javascript",
"python",
"selenium",
"selenium_rc",
"testing"
] |
stackoverflow_0001819903_javascript_python_selenium_selenium_rc_testing.txt
|
Q:
python url fetch help - regex
I have a web site where there are links like <a href="http://www.example.com?read.php=123"> Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
A:
import re
re.findall("\?read\.php=(\d+)",data)
A:
"If you have a problem, and decide to use regex, now you have two problems..."
If you are reading one particular web page and you know how it is formatted, then regex is fine - you can use S. Mark's answer. To parse a particular link, you can use Kimvai's answer. However, to get all the links from a page, you're better off using something more serious. Any regex solution you come up with will have flaws,
I recommend mechanize. If you notice, the Browser class there has a links method which gets you all the links in a page. It has the added benefit of being able to download the page for you =) .
A:
While the other answers are sort of correct, you should probably use the urllib2 library instead;
from urllib2 import urlparse
import re
urlre = re.compile('<a[^>]+href="([^"]+)"[^>]*>',re.IGNORECASE)
links = urlre.findall('<a href="http://www.example.com?read.php=123">')
for link in links:
url = urlparse.urlparse(link)
s = [x.split("=") for x in url[4].split(';')]
d = {}
for k,v in s:
d[k]=v
print d["read.php"]
It's not as simple as some of the above, but guaranteed to work even with more complex urls.
A:
This will work irrespective of how your links are formatted (e.g. if some look like <a href="foo=123"/> and some look like <A TARGET="_blank" HREF='foo=123'/>).
import re
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
p = re.compile('^.*=([\d]*)$')
for a in soup.findAll('a'):
m = p.match(a["href"])
if m:
print m.groups()[0]
|
python url fetch help - regex
|
I have a web site where there are links like <a href="http://www.example.com?read.php=123"> Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance.
|
[
"import re\nre.findall(\"\\?read\\.php=(\\d+)\",data)\n\n",
"\"If you have a problem, and decide to use regex, now you have two problems...\" \nIf you are reading one particular web page and you know how it is formatted, then regex is fine - you can use S. Mark's answer. To parse a particular link, you can use Kimvai's answer. However, to get all the links from a page, you're better off using something more serious. Any regex solution you come up with will have flaws,\nI recommend mechanize. If you notice, the Browser class there has a links method which gets you all the links in a page. It has the added benefit of being able to download the page for you =) .\n",
"While the other answers are sort of correct, you should probably use the urllib2 library instead;\nfrom urllib2 import urlparse\nimport re\nurlre = re.compile('<a[^>]+href=\"([^\"]+)\"[^>]*>',re.IGNORECASE)\nlinks = urlre.findall('<a href=\"http://www.example.com?read.php=123\">')\nfor link in links:\n url = urlparse.urlparse(link)\n s = [x.split(\"=\") for x in url[4].split(';')]\n d = {}\n for k,v in s:\n d[k]=v\n print d[\"read.php\"]\n\nIt's not as simple as some of the above, but guaranteed to work even with more complex urls.\n",
"This will work irrespective of how your links are formatted (e.g. if some look like <a href=\"foo=123\"/> and some look like <A TARGET=\"_blank\" HREF='foo=123'/>).\nimport re\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(html)\np = re.compile('^.*=([\\d]*)$')\nfor a in soup.findAll('a'):\n m = p.match(a[\"href\"])\n if m:\n print m.groups()[0]\n\n"
] |
[
3,
2,
1,
1
] |
[
"/[0-9]/\nthats the regex sytax you want\nfor reference see\nhttp://gnosis.cx/publish/programming/regular_expressions.html\n",
"One without the need for regex\n>>> s='<a href=\"http://www.example.com?read.php=123\">'\n>>> for item in s.split(\">\"):\n... if \"href\" in item:\n... print item[item.index(\"a href\")+len(\"a href=\"): ]\n...\n\"http://www.example.com?read.php=123\"\n\nif you want to extract the numbers\nitem[item.index(\"a href\")+len(\"a href=\"): ].split(\"=\")[-1]\n\n"
] |
[
-1,
-1
] |
[
"python",
"regex"
] |
stackoverflow_0001899412_python_regex.txt
|
Q:
How to properly remove a specific ManyToMany relationship?
I have a ManyToMany relationship with one of my Models. On deleting a child, I want to remove the relationship but leave the record as it might be being used by other objects. On calling the delete view, I get an AttributeError error:
Exception Value: 'QuerySet' object has
no attribute 'clear'
This is my models.py:
class Feed(models.Model):
username = models.CharField(max_length=255, unique=True)
class Digest(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(User)
items = models.PositiveIntegerField()
keywords = models.CharField(max_length=255, null=True, blank=True)
digest_id = models.CharField(max_length=20, unique=True)
time_added = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=1)
feeds = models.ManyToManyField(Feed)
And the relevant section of views.py:
def feed_delete(request, id):
digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
Feed.objects.get(id=request.POST.get('id')).digest_set.filter(id=id).clear()
return HttpResponseRedirect(digest.get_absolute_url())
A:
Clear the fields on a Digest isntance
digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
digest.feeds.clear()
#do your processing
In response to your comment.
digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
feed=digest.feeds.get(id=2)#get an instance of the feed to remove
digest.feeds.remove(feed)#remove the instance
Hope this helps!
|
How to properly remove a specific ManyToMany relationship?
|
I have a ManyToMany relationship with one of my Models. On deleting a child, I want to remove the relationship but leave the record as it might be being used by other objects. On calling the delete view, I get an AttributeError error:
Exception Value: 'QuerySet' object has
no attribute 'clear'
This is my models.py:
class Feed(models.Model):
username = models.CharField(max_length=255, unique=True)
class Digest(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(User)
items = models.PositiveIntegerField()
keywords = models.CharField(max_length=255, null=True, blank=True)
digest_id = models.CharField(max_length=20, unique=True)
time_added = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=1)
feeds = models.ManyToManyField(Feed)
And the relevant section of views.py:
def feed_delete(request, id):
digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
Feed.objects.get(id=request.POST.get('id')).digest_set.filter(id=id).clear()
return HttpResponseRedirect(digest.get_absolute_url())
|
[
"Clear the fields on a Digest isntance\ndigest = get_object_or_404(Digest, id=id)\nif digest.user == request.user:\n digest.feeds.clear()\n #do your processing\n\nIn response to your comment.\ndigest = get_object_or_404(Digest, id=id)\nif digest.user == request.user:\n feed=digest.feeds.get(id=2)#get an instance of the feed to remove\n digest.feeds.remove(feed)#remove the instance \n\nHope this helps!\n"
] |
[
6
] |
[] |
[] |
[
"django",
"django_models",
"many_to_many",
"python"
] |
stackoverflow_0001902487_django_django_models_many_to_many_python.txt
|
Q:
Running Django Tests with a Precommit Hook
I would like to run all my django tests using mercurial's precommit hook. Whenever a test fails the commit will be aborted.
The goal is to block build-breaking commits as often as possible.
edit: Ended up using the external script route. Here is the reletant portion of my hgrc:
[hooks]
precommit = python ./pinax/projects/lgr/manage.py test lgr_photos --verbosity=0 --noinput
commit = hg push
Here is my progress on the hook function:
from os.path import join, dirname
import sys
from django.core.management import call_command
def hook(ui, repo, **kwargs):
project_path = join( dirname(repo.path), 'pinax', 'projects')
sys.path.insert(0, project_path)
from lgr.manage import *
output = call_command('test', verbosity=0, interactive=False)
#ui.warn(output)
What am I doing wrong here?
PS - It's giving a HUGE error traceback, which is included in it's entirety below
jim@ubuntu:~/workspace/lgr$ hg ci -m 'testing hooks'
No username found, using 'jim@ubuntu.ubuntu-domain' instead
error: precommit hook raised an exception: '_demandmod' object is not iterable
** unknown exception encountered, details follow
** report bug details to http://mercurial.selenic.com/bts/
** or mercurial@selenic.com
** Mercurial Distributed SCM (version 1.3.1)
** Extensions loaded:
Traceback (most recent call last):
File "/usr/bin/hg", line 27, in <module>
mercurial.dispatch.run()
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 16, in run
sys.exit(dispatch(sys.argv[1:]))
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 27, in dispatch
return _runcatch(u, args)
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 43, in _runcatch
return _dispatch(ui, args)
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 449, in _dispatch
return runcommand(lui, repo, cmd, fullargs, ui, options, d)
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 317, in runcommand
ret = _runcommand(ui, options, cmd, d)
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 501, in _runcommand
return checkargs()
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 454, in checkargs
return cmdfunc()
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 448, in <lambda>
d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
File "/usr/lib/pymodules/python2.6/mercurial/util.py", line 402, in check
return func(*args, **kwargs)
File "/usr/lib/pymodules/python2.6/mercurial/commands.py", line 667, in commit
node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
File "/usr/lib/pymodules/python2.6/mercurial/cmdutil.py", line 1213, in commit
return commitfunc(ui, repo, message, match(repo, pats, opts), opts)
File "/usr/lib/pymodules/python2.6/mercurial/commands.py", line 665, in commitfunc
editor=e, extra=extra)
File "/usr/lib/pymodules/python2.6/mercurial/localrepo.py", line 886, in commit
ret = self.commitctx(cctx, True)
File "/usr/lib/pymodules/python2.6/mercurial/localrepo.py", line 915, in commitctx
self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
File "/usr/lib/pymodules/python2.6/mercurial/localrepo.py", line 139, in hook
return hook.hook(self.ui, self, name, throw, **args)
File "/usr/lib/pymodules/python2.6/mercurial/hook.py", line 119, in hook
r = _pythonhook(ui, repo, name, hname, hookfn, args, throw) or r
File "/usr/lib/pymodules/python2.6/mercurial/hook.py", line 52, in _pythonhook
r = obj(ui=ui, repo=repo, hooktype=name, **args)
here is the important part:
File "/home/jim/run_lgr_tests.py", line 11, in hook
output = call_command('test', verbosity=0, interactive=False)
and the rest:
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 166, in call_command
return klass.execute(*args, **defaults)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 213, in execute
translation.activate('en-us')
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/__init__.py", line 73, in activate
return real_activate(language)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/__init__.py", line 43, in delayed_loader
return g['real_%s' % caller](*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 205, in activate
_active[currentThread()] = translation(language)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 194, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 180, in _fetch
app = import_module(appname)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 84, in _demandimport
return _origimport(name, globals, locals, fromlist)
File "/home/jim/workspace/lgr/pinax/projects/lgr/apps/lgr_hacks.py", line 5, in <module>
User.email = models.EmailField(_('email address'), blank=True, max_length=200)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/__init__.py", line 62, in ugettext
return real_ugettext(message)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 286, in ugettext
return do_translate(message, 'ugettext')
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 276, in do_translate
_default = translation(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 194, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 180, in _fetch
app = import_module(appname)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 84, in _demandimport
return _origimport(name, globals, locals, fromlist)
File "/home/jim/workspace/lgr/pinax/apps/external_apps/djangodblog/__init__.py", line 1, in <module>
import djangodblog.admin
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 91, in _demandimport
return _origimport(name, globals, locals, fromlist)
File "/home/jim/workspace/lgr/pinax/apps/external_apps/djangodblog/admin.py", line 14, in <module>
admin.site.register(ErrorBatch, ErrorBatchAdmin)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py", line 90, in register
validate(admin_class, model)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/validation.py", line 22, in validate
models.get_apps()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 100, in get_apps
self._populate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 58, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 74, in load_app
models = import_module('.models', app_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 84, in _demandimport
return _origimport(name, globals, locals, fromlist)
File "/home/jim/workspace/lgr/pinax/projects/lgr/apps/account/models.py", line 7, in <module>
from timezones.fields import TimeZoneField
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 103, in _demandimport
mod = _origimport(name, globals, locals)
File "/home/jim/workspace/lgr/pinax/apps/external_apps/timezones/fields.py", line 12, in <module>
default_tz = pytz.timezone(getattr(settings, "TIME_ZONE", "UTC"))
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 75, in __getattribute__
self._load()
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 47, in _load
mod = _origimport(head, globals, locals)
File "/home/jim/workspace/lgr/pinax/libs/external_libs/pytz-2008b/pytz/__init__.py", line 29, in <module>
from pkg_resources import resource_stream
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 103, in _demandimport
mod = _origimport(name, globals, locals)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 2562, in <module>
working_set.require(__requires__)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 626, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 505, in resolve
requirements = list(requirements)[::-1] # set up the stack
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 2380, in parse_requirements
for line in lines:
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1814, in yield_lines
for s in yield_lines(ss):
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1813, in yield_lines
for ss in strs:
TypeError: '_demandmod' object is not iterable
A:
It looks like Mercurial's way of importing modules is clashing with Django's somehow.
Before trying to dive in and sort that out, is there any reason to not just run the tests with the normal command?
[hooks]
precommit.runtests = python manage.py test
|
Running Django Tests with a Precommit Hook
|
I would like to run all my django tests using mercurial's precommit hook. Whenever a test fails the commit will be aborted.
The goal is to block build-breaking commits as often as possible.
edit: Ended up using the external script route. Here is the reletant portion of my hgrc:
[hooks]
precommit = python ./pinax/projects/lgr/manage.py test lgr_photos --verbosity=0 --noinput
commit = hg push
Here is my progress on the hook function:
from os.path import join, dirname
import sys
from django.core.management import call_command
def hook(ui, repo, **kwargs):
project_path = join( dirname(repo.path), 'pinax', 'projects')
sys.path.insert(0, project_path)
from lgr.manage import *
output = call_command('test', verbosity=0, interactive=False)
#ui.warn(output)
What am I doing wrong here?
PS - It's giving a HUGE error traceback, which is included in it's entirety below
jim@ubuntu:~/workspace/lgr$ hg ci -m 'testing hooks'
No username found, using 'jim@ubuntu.ubuntu-domain' instead
error: precommit hook raised an exception: '_demandmod' object is not iterable
** unknown exception encountered, details follow
** report bug details to http://mercurial.selenic.com/bts/
** or mercurial@selenic.com
** Mercurial Distributed SCM (version 1.3.1)
** Extensions loaded:
Traceback (most recent call last):
File "/usr/bin/hg", line 27, in <module>
mercurial.dispatch.run()
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 16, in run
sys.exit(dispatch(sys.argv[1:]))
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 27, in dispatch
return _runcatch(u, args)
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 43, in _runcatch
return _dispatch(ui, args)
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 449, in _dispatch
return runcommand(lui, repo, cmd, fullargs, ui, options, d)
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 317, in runcommand
ret = _runcommand(ui, options, cmd, d)
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 501, in _runcommand
return checkargs()
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 454, in checkargs
return cmdfunc()
File "/usr/lib/pymodules/python2.6/mercurial/dispatch.py", line 448, in <lambda>
d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
File "/usr/lib/pymodules/python2.6/mercurial/util.py", line 402, in check
return func(*args, **kwargs)
File "/usr/lib/pymodules/python2.6/mercurial/commands.py", line 667, in commit
node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
File "/usr/lib/pymodules/python2.6/mercurial/cmdutil.py", line 1213, in commit
return commitfunc(ui, repo, message, match(repo, pats, opts), opts)
File "/usr/lib/pymodules/python2.6/mercurial/commands.py", line 665, in commitfunc
editor=e, extra=extra)
File "/usr/lib/pymodules/python2.6/mercurial/localrepo.py", line 886, in commit
ret = self.commitctx(cctx, True)
File "/usr/lib/pymodules/python2.6/mercurial/localrepo.py", line 915, in commitctx
self.hook("precommit", throw=True, parent1=xp1, parent2=xp2)
File "/usr/lib/pymodules/python2.6/mercurial/localrepo.py", line 139, in hook
return hook.hook(self.ui, self, name, throw, **args)
File "/usr/lib/pymodules/python2.6/mercurial/hook.py", line 119, in hook
r = _pythonhook(ui, repo, name, hname, hookfn, args, throw) or r
File "/usr/lib/pymodules/python2.6/mercurial/hook.py", line 52, in _pythonhook
r = obj(ui=ui, repo=repo, hooktype=name, **args)
here is the important part:
File "/home/jim/run_lgr_tests.py", line 11, in hook
output = call_command('test', verbosity=0, interactive=False)
and the rest:
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 166, in call_command
return klass.execute(*args, **defaults)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 213, in execute
translation.activate('en-us')
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/__init__.py", line 73, in activate
return real_activate(language)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/__init__.py", line 43, in delayed_loader
return g['real_%s' % caller](*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 205, in activate
_active[currentThread()] = translation(language)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 194, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 180, in _fetch
app = import_module(appname)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 84, in _demandimport
return _origimport(name, globals, locals, fromlist)
File "/home/jim/workspace/lgr/pinax/projects/lgr/apps/lgr_hacks.py", line 5, in <module>
User.email = models.EmailField(_('email address'), blank=True, max_length=200)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/__init__.py", line 62, in ugettext
return real_ugettext(message)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 286, in ugettext
return do_translate(message, 'ugettext')
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 276, in do_translate
_default = translation(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 194, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.6/dist-packages/django/utils/translation/trans_real.py", line 180, in _fetch
app = import_module(appname)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 84, in _demandimport
return _origimport(name, globals, locals, fromlist)
File "/home/jim/workspace/lgr/pinax/apps/external_apps/djangodblog/__init__.py", line 1, in <module>
import djangodblog.admin
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 91, in _demandimport
return _origimport(name, globals, locals, fromlist)
File "/home/jim/workspace/lgr/pinax/apps/external_apps/djangodblog/admin.py", line 14, in <module>
admin.site.register(ErrorBatch, ErrorBatchAdmin)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py", line 90, in register
validate(admin_class, model)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/validation.py", line 22, in validate
models.get_apps()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 100, in get_apps
self._populate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 58, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 74, in load_app
models = import_module('.models', app_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 84, in _demandimport
return _origimport(name, globals, locals, fromlist)
File "/home/jim/workspace/lgr/pinax/projects/lgr/apps/account/models.py", line 7, in <module>
from timezones.fields import TimeZoneField
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 103, in _demandimport
mod = _origimport(name, globals, locals)
File "/home/jim/workspace/lgr/pinax/apps/external_apps/timezones/fields.py", line 12, in <module>
default_tz = pytz.timezone(getattr(settings, "TIME_ZONE", "UTC"))
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 75, in __getattribute__
self._load()
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 47, in _load
mod = _origimport(head, globals, locals)
File "/home/jim/workspace/lgr/pinax/libs/external_libs/pytz-2008b/pytz/__init__.py", line 29, in <module>
from pkg_resources import resource_stream
File "/usr/lib/pymodules/python2.6/mercurial/demandimport.py", line 103, in _demandimport
mod = _origimport(name, globals, locals)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 2562, in <module>
working_set.require(__requires__)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 626, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 505, in resolve
requirements = list(requirements)[::-1] # set up the stack
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 2380, in parse_requirements
for line in lines:
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1814, in yield_lines
for s in yield_lines(ss):
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1813, in yield_lines
for ss in strs:
TypeError: '_demandmod' object is not iterable
|
[
"It looks like Mercurial's way of importing modules is clashing with Django's somehow.\nBefore trying to dive in and sort that out, is there any reason to not just run the tests with the normal command?\n[hooks]\nprecommit.runtests = python manage.py test\n\n"
] |
[
7
] |
[] |
[] |
[
"django",
"mercurial",
"pre_commit",
"python",
"version_control"
] |
stackoverflow_0001902817_django_mercurial_pre_commit_python_version_control.txt
|
Q:
How do I chain object instantiation with its methods?
For example this chunk of code:
new_log = ActivityLog(user=self.user,
activity=activity)
new_log.save()
Can I chain it to be like new_log = ActivityLog(...).save() ?
I believe I tried the above, but it doesn't work. Is there a way to make it a 1 liner?
A:
Let save() return self, such as:
class ActivityLog (object): # EDIT: OR INHERIT FROM WHATEVER OTHER CLASS, I DONT CARE
...
def save(self):
...
return self
NOTE: This is a generic coding pattern called method chaining.
A:
Django provides a convenience method on the model manager for just this purpose :-)
new_log = ActivityLog.objects.create(user=self.user, activity=activity)
The docs on create are here. It is billed as:
A convenience method for creating an object and saving it all in one step.
|
How do I chain object instantiation with its methods?
|
For example this chunk of code:
new_log = ActivityLog(user=self.user,
activity=activity)
new_log.save()
Can I chain it to be like new_log = ActivityLog(...).save() ?
I believe I tried the above, but it doesn't work. Is there a way to make it a 1 liner?
|
[
"Let save() return self, such as:\nclass ActivityLog (object): # EDIT: OR INHERIT FROM WHATEVER OTHER CLASS, I DONT CARE\n ...\n\n def save(self):\n ...\n return self\n\nNOTE: This is a generic coding pattern called method chaining.\n",
"Django provides a convenience method on the model manager for just this purpose :-)\nnew_log = ActivityLog.objects.create(user=self.user, activity=activity)\n\nThe docs on create are here. It is billed as:\n\nA convenience method for creating an object and saving it all in one step.\n\n"
] |
[
6,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001902836_python.txt
|
Q:
Django Admin app: building a dynamic list of admin actions
I am trying to dynamically build a list of admin actions using the get_actions() method on a ModelAdmin. Each action relates to a particular instance of another model, and as new instances may be added or removed, I want to make sure the list of actions reflects that.
Here's the ModelAdmin:
class PackageAdmin(admin.ModelAdmin):
list_display = ('name', 'quality')
def _actions(self, request):
for q in models.Quality.objects.all():
action = lambda modeladmin, req, qset: qset.update(quality=q)
name = "mark_%s" % (q,)
yield (name, (action, name, "Mark selected as %s quality" % (q,)))
def get_actions(self, request):
return dict(action for action in self._actions(request))
(The weird repetitive dict of tuples return value is explained by the Django docs for get_actions().)
As expected, this results in a list of appropriately named admin actions for bulk assignment of Quality foreign keys to Package objects.
The problem is that whichever action I choose, the same Quality object gets assigned to the selected Packages.
I assume that the closures I am creating with the lambda keyword all contain a reference to the same q object, so every iteration changes the value of q for every function.
Can I break this reference, allowing me to still use a list of closures containing different values of q?
Edit: I realise that lambda is not necessary in this example. Instead of:
action = lambda modeladmin, req, qset: qset.update(quality=q)
I could simply use def:
def action(modeladmin, req, qset):
return qset.update(quality=q)
A:
try
def make_action(quality):
return lambda modeladmin, req, qset: qset.update(quality=quality)
for q in models.Quality.objects.all():
action = make_action(q)
name = "mark_%s" % (q,)
yield (name, (action, name, "Mark selected as %s quality" % (q,)))
if that doesn't work, i suspect the bug has something to do with your use of yield. maybe try:
def make_action(quality):
name = 'mark_%s' % quality
action = lambda modeladmin, req, qset: qset.update(quality=quality)
return (name, (action, name, "Mark selected as %s quality" % quality))
def get_actions(self, request):
return dict([make_action for q in models.Quality.objects.all()])
A:
As I mentioned in my comment to andylei's answer, I just found a solution; using another function to create the closure seems to break the reference, meaning that now every action refers to the correct instance of Quality.
def create_action(quality):
fun = lambda modeladmin, request, queryset: queryset.update(quality=quality)
name = "mark_%s" % (quality,)
return (name, (fun, name, "Mark selected as %s quality" % (quality,)))
class PackageAdmin(admin.ModelAdmin):
list_display = ('name', 'quality')
def get_actions(self, request):
return dict(create_action(q) for q in models.Quality.objects.all())
A:
I am surprised that q stays the same object within the loop.
Does it work with quality=q.id in your lambda?
|
Django Admin app: building a dynamic list of admin actions
|
I am trying to dynamically build a list of admin actions using the get_actions() method on a ModelAdmin. Each action relates to a particular instance of another model, and as new instances may be added or removed, I want to make sure the list of actions reflects that.
Here's the ModelAdmin:
class PackageAdmin(admin.ModelAdmin):
list_display = ('name', 'quality')
def _actions(self, request):
for q in models.Quality.objects.all():
action = lambda modeladmin, req, qset: qset.update(quality=q)
name = "mark_%s" % (q,)
yield (name, (action, name, "Mark selected as %s quality" % (q,)))
def get_actions(self, request):
return dict(action for action in self._actions(request))
(The weird repetitive dict of tuples return value is explained by the Django docs for get_actions().)
As expected, this results in a list of appropriately named admin actions for bulk assignment of Quality foreign keys to Package objects.
The problem is that whichever action I choose, the same Quality object gets assigned to the selected Packages.
I assume that the closures I am creating with the lambda keyword all contain a reference to the same q object, so every iteration changes the value of q for every function.
Can I break this reference, allowing me to still use a list of closures containing different values of q?
Edit: I realise that lambda is not necessary in this example. Instead of:
action = lambda modeladmin, req, qset: qset.update(quality=q)
I could simply use def:
def action(modeladmin, req, qset):
return qset.update(quality=q)
|
[
"try \n def make_action(quality):\n return lambda modeladmin, req, qset: qset.update(quality=quality)\n\n for q in models.Quality.objects.all():\n action = make_action(q)\n name = \"mark_%s\" % (q,)\n yield (name, (action, name, \"Mark selected as %s quality\" % (q,)))\n\nif that doesn't work, i suspect the bug has something to do with your use of yield. maybe try:\ndef make_action(quality):\n name = 'mark_%s' % quality\n action = lambda modeladmin, req, qset: qset.update(quality=quality)\n return (name, (action, name, \"Mark selected as %s quality\" % quality))\n\ndef get_actions(self, request):\n return dict([make_action for q in models.Quality.objects.all()])\n\n",
"As I mentioned in my comment to andylei's answer, I just found a solution; using another function to create the closure seems to break the reference, meaning that now every action refers to the correct instance of Quality.\ndef create_action(quality):\n fun = lambda modeladmin, request, queryset: queryset.update(quality=quality)\n name = \"mark_%s\" % (quality,)\n return (name, (fun, name, \"Mark selected as %s quality\" % (quality,)))\n\nclass PackageAdmin(admin.ModelAdmin):\n list_display = ('name', 'quality')\n\n def get_actions(self, request):\n return dict(create_action(q) for q in models.Quality.objects.all())\n\n",
"I am surprised that q stays the same object within the loop.\nDoes it work with quality=q.id in your lambda?\n"
] |
[
7,
5,
0
] |
[] |
[] |
[
"closures",
"django",
"python"
] |
stackoverflow_0001902332_closures_django_python.txt
|
Q:
How to implement time event scheduler in python?
In python how to implement a thread which runs in the background (may be when the module loads) and calls the function every minute Monday to Friday 10 AM to 3 PM. For example the function should be called at:
10:01 AM
10:02 AM
10:03 AM
.
.
2:59 PM
Any pointers?
Environment: Django
Thanks
A:
Django is a server application, which only reacts to external events.
You should use a scheduler like cron to create events that call your django application, either calling a management subcommand or doing an HTTP request on some special page.
A:
The threading.Timer class is convenient to do such tasks. But you have to compute interval yourself.
A:
I think you can make a command http://docs.djangoproject.com/en/1.1/howto/custom-management-commands/#howto-custom-management-commands and then cron it.
|
How to implement time event scheduler in python?
|
In python how to implement a thread which runs in the background (may be when the module loads) and calls the function every minute Monday to Friday 10 AM to 3 PM. For example the function should be called at:
10:01 AM
10:02 AM
10:03 AM
.
.
2:59 PM
Any pointers?
Environment: Django
Thanks
|
[
"Django is a server application, which only reacts to external events.\nYou should use a scheduler like cron to create events that call your django application, either calling a management subcommand or doing an HTTP request on some special page.\n",
"The threading.Timer class is convenient to do such tasks. But you have to compute interval yourself.\n",
"I think you can make a command http://docs.djangoproject.com/en/1.1/howto/custom-management-commands/#howto-custom-management-commands and then cron it.\n"
] |
[
4,
2,
1
] |
[
"Note sure how django affects threads (unless you're using App Engine where you can't do low level such), but once your thread is running you can continuously check timestamps:\nfrom datetime import time\nfrom datetime import date\ntime_delta = 60\nwhile True:\n end_time = time.time() + time_delta\n while time.time() < end_time:\n time.sleep(1)\n if date.today().weekday() in range(1,5):\n #do something baby\n\nNot tested, so take it for a spin first.\n",
"Here is an article about scheduling tasks in cron from google code.\nScheduling Tasks with Cron\n"
] |
[
-1,
-1
] |
[
"django",
"multithreading",
"python",
"scheduling"
] |
stackoverflow_0001902338_django_multithreading_python_scheduling.txt
|
Q:
Validate that atleast one modelfield has value in Django admin
Given the following model, how do I require that atleast one of the two fields has been given a value?
class ZipUpload(models.Model):
zip_file = models.FileField(upload_to="/tmp", blank=True,
help_text='Select a file to upload.')
zip_file_path = models.FilePathField(path="/tmp", blank=True,
help_text="A path to a file on the server)
I'm working on a small site with a small set of users, so I was hoping to make this work with just using the standard admin-site.
I have considered overriding Model.save(), and adding a check there, but then I don't know how to alert the user of the error in a good way.
A:
This kind of validation is what a customized Form is for. Define a Form, write validation methods in the Form. Bind the Form to the Model to create the Admin interface.
|
Validate that atleast one modelfield has value in Django admin
|
Given the following model, how do I require that atleast one of the two fields has been given a value?
class ZipUpload(models.Model):
zip_file = models.FileField(upload_to="/tmp", blank=True,
help_text='Select a file to upload.')
zip_file_path = models.FilePathField(path="/tmp", blank=True,
help_text="A path to a file on the server)
I'm working on a small site with a small set of users, so I was hoping to make this work with just using the standard admin-site.
I have considered overriding Model.save(), and adding a check there, but then I don't know how to alert the user of the error in a good way.
|
[
"This kind of validation is what a customized Form is for. Define a Form, write validation methods in the Form. Bind the Form to the Model to create the Admin interface.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_admin",
"django_models",
"python"
] |
stackoverflow_0001903158_django_django_admin_django_models_python.txt
|
Q:
Are there any matrix math modules compatible with Python 3.x?
When I began this project, I thought it would be easy to get libraries for common stuff like matrix math, so I chose to work in Python 3.1- it being the most recent, updated version of the language. Unfortunately, NumPy is only compatible with 2.5 and 2.6 and seems to be the only game in town! Even other stuff that I turned up like gameobjects seemed to be based on NumPy and therefore incompatible with 3.x as well.
Does anyone out there know of a matrix library that is compatible with 3? I need to be able to do the following: matrix add, subtract, multiply, scalar multiply, inverse, transpose, and determinant. I've been looking all day and all roads seem to lead back to NumPy. I even tried this module: http://www.nightmare.com/squirl/python-ext/misc/matrix.py but it too is for 2.x. Even after converting it using the 2to3 tool, I can't get the yarn module that it refers to (and is probably itself 2.x).
Any help is hugely appreciated.
A:
Given that a large portion of those interested in this sort of development are involved in NumPy, and given their schedule for migrating I think the answer is "no, there is nothing yet".
I would advise treating Python 3.x as "still experimental" and start with Python 2.6 instead. Make some small effort to write your code in a such a way that it won't be too hard to migrate in, say, a year or two, when the Python 3.x series really stabilizes, but don't jump there just yet. Other more general questions have answers that may help you decide.
A:
EDIT: PyEuclid has supports matrices, vectors up to 4 dimensions and is designed for geometric operations.
Otherwise, the answer is probably not what you want, but:
use python 2.x instead, do use numpy (which is really good), until numpy supports python 3.x
implement your own Matrix class, since you don't require too much functionality and it's a good exercise to implement. Should be less work than looking a day on the internet.
|
Are there any matrix math modules compatible with Python 3.x?
|
When I began this project, I thought it would be easy to get libraries for common stuff like matrix math, so I chose to work in Python 3.1- it being the most recent, updated version of the language. Unfortunately, NumPy is only compatible with 2.5 and 2.6 and seems to be the only game in town! Even other stuff that I turned up like gameobjects seemed to be based on NumPy and therefore incompatible with 3.x as well.
Does anyone out there know of a matrix library that is compatible with 3? I need to be able to do the following: matrix add, subtract, multiply, scalar multiply, inverse, transpose, and determinant. I've been looking all day and all roads seem to lead back to NumPy. I even tried this module: http://www.nightmare.com/squirl/python-ext/misc/matrix.py but it too is for 2.x. Even after converting it using the 2to3 tool, I can't get the yarn module that it refers to (and is probably itself 2.x).
Any help is hugely appreciated.
|
[
"Given that a large portion of those interested in this sort of development are involved in NumPy, and given their schedule for migrating I think the answer is \"no, there is nothing yet\".\nI would advise treating Python 3.x as \"still experimental\" and start with Python 2.6 instead. Make some small effort to write your code in a such a way that it won't be too hard to migrate in, say, a year or two, when the Python 3.x series really stabilizes, but don't jump there just yet. Other more general questions have answers that may help you decide.\n",
"EDIT: PyEuclid has supports matrices, vectors up to 4 dimensions and is designed for geometric operations.\nOtherwise, the answer is probably not what you want, but:\n\nuse python 2.x instead, do use numpy (which is really good), until numpy supports python 3.x\nimplement your own Matrix class, since you don't require too much functionality and it's a good exercise to implement. Should be less work than looking a day on the internet.\n\n"
] |
[
5,
1
] |
[] |
[] |
[
"math",
"matrix",
"python"
] |
stackoverflow_0001903209_math_matrix_python.txt
|
Q:
python libraries for programatic email access: mime, smtp, pop3
Does python have built in libraries for accessing email including: smtp, pop3, mime parsers etc?
A:
Absolutely:
smtplib — SMTP protocol client
poplib — POP3 protocol client
imaplib — IMAP4 protocol client
email — An email and MIME handling package
They are all included in the Python standard library.
|
python libraries for programatic email access: mime, smtp, pop3
|
Does python have built in libraries for accessing email including: smtp, pop3, mime parsers etc?
|
[
"Absolutely:\n\nsmtplib — SMTP protocol client\npoplib — POP3 protocol client\nimaplib — IMAP4 protocol client\nemail — An email and MIME handling package\n\nThey are all included in the Python standard library.\n"
] |
[
3
] |
[] |
[] |
[
"email",
"pop3",
"python"
] |
stackoverflow_0001904108_email_pop3_python.txt
|
Q:
Python Windows Service Problems - Works when using debug argument but not while started as a service?
hopefully someone here can shed some light on my issue :D
I've been creating a Windows XP service in python that is designed to monitor/repair selected Windows/Application/Service settings, atm I have been focusing on default DCOM settings.
The idea is to backup our default configuration within another registry key for reference. Every 30 minutes (currently every 30 seconds for testing) I would like the service to query the current windows default DCOM settings from the registry and compare the results to the default configuration. If discrepancies are found, the service will replace the current windows settings with the custom configuration settings.
I have already created/tested my class to handle the registry checking/repairing and so far it runs flawlessly.. Until I compile it to an exe and run it as a service.
The service itself starts up just fine and it seems to loop every 30 seconds as defined, but my module to handle the registry checking/repairing does not seem to get run as specified.
I created a log file and was able to obtain the following error:
Traceback (most recent call last):
File "DCOMMon.pyc", line 52, in RepairDCOM
File "DCOMMon.pyc", line 97, in GetDefaultDCOM
File "pywmi.pyc", line 396, in call
File "pywmi.pyc", line 189, in handle_com_error
x_wmi: -0x7ffdfff7 - Exception occurred.
Error in: SWbemObjectEx
-0x7ffbfe10 -
When I stop the service and run the exe manually, specifying the debug argument: DCOMMon.exe debug, the service starts up and runs just fine, performing all tasks as expected. The only differences that I can see is that the service starts the process as the SYSTEM user instead of the logged on user which leads me to believe (just guessing here) that it might be some sort of missed permission/policy for the SYSTEM user? I have tested running the service as another user but there was no difference there either.
Other thoughts were to add the wmi service to the dependencies of my service but truthfully I have no idea what that would do :P This is the first time I've attempted to create a windows service in python, without using something like srvany.exe.
I have spent the better part of last night and today trying to google around and find some information regarding py2exe and wmi compatibility but so far the suggestions I have found have not helped solve the above issue.
Any suggestions would be appreciated.
PS: Don't hate me for the poor logging, I cut/pasted my logger from a different scripts and I have not made the appropriate changes, it might double up each line :P. The log file can be found here: "%WINDIR%\system32\DCOMMon.log"
UPDATE
I have tried to split this project up into two exe files instead of one. Let the service make and external call to the other exe to run the wmi registry portion. Again, when running with the debug arg it works just fine, but when I start it as a service it logs the same error message. More and more this is starting to look like a permission issue an not a program issue :(
UPDATE
DCOMMon.py - Requires pywin32, wmi (renamed to pywmi),
# DCOMMon.py
import win32api, win32service, win32serviceutil, win32event, win32evtlogutil, win32traceutil
import logging, logging.handlers, os, re, sys, thread, time, traceback, pywmi # pywmi == wmi module renamed as suggested in online post
import _winreg as reg
DCOM_DEFAULT_CONFIGURATION = ["EnableDCOM", "EnableRemoteConnect", "LegacyAuthenticationLevel", "LegacyImpersonationLevel", "DefaultAccessPermission",
"DefaultLaunchPermission", "MachineAccessRestriction", "MachineLaunchRestriction"]
DCOM_DEFAULT_ACCESS_PERMISSION = [1, 0, 4, 128, 92, 0, 0, 0, 108, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 72, 0, 3, 0, 0, 0, 0, 0, 24, 0, 7, 0, 0, 0, 1, 2,
0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 7, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0, 7,
0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32,
0, 0, 0, 32, 2, 0, 0]
DCOM_DEFAULT_LAUNCH_PERMISSION = [1, 0, 4, 128, 132, 0, 0, 0, 148, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 112, 0, 5, 0, 0, 0, 0, 0, 24, 0, 31, 0, 0, 0, 1,
2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0,
31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 20, 0,
31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5,
32, 0, 0, 0, 32, 2, 0, 0]
DCOM_MACHINE_ACCESS_RESTRICTION = [1, 0, 4, 128, 68, 0, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 48, 0, 2, 0, 0, 0, 0, 0, 20, 0, 3, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0, 7, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0,
0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]
DCOM_MACHINE_LAUNCH_RESTRICTION = [1, 0, 4, 128, 72, 0, 0, 0, 88, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 52, 0, 2, 0, 0, 0, 0, 0, 24, 0, 31, 0, 0, 0, 1,
2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0,
0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]
COMPUTER = os.environ["COMPUTERNAME"]
REGISTRY = pywmi.WMI(COMPUTER, namespace="root/default").StdRegProv
LOGFILE = os.getcwd() + "\\DCOMMon.log"
def Logger(title, filename):
logger = logging.getLogger(title)
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(filename, maxBytes=0, backupCount=0)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def LogIt(filename=LOGFILE):
#try:
# if os.path.exists(filename):
# os.remove(filename)
#except:
# pass
log = Logger("DCOMMon", filename)
tb = str(traceback.format_exc()).split("\n")
log.error("")
for i, a in enumerate(tb):
if a.strip() != "":
log.error(a)
class Monitor:
def RepairDCOM(self):
try:
repaired = {}
dict1 = self.GetDefaultDCOM()
dict2 = self.GetCurrentDCOM()
compared = self.CompareDCOM(dict1, dict2)
for dobj in DCOM_DEFAULT_CONFIGURATION:
try:
compared[dobj]
if dobj == "LegacyAuthenticationLevel" or dobj == "LegacyImpersonationLevel":
REGISTRY.SetDWORDValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, uValue=dict1[dobj])
elif dobj == "DefaultAccessPermission" or dobj == "DefaultLaunchPermission" or \
dobj == "MachineAccessRestriction" or dobj == "MachineLaunchRestriction":
REGISTRY.SetBinaryValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, uValue=dict1[dobj])
elif dobj == "EnableDCOM" or dobj == "EnableRemoteConnect":
REGISTRY.SetStringValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, sValue=dict1[dobj])
except KeyError:
pass
except:
LogIt(LOGFILE)
def CompareDCOM(self, dict1, dict2):
compare = {}
for (key, value) in dict2.iteritems():
try:
if dict1[key] != value:
compare[key] = value
except KeyError:
compare[key] = value
return compare
def GetCurrentDCOM(self):
current = {}
for name in REGISTRY.EnumValues(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole")[1]:
value = REGISTRY.GetStringValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1]
if value:
current[str(name)] = str(value)
else:
value = REGISTRY.GetDWORDValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1]
if not value:
value = REGISTRY.GetBinaryValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1]
current[str(name)] = value
return current
def GetDefaultDCOM(self):
default = {}
# Get Default DCOM Settings
for name in REGISTRY.EnumValues(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon")[1]:
value = REGISTRY.GetStringValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1]
if value:
default[str(name)] = str(value)
else:
value = REGISTRY.GetDWORDValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1]
if not value:
value = REGISTRY.GetBinaryValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1]
default[str(name)] = value
return default
class DCOMMon(win32serviceutil.ServiceFramework):
_svc_name_ = "DCOMMon"
_svc_display_name_ = "DCOM Monitoring Service"
_svc_description_ = "DCOM Monitoring Service"
_svc_deps_ = ["EventLog"]
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.isAlive = True
def SvcDoRun(self):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ': DCOM Monitoring Service - Service Started'))
self.timeout=30000 # In milliseconds
while self.isAlive:
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
if rc == win32event.WAIT_OBJECT_0:
break
else:
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ': DCOM Monitoring Service - Examining DCOM Configuration'))
Monitor().RepairDCOM()
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ': DCOM Monitoring Service - Service Stopped'))
return
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
LOG.close()
self.isAlive = False
return
#def ctrlHandler(ctrlType):
# return True
if __name__ == '__main__':
# win32api.SetConsoleCtrlHandler(ctrlHandler, True)
#print Monitor().RepairDCOM()
win32serviceutil.HandleCommandLine(DCOMMon)
DCOMMon_setup.py - Requires py2exe (self executable, no need for py2exe arg)
# DCOMMon_setup.py (self executable, no need for py2exe arg)
# Usage:
# DCOMMon.exe install
# DCOMMon.exe start
# DCOMMon.exe stop
# DCOMMon.exe remove
# DCOMMon.exe debug
# you can see output of this program running python site-packages\win32\lib\win32traceutil
try:
# (snippet I found somewhere, searching something??)
# if this doesn't work, try import modulefinder
import py2exe.mf as modulefinder
import win32com, sys
for p in win32com.__path__[1:]:
modulefinder.AddPackagePath("win32com", p)
for extra in ["win32com.shell"]: #,"win32com.mapi"
__import__(extra)
m = sys.modules[extra]
for p in m.__path__[1:]:
modulefinder.AddPackagePath(extra, p)
except ImportError:
print "NOT FOUND"
from distutils.core import setup
import py2exe, sys
if len(sys.argv) == 1:
sys.argv.append("py2exe")
#sys.argv.append("-q")
class Target:
def __init__(self, **kw):
self.__dict__.update(kw)
# for the versioninfo resources
self.version = "1.0.0.1"
self.language = "English (Canada)"
self.company_name = "Whoever"
self.copyright = "Nobody"
self.name = "Nobody Home"
myservice = Target(
description = 'DCOM Monitoring Service',
modules = ['DCOMMon'],
cmdline_style='pywin32'
#dest_base = 'DCOMMon'
)
setup(
options = {"py2exe": {"compressed": 1, "bundle_files": 1, "ascii": 1, "packages": ["encodings"]} },
console=["DCOMMon.py"],
zipfile = None,
service=[myservice]
)
A:
So I guess it's time to admit my stupidity.... :P
It turns out this was not a python issue, py2exe issue, nor a WMI issue. :(
This was more or less a simple permission issue. So simple I overlooked it for the better part of a month. :(
Rule of thumb, if you want to create a service that calls to specific registry keys to obtain (in this case) default configuration settings....
maybe... JUST MAYBE....
One should place their default key within the "HKEY_LOCAL_MACHINE", instead of "HKEY_CURRENT_USER"?? :P
Yeah, it's that simple...
I should have remembered this rule from other projects I have worked on in the past. When you are running as the Local System account, simply put, there is no "HKEY_CURRENT_USER" subkey to access. If you absolutely have to access a specific user's "HKEY_CURRENT_USER" subkey, I would guess the only way would be to impersonate the user. Luckily for me this is not necessary for what I am attempting to accomplish.
The below link provided me with what I needed to jog my memory and fix the issue:
http://msdn.microsoft.com/en-us/library/ms684190%28VS.85%29.aspx
So to make a long story short, I migrated all of my default values over to "HKEY_LOCAL_MACHINE\SOFTWARE" subkey and my service is working perfectly. :D
Thanks for your help guys but this problem is solved ;)
A:
I am not an expert at this, but here are my two cents worth:
This article tells me that you might need to be logged in as someone with the required target system permissions.
However, I find that a little excessive. Have you tried compiling your script from the command line while running the command prompt as the administrator of the computer - so that you can unlock all permissions (on Windows Vista and Windows 7, this is achieved by right clicking on the command prompt icon in the start menu and clicking on "run as administrator").
Hope this helps
|
Python Windows Service Problems - Works when using debug argument but not while started as a service?
|
hopefully someone here can shed some light on my issue :D
I've been creating a Windows XP service in python that is designed to monitor/repair selected Windows/Application/Service settings, atm I have been focusing on default DCOM settings.
The idea is to backup our default configuration within another registry key for reference. Every 30 minutes (currently every 30 seconds for testing) I would like the service to query the current windows default DCOM settings from the registry and compare the results to the default configuration. If discrepancies are found, the service will replace the current windows settings with the custom configuration settings.
I have already created/tested my class to handle the registry checking/repairing and so far it runs flawlessly.. Until I compile it to an exe and run it as a service.
The service itself starts up just fine and it seems to loop every 30 seconds as defined, but my module to handle the registry checking/repairing does not seem to get run as specified.
I created a log file and was able to obtain the following error:
Traceback (most recent call last):
File "DCOMMon.pyc", line 52, in RepairDCOM
File "DCOMMon.pyc", line 97, in GetDefaultDCOM
File "pywmi.pyc", line 396, in call
File "pywmi.pyc", line 189, in handle_com_error
x_wmi: -0x7ffdfff7 - Exception occurred.
Error in: SWbemObjectEx
-0x7ffbfe10 -
When I stop the service and run the exe manually, specifying the debug argument: DCOMMon.exe debug, the service starts up and runs just fine, performing all tasks as expected. The only differences that I can see is that the service starts the process as the SYSTEM user instead of the logged on user which leads me to believe (just guessing here) that it might be some sort of missed permission/policy for the SYSTEM user? I have tested running the service as another user but there was no difference there either.
Other thoughts were to add the wmi service to the dependencies of my service but truthfully I have no idea what that would do :P This is the first time I've attempted to create a windows service in python, without using something like srvany.exe.
I have spent the better part of last night and today trying to google around and find some information regarding py2exe and wmi compatibility but so far the suggestions I have found have not helped solve the above issue.
Any suggestions would be appreciated.
PS: Don't hate me for the poor logging, I cut/pasted my logger from a different scripts and I have not made the appropriate changes, it might double up each line :P. The log file can be found here: "%WINDIR%\system32\DCOMMon.log"
UPDATE
I have tried to split this project up into two exe files instead of one. Let the service make and external call to the other exe to run the wmi registry portion. Again, when running with the debug arg it works just fine, but when I start it as a service it logs the same error message. More and more this is starting to look like a permission issue an not a program issue :(
UPDATE
DCOMMon.py - Requires pywin32, wmi (renamed to pywmi),
# DCOMMon.py
import win32api, win32service, win32serviceutil, win32event, win32evtlogutil, win32traceutil
import logging, logging.handlers, os, re, sys, thread, time, traceback, pywmi # pywmi == wmi module renamed as suggested in online post
import _winreg as reg
DCOM_DEFAULT_CONFIGURATION = ["EnableDCOM", "EnableRemoteConnect", "LegacyAuthenticationLevel", "LegacyImpersonationLevel", "DefaultAccessPermission",
"DefaultLaunchPermission", "MachineAccessRestriction", "MachineLaunchRestriction"]
DCOM_DEFAULT_ACCESS_PERMISSION = [1, 0, 4, 128, 92, 0, 0, 0, 108, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 72, 0, 3, 0, 0, 0, 0, 0, 24, 0, 7, 0, 0, 0, 1, 2,
0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 7, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0, 7,
0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32,
0, 0, 0, 32, 2, 0, 0]
DCOM_DEFAULT_LAUNCH_PERMISSION = [1, 0, 4, 128, 132, 0, 0, 0, 148, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 112, 0, 5, 0, 0, 0, 0, 0, 24, 0, 31, 0, 0, 0, 1,
2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0,
31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 20, 0,
31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5,
32, 0, 0, 0, 32, 2, 0, 0]
DCOM_MACHINE_ACCESS_RESTRICTION = [1, 0, 4, 128, 68, 0, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 48, 0, 2, 0, 0, 0, 0, 0, 20, 0, 3, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 5, 7, 0, 0, 0, 0, 0, 20, 0, 7, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0,
0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]
DCOM_MACHINE_LAUNCH_RESTRICTION = [1, 0, 4, 128, 72, 0, 0, 0, 88, 0, 0, 0, 0, 0, 0, 0, 20, 0, 0, 0, 2, 0, 52, 0, 2, 0, 0, 0, 0, 0, 24, 0, 31, 0, 0, 0, 1,
2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 0, 0, 20, 0, 31, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 0,
0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]
COMPUTER = os.environ["COMPUTERNAME"]
REGISTRY = pywmi.WMI(COMPUTER, namespace="root/default").StdRegProv
LOGFILE = os.getcwd() + "\\DCOMMon.log"
def Logger(title, filename):
logger = logging.getLogger(title)
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(filename, maxBytes=0, backupCount=0)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def LogIt(filename=LOGFILE):
#try:
# if os.path.exists(filename):
# os.remove(filename)
#except:
# pass
log = Logger("DCOMMon", filename)
tb = str(traceback.format_exc()).split("\n")
log.error("")
for i, a in enumerate(tb):
if a.strip() != "":
log.error(a)
class Monitor:
def RepairDCOM(self):
try:
repaired = {}
dict1 = self.GetDefaultDCOM()
dict2 = self.GetCurrentDCOM()
compared = self.CompareDCOM(dict1, dict2)
for dobj in DCOM_DEFAULT_CONFIGURATION:
try:
compared[dobj]
if dobj == "LegacyAuthenticationLevel" or dobj == "LegacyImpersonationLevel":
REGISTRY.SetDWORDValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, uValue=dict1[dobj])
elif dobj == "DefaultAccessPermission" or dobj == "DefaultLaunchPermission" or \
dobj == "MachineAccessRestriction" or dobj == "MachineLaunchRestriction":
REGISTRY.SetBinaryValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, uValue=dict1[dobj])
elif dobj == "EnableDCOM" or dobj == "EnableRemoteConnect":
REGISTRY.SetStringValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=dobj, sValue=dict1[dobj])
except KeyError:
pass
except:
LogIt(LOGFILE)
def CompareDCOM(self, dict1, dict2):
compare = {}
for (key, value) in dict2.iteritems():
try:
if dict1[key] != value:
compare[key] = value
except KeyError:
compare[key] = value
return compare
def GetCurrentDCOM(self):
current = {}
for name in REGISTRY.EnumValues(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole")[1]:
value = REGISTRY.GetStringValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1]
if value:
current[str(name)] = str(value)
else:
value = REGISTRY.GetDWORDValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1]
if not value:
value = REGISTRY.GetBinaryValue(hDefKey=reg.HKEY_LOCAL_MACHINE, sSubKeyName="SOFTWARE\\Microsoft\\Ole", sValueName=str(name))[1]
current[str(name)] = value
return current
def GetDefaultDCOM(self):
default = {}
# Get Default DCOM Settings
for name in REGISTRY.EnumValues(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon")[1]:
value = REGISTRY.GetStringValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1]
if value:
default[str(name)] = str(value)
else:
value = REGISTRY.GetDWORDValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1]
if not value:
value = REGISTRY.GetBinaryValue(hDefKey=reg.HKEY_CURRENT_USER, sSubKeyName="Software\\DCOMMon", sValueName=str(name))[1]
default[str(name)] = value
return default
class DCOMMon(win32serviceutil.ServiceFramework):
_svc_name_ = "DCOMMon"
_svc_display_name_ = "DCOM Monitoring Service"
_svc_description_ = "DCOM Monitoring Service"
_svc_deps_ = ["EventLog"]
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.isAlive = True
def SvcDoRun(self):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ': DCOM Monitoring Service - Service Started'))
self.timeout=30000 # In milliseconds
while self.isAlive:
rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
if rc == win32event.WAIT_OBJECT_0:
break
else:
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ': DCOM Monitoring Service - Examining DCOM Configuration'))
Monitor().RepairDCOM()
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ': DCOM Monitoring Service - Service Stopped'))
return
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
LOG.close()
self.isAlive = False
return
#def ctrlHandler(ctrlType):
# return True
if __name__ == '__main__':
# win32api.SetConsoleCtrlHandler(ctrlHandler, True)
#print Monitor().RepairDCOM()
win32serviceutil.HandleCommandLine(DCOMMon)
DCOMMon_setup.py - Requires py2exe (self executable, no need for py2exe arg)
# DCOMMon_setup.py (self executable, no need for py2exe arg)
# Usage:
# DCOMMon.exe install
# DCOMMon.exe start
# DCOMMon.exe stop
# DCOMMon.exe remove
# DCOMMon.exe debug
# you can see output of this program running python site-packages\win32\lib\win32traceutil
try:
# (snippet I found somewhere, searching something??)
# if this doesn't work, try import modulefinder
import py2exe.mf as modulefinder
import win32com, sys
for p in win32com.__path__[1:]:
modulefinder.AddPackagePath("win32com", p)
for extra in ["win32com.shell"]: #,"win32com.mapi"
__import__(extra)
m = sys.modules[extra]
for p in m.__path__[1:]:
modulefinder.AddPackagePath(extra, p)
except ImportError:
print "NOT FOUND"
from distutils.core import setup
import py2exe, sys
if len(sys.argv) == 1:
sys.argv.append("py2exe")
#sys.argv.append("-q")
class Target:
def __init__(self, **kw):
self.__dict__.update(kw)
# for the versioninfo resources
self.version = "1.0.0.1"
self.language = "English (Canada)"
self.company_name = "Whoever"
self.copyright = "Nobody"
self.name = "Nobody Home"
myservice = Target(
description = 'DCOM Monitoring Service',
modules = ['DCOMMon'],
cmdline_style='pywin32'
#dest_base = 'DCOMMon'
)
setup(
options = {"py2exe": {"compressed": 1, "bundle_files": 1, "ascii": 1, "packages": ["encodings"]} },
console=["DCOMMon.py"],
zipfile = None,
service=[myservice]
)
|
[
"So I guess it's time to admit my stupidity.... :P\nIt turns out this was not a python issue, py2exe issue, nor a WMI issue. :(\nThis was more or less a simple permission issue. So simple I overlooked it for the better part of a month. :(\nRule of thumb, if you want to create a service that calls to specific registry keys to obtain (in this case) default configuration settings.... \nmaybe... JUST MAYBE....\nOne should place their default key within the \"HKEY_LOCAL_MACHINE\", instead of \"HKEY_CURRENT_USER\"?? :P\nYeah, it's that simple...\nI should have remembered this rule from other projects I have worked on in the past. When you are running as the Local System account, simply put, there is no \"HKEY_CURRENT_USER\" subkey to access. If you absolutely have to access a specific user's \"HKEY_CURRENT_USER\" subkey, I would guess the only way would be to impersonate the user. Luckily for me this is not necessary for what I am attempting to accomplish.\nThe below link provided me with what I needed to jog my memory and fix the issue:\nhttp://msdn.microsoft.com/en-us/library/ms684190%28VS.85%29.aspx\nSo to make a long story short, I migrated all of my default values over to \"HKEY_LOCAL_MACHINE\\SOFTWARE\" subkey and my service is working perfectly. :D\nThanks for your help guys but this problem is solved ;)\n",
"I am not an expert at this, but here are my two cents worth:\nThis article tells me that you might need to be logged in as someone with the required target system permissions. \nHowever, I find that a little excessive. Have you tried compiling your script from the command line while running the command prompt as the administrator of the computer - so that you can unlock all permissions (on Windows Vista and Windows 7, this is achieved by right clicking on the command prompt icon in the start menu and clicking on \"run as administrator\").\nHope this helps\n"
] |
[
1,
0
] |
[] |
[] |
[
"py2exe",
"python",
"pywin32",
"windows_services",
"wmi"
] |
stackoverflow_0001780066_py2exe_python_pywin32_windows_services_wmi.txt
|
Q:
Alter namespace prefixing with ElementTree in Python
By default, when you call ElementTree.parse(someXMLfile) the Python ElementTree library prefixes every parsed node with it's namespace URI in Clark's Notation:
{http://example.org/namespace/spec}mynode
This makes accessing specific nodes by name a huge pain later in the code.
I've read through the docs on ElementTree and namespaces and it looks like the iterparse() function should allow me to alter the way the parser prefixes namespaces, but for the life of me I can't actually make it change the prefix. It seems like that may happen in the background before the ns-start event even fires as in this example:
for event, elem in iterparse(source):
if event == "start-ns":
namespaces.append(elem)
elif event == "end-ns":
namespaces.pop()
else:
...
How do I make it change the prefixing behavior and what is the proper thing to return when the function ends?
A:
You don't specifically need to use iterparse. Instead, the following script:
from cStringIO import StringIO
import xml.etree.ElementTree as ET
NS_MAP = {
'http://www.red-dove.com/ns/abc' : 'rdc',
'http://www.adobe.com/2006/mxml' : 'mx',
'http://www.red-dove.com/ns/def' : 'oth',
}
DATA = '''<?xml version="1.0" encoding="utf-8"?>
<rdc:container xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:rdc="http://www.red-dove.com/ns/abc"
xmlns:oth="http://www.red-dove.com/ns/def">
<mx:Style>
<oth:style1/>
</mx:Style>
<mx:Style>
<oth:style2/>
</mx:Style>
<mx:Style>
<oth:style3/>
</mx:Style>
</rdc:container>'''
tree = ET.parse(StringIO(DATA))
some_node = tree.getroot().getchildren()[1]
print ET.fixtag(some_node.tag, NS_MAP)
some_node = some_node.getchildren()[0]
print ET.fixtag(some_node.tag, NS_MAP)
produces
('mx:Style', None)
('oth:style2', None)
Which shows how you can access the fully-qualified tag names of individual nodes in a parsed tree. You should be able to adapt this to your specific needs.
A:
xml.etree.ElementTree doesn't appear to have fixtag, well, not according to the documentation. However I've looked at some source code for fixtag and you do:
import xml.etree.ElementTree as ET
for event, elem in ET.iterparse(inFile, events=("start", "end")):
namespace, looktag = string.split(elem.tag[1:], "}", 1)
You have the tag string in looktag, suitable for a lookup. The namespace is in namespace.
|
Alter namespace prefixing with ElementTree in Python
|
By default, when you call ElementTree.parse(someXMLfile) the Python ElementTree library prefixes every parsed node with it's namespace URI in Clark's Notation:
{http://example.org/namespace/spec}mynode
This makes accessing specific nodes by name a huge pain later in the code.
I've read through the docs on ElementTree and namespaces and it looks like the iterparse() function should allow me to alter the way the parser prefixes namespaces, but for the life of me I can't actually make it change the prefix. It seems like that may happen in the background before the ns-start event even fires as in this example:
for event, elem in iterparse(source):
if event == "start-ns":
namespaces.append(elem)
elif event == "end-ns":
namespaces.pop()
else:
...
How do I make it change the prefixing behavior and what is the proper thing to return when the function ends?
|
[
"You don't specifically need to use iterparse. Instead, the following script:\nfrom cStringIO import StringIO\nimport xml.etree.ElementTree as ET\n\nNS_MAP = {\n 'http://www.red-dove.com/ns/abc' : 'rdc',\n 'http://www.adobe.com/2006/mxml' : 'mx',\n 'http://www.red-dove.com/ns/def' : 'oth',\n}\n\nDATA = '''<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rdc:container xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n xmlns:rdc=\"http://www.red-dove.com/ns/abc\"\n xmlns:oth=\"http://www.red-dove.com/ns/def\">\n <mx:Style>\n <oth:style1/>\n </mx:Style>\n <mx:Style>\n <oth:style2/>\n </mx:Style>\n <mx:Style>\n <oth:style3/>\n </mx:Style>\n</rdc:container>'''\n\ntree = ET.parse(StringIO(DATA))\nsome_node = tree.getroot().getchildren()[1]\nprint ET.fixtag(some_node.tag, NS_MAP)\nsome_node = some_node.getchildren()[0]\nprint ET.fixtag(some_node.tag, NS_MAP)\n\nproduces\n\n('mx:Style', None)\n('oth:style2', None)\n\nWhich shows how you can access the fully-qualified tag names of individual nodes in a parsed tree. You should be able to adapt this to your specific needs.\n",
"xml.etree.ElementTree doesn't appear to have fixtag, well, not according to the documentation. However I've looked at some source code for fixtag and you do:\nimport xml.etree.ElementTree as ET\n\nfor event, elem in ET.iterparse(inFile, events=(\"start\", \"end\")):\n namespace, looktag = string.split(elem.tag[1:], \"}\", 1)\n\nYou have the tag string in looktag, suitable for a lookup. The namespace is in namespace.\n"
] |
[
6,
2
] |
[] |
[] |
[
"elementtree",
"namespaces",
"python",
"xml"
] |
stackoverflow_0001249876_elementtree_namespaces_python_xml.txt
|
Q:
Getting a list of all churches in a certain state using Python
I am pretty good with Python, so pseudo-code will suffice when details are trivial. Please get me started on the task - how do go about crawling the net for the snail mail addresses of churches in my state. Once I have a one liner such as "123 Old West Road #3 Old Lyme City MD 01234", I can probably parse it into City, State, Street, number, apt with enough trial and error. My problem is - if I use white pages online, then how do I deal with all the HTML junk, HTML tables, ads, etc? I do not think I need their phone number, but it will not hurt - I can always throw it out once parsed. Even if your solution is half-manual (such as save to pdf, then open acrobat, save as text) - I might be happy with it still. Thanks! Heck, I will even accept Perl snippets - I can translate them myself.
A:
Try lynx --dump <url> to download the web pages. All the troublesome HTML tags will be stripped from the output, and all the links from the page will appear together.
A:
You could use mechanize. It's a python library that simulates a browser, so you could crawl through the white pages (similarly to what you do manually).
In order to deal with the 'html junk' python has a library for that too: BeautifulSoup
It is a lovely way to get the data you want out of HTML (of course it assumes you know a little bit about HTML, as you will still have to navigate the parse tree).
Update: As to your follow-up question on how to click through multiple pages. mechanize is a library to do just that. Take a closer look at their examples, esp. the follow_link method. As I said it simulates a browser, so 'clicking' can be realized quickly in python.
A:
What you're trying to do is called Scraping or web scraping.
If you do some searches on python and scraping, you may find a list of tools that will help.
(I have never used scrapy, but it's site looks promising :)
A:
Beautiful Soup is a no brainer. Here's a site you might start at http://www.churchangel.com/. They have a huge list and the formatting is very regular -- translation: easy to setup BSoup to scrape.
A:
Python scripts might not be the best tool for this job, if you're just looking for addresses of churches in a geographic area.
The US census provides a data set of churches for use with geographic information systems. If finding all the x in a spatial area is a recurring problem, invest in learning a GIS. Then you can bring your Python skills to bear on many geographic tasks.
|
Getting a list of all churches in a certain state using Python
|
I am pretty good with Python, so pseudo-code will suffice when details are trivial. Please get me started on the task - how do go about crawling the net for the snail mail addresses of churches in my state. Once I have a one liner such as "123 Old West Road #3 Old Lyme City MD 01234", I can probably parse it into City, State, Street, number, apt with enough trial and error. My problem is - if I use white pages online, then how do I deal with all the HTML junk, HTML tables, ads, etc? I do not think I need their phone number, but it will not hurt - I can always throw it out once parsed. Even if your solution is half-manual (such as save to pdf, then open acrobat, save as text) - I might be happy with it still. Thanks! Heck, I will even accept Perl snippets - I can translate them myself.
|
[
"Try lynx --dump <url> to download the web pages. All the troublesome HTML tags will be stripped from the output, and all the links from the page will appear together.\n",
"You could use mechanize. It's a python library that simulates a browser, so you could crawl through the white pages (similarly to what you do manually).\nIn order to deal with the 'html junk' python has a library for that too: BeautifulSoup\nIt is a lovely way to get the data you want out of HTML (of course it assumes you know a little bit about HTML, as you will still have to navigate the parse tree).\nUpdate: As to your follow-up question on how to click through multiple pages. mechanize is a library to do just that. Take a closer look at their examples, esp. the follow_link method. As I said it simulates a browser, so 'clicking' can be realized quickly in python.\n",
"What you're trying to do is called Scraping or web scraping.\nIf you do some searches on python and scraping, you may find a list of tools that will help.\n(I have never used scrapy, but it's site looks promising :)\n",
"Beautiful Soup is a no brainer. Here's a site you might start at http://www.churchangel.com/. They have a huge list and the formatting is very regular -- translation: easy to setup BSoup to scrape.\n",
"Python scripts might not be the best tool for this job, if you're just looking for addresses of churches in a geographic area.\nThe US census provides a data set of churches for use with geographic information systems. If finding all the x in a spatial area is a recurring problem, invest in learning a GIS. Then you can bring your Python skills to bear on many geographic tasks.\n"
] |
[
2,
2,
2,
2,
1
] |
[] |
[] |
[
"automation",
"pseudocode",
"python",
"street_address",
"web_crawler"
] |
stackoverflow_0001903966_automation_pseudocode_python_street_address_web_crawler.txt
|
Q:
Does Reddit use any type of ORM?
Sorry I want to learn Python, and was curious if Reddit's codebase uses any sort of ORM?
A:
Have a look: http://code.reddit.com/browser/r2/r2/lib/db/
A:
Yes. Reddit uses the Pylons framework, and relies on the SQLAlchemy framework for its own ORM layer. However, SQLAlchemy is a fairly low-level ORM library as far as ORMs go, and so Reddit has a fair amount of custom code that makes the ORM stuff work.
|
Does Reddit use any type of ORM?
|
Sorry I want to learn Python, and was curious if Reddit's codebase uses any sort of ORM?
|
[
"Have a look: http://code.reddit.com/browser/r2/r2/lib/db/\n",
"Yes. Reddit uses the Pylons framework, and relies on the SQLAlchemy framework for its own ORM layer. However, SQLAlchemy is a fairly low-level ORM library as far as ORMs go, and so Reddit has a fair amount of custom code that makes the ORM stuff work.\n"
] |
[
4,
3
] |
[] |
[] |
[
"python",
"reddit"
] |
stackoverflow_0001904319_python_reddit.txt
|
Q:
Run a remote python script from ASP.Net
I have a python script on a linux server that I can SSH into and I want to run the script on the linux server( and pass it parameters entered by the user) and get the output on an ASP.net webpage running on IIS. How would I be able to do that?
Would it be easier if I was running a wamp server?
Edit: The servers are in the same internal intranet.
A:
Probably the best approach is the least coupled one. If you can determine a protocol that you're comfortable with the two (asp/python) talking in, it will go a long way to reducing headaches.
Let's say you pick XML.
Setup the python script to run as a WSGI application with either cherrypy or apache (or whatever). The script formats it's response in XML and passes that to WSGI which returns the XML over HTTP.
On the ASP.NET side of things, whenever you want to "run the script" you simply query the URL with the WebRequest class, then parse the results with LINQ-to-XML (which on a side note is a really cool technology).
Here's where this becomes relevant: Later on if either the ASP.NET implementation or the python implementation changes you don't have to re-code/refactor the other. Later if you realize that the ASP.NET app and some desktop app need to be able to do that, you've standardized on a protocol and implementing it should be easy and well supported.
|
Run a remote python script from ASP.Net
|
I have a python script on a linux server that I can SSH into and I want to run the script on the linux server( and pass it parameters entered by the user) and get the output on an ASP.net webpage running on IIS. How would I be able to do that?
Would it be easier if I was running a wamp server?
Edit: The servers are in the same internal intranet.
|
[
"Probably the best approach is the least coupled one. If you can determine a protocol that you're comfortable with the two (asp/python) talking in, it will go a long way to reducing headaches.\nLet's say you pick XML.\nSetup the python script to run as a WSGI application with either cherrypy or apache (or whatever). The script formats it's response in XML and passes that to WSGI which returns the XML over HTTP.\nOn the ASP.NET side of things, whenever you want to \"run the script\" you simply query the URL with the WebRequest class, then parse the results with LINQ-to-XML (which on a side note is a really cool technology).\nHere's where this becomes relevant: Later on if either the ASP.NET implementation or the python implementation changes you don't have to re-code/refactor the other. Later if you realize that the ASP.NET app and some desktop app need to be able to do that, you've standardized on a protocol and implementing it should be easy and well supported.\n"
] |
[
0
] |
[] |
[] |
[
"asp.net",
"python",
"remote_execution"
] |
stackoverflow_0001904320_asp.net_python_remote_execution.txt
|
Q:
Python tempfile module and threads aren't playing nice; what am I doing wrong?
I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.)
Yet if I sort of replicate what the tempfile module is doing (not all the security checks, but just generating a file descriptor and then using os.fdopen to produce a file object) I have no problems.
Before filing this as a bug with Python, I figured I'd check here, as it's much more likely that I'm doing something subtly wrong. But if I am, a day of trying to figure it out hasn't gotten me anywhere.
#!/usr/bin/python
import threading
import thread
import tempfile
import os
import time
import sys
NUM_THREADS = 10000
def worker_tempfile():
tempfd, tempfn = tempfile.mkstemp()
tempobj = os.fdopen(tempfd, 'wb')
tempobj.write('hello, world')
tempobj.close()
os.remove(tempfn)
time.sleep(10)
def worker_notempfile(index):
tempfn = str(index) + '.txt'
# The values I'm passing os.open may be different than tempfile.mkstemp
# uses, but it works this way as does using the open() function to create
# a file object directly.
tempfd = os.open(tempfn,
os.O_EXCL | os.O_CREAT | os.O_TRUNC | os.O_RDWR)
tempobj = os.fdopen(tempfd, 'wb')
tempobj.write('hello, world')
tempobj.close()
os.remove(tempfn)
time.sleep(10)
def main():
for count in range(NUM_THREADS):
if count % 100 == 0:
print('Opening thread %s' % count)
wthread = threading.Thread(target=worker_tempfile)
#wthread = threading.Thread(target=worker_notempfile, args=(count,))
started = False
while not started:
try:
wthread.start()
started = True
except thread.error:
print('failed starting thread %s; sleeping' % count)
time.sleep(3)
if __name__ == '__main__':
main()
If I run it with the worker_notempfile line active and the worker_tempfile line commented-out, it runs to completion.
The other way around (using worker_tempfile) I get the following error:
$ python threadtempfiletest.py
Opening thread 0
Opening thread 100
Opening thread 200
Opening thread 300
Exception in thread Thread-301:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 460, in __bootstrap
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 440, in run
File "threadtempfiletest.py", line 17, in worker_tempfile
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py", line 302, in mkstemp
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py", line 236, in _mkstemp_inner
OSError: [Errno 24] Too many open files: '/var/folders/4L/4LtD6bCvEoipksvnAcJ2Ok+++Tk/-Tmp-/tmpJ6wjV0'
Any ideas what I'm doing wrong? Is this a bug in Python, or am I being bone-headed?
UPDATE 2009-12-14:
I think I've found the answer, but I don't like it. Since nobody was able to replicate the problem, I went hunting around our office for machines. It passed on everything except my machine. I tested on a Mac with the same software versions I was using. I even went hunting for a Desktop G5 with the EXACT same hardware and software config I had -- same result. Both tests (with tempfile and without tempfile) succeeded on everything.
For kicks, I downloaded Python 2.6.4, and tried it on my desktop, and same pattern on my system as Python 2.5.1: tempfile failed, and notempfile succeeded.
This is leading me to the conclusion that something's hosed on my Mac, but I sure can't figure out what. Any suggestions are welcome.
A:
I am unable to reproduce the problem with (Apple's own build of) Python 2.5.1 on Mac OS X 10.5.9 -- runs to completion just fine!
I've tried both on a Macbook Pro, i.e., an Intel processor, and an old PowerMac, i.e., a PPC processor.
So I can only imagine there must have been a bug in 10.5.8 which I never noticed (don't have any 10.5.8 around to test, as I always upgrade promptly whenever software update offers it). All I can suggest is that you try upgrading to 10.5.9 and see if the bug disappears -- if it doesn't, I have no idea how this behavior difference between my machines and yours is possible.
A:
I think your answer can be found here. You have to explicitly os.close() the file descriptor given as the first part of the tuple that mkstemp gives you.
Edit: no, the OP is already doing what is supposed to be done. I'm leaving the answer up for the nice link.
A:
I just tested your code on my Ubuntu Linux computer here, and it worked perfectly for me.
I have one suggestion for you to try. I don't know that it will help but it can't hurt. Rewrite your code to use with:
from __future__ import with_statement
def worker_tempfile():
tempfd, tempfn = tempfile.mkstemp()
with os.fdopen(tempfd, 'wb') as tempobj:
tempobj.write('hello, world')
os.remove(tempfn)
time.sleep(10)
The with statement is supposed to make sure that the file object gets closed no matter what. Perhaps it might help?
Good luck. Great job on the question, by the way.
A:
Why do you think the error is not genuine? You are launching 10000 threads, each opening a file, while the maximum number of open files is typically 1024 under Unix systems.
First try to keep manually track of the number of files currently open and check whether it bumps past the OS limit.
A:
Since nobody was able to replicate the problem, I went hunting around our office for machines. It passed on everything except my machine. I tested on a Mac with the same software versions I was using. I even went hunting for a Desktop G5 with the EXACT same hardware and software config I had -- same result. Both tests (with tempfile and without tempfile) succeeded on everything.
For kicks, I downloaded Python 2.6.4, and tried it on my desktop, and same pattern on my system as Python 2.5.1: tempfile failed, and notempfile succeeded.
This is leading me to the conclusion that something's hosed on my Mac, so this isn't likely to be a problem that anyone else runs into ever.
Thanks VERY much to everyone (especially Alex Martelli) who helped on this!
|
Python tempfile module and threads aren't playing nice; what am I doing wrong?
|
I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.)
Yet if I sort of replicate what the tempfile module is doing (not all the security checks, but just generating a file descriptor and then using os.fdopen to produce a file object) I have no problems.
Before filing this as a bug with Python, I figured I'd check here, as it's much more likely that I'm doing something subtly wrong. But if I am, a day of trying to figure it out hasn't gotten me anywhere.
#!/usr/bin/python
import threading
import thread
import tempfile
import os
import time
import sys
NUM_THREADS = 10000
def worker_tempfile():
tempfd, tempfn = tempfile.mkstemp()
tempobj = os.fdopen(tempfd, 'wb')
tempobj.write('hello, world')
tempobj.close()
os.remove(tempfn)
time.sleep(10)
def worker_notempfile(index):
tempfn = str(index) + '.txt'
# The values I'm passing os.open may be different than tempfile.mkstemp
# uses, but it works this way as does using the open() function to create
# a file object directly.
tempfd = os.open(tempfn,
os.O_EXCL | os.O_CREAT | os.O_TRUNC | os.O_RDWR)
tempobj = os.fdopen(tempfd, 'wb')
tempobj.write('hello, world')
tempobj.close()
os.remove(tempfn)
time.sleep(10)
def main():
for count in range(NUM_THREADS):
if count % 100 == 0:
print('Opening thread %s' % count)
wthread = threading.Thread(target=worker_tempfile)
#wthread = threading.Thread(target=worker_notempfile, args=(count,))
started = False
while not started:
try:
wthread.start()
started = True
except thread.error:
print('failed starting thread %s; sleeping' % count)
time.sleep(3)
if __name__ == '__main__':
main()
If I run it with the worker_notempfile line active and the worker_tempfile line commented-out, it runs to completion.
The other way around (using worker_tempfile) I get the following error:
$ python threadtempfiletest.py
Opening thread 0
Opening thread 100
Opening thread 200
Opening thread 300
Exception in thread Thread-301:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 460, in __bootstrap
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 440, in run
File "threadtempfiletest.py", line 17, in worker_tempfile
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py", line 302, in mkstemp
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py", line 236, in _mkstemp_inner
OSError: [Errno 24] Too many open files: '/var/folders/4L/4LtD6bCvEoipksvnAcJ2Ok+++Tk/-Tmp-/tmpJ6wjV0'
Any ideas what I'm doing wrong? Is this a bug in Python, or am I being bone-headed?
UPDATE 2009-12-14:
I think I've found the answer, but I don't like it. Since nobody was able to replicate the problem, I went hunting around our office for machines. It passed on everything except my machine. I tested on a Mac with the same software versions I was using. I even went hunting for a Desktop G5 with the EXACT same hardware and software config I had -- same result. Both tests (with tempfile and without tempfile) succeeded on everything.
For kicks, I downloaded Python 2.6.4, and tried it on my desktop, and same pattern on my system as Python 2.5.1: tempfile failed, and notempfile succeeded.
This is leading me to the conclusion that something's hosed on my Mac, but I sure can't figure out what. Any suggestions are welcome.
|
[
"I am unable to reproduce the problem with (Apple's own build of) Python 2.5.1 on Mac OS X 10.5.9 -- runs to completion just fine!\nI've tried both on a Macbook Pro, i.e., an Intel processor, and an old PowerMac, i.e., a PPC processor.\nSo I can only imagine there must have been a bug in 10.5.8 which I never noticed (don't have any 10.5.8 around to test, as I always upgrade promptly whenever software update offers it). All I can suggest is that you try upgrading to 10.5.9 and see if the bug disappears -- if it doesn't, I have no idea how this behavior difference between my machines and yours is possible.\n",
"I think your answer can be found here. You have to explicitly os.close() the file descriptor given as the first part of the tuple that mkstemp gives you.\nEdit: no, the OP is already doing what is supposed to be done. I'm leaving the answer up for the nice link.\n",
"I just tested your code on my Ubuntu Linux computer here, and it worked perfectly for me.\nI have one suggestion for you to try. I don't know that it will help but it can't hurt. Rewrite your code to use with:\nfrom __future__ import with_statement\n\ndef worker_tempfile():\n tempfd, tempfn = tempfile.mkstemp()\n with os.fdopen(tempfd, 'wb') as tempobj:\n tempobj.write('hello, world')\n os.remove(tempfn)\n time.sleep(10)\n\nThe with statement is supposed to make sure that the file object gets closed no matter what. Perhaps it might help?\nGood luck. Great job on the question, by the way.\n",
"Why do you think the error is not genuine? You are launching 10000 threads, each opening a file, while the maximum number of open files is typically 1024 under Unix systems.\nFirst try to keep manually track of the number of files currently open and check whether it bumps past the OS limit.\n",
"Since nobody was able to replicate the problem, I went hunting around our office for machines. It passed on everything except my machine. I tested on a Mac with the same software versions I was using. I even went hunting for a Desktop G5 with the EXACT same hardware and software config I had -- same result. Both tests (with tempfile and without tempfile) succeeded on everything.\nFor kicks, I downloaded Python 2.6.4, and tried it on my desktop, and same pattern on my system as Python 2.5.1: tempfile failed, and notempfile succeeded.\nThis is leading me to the conclusion that something's hosed on my Mac, so this isn't likely to be a problem that anyone else runs into ever.\nThanks VERY much to everyone (especially Alex Martelli) who helped on this!\n"
] |
[
4,
3,
1,
1,
0
] |
[] |
[] |
[
"multithreading",
"python",
"temporary_files"
] |
stackoverflow_0001895350_multithreading_python_temporary_files.txt
|
Q:
Synchronizing time between simple python-socket-based server and clients
I have the beginnings of a small multiplayer game that I'm writing in python as a learning exercise. Currently the server runs at 10 fps, while the clients run at whatever rate they like. This works well to conserve bandwidth, but unless the client tells the server when its input happened, all input gets quantized to 100ms intervals. How can I synchronize time between client and server so that I can make these corrections? A major hurdle here is that I'll need to determine ping times and compensate for them.
A:
I accidentally came across an excruciatingly fine blog post on how to do distributed network physics in general (without traditional client prediction). I highly recommend it, along with the GDC slides Fiedler presented a couple of years ago. Good luck!
A:
This is a very interesting question. Unfortunately there's no easy answer. You just have to understnad the issue well and settle for a solution that is good enough for your application.
My first instinct was that the Network Time Protocol (NTP) for setting machine clocks from NTP servers would have addressed this issue. One of the issues addressed there concerns Jitter Buffers, which involves packet delay variation. This is elaborated in RFC 3393; IP Packet Delay Variation Metric for IP Performance Metrics (IPPM).
|
Synchronizing time between simple python-socket-based server and clients
|
I have the beginnings of a small multiplayer game that I'm writing in python as a learning exercise. Currently the server runs at 10 fps, while the clients run at whatever rate they like. This works well to conserve bandwidth, but unless the client tells the server when its input happened, all input gets quantized to 100ms intervals. How can I synchronize time between client and server so that I can make these corrections? A major hurdle here is that I'll need to determine ping times and compensate for them.
|
[
"I accidentally came across an excruciatingly fine blog post on how to do distributed network physics in general (without traditional client prediction). I highly recommend it, along with the GDC slides Fiedler presented a couple of years ago. Good luck!\n",
"This is a very interesting question. Unfortunately there's no easy answer. You just have to understnad the issue well and settle for a solution that is good enough for your application.\nMy first instinct was that the Network Time Protocol (NTP) for setting machine clocks from NTP servers would have addressed this issue. One of the issues addressed there concerns Jitter Buffers, which involves packet delay variation. This is elaborated in RFC 3393; IP Packet Delay Variation Metric for IP Performance Metrics (IPPM).\n"
] |
[
1,
0
] |
[] |
[] |
[
"multiplayer",
"networking",
"python",
"udp"
] |
stackoverflow_0001893987_multiplayer_networking_python_udp.txt
|
Q:
How to have `pip install --editable` to run sdist instead of develop?
This Python package install using pip or easy_install from repos points out a very interesting features of pip.
However, sometimes you just want it to install the source distribution; this is particularly true when
you are running in a virtualenv (so you don't care about messing up the python path, since you are deliberating doing it in an env),
when you are not the developer of that particular package, and you don't want to have it "editable",
when you cannot pip install package-name because the package is not in any index,
when there is no tar.gz available.
Thanks for your answers!
A:
Have you tried just omitting the --editable? If I run
pip install hg+http://bitbucket.org/carljm/django-markitup/
it clones the repo to a temporary build directory and installs normally (via setup.py install rather than setup.py develop).
Of course, if you then freeze this environment, the generated requirement will not be fulfillable. If you need this, then just use --editable (there's really not much difference, works fine even if you don't actually need to edit the package) or just run your own instance of something like chishop and upload the sdists you need to it, then use the -i or --extra-index-url option.
|
How to have `pip install --editable` to run sdist instead of develop?
|
This Python package install using pip or easy_install from repos points out a very interesting features of pip.
However, sometimes you just want it to install the source distribution; this is particularly true when
you are running in a virtualenv (so you don't care about messing up the python path, since you are deliberating doing it in an env),
when you are not the developer of that particular package, and you don't want to have it "editable",
when you cannot pip install package-name because the package is not in any index,
when there is no tar.gz available.
Thanks for your answers!
|
[
"Have you tried just omitting the --editable? If I run\npip install hg+http://bitbucket.org/carljm/django-markitup/\n\nit clones the repo to a temporary build directory and installs normally (via setup.py install rather than setup.py develop).\nOf course, if you then freeze this environment, the generated requirement will not be fulfillable. If you need this, then just use --editable (there's really not much difference, works fine even if you don't actually need to edit the package) or just run your own instance of something like chishop and upload the sdists you need to it, then use the -i or --extra-index-url option.\n"
] |
[
3
] |
[] |
[] |
[
"build_automation",
"installation",
"pip",
"python"
] |
stackoverflow_0001900775_build_automation_installation_pip_python.txt
|
Q:
How to add a variable to the module I import from?
What I want to do is something like this:
template.py
def dummy_func():
print(VAR)
# more functions like this to follow
fabfile.py
# this gets called by fabric (fabfile.org)
# safe to think of it as ant build.xml
import template
template.VAR = 'some_val'
from template import *
Namely I have a template module other modules should 'extend' contributing the required variables.
Can this be done in a functional manner (as opposed to object inheritance)?
EDIT: Added a bit more code.
A:
I'm not sure what you mean by "a functional manner" -- do you mean, as in functional programming? That's not going to happen (since you're intrinsically trying to modify an object, which is the reverse of FP). Or do you mean something like "a way that works"?
For the latter interpretation, the big problem is the import * part -- among the many problems that suggest not using that, you're going to be running smack into one: it performs a snapshot of whatever module-level names are bound at the time (or just those listed in __all__ in the module, if that's defined) -- future changes to the bindings of names will never be reflected in modules that previously did the import *.
Why do you believe you need to merge the template_module's namespace into that of the importing module? If you just did a regular import template_module as tm, then simply referring to all the relevant names as tm.this, tm.that will work just fine (including picking up all changes to the bindings up to the instant of use -- in other words, it uses the "late binding" approach that you appear to require here).
A:
If you change a property of a module in one place, it will be the same in other places too. Proof:
Create a file '/tmp/test1.py':
imoprt os
os.path = '' # set os.path (module) to a mere string
os.zzz = 'zzz'
Then
cd /tmp && python
>>> dir(test)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'os', 'z']
>>> test.os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> test.os.path
''
>>> import os
>>> os.path
''
>>> os.zzz
'zzz'
Now os.path is an empty string even in the main application, and zzz is everywhere too.
A:
Turns out this has a fabric-centric solution.
So you have an abstract some__fab__template.py and a concrete fabfile.py that should 'extend' the template contributing some required variables (e.g. project name).
I've implemented it utilizing fab's env dictionary.
In template file you reference env.VAR and in the 'concrete' fabfile.py you do this:
from fabric.api import *
env.VAR = 'some value'
import some__fab__template
def dist():
some__fab__template.dist()
|
How to add a variable to the module I import from?
|
What I want to do is something like this:
template.py
def dummy_func():
print(VAR)
# more functions like this to follow
fabfile.py
# this gets called by fabric (fabfile.org)
# safe to think of it as ant build.xml
import template
template.VAR = 'some_val'
from template import *
Namely I have a template module other modules should 'extend' contributing the required variables.
Can this be done in a functional manner (as opposed to object inheritance)?
EDIT: Added a bit more code.
|
[
"I'm not sure what you mean by \"a functional manner\" -- do you mean, as in functional programming? That's not going to happen (since you're intrinsically trying to modify an object, which is the reverse of FP). Or do you mean something like \"a way that works\"?\nFor the latter interpretation, the big problem is the import * part -- among the many problems that suggest not using that, you're going to be running smack into one: it performs a snapshot of whatever module-level names are bound at the time (or just those listed in __all__ in the module, if that's defined) -- future changes to the bindings of names will never be reflected in modules that previously did the import *.\nWhy do you believe you need to merge the template_module's namespace into that of the importing module? If you just did a regular import template_module as tm, then simply referring to all the relevant names as tm.this, tm.that will work just fine (including picking up all changes to the bindings up to the instant of use -- in other words, it uses the \"late binding\" approach that you appear to require here).\n",
"If you change a property of a module in one place, it will be the same in other places too. Proof:\nCreate a file '/tmp/test1.py':\nimoprt os\nos.path = '' # set os.path (module) to a mere string\nos.zzz = 'zzz'\n\nThen\ncd /tmp && python\n\n>>> dir(test)\n['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'os', 'z']\n>>> test.os\n<module 'os' from '/usr/lib/python2.6/os.pyc'>\n>>> test.os.path\n''\n>>> import os\n>>> os.path\n''\n>>> os.zzz\n'zzz'\n\nNow os.path is an empty string even in the main application, and zzz is everywhere too.\n",
"Turns out this has a fabric-centric solution.\nSo you have an abstract some__fab__template.py and a concrete fabfile.py that should 'extend' the template contributing some required variables (e.g. project name).\nI've implemented it utilizing fab's env dictionary.\nIn template file you reference env.VAR and in the 'concrete' fabfile.py you do this:\nfrom fabric.api import *\nenv.VAR = 'some value'\nimport some__fab__template\n\ndef dist():\n some__fab__template.dist()\n\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"fabric",
"python"
] |
stackoverflow_0001902656_fabric_python.txt
|
Q:
PyObjc and Cocoa on Snow Leopard
I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and not get into University. So this is quite important to me.
I want to use Python to develop a Cocoa app. I know that I need PyObjc, however all details on the net seem to assume it is pre-installed. Apparently this is the case with Leopard and Snow Leopard but I don't seem to have it on Snow Leopard and never noticed it on Leopard. Also, I have tried installing the latest beta of PyObjc by following the instructions on the Sourceforge page, but with no luck.
I would really appreciate it if anyone could shed some light on what needs to be installed, how, and links to any resources or tutorials that could help me.
Thanks in advance for the help!
Update: I see that this is a popular question, I just got the 'Notable Question' badge for it so I thought I would update anyone coming to this page on what I did after getting the answers.
Unfortunately, I wasn't able to use Python to create a Mac application. This was rather disappointing at the time, but probably a good thing. I made a Windows app in C# for my project, it was a tool for creating and running Assembly apps in a simulated environment. My course teacher has now started to use my tool to teach the course instead of his own! I got a very high score on the computing project (over 90%) and this contributed to me getting an A* in my computing A-Level (the highest grade available) and I consequently got in to Southampton University to study Computer Science.
This summer, I decided to make an iPad app (soon to be released) and I am glad to say that I know think I could make a Mac OS application in Objective-C as I feel I have learnt enough. I am glad that I took the time to learn it, it is a great language and really useful with iOS becoming so popular.
Sorry for all the boasting, but I am really happy about it. What I really want to say is, if you are coming to this page hoping to use PyObjc to create Mac apps easily, don't bother. It takes some time and some effort, but once you have learnt Objective-C, it is really satisfying to create apps with it. Good Luck!
A:
Allow me to echo what has already been said. I too am a student who just started a Cocoa development project, and at the beginning I thought "Well, I already know Python, I'll just use PyObjC and save myself from having to learn Objective-C, which looks beyond my grasp." I learned quickly that it can't be done. You can develop for OS X without learning Objective-C, but not without learning the Cocoa libraries, which constitute 99% of what you need to learn to write a Cocoa app in Objective-C. Objective-C itself isn't that hard; it's the Cocoa libraries that you need to invest in learning.
PyObjC basically uses Cocoa libraries and Python syntax. I gave up with it quickly and decided that if I was going to have to learn Cocoa, I may as well use Objective-C.
If you're looking to learn, Aaron Hillegass's book is a good place to start. Good luck!
A:
You mean like Checkout? :-) I only mention it because Checkout is gorgeous and written with PyObjC...
Your concerns are valid, although probably not as much of a potential showstopper as you'd think. Using PyObjC still requires you to learn some Objective-C, and definitely requires you to understand at least some of the Cocoa frameworks, since you need to call into the Cocoa frameworks whenever you need to do some sort of Cocoa-specific task.
I recommend you read and consider the SO question "Why is the PyObjC documentation so bad?" and "PyObjc vs RubyCocoa for Mac development: Which is more mature?" before you completely convince yourself that "just PyObjC" will make things much easier. I refuse to disparage PyObjC because it is quite powerful and incredibly useful, but realize that nothing is a silver bullet, and no language or technology is best for all problems.
The Objective-C language is simple and pretty straightforward. The Cocoa frameworks generally dominate the learning curve for new Cocoa programmers. Plus, you have StackOverflow and lots of other resources to help answer your questions. (Judging by the activity of the "pyobjc" tag, you also stand a better chance of getting good Objective-C help on SO.)
A:
And as one of the Checkout developers I'll weigh in too (hi Quinn!). From what we've seen PyObjC runs fairly well on Snow Leopard. We've built one of the latest SVN revisions 2.2b with some customizations on Leopard and just moved over the site-packages folder.
Theoretically you should be able to use the built in Python/PyObjC (just do import objc, Foundation, AppKit) but as we ship/work with custom versions of both Python and PyObjC I'm not sure what the status exactly is. The mailing list doesn't mention a lot of people having issues (just a few) so that could be a good sign.
Good luck with the project, and if you have specific POS questions shoot me an email ;-)
A:
I hardly use PyObjC myself, but I believe you need to run the Xcode installer on the Snow Leopard DVD in order to use PyObjC.
Also, as Quinn said, you will need to understand at least some Objective-C in order to use a Cocoa bridge like PyObjC without tearing your hair out. It just doesn't insulate you that completely.
A:
I'm going to agree with Quinn here. Even if you're already proficient in Python, learning how to interface Python and Cocoa is not going to be any easier than learning Cocoa with Objective-C.
Objective-C is a simple, clean language that is quite easy to grok. Building the GUI and hooking it up to the back-end will be harder than learning the Objective-C to write the back-end, and building the GUI and hooking it up isn't that hard.
Follow the Cocoa app tutorial (you should be able to get through it in a day, or maybe a weekend if you go slow) and you'll be well on your way.
A:
I'm a long time python developer who's been doing iPhone apps for awhile now (and only using my python knowledge to package up build files for the apps in run scripts), then who started making some PyObjC apps.
I'd have to say, PyObjC is pretty much STILL having to learn objective C (which I already know via iPhone dev), however you get several pretty cool benefits if you use it instead
Easy use of python libraries you know (faster for you)
Option to drop it and go to wxPython if styimied by Cocoa
Somewhat faster development time (you're writing less code, and the translation between the two languages is pretty darn easy to get used to).
Additionally, interface builder is a little tricky to get used to comparatively speaking, but if you're a python dev, it's not like you're exactly used to a functional gui builder anyhow :oP
|
PyObjc and Cocoa on Snow Leopard
|
I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and not get into University. So this is quite important to me.
I want to use Python to develop a Cocoa app. I know that I need PyObjc, however all details on the net seem to assume it is pre-installed. Apparently this is the case with Leopard and Snow Leopard but I don't seem to have it on Snow Leopard and never noticed it on Leopard. Also, I have tried installing the latest beta of PyObjc by following the instructions on the Sourceforge page, but with no luck.
I would really appreciate it if anyone could shed some light on what needs to be installed, how, and links to any resources or tutorials that could help me.
Thanks in advance for the help!
Update: I see that this is a popular question, I just got the 'Notable Question' badge for it so I thought I would update anyone coming to this page on what I did after getting the answers.
Unfortunately, I wasn't able to use Python to create a Mac application. This was rather disappointing at the time, but probably a good thing. I made a Windows app in C# for my project, it was a tool for creating and running Assembly apps in a simulated environment. My course teacher has now started to use my tool to teach the course instead of his own! I got a very high score on the computing project (over 90%) and this contributed to me getting an A* in my computing A-Level (the highest grade available) and I consequently got in to Southampton University to study Computer Science.
This summer, I decided to make an iPad app (soon to be released) and I am glad to say that I know think I could make a Mac OS application in Objective-C as I feel I have learnt enough. I am glad that I took the time to learn it, it is a great language and really useful with iOS becoming so popular.
Sorry for all the boasting, but I am really happy about it. What I really want to say is, if you are coming to this page hoping to use PyObjc to create Mac apps easily, don't bother. It takes some time and some effort, but once you have learnt Objective-C, it is really satisfying to create apps with it. Good Luck!
|
[
"Allow me to echo what has already been said. I too am a student who just started a Cocoa development project, and at the beginning I thought \"Well, I already know Python, I'll just use PyObjC and save myself from having to learn Objective-C, which looks beyond my grasp.\" I learned quickly that it can't be done. You can develop for OS X without learning Objective-C, but not without learning the Cocoa libraries, which constitute 99% of what you need to learn to write a Cocoa app in Objective-C. Objective-C itself isn't that hard; it's the Cocoa libraries that you need to invest in learning.\nPyObjC basically uses Cocoa libraries and Python syntax. I gave up with it quickly and decided that if I was going to have to learn Cocoa, I may as well use Objective-C.\nIf you're looking to learn, Aaron Hillegass's book is a good place to start. Good luck!\n",
"You mean like Checkout? :-) I only mention it because Checkout is gorgeous and written with PyObjC...\nYour concerns are valid, although probably not as much of a potential showstopper as you'd think. Using PyObjC still requires you to learn some Objective-C, and definitely requires you to understand at least some of the Cocoa frameworks, since you need to call into the Cocoa frameworks whenever you need to do some sort of Cocoa-specific task.\nI recommend you read and consider the SO question \"Why is the PyObjC documentation so bad?\" and \"PyObjc vs RubyCocoa for Mac development: Which is more mature?\" before you completely convince yourself that \"just PyObjC\" will make things much easier. I refuse to disparage PyObjC because it is quite powerful and incredibly useful, but realize that nothing is a silver bullet, and no language or technology is best for all problems.\nThe Objective-C language is simple and pretty straightforward. The Cocoa frameworks generally dominate the learning curve for new Cocoa programmers. Plus, you have StackOverflow and lots of other resources to help answer your questions. (Judging by the activity of the \"pyobjc\" tag, you also stand a better chance of getting good Objective-C help on SO.)\n",
"And as one of the Checkout developers I'll weigh in too (hi Quinn!). From what we've seen PyObjC runs fairly well on Snow Leopard. We've built one of the latest SVN revisions 2.2b with some customizations on Leopard and just moved over the site-packages folder.\nTheoretically you should be able to use the built in Python/PyObjC (just do import objc, Foundation, AppKit) but as we ship/work with custom versions of both Python and PyObjC I'm not sure what the status exactly is. The mailing list doesn't mention a lot of people having issues (just a few) so that could be a good sign.\nGood luck with the project, and if you have specific POS questions shoot me an email ;-)\n",
"I hardly use PyObjC myself, but I believe you need to run the Xcode installer on the Snow Leopard DVD in order to use PyObjC.\nAlso, as Quinn said, you will need to understand at least some Objective-C in order to use a Cocoa bridge like PyObjC without tearing your hair out. It just doesn't insulate you that completely.\n",
"I'm going to agree with Quinn here. Even if you're already proficient in Python, learning how to interface Python and Cocoa is not going to be any easier than learning Cocoa with Objective-C.\nObjective-C is a simple, clean language that is quite easy to grok. Building the GUI and hooking it up to the back-end will be harder than learning the Objective-C to write the back-end, and building the GUI and hooking it up isn't that hard.\nFollow the Cocoa app tutorial (you should be able to get through it in a day, or maybe a weekend if you go slow) and you'll be well on your way.\n",
"I'm a long time python developer who's been doing iPhone apps for awhile now (and only using my python knowledge to package up build files for the apps in run scripts), then who started making some PyObjC apps.\nI'd have to say, PyObjC is pretty much STILL having to learn objective C (which I already know via iPhone dev), however you get several pretty cool benefits if you use it instead\n\nEasy use of python libraries you know (faster for you)\nOption to drop it and go to wxPython if styimied by Cocoa\nSomewhat faster development time (you're writing less code, and the translation between the two languages is pretty darn easy to get used to).\n\nAdditionally, interface builder is a little tricky to get used to comparatively speaking, but if you're a python dev, it's not like you're exactly used to a functional gui builder anyhow :oP\n"
] |
[
18,
7,
4,
3,
3,
3
] |
[] |
[] |
[
"cocoa",
"osx_snow_leopard",
"pyobjc",
"python",
"xcode"
] |
stackoverflow_0001359227_cocoa_osx_snow_leopard_pyobjc_python_xcode.txt
|
Q:
PyQt: Call a TrayMinimized application
I have an application wich is minimized to the tray (showing an icon) when the user close it. What I need to know is how can I call it back with a combination of keys, like Ctrl+Alt+Something. Actually I call it back when I double-click it, but it will be nice to do the same on a keystroke. Here is a portion of the code:
# -*- coding: utf-8 -*-
"""The user interface for our app"""
import os,sys
import ConfigParser
# Import Qt modules
from PyQt4 import QtCore,QtGui
# Import the compiled UI module
from octo import Ui_Form
CFG_PATH = "etc/config.list" #Config File Path
#config.list vars DEFAULT Values
ClipCount = 8
Static = ""
window = None
# Create a class for our main window
class Main(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
# This is always the same
self.ui=Ui_Form()
self.ui.setupUi(self)
# Window Icon
icon = QtGui.QIcon("SSaver.ico")
self.setWindowIcon(icon)
self.setWindowTitle("Octopy")
# Set the timer =)
self.timer = self.startTimer(1000) #self.killTimer(self.timer)
# Clipboard Counter
self.counter = 0
#Last trapped clipboard
self.LastClip = ""
self.tentacles = [""] * 8
self.cmd = []
self.cmd.append(self.ui.cmd_1)
self.cmd.append(self.ui.cmd_2)
self.cmd.append(self.ui.cmd_3)
self.cmd.append(self.ui.cmd_4)
self.cmd.append(self.ui.cmd_5)
self.cmd.append(self.ui.cmd_6)
self.cmd.append(self.ui.cmd_7)
self.cmd.append(self.ui.cmd_8)
## Events ##
def on_cmd_8_pressed(self): #Clear
for i in range(0,7):
self.tentacles[i] = ""
self.cmd[i].setText(self.tentacles[i])
def on_cmd_1_pressed(self):
t = self.ui.cmd_1.text()
self.setClp(t)
def on_cmd_2_pressed(self):
t = self.ui.cmd_2.text()
self.setClp(t)
def on_cmd_3_pressed(self):
t = self.ui.cmd_3.text()
self.setClp(t)
def on_cmd_4_pressed(self):
t = self.ui.cmd_4.text()
self.setClp(t)
def on_cmd_5_pressed(self):
t = self.ui.cmd_5.text()
self.setClp(t)
def on_cmd_6_pressed(self):
t = self.ui.cmd_6.text()
self.setClp(t)
def on_cmd_7_pressed(self):
t = self.ui.cmd_7.text()
self.setClp(t)
def hideEvent(self,event): # Capture close and minimize events
pass
def keyPressEvent(self,ev):
if ev.key() == 16777216:
self.hide()
def showEvent(self,ev):
self.fillClp()
def timerEvent(self,ev):
c = self.getClp()
if c:
#print c, self.counter
self.tentacles[self.counter] = c
if self.counter < 7:
self.counter += 1
else:
self.counter = 0
self.fillClp()
## Functions ##
def fillClp(self):
for i in range(0,7):
self.cmd[i].setText(self.tentacles[i])
def getClp(self):
clp = QtGui.QApplication.clipboard()
c = clp.text()
if self.LastClip != c:
self.LastClip = c
return c
else:
return None
def setClp(self, t):
clp = QtGui.QApplication.clipboard()
clp.setText(t)
class SystemTrayIcon(QtGui.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtGui.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtGui.QMenu(parent)
# Actions
self.action_quit = QtGui.QAction("Quit", self)
self.action_about = QtGui.QAction("About Octopy", self)
# Add actions to menu
menu.addAction(self.action_about)
menu.addSeparator()
menu.addAction(self.action_quit)
# Connect menu with signals
self.connect(self.action_about, QtCore.SIGNAL("triggered()"), self.about)
self.connect(self.action_quit, QtCore.SIGNAL("triggered()"), self.quit)
# Other signals
traySignal = "activated(QSystemTrayIcon::ActivationReason)"
QtCore.QObject.connect(self, QtCore.SIGNAL(traySignal), self.icon_activated)
# Create Menu
self.setContextMenu(menu)
def quit(self):
w = QtGui.QWidget()
reply = QtGui.QMessageBox.question(w, 'Confirm Action',"Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
QtGui.QApplication.quit()
def about(self):
w = QtGui.QWidget()
QtGui.QMessageBox.information(w, 'About', "Octopy Multi-Clipboard Manager\n Developed by mRt.")
def icon_activated(self, reason):
if reason == QtGui.QSystemTrayIcon.DoubleClick:
window.show()
else:
print "otro"
def main():
# Again, this is boilerplate, it's going to be the same on
# almost every app you write
app = QtGui.QApplication(sys.argv)
# TrayIcon
w = QtGui.QWidget()
icon = QtGui.QIcon("SSaver.ico")
trayIcon = SystemTrayIcon(icon, w)
trayIcon.show()
trayIcon.setToolTip("Octopy Multi-Clipboard Manager")
# Main Window
global window
window=Main()
window.show()
window.setWindowTitle("Octopy")
app.setQuitOnLastWindowClosed(0)
sys.exit(app.exec_())
def readIni():
cfg = ConfigParser.ConfigParser()
cfg.read(CFG_PATH)
ClipCount = int(cfg.get("Other","ClipCount"))
Static = cfg.get("Other","Static")
clip = [""] * int(ClipCount+1)
if __name__ == "__main__":
readIni()
main()
The complete program is hosted on google: http://code.google.com/p/octopys/downloads/list
A:
For a keystroke to be handled by your application when it does not have keyboard focus, you need to install a global shortcut. Qt doesn't support this, but Qxt, a Qt extension library, does. See
http://doc.libqxt.org/0.5.0/classQxtGlobalShortcut.html. I don't know if PyQt bindings exist for Qxt.
|
PyQt: Call a TrayMinimized application
|
I have an application wich is minimized to the tray (showing an icon) when the user close it. What I need to know is how can I call it back with a combination of keys, like Ctrl+Alt+Something. Actually I call it back when I double-click it, but it will be nice to do the same on a keystroke. Here is a portion of the code:
# -*- coding: utf-8 -*-
"""The user interface for our app"""
import os,sys
import ConfigParser
# Import Qt modules
from PyQt4 import QtCore,QtGui
# Import the compiled UI module
from octo import Ui_Form
CFG_PATH = "etc/config.list" #Config File Path
#config.list vars DEFAULT Values
ClipCount = 8
Static = ""
window = None
# Create a class for our main window
class Main(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
# This is always the same
self.ui=Ui_Form()
self.ui.setupUi(self)
# Window Icon
icon = QtGui.QIcon("SSaver.ico")
self.setWindowIcon(icon)
self.setWindowTitle("Octopy")
# Set the timer =)
self.timer = self.startTimer(1000) #self.killTimer(self.timer)
# Clipboard Counter
self.counter = 0
#Last trapped clipboard
self.LastClip = ""
self.tentacles = [""] * 8
self.cmd = []
self.cmd.append(self.ui.cmd_1)
self.cmd.append(self.ui.cmd_2)
self.cmd.append(self.ui.cmd_3)
self.cmd.append(self.ui.cmd_4)
self.cmd.append(self.ui.cmd_5)
self.cmd.append(self.ui.cmd_6)
self.cmd.append(self.ui.cmd_7)
self.cmd.append(self.ui.cmd_8)
## Events ##
def on_cmd_8_pressed(self): #Clear
for i in range(0,7):
self.tentacles[i] = ""
self.cmd[i].setText(self.tentacles[i])
def on_cmd_1_pressed(self):
t = self.ui.cmd_1.text()
self.setClp(t)
def on_cmd_2_pressed(self):
t = self.ui.cmd_2.text()
self.setClp(t)
def on_cmd_3_pressed(self):
t = self.ui.cmd_3.text()
self.setClp(t)
def on_cmd_4_pressed(self):
t = self.ui.cmd_4.text()
self.setClp(t)
def on_cmd_5_pressed(self):
t = self.ui.cmd_5.text()
self.setClp(t)
def on_cmd_6_pressed(self):
t = self.ui.cmd_6.text()
self.setClp(t)
def on_cmd_7_pressed(self):
t = self.ui.cmd_7.text()
self.setClp(t)
def hideEvent(self,event): # Capture close and minimize events
pass
def keyPressEvent(self,ev):
if ev.key() == 16777216:
self.hide()
def showEvent(self,ev):
self.fillClp()
def timerEvent(self,ev):
c = self.getClp()
if c:
#print c, self.counter
self.tentacles[self.counter] = c
if self.counter < 7:
self.counter += 1
else:
self.counter = 0
self.fillClp()
## Functions ##
def fillClp(self):
for i in range(0,7):
self.cmd[i].setText(self.tentacles[i])
def getClp(self):
clp = QtGui.QApplication.clipboard()
c = clp.text()
if self.LastClip != c:
self.LastClip = c
return c
else:
return None
def setClp(self, t):
clp = QtGui.QApplication.clipboard()
clp.setText(t)
class SystemTrayIcon(QtGui.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtGui.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtGui.QMenu(parent)
# Actions
self.action_quit = QtGui.QAction("Quit", self)
self.action_about = QtGui.QAction("About Octopy", self)
# Add actions to menu
menu.addAction(self.action_about)
menu.addSeparator()
menu.addAction(self.action_quit)
# Connect menu with signals
self.connect(self.action_about, QtCore.SIGNAL("triggered()"), self.about)
self.connect(self.action_quit, QtCore.SIGNAL("triggered()"), self.quit)
# Other signals
traySignal = "activated(QSystemTrayIcon::ActivationReason)"
QtCore.QObject.connect(self, QtCore.SIGNAL(traySignal), self.icon_activated)
# Create Menu
self.setContextMenu(menu)
def quit(self):
w = QtGui.QWidget()
reply = QtGui.QMessageBox.question(w, 'Confirm Action',"Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
QtGui.QApplication.quit()
def about(self):
w = QtGui.QWidget()
QtGui.QMessageBox.information(w, 'About', "Octopy Multi-Clipboard Manager\n Developed by mRt.")
def icon_activated(self, reason):
if reason == QtGui.QSystemTrayIcon.DoubleClick:
window.show()
else:
print "otro"
def main():
# Again, this is boilerplate, it's going to be the same on
# almost every app you write
app = QtGui.QApplication(sys.argv)
# TrayIcon
w = QtGui.QWidget()
icon = QtGui.QIcon("SSaver.ico")
trayIcon = SystemTrayIcon(icon, w)
trayIcon.show()
trayIcon.setToolTip("Octopy Multi-Clipboard Manager")
# Main Window
global window
window=Main()
window.show()
window.setWindowTitle("Octopy")
app.setQuitOnLastWindowClosed(0)
sys.exit(app.exec_())
def readIni():
cfg = ConfigParser.ConfigParser()
cfg.read(CFG_PATH)
ClipCount = int(cfg.get("Other","ClipCount"))
Static = cfg.get("Other","Static")
clip = [""] * int(ClipCount+1)
if __name__ == "__main__":
readIni()
main()
The complete program is hosted on google: http://code.google.com/p/octopys/downloads/list
|
[
"For a keystroke to be handled by your application when it does not have keyboard focus, you need to install a global shortcut. Qt doesn't support this, but Qxt, a Qt extension library, does. See \nhttp://doc.libqxt.org/0.5.0/classQxtGlobalShortcut.html. I don't know if PyQt bindings exist for Qxt.\n"
] |
[
1
] |
[] |
[] |
[
"pyqt",
"python",
"qt"
] |
stackoverflow_0001904557_pyqt_python_qt.txt
|
Q:
Literals in django template language?
If I want some text to appear literally in a Django template, e.g.
{{Image.jpg|title}}
and I want that text to be output (not interpretated) in the HTML, how do I do so?
A:
Try the {% templatetag %} template tag
{% templatetag openvariable %}Image.jpg|title{% templatetag closevariable %}
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag
A:
You could start it with an HTML entity. e.g.:
{{Image.jpg|title}}
However, I can only imagine this means you are writing content in your templates, which is normally not advisable.
|
Literals in django template language?
|
If I want some text to appear literally in a Django template, e.g.
{{Image.jpg|title}}
and I want that text to be output (not interpretated) in the HTML, how do I do so?
|
[
"Try the {% templatetag %} template tag\n{% templatetag openvariable %}Image.jpg|title{% templatetag closevariable %}\n\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag\n",
"You could start it with an HTML entity. e.g.:\n{{Image.jpg|title}}\n\nHowever, I can only imagine this means you are writing content in your templates, which is normally not advisable.\n"
] |
[
5,
1
] |
[] |
[] |
[
"django",
"django_templates",
"literals",
"python",
"templates"
] |
stackoverflow_0001905396_django_django_templates_literals_python_templates.txt
|
Q:
Python QPushButton setIcon: put icon on button
I want to put an in ICON into a push button.. the code should work like that:
self.printButton = QtGui.QPushButton(self.tab_name)
self.printButton.setIcon(QtGui.QPixmap('printer.tif'))
self.printButton.setGeometry(QtCore.QRect(1030, 500, 161, 61))
But instead, it gives the error message:
TypeError: argument 1 of QAbstractButton.setIcon() has an invalid type
What is missing here?
All comments and suggestions are highly appreciated.
A:
This is strange, I quickly tested the code on my C++ application and it seems to be working...
Maybe by using this you could correct your problem :
rMyIcon = QtGui.QPixmap("printer.tif");
self.printButton.setIcon(QtGui.QIcon(rMyIcon))
Hope this helps a bit...
A:
Create a QIcon rather than a QPixmap for passing to setIcon(). Try changing the second line to
self.printButton.setIcon(QtGui.QIcon('printer.tif'))
A:
Hi Baysmith and Andy... thanks for the input. I tested your suggestions, it worked. I also have to add setIconSize, otherwise the icon is displayed very small. Here is code:
def printerButton(self,tab_name):
self.printButton = QtGui.QPushButton(tab_name)
self.printButton.setIcon(QtGui.QIcon('icons/printer.tif'))
self.printButton.setIconSize(QtCore.QSize(130,130))
self.printButton.setGeometry(QtCore.QRect(1030, 500, 161, 61))
Hope this help others too....|:0),
|
Python QPushButton setIcon: put icon on button
|
I want to put an in ICON into a push button.. the code should work like that:
self.printButton = QtGui.QPushButton(self.tab_name)
self.printButton.setIcon(QtGui.QPixmap('printer.tif'))
self.printButton.setGeometry(QtCore.QRect(1030, 500, 161, 61))
But instead, it gives the error message:
TypeError: argument 1 of QAbstractButton.setIcon() has an invalid type
What is missing here?
All comments and suggestions are highly appreciated.
|
[
"This is strange, I quickly tested the code on my C++ application and it seems to be working...\nMaybe by using this you could correct your problem :\nrMyIcon = QtGui.QPixmap(\"printer.tif\");\nself.printButton.setIcon(QtGui.QIcon(rMyIcon))\n\nHope this helps a bit...\n",
"Create a QIcon rather than a QPixmap for passing to setIcon(). Try changing the second line to\nself.printButton.setIcon(QtGui.QIcon('printer.tif'))\n\n",
"Hi Baysmith and Andy... thanks for the input. I tested your suggestions, it worked. I also have to add setIconSize, otherwise the icon is displayed very small. Here is code:\ndef printerButton(self,tab_name):\n self.printButton = QtGui.QPushButton(tab_name)\n self.printButton.setIcon(QtGui.QIcon('icons/printer.tif'))\n self.printButton.setIconSize(QtCore.QSize(130,130))\n self.printButton.setGeometry(QtCore.QRect(1030, 500, 161, 61))\n\nHope this help others too....|:0),\n"
] |
[
18,
7,
5
] |
[] |
[] |
[
"button",
"icons",
"python",
"qt",
"user_interface"
] |
stackoverflow_0001905402_button_icons_python_qt_user_interface.txt
|
Q:
dict keys with spaces in Django templates
I am trying to present a dictionary from my view.py at the HTML template such as:
test = { 'works': True, 'this fails':False }
and in the template:
This works without a problem:
{{ test.works }}
But a dictionary key that is having an empty space between words such as 'this fails' doesn't work:
{{ test.this fails }}
I get this error:
Could not parse the remainder: ' fails' from 'this fails'
How can I overcome this problem? I am not the one filling the models, so I can't change the keys of the dict to remove spaces.
A:
The filter you want is something like
@register.filter(name='getkey')
def getkey(value, arg):
return value[arg]
And used with
{{test|getkey:'this works'}}
source: http://www.bhphp.com/blog4.php/2009/08/17/django-templates-and-dictionaries
A:
I don't know any standard solution in Django. I think it is possible with a template filter.
You may be interested by this article http://push.cx/2007/django-template-tag-for-dictionary-access (the author is using template tag term but in fact it is a template filter)
I hope it helps
|
dict keys with spaces in Django templates
|
I am trying to present a dictionary from my view.py at the HTML template such as:
test = { 'works': True, 'this fails':False }
and in the template:
This works without a problem:
{{ test.works }}
But a dictionary key that is having an empty space between words such as 'this fails' doesn't work:
{{ test.this fails }}
I get this error:
Could not parse the remainder: ' fails' from 'this fails'
How can I overcome this problem? I am not the one filling the models, so I can't change the keys of the dict to remove spaces.
|
[
"The filter you want is something like \n@register.filter(name='getkey')\ndef getkey(value, arg):\n return value[arg]\n\nAnd used with \n{{test|getkey:'this works'}}\n\nsource: http://www.bhphp.com/blog4.php/2009/08/17/django-templates-and-dictionaries\n",
"I don't know any standard solution in Django. I think it is possible with a template filter. \nYou may be interested by this article http://push.cx/2007/django-template-tag-for-dictionary-access (the author is using template tag term but in fact it is a template filter)\nI hope it helps\n"
] |
[
18,
2
] |
[
"That doesn't look right to me. Can you do the following?\n{{ test['works'] }} \n{{ test['this fails'] }}\n\nThis is how dictionary access in python typically works.\n"
] |
[
-4
] |
[
"django",
"django_templates",
"python",
"whitespace"
] |
stackoverflow_0001906129_django_django_templates_python_whitespace.txt
|
Q:
pyExcelerator has problems reading some files
I've got a problem using pyExcelerator when reading some xls-files.
There're some python scripts i wrote, that use this library to parse XLS-files and populate database with info.
The templates for the files these scripts parse may vary and i sometimes reconfigure the script to handle them. With the one of the templates i ran into problem: pyExcelerator just raises an exception:
Traceback (most recent call last):
File "/home/* * */parsexls.py",
line 64, in handle_label
parser.parse()
File "/home/* * */parsers.py", line 335, in parse
self.contents = pyExcelerator.parse_xls(self.file_record.file,
self.encoding)
File "/usr/local/lib/python2.6/dist-packages/pyExcelerator/ImportXLS.py",
line 327, in parse_xls
ole_streams = CompoundDoc.Reader(filename).STREAMS
File "/usr/local/lib/python2.6/dist-packages/pyExcelerator/CompoundDoc.py",
line 67, in __init__
self.__build_short_sectors_data()
File "/usr/local/lib/python2.6/dist-packages/pyExcelerator/CompoundDoc.py",
line 256, in __build_short_sectors_data
dentry_start_sid, stream_size) = self.dir_entry_list[0]
IndexError: list index out of range
Some of the problem XLS-files contained empty sheets and removing of these sheets helped, but many of the files can't be handled even without empty sheets. There's nothing extraordinary in these files and they contain no formulas or pictures - just strings, numbers and dates.
As i can see, the pyExcelerator is abandoned by it's author :(
Any suggestions on fixing this issue are much appreciated.
A:
I'm the author of xlrd. It reads XLS files and is not a fork of anything. I maintain a package called xlwt which writes XLS files and is a fork of pyExcelerator. The parse_xls functionality in pyExcelerator was deprecated to the point of removal from xlwt. Use xlrd instead.
Given the traceback that you reproduced, it looks like the file may be corrupted. What it is doing there happens well before the sheet data is parsed. What software produces these files? Can you open them with Excel or OpenOffice.org's Calc or Gnumeric? xlrd may give you a more meaningful error message. You may like to send me (insert_punctuation('sjmachin', 'lexicon', 'net')) copies of your failing file(s); please include some with and some without empty sheets. By the way, what are you using to remove empty sheets? What error message do you get from pyExcelerator when processing files with empty sheets?
A:
You might wish to give xlrd a try... it started (I believe) as a fork of pyExcelerator, so incorporating requires few code changes, but it is actively maintained:
http://pypi.python.org/pypi/xlrd
Project website
General info, release notes and history from the documentation
|
pyExcelerator has problems reading some files
|
I've got a problem using pyExcelerator when reading some xls-files.
There're some python scripts i wrote, that use this library to parse XLS-files and populate database with info.
The templates for the files these scripts parse may vary and i sometimes reconfigure the script to handle them. With the one of the templates i ran into problem: pyExcelerator just raises an exception:
Traceback (most recent call last):
File "/home/* * */parsexls.py",
line 64, in handle_label
parser.parse()
File "/home/* * */parsers.py", line 335, in parse
self.contents = pyExcelerator.parse_xls(self.file_record.file,
self.encoding)
File "/usr/local/lib/python2.6/dist-packages/pyExcelerator/ImportXLS.py",
line 327, in parse_xls
ole_streams = CompoundDoc.Reader(filename).STREAMS
File "/usr/local/lib/python2.6/dist-packages/pyExcelerator/CompoundDoc.py",
line 67, in __init__
self.__build_short_sectors_data()
File "/usr/local/lib/python2.6/dist-packages/pyExcelerator/CompoundDoc.py",
line 256, in __build_short_sectors_data
dentry_start_sid, stream_size) = self.dir_entry_list[0]
IndexError: list index out of range
Some of the problem XLS-files contained empty sheets and removing of these sheets helped, but many of the files can't be handled even without empty sheets. There's nothing extraordinary in these files and they contain no formulas or pictures - just strings, numbers and dates.
As i can see, the pyExcelerator is abandoned by it's author :(
Any suggestions on fixing this issue are much appreciated.
|
[
"I'm the author of xlrd. It reads XLS files and is not a fork of anything. I maintain a package called xlwt which writes XLS files and is a fork of pyExcelerator. The parse_xls functionality in pyExcelerator was deprecated to the point of removal from xlwt. Use xlrd instead.\nGiven the traceback that you reproduced, it looks like the file may be corrupted. What it is doing there happens well before the sheet data is parsed. What software produces these files? Can you open them with Excel or OpenOffice.org's Calc or Gnumeric? xlrd may give you a more meaningful error message. You may like to send me (insert_punctuation('sjmachin', 'lexicon', 'net')) copies of your failing file(s); please include some with and some without empty sheets. By the way, what are you using to remove empty sheets? What error message do you get from pyExcelerator when processing files with empty sheets?\n",
"You might wish to give xlrd a try... it started (I believe) as a fork of pyExcelerator, so incorporating requires few code changes, but it is actively maintained:\nhttp://pypi.python.org/pypi/xlrd\nProject website\nGeneral info, release notes and history from the documentation\n"
] |
[
2,
1
] |
[] |
[] |
[
"excel",
"pyexcelerator",
"python",
"xls"
] |
stackoverflow_0001881253_excel_pyexcelerator_python_xls.txt
|
Q:
Keyword Matching in Pyparsing: non-greedy slurping of tokens
Pythonistas:
Suppose you want to parse the following string using Pyparsing:
'ABC_123_SPEED_X 123'
were ABC_123 is an identifier; SPEED_X is a parameter, and 123 is a value. I thought of the following BNF using Pyparsing:
Identifier = Word( alphanums + '_' )
Parameter = Keyword('SPEED_X') or Keyword('SPEED_Y') or Keyword('SPEED_Z')
Value = # assume I already have an expression valid for any value
Entry = Identifier + Literal('_') + Parameter + Value
tokens = Entry.parseString('ABC_123_SPEED_X 123')
#Error: pyparsing.ParseException: Expected "_" (at char 16), (line:1, col:17)
If I remove the underscore from the middle (and adjust the Entry definition accordingly) it parses correctly.
How can I make this parser be a bit lazier and wait until it matches the Keyword (as opposed to slurping the entire string as an Identifier and waiting for the _, which does not exist.
Thank you.
[Note: This is a complete rewrite of my question; I had not realized what the real problem was]
A:
I based my answer off of this one, since what you're trying to do is get a non-greedy match. It seems like this is difficult to make happen in pyparsing, but not impossible with some cleverness and compromise. The following seems to work:
from pyparsing import *
Parameter = Literal('SPEED_X') | Literal('SPEED_Y') | Literal('SPEED_Z')
UndParam = Suppress('_') + Parameter
Identifier = SkipTo(UndParam)
Value = Word(nums)
Entry = Identifier + UndParam + Value
When we run this from the interactive interpreter, we can see the following:
>>> Entry.parseString('ABC_123_SPEED_X 123')
(['ABC_123', 'SPEED_X', '123'], {})
Note that this is a compromise; because I use SkipTo, the Identifier can be full of evil, disgusting characters, not just beautiful alphanums with the occasional underscore.
EDIT: Thanks to Paul McGuire, we can concoct a truly elegant solution by setting Identifier to the following:
Identifier = Combine(Word(alphanums) +
ZeroOrMore('_' + ~Parameter + Word(alphanums)))
Let's inspect how this works. First, ignore the outer Combine; we'll get to this later. Starting with Word(alphanums) we know we'll get the 'ABC' part of the reference string, 'ABC_123_SPEED_X 123'. It's important to note that we didn't allow the "word" to contain underscores in this case. We build that separately in to the logic.
Next, we need to capture the '_123' part without also sucking in '_SPEED_X'. Let's also skip over ZeroOrMore at this point and return to it later. We start with the underscore as a Literal, but we can shortcut with just '_', which will get us the leading underscore, but not all of '_123'. Instictively, we would place another Word(alphanums) to capture the rest, but that's exactly what will get us in trouble by consuming all of the remaining '_123_SPEED_X'. Instead, we say, "So long as what follows the underscore is not the Parameter, parse that as part of my Identifier. We state that in pyparsing terms as '_' + ~Parameter + Word(alphanums). Since we assume we can have an arbitrary number of underscore + WordButNotParameter repeats, we wrap that expression a ZeroOrMore construct. (If you always expect at least underscore + WordButNotParameter following the initial, you can use OneOrMore.)
Finally, we need to wrap the initial Word and the special underscore + Word repeats together so that it's understood they are contiguous, not separated by whitespace, so we wrap the whole expression up in a Combine construct. This way 'ABC _123_SPEED_X' will raise a parse error, but 'ABC_123_SPEED_X' will parse correctly.
Note also that I had to change Keyword to Literal because the ways of the former are far too subtle and quick to anger. I do not trust Keywords, nor could I get matching with them.
A:
If you are sure that the identifier never ends with an underscore, you can enforce it in the definition:
from pyparsing import *
my_string = 'ABC_123_SPEED_X 123'
Identifier = Combine(Word(alphanums) + Literal('_') + Word(alphanums))
Parameter = Literal('SPEED_X') | Literal('SPEED_Y') | Literal('SPEED_Z')
Value = Word(nums)
Entry = Identifier + Literal('_').suppress() + Parameter + Value
tokens = Entry.parseString(my_string)
print tokens # prints: ['ABC_123', 'SPEED_X', '123']
If it's not the case but if the identifier length is fixed you can define Identifier like this:
Identifier = Word( alphanums + '_' , exact=7)
A:
You can also parse the identifier and parameter as one token, and split them in a parse action:
from pyparsing import *
import re
def split_ident_and_param(tokens):
mo = re.match(r"^(.*?_.*?)_(.*?_.*?)$", tokens[0])
return [mo.group(1), mo.group(2)]
ident_and_param = Word(alphanums + "_").setParseAction(split_ident_and_param)
value = Word(nums)
entry = ident_and_param + value
print entry.parseString("APC_123_SPEED_X 123")
The example above assumes that the identifiers and parameters always have the format XXX_YYY (containing one single underscore).
If this is not the case, you need to adjust the split_ident_and_param() method.
|
Keyword Matching in Pyparsing: non-greedy slurping of tokens
|
Pythonistas:
Suppose you want to parse the following string using Pyparsing:
'ABC_123_SPEED_X 123'
were ABC_123 is an identifier; SPEED_X is a parameter, and 123 is a value. I thought of the following BNF using Pyparsing:
Identifier = Word( alphanums + '_' )
Parameter = Keyword('SPEED_X') or Keyword('SPEED_Y') or Keyword('SPEED_Z')
Value = # assume I already have an expression valid for any value
Entry = Identifier + Literal('_') + Parameter + Value
tokens = Entry.parseString('ABC_123_SPEED_X 123')
#Error: pyparsing.ParseException: Expected "_" (at char 16), (line:1, col:17)
If I remove the underscore from the middle (and adjust the Entry definition accordingly) it parses correctly.
How can I make this parser be a bit lazier and wait until it matches the Keyword (as opposed to slurping the entire string as an Identifier and waiting for the _, which does not exist.
Thank you.
[Note: This is a complete rewrite of my question; I had not realized what the real problem was]
|
[
"I based my answer off of this one, since what you're trying to do is get a non-greedy match. It seems like this is difficult to make happen in pyparsing, but not impossible with some cleverness and compromise. The following seems to work:\nfrom pyparsing import *\nParameter = Literal('SPEED_X') | Literal('SPEED_Y') | Literal('SPEED_Z')\nUndParam = Suppress('_') + Parameter\nIdentifier = SkipTo(UndParam)\nValue = Word(nums)\nEntry = Identifier + UndParam + Value\n\nWhen we run this from the interactive interpreter, we can see the following:\n>>> Entry.parseString('ABC_123_SPEED_X 123')\n(['ABC_123', 'SPEED_X', '123'], {})\n\nNote that this is a compromise; because I use SkipTo, the Identifier can be full of evil, disgusting characters, not just beautiful alphanums with the occasional underscore. \nEDIT: Thanks to Paul McGuire, we can concoct a truly elegant solution by setting Identifier to the following:\nIdentifier = Combine(Word(alphanums) +\n ZeroOrMore('_' + ~Parameter + Word(alphanums)))\n\nLet's inspect how this works. First, ignore the outer Combine; we'll get to this later. Starting with Word(alphanums) we know we'll get the 'ABC' part of the reference string, 'ABC_123_SPEED_X 123'. It's important to note that we didn't allow the \"word\" to contain underscores in this case. We build that separately in to the logic.\nNext, we need to capture the '_123' part without also sucking in '_SPEED_X'. Let's also skip over ZeroOrMore at this point and return to it later. We start with the underscore as a Literal, but we can shortcut with just '_', which will get us the leading underscore, but not all of '_123'. Instictively, we would place another Word(alphanums) to capture the rest, but that's exactly what will get us in trouble by consuming all of the remaining '_123_SPEED_X'. Instead, we say, \"So long as what follows the underscore is not the Parameter, parse that as part of my Identifier. We state that in pyparsing terms as '_' + ~Parameter + Word(alphanums). Since we assume we can have an arbitrary number of underscore + WordButNotParameter repeats, we wrap that expression a ZeroOrMore construct. (If you always expect at least underscore + WordButNotParameter following the initial, you can use OneOrMore.)\nFinally, we need to wrap the initial Word and the special underscore + Word repeats together so that it's understood they are contiguous, not separated by whitespace, so we wrap the whole expression up in a Combine construct. This way 'ABC _123_SPEED_X' will raise a parse error, but 'ABC_123_SPEED_X' will parse correctly.\nNote also that I had to change Keyword to Literal because the ways of the former are far too subtle and quick to anger. I do not trust Keywords, nor could I get matching with them.\n",
"If you are sure that the identifier never ends with an underscore, you can enforce it in the definition:\nfrom pyparsing import *\n\nmy_string = 'ABC_123_SPEED_X 123'\n\nIdentifier = Combine(Word(alphanums) + Literal('_') + Word(alphanums))\nParameter = Literal('SPEED_X') | Literal('SPEED_Y') | Literal('SPEED_Z')\nValue = Word(nums)\nEntry = Identifier + Literal('_').suppress() + Parameter + Value\ntokens = Entry.parseString(my_string)\n\nprint tokens # prints: ['ABC_123', 'SPEED_X', '123']\n\nIf it's not the case but if the identifier length is fixed you can define Identifier like this:\nIdentifier = Word( alphanums + '_' , exact=7)\n\n",
"You can also parse the identifier and parameter as one token, and split them in a parse action:\nfrom pyparsing import *\nimport re\n\ndef split_ident_and_param(tokens):\n mo = re.match(r\"^(.*?_.*?)_(.*?_.*?)$\", tokens[0])\n return [mo.group(1), mo.group(2)]\n\nident_and_param = Word(alphanums + \"_\").setParseAction(split_ident_and_param)\nvalue = Word(nums)\nentry = ident_and_param + value\n\nprint entry.parseString(\"APC_123_SPEED_X 123\")\n\nThe example above assumes that the identifiers and parameters always have the format XXX_YYY (containing one single underscore).\nIf this is not the case, you need to adjust the split_ident_and_param() method.\n"
] |
[
7,
1,
1
] |
[
"This answers a question that you probably have also asked yourself: \"What's a real-world application for reduce?):\n>>> keys = ['CAT', 'DOG', 'HORSE', 'DEER', 'RHINOCEROS']\n>>> p = reduce(lambda x, y: x | y, [Keyword(x) for x in keys])\n>>> p\n{{{{\"CAT\" | \"DOG\"} | \"HORSE\"} | \"DEER\"} | \"RHINOCEROS\"}\n\nEdit:\nThis was a pretty good answer to the original question. I'll have to work on the new one.\nFurther edit:\nI'm pretty sure you can't do what you're trying to do. The parser that pyparsing creates doesn't do lookahead. So if you tell it to match Word(alphanums + '_'), it's going to keep matching characters until it finds one that's not a letter, number, or underscore.\n"
] |
[
-1
] |
[
"grammar",
"parsing",
"pyparsing",
"python"
] |
stackoverflow_0001905278_grammar_parsing_pyparsing_python.txt
|
Q:
split svnversion output in bash
I have this function, works fine, but I would like to rewrite it in bash. the problem is, I have too little knowledge of what's available in bash.
#!/usr/bin/python
def parse_svnversion(value):
"""split the output of svnversion into its three components
given a string that looks like the output of the command
svnversion, returns the 3-tuple (low, high, flags)
>>> parse_svnversion('1024')
(1024, 1024, '')
>>> parse_svnversion('1024:2000')
(1024, 2000, '')
>>> parse_svnversion('1024M')
(1024, 1024, 'M')
>>> parse_svnversion('1024:2000MP')
(1024, 2000, 'MP')
"""
values = filter(lambda x: x.isdigit() or x==':', value).split(':')
return int(values[0]), int(values[-1]), filter(str.isalpha, value)
if __name__ == '__main__':
import doctest
doctest.testmod()
what I would like is a similarly small bash function that I can invoke and that will set something (three variables? an array?) that I can use. if it's an array, I would really like it to be of fixed size (3).
A:
This creates an array called "tuple" with three elements:
[[ $(svnversion .) =~ ([0-9]+):*([0-9]*)([A-Z]*) ]]
tuple[0]=${BASH_REMATCH[1]}
tuple[1]=${BASH_REMATCH[2]:-${tuple[0]}}
tuple[2]=${BASH_REMATCH[3]:-''}
Requires Bash 3.2 or greater. It may work in Bash >= 3 and < 3.2. Not portable to the Bourne shell, although it can be adapted for the Korn shell or the Z shell.
ksh uses the .sh.match array variable, for example: ${.sh.match[1]}
zsh uses the match array variable, for example: ${match[1]} or you can do
setopt bashrematch ksharrays
to have it work with the Bash version exactly as above.
The brace substitutions should be the same for all three.
A:
you can use this subroutine
parsesvn(){
toparse="$1"
num=${toparse%%[A-Z]*}
alpha=${toparse##*[0-9]}
IFS=":"
set -- $num
for i in $@
do
printf "%s " $i
done
if [ ! -z "$alpha" ];then
printf "%s" "$alpha"
fi
}
# main #
var=$(parsesvn "1024:2000")
set -- $var
if [ "$1" -lt "$2" ];then
echo "ok"
greater=$2
else
echo "LHS: $1 greater than RHS: $2"
fi
echo "greater is $greater"
A:
The following solution stores the values into the array arr[ ] to match your original tuple as closely as possible. After the if-else-fi block you can do whatever you want with arr[0],arr[1], and arr[2]. I tried to match your post (and comment) as closely as possible. Also, I took the liberty to send the warning and notice messages to STDERR rather than STDOUT thinking you probably want to separate those.
#!/bin/bash
parse_svnversion()
{
if [[ "$1" = *:* ]]; then
arr[0]=${1%:*}
arr[2]=${1//[0-9:]/}
tmp_arr[1]=${1#*:}
arr[1]=${tmp_arr[1]//${arr[2]}/}
else
arr[2]=${1//[0-9:]/}
arr[0]=${1//${arr[2]}/}
arr[1]=${arr[0]}
fi
echo ${arr[@]}
head_rev=$( (( ${arr[0]} > ${arr[1]} )) && echo ${arr[0]} || echo ${arr[1]} )
echo "Notice: head revision is $head_rev" >&2
if (( ${arr[1]} < ${arr[0]} )); then
echo "Warning: you're working with mixed revisions" >&2
fi
if [[ -n ${arr[2]} ]]; then
echo "Warning: there are flags" >&2
fi
}
parse_svnversion "1024"
parse_svnversion "1024:2000"
parse_svnversion "1024M"
parse_svnversion "1024:2000MP"
parse_svnversion "2000:1024M"
Result without STDERR (sent to /dev/null)
$ ./svn_split.sh 2> /dev/null
1024 1024
1024 2000
1024 1024 M
1024 2000 MP
2000 1024 M
Result with STDERR
$ ./svn_split.sh
1024 1024
Notice: head revision is 1024
1024 2000
Notice: head revision is 2000
1024 1024 M
Notice: head revision is 1024
Warning: there are flags
1024 2000 MP
Notice: head revision is 2000
Warning: there are flags
2000 1024 M
Notice: head revision is 2000
Warning: you're working with mixed revisions
Warning: there are flags
|
split svnversion output in bash
|
I have this function, works fine, but I would like to rewrite it in bash. the problem is, I have too little knowledge of what's available in bash.
#!/usr/bin/python
def parse_svnversion(value):
"""split the output of svnversion into its three components
given a string that looks like the output of the command
svnversion, returns the 3-tuple (low, high, flags)
>>> parse_svnversion('1024')
(1024, 1024, '')
>>> parse_svnversion('1024:2000')
(1024, 2000, '')
>>> parse_svnversion('1024M')
(1024, 1024, 'M')
>>> parse_svnversion('1024:2000MP')
(1024, 2000, 'MP')
"""
values = filter(lambda x: x.isdigit() or x==':', value).split(':')
return int(values[0]), int(values[-1]), filter(str.isalpha, value)
if __name__ == '__main__':
import doctest
doctest.testmod()
what I would like is a similarly small bash function that I can invoke and that will set something (three variables? an array?) that I can use. if it's an array, I would really like it to be of fixed size (3).
|
[
"This creates an array called \"tuple\" with three elements:\n[[ $(svnversion .) =~ ([0-9]+):*([0-9]*)([A-Z]*) ]]\ntuple[0]=${BASH_REMATCH[1]}\ntuple[1]=${BASH_REMATCH[2]:-${tuple[0]}}\ntuple[2]=${BASH_REMATCH[3]:-''}\n\nRequires Bash 3.2 or greater. It may work in Bash >= 3 and < 3.2. Not portable to the Bourne shell, although it can be adapted for the Korn shell or the Z shell.\nksh uses the .sh.match array variable, for example: ${.sh.match[1]}\nzsh uses the match array variable, for example: ${match[1]} or you can do\nsetopt bashrematch ksharrays\n\nto have it work with the Bash version exactly as above.\nThe brace substitutions should be the same for all three.\n",
"you can use this subroutine\nparsesvn(){\n toparse=\"$1\"\n num=${toparse%%[A-Z]*}\n alpha=${toparse##*[0-9]}\n IFS=\":\"\n set -- $num\n for i in $@\n do\n printf \"%s \" $i\n done\n if [ ! -z \"$alpha\" ];then\n printf \"%s\" \"$alpha\"\n fi\n}\n\n# main #\nvar=$(parsesvn \"1024:2000\")\nset -- $var\nif [ \"$1\" -lt \"$2\" ];then\n echo \"ok\"\n greater=$2\nelse\n echo \"LHS: $1 greater than RHS: $2\"\nfi\necho \"greater is $greater\"\n\n",
"The following solution stores the values into the array arr[ ] to match your original tuple as closely as possible. After the if-else-fi block you can do whatever you want with arr[0],arr[1], and arr[2]. I tried to match your post (and comment) as closely as possible. Also, I took the liberty to send the warning and notice messages to STDERR rather than STDOUT thinking you probably want to separate those.\n#!/bin/bash\n\nparse_svnversion()\n{\n if [[ \"$1\" = *:* ]]; then\n arr[0]=${1%:*}\n arr[2]=${1//[0-9:]/}\n tmp_arr[1]=${1#*:}\n arr[1]=${tmp_arr[1]//${arr[2]}/}\n else\n arr[2]=${1//[0-9:]/}\n arr[0]=${1//${arr[2]}/}\n arr[1]=${arr[0]}\n fi\n\n echo ${arr[@]} \n\n head_rev=$( (( ${arr[0]} > ${arr[1]} )) && echo ${arr[0]} || echo ${arr[1]} )\n echo \"Notice: head revision is $head_rev\" >&2\n\n if (( ${arr[1]} < ${arr[0]} )); then\n echo \"Warning: you're working with mixed revisions\" >&2\n fi\n if [[ -n ${arr[2]} ]]; then\n echo \"Warning: there are flags\" >&2\n fi\n}\n\nparse_svnversion \"1024\"\nparse_svnversion \"1024:2000\"\nparse_svnversion \"1024M\"\nparse_svnversion \"1024:2000MP\"\nparse_svnversion \"2000:1024M\"\n\nResult without STDERR (sent to /dev/null)\n\n$ ./svn_split.sh 2> /dev/null\n1024 1024\n1024 2000\n1024 1024 M\n1024 2000 MP\n2000 1024 M\n\nResult with STDERR\n\n$ ./svn_split.sh\n1024 1024\nNotice: head revision is 1024\n1024 2000\nNotice: head revision is 2000\n1024 1024 M\nNotice: head revision is 1024\nWarning: there are flags\n1024 2000 MP\nNotice: head revision is 2000\nWarning: there are flags\n2000 1024 M\nNotice: head revision is 2000\nWarning: you're working with mixed revisions\nWarning: there are flags\n\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"bash",
"parsing",
"python"
] |
stackoverflow_0001905980_bash_parsing_python.txt
|
Q:
Django general template controled by which variables?
I have been developing some Django app and there's some duplicated code for different Models. I'd like to create a generic table template and pass the Model class, a list of model instances, and Form classes to it so it can render the page and generate the forms to add/delete elements. Then create some generic add/delete views to work with this Forms.
Which would be the correct part to define the configuration of the template for every different Model? Would it be right if I just create some class static variables and functions like:
class Test(models.Model):
# Model
name = models.CharField(max_length=20)
description = models.TextField(blank=True)
# Template configuration
title = "Test"
table_columns = ['name', ] # Columns I want to show in the table
def get_columns(self):
return [self.name, ]
Or is there some cleaner way to define this kind of things in Django?
EDIT: Seems like some of the information I want to use to configure the Template already has a name and should go inside model.Meta, like verbose_name or verbose_name_plural.
A:
I'm not exaclty sure about your question and your code, but here is a short story about _meta ...
To access the column name of a class, you can inspect the _meta attribute of the class.
Example. A sample model, which defines three fields and a helper methods whats_inside, which just iterates over _meta.fields and prints out the names of the columns of the class:
from django.db import models
def whats_inside(cls):
for item in cls._meta.fields:
print item.name
class Sample(models.Model):
name = models.CharField(max_length=80)
desc = models.CharField(max_length=80)
date_added = models.DateTimeField(auto_now=True, auto_now_add=True)
When we start ./manage shell, we can call whats_inside with Sample as argument (note: ms is just the package the model is located in this case, yours will differ):
$ ./manage.py shell
Python 2.6 (r26:66714, Oct 4 2008, 02:48:43)
Type "copyright", "credits" or "license" for more information.
IPython 0.9.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: from ms.models import Sample, whats_inside
In [2]: whats_inside(Sample)
id
name
desc
date_added
In [3]:
A:
As MYYN says, your question is not very clear. However i assume you would like to do the following:
Create a generic template
Dynamically load this template based on the model and other params passed
The table in the template is populated with the necessary forms etc
Create views, for the forms to submit to
I would use a custom template tag rather then including the code in your model (since its purely a presentation issue, i.e you would like all the fields available in the model but only display some of them). For example you could create a template tag which you call like:
{% gen_table somemodel %}
Documentation for template tags
Also read this great post on custom template tags and some of my sample code.
I also noticed you seem to be defining a custom method in your model class, however i believe the way to do this is by creating a custom model manager (read this blog post), also an example can be found here
|
Django general template controled by which variables?
|
I have been developing some Django app and there's some duplicated code for different Models. I'd like to create a generic table template and pass the Model class, a list of model instances, and Form classes to it so it can render the page and generate the forms to add/delete elements. Then create some generic add/delete views to work with this Forms.
Which would be the correct part to define the configuration of the template for every different Model? Would it be right if I just create some class static variables and functions like:
class Test(models.Model):
# Model
name = models.CharField(max_length=20)
description = models.TextField(blank=True)
# Template configuration
title = "Test"
table_columns = ['name', ] # Columns I want to show in the table
def get_columns(self):
return [self.name, ]
Or is there some cleaner way to define this kind of things in Django?
EDIT: Seems like some of the information I want to use to configure the Template already has a name and should go inside model.Meta, like verbose_name or verbose_name_plural.
|
[
"I'm not exaclty sure about your question and your code, but here is a short story about _meta ...\nTo access the column name of a class, you can inspect the _meta attribute of the class.\nExample. A sample model, which defines three fields and a helper methods whats_inside, which just iterates over _meta.fields and prints out the names of the columns of the class:\nfrom django.db import models\n\ndef whats_inside(cls):\n for item in cls._meta.fields:\n print item.name\n\nclass Sample(models.Model):\n\n name = models.CharField(max_length=80)\n desc = models.CharField(max_length=80)\n date_added = models.DateTimeField(auto_now=True, auto_now_add=True)\n\nWhen we start ./manage shell, we can call whats_inside with Sample as argument (note: ms is just the package the model is located in this case, yours will differ):\n$ ./manage.py shell \nPython 2.6 (r26:66714, Oct 4 2008, 02:48:43) \nType \"copyright\", \"credits\" or \"license\" for more information.\n\nIPython 0.9.1 -- An enhanced Interactive Python.\n? -> Introduction and overview of IPython's features.\n%quickref -> Quick reference.\nhelp -> Python's own help system.\nobject? -> Details about 'object'. ?object also works, ?? prints more.\n\nIn [1]: from ms.models import Sample, whats_inside\n\nIn [2]: whats_inside(Sample)\nid\nname\ndesc\ndate_added\n\nIn [3]: \n\n",
"As MYYN says, your question is not very clear. However i assume you would like to do the following:\n\nCreate a generic template\nDynamically load this template based on the model and other params passed\nThe table in the template is populated with the necessary forms etc \nCreate views, for the forms to submit to\n\nI would use a custom template tag rather then including the code in your model (since its purely a presentation issue, i.e you would like all the fields available in the model but only display some of them). For example you could create a template tag which you call like:\n{% gen_table somemodel %}\n\nDocumentation for template tags\nAlso read this great post on custom template tags and some of my sample code.\nI also noticed you seem to be defining a custom method in your model class, however i believe the way to do this is by creating a custom model manager (read this blog post), also an example can be found here\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"django_forms",
"django_templates",
"python"
] |
stackoverflow_0001906350_django_django_forms_django_templates_python.txt
|
Q:
In python, is there a setdefault() equivalent for getting object attributes?
Python's setdefault allows you to get a value from a dictionary, but if the key doesn't exist, then you assign the based on parameter default. You then fetch whatever is at the key in the dictionary.
Without manipulating an object's __dict__Is there a similar function for objects?
e.g.
I have an object foo which may or may not have attribute bar. How can I do something like:
result = setdefaultattr(foo,'bar','bah')
A:
Note that the currently accepted answer will, if the attribute doesn't exist already, have called hasattr(), setattr() and getattr(). This would be necessary only if the OP had done something like overriding setattr and/or getattr -- in which case the OP is not the innocent enquirer we took him for. Otherwise calling all 3 functions is gross; the setattr() call should be followed by return value so that it doesn't fall through to return getattr(....)
According to the docs, hasattr() is implemented by calling getattr() and catching exceptions. The following code may be faster when the attribute exists already:
def setdefaultattr(obj, name, value):
try:
return getattr(obj, name)
except AttributeError:
setattr(obj, name, value)
return value
A:
Python doesn't have one built in, but you can define your own:
def setdefaultattr(obj, name, value):
if not hasattr(obj, name):
setattr(obj, name, value)
return getattr(obj, name)
A:
vars(obj).setdefault(name, value)
|
In python, is there a setdefault() equivalent for getting object attributes?
|
Python's setdefault allows you to get a value from a dictionary, but if the key doesn't exist, then you assign the based on parameter default. You then fetch whatever is at the key in the dictionary.
Without manipulating an object's __dict__Is there a similar function for objects?
e.g.
I have an object foo which may or may not have attribute bar. How can I do something like:
result = setdefaultattr(foo,'bar','bah')
|
[
"Note that the currently accepted answer will, if the attribute doesn't exist already, have called hasattr(), setattr() and getattr(). This would be necessary only if the OP had done something like overriding setattr and/or getattr -- in which case the OP is not the innocent enquirer we took him for. Otherwise calling all 3 functions is gross; the setattr() call should be followed by return value so that it doesn't fall through to return getattr(....)\nAccording to the docs, hasattr() is implemented by calling getattr() and catching exceptions. The following code may be faster when the attribute exists already:\ndef setdefaultattr(obj, name, value):\n try:\n return getattr(obj, name)\n except AttributeError:\n setattr(obj, name, value)\n return value\n\n",
"Python doesn't have one built in, but you can define your own:\ndef setdefaultattr(obj, name, value):\n if not hasattr(obj, name):\n setattr(obj, name, value)\n return getattr(obj, name)\n\n",
"vars(obj).setdefault(name, value)\n\n"
] |
[
26,
9,
4
] |
[
"Don't Do This.\nPlease use __init__ to provide default values. That's the Pythonic way.\nclass Foo( object ):\n def __init__( self ):\n self.bar = 'bah'\n\nThis is the normal, standard, typical approach. There's no compelling reason to do otherwise.\n"
] |
[
-2
] |
[
"python"
] |
stackoverflow_0001904723_python.txt
|
Q:
python unbound method again
This gets me into difficult time (sorry, i am still very new to python)
Thank you for any kind of help.
The error
print Student.MostFrequent() TypeError: unbound method
MostFrequent() must be called with
Student instance as first argument
(got nothing instead)
This Student.MostFrequent() is called all the way in the end (last line) and the def is last def in the class
EDITED - Naming convention
My long code
import csv
class Student:
sports = []
ftopics = []
stopics = []
choice_list = []
choice_dict = {}
def __init__(self, row):
self.lname, self.fname, self.ID, self.gender, self.sport, self.movie, self.movieyr, self.country, self.ftopic, self.stopic = row
self.sports.append(self.sport)
self.ftopics.append(self.ftopic)
self.stopics.append(self.stopic)
def print_information(self):
return (self.lname, self.fname, self.ID, self.gender)
def print_first(self):
return (self.lname, self.fname, self.sport)
def print_second(self):
return (self.lname, self.fname, self.movie, self.movieyr)
def print_third(self):
return (self.lname, self.fname, self.country)
def print_fourth(self):
return (self.lname, self.fname, self.ftopic, self.stopic)
def most_frequent(self):
for choice in self.choice_list:
self.choice_dict[choice] = self.choice_dict.get(choice, 0) + 1
self.mostFrequent = sorted([(v, k) for k, v in self.choice_dict.items()], reverse=True)
print self.mostFrequent
reader = csv.reader(open('new_mondy_csc_data_revise.csv'), delimiter=',', quotechar='"')
header = tuple(reader.next())
print "%-17s|%-10s|%-6s|%s" %header[:4]
print "-" * 45
students = list(map(Student, reader)) # read all remaining lines
for student in students:
print "%-17s|%-10s|%-6s|%3s" % student.print_information()
print "%-17s|%-10s|%s" %(header[0],header[1],header[4])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_first()
print "%-17s|%-10s|%-16s|%s" %(header[0],header[1],header[5],header[6])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_second()
print "%-17s|%-10s|%s" %(header[0],header[1],header[7])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_third()
print "%-17s|%-10s|%-15s|%s" %(header[0],header[1],header[8],header[9])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_fourth()
k = len(students)
# Printing all sports that are specified by students
for s in set(Student.sports): # class attribute
print s, Student.sports.count(s), round(((float(Student.sports.count(s)) / k) *100),1)
# Printing sports that are not picked
allsports = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
allsports.sort()
for s in set(allsports) - set(Student.sports):
print s, 0, '0%'
Student.choice_list = Student.sports
X = Student()
X.most_frequent()
#class Search(Student):
# def __init__(self):
# Student.__init__
A:
use Student().MostFrequent()
edit:
beware that you use class attributes and this is dangerous. here an example:
>>> class Person:
... name = None
... hobbies = []
... def __init__(self, name):
... self.name = name
...
>>> a = Person('marco')
>>> b = Person('francesco')
>>> a.hobbies.append('football')
>>> b.hobbies
['football']
>>> a.name
'marco'
>>> b.name
'francesco'
>>> a.name = 'mario'
>>> b.name
'francesco'
>>> a.name
'mario'
>>>
as you can see i modify marco's hobbies and francesco's hobbies are modified consequentially.
A:
first read PEP-8 on naming conventions:
Method Names and Instance Variables
Use the function naming rules: lowercase with words separated by
underscores as necessary to improve readability.
second you are calling mostFrequest on the class Student, not an instance of it. Use the method on an instance instead:
student = Student(row)
student.MostFrequent()
A:
What you probably want is to define most_frequent as a classmethod:
@classmethod
def most_frequent(cls):
for choice in cls.choice_list:
cls.choice_dict[choice] = cls.choice_dict.get(choice, 0) + 1
cls.mostFrequent = sorted([(v, k) for k, v in cls.choice_dict.items()], reverse=True)
return cls.mostFrequent
A:
First, I recommend making function names lower case only.
The error you get results from the usage of MostFrequent as a static method. For this to work, you need to explicitly pass an instance of Student as first argument.
If called directly on an instance of Student, the instance will implicitly be passed as first argument.
Consider using the staticmethod decorator for static usage of functions.
A:
You only rarely call methods on a class definition (Student)
Almost always, you create an instance of the class
someStudent = Student(someRow)
Then you call the method on the instance ("object"), someStudent.
someStudent.MostFrequent()
A:
Student.MostFrequent means You're trying to use static method, not instance method. So You must first create instance by calling Student() and then call MostFrequent() on it.
P.S.: If this is not part of some arcane project, I urge you to follow PEP 8 and use most_frequent as method name.
|
python unbound method again
|
This gets me into difficult time (sorry, i am still very new to python)
Thank you for any kind of help.
The error
print Student.MostFrequent() TypeError: unbound method
MostFrequent() must be called with
Student instance as first argument
(got nothing instead)
This Student.MostFrequent() is called all the way in the end (last line) and the def is last def in the class
EDITED - Naming convention
My long code
import csv
class Student:
sports = []
ftopics = []
stopics = []
choice_list = []
choice_dict = {}
def __init__(self, row):
self.lname, self.fname, self.ID, self.gender, self.sport, self.movie, self.movieyr, self.country, self.ftopic, self.stopic = row
self.sports.append(self.sport)
self.ftopics.append(self.ftopic)
self.stopics.append(self.stopic)
def print_information(self):
return (self.lname, self.fname, self.ID, self.gender)
def print_first(self):
return (self.lname, self.fname, self.sport)
def print_second(self):
return (self.lname, self.fname, self.movie, self.movieyr)
def print_third(self):
return (self.lname, self.fname, self.country)
def print_fourth(self):
return (self.lname, self.fname, self.ftopic, self.stopic)
def most_frequent(self):
for choice in self.choice_list:
self.choice_dict[choice] = self.choice_dict.get(choice, 0) + 1
self.mostFrequent = sorted([(v, k) for k, v in self.choice_dict.items()], reverse=True)
print self.mostFrequent
reader = csv.reader(open('new_mondy_csc_data_revise.csv'), delimiter=',', quotechar='"')
header = tuple(reader.next())
print "%-17s|%-10s|%-6s|%s" %header[:4]
print "-" * 45
students = list(map(Student, reader)) # read all remaining lines
for student in students:
print "%-17s|%-10s|%-6s|%3s" % student.print_information()
print "%-17s|%-10s|%s" %(header[0],header[1],header[4])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_first()
print "%-17s|%-10s|%-16s|%s" %(header[0],header[1],header[5],header[6])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_second()
print "%-17s|%-10s|%s" %(header[0],header[1],header[7])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_third()
print "%-17s|%-10s|%-15s|%s" %(header[0],header[1],header[8],header[9])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_fourth()
k = len(students)
# Printing all sports that are specified by students
for s in set(Student.sports): # class attribute
print s, Student.sports.count(s), round(((float(Student.sports.count(s)) / k) *100),1)
# Printing sports that are not picked
allsports = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
allsports.sort()
for s in set(allsports) - set(Student.sports):
print s, 0, '0%'
Student.choice_list = Student.sports
X = Student()
X.most_frequent()
#class Search(Student):
# def __init__(self):
# Student.__init__
|
[
"use Student().MostFrequent()\nedit:\nbeware that you use class attributes and this is dangerous. here an example:\n>>> class Person:\n... name = None\n... hobbies = []\n... def __init__(self, name):\n... self.name = name\n... \n>>> a = Person('marco')\n>>> b = Person('francesco')\n>>> a.hobbies.append('football')\n>>> b.hobbies\n['football']\n>>> a.name\n'marco'\n>>> b.name\n'francesco'\n>>> a.name = 'mario'\n>>> b.name\n'francesco'\n>>> a.name\n'mario'\n>>> \n\nas you can see i modify marco's hobbies and francesco's hobbies are modified consequentially.\n",
"first read PEP-8 on naming conventions:\n\nMethod Names and Instance Variables\n\n Use the function naming rules: lowercase with words separated by\n underscores as necessary to improve readability.\n\nsecond you are calling mostFrequest on the class Student, not an instance of it. Use the method on an instance instead:\nstudent = Student(row)\nstudent.MostFrequent()\n\n",
"What you probably want is to define most_frequent as a classmethod:\n@classmethod\ndef most_frequent(cls):\n for choice in cls.choice_list:\n cls.choice_dict[choice] = cls.choice_dict.get(choice, 0) + 1\n cls.mostFrequent = sorted([(v, k) for k, v in cls.choice_dict.items()], reverse=True)\n return cls.mostFrequent\n\n",
"First, I recommend making function names lower case only.\nThe error you get results from the usage of MostFrequent as a static method. For this to work, you need to explicitly pass an instance of Student as first argument.\nIf called directly on an instance of Student, the instance will implicitly be passed as first argument.\nConsider using the staticmethod decorator for static usage of functions.\n",
"You only rarely call methods on a class definition (Student)\nAlmost always, you create an instance of the class\nsomeStudent = Student(someRow)\n\nThen you call the method on the instance (\"object\"), someStudent.\nsomeStudent.MostFrequent()\n\n",
"Student.MostFrequent means You're trying to use static method, not instance method. So You must first create instance by calling Student() and then call MostFrequent() on it.\nP.S.: If this is not part of some arcane project, I urge you to follow PEP 8 and use most_frequent as method name.\n"
] |
[
7,
7,
2,
1,
0,
0
] |
[
"in your class def, the method definition \ndef MostFrequent(self,mostFrequent):\n\nhas the extra variable mostFrequent that you probably don't want there. Try changing to :\ndef MostFrequent(self):\n\n"
] |
[
-1
] |
[
"class",
"python"
] |
stackoverflow_0001906926_class_python.txt
|
Q:
How to connect an application with Facebook?
The topic may be a bit ambiguous.
I am writing a Python application. I want to upload it on Facebook as a Facebook application (NOT Facebook Connect).
But I am having the hardest time figuring out how to implement the features of my application with Facebook.
My application currently uses a MySQL database. Now I want a user of Facebook to use my application and store the results in his/her account. How do I do it? I am afraid to say it but I am a bit scared of all the documentations. So if someone could give me some pointers, I would really really appreciate it.
A:
There is a good Facebook library that supports Django, pyfacebook. There are some examples in that package of how to use it.
And there's no substitute for the actual Facebook developer documentation - it's written with PHP in mind, but you can use the same API calls via the Python library.
However we can't really give you an entire tutorial via StackOverflow. If you have any specific questions, please ask them.
A:
Amit, in addition to the links above also have a look at the following links. Also note: You mention you would like to 'upload your app into facebook' you can add your app to facebook, however they DO NOT host it. You will have to host the application on your own server.
http://uswaretech.com/blog/2009/02/how-to-build-a-facebook-app-in-django/
http://lethain.com/entry/2007/dec/04/two-faced-django-part-1-building-project-exists-si/
|
How to connect an application with Facebook?
|
The topic may be a bit ambiguous.
I am writing a Python application. I want to upload it on Facebook as a Facebook application (NOT Facebook Connect).
But I am having the hardest time figuring out how to implement the features of my application with Facebook.
My application currently uses a MySQL database. Now I want a user of Facebook to use my application and store the results in his/her account. How do I do it? I am afraid to say it but I am a bit scared of all the documentations. So if someone could give me some pointers, I would really really appreciate it.
|
[
"There is a good Facebook library that supports Django, pyfacebook. There are some examples in that package of how to use it.\nAnd there's no substitute for the actual Facebook developer documentation - it's written with PHP in mind, but you can use the same API calls via the Python library.\nHowever we can't really give you an entire tutorial via StackOverflow. If you have any specific questions, please ask them.\n",
"Amit, in addition to the links above also have a look at the following links. Also note: You mention you would like to 'upload your app into facebook' you can add your app to facebook, however they DO NOT host it. You will have to host the application on your own server.\n\nhttp://uswaretech.com/blog/2009/02/how-to-build-a-facebook-app-in-django/\nhttp://lethain.com/entry/2007/dec/04/two-faced-django-part-1-building-project-exists-si/\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"django",
"facebook",
"facebook_fql",
"python"
] |
stackoverflow_0001906184_django_facebook_facebook_fql_python.txt
|
Q:
How can I express base class method calling derived virtual?
what's the way to do in python the following in C++?
B* b = new D();
b->virtual_fn();
Which would call virtual_fn in D. Are there a form of references to do this?
A:
Effectively, all instance methods in Python are virtual and types are inferred. For example, this works:
class Vehicle:
def __init__(self, lp):
self.license_plate = lp
def alert(self):
raise NotImplementedError("Must implement this!")
class Boat(Vehicle):
def alert(self):
print "honk, honk!"
class Car(Vehicle):
def alert(self):
print "meep meep!"
class FireEngine(Vehicle):
def alert(self):
print "woo woo!"
vehicles = [Boat('!'), Car('ADJ-4891'), FireEngine('FRM-1498')]
for v in vehicles:
print v.license_plate + ': ' + v.alert()
# prints:
# !: honk, honk!
# ADJ-4891: meep meep!
# FRM-1498: woo woo!
A:
In Python, values have types not variables. The latter are simply useful names for the values that they are currently bound to. Since variables do not have types, if you create a D object and bind a variable to it, then you get the methods explicitly defined by the D class and any in the B class that have not been replaced. Effectively, everything is virtual.
Now if you want to call a method in B that has been replaced in D, you have to call the method and pass self explicitly. Here's an example with id() doctored to protect the innocent.
>>> class B(object):
... def virtual_fn(self):
... print 'in B.virtual_fn() for', id(self)
... def other_virtual_fn(self):
... print 'in B.other_virtual_fn() for', id(self)
... def call_virtual(self):
... print 'in B.call_virtual() for', id(self)
...
>>> class D(B):
... def virtual_fn(self):
... print 'in D.virtual_fn() for', id(self)
...
>>> b_obj = B()
>>> d_obj = D()
>>> id(b_obj)
1
>>> id(d_obj)
2
>>>
>>> b_obj.virtual_fn()
in B.virtual_fn() for 1
>>> d_obj.virtual_fn()
in D.virtual_fn() for 2
>>> d_obj.other_virtual_fn()
in B.other_virtual_fn() for 2
>>>
>>> B.virtual_fn(d_obj)
in B.virtual_fn() for 2
>>>
>>> d_obj.call_virtual()
in B.call_virtual() for 2
in D.virtual_fn() for 2
>>>
Remember that d_obj.virtual_fn() is essentially syntactical sugar for D.virtual_fn(d_obj). So if you want to explicitly call a hidden method of a base class, you do so without the sugar - B.virtual_fn(d_obj). I would highly recommend reading the Method Resolution Order (mro) document from Python 2.3. It really explains how all of this works rather well.
Edit
After reading the question again, I added the call_virtual stuff since I'm pretty sure that this is what you are interested in.
|
How can I express base class method calling derived virtual?
|
what's the way to do in python the following in C++?
B* b = new D();
b->virtual_fn();
Which would call virtual_fn in D. Are there a form of references to do this?
|
[
"Effectively, all instance methods in Python are virtual and types are inferred. For example, this works:\nclass Vehicle:\n def __init__(self, lp):\n self.license_plate = lp\n def alert(self):\n raise NotImplementedError(\"Must implement this!\")\n\nclass Boat(Vehicle):\n def alert(self):\n print \"honk, honk!\"\n\nclass Car(Vehicle):\n def alert(self):\n print \"meep meep!\"\n\nclass FireEngine(Vehicle):\n def alert(self):\n print \"woo woo!\"\n\nvehicles = [Boat('!'), Car('ADJ-4891'), FireEngine('FRM-1498')]\n\nfor v in vehicles:\n print v.license_plate + ': ' + v.alert()\n\n# prints:\n# !: honk, honk!\n# ADJ-4891: meep meep!\n# FRM-1498: woo woo!\n\n",
"In Python, values have types not variables. The latter are simply useful names for the values that they are currently bound to. Since variables do not have types, if you create a D object and bind a variable to it, then you get the methods explicitly defined by the D class and any in the B class that have not been replaced. Effectively, everything is virtual.\nNow if you want to call a method in B that has been replaced in D, you have to call the method and pass self explicitly. Here's an example with id() doctored to protect the innocent.\n>>> class B(object):\n... def virtual_fn(self):\n... print 'in B.virtual_fn() for', id(self)\n... def other_virtual_fn(self):\n... print 'in B.other_virtual_fn() for', id(self)\n... def call_virtual(self):\n... print 'in B.call_virtual() for', id(self)\n... \n>>> class D(B):\n... def virtual_fn(self):\n... print 'in D.virtual_fn() for', id(self)\n... \n>>> b_obj = B()\n>>> d_obj = D()\n>>> id(b_obj)\n1\n>>> id(d_obj)\n2\n>>>\n>>> b_obj.virtual_fn()\nin B.virtual_fn() for 1\n>>> d_obj.virtual_fn()\nin D.virtual_fn() for 2\n>>> d_obj.other_virtual_fn()\nin B.other_virtual_fn() for 2\n>>>\n>>> B.virtual_fn(d_obj)\nin B.virtual_fn() for 2\n>>>\n>>> d_obj.call_virtual()\nin B.call_virtual() for 2\nin D.virtual_fn() for 2\n>>>\n\nRemember that d_obj.virtual_fn() is essentially syntactical sugar for D.virtual_fn(d_obj). So if you want to explicitly call a hidden method of a base class, you do so without the sugar - B.virtual_fn(d_obj). I would highly recommend reading the Method Resolution Order (mro) document from Python 2.3. It really explains how all of this works rather well.\nEdit\nAfter reading the question again, I added the call_virtual stuff since I'm pretty sure that this is what you are interested in.\n"
] |
[
2,
2
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0001907182_oop_python.txt
|
Q:
nested looping in python
in a string suppose 12345 , i want to take nested loops , so that i would be able to iterate through the string in this following way :-
1, 2, 3, 4, 5 would be taken as integers
12, 3, 4,5 as integers
1, 23, 4, 5 as integers
1, 2, 34, 5 as integers
...
And so on. I know what's the logic but being a noob in Python, I'm not able to form the loop.
A:
This smells a bit like homework.
Try writing down the successive outputs, one per line, and look for a pattern. See if you can explain that pattern with slices of the input string. Then look for a numeric pattern to the slicing.
Also, please edit your question to put quotes around your strings. What you've written isn't very clear in terms of the outputs, whether you output strings with commas or lists of substrings.
A:
You can do the inner traversals by following code, the first traversal is trivial.
s = '12345'
chars = [c for c in s]
for i in range(len(s) - 1):
print '%d:' % i,
for el in chars[:i] + [chars[i] + chars[i + 1]] + chars[i + 2:]:
print el,
print
A:
number = 12345
str_number = str(number)
output = []
for index, part in enumerate(str_number[:-1]):
output_part = []
for second_index, second_part in enumerate(str_number):
if index == second_index:
continue
elif index == second_index - 1:
output_part.append(int(part + second_part))
else:
output_part.append(int(second_part))
output.append(output_part)
print output
STick it inside a function definition and put an "yield output_part" in place of the "output.append" line to get a usefull interator.
|
nested looping in python
|
in a string suppose 12345 , i want to take nested loops , so that i would be able to iterate through the string in this following way :-
1, 2, 3, 4, 5 would be taken as integers
12, 3, 4,5 as integers
1, 23, 4, 5 as integers
1, 2, 34, 5 as integers
...
And so on. I know what's the logic but being a noob in Python, I'm not able to form the loop.
|
[
"This smells a bit like homework.\nTry writing down the successive outputs, one per line, and look for a pattern. See if you can explain that pattern with slices of the input string. Then look for a numeric pattern to the slicing.\nAlso, please edit your question to put quotes around your strings. What you've written isn't very clear in terms of the outputs, whether you output strings with commas or lists of substrings.\n",
"You can do the inner traversals by following code, the first traversal is trivial.\ns = '12345'\n\nchars = [c for c in s]\n\nfor i in range(len(s) - 1):\n print '%d:' % i,\n for el in chars[:i] + [chars[i] + chars[i + 1]] + chars[i + 2:]:\n print el,\n print\n\n",
"number = 12345\n\nstr_number = str(number)\n\noutput = []\nfor index, part in enumerate(str_number[:-1]):\n output_part = []\n for second_index, second_part in enumerate(str_number):\n if index == second_index:\n continue\n elif index == second_index - 1:\n output_part.append(int(part + second_part))\n else:\n output_part.append(int(second_part))\n output.append(output_part)\n\nprint output\n\nSTick it inside a function definition and put an \"yield output_part\" in place of the \"output.append\" line to get a usefull interator.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001907519_python.txt
|
Q:
python http handler
I want something like BaseHTTPRequestHandler, except that I don't want it to bind to any sockets; I want to handle the raw HTTP data to and from it myself. Is there a good way that I can do this in Python?
To Clarify, I want a class that receives raw TCP data from Python (NOT a socket), processes it and returns TCP data as a response (to python again). So this class will handle TCP handshaking, and will have methods that override what I send on HTTP GET and POST, like do_GET and do_POST. So, I want something like the Server infrastructure that already exists, except I want to pass all raw TCP packets in python and not through operating system sockets.
A:
BaseHTTPRequestHandler derives from StreamRequestHandler, which basically reads from file self.rfile and writes to self.wfile, so you can derive a class from BaseHTTPRequestHandler and supply your own rfile and wfile e.g.
import StringIO
from BaseHTTPServer import BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def __init__(self, inText, outFile):
self.rfile = StringIO.StringIO(inText)
self.wfile = outFile
BaseHTTPRequestHandler.__init__(self, "", "", "")
def setup(self):
pass
def handle(self):
BaseHTTPRequestHandler.handle(self)
def finish(self):
BaseHTTPRequestHandler.finish(self)
def address_string(self):
return "dummy_server"
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("<html><head><title>WoW</title></head>")
self.wfile.write("<body><p>This is a Total Wowness</p>")
self.wfile.write("</body></html>")
outFile = StringIO.StringIO()
handler = MyHandler("GET /wow HTTP/1.1", outFile)
print ''.join(outFile.buflist)
Output:
dummy_server - - [15/Dec/2009 19:22:24] "GET /wow HTTP/1.1" 200 -
HTTP/1.0 200 OK
Server: BaseHTTP/0.3 Python/2.5.1
Date: Tue, 15 Dec 2009 13:52:24 GMT
Content-type: text/html
<html><head><title>WoW</title></head><body><p>This is a Total Wowness</p></body></html>
|
python http handler
|
I want something like BaseHTTPRequestHandler, except that I don't want it to bind to any sockets; I want to handle the raw HTTP data to and from it myself. Is there a good way that I can do this in Python?
To Clarify, I want a class that receives raw TCP data from Python (NOT a socket), processes it and returns TCP data as a response (to python again). So this class will handle TCP handshaking, and will have methods that override what I send on HTTP GET and POST, like do_GET and do_POST. So, I want something like the Server infrastructure that already exists, except I want to pass all raw TCP packets in python and not through operating system sockets.
|
[
"BaseHTTPRequestHandler derives from StreamRequestHandler, which basically reads from file self.rfile and writes to self.wfile, so you can derive a class from BaseHTTPRequestHandler and supply your own rfile and wfile e.g.\nimport StringIO\nfrom BaseHTTPServer import BaseHTTPRequestHandler\n\nclass MyHandler(BaseHTTPRequestHandler):\n\n def __init__(self, inText, outFile):\n self.rfile = StringIO.StringIO(inText)\n self.wfile = outFile\n BaseHTTPRequestHandler.__init__(self, \"\", \"\", \"\")\n\n def setup(self):\n pass\n\n def handle(self):\n BaseHTTPRequestHandler.handle(self)\n\n def finish(self):\n BaseHTTPRequestHandler.finish(self)\n\n def address_string(self):\n return \"dummy_server\"\n\n def do_GET(self):\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n self.wfile.write(\"<html><head><title>WoW</title></head>\")\n self.wfile.write(\"<body><p>This is a Total Wowness</p>\")\n self.wfile.write(\"</body></html>\")\n\noutFile = StringIO.StringIO()\n\nhandler = MyHandler(\"GET /wow HTTP/1.1\", outFile)\nprint ''.join(outFile.buflist)\n\nOutput:\ndummy_server - - [15/Dec/2009 19:22:24] \"GET /wow HTTP/1.1\" 200 -\nHTTP/1.0 200 OK\nServer: BaseHTTP/0.3 Python/2.5.1\nDate: Tue, 15 Dec 2009 13:52:24 GMT\nContent-type: text/html\n\n<html><head><title>WoW</title></head><body><p>This is a Total Wowness</p></body></html>\n\n"
] |
[
3
] |
[] |
[] |
[
"handler",
"http",
"python",
"request"
] |
stackoverflow_0001907071_handler_http_python_request.txt
|
Q:
python raw_input def input problem
I am only going to post the portion where the problem is at, the program has no error (all the codes are valid except for this raw_input problem)
I tested with search_function(1) and etc and it worked.
But if I do this while loop, it doesn't print anything.
Example output:
Enter a number to print specific table,
or STOP to quit: 2 Enter a number to
print specific table, or STOP to quit:
2 Enter a number to print specific
table, or STOP to quit: 1 Enter a
number to print specific table, or STOP
to quit: Enter a number to print
specific table, or STOP to quit: 1
Enter a number to print specific table,
or STOP to quit: Enter a number to
print specific table, or STOP to quit:
STOP
def search_function(x):
if x == 1:
for student in students:
print "%-17s|%-10s|%-6s|%3s" % student.print_information()
print '\n'
if x == 2:
print "%-17s|%-10s|%s" %(header[0],header[1],header[4])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_first()
print '\n'
print "Simple Analysis on favorite sports: "
# Printing all sports that are specified by students
for s in set(Student.sports): # class attribute
print s, Student.sports.count(s), round(((float(Student.sports.count(s)) / num_students) *100),1)
# Printing sports that are not picked
allsports = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
for s in set(allsports) - set(Student.sports):
print s, 0, '0%'
choice_list = Student.sports
for choice in choice_list:
choice_dict[choice] = choice_dict.get(choice, 0) + 1
print max(choice_dict)
print min(choice_dict)
elif x == 3:
print "%-17|%-10s|%-16s|%s" %(header[0],header[1],header[5],header[6])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_second()
print '\n'
elif x == 4:
print "%-17s|%-10s|%s" %(header[0],header[1],header[7])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_third()
print '\n'
elif x == 5:
print "%-17s|%-10s|%-15s|%s" %(header[0],header[1],header[8],header[9])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_fourth()
print '\n'
x = raw_input("Enter a number to print specific table, or STOP to quit: ")
while x != 'STOP':
search_function(x)
x = raw_input("Enter a number to print specific table, or STOP to quit: ")
A:
raw_input() returns string, while your code expects integer. Use search_function(int(x)) or change conditions to compare with strings.
A:
Test for x == 'STOP' first and break if True, else cast to int and call search_function:
while True:
x = raw_input("Enter a number to print specific table, or STOP to quit: ")
if x == 'STOP':
break
search_function(int(x))
|
python raw_input def input problem
|
I am only going to post the portion where the problem is at, the program has no error (all the codes are valid except for this raw_input problem)
I tested with search_function(1) and etc and it worked.
But if I do this while loop, it doesn't print anything.
Example output:
Enter a number to print specific table,
or STOP to quit: 2 Enter a number to
print specific table, or STOP to quit:
2 Enter a number to print specific
table, or STOP to quit: 1 Enter a
number to print specific table, or STOP
to quit: Enter a number to print
specific table, or STOP to quit: 1
Enter a number to print specific table,
or STOP to quit: Enter a number to
print specific table, or STOP to quit:
STOP
def search_function(x):
if x == 1:
for student in students:
print "%-17s|%-10s|%-6s|%3s" % student.print_information()
print '\n'
if x == 2:
print "%-17s|%-10s|%s" %(header[0],header[1],header[4])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_first()
print '\n'
print "Simple Analysis on favorite sports: "
# Printing all sports that are specified by students
for s in set(Student.sports): # class attribute
print s, Student.sports.count(s), round(((float(Student.sports.count(s)) / num_students) *100),1)
# Printing sports that are not picked
allsports = ['Basketball','Football','Other','Baseball','Handball','Soccer','Volleyball','I do not like sport']
for s in set(allsports) - set(Student.sports):
print s, 0, '0%'
choice_list = Student.sports
for choice in choice_list:
choice_dict[choice] = choice_dict.get(choice, 0) + 1
print max(choice_dict)
print min(choice_dict)
elif x == 3:
print "%-17|%-10s|%-16s|%s" %(header[0],header[1],header[5],header[6])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_second()
print '\n'
elif x == 4:
print "%-17s|%-10s|%s" %(header[0],header[1],header[7])
print "-" * 45
for student in students:
print "%-17s|%-10s|%s" %student.print_third()
print '\n'
elif x == 5:
print "%-17s|%-10s|%-15s|%s" %(header[0],header[1],header[8],header[9])
print "-" * 45
for student in students:
print "%-17s|%-10s|%-16s|%s" % student.print_fourth()
print '\n'
x = raw_input("Enter a number to print specific table, or STOP to quit: ")
while x != 'STOP':
search_function(x)
x = raw_input("Enter a number to print specific table, or STOP to quit: ")
|
[
"raw_input() returns string, while your code expects integer. Use search_function(int(x)) or change conditions to compare with strings.\n",
"Test for x == 'STOP' first and break if True, else cast to int and call search_function:\nwhile True:\n x = raw_input(\"Enter a number to print specific table, or STOP to quit: \")\n if x == 'STOP':\n break\n search_function(int(x))\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"input",
"python"
] |
stackoverflow_0001907647_input_python.txt
|
Q:
Framework for building visually rich desktop applications?
I've started building an app with Flex/Air but am getting sick of it's clunkyness.
The app that I'm building has similar behaviour to Prezi (www.prezi.com) but in a completely different field.
I'm looking for something on the desktop which has flex like capabilities, such as drawing vectors then zooming in/out, rotating etc, gui widgets would be a bonus but not essential.
If it was written in Python/Ruby or had an abstraction in either language that would be great.
I've had a quick look at PyGame and Pyglet but am not sure of their suitability.
Any ideas?
Cheers,
Chris
A:
Qt (Python bindings: PyQt) is a flexible and mature framework that can certainly do that (take a look at QGraphicsView and QGraphicsScene for example).
You'll have to code most of it 'by hand' though (the designer is good for standard GUI widgets but is lacking functionality in this particular area).
A:
If you have any .NET experience I would recommend Silverlight. I have worked with it in the academic setting and it has impressed me very much. Some of the examples are pretty mind blowing, for the web applications at least. I also know they did focus on making silverlight into exactly what your question asks, a framework for building "visually rich" desktop applications also. There is a set of tools called expression blend that interact directly with visual studio to build the GUI and it's pretty impressive the control their GUI gives you in making your GUI. At least worth a look.
|
Framework for building visually rich desktop applications?
|
I've started building an app with Flex/Air but am getting sick of it's clunkyness.
The app that I'm building has similar behaviour to Prezi (www.prezi.com) but in a completely different field.
I'm looking for something on the desktop which has flex like capabilities, such as drawing vectors then zooming in/out, rotating etc, gui widgets would be a bonus but not essential.
If it was written in Python/Ruby or had an abstraction in either language that would be great.
I've had a quick look at PyGame and Pyglet but am not sure of their suitability.
Any ideas?
Cheers,
Chris
|
[
"Qt (Python bindings: PyQt) is a flexible and mature framework that can certainly do that (take a look at QGraphicsView and QGraphicsScene for example). \nYou'll have to code most of it 'by hand' though (the designer is good for standard GUI widgets but is lacking functionality in this particular area).\n",
"If you have any .NET experience I would recommend Silverlight. I have worked with it in the academic setting and it has impressed me very much. Some of the examples are pretty mind blowing, for the web applications at least. I also know they did focus on making silverlight into exactly what your question asks, a framework for building \"visually rich\" desktop applications also. There is a set of tools called expression blend that interact directly with visual studio to build the GUI and it's pretty impressive the control their GUI gives you in making your GUI. At least worth a look.\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"svg",
"vector"
] |
stackoverflow_0001907736_python_svg_vector.txt
|
Q:
Whether to simplify two stage regular expression?
I'm newbie in Python, but this question is not a homework (actually this code helps to generate RSS on my Subversion server).
I have an array of strings in the info_lines variable. And I want to replace each occurrence of the bug ID. My current code looks like the following:
for ln in range(3, len(info_lines)): # skip two strings since there are author&date info
if re.search( r'(?:BUG|FIX):(?:[ ,]*(\d+))+', info_lines[ln] ):
info_lines[ln] = re.sub( r'(\d+)+', r'<a href="http://bugzilla.mycompany.com/show_bug.cgi?id=\1">\1</a>', info_lines[ln] )
formatted_lines = "<br/>".join( info_lines[3:] )
It should replace the following text:
STABLE
FIX: some bug fixed
FIX: 10, 24, 3355
FIX: error 1024 was fixed
with this one:
STABLE
FIX: some bug fixed
FIX: <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=10">10</a>, <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=24">24</a>, <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=3355">3355</a>
FIX: error 1024 was fixed
Notice that 1024 shouldn't be replaced with the link.
My current code do the job, but I interested whether it could be simplified, optimized, etc. May be it could be replaced with only one replacement regular expression? Or it could be replaced with one magic Python function from known libraries?
A:
No, there's not much of a better way to do it. The replacement code messes up the case where there are bug numbers and other numbers on the same line, but even so, you're not getting away from two res because you want support for a comma-separated bug list.
import re
info_lines = [
"Me",
"now",
"STABLE",
"FIX: some bug fixed",
"FIX: 10, 24, 3355",
"FIX: error 1024 was fixed",
"FIX: 15 (dupe of BUG:25) fixed crash on x = 250."
]
linkText = r'<a href="http://bugzilla.mycompany.com/show_bug.cgi?id=\1">\1</a>'
bugSearch = re.compile(r'(?:BUG|FIX):(?:[ ,]*(\d+))+')
bugMatch = re.compile(r'(\d+)')
for k, ln in enumerate(info_lines[3:]):
while True:
m = bugSearch.search(ln)
if m:
ln = ln[:m.start()] + bugMatch.sub(linkText, m.group()) + ln[m.end():]
else:
break
info_lines[k+3] = ln
for ln in info_lines:
print ln
Output:
Me
now
STABLE
FIX: some bug fixed
FIX: <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=10">10</a>, <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=24">24</a>, <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=3355">3355</a>
FIX: error 1024 was fixed
FIX: <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=15">15</a> (dupe of BUG:<a href="http://bugzilla.mycompany.com/show_bug.cgi?id=25">25</a>) fixed crash on x = 250.
If you required every bug number to be prefixed with "FIX:" or "BUG:", then things get much simpler:
linkText = r'\1<a href="http://bugzilla.mycompany.com/show_bug.cgi?id=\2">\2</a>'
bugSearch = re.compile(r'((?:BUG|FIX):(?: )?)(\d+)')
info_lines[3:] = [bugSearch.sub(linkText, ln) for ln in info_lines[3:]]
for ln in info_lines:
print ln
Output:
Me
now
STABLE
FIX: some bug fixed
FIX: <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=10">10</a>, 24, 3355
FIX: error 1024 was fixed
FIX: <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=15">15</a> (dupe of BUG:<a href="http://bugzilla.mycompany.com/show_bug.cgi?id=25">25</a>) fixed crash on x = 250.
A:
I would say that it's fine as-is, although I personally would prefer different syntax for bug numbers. I would differentiate them from bare numbers by either having "bug 144", "issue 196" or just "#153". That means they can then be embedded in a longer message, to provide clearer context. This is especially helpful in cases like "Preliminary work for bug 355" or "Finishing clearup from #1293".
|
Whether to simplify two stage regular expression?
|
I'm newbie in Python, but this question is not a homework (actually this code helps to generate RSS on my Subversion server).
I have an array of strings in the info_lines variable. And I want to replace each occurrence of the bug ID. My current code looks like the following:
for ln in range(3, len(info_lines)): # skip two strings since there are author&date info
if re.search( r'(?:BUG|FIX):(?:[ ,]*(\d+))+', info_lines[ln] ):
info_lines[ln] = re.sub( r'(\d+)+', r'<a href="http://bugzilla.mycompany.com/show_bug.cgi?id=\1">\1</a>', info_lines[ln] )
formatted_lines = "<br/>".join( info_lines[3:] )
It should replace the following text:
STABLE
FIX: some bug fixed
FIX: 10, 24, 3355
FIX: error 1024 was fixed
with this one:
STABLE
FIX: some bug fixed
FIX: <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=10">10</a>, <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=24">24</a>, <a href="http://bugzilla.mycompany.com/show_bug.cgi?id=3355">3355</a>
FIX: error 1024 was fixed
Notice that 1024 shouldn't be replaced with the link.
My current code do the job, but I interested whether it could be simplified, optimized, etc. May be it could be replaced with only one replacement regular expression? Or it could be replaced with one magic Python function from known libraries?
|
[
"No, there's not much of a better way to do it. The replacement code messes up the case where there are bug numbers and other numbers on the same line, but even so, you're not getting away from two res because you want support for a comma-separated bug list.\nimport re\n\ninfo_lines = [\n \"Me\",\n \"now\",\n \"STABLE\",\n \"FIX: some bug fixed\",\n \"FIX: 10, 24, 3355\",\n \"FIX: error 1024 was fixed\",\n \"FIX: 15 (dupe of BUG:25) fixed crash on x = 250.\"\n]\nlinkText = r'<a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=\\1\">\\1</a>'\nbugSearch = re.compile(r'(?:BUG|FIX):(?:[ ,]*(\\d+))+')\nbugMatch = re.compile(r'(\\d+)')\n\nfor k, ln in enumerate(info_lines[3:]):\n while True:\n m = bugSearch.search(ln)\n if m:\n ln = ln[:m.start()] + bugMatch.sub(linkText, m.group()) + ln[m.end():]\n else:\n break\n info_lines[k+3] = ln\n\nfor ln in info_lines:\n print ln\n\nOutput:\nMe\nnow\nSTABLE\nFIX: some bug fixed\nFIX: <a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=10\">10</a>, <a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=24\">24</a>, <a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=3355\">3355</a>\nFIX: error 1024 was fixed\nFIX: <a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=15\">15</a> (dupe of BUG:<a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=25\">25</a>) fixed crash on x = 250.\n\nIf you required every bug number to be prefixed with \"FIX:\" or \"BUG:\", then things get much simpler:\nlinkText = r'\\1<a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=\\2\">\\2</a>'\nbugSearch = re.compile(r'((?:BUG|FIX):(?: )?)(\\d+)')\n\ninfo_lines[3:] = [bugSearch.sub(linkText, ln) for ln in info_lines[3:]]\n\nfor ln in info_lines:\n print ln\n\nOutput:\nMe\nnow\nSTABLE\nFIX: some bug fixed\nFIX: <a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=10\">10</a>, 24, 3355\nFIX: error 1024 was fixed\nFIX: <a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=15\">15</a> (dupe of BUG:<a href=\"http://bugzilla.mycompany.com/show_bug.cgi?id=25\">25</a>) fixed crash on x = 250.\n\n",
"I would say that it's fine as-is, although I personally would prefer different syntax for bug numbers. I would differentiate them from bare numbers by either having \"bug 144\", \"issue 196\" or just \"#153\". That means they can then be embedded in a longer message, to provide clearer context. This is especially helpful in cases like \"Preliminary work for bug 355\" or \"Finishing clearup from #1293\".\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001907137_python_regex.txt
|
Q:
Problems installing MySQL-python-1.2.3c1 on Mac Snow Leopard
I am having a problem installing the Python MySQL connector (MySQL-python-1.2.3c1) on my Mac OSX Snow Leopard.
System State
I have manually compiled an installed:
mysql-5.1.41
This seems to work fine, as I can create and query a database from the commandline.
I have compiled:
MySQL-python-1.2.3c1
I first set the following in the site.cfg file:
mysql_config = /usr/local/mysql/bin/mysql_config
I then built and compiled MySQL-python-1.2.3c1 following their guide:
sudo python setup.py build
sudo python setup.py install
I now test the installation with Python:
python -c "import MySQLdb"
Error Message
This then gives me the following error, and I'm stumped as to how to fix it:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows
Referenced from: /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
Expected in: flat namespace
in /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
mymac: username$
Things I've Tried
I've looked at this blog antoniocangiano.com but it is for an older version of MySQL-python and is not really applicable. But I tried adding the soft link it mentions.
I then looked at this blog post: http://blog.some-abstract-type.com/2009/09/mysql-python-and-mac-os-x-106-snow.html. And tried building compiling with the ARCHFLAGS settings - but no joy.
Please Help
If you have any ideas please let me know.
Many thanks
Ben...
A:
What does
otool -L /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
report?
A:
First, I would suggest using the MySQL binaries for MacOS X 10.5 64-bit (x86_64). The tar ball works on MacOS X 10.6.
You said you used ARCHFLAGS.. however, try it again like this:
shell> ARCHFLAGS="-arch x86_64" python setup.py build
shell> sudo python setup.py install
Thus building as normal user, installing as root. (It's good to remove the source, and unpack correcting the site.cfg file again).
|
Problems installing MySQL-python-1.2.3c1 on Mac Snow Leopard
|
I am having a problem installing the Python MySQL connector (MySQL-python-1.2.3c1) on my Mac OSX Snow Leopard.
System State
I have manually compiled an installed:
mysql-5.1.41
This seems to work fine, as I can create and query a database from the commandline.
I have compiled:
MySQL-python-1.2.3c1
I first set the following in the site.cfg file:
mysql_config = /usr/local/mysql/bin/mysql_config
I then built and compiled MySQL-python-1.2.3c1 following their guide:
sudo python setup.py build
sudo python setup.py install
I now test the installation with Python:
python -c "import MySQLdb"
Error Message
This then gives me the following error, and I'm stumped as to how to fix it:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module>
File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 6, in __bootstrap__
ImportError: dlopen(/Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Symbol not found: _mysql_affected_rows
Referenced from: /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
Expected in: flat namespace
in /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so
mymac: username$
Things I've Tried
I've looked at this blog antoniocangiano.com but it is for an older version of MySQL-python and is not really applicable. But I tried adding the soft link it mentions.
I then looked at this blog post: http://blog.some-abstract-type.com/2009/09/mysql-python-and-mac-os-x-106-snow.html. And tried building compiling with the ARCHFLAGS settings - but no joy.
Please Help
If you have any ideas please let me know.
Many thanks
Ben...
|
[
"What does \notool -L /Users/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so\n\nreport?\n",
"First, I would suggest using the MySQL binaries for MacOS X 10.5 64-bit (x86_64). The tar ball works on MacOS X 10.6.\nYou said you used ARCHFLAGS.. however, try it again like this:\nshell> ARCHFLAGS=\"-arch x86_64\" python setup.py build\nshell> sudo python setup.py install\n\nThus building as normal user, installing as root. (It's good to remove the source, and unpack correcting the site.cfg file again).\n"
] |
[
1,
1
] |
[] |
[] |
[
"compilation",
"macos",
"mysql",
"osx_snow_leopard",
"python"
] |
stackoverflow_0001907540_compilation_macos_mysql_osx_snow_leopard_python.txt
|
Q:
context within a query filter?
I have a very basic contact model. The model has the following fields:
class Entry(models.Model):
name = models.CharField(max_length=64, unique=False)
organization = models.CharField(max_length=100, unique=False, blank=True, null=True)
team = models.CharField(max_length=64, unique=False, blank=True, null=True)
position = models.CharField(max_length=64, unique=False, blank=True, null=True)
address = models.CharField(max_length=130, unique=False, blank=True, null=True)
...
def __unicode__(self):
return u'%s' % self.name
I have different templates to display/edit individual entries. I'd like to accomplish the following.
When viewing an individual record, I'd like the user to be able to click on "organization" and be redirected to a template that lists all of the existing records in the db from that organization. I've built the template but I'm unsure of the view code.
I feel like it should be something like this, but I don't think it's legal.
def display_organization(request):
records = Entry.objects.filter(organization__exact=Context)
t = get_template('org_list.html')
html = t.render(Context({'records': records}))
return HttpResponse(html)
Can anyone assist?
A:
You probably want the display_organization URL map to include a parameter for the organization:
('^organization/(?P<org_name>.+)$', 'myapp.views.display_organization'),
With that, your display_organization function must accept the org_name parameter too:
def display_organization(request, org_name):
records = Entry.objects.filter(organization__exact=org_name)
html = get_template('org_list.html').render({'records': records})
return HttpResponse(html)
A:
You're making it quite complex by depending on the URL. It's fine if there's only one or two things that work that way.
I'd say, keep it simple and just use request.GET
def display_organization(request):
records = Entry.objects.filter(organization__iexact=request.GET['organization'])
...
|
context within a query filter?
|
I have a very basic contact model. The model has the following fields:
class Entry(models.Model):
name = models.CharField(max_length=64, unique=False)
organization = models.CharField(max_length=100, unique=False, blank=True, null=True)
team = models.CharField(max_length=64, unique=False, blank=True, null=True)
position = models.CharField(max_length=64, unique=False, blank=True, null=True)
address = models.CharField(max_length=130, unique=False, blank=True, null=True)
...
def __unicode__(self):
return u'%s' % self.name
I have different templates to display/edit individual entries. I'd like to accomplish the following.
When viewing an individual record, I'd like the user to be able to click on "organization" and be redirected to a template that lists all of the existing records in the db from that organization. I've built the template but I'm unsure of the view code.
I feel like it should be something like this, but I don't think it's legal.
def display_organization(request):
records = Entry.objects.filter(organization__exact=Context)
t = get_template('org_list.html')
html = t.render(Context({'records': records}))
return HttpResponse(html)
Can anyone assist?
|
[
"You probably want the display_organization URL map to include a parameter for the organization:\n('^organization/(?P<org_name>.+)$', 'myapp.views.display_organization'),\n\nWith that, your display_organization function must accept the org_name parameter too:\ndef display_organization(request, org_name):\n records = Entry.objects.filter(organization__exact=org_name)\n html = get_template('org_list.html').render({'records': records})\n return HttpResponse(html)\n\n",
"You're making it quite complex by depending on the URL. It's fine if there's only one or two things that work that way.\nI'd say, keep it simple and just use request.GET\ndef display_organization(request):\n records = Entry.objects.filter(organization__iexact=request.GET['organization'])\n ...\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001902813_django_python.txt
|
Q:
how can I make 'between' query with web2py.DAL?
I'm trying to make a query function that accepts two datetime.date object(start_date and end_date), and return all records with a related field that's between start_date and end_date.
However, I found nothing like a between function in the web2py manual, so I implement it this way:
for o in objects:
# notice that create_time is a datetime field
create_date = dt.datetime.strptime(o['create_time'],
"%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
if query_dict['create_date_1'] <= create_date <= query_dict['create_date_2']:
result.append(l)
Doing this is too slow for my application because their can be many objects.
So, is there a better way I can implement this using web2py.DAL?
Thanks in advance ;)
A:
db((db.mytable.create_date>=query_dict['create_date1'])&(db.mytable.create_date<=query_dict['create_date2'])).select()
|
how can I make 'between' query with web2py.DAL?
|
I'm trying to make a query function that accepts two datetime.date object(start_date and end_date), and return all records with a related field that's between start_date and end_date.
However, I found nothing like a between function in the web2py manual, so I implement it this way:
for o in objects:
# notice that create_time is a datetime field
create_date = dt.datetime.strptime(o['create_time'],
"%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
if query_dict['create_date_1'] <= create_date <= query_dict['create_date_2']:
result.append(l)
Doing this is too slow for my application because their can be many objects.
So, is there a better way I can implement this using web2py.DAL?
Thanks in advance ;)
|
[
"db((db.mytable.create_date>=query_dict['create_date1'])&(db.mytable.create_date<=query_dict['create_date2'])).select()\n"
] |
[
3
] |
[] |
[] |
[
"python",
"web2py"
] |
stackoverflow_0001907088_python_web2py.txt
|
Q:
Encoding utf-8 to base64 with accents
I have some data like this:
data1 = ['Agos', '30490349304']
data2 = ['Desir\xc3\xa9','9839483948']
I'm using an API that expects the data encoded in base64, so what I do is:
data = data1
string = base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
myXMLRPCCall(string)
Which works fine with data1. With data2 the encoding goes ok, but then the XMLRPC returns an error, since it expects (from the API docs) only ISO-8859-1 (Latin1) characters.
My question is: how can I transform my string into Latin1 so that the API accepts it?
A:
First make sure you're not confused about encodings, etc. Read, for example, this.
Then notice that the main problem isn't with the base64 encoding, but with the fact that you're trying to put byte string (normal string in Python 2.x) inside a Unicode string. I believe you can fix this by removing the "u" from the last string in your example code.
A:
base64.b64encode("Hi, %s! Your code is %s" % (data[0].decode('utf8').encode('latin1'), data[0]))
A:
This seem to work:
...
data = data2
base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
# => 'SGksIERlc2lyw6khIFlvdXIgY29kZSBpcyBEZXNpcsOp'
# I can't test the XMLRPC parts, so this is just a hint ..
for_the_wire = base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
latin_1_encoded = for_the_wire.encode('latin-1')
# send latin_1_encoded over the wire ..
Some python (2.X) unicode readings:
http://evanjones.ca/python-utf8.html
http://www.amk.ca/python/howto/unicode
http://boodebr.org/main/python/all-about-python-and-unicode
|
Encoding utf-8 to base64 with accents
|
I have some data like this:
data1 = ['Agos', '30490349304']
data2 = ['Desir\xc3\xa9','9839483948']
I'm using an API that expects the data encoded in base64, so what I do is:
data = data1
string = base64.b64encode("Hi, %s! Your code is %s" % (data[0], data[0]))
myXMLRPCCall(string)
Which works fine with data1. With data2 the encoding goes ok, but then the XMLRPC returns an error, since it expects (from the API docs) only ISO-8859-1 (Latin1) characters.
My question is: how can I transform my string into Latin1 so that the API accepts it?
|
[
"First make sure you're not confused about encodings, etc. Read, for example, this.\nThen notice that the main problem isn't with the base64 encoding, but with the fact that you're trying to put byte string (normal string in Python 2.x) inside a Unicode string. I believe you can fix this by removing the \"u\" from the last string in your example code.\n",
"base64.b64encode(\"Hi, %s! Your code is %s\" % (data[0].decode('utf8').encode('latin1'), data[0]))\n\n",
"This seem to work:\n...\n\ndata = data2\nbase64.b64encode(\"Hi, %s! Your code is %s\" % (data[0], data[0]))\n# => 'SGksIERlc2lyw6khIFlvdXIgY29kZSBpcyBEZXNpcsOp'\n\n# I can't test the XMLRPC parts, so this is just a hint ..\nfor_the_wire = base64.b64encode(\"Hi, %s! Your code is %s\" % (data[0], data[0]))\nlatin_1_encoded = for_the_wire.encode('latin-1')\n\n# send latin_1_encoded over the wire ..\n\nSome python (2.X) unicode readings:\n\nhttp://evanjones.ca/python-utf8.html\nhttp://www.amk.ca/python/howto/unicode\nhttp://boodebr.org/main/python/all-about-python-and-unicode\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"ascii",
"base64",
"encoding",
"python",
"utf_8"
] |
stackoverflow_0001908035_ascii_base64_encoding_python_utf_8.txt
|
Q:
turbogears request/user object in templates and request context
I am currently making the switch from Django to Turbogears 2.1 and am running into some problems that I could not find the answers to in the Turbogears docs. If tg developers read this, let me tell you that one of the best features Django has over TG is its documentation!
1) How do I access the request (user?) object within a mako template in order to check if the user is authenticated? For instance
if (request.user.is_authenticated)
'logout link'
else
'login link'
2) A related quesiton (as the user object is exposed in Django to templates via context processors). Is there a way to add data to the request context? For instance, in my Django app I add a cached dictionary of notifications for the user if the user is logged in via a definition in a context_processors.py file and then include that def in the TEMPLATE_CONTEXT_PROCESSORS tuple in the settings file.
3) This may warrant its own question, but I thought I'd throw it in in case anyone has a quick suggestion. I'm using Netbeans as my IDE and it offers no code coloring or tools for mako files. However, trying to rename the templates with a .html extension throws a mako error. Is there any way around this or am I stuck with plain text and the .mak extension?
Thanks very much
A:
I've moved from Turbogears 1.0 to Django. Might not be able to answer all of these, but I believe in general TG2 tries to keep things fairly similar to TG1. Hopefully pointing out how it works in TG 1, might help...
1) In Turbogears 1.0 you would use tg.identity.anonymous to see if the user was logged in or not. A quick look at the docs, shows it's most likely still the same.
2) Turbogears called this sort of thing stdvars - see here for details for TG 1 http://docs.turbogears.org/1.0/stdvars
3) Sorry don't know, but I presume you can probably just tell Netbeans to consider .mak as another extension for html files (so it uses html syntax highlighting).
|
turbogears request/user object in templates and request context
|
I am currently making the switch from Django to Turbogears 2.1 and am running into some problems that I could not find the answers to in the Turbogears docs. If tg developers read this, let me tell you that one of the best features Django has over TG is its documentation!
1) How do I access the request (user?) object within a mako template in order to check if the user is authenticated? For instance
if (request.user.is_authenticated)
'logout link'
else
'login link'
2) A related quesiton (as the user object is exposed in Django to templates via context processors). Is there a way to add data to the request context? For instance, in my Django app I add a cached dictionary of notifications for the user if the user is logged in via a definition in a context_processors.py file and then include that def in the TEMPLATE_CONTEXT_PROCESSORS tuple in the settings file.
3) This may warrant its own question, but I thought I'd throw it in in case anyone has a quick suggestion. I'm using Netbeans as my IDE and it offers no code coloring or tools for mako files. However, trying to rename the templates with a .html extension throws a mako error. Is there any way around this or am I stuck with plain text and the .mak extension?
Thanks very much
|
[
"I've moved from Turbogears 1.0 to Django. Might not be able to answer all of these, but I believe in general TG2 tries to keep things fairly similar to TG1. Hopefully pointing out how it works in TG 1, might help...\n1) In Turbogears 1.0 you would use tg.identity.anonymous to see if the user was logged in or not. A quick look at the docs, shows it's most likely still the same.\n2) Turbogears called this sort of thing stdvars - see here for details for TG 1 http://docs.turbogears.org/1.0/stdvars\n3) Sorry don't know, but I presume you can probably just tell Netbeans to consider .mak as another extension for html files (so it uses html syntax highlighting).\n"
] |
[
1
] |
[] |
[] |
[
"django",
"mako",
"python",
"requestcontext",
"turbogears"
] |
stackoverflow_0001905885_django_mako_python_requestcontext_turbogears.txt
|
Q:
From Sax to Dom with DTD (python)
I need a validated DomTree with DTD (to use getElementById).
Validating and Parsing works, but the dom does't work properly:
from xml.dom import minidom
from xml.dom.pulldom import SAX2DOM
from lxml import etree
import lxml.sax
from StringIO import StringIO
data_string = """\
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE foo [
<!ELEMENT foo (bar)*>
<!ELEMENT bar (#PCDATA)>
<!ATTLIST bar id ID #REQUIRED>]><foo><bar id="nr_0">text</bar></foo>
"""
#parser, with vali. at parsing
etree_parser = etree.XMLParser(dtd_validation=True,attribute_defaults=True)
#parse it
sax_tree = etree.parse(StringIO(data_string),etree_parser);
handler = SAX2DOM();
lxml.sax.saxify(sax_tree,handler);
domObject = handler.document;
print domObject.getElementById("nr_0");
#returns None
print minidom.parseString(data_string).getElementById("nr_0");
#returns <DOM Element: bar at 0x7f36b77dc0e0>
It seems that SAX2DOM wont pass the DTD to the dom. Did I forgott something?
I've read it is impossible to load the DTD after the dom is build.
any ideas?
A:
As far as I know: SAX DTD events are not handled by the ContentHandler, but by the DTDHandler, which is a property you can set on the sax parser (XMLReader). This means that you cannot do this without serializing and reparsing the document.
validated_string = etree.tostring(tree)
domDocument = minidom.parseString(validated_string)
On the other hand: unless you really need a minidom document, you'd be better off just staying with the lxml tree. (you can use xpath for the equivalent of getElementById, or have a look at etree.XMLDTDID and etree.parseid)
|
From Sax to Dom with DTD (python)
|
I need a validated DomTree with DTD (to use getElementById).
Validating and Parsing works, but the dom does't work properly:
from xml.dom import minidom
from xml.dom.pulldom import SAX2DOM
from lxml import etree
import lxml.sax
from StringIO import StringIO
data_string = """\
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE foo [
<!ELEMENT foo (bar)*>
<!ELEMENT bar (#PCDATA)>
<!ATTLIST bar id ID #REQUIRED>]><foo><bar id="nr_0">text</bar></foo>
"""
#parser, with vali. at parsing
etree_parser = etree.XMLParser(dtd_validation=True,attribute_defaults=True)
#parse it
sax_tree = etree.parse(StringIO(data_string),etree_parser);
handler = SAX2DOM();
lxml.sax.saxify(sax_tree,handler);
domObject = handler.document;
print domObject.getElementById("nr_0");
#returns None
print minidom.parseString(data_string).getElementById("nr_0");
#returns <DOM Element: bar at 0x7f36b77dc0e0>
It seems that SAX2DOM wont pass the DTD to the dom. Did I forgott something?
I've read it is impossible to load the DTD after the dom is build.
any ideas?
|
[
"As far as I know: SAX DTD events are not handled by the ContentHandler, but by the DTDHandler, which is a property you can set on the sax parser (XMLReader). This means that you cannot do this without serializing and reparsing the document.\nvalidated_string = etree.tostring(tree)\ndomDocument = minidom.parseString(validated_string)\n\nOn the other hand: unless you really need a minidom document, you'd be better off just staying with the lxml tree. (you can use xpath for the equivalent of getElementById, or have a look at etree.XMLDTDID and etree.parseid)\n"
] |
[
1
] |
[] |
[] |
[
"dom",
"dtd",
"python",
"sax"
] |
stackoverflow_0001907740_dom_dtd_python_sax.txt
|
Q:
How to combine multiple images fast for page views counter
How can I combine multiple images, such as base image with logo and number of digits images to display graphical counter with pageviews count, updated dynamically?
It should be very fast, with thousands of renders per second. User should see counter image without Javascript and with single img tag.
I prefer to implement that counter with Python using PIL library, but other solutions welcome as well.
A:
Precompute for the given background the image of a single digit (for each digit 0 ... 10) at each digit position.
Then to create arbitrary number you only have to paste the correct images next to eachother, but you won't have to do any alpha blending. Therefore this must be more efficient.
Also, if certain page counts are more common (e.g. page counts < 10000) you might want to precompute these (10000) complete counter images to serve those directly.
EDIT:
You can do this with python PIL, or any other method. If you have a specific difficulty with PIL then please ask a more direct question about the problems you have encounterd.
A:
If you really need to handle thousands "renders" per second I would not suggest to generate the images on the fly. How about precomputing n images where n is the expected (you might want to be generous here) count you have to handle?
I know you state that you don't want to use javascript and you only want one img tag, but I would recommend to reconsider pushing visualization to the client side as you would burn unnecessary resources if you really get the load you are expecting (thousands hits / second, every hit incrementing the counter and generating an image using PIL).
A:
Since the background is uniform in your example, render the string "0123456789" and use CSS sprites to build the counter.
|
How to combine multiple images fast for page views counter
|
How can I combine multiple images, such as base image with logo and number of digits images to display graphical counter with pageviews count, updated dynamically?
It should be very fast, with thousands of renders per second. User should see counter image without Javascript and with single img tag.
I prefer to implement that counter with Python using PIL library, but other solutions welcome as well.
|
[
"Precompute for the given background the image of a single digit (for each digit 0 ... 10) at each digit position.\nThen to create arbitrary number you only have to paste the correct images next to eachother, but you won't have to do any alpha blending. Therefore this must be more efficient.\nAlso, if certain page counts are more common (e.g. page counts < 10000) you might want to precompute these (10000) complete counter images to serve those directly.\nEDIT:\nYou can do this with python PIL, or any other method. If you have a specific difficulty with PIL then please ask a more direct question about the problems you have encounterd.\n",
"If you really need to handle thousands \"renders\" per second I would not suggest to generate the images on the fly. How about precomputing n images where n is the expected (you might want to be generous here) count you have to handle?\nI know you state that you don't want to use javascript and you only want one img tag, but I would recommend to reconsider pushing visualization to the client side as you would burn unnecessary resources if you really get the load you are expecting (thousands hits / second, every hit incrementing the counter and generating an image using PIL).\n",
"Since the background is uniform in your example, render the string \"0123456789\" and use CSS sprites to build the counter.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"counter",
"python",
"python_imaging_library"
] |
stackoverflow_0001908334_counter_python_python_imaging_library.txt
|
Q:
Best way to add python scripting into QT application?
I have a QT 4.6 application (C++ language) and i need to add python scripting to it on windows platform. Unfortunately, i never embed python before, and it seems to be a lot of different ways to do so. Can anyone share his wisdom and point me into some articles/documentation i can read to perform a specified task in less painful way?
A:
Edit:
You can use PythonQt (not PyQt) that allow you to use Python with Qt. I think this is what you are searching for.
Here a documentation on the official website: http://doc.qt.digia.com/qq/qq23-pythonqt.html.
A:
You should take a look at PythonQt. From the homepage:
PythonQt is a dynamic Python
binding for Qt. It offers
an easy way to embed the Python
scripting language into your Qt
applications. It makes heavy use of
the QMetaObject system and thus
requires Qt4.x. In contrast to PyQt ,
PythonQt is not a complete Python
wrapper around the complete Qt
functionality. So if you are looking
for a way to write complete
applications in Python using the Qt
GUI, you should use PyQt.
If you are looking for a simple way to
embed Python objects into your C++/Qt
Application and to script parts of
your application via Python, PythonQt
is the way to go!
Build/installation instructions for Windows is near the bottom of the page.
|
Best way to add python scripting into QT application?
|
I have a QT 4.6 application (C++ language) and i need to add python scripting to it on windows platform. Unfortunately, i never embed python before, and it seems to be a lot of different ways to do so. Can anyone share his wisdom and point me into some articles/documentation i can read to perform a specified task in less painful way?
|
[
"Edit:\nYou can use PythonQt (not PyQt) that allow you to use Python with Qt. I think this is what you are searching for.\nHere a documentation on the official website: http://doc.qt.digia.com/qq/qq23-pythonqt.html.\n",
"You should take a look at PythonQt. From the homepage:\n\nPythonQt is a dynamic Python\n binding for Qt. It offers\n an easy way to embed the Python\n scripting language into your Qt\n applications. It makes heavy use of\n the QMetaObject system and thus\n requires Qt4.x. In contrast to PyQt ,\n PythonQt is not a complete Python\n wrapper around the complete Qt\n functionality. So if you are looking\n for a way to write complete\n applications in Python using the Qt\n GUI, you should use PyQt.\nIf you are looking for a simple way to\n embed Python objects into your C++/Qt\n Application and to script parts of\n your application via Python, PythonQt\n is the way to go!\n\nBuild/installation instructions for Windows is near the bottom of the page.\n"
] |
[
6,
6
] |
[] |
[] |
[
"c++",
"python",
"qt"
] |
stackoverflow_0001908269_c++_python_qt.txt
|
Q:
Blocking behavior of PyGTK's main loop
My intention was to use pyGTK's main loop to create a function that blocks while it waits for the user's input. The problem I've encountered is best explained in code:
#! /usr/bin/python
import gtk
def test():
retval = True
def cb(widget):
retval = False
gtk.main_quit()
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
button = gtk.Button("Test")
button.connect("clicked", cb)
button.show()
window.add(button)
window.show()
gtk.main()
return retval
if __name__ == "__main__":
print test() # prints True when the button is clicked
It seems that the exact order of instructions (change value of retval, then exit main loop) isn't being followed here.
Is there any way around this, or is this just bad design on my part?
A:
This is the dialog pattern. Use a gtk.Dialog. Dialog.run() blocks exactly how you need it to, and returns the dialog's return code.
A:
What is happening is that when python sees foo = bar as the first reference to foo in a function it assumes that it is a local variable. In python3k you can get around this by using the nonlocal keyword. For 2.x you can wrap your retval in a list so that you aren't directly assigning to it.
retval = [True]
def cb(widget):
retval[0] = False
gtk.main_quit()
...
return retval[0]
not really an elegant solution, hence the addition of nonlocal in 3.x (PEP)
|
Blocking behavior of PyGTK's main loop
|
My intention was to use pyGTK's main loop to create a function that blocks while it waits for the user's input. The problem I've encountered is best explained in code:
#! /usr/bin/python
import gtk
def test():
retval = True
def cb(widget):
retval = False
gtk.main_quit()
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
button = gtk.Button("Test")
button.connect("clicked", cb)
button.show()
window.add(button)
window.show()
gtk.main()
return retval
if __name__ == "__main__":
print test() # prints True when the button is clicked
It seems that the exact order of instructions (change value of retval, then exit main loop) isn't being followed here.
Is there any way around this, or is this just bad design on my part?
|
[
"This is the dialog pattern. Use a gtk.Dialog. Dialog.run() blocks exactly how you need it to, and returns the dialog's return code.\n",
"What is happening is that when python sees foo = bar as the first reference to foo in a function it assumes that it is a local variable. In python3k you can get around this by using the nonlocal keyword. For 2.x you can wrap your retval in a list so that you aren't directly assigning to it.\nretval = [True]\ndef cb(widget):\n retval[0] = False\n gtk.main_quit()\n...\nreturn retval[0]\n\nnot really an elegant solution, hence the addition of nonlocal in 3.x (PEP)\n"
] |
[
3,
2
] |
[] |
[] |
[
"callback",
"pygtk",
"python"
] |
stackoverflow_0001890715_callback_pygtk_python.txt
|
Q:
Improve code: test for key in dict and store in datastore
Hey, I'm fairly new to python I have this piece of code which stores the birth info to the datastore in Google App Engine. The code works but is it the correct way to do it? Is there a simpler way to do it, to make sure that the key exists before storing it in datastore?
def store_birthinfo(self, user, birthday):
"""
Store birthinfo
"""
name = ''
date = ''
place = ''
country = ''
for key in birthday.keys():
if key == 'name':
name = birthday['name']
elif key == 'date':
date = birthday['date']
elif key == 'place':
place = birthday['place']
elif key == 'country':
country = birthday['country']
birthinfo = BirthInfo(user = user,
date = date,
place = place,
country = country)
birthinfo.put()
A:
def store_birthinfo(self, user, birthday):
"""
Store birthinfo
"""
birthinfo = BirthInfo(user=user, **birthday)
birthinfo.put()
see the docs on unpacking argument lists.
A:
ʞɔıu's answer is the shortest, though it has slightly different semantics than yours, in that yours will provide an explicit empty string argument if the key is missing from the dictionary, while ʞɔıu's will omit the keyword argument altogether.
For the sake of completeness, there's a simpler way to do what you were doing without going all the way to **:
def store_birthinfo(self, user, birthday):
"""
Store birthinfo
"""
birthinfo = BirthInfo(user = user,
date = birthday.get('date', ''),
place = birthday.get('place', ''),
country = birthday.get('country', ''))
birthinfo.put()
A:
You can create a default dictionary and then update the target dictionary as in
def store_birthinfo(self, user, birthday):
"""Store birthinfo"""
birth_defaults = { 'name' : '',
'date' : '',
'place' : '',
'country' : ''}
birth_defaults.update(birthday)
birthinfo = BirthInfo(**birth_defaults)
birthinfo.put()
In this way you will always have all the params set.
A:
A problem might be if your variable 'birthday' contains keys that the class BirthInfo doesn't expect. A more solid solution might be this which also gives you the clear insight into if blanks ones become None or empty string:
def store_birthinfo(self, user, birthday):
data = dict(name='', date='', place='', country='')
for key in [x for x in birthday.keys() if x in data]:
data[key] = birthday[key]
BirthInfo(user=user, **data).put()
A:
Building on Peter Bengtsson's post, you could also define the list of relevant keys, and leave data as an empty {} until the loop populates it.
def store_birthinfo(self, user, birthday):
data = {}
for key in 'date', 'place', 'country':
data[key] = birthday.get(key, '')
BirthInfo(user=user, **data).put()
I believe this is the most terse and extensible way to specify which keys to use from the birthday dict. With a little more verbosity, you could probably write a function to introspect BirthInfo for the arguments it can accept.
|
Improve code: test for key in dict and store in datastore
|
Hey, I'm fairly new to python I have this piece of code which stores the birth info to the datastore in Google App Engine. The code works but is it the correct way to do it? Is there a simpler way to do it, to make sure that the key exists before storing it in datastore?
def store_birthinfo(self, user, birthday):
"""
Store birthinfo
"""
name = ''
date = ''
place = ''
country = ''
for key in birthday.keys():
if key == 'name':
name = birthday['name']
elif key == 'date':
date = birthday['date']
elif key == 'place':
place = birthday['place']
elif key == 'country':
country = birthday['country']
birthinfo = BirthInfo(user = user,
date = date,
place = place,
country = country)
birthinfo.put()
|
[
"def store_birthinfo(self, user, birthday):\n \"\"\"\n Store birthinfo\n \"\"\"\n\n birthinfo = BirthInfo(user=user, **birthday)\n birthinfo.put()\n\nsee the docs on unpacking argument lists.\n",
"ʞɔıu's answer is the shortest, though it has slightly different semantics than yours, in that yours will provide an explicit empty string argument if the key is missing from the dictionary, while ʞɔıu's will omit the keyword argument altogether. \nFor the sake of completeness, there's a simpler way to do what you were doing without going all the way to **:\ndef store_birthinfo(self, user, birthday):\n \"\"\"\n Store birthinfo\n \"\"\"\n\n birthinfo = BirthInfo(user = user,\n date = birthday.get('date', ''),\n place = birthday.get('place', ''),\n country = birthday.get('country', ''))\n birthinfo.put()\n\n",
"You can create a default dictionary and then update the target dictionary as in\ndef store_birthinfo(self, user, birthday):\n \"\"\"Store birthinfo\"\"\"\n birth_defaults = { 'name' : '',\n 'date' : '',\n 'place' : '',\n 'country' : ''}\n\n birth_defaults.update(birthday)\n birthinfo = BirthInfo(**birth_defaults)\n birthinfo.put()\n\nIn this way you will always have all the params set.\n",
"A problem might be if your variable 'birthday' contains keys that the class BirthInfo doesn't expect. A more solid solution might be this which also gives you the clear insight into if blanks ones become None or empty string:\ndef store_birthinfo(self, user, birthday):\n data = dict(name='', date='', place='', country='')\n for key in [x for x in birthday.keys() if x in data]:\n data[key] = birthday[key]\n\n BirthInfo(user=user, **data).put()\n\n",
"Building on Peter Bengtsson's post, you could also define the list of relevant keys, and leave data as an empty {} until the loop populates it.\ndef store_birthinfo(self, user, birthday):\n data = {}\n for key in 'date', 'place', 'country':\n data[key] = birthday.get(key, '')\n BirthInfo(user=user, **data).put()\n\nI believe this is the most terse and extensible way to specify which keys to use from the birthday dict. With a little more verbosity, you could probably write a function to introspect BirthInfo for the arguments it can accept.\n"
] |
[
2,
1,
1,
0,
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001908104_google_app_engine_python.txt
|
Q:
buildbot: run svn with --trust-server-cert
I am trying to install buildbot for my project.
I always run my svn commands with trust-server-cert option. How can I pass that to SVN thru buildbot?
I don't see there is a way for doing that. What is the shortest workaround?
A:
Use the extra_args argument to the buildbot.steps.source.SVN constructor.
|
buildbot: run svn with --trust-server-cert
|
I am trying to install buildbot for my project.
I always run my svn commands with trust-server-cert option. How can I pass that to SVN thru buildbot?
I don't see there is a way for doing that. What is the shortest workaround?
|
[
"Use the extra_args argument to the buildbot.steps.source.SVN constructor.\n"
] |
[
2
] |
[] |
[] |
[
"build_process",
"buildbot",
"project_management",
"python",
"svn"
] |
stackoverflow_0001908856_build_process_buildbot_project_management_python_svn.txt
|
Q:
Python: list problems
I've read in a text file and converted each line into a list.
using this script:
l = [s.strip().split() for s in open("cluster2.wcnf").readlines()]
How would i go about :
the file it opens is dynamic rather than static? i.e. the user
chooses the file to open.
Select specific lines to read after it has been converted to a list.
assign objects to values in the list
select the first, last or a number of values in each line?
thanks in advance
A:
First of all, you must drop .readlines() from your list comprehension.
Second, l is a list of lists, to access first line just do: l[0]. First element of the first line would then be l[0][0].
The problem with the growing file I believe cannot be solved with such approach, though. If by dynamic you mean file name, rather the file behaviour then you could replace hard-coded file name for the variable that's going to be defined from the user input.
A:
Things like opening files with names got from the user(i.e. using strings) and selecting/assigning items within a list are really very basic Python concepts. I think the best you can do is to read a good book on Python. I would recommend Dive Into Python.
A:
Number 1:
When you say you want the file it opens to be dynamic do you mean you want the user to input the file name to be opened? If so you can simply store the file name into a variable. For example:
name = "myfile.txt"
and replace your "cluster2.wcnf" with name.
Number 4:
You can use the indexing mentioned by SilentGhost to index the first item in each line (i.e. l[0][0]. To look at the last item you can use negative indexing; l[0][-1] will give you the last item in the first list. And if you want a range of items you can use something like l[0][2:6] which will give you the items of index 2, 3, 4, and 5. That is items in the range [2,6).
A:
This is a more optimised way of reading in a whole file where each line is also split into a list
import csv, sys
# 1 - User specifies file
file = input('File: ')
f = open(file, 'r')
reader = csv.reader(f, delimiter=' ')
lines = list(reader)
f.close()
# 2 - Select specific lines
print lines[4]
# 3 - Assign to list
lines[4] = obj # makes the whole line into that obj
lines[4][0] = obj # replaces the first item on the line with that obj
# 4 - Select first, last or a number of values
print lines[4][0] # first item in line 4
print lines[4][-1] # last item in line 4
print lines[4][1:4] # 2nd, 3rd and 4th items in line 4
A:
The way you ask the questions you ask indicates to me that you aren't exactly clear on what you want your program to do eventually.
First, that line doesn't just convert the file to a list. It converts it to a list of tuples. Each tuple is a set of space separated values for one line in the file.
I will answer your questions as given, but I expect some of the answers may confuse you even more.
1 the file it opens is dynamic rather than static? i.e. the user chooses the file to open.
"cluster2.wcf" doesn't have to be a string. It can be a variable. If one is to read your question very literally, here is how you would modify the code to do it:
filename = raw_input("Which file would you like to read: ")
l = [s.strip().split() for s in open(filename).readlines()]
A point to note here. After you read the file into the list, the list is going to look like this:
[('This', 'is', 'the', 'first', 'line.'),
('This', 'is', 'the', 'second', 'line.'),
('And', 'finally', 'the', 'last', 'line.')]
Each element of your list is a further list of all the 'words' on that line. Words being defined as space separated groups of characters.
2 Select specific lines to read after it has been converted to a list.
This question is a confusing question. You have already read the file. Do you want to read it again? What I am guessing you actually mean is "How do I work with a specific line of the file after I've read it into a list?". I will answer this question.
Each line of the file will correspond to a particular element of the list. List elements are accessed by numbers starting with 0. The first line of your file will be in l[0]. The second in l[1] and so on up to (and this is a bit of Python magic here) l[-1]. Negative indexes in Python count backwards from the end of the list.
3 assign objects to values in the list
This one is confusing because you don't specify what kind of objects you want to assign or what you want to do with the list after you assign objects to values in it. Here is an answer that takes your question very literally...
l[0] = object()
That assigns an object to the list element that used to contain a tuple representing the first line of your file. Combining this with the previous answer I am betting you can figure out how to assign an object to any element of your list.
4 select the first, last or a number of values in each line?
This depends on exactly how you want to select them. If you want to do it individually you do it this way:
first_word_of_first_line = l[0][0]
last_word_of_first_line = l[0][-1]
first_word_of_last_line = l[-1][0]
last_word_of_last_line = l[-1][-1]
first_five_words of_second_line = l[1][0:5] # The : is for specifying a range of values
last_five_words_of_first_line = l[0][-5:] # The : with no end means 'until the end'
Unfortunately, the way to get the first 4 words of the first 2 lines is not this:
first_four_words_of_first_two_lines = l[0:2][0:4] # DOESN'T WORK!!!
The reason for that is that the result of fetching a range of values from a list is a list, and so the [0:4] applies to that list instead. What you really mean to do is to apply the [0:4] to apply to each element of the resulting list to create a new list. Here is how you would do that:
first_four_words_of_first_two_lines = [x[0:4] for x in l[0:2]]
That gives you a new list that looks like this (given the example for question 1):
[('This', 'is', 'the', 'first'),
('This', 'is', 'the', 'second')]
I hope that is helpful. As I said, I think your questions indicate some confusion about things. But I don't know what they indicate confusion about, so I just tried to answer them as best I could.
|
Python: list problems
|
I've read in a text file and converted each line into a list.
using this script:
l = [s.strip().split() for s in open("cluster2.wcnf").readlines()]
How would i go about :
the file it opens is dynamic rather than static? i.e. the user
chooses the file to open.
Select specific lines to read after it has been converted to a list.
assign objects to values in the list
select the first, last or a number of values in each line?
thanks in advance
|
[
"First of all, you must drop .readlines() from your list comprehension.\nSecond, l is a list of lists, to access first line just do: l[0]. First element of the first line would then be l[0][0].\nThe problem with the growing file I believe cannot be solved with such approach, though. If by dynamic you mean file name, rather the file behaviour then you could replace hard-coded file name for the variable that's going to be defined from the user input.\n",
"Things like opening files with names got from the user(i.e. using strings) and selecting/assigning items within a list are really very basic Python concepts. I think the best you can do is to read a good book on Python. I would recommend Dive Into Python. \n",
"Number 1:\nWhen you say you want the file it opens to be dynamic do you mean you want the user to input the file name to be opened? If so you can simply store the file name into a variable. For example:\nname = \"myfile.txt\"\n\nand replace your \"cluster2.wcnf\" with name. \nNumber 4:\nYou can use the indexing mentioned by SilentGhost to index the first item in each line (i.e. l[0][0]. To look at the last item you can use negative indexing; l[0][-1] will give you the last item in the first list. And if you want a range of items you can use something like l[0][2:6] which will give you the items of index 2, 3, 4, and 5. That is items in the range [2,6).\n",
"This is a more optimised way of reading in a whole file where each line is also split into a list\nimport csv, sys\n\n# 1 - User specifies file\nfile = input('File: ')\n\nf = open(file, 'r')\nreader = csv.reader(f, delimiter=' ')\nlines = list(reader)\nf.close()\n\n# 2 - Select specific lines\nprint lines[4]\n\n# 3 - Assign to list\nlines[4] = obj # makes the whole line into that obj\nlines[4][0] = obj # replaces the first item on the line with that obj\n\n# 4 - Select first, last or a number of values\nprint lines[4][0] # first item in line 4\nprint lines[4][-1] # last item in line 4\nprint lines[4][1:4] # 2nd, 3rd and 4th items in line 4\n\n",
"The way you ask the questions you ask indicates to me that you aren't exactly clear on what you want your program to do eventually.\nFirst, that line doesn't just convert the file to a list. It converts it to a list of tuples. Each tuple is a set of space separated values for one line in the file.\nI will answer your questions as given, but I expect some of the answers may confuse you even more.\n1 the file it opens is dynamic rather than static? i.e. the user chooses the file to open.\n\"cluster2.wcf\" doesn't have to be a string. It can be a variable. If one is to read your question very literally, here is how you would modify the code to do it:\nfilename = raw_input(\"Which file would you like to read: \")\nl = [s.strip().split() for s in open(filename).readlines()]\n\nA point to note here. After you read the file into the list, the list is going to look like this:\n[('This', 'is', 'the', 'first', 'line.'),\n ('This', 'is', 'the', 'second', 'line.'),\n ('And', 'finally', 'the', 'last', 'line.')]\n\nEach element of your list is a further list of all the 'words' on that line. Words being defined as space separated groups of characters.\n\n2 Select specific lines to read after it has been converted to a list.\nThis question is a confusing question. You have already read the file. Do you want to read it again? What I am guessing you actually mean is \"How do I work with a specific line of the file after I've read it into a list?\". I will answer this question.\nEach line of the file will correspond to a particular element of the list. List elements are accessed by numbers starting with 0. The first line of your file will be in l[0]. The second in l[1] and so on up to (and this is a bit of Python magic here) l[-1]. Negative indexes in Python count backwards from the end of the list.\n\n3 assign objects to values in the list\nThis one is confusing because you don't specify what kind of objects you want to assign or what you want to do with the list after you assign objects to values in it. Here is an answer that takes your question very literally...\nl[0] = object()\n\nThat assigns an object to the list element that used to contain a tuple representing the first line of your file. Combining this with the previous answer I am betting you can figure out how to assign an object to any element of your list.\n\n4 select the first, last or a number of values in each line?\nThis depends on exactly how you want to select them. If you want to do it individually you do it this way:\nfirst_word_of_first_line = l[0][0]\nlast_word_of_first_line = l[0][-1]\nfirst_word_of_last_line = l[-1][0]\nlast_word_of_last_line = l[-1][-1]\nfirst_five_words of_second_line = l[1][0:5] # The : is for specifying a range of values\nlast_five_words_of_first_line = l[0][-5:] # The : with no end means 'until the end'\n\nUnfortunately, the way to get the first 4 words of the first 2 lines is not this:\nfirst_four_words_of_first_two_lines = l[0:2][0:4] # DOESN'T WORK!!!\n\nThe reason for that is that the result of fetching a range of values from a list is a list, and so the [0:4] applies to that list instead. What you really mean to do is to apply the [0:4] to apply to each element of the resulting list to create a new list. Here is how you would do that:\nfirst_four_words_of_first_two_lines = [x[0:4] for x in l[0:2]]\n\nThat gives you a new list that looks like this (given the example for question 1):\n[('This', 'is', 'the', 'first'),\n ('This', 'is', 'the', 'second')]\n\n\nI hope that is helpful. As I said, I think your questions indicate some confusion about things. But I don't know what they indicate confusion about, so I just tried to answer them as best I could.\n"
] |
[
1,
0,
0,
0,
0
] |
[] |
[] |
[
"line",
"list",
"python",
"select"
] |
stackoverflow_0001908961_line_list_python_select.txt
|
Q:
Starting Python script without explicitly having X11 open
I had Python v2.3 on my system. When I wanted to run a Tkinter script I could just use
python myscript.py
I recently upgraded to Python 2.5 and now I need to have X11 running and the "DISPLAY" environment variable set before I can run any of my scripts. This is bad for me, because I can't distribute any scripts without explicitly stating "if you're running Python > v2.3, you will need to have X11 open before running this script". Is there a way around this? I'm on OS X Tiger.
A:
Install python2.5 or python2.6 for OS X from python.org. They use the native Aqua Tk and thus do not require X11 for IDLE or python scripts that use Tkinter.
A:
I have installed Python 2.6.4 and I haven't any problem at all running it without a $DISPLAY variable ...
I'm on linux ...
A:
If I had to guess (and I do...), it sounds like you installed an X11 based version of python and tkinter rather than one that uses the native windowing system on OSX. I think you can safely write your scripts without telling people they have to have X11 running. You merely have to say they have to have a proper environment set up -- either a native version of python+Tkinter or have X11 running and have an X11-based version of python+Tkinter
In other words, this isn't a regression in python that you have to code around, it's just a side effect of your particular installation of python.
|
Starting Python script without explicitly having X11 open
|
I had Python v2.3 on my system. When I wanted to run a Tkinter script I could just use
python myscript.py
I recently upgraded to Python 2.5 and now I need to have X11 running and the "DISPLAY" environment variable set before I can run any of my scripts. This is bad for me, because I can't distribute any scripts without explicitly stating "if you're running Python > v2.3, you will need to have X11 open before running this script". Is there a way around this? I'm on OS X Tiger.
|
[
"Install python2.5 or python2.6 for OS X from python.org. They use the native Aqua Tk and thus do not require X11 for IDLE or python scripts that use Tkinter.\n",
"I have installed Python 2.6.4 and I haven't any problem at all running it without a $DISPLAY variable ...\nI'm on linux ...\n",
"If I had to guess (and I do...), it sounds like you installed an X11 based version of python and tkinter rather than one that uses the native windowing system on OSX. I think you can safely write your scripts without telling people they have to have X11 running. You merely have to say they have to have a proper environment set up -- either a native version of python+Tkinter or have X11 running and have an X11-based version of python+Tkinter\nIn other words, this isn't a regression in python that you have to code around, it's just a side effect of your particular installation of python.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"macos",
"python",
"tkinter",
"x11"
] |
stackoverflow_0001905382_macos_python_tkinter_x11.txt
|
Q:
Integrate Python app into PHP site
This might sound really crazy, but still...
For our revamped project site, we want to integrate Trac (as code browser, developer wiki and issue tracker) into the site design. That is, of course, difficult, since Trac is written in Python and our site in PHP. Does anybody here know a way how to integrate a header and footer (PHP) into the Trac template (preferrably without invoking a - or rather two for header and footer - PHP process from the command line)?
A:
The best option probably is to (re)write the header and footer using python.
If the header and footer are relatively static you can also generate them once using php (or once every x minutes) and include them from the filesystem. (You probably already thought about this and dismissed the idea because your sites are too dynamic to use this option?)
While I would not really recommend it you could also use some form of AJAX to load parts of the page, and nothing prevents you from loading this content from a php based system. That could keep all parts dynamic. Your pages will probably look ugly while loading, and you now generate more hits on the server than needed, but if it is nog a big site this might be a big.
Warning: If you have user logins on both systems you will probably run into problems with people only being logged in to half of your site.
A:
Abstraction is your friend.
Isolate the raw HTML from your PHP in the header and footer in a simple templating language, if possible, and write Python and PHP interfaces to your templating language. Or, reuse the work that other people have done. This chart shows that Template Attribute Language (TAL) has Python and PHP5 support.
A:
Your Python code will have access to your users' cookies. A template would be best, but if you don't have one available (or the header/footer are trivially small, or whatever), you can simply port the PHP header and footer code to Python, using the cookies that are already there to query the database or whatever you need to do.
If you want to retain your links for logging in, registering, and whatever else might be in the PHP version, simply link to the PHP side, then redirect back to Trac once PHP's done its job.
|
Integrate Python app into PHP site
|
This might sound really crazy, but still...
For our revamped project site, we want to integrate Trac (as code browser, developer wiki and issue tracker) into the site design. That is, of course, difficult, since Trac is written in Python and our site in PHP. Does anybody here know a way how to integrate a header and footer (PHP) into the Trac template (preferrably without invoking a - or rather two for header and footer - PHP process from the command line)?
|
[
"The best option probably is to (re)write the header and footer using python.\nIf the header and footer are relatively static you can also generate them once using php (or once every x minutes) and include them from the filesystem. (You probably already thought about this and dismissed the idea because your sites are too dynamic to use this option?)\nWhile I would not really recommend it you could also use some form of AJAX to load parts of the page, and nothing prevents you from loading this content from a php based system. That could keep all parts dynamic. Your pages will probably look ugly while loading, and you now generate more hits on the server than needed, but if it is nog a big site this might be a big.\nWarning: If you have user logins on both systems you will probably run into problems with people only being logged in to half of your site.\n",
"Abstraction is your friend.\nIsolate the raw HTML from your PHP in the header and footer in a simple templating language, if possible, and write Python and PHP interfaces to your templating language. Or, reuse the work that other people have done. This chart shows that Template Attribute Language (TAL) has Python and PHP5 support.\n",
"Your Python code will have access to your users' cookies. A template would be best, but if you don't have one available (or the header/footer are trivially small, or whatever), you can simply port the PHP header and footer code to Python, using the cookies that are already there to query the database or whatever you need to do.\nIf you want to retain your links for logging in, registering, and whatever else might be in the PHP version, simply link to the PHP side, then redirect back to Trac once PHP's done its job.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"integration",
"php",
"python",
"trac"
] |
stackoverflow_0001907782_integration_php_python_trac.txt
|
Q:
Django date filter to output "am" or "A.M."
The Django date template filter takes the format character "a" for "a.m." and "A" for "AM". How do you get lower case without periods or upper case with the periods?
You can use lower and upper filters, but they will mess with month and day of the week formatting.
A:
Alternately you could inherit the base functionality and simply add the output you're looking for. (again with a custom filter).
Here's a custom template fitler which adds a new argument 'c' that will change (get it, c... change) the functional of a/A. It basically serves as a switch to toggle the functionality of a/A. That's hard to explain. Here's some examples:
{{ datetime|smartdate:"h:i A" }} = '12:30 AM'
{{ datetime|smartdate:"h:i Ac" }} = '12:30 A.M.'
{{ datetime|smartdate:"h:i a" }} = '12:30 a.m.'
{{ datetime|smartdate:"h:i ac" }} = '12:30 am'
And here's the filter...
import re
from django.template.defaultfilters import date as date_filter
# --------------------------------------------------------------------------------
# |smartdate:"date format" -- new arg 'c' (change) alteras the AM/pm appearance
# --------------------------------------------------------------------------------
@register.filter
def smartdate(value, arg):
rendered = date_filter(value, arg)
if 'c' in arg:
rendered = re.sub('(a|p)\.m\.c', lambda m: '%sm' % m.group(1), rendered)
rendered = re.sub('(A|P)Mc', lambda m: '%s.M.' % m.group(1), rendered)
return rendered
Edit -- Slightly optimized the filter
A:
you can create your own filter so your templates will look like this:
{{ value|date:"D d M Y" }} {{ value|meridiem:"u" }}
where meridiem could be:
def meridiem(value, arg="ld"):
if not value:
return u''
if 'u' in arg:
if 'd' in arg:
return 'A.M.'
return 'AM'
else:
if 'd' in arg:
return 'a.m.'
return 'am'
this is not really elegant but could be a simple solution. beware that i did not test the code.
A:
Best way would be to write a custom template filter.
Documentation here
|
Django date filter to output "am" or "A.M."
|
The Django date template filter takes the format character "a" for "a.m." and "A" for "AM". How do you get lower case without periods or upper case with the periods?
You can use lower and upper filters, but they will mess with month and day of the week formatting.
|
[
"Alternately you could inherit the base functionality and simply add the output you're looking for. (again with a custom filter).\nHere's a custom template fitler which adds a new argument 'c' that will change (get it, c... change) the functional of a/A. It basically serves as a switch to toggle the functionality of a/A. That's hard to explain. Here's some examples:\n{{ datetime|smartdate:\"h:i A\" }} = '12:30 AM'\n{{ datetime|smartdate:\"h:i Ac\" }} = '12:30 A.M.'\n{{ datetime|smartdate:\"h:i a\" }} = '12:30 a.m.'\n{{ datetime|smartdate:\"h:i ac\" }} = '12:30 am'\n\nAnd here's the filter...\nimport re\nfrom django.template.defaultfilters import date as date_filter\n\n# --------------------------------------------------------------------------------\n# |smartdate:\"date format\" -- new arg 'c' (change) alteras the AM/pm appearance\n# --------------------------------------------------------------------------------\n@register.filter\ndef smartdate(value, arg):\n rendered = date_filter(value, arg)\n if 'c' in arg:\n rendered = re.sub('(a|p)\\.m\\.c', lambda m: '%sm' % m.group(1), rendered)\n rendered = re.sub('(A|P)Mc', lambda m: '%s.M.' % m.group(1), rendered)\n return rendered\n\nEdit -- Slightly optimized the filter\n",
"you can create your own filter so your templates will look like this:\n{{ value|date:\"D d M Y\" }} {{ value|meridiem:\"u\" }}\n\nwhere meridiem could be:\ndef meridiem(value, arg=\"ld\"):\n if not value:\n return u''\n if 'u' in arg:\n if 'd' in arg:\n return 'A.M.'\n return 'AM'\n else:\n if 'd' in arg:\n return 'a.m.'\n return 'am'\n\nthis is not really elegant but could be a simple solution. beware that i did not test the code.\n",
"Best way would be to write a custom template filter.\nDocumentation here\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001905721_django_python.txt
|
Q:
C/Python Socket Performance?
my question simply relates to the difference in performance between a socket in C and in Python. Since my Python build is CPython, I assume it's similar, but I'm curious if someone actually has "real" benchmarks, or at least an opinion that's evidence based.
My logics is as such:
C socket much faster? then write a C
extension.
not/barely a difference?
keep writing in Python and figure out
how to obtain packet level control
(scapy? dpkt?)
I'm sure someone will want to know for either context or curiosity. I plan to build a sort of proxy for myself (not for internet browsing, anonymity, etc) and will bind the application I want to use with it to a specific port. Then, all packets on said port will be queued, address header modified, and then sent, etc, etc.
Thanks in advance.
A:
In general, sockets in Python perform just fine. For example, the reference implementation of the BitTorrent tracker server is written in Python.
When doing networking operations, the speed of the network is usually the limiting factor. That is, any possible tiny difference in speed between C and Python's socket code is completely overshadowed by the fact that you're doing networking of some kind.
However, your description of what you want to do indicates that you want to inspect and modify individual IP packets. This is beyond the capabilities of Python's standard networking libraries, and is in any case a very OS-dependent operation. Rather than asking "which is faster?" you will need to first ask "is this possible?"
A:
i would think C would be faster, but python would be a lot easier to manage and use.
the difference would be so small, you wouldn't need it unless you were trying to send masses amount of data (something stupid like 1 million gb/second lol)
joe
|
C/Python Socket Performance?
|
my question simply relates to the difference in performance between a socket in C and in Python. Since my Python build is CPython, I assume it's similar, but I'm curious if someone actually has "real" benchmarks, or at least an opinion that's evidence based.
My logics is as such:
C socket much faster? then write a C
extension.
not/barely a difference?
keep writing in Python and figure out
how to obtain packet level control
(scapy? dpkt?)
I'm sure someone will want to know for either context or curiosity. I plan to build a sort of proxy for myself (not for internet browsing, anonymity, etc) and will bind the application I want to use with it to a specific port. Then, all packets on said port will be queued, address header modified, and then sent, etc, etc.
Thanks in advance.
|
[
"In general, sockets in Python perform just fine. For example, the reference implementation of the BitTorrent tracker server is written in Python.\nWhen doing networking operations, the speed of the network is usually the limiting factor. That is, any possible tiny difference in speed between C and Python's socket code is completely overshadowed by the fact that you're doing networking of some kind.\nHowever, your description of what you want to do indicates that you want to inspect and modify individual IP packets. This is beyond the capabilities of Python's standard networking libraries, and is in any case a very OS-dependent operation. Rather than asking \"which is faster?\" you will need to first ask \"is this possible?\"\n",
"i would think C would be faster, but python would be a lot easier to manage and use.\nthe difference would be so small, you wouldn't need it unless you were trying to send masses amount of data (something stupid like 1 million gb/second lol)\njoe\n"
] |
[
13,
1
] |
[] |
[] |
[
"c",
"python",
"scapy",
"sockets"
] |
stackoverflow_0001909471_c_python_scapy_sockets.txt
|
Q:
Combine lxml XSLT pretty_print with strip-space
I'm cleaning up some gross XML, and so I've had pretty_print = True set in the call to etree.tostring() on my lxml output of the XSL transform. However, that left me with a few junk whitespace nodes from the original input, so I added
<xsl:strip-space elements="*"/>
...but that completely collapses all whitespace, ignoring pretty print. Is there an easy way to make strip-space just apply to the input, and still get lxml to apply pretty print?
A:
Do it in two steps? First strip the spaces, then pretty-print?
Just a thought.
|
Combine lxml XSLT pretty_print with strip-space
|
I'm cleaning up some gross XML, and so I've had pretty_print = True set in the call to etree.tostring() on my lxml output of the XSL transform. However, that left me with a few junk whitespace nodes from the original input, so I added
<xsl:strip-space elements="*"/>
...but that completely collapses all whitespace, ignoring pretty print. Is there an easy way to make strip-space just apply to the input, and still get lxml to apply pretty print?
|
[
"Do it in two steps? First strip the spaces, then pretty-print?\nJust a thought.\n"
] |
[
1
] |
[] |
[] |
[
"lxml",
"pretty_print",
"python",
"xml",
"xslt"
] |
stackoverflow_0001909401_lxml_pretty_print_python_xml_xslt.txt
|
Q:
Higher-performance method do this type of insert from python?
Given two arrays hashes and table, for each value in hashes I want to store the position of the element at the element's value's offset in the array table. Here is the naïve algorithm:
def insert_n(table,hashes):
for x in xrange(len(hashes)):
table[hashes[x]]=x
This is extremely slow. Psyco helps some here, but hardly.
Numpy has a solution:
numpy.insert(table,numpy.arange(len(hashes)),hashes)
But according to my benchmarks, this is still extremely slow for such a simple operation. Is there a faster way to perform this that can be used from python?
Some additional example code:
import numpy
from time import time
table_size=2**20
hashes_size=2**19
table=numpy.zeros(table_size,dtype=numpy.uint32)
hashes=numpy.fromstring(numpy.random.bytes((hashes_size)*4),
dtype=numpy.uint32)%table_size
t0=time()
numpy.insert(table,numpy.arange(len(hashes)),hashes)
print time()-t0
A:
This is fast and simple (assuming table and hashes are numpy.uint32 arrays):
table[hashes] = numpy.arange(len(hashes), dtype=numpy.uint32)
You may want to compare the speed with this:
table[hashes] = xrange(len(hashes))
By the way, numpy.insert does not do the same thing as the for-loop you posted.
|
Higher-performance method do this type of insert from python?
|
Given two arrays hashes and table, for each value in hashes I want to store the position of the element at the element's value's offset in the array table. Here is the naïve algorithm:
def insert_n(table,hashes):
for x in xrange(len(hashes)):
table[hashes[x]]=x
This is extremely slow. Psyco helps some here, but hardly.
Numpy has a solution:
numpy.insert(table,numpy.arange(len(hashes)),hashes)
But according to my benchmarks, this is still extremely slow for such a simple operation. Is there a faster way to perform this that can be used from python?
Some additional example code:
import numpy
from time import time
table_size=2**20
hashes_size=2**19
table=numpy.zeros(table_size,dtype=numpy.uint32)
hashes=numpy.fromstring(numpy.random.bytes((hashes_size)*4),
dtype=numpy.uint32)%table_size
t0=time()
numpy.insert(table,numpy.arange(len(hashes)),hashes)
print time()-t0
|
[
"This is fast and simple (assuming table and hashes are numpy.uint32 arrays):\ntable[hashes] = numpy.arange(len(hashes), dtype=numpy.uint32)\n\nYou may want to compare the speed with this:\ntable[hashes] = xrange(len(hashes))\n\nBy the way, numpy.insert does not do the same thing as the for-loop you posted.\n"
] |
[
2
] |
[] |
[] |
[
"algorithm",
"benchmarking",
"performance",
"python"
] |
stackoverflow_0001907911_algorithm_benchmarking_performance_python.txt
|
Q:
How does one feed a list of files into an app with appscript and Python?
Get your newb-shields up, I'm about to sprinkle you with some.
I'm trying to get Photoshop CS4 to open a folderful of JPEG images with AppScript+Python, which could be described like so in BASH:
#!/bin/bash
for F in `ls ~/Desktop/test`; do
open -a "Adobe Photoshop CS4" $F
# proceed to mutilate the image appearance
done
I'm failing at the ls ~/Desktop/test stage. I'd really like to ask Finder to list a folder for me, and feed the result into Photoshop one at a time to process them.
A JavaScript equivalent with Adobe's ExtendScript bridge would be:
#target photoshop
var folder = Folder("~/Desktop/test");
var images = folder.getFiles();
for (var i=0; i < images.length; i++) {
if (images[i] instanceof File && images[i].hidden == false) {
var doc = app.open(images[i]);
// do something to the image here
doc.close(SaveOptions.DONOTSAVECHANGES);
}
}
I can get me a document_file object with a horribly silly contraption like x = app('Finder').home.folders['Desktop']().folders['test']().items()[0], but that turns out to be a really silly object. Trying to app('Adobe Photoshop CS4').open(x) this object will throw an OSERROR: 1230, with a MESSAGE: File/Folder expected.
(Uh-oh, this document_file actually responds to URL(), so File.makewithurl(x.URL()) can be fed into open())
Ehm, having solved that, is there a way to actually do this by asking Finder for the list of files in a given folder, specified by a UNIX path?
A:
Photoshop's open command requires an alias object (or list of alias objects).
from appscript import *
folder = '/path/to/folder'
ps = app('Adobe Photoshop CS4')
for f in app('Finder').items[mactypes.Alias(folder)].files.get(resulttype=k.alias):
ps.open(f)
# do stuff here...
|
How does one feed a list of files into an app with appscript and Python?
|
Get your newb-shields up, I'm about to sprinkle you with some.
I'm trying to get Photoshop CS4 to open a folderful of JPEG images with AppScript+Python, which could be described like so in BASH:
#!/bin/bash
for F in `ls ~/Desktop/test`; do
open -a "Adobe Photoshop CS4" $F
# proceed to mutilate the image appearance
done
I'm failing at the ls ~/Desktop/test stage. I'd really like to ask Finder to list a folder for me, and feed the result into Photoshop one at a time to process them.
A JavaScript equivalent with Adobe's ExtendScript bridge would be:
#target photoshop
var folder = Folder("~/Desktop/test");
var images = folder.getFiles();
for (var i=0; i < images.length; i++) {
if (images[i] instanceof File && images[i].hidden == false) {
var doc = app.open(images[i]);
// do something to the image here
doc.close(SaveOptions.DONOTSAVECHANGES);
}
}
I can get me a document_file object with a horribly silly contraption like x = app('Finder').home.folders['Desktop']().folders['test']().items()[0], but that turns out to be a really silly object. Trying to app('Adobe Photoshop CS4').open(x) this object will throw an OSERROR: 1230, with a MESSAGE: File/Folder expected.
(Uh-oh, this document_file actually responds to URL(), so File.makewithurl(x.URL()) can be fed into open())
Ehm, having solved that, is there a way to actually do this by asking Finder for the list of files in a given folder, specified by a UNIX path?
|
[
"Photoshop's open command requires an alias object (or list of alias objects).\nfrom appscript import *\n\nfolder = '/path/to/folder'\n\nps = app('Adobe Photoshop CS4')\n\nfor f in app('Finder').items[mactypes.Alias(folder)].files.get(resulttype=k.alias):\n ps.open(f)\n # do stuff here...\n\n"
] |
[
3
] |
[] |
[] |
[
"applescript",
"finder",
"macos",
"python",
"sourceforge_appscript"
] |
stackoverflow_0001909282_applescript_finder_macos_python_sourceforge_appscript.txt
|
Q:
Read https url from Python with basic access authentication
How do you open https url in Python?
import urllib2
url = "https://user:password@domain.com/path/
f = urllib2.urlopen(url)
print f.read()
gives:
httplib.InvalidURL: nonnumeric port: 'password@domain.com'
A:
This has never failed me
import urllib2, base64
username = 'foo'
password = 'bar'
auth_encoded = base64.encodestring('%s:%s' % (username, password))[:-1]
req = urllib2.Request('https://somewebsite.com')
req.add_header('Authorization', 'Basic %s' % auth_encoded)
try:
response = urllib2.urlopen(req)
except urllib2.HTTPError, http_e:
# etc...
pass
A:
Please read about the urllib2 password manager and the basic authentication handler as well as the digest authentication handler.
http://docs.python.org/library/urllib2.html#abstractbasicauthhandler-objects
http://docs.python.org/library/urllib2.html#httpdigestauthhandler-objects
Your urllib2 script must actually provide enough information to do HTTP authentication. Usernames, Passwords, Domains, etc.
A:
If you want to pass username and password information to urllib2 you'll need to use an HTTPBasicAuthHandler.
Here's a tutorial showing you how to do it.
A:
You cannot pass credentials to urllib2.open like that. In your case, user is interpreted as the domain name, while password@domain.com is interpreted as the port number.
|
Read https url from Python with basic access authentication
|
How do you open https url in Python?
import urllib2
url = "https://user:password@domain.com/path/
f = urllib2.urlopen(url)
print f.read()
gives:
httplib.InvalidURL: nonnumeric port: 'password@domain.com'
|
[
"This has never failed me\nimport urllib2, base64\nusername = 'foo'\npassword = 'bar'\nauth_encoded = base64.encodestring('%s:%s' % (username, password))[:-1]\n\nreq = urllib2.Request('https://somewebsite.com')\nreq.add_header('Authorization', 'Basic %s' % auth_encoded)\ntry:\n response = urllib2.urlopen(req)\nexcept urllib2.HTTPError, http_e:\n # etc...\n pass\n\n",
"Please read about the urllib2 password manager and the basic authentication handler as well as the digest authentication handler.\nhttp://docs.python.org/library/urllib2.html#abstractbasicauthhandler-objects\nhttp://docs.python.org/library/urllib2.html#httpdigestauthhandler-objects\nYour urllib2 script must actually provide enough information to do HTTP authentication. Usernames, Passwords, Domains, etc.\n",
"If you want to pass username and password information to urllib2 you'll need to use an HTTPBasicAuthHandler.\nHere's a tutorial showing you how to do it.\n",
"You cannot pass credentials to urllib2.open like that. In your case, user is interpreted as the domain name, while password@domain.com is interpreted as the port number. \n"
] |
[
11,
5,
3,
2
] |
[] |
[] |
[
"authentication",
"https",
"passwords",
"python"
] |
stackoverflow_0001906977_authentication_https_passwords_python.txt
|
Q:
Python: List to integers
I have read a file in and converted each line into a list. A sample of the list looks like:
['15', '2', '0'], ['63', '3', '445', '456' '0'], ['23', '4', '0']
i want to retrieve the first number from each list and convert it to and integer so when i carry out the type function i.e.
type(x)
<type 'int'> is returned
Also when i print x the integers are printed individually rather than joined. i.e. if i took the first 3 numbers from the list above the numbers are not printed as:
156323
A:
To cast your ints:
my_ints = [int(l[0]) for l in your_list]
To print them out:
print "".join(map(str, my_ints))
A:
If you want a list with the first number of each list, [int(L[0]) for L in lines] (assuming the list of lists is called lines); if you want the first two numbers of each list (it's hard to tell from your question), [int(s) for L in lines for s in L[:2]]; and so forth.
If you don't want a list of such numbers, but just to do one iteration on them, you can use a generator expression, i.e.:
for number in (int(s) for L in lines for s in L[:2]):
...do something with number...
or an equivalent nested-loop approach such as:
for L in lines:
for s in L[:2]:
number = int(s)
...do something with number...
A:
# Converts all items in all lists to integers.
ls = [map(int, x) for x in the_first_list]
Or if you just want the first two items:
ls = [map(int, x[:2]) for x in the_first_list]
In python 3.x you'd have to also wrap the map in a list constructor, like this
ls = [list(map(int, x[:2])) ...
A:
If I understood your question correctly, it is [int x[0] for x in list_of_lists]
A:
lines = [['15', '2', '0'], ['63', '3', '445', '456' '0'], ['23', '4', '0']]
first_values_as_ints = [int(line[0]) for line in lines]
for x in first_values_as_ints:
print x,
|
Python: List to integers
|
I have read a file in and converted each line into a list. A sample of the list looks like:
['15', '2', '0'], ['63', '3', '445', '456' '0'], ['23', '4', '0']
i want to retrieve the first number from each list and convert it to and integer so when i carry out the type function i.e.
type(x)
<type 'int'> is returned
Also when i print x the integers are printed individually rather than joined. i.e. if i took the first 3 numbers from the list above the numbers are not printed as:
156323
|
[
"To cast your ints:\nmy_ints = [int(l[0]) for l in your_list]\n\nTo print them out:\nprint \"\".join(map(str, my_ints))\n\n",
"If you want a list with the first number of each list, [int(L[0]) for L in lines] (assuming the list of lists is called lines); if you want the first two numbers of each list (it's hard to tell from your question), [int(s) for L in lines for s in L[:2]]; and so forth.\nIf you don't want a list of such numbers, but just to do one iteration on them, you can use a generator expression, i.e.:\nfor number in (int(s) for L in lines for s in L[:2]):\n ...do something with number...\n\nor an equivalent nested-loop approach such as:\nfor L in lines:\n for s in L[:2]:\n number = int(s)\n ...do something with number...\n\n",
"# Converts all items in all lists to integers.\nls = [map(int, x) for x in the_first_list]\n\nOr if you just want the first two items:\nls = [map(int, x[:2]) for x in the_first_list]\n\nIn python 3.x you'd have to also wrap the map in a list constructor, like this\nls = [list(map(int, x[:2])) ...\n\n",
"If I understood your question correctly, it is [int x[0] for x in list_of_lists]\n",
"lines = [['15', '2', '0'], ['63', '3', '445', '456' '0'], ['23', '4', '0']]\nfirst_values_as_ints = [int(line[0]) for line in lines]\nfor x in first_values_as_ints:\n print x,\n\n"
] |
[
11,
3,
1,
0,
0
] |
[] |
[] |
[
"integer",
"list",
"python"
] |
stackoverflow_0001909619_integer_list_python.txt
|
Q:
ISO public Django apps developed Agile / BDD style with Doctest, Unitests and Selenium
I've found several blog posts where TDD/BDD is explained, but the examples are usually really basic. Usually they are just for Models. I want to see how people are really using BDD in Real Life.
I'd love be pointed towards some Django apps that were built test first style so I can learn from them.
I know that Rails had many examples, surely Django has a few examples too.
A:
Your likely doing it right already. For the moment, there's an ample amount of blog posts from Django developers where they talk about doing Django development right and how they solved issues with testing some heavy-duty stuff, but not a single resource that covers it all, especially not with employing TDD exclusively.
If your into reading other people's source code, I think your on the best track of learning how experienced Python and Django developers do their magic, manage, test and redistribute their code.
I'd suggest you make a commitment to hop over to GitHub, Bitbucket or Project Hosting on Google Code regularly and query for Django projects. It's great to get involved with something small that you can quickly sink your teeth into and really understand whats going on and maybe even go a step further and see how you can contribute.
Unfortunately, I'm not aware of there being any Django project that's distributed with documentation on how development is being performed. It's not really the wild wild west: there's versioned documentation, wishlists, issue trackers, TODOs, branches and tags that show the development timelines, but not exactly something that covers the whole process from thought to a full, clean realization.
And too, unfortunately, most books deal with developing Django applications without a set development methodology. I think that's only fair, because people have their own way of doing things and tools that work best for them and a book like that would need to be at least 2000 pages long to cover all the variables..
I personally like to try doing something myself and then learn by example from other people by looking on what they've done to address the same problem; I feel that gives me a full perspective with the rights, wrongs and whys of doing things. I recently decoupled an app from my project by using the contentypes framework and I wasn't all too comfortable on how my tests turned out. I then looked at the tests from django-tagging by James Bennett and saw where my thinking went awry and it really helped me a lot.
|
ISO public Django apps developed Agile / BDD style with Doctest, Unitests and Selenium
|
I've found several blog posts where TDD/BDD is explained, but the examples are usually really basic. Usually they are just for Models. I want to see how people are really using BDD in Real Life.
I'd love be pointed towards some Django apps that were built test first style so I can learn from them.
I know that Rails had many examples, surely Django has a few examples too.
|
[
"Your likely doing it right already. For the moment, there's an ample amount of blog posts from Django developers where they talk about doing Django development right and how they solved issues with testing some heavy-duty stuff, but not a single resource that covers it all, especially not with employing TDD exclusively.\nIf your into reading other people's source code, I think your on the best track of learning how experienced Python and Django developers do their magic, manage, test and redistribute their code.\nI'd suggest you make a commitment to hop over to GitHub, Bitbucket or Project Hosting on Google Code regularly and query for Django projects. It's great to get involved with something small that you can quickly sink your teeth into and really understand whats going on and maybe even go a step further and see how you can contribute.\nUnfortunately, I'm not aware of there being any Django project that's distributed with documentation on how development is being performed. It's not really the wild wild west: there's versioned documentation, wishlists, issue trackers, TODOs, branches and tags that show the development timelines, but not exactly something that covers the whole process from thought to a full, clean realization. \nAnd too, unfortunately, most books deal with developing Django applications without a set development methodology. I think that's only fair, because people have their own way of doing things and tools that work best for them and a book like that would need to be at least 2000 pages long to cover all the variables..\nI personally like to try doing something myself and then learn by example from other people by looking on what they've done to address the same problem; I feel that gives me a full perspective with the rights, wrongs and whys of doing things. I recently decoupled an app from my project by using the contentypes framework and I wasn't all too comfortable on how my tests turned out. I then looked at the tests from django-tagging by James Bennett and saw where my thinking went awry and it really helped me a lot.\n"
] |
[
3
] |
[] |
[] |
[
"agile",
"bdd",
"django",
"python",
"tdd"
] |
stackoverflow_0001909674_agile_bdd_django_python_tdd.txt
|
Q:
Is it possible to use functions before declaring their body in python?
Is there any way to make possible to use functions in your file before you actually declare their body?
The following code doesn't seem to work:
abc = myFunction
def myFunction():
print "123"
Thanks
A:
You can't use the myFunction variable before it's assigned. Your example code is similar to:
def myFunction():
print abc
abc = 123
To do what you want, either re-arrange the order:
def myFunction():
print "123"
abc = myFunction
Or declare abc as just a proxy:
# Style 1
abc = lambda: myFunction()
# Style 2
def abc():
return myFunction()
def myFunction():
print "123"
If your function takes parameters, use *args and **kwargs:
# Style 1
abc = lambda *args, **kwargs: myFunction(*args, **kwargs)
# Style 2
def abc(*args, **kwargs):
return myFunction(*args, **kwargs)
def myFunction(x):
print x
A:
You can declare functions that use forward declarations, but Python executes the code in your source from top to bottom. So, this would compile and run:
def foo():
print "in foo"
bar()
def bar():
print "in bar"
foo()
foo()
(except it would cause a stack overflow at runtime, of course). In your example, Python is executing the line
abc = myFunction
before myFunction is defined as anything. You could think of this in terms of typing your source code interactively into the interpreter. When you type in your assignment, you wouldn't have even typed in the definition of myFunction yet, so Python wouldn't be able to refer to it.
Another way to look at this might be the following:
>>> myFunction = "hello"
>>> abc = myFunction
>>> def myFunction():
... print "there"
...
>>> abc
'hello'
>>> myFunction
<function myFunction at 0x63270>
>>> myFunction()
there
As you can see, the definition of the myFunction function just changes the binding of the symbol myFunction to a function object.
A:
short answer is no.
In Python, statements are evaluated along as they are parsed - myFunction wasn't parsed so Python doesn't know about it.
A:
You can declare an empty function, use it to set attributes or anything like this, and then modify its code later.
def myFunction():
pass
myFunction.foo = 'bar'
def makeFunction(obj):
def myFunction():
print "123"
f = myFunction
for attr in dir(obj):
if attr not in dir(f):
setattr(f, attr, getattr(obj, attr))
return f
myFunction = makeFunction(myFunction)
myFunction()
print myFunction.foo
A:
Python will raise a NameError as it encounters any reference to any name (token that's a valid variable/class/function/object name) for which there was no previous binding.
The Python interpreter executes the source code of a file as it reads it. Thus def foo(): is actually statement which defines foo() as the code is being loaded.
It's easy to think that forward references are supported. Consider this:
def foo():
return abc
abc="FooBar, Dude"
print foo()
... and you'll see that it can be run without issues. It's best to think of the definition of foo() as being quoted. The contents aren't evaluated until the function is invoked. So the NameError isn't raised (so long as some value has been bound to the name "abc" before the call to the function.
Notice that some of these semantics are sufficiently different than those from languages like Java, C/C++, and Perl that Pythonistas often prefer to use slightly different terminology. Variables and such are called "names" and the process of associating those with values (or, more generally, objects) is referred to as "binding." So instead of "assigning values to variables" you are "binding objects to names."
Informally names, especially for simple numeric or string objects, are called "variables" and statements such as x='foo' are referred to as assignments. The semantics are usually similar enough that we won't care.
|
Is it possible to use functions before declaring their body in python?
|
Is there any way to make possible to use functions in your file before you actually declare their body?
The following code doesn't seem to work:
abc = myFunction
def myFunction():
print "123"
Thanks
|
[
"You can't use the myFunction variable before it's assigned. Your example code is similar to:\ndef myFunction():\n print abc\n abc = 123\n\nTo do what you want, either re-arrange the order:\ndef myFunction():\n print \"123\"\n\nabc = myFunction\n\nOr declare abc as just a proxy:\n# Style 1\nabc = lambda: myFunction()\n\n# Style 2\ndef abc():\n return myFunction()\n\ndef myFunction():\n print \"123\"\n\nIf your function takes parameters, use *args and **kwargs:\n# Style 1\nabc = lambda *args, **kwargs: myFunction(*args, **kwargs)\n\n# Style 2\ndef abc(*args, **kwargs):\n return myFunction(*args, **kwargs)\n\ndef myFunction(x):\n print x\n\n",
"You can declare functions that use forward declarations, but Python executes the code in your source from top to bottom. So, this would compile and run:\ndef foo():\n print \"in foo\"\n bar()\n\ndef bar():\n print \"in bar\"\n foo()\n\nfoo()\n\n(except it would cause a stack overflow at runtime, of course). In your example, Python is executing the line\nabc = myFunction\n\nbefore myFunction is defined as anything. You could think of this in terms of typing your source code interactively into the interpreter. When you type in your assignment, you wouldn't have even typed in the definition of myFunction yet, so Python wouldn't be able to refer to it.\nAnother way to look at this might be the following:\n>>> myFunction = \"hello\"\n>>> abc = myFunction\n>>> def myFunction():\n... print \"there\"\n... \n>>> abc\n'hello'\n>>> myFunction\n<function myFunction at 0x63270>\n>>> myFunction()\nthere\n\nAs you can see, the definition of the myFunction function just changes the binding of the symbol myFunction to a function object.\n",
"short answer is no.\nIn Python, statements are evaluated along as they are parsed - myFunction wasn't parsed so Python doesn't know about it.\n",
"You can declare an empty function, use it to set attributes or anything like this, and then modify its code later.\ndef myFunction():\n pass\n\nmyFunction.foo = 'bar'\n\ndef makeFunction(obj):\n def myFunction():\n print \"123\"\n\n f = myFunction\n for attr in dir(obj):\n if attr not in dir(f):\n setattr(f, attr, getattr(obj, attr))\n\n return f\n\n\nmyFunction = makeFunction(myFunction)\nmyFunction()\nprint myFunction.foo\n\n",
"Python will raise a NameError as it encounters any reference to any name (token that's a valid variable/class/function/object name) for which there was no previous binding.\nThe Python interpreter executes the source code of a file as it reads it. Thus def foo(): is actually statement which defines foo() as the code is being loaded.\nIt's easy to think that forward references are supported. Consider this:\ndef foo():\n return abc\n\nabc=\"FooBar, Dude\"\n\nprint foo()\n\n... and you'll see that it can be run without issues. It's best to think of the definition of foo() as being quoted. The contents aren't evaluated until the function is invoked. So the NameError isn't raised (so long as some value has been bound to the name \"abc\" before the call to the function.\nNotice that some of these semantics are sufficiently different than those from languages like Java, C/C++, and Perl that Pythonistas often prefer to use slightly different terminology. Variables and such are called \"names\" and the process of associating those with values (or, more generally, objects) is referred to as \"binding.\" So instead of \"assigning values to variables\" you are \"binding objects to names.\"\nInformally names, especially for simple numeric or string objects, are called \"variables\" and statements such as x='foo' are referred to as assignments. The semantics are usually similar enough that we won't care.\n"
] |
[
21,
13,
1,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001909325_python.txt
|
Q:
Dynamically build and return a Python list in a C Python extension
I'm writing a Python extension in C, and I'm trying to figure out how to dynamically build and return a Python list using my extension. I know how to build a list of predetermined size using Py_BuildValue. Is there a way to create a list with Py_BuildValue then append items to that list? Is there a different, and better, alternative?
A:
How about using PyList_Append, just like (modulo reference management and whatnot) you'd use .append in Python?
Looking at the list API docs may help as well.
|
Dynamically build and return a Python list in a C Python extension
|
I'm writing a Python extension in C, and I'm trying to figure out how to dynamically build and return a Python list using my extension. I know how to build a list of predetermined size using Py_BuildValue. Is there a way to create a list with Py_BuildValue then append items to that list? Is there a different, and better, alternative?
|
[
"How about using PyList_Append, just like (modulo reference management and whatnot) you'd use .append in Python?\nLooking at the list API docs may help as well.\n"
] |
[
4
] |
[] |
[] |
[
"cextension",
"cpython",
"python"
] |
stackoverflow_0001910258_cextension_cpython_python.txt
|
Q:
facebook app in python showing file list
i am making a facebook app in python with django. now i have successfully resolved the callback url to my localhost account. but the app is not displaying on facebook.
when i navigate to apps.facebook.com/'myappname', it authenticates and then displays the file list on project folder?
A:
Based on your comments, I think I see what's going on. 192.168.2.2 is not a valid URL. That is a local network IP, and cannot be accessed from outside your network.
You need to set your Canvas Callback URL to the external IP address of your modem.
|
facebook app in python showing file list
|
i am making a facebook app in python with django. now i have successfully resolved the callback url to my localhost account. but the app is not displaying on facebook.
when i navigate to apps.facebook.com/'myappname', it authenticates and then displays the file list on project folder?
|
[
"Based on your comments, I think I see what's going on. 192.168.2.2 is not a valid URL. That is a local network IP, and cannot be accessed from outside your network.\nYou need to set your Canvas Callback URL to the external IP address of your modem.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"facebook",
"python"
] |
stackoverflow_0001910131_django_facebook_python.txt
|
Q:
Parsing XML to a hash table
I have an XML file in the following format:
<doc>
<id name="X">
<type name="A">
<min val="100" id="80"/>
<max val="200" id="90"/>
</type>
<type name="B">
<min val="100" id="20"/>
<max val="20" id="90"/>
</type>
</id>
<type...>
</type>
</doc>
I would like to parse this document and build a hash table
{X: {"A": [(100,80), (200,90)], "B": [(100,20), (20,90)]}, Y: .....}
How would I do this in Python?
A:
I disagree with the suggestion in other answers to use minidom -- that's a so-so Python adaptation of a standard originally conceived for other languages, usable but not a great fit. The recommended approach in modern Python is ElementTree.
The same interface is also implemented, faster, in third party module lxml, but unless you need blazing speed the version included with the Python standard library is fine (and faster than minidom anyway) -- the key point is to program to that interface, then you can always switch to a different implementation of the same interface in the future if you want to, with minimal changes to your own code.
For example, after the needed imports &c, the following code is a minimal implementation of your example (it does not verify that the XML is correct, just extracts the data assuming correctness -- adding various kinds of checks is pretty easy of course):
from xml.etree import ElementTree as et # or, import any other, faster version of ET
def xml2data(xmlfile):
tree = et.parse(xmlfile)
data = {}
for anid in tree.getroot().getchildren():
currdict = data[anid.get('name')] = {}
for atype in anid.getchildren():
currlist = currdict[atype.get('name')] = []
for c in atype.getchildren():
currlist.append((c.get('val'), c.get('id')))
return data
This produces your desired result given your sample input.
A:
Do not reinvent the wheel. Use Amara toolkit.
Variable names are just keys in a dictionary anyway.
http://www.xml3k.org/Amara
A:
I would recommend using the minidom library.
The docs are pretty good so you should be up and running in no time.
Dan.
A:
As others have stated minidom is the way to go here. You open (and parse) the file, while going through the nodes you check if its relevant and should be read. That way, you also know if you want to read the child nodes.
Threw together this, seems to do what you want. Some of the values are read by attribute position rather than attribute name. And theres no error handling. And the print () at the end means its Python 3.x.
I'll leave it as an exercise to improve upon that, just wanted to post a snippet to get you started.
Happy hacking! :)
xml.txt
<doc>
<id name="X">
<type name="A">
<min val="100" id="80"/>
<max val="200" id="90"/>
</type>
<type name="B">
<min val="100" id="20"/>
<max val="20" id="90"/>
</type>
</id>
</doc>
parsexml.py
from xml.dom import minidom
data={}
doc=minidom.parse("xml.txt")
for n in doc.childNodes[0].childNodes:
if n.localName=="id":
id_name = n.attributes.item(0).nodeValue
data[id_name] = {}
for j in n.childNodes:
if j.localName=="type":
type_name = j.attributes.item(0).nodeValue
data[id_name][type_name] = [(),()]
for k in j.childNodes:
if k.localName=="min":
data[id_name][type_name][0] = \
(k.attributes.item(1).nodeValue, \
k.attributes.item(0).nodeValue)
if k.localName=="max":
data[id_name][type_name][1] = \
(k.attributes.item(1).nodeValue, \
k.attributes.item(0).nodeValue)
print (data)
Output:
{'X': {'A': [('100', '80'), ('200', '90')], 'B': [('100', '20'), ('20', '90')]}}
A:
Another XML parsing library: http://www.crummy.com/software/BeautifulSoup/
Parsing XML documentation starts here: http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20XML
A:
Why not try something like the PyXml library. They have lots of documentation and tutorials.
|
Parsing XML to a hash table
|
I have an XML file in the following format:
<doc>
<id name="X">
<type name="A">
<min val="100" id="80"/>
<max val="200" id="90"/>
</type>
<type name="B">
<min val="100" id="20"/>
<max val="20" id="90"/>
</type>
</id>
<type...>
</type>
</doc>
I would like to parse this document and build a hash table
{X: {"A": [(100,80), (200,90)], "B": [(100,20), (20,90)]}, Y: .....}
How would I do this in Python?
|
[
"I disagree with the suggestion in other answers to use minidom -- that's a so-so Python adaptation of a standard originally conceived for other languages, usable but not a great fit. The recommended approach in modern Python is ElementTree.\nThe same interface is also implemented, faster, in third party module lxml, but unless you need blazing speed the version included with the Python standard library is fine (and faster than minidom anyway) -- the key point is to program to that interface, then you can always switch to a different implementation of the same interface in the future if you want to, with minimal changes to your own code.\nFor example, after the needed imports &c, the following code is a minimal implementation of your example (it does not verify that the XML is correct, just extracts the data assuming correctness -- adding various kinds of checks is pretty easy of course):\nfrom xml.etree import ElementTree as et # or, import any other, faster version of ET\n\ndef xml2data(xmlfile):\n tree = et.parse(xmlfile)\n data = {}\n for anid in tree.getroot().getchildren():\n currdict = data[anid.get('name')] = {}\n for atype in anid.getchildren():\n currlist = currdict[atype.get('name')] = []\n for c in atype.getchildren():\n currlist.append((c.get('val'), c.get('id')))\n return data\n\nThis produces your desired result given your sample input.\n",
"Do not reinvent the wheel. Use Amara toolkit.\nVariable names are just keys in a dictionary anyway.\nhttp://www.xml3k.org/Amara\n",
"I would recommend using the minidom library.\nThe docs are pretty good so you should be up and running in no time.\nDan.\n",
"As others have stated minidom is the way to go here. You open (and parse) the file, while going through the nodes you check if its relevant and should be read. That way, you also know if you want to read the child nodes.\nThrew together this, seems to do what you want. Some of the values are read by attribute position rather than attribute name. And theres no error handling. And the print () at the end means its Python 3.x.\nI'll leave it as an exercise to improve upon that, just wanted to post a snippet to get you started.\nHappy hacking! :)\nxml.txt\n<doc>\n<id name=\"X\">\n <type name=\"A\">\n <min val=\"100\" id=\"80\"/>\n <max val=\"200\" id=\"90\"/>\n </type>\n <type name=\"B\">\n <min val=\"100\" id=\"20\"/>\n <max val=\"20\" id=\"90\"/>\n </type>\n</id>\n</doc>\n\nparsexml.py\nfrom xml.dom import minidom\ndata={}\ndoc=minidom.parse(\"xml.txt\")\nfor n in doc.childNodes[0].childNodes:\n if n.localName==\"id\":\n id_name = n.attributes.item(0).nodeValue\n data[id_name] = {}\n for j in n.childNodes:\n if j.localName==\"type\":\n type_name = j.attributes.item(0).nodeValue\n data[id_name][type_name] = [(),()]\n for k in j.childNodes:\n if k.localName==\"min\":\n data[id_name][type_name][0] = \\\n (k.attributes.item(1).nodeValue, \\\n k.attributes.item(0).nodeValue)\n if k.localName==\"max\":\n data[id_name][type_name][1] = \\\n (k.attributes.item(1).nodeValue, \\\n k.attributes.item(0).nodeValue)\nprint (data)\n\nOutput:\n{'X': {'A': [('100', '80'), ('200', '90')], 'B': [('100', '20'), ('20', '90')]}}\n\n",
"Another XML parsing library: http://www.crummy.com/software/BeautifulSoup/\n\nParsing XML documentation starts here: http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20XML\n\n",
"Why not try something like the PyXml library. They have lots of documentation and tutorials.\n"
] |
[
12,
3,
2,
2,
1,
0
] |
[] |
[] |
[
"dom",
"python",
"xml"
] |
stackoverflow_0001908410_dom_python_xml.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.