content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
|---|---|---|---|---|---|---|---|---|
Q:
python instance variables as optional arguments
In python, is there a way I can use instance variables as optional arguments in a class method? ie:
def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
# do stuff....
Any help would be appreciated.
A:
Try this:
def foo(self, blah=None):
if blah is None: # faster than blah == None - thanks to kcwu
blah = self.instance_var
A:
All the responses suggesting None are correct; if you want to make sure a caller can pass None as a regular argument, use a special sentinel and test with is:
class Foo(object):
__default = object()
def foo(self, blah=Foo.__default):
if blah is Foo.__default: blah = self.instavar
Each call to object() makes a unique object, such that is will never succeed between it and any other value. The two underscores in __default mean "strongly private", meaning that callers know they shouldn't try to mess with it (and would need quite some work to do so, explicitly imitating the name mangling that the compiler is doing).
The reason you can't just use the code you posted, btw, is that default values evaluate when the def statement evaluates, not later at call time; and at the time def evaluates, there is as yet no self from which to take the instance variable.
A:
no, because the instance doesn't exist when class function definition time
You have to rewrite as following
def function(self, arg1=val1, arg2=val2, arg3=None):
if arg3 is None:
arg3 = self.instance_var
This is slightly different to original one: you cannot pass arg3 with None value if you really want.
Alternative solution:
def function(self, arg1=val1, arg2=val2, **argd):
arg3 = argd.get('arg3', self.instance_var)
A:
def foo(self, blah=None):
blah = blah if not blah is None else self.instance_var
This works with python 2.5 and forwards and handles the cases where blah is empty strings, lists and so on.
|
python instance variables as optional arguments
|
In python, is there a way I can use instance variables as optional arguments in a class method? ie:
def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
# do stuff....
Any help would be appreciated.
|
[
"Try this:\ndef foo(self, blah=None):\n if blah is None: # faster than blah == None - thanks to kcwu\n blah = self.instance_var\n\n",
"All the responses suggesting None are correct; if you want to make sure a caller can pass None as a regular argument, use a special sentinel and test with is:\nclass Foo(object):\n __default = object()\n def foo(self, blah=Foo.__default):\n if blah is Foo.__default: blah = self.instavar\n\nEach call to object() makes a unique object, such that is will never succeed between it and any other value. The two underscores in __default mean \"strongly private\", meaning that callers know they shouldn't try to mess with it (and would need quite some work to do so, explicitly imitating the name mangling that the compiler is doing).\nThe reason you can't just use the code you posted, btw, is that default values evaluate when the def statement evaluates, not later at call time; and at the time def evaluates, there is as yet no self from which to take the instance variable.\n",
"no, because the instance doesn't exist when class function definition time\nYou have to rewrite as following\ndef function(self, arg1=val1, arg2=val2, arg3=None):\n if arg3 is None:\n arg3 = self.instance_var\n\nThis is slightly different to original one: you cannot pass arg3 with None value if you really want.\nAlternative solution:\ndef function(self, arg1=val1, arg2=val2, **argd):\n arg3 = argd.get('arg3', self.instance_var)\n\n",
"def foo(self, blah=None):\n blah = blah if not blah is None else self.instance_var\n\nThis works with python 2.5 and forwards and handles the cases where blah is empty strings, lists and so on.\n"
] |
[
16,
5,
2,
0
] |
[
"An alternative way of doing this would be:\ndef foo(self, blah=None):\n blah = blah or self.instance_var\n\nThis shorter version looks better, specially when there is more than one optional argument.\nUse with care. See the comments below...\n"
] |
[
-1
] |
[
"class",
"function",
"python"
] |
stackoverflow_0000867115_class_function_python.txt
|
Q:
Implementation of an async method in Python DBus
How do I implement an async method in Python DBus? An Example below:
class LastfmApi(dbus.service.Object):
def __init__(self):
bus_name = dbus.service.BusName('fm.lastfm.api', bus=dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/')
@dbus.service.method('fm.last.api.account', out_signature="s")
def getUsername(self):
## How do I get this method done asynchronously ??
## For example, this method should go off and retrieve the "username"
## asynchronously. When this method returns, the "username" isn't available
## immediately but will be made available at a later time.
I am using Twisted's glib2 reactor.
Update: I know this behavior is possible to implement - DBus includes a "serial" (unique identifier) to method calls and the called method has access to this identifier in order to match "calls" with "replies".
A:
I haven't tried this, but reading the documentation for dbus.service.method reveals the async_callbacks parameter. It sounds like one uses this parameter to provide an asynchronous result. For example:
@dbus.service.method('fm.last.api.account', out_signature="s",
async_callbacks=("callback", "errback"))
def getUsername(self, callback, errback):
reactor.callLater(3, callback, "alice")
If, instead, you have an API which returned a Deferred, then you can easily associate the Deferred with these callbacks:
d.addCallbacks(callback, errback)
As far as the correlation between call and response goes, I assume that all the serial number handling is hidden inside dbus.service.method. I suspect that the callback and errback functions that are passed in when you use the async_callbacks feature are either instances of some class which is callable and has the serial number as an attribute, or else are defined as nested functions and close over the serial number. This way, when you call one of them, they can make sure to pass the right value back to the connection to associate the response with the original request.
However, that's just a slightly educated guess based on your mention of serial numbers and my experience with implementing various async systems. :) A read of the implementation of dbus.service.method would probably reveal the actual strategy without too much pain.
(Okay, I actually went and looked at the implementation now, and unfortunately it's rather complicated, and I lost the trail when it got to some code that's defined in the C-level dbus bindings, which is a bit more digging than I'm interested in doing. I still suspect the general idea I described above is correct, but the details of the implementation are more involved than I expected.)
|
Implementation of an async method in Python DBus
|
How do I implement an async method in Python DBus? An Example below:
class LastfmApi(dbus.service.Object):
def __init__(self):
bus_name = dbus.service.BusName('fm.lastfm.api', bus=dbus.SessionBus())
dbus.service.Object.__init__(self, bus_name, '/')
@dbus.service.method('fm.last.api.account', out_signature="s")
def getUsername(self):
## How do I get this method done asynchronously ??
## For example, this method should go off and retrieve the "username"
## asynchronously. When this method returns, the "username" isn't available
## immediately but will be made available at a later time.
I am using Twisted's glib2 reactor.
Update: I know this behavior is possible to implement - DBus includes a "serial" (unique identifier) to method calls and the called method has access to this identifier in order to match "calls" with "replies".
|
[
"I haven't tried this, but reading the documentation for dbus.service.method reveals the async_callbacks parameter. It sounds like one uses this parameter to provide an asynchronous result. For example:\n@dbus.service.method('fm.last.api.account', out_signature=\"s\",\n async_callbacks=(\"callback\", \"errback\"))\ndef getUsername(self, callback, errback):\n reactor.callLater(3, callback, \"alice\")\n\nIf, instead, you have an API which returned a Deferred, then you can easily associate the Deferred with these callbacks:\nd.addCallbacks(callback, errback)\n\nAs far as the correlation between call and response goes, I assume that all the serial number handling is hidden inside dbus.service.method. I suspect that the callback and errback functions that are passed in when you use the async_callbacks feature are either instances of some class which is callable and has the serial number as an attribute, or else are defined as nested functions and close over the serial number. This way, when you call one of them, they can make sure to pass the right value back to the connection to associate the response with the original request.\nHowever, that's just a slightly educated guess based on your mention of serial numbers and my experience with implementing various async systems. :) A read of the implementation of dbus.service.method would probably reveal the actual strategy without too much pain.\n(Okay, I actually went and looked at the implementation now, and unfortunately it's rather complicated, and I lost the trail when it got to some code that's defined in the C-level dbus bindings, which is a bit more digging than I'm interested in doing. I still suspect the general idea I described above is correct, but the details of the implementation are more involved than I expected.)\n"
] |
[
6
] |
[] |
[] |
[
"asynchronous",
"dbus",
"python",
"twisted"
] |
stackoverflow_0002142115_asynchronous_dbus_python_twisted.txt
|
Q:
How can you search Github project Network for unmerged commits to a particular file?
I'm working on a project that is hosted @ Github.com
It seems that forum/models.py has some errors in it that are preventing me from syncdb.
I was curious if there was a way to search through the network to find all the changes that had been made in the entire Branch Network to forum/models.py to see if someone had fixed the errors already.
this is the Project:
http://github.com/cnprog/CNPROG/network
These branches have not been merged into the main project yet.
A:
The closest thing I can think of is to do something like the following:
git log branch1 branch2 branch3 -- forum/models.py
where branch1 etc. are the various branches, which you would need local copies of.
A:
I contacted Github:
There isn't a search for unmerged commits, but if you hit the forkqueue you'll get a nice list of unmerged commits.
Assuming that people wrote good commit messages, you might be able to find the fix there if it exists.
For other projects the forkqueue URL would be:
http://github.com/project_name/project_name/forkqueue
A:
Take a look at these:
Git history commands
HIH
...richie
A:
May be 'git blame' can help you, if you know a line where error is located.
git blame manual
|
How can you search Github project Network for unmerged commits to a particular file?
|
I'm working on a project that is hosted @ Github.com
It seems that forum/models.py has some errors in it that are preventing me from syncdb.
I was curious if there was a way to search through the network to find all the changes that had been made in the entire Branch Network to forum/models.py to see if someone had fixed the errors already.
this is the Project:
http://github.com/cnprog/CNPROG/network
These branches have not been merged into the main project yet.
|
[
"The closest thing I can think of is to do something like the following:\ngit log branch1 branch2 branch3 -- forum/models.py\n\nwhere branch1 etc. are the various branches, which you would need local copies of.\n",
"I contacted Github:\nThere isn't a search for unmerged commits, but if you hit the forkqueue you'll get a nice list of unmerged commits.\nAssuming that people wrote good commit messages, you might be able to find the fix there if it exists.\nFor other projects the forkqueue URL would be:\nhttp://github.com/project_name/project_name/forkqueue\n",
"Take a look at these:\nGit history commands\nHIH\n...richie\n",
"May be 'git blame' can help you, if you know a line where error is located.\ngit blame manual\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"git",
"github",
"python"
] |
stackoverflow_0002140756_git_github_python.txt
|
Q:
Convert google search results into json in python 3.1
I am writing a Python program that feeds a search term to google using the google search API and downloads the first 10 results. I was able to do this in Python 2.6 as follows:
query = urllib.parse.urlencode({'q' : 'searchterm','start' : k},doseq=false)
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
% (query)
results = urllib.urlopen(url)
resultsjson = json.loads(results.read())
betterResults += resultsjson["responseData"]["results"]
Google's search API returns the results as a json, so I used the above code to download the results into a json of my and parse them into a list (betterResults).
When I switched over to Python 3, my program began throwing exceptions. Apparently, in Python 2.6 the object returned by urlopen() is a file-like object that can be loaded into a json. In Python 3.1, the object returned is an HTTPResponse object, which does contain a read() method, as required by the json specifications, but is a byte object. I was therefore unable to access the information as I had in 2.6.
Is there any way to access the json returned by google? How can I get the results in Python 3 and be able to select which fields I want, as I was able to do with the json?
Thank you very much,
bsg
A:
You'll need to decode the byte object if you want to use it with json.loads
resultjson = json.loads(results.read().decode())
docs also suggest to pass encoding parameter to the loads function:
json.loads(results.read(), encoding=<encoding-type>)
I think Lennart has an explanation how to get the encoding-type.
A:
The object returned by urlopen is file like, you are wrong there. But you use json.loads(), which expects a string. json.load() expects a file like object.
However, json.load() expects the result of the read() method to be a string, while of course the read you get will be bytes, so you need to decode it from bytes to a string first.
So, something like this:
query = urllib.parse.urlencode({'q' : 'searchterm','start' : k},doseq=false)
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
% (query)
results = urllib.urlopen(url)
encoding = input.getheader('content-type').split('=')[-1]
resultsjson = json.loads(results.read().decode(encoding))
betterResults += resultsjson["responseData"]["results"]
Might work. (I didn't test it).
|
Convert google search results into json in python 3.1
|
I am writing a Python program that feeds a search term to google using the google search API and downloads the first 10 results. I was able to do this in Python 2.6 as follows:
query = urllib.parse.urlencode({'q' : 'searchterm','start' : k},doseq=false)
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \
% (query)
results = urllib.urlopen(url)
resultsjson = json.loads(results.read())
betterResults += resultsjson["responseData"]["results"]
Google's search API returns the results as a json, so I used the above code to download the results into a json of my and parse them into a list (betterResults).
When I switched over to Python 3, my program began throwing exceptions. Apparently, in Python 2.6 the object returned by urlopen() is a file-like object that can be loaded into a json. In Python 3.1, the object returned is an HTTPResponse object, which does contain a read() method, as required by the json specifications, but is a byte object. I was therefore unable to access the information as I had in 2.6.
Is there any way to access the json returned by google? How can I get the results in Python 3 and be able to select which fields I want, as I was able to do with the json?
Thank you very much,
bsg
|
[
"You'll need to decode the byte object if you want to use it with json.loads\nresultjson = json.loads(results.read().decode())\n\ndocs also suggest to pass encoding parameter to the loads function:\njson.loads(results.read(), encoding=<encoding-type>)\n\nI think Lennart has an explanation how to get the encoding-type.\n",
"The object returned by urlopen is file like, you are wrong there. But you use json.loads(), which expects a string. json.load() expects a file like object.\nHowever, json.load() expects the result of the read() method to be a string, while of course the read you get will be bytes, so you need to decode it from bytes to a string first.\nSo, something like this:\nquery = urllib.parse.urlencode({'q' : 'searchterm','start' : k},doseq=false)\nurl = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \\\n % (query)\nresults = urllib.urlopen(url)\nencoding = input.getheader('content-type').split('=')[-1]\nresultsjson = json.loads(results.read().decode(encoding))\nbetterResults += resultsjson[\"responseData\"][\"results\"]\n\nMight work. (I didn't test it).\n"
] |
[
2,
1
] |
[] |
[] |
[
"google_search_api",
"httpresponse",
"json",
"python"
] |
stackoverflow_0002143206_google_search_api_httpresponse_json_python.txt
|
Q:
How do I get the "Interests" of a facebook user uing Facebook Connect? (I'm using Django/python and pyFacebook middleware)
def index(request):
fbdata = []
if request.facebook.check_session(request):
fbdata = request.facebook.users.getInfo(request.facebook.uid, ['name', 'pic'])
print fbdata
This works! I am able to get the user's picture and name.
However...I'd like to get the interests of that user. How can I do that?
By the way, I installed pyfacebook middleware on Django/python.
A:
Add "interests" in the fields you want to fetch, like this:
fbdata = request.facebook.users.getInfo(request.facebook.uid,
['name', 'pic', 'interests'])
|
How do I get the "Interests" of a facebook user uing Facebook Connect? (I'm using Django/python and pyFacebook middleware)
|
def index(request):
fbdata = []
if request.facebook.check_session(request):
fbdata = request.facebook.users.getInfo(request.facebook.uid, ['name', 'pic'])
print fbdata
This works! I am able to get the user's picture and name.
However...I'd like to get the interests of that user. How can I do that?
By the way, I installed pyfacebook middleware on Django/python.
|
[
"Add \"interests\" in the fields you want to fetch, like this:\nfbdata = request.facebook.users.getInfo(request.facebook.uid, \n ['name', 'pic', 'interests'])\n\n"
] |
[
2
] |
[] |
[] |
[
"django",
"facebook",
"python"
] |
stackoverflow_0002143148_django_facebook_python.txt
|
Q:
Python indentation issue?
I'm pretty new to python. This is my first time working with classes in python. When I try to run this script, I get
IndentationError: expected an indented
block
What is wrong with this?
import random
class Individual:
alleles = (0,1)
length = 5
string = ""
def __init__(self):
#some constructor work, here.
def evaluate(self):
#some stuff here.
def mutate(self, gene):
#mutate the given gene.
def onePointCrossover(self, partner):
#at some random point, crossover.
def twoPointCrossover(self, partner):
#at two random(?) points, crossover.
class World:
def __init__(self):
#stuff.
def buildPopulation(self):
#stuff.
for individual in self.population():
for i in range(0, individual.length):
print random.random()
def display(self):
#print some output stuff.
if __name__ == '__main__':
print "hi there"
A:
All of those methods that consist of just a comment.
To fix it, for example, do this
def twoPointCrossover(self, partner):
#at two random(?) points, crossover.
pass
The comments don't count as compilable statements, so you have a bunch of empty blocks. That is why it gives you the indent error.
A:
If you use something that ends in : expecting an indented block and you don't have anything that you want to put there (other than a comment) then you need to use pass.
E.g.
def doNothing(self):
pass
A:
When you're just outlining your classes and have a bunch of methods which do nothing, you need to insert the pass statement to indicate that nothing is happening.
Like so:
class Individual:
alleles = (0,1)
length = 5
string = ""
def __init__(self):
#some constructor work, here.
pass
def evaluate(self):
#some stuff here.
pass
...
The unexpected indent message is because python is looking for an indented statement to follow the method definition.
A:
Change:
class World:
def __init__(self):
#stuff.
To:
class World:
def __init__(self):
#stuff
pass
and so on for all the methods.
A:
Unless you're abbreviating your code for this post, you'll need pass after all of those functions that don't have any code.
A:
def __init__(self):
#stuff.
That looks wrong at first glance. Try changing it to this:
def __init__(self):
#stuff.
pass
A:
Double check the tabs and spaces in all the code, make sure you are not mixing them. A line with several spaces may the same as a line with a single tab.
A:
Others have covered pass, so I will just add that for beginning python programmers, it can take some getting used to the importance of whitespace.
Until you get used to it you might want to get in the habit of converting tabs to spaces or spaces to tabs when you save a file. Personally I prefer tabs because it is easier to tell the difference if it is off by one (especially at the beginning/end of a nested block).
|
Python indentation issue?
|
I'm pretty new to python. This is my first time working with classes in python. When I try to run this script, I get
IndentationError: expected an indented
block
What is wrong with this?
import random
class Individual:
alleles = (0,1)
length = 5
string = ""
def __init__(self):
#some constructor work, here.
def evaluate(self):
#some stuff here.
def mutate(self, gene):
#mutate the given gene.
def onePointCrossover(self, partner):
#at some random point, crossover.
def twoPointCrossover(self, partner):
#at two random(?) points, crossover.
class World:
def __init__(self):
#stuff.
def buildPopulation(self):
#stuff.
for individual in self.population():
for i in range(0, individual.length):
print random.random()
def display(self):
#print some output stuff.
if __name__ == '__main__':
print "hi there"
|
[
"All of those methods that consist of just a comment.\nTo fix it, for example, do this\ndef twoPointCrossover(self, partner):\n #at two random(?) points, crossover.\n pass\n\nThe comments don't count as compilable statements, so you have a bunch of empty blocks. That is why it gives you the indent error.\n",
"If you use something that ends in : expecting an indented block and you don't have anything that you want to put there (other than a comment) then you need to use pass.\nE.g.\ndef doNothing(self):\n pass\n\n",
"When you're just outlining your classes and have a bunch of methods which do nothing, you need to insert the pass statement to indicate that nothing is happening. \nLike so: \nclass Individual:\n alleles = (0,1)\n length = 5\n string = \"\"\n\n def __init__(self):\n #some constructor work, here.\n pass\n\n def evaluate(self):\n #some stuff here.\n pass\n ...\n\nThe unexpected indent message is because python is looking for an indented statement to follow the method definition. \n",
"Change:\nclass World:\n def __init__(self):\n #stuff.\n\nTo:\nclass World:\n def __init__(self):\n #stuff\n pass\n\nand so on for all the methods.\n",
"Unless you're abbreviating your code for this post, you'll need pass after all of those functions that don't have any code.\n",
"def __init__(self):\n #stuff.\n\nThat looks wrong at first glance. Try changing it to this:\ndef __init__(self):\n #stuff.\n pass\n\n",
"Double check the tabs and spaces in all the code, make sure you are not mixing them. A line with several spaces may the same as a line with a single tab.\n",
"Others have covered pass, so I will just add that for beginning python programmers, it can take some getting used to the importance of whitespace.\nUntil you get used to it you might want to get in the habit of converting tabs to spaces or spaces to tabs when you save a file. Personally I prefer tabs because it is easier to tell the difference if it is off by one (especially at the beginning/end of a nested block).\n"
] |
[
11,
4,
3,
2,
2,
2,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002143291_python.txt
|
Q:
How do I get a content-type of a file in Python? (with url..)
Suppose I haev a video file:
http://mydomain.com/thevideofile.mp4
How do I get the header and the content-type of this file? With Python. But , I don't want to download the entire file.
i want it to return:
video/mp4
Edit: this is what I did. What do you think?
f = urllib2.urlopen(url)
params['mime'] = f.headers['content-type']
A:
Like so:
>>> import httplib
>>> conn = httplib.HTTPConnection("mydomain.com")
>>> conn.request("HEAD", "/thevideofile.mp4")
>>> res = conn.getresponse()
>>> print res.getheaders()
That will only download and print the headers because it is making a HEAD request:
Asks for the response identical to the one that would correspond to a GET
request, but without the response
body. This is useful for retrieving
meta-information written in response
headers, without having to transport
the entire content.
(via Wikipedia)
A:
This is a higher level answer than Brian's. Using the urllib machinery has the usual advantages such as handling redirects automatically and so on.
import urllib2
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
url = "http://mydomain.com/thevideofile.mp4"
head = urllib2.urlopen(HeadRequest(url))
head.read() # This will return empty string and closes the connection
print head.headers.maintype
print head.headers.subtype
print head.headers.type
A:
you can get the video type using the info() method or the headers dict
f=urllib2.urlopen(url)
print f.headers['Content-Type']
print f.info()
A test run with an randomly selected avi file googled on the net that is more than 600Mb
$ cat test.py
#!/usr/bin/env python
import urllib2
url="http://www.merseypirates.com/rjnsteve/rjnsteve/oem16.avi"
f=urllib2.urlopen(url)
print f.headers['Content-Type']
$ time python test.py
video/x-msvideo
real 0m4.931s
user 0m0.115s
sys 0m0.042s
it will only "take up bandwidth" when the file is actually downloaded , ie packets are being sent to and from the socket.
|
How do I get a content-type of a file in Python? (with url..)
|
Suppose I haev a video file:
http://mydomain.com/thevideofile.mp4
How do I get the header and the content-type of this file? With Python. But , I don't want to download the entire file.
i want it to return:
video/mp4
Edit: this is what I did. What do you think?
f = urllib2.urlopen(url)
params['mime'] = f.headers['content-type']
|
[
"Like so:\n>>> import httplib\n>>> conn = httplib.HTTPConnection(\"mydomain.com\")\n>>> conn.request(\"HEAD\", \"/thevideofile.mp4\")\n>>> res = conn.getresponse()\n>>> print res.getheaders()\n\nThat will only download and print the headers because it is making a HEAD request:\n\nAsks for the response identical to the one that would correspond to a GET\n request, but without the response\n body. This is useful for retrieving\n meta-information written in response\n headers, without having to transport\n the entire content.\n\n(via Wikipedia)\n",
"This is a higher level answer than Brian's. Using the urllib machinery has the usual advantages such as handling redirects automatically and so on.\nimport urllib2\n\nclass HeadRequest(urllib2.Request):\n def get_method(self):\n return \"HEAD\"\n\nurl = \"http://mydomain.com/thevideofile.mp4\"\nhead = urllib2.urlopen(HeadRequest(url))\nhead.read() # This will return empty string and closes the connection\nprint head.headers.maintype\nprint head.headers.subtype\nprint head.headers.type\n\n",
"you can get the video type using the info() method or the headers dict\nf=urllib2.urlopen(url)\nprint f.headers['Content-Type']\nprint f.info()\n\nA test run with an randomly selected avi file googled on the net that is more than 600Mb\n$ cat test.py\n#!/usr/bin/env python\nimport urllib2\nurl=\"http://www.merseypirates.com/rjnsteve/rjnsteve/oem16.avi\"\nf=urllib2.urlopen(url)\nprint f.headers['Content-Type']\n\n$ time python test.py\nvideo/x-msvideo\n\nreal 0m4.931s\nuser 0m0.115s\nsys 0m0.042s\n\nit will only \"take up bandwidth\" when the file is actually downloaded , ie packets are being sent to and from the socket.\n"
] |
[
12,
4,
0
] |
[] |
[] |
[
"content_type",
"http",
"python",
"url"
] |
stackoverflow_0002143674_content_type_http_python_url.txt
|
Q:
Python DBUS SESSION_BUS - X11 dependency
I've got running sample python code which is fine in Ubuntu desktop:
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
from dbus.mainloop.glib import threads_init
import subprocess
from subprocess import call
gobject.threads_init()
threads_init()
dbus.mainloop.glib.DBusGMainLoop( set_as_default = True )
p = subprocess.Popen('dbus-launch --sh-syntax', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
call( "export DBUS_SESSION_BUS_ADDRESS" , shell=True )
call( "export DBUS_SESSION_BUS_PID" , shell=True )
bus = dbus.SessionBus()
# get DBUS objects, do other stuff with SESSION_BUS
# in same time we can start more independent processes with this file
# finaly kill the SESSION_BUS process
After success on desktop I moved the code to the server edition which is only with shell. The dbus-launch starts the process, but python dbus.SessionBus() returns error with "/bin/dbus-launch terminated abnormally with the following error: Autolaunch error: X11 initialization failed".
Hope there shouldn't be strict dependency between SESSION_BUS and X11 when the process started with "dbus-launch" go up and running with success. The error comes in python.
Best solution will be clean python or linux environment settings, worst but maybe acceptable with some fake or virtual X11 (I was not lucky when I try it)
A:
The problem is that you're running the export calls in separate shells. You need to capture the output of dbus-launch, parse the values, and use os.environ to write them to the environment:
p = subprocess.Popen('dbus-launch', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for var in p.stdout:
sp = var.split('=', 1)
print sp
os.environ[sp[0]] = sp[1][:-1]
|
Python DBUS SESSION_BUS - X11 dependency
|
I've got running sample python code which is fine in Ubuntu desktop:
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
from dbus.mainloop.glib import threads_init
import subprocess
from subprocess import call
gobject.threads_init()
threads_init()
dbus.mainloop.glib.DBusGMainLoop( set_as_default = True )
p = subprocess.Popen('dbus-launch --sh-syntax', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
call( "export DBUS_SESSION_BUS_ADDRESS" , shell=True )
call( "export DBUS_SESSION_BUS_PID" , shell=True )
bus = dbus.SessionBus()
# get DBUS objects, do other stuff with SESSION_BUS
# in same time we can start more independent processes with this file
# finaly kill the SESSION_BUS process
After success on desktop I moved the code to the server edition which is only with shell. The dbus-launch starts the process, but python dbus.SessionBus() returns error with "/bin/dbus-launch terminated abnormally with the following error: Autolaunch error: X11 initialization failed".
Hope there shouldn't be strict dependency between SESSION_BUS and X11 when the process started with "dbus-launch" go up and running with success. The error comes in python.
Best solution will be clean python or linux environment settings, worst but maybe acceptable with some fake or virtual X11 (I was not lucky when I try it)
|
[
"The problem is that you're running the export calls in separate shells. You need to capture the output of dbus-launch, parse the values, and use os.environ to write them to the environment:\np = subprocess.Popen('dbus-launch', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\nfor var in p.stdout:\n sp = var.split('=', 1)\n print sp\n os.environ[sp[0]] = sp[1][:-1]\n\n"
] |
[
5
] |
[] |
[] |
[
"dbus",
"python",
"x11"
] |
stackoverflow_0002143785_dbus_python_x11.txt
|
Q:
Read the first line of batch file from the same batch file?
I have a batch file that tries to run the program specified in its first line. Similar to Unix's shebang:
C:\> more foo.bat
#!C:\Python27\python.exe
%PYTHON% foo-script.py
C:\>
What I want to know is: is there a way to automatically set %PYTHON% to C:\Python27\python.exe which is specified in the first line of the script following the shebang (#!)?
Background: I am trying to do this so as to explicitly specify the Python interpreter to invoke (as there are multiple Python interpreters installed on the system) in the wrapper script.
Assumption: You can assume that script already knows it's own filename (foo) and %~dp0 is the directory of this script. How do we read the first line excluding the shebang?
Clarification: Adding C:\PythonXY to %PATH% is not a solution. The shebang line is supposed to be modified during install time (the original script is generated on the build machine only) on the user's machine .. which may have multiple Python installations of the same version. And only the shebang line is modifyable (that is how the program works).
A:
Firstly , on windows, there is no need for shebang. Its best to include the path of the Python interpreter to the PATH environment variable of the user who is running the script. That said, to get the first line in batch, you can use set
set /p var=<file
since you have multiple version of interpreter, why not just use the correct one when you invoke the script?
c:\python27\bin\python.exe myscript.py
Edit:
@echo off
set /p var=<test.py
call %var:~2% test.py
output
C:\test>more test1.py
#!c:\Python26\python.exe
print "hello"
C:\test>more test.bat
@echo off
set /p var=<test1.py
call %var:~2% test1.py
C:\test>test.bat
hello
A:
Shebangs are only native to the filesystems of Unix/Linux/BSD variants, due to their design and layout, the filesystem knows that when a file begins with a shebang, the filesystem triggers the user's terminal process to invoke the shell based on the shebang, usually /bin/sh. This can be confirmed by browsing through the filesystem routines here.
Edit: Have edited my answer to make it fully clear in the context of the Windows environment.
In short this is not possible under Windows (2000 upwards to Windows 7) as the NTFS lacks such a capability to interpret the contents of the data (NTFS does not care what is in the file), and therefore lack the means of having an exec call to load the shebang script, only .EXE, .DLL, .SYS,.DRV's are catered for, but for a script....
Hope this helps,
Best regards,
Tom.
|
Read the first line of batch file from the same batch file?
|
I have a batch file that tries to run the program specified in its first line. Similar to Unix's shebang:
C:\> more foo.bat
#!C:\Python27\python.exe
%PYTHON% foo-script.py
C:\>
What I want to know is: is there a way to automatically set %PYTHON% to C:\Python27\python.exe which is specified in the first line of the script following the shebang (#!)?
Background: I am trying to do this so as to explicitly specify the Python interpreter to invoke (as there are multiple Python interpreters installed on the system) in the wrapper script.
Assumption: You can assume that script already knows it's own filename (foo) and %~dp0 is the directory of this script. How do we read the first line excluding the shebang?
Clarification: Adding C:\PythonXY to %PATH% is not a solution. The shebang line is supposed to be modified during install time (the original script is generated on the build machine only) on the user's machine .. which may have multiple Python installations of the same version. And only the shebang line is modifyable (that is how the program works).
|
[
"Firstly , on windows, there is no need for shebang. Its best to include the path of the Python interpreter to the PATH environment variable of the user who is running the script. That said, to get the first line in batch, you can use set\nset /p var=<file\n\nsince you have multiple version of interpreter, why not just use the correct one when you invoke the script?\nc:\\python27\\bin\\python.exe myscript.py\n\nEdit:\n@echo off\nset /p var=<test.py\ncall %var:~2% test.py\n\noutput\nC:\\test>more test1.py\n#!c:\\Python26\\python.exe\n\nprint \"hello\"\n\n\nC:\\test>more test.bat\n@echo off\nset /p var=<test1.py\ncall %var:~2% test1.py\n\nC:\\test>test.bat\nhello\n\n",
"Shebangs are only native to the filesystems of Unix/Linux/BSD variants, due to their design and layout, the filesystem knows that when a file begins with a shebang, the filesystem triggers the user's terminal process to invoke the shell based on the shebang, usually /bin/sh. This can be confirmed by browsing through the filesystem routines here.\nEdit: Have edited my answer to make it fully clear in the context of the Windows environment.\nIn short this is not possible under Windows (2000 upwards to Windows 7) as the NTFS lacks such a capability to interpret the contents of the data (NTFS does not care what is in the file), and therefore lack the means of having an exec call to load the shebang script, only .EXE, .DLL, .SYS,.DRV's are catered for, but for a script....\nHope this helps,\nBest regards,\nTom.\n"
] |
[
4,
0
] |
[] |
[] |
[
"batch_file",
"python",
"shebang",
"windows"
] |
stackoverflow_0002143897_batch_file_python_shebang_windows.txt
|
Q:
psp (python server pages) code under mod_wsgi?
Is there some way to run .psp (python server pages) code under apache + mod_wsgi? While we are moving towards newer wsgi based frameworks we still have some legacy code written in psp which runs under mod_python.
We'd like to be able to run it on the same server that hosts other wsgi based python code. In short - is there a way to support psp under mod_wsgi? Or are there any other tricks to at least allow mod_wsgi and mod_python to play nice in the same server?
-S
A:
No, there is no port of mod_python PSP for mod_wsgi.
Yes, you can run mod_python and mod_wsgi on same server so long as both use same version of Python and both link dynamically with Python library. See:
http://code.google.com/p/modwsgi/wiki/InstallationIssues
It isn't recommended to run both together though as mod_wsgi then gets afflicted by the memory leaks due to mod_python, plus some other configurability in mod_wsgi is restricted due to mod_python controlling Python interpreter initialisation.
|
psp (python server pages) code under mod_wsgi?
|
Is there some way to run .psp (python server pages) code under apache + mod_wsgi? While we are moving towards newer wsgi based frameworks we still have some legacy code written in psp which runs under mod_python.
We'd like to be able to run it on the same server that hosts other wsgi based python code. In short - is there a way to support psp under mod_wsgi? Or are there any other tricks to at least allow mod_wsgi and mod_python to play nice in the same server?
-S
|
[
"No, there is no port of mod_python PSP for mod_wsgi.\nYes, you can run mod_python and mod_wsgi on same server so long as both use same version of Python and both link dynamically with Python library. See:\nhttp://code.google.com/p/modwsgi/wiki/InstallationIssues\nIt isn't recommended to run both together though as mod_wsgi then gets afflicted by the memory leaks due to mod_python, plus some other configurability in mod_wsgi is restricted due to mod_python controlling Python interpreter initialisation.\n"
] |
[
1
] |
[] |
[] |
[
"mod_python",
"python",
"python_server_pages",
"wsgi"
] |
stackoverflow_0002143915_mod_python_python_python_server_pages_wsgi.txt
|
Q:
what is {% trans "This is the title." %} used for,i can't understand the api
i know the {% trans %} is for translation,
and how can i translate {% trans "This is the title." %} to chinese.
thanks
D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm
in.py compilemessages
processing file django.po in D:\zjm_code\register2\locale\cn\LC_MESSAGES
msgfmt: iconv failure
A:
You don't follow the documentation?
3 steps:
Add {% load i18n %} in the template (as Michał Ludwiński says). Put the {% trans %} in your templates, or _ in python code, etc.
Build a translation dictionary:
Run django-admin.py makemessages -l cn (cn = China language code) in your Django project root.
Edit locale/cn/LC_MESSAGES/django.po. Just under msgid "Hello!" change msgstr "" to to msgstr "nihao". Don't change msgid. You can use unicode, but I'd use pinyin until you are sure everything else works.
Run django-admin.py compilemessages
Setup language translation. You might need to enable some middle-ware.
A:
before you will try to use {% trans %} blocktag you need to type
{% load i18n %}
then you can use the tag to type in the text you want to be translated (one thing is important - the text ought to be in main project language which is set in settings)
if you have already some text you want to translate type in your projects main dir:
./manage.py makemessages -l pl
where "pl" can by country code of the language of choice. this command will make django scripts generate a right localization file located in the ./locale/(language-code)/LC_MESSAGES/django.po.
after doing the translation stuff you simply type
./manage.py compilemessages
and that should do the trick.
A:
I18n in Django
|
what is {% trans "This is the title." %} used for,i can't understand the api
|
i know the {% trans %} is for translation,
and how can i translate {% trans "This is the title." %} to chinese.
thanks
D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm
in.py compilemessages
processing file django.po in D:\zjm_code\register2\locale\cn\LC_MESSAGES
msgfmt: iconv failure
|
[
"You don't follow the documentation?\n3 steps:\n\nAdd {% load i18n %} in the template (as Michał Ludwiński says). Put the {% trans %} in your templates, or _ in python code, etc.\nBuild a translation dictionary:\n\nRun django-admin.py makemessages -l cn (cn = China language code) in your Django project root.\nEdit locale/cn/LC_MESSAGES/django.po. Just under msgid \"Hello!\" change msgstr \"\" to to msgstr \"nihao\". Don't change msgid. You can use unicode, but I'd use pinyin until you are sure everything else works.\nRun django-admin.py compilemessages\n\nSetup language translation. You might need to enable some middle-ware.\n\n",
"before you will try to use {% trans %} blocktag you need to type\n{% load i18n %}\n\nthen you can use the tag to type in the text you want to be translated (one thing is important - the text ought to be in main project language which is set in settings)\nif you have already some text you want to translate type in your projects main dir:\n./manage.py makemessages -l pl\n\nwhere \"pl\" can by country code of the language of choice. this command will make django scripts generate a right localization file located in the ./locale/(language-code)/LC_MESSAGES/django.po.\nafter doing the translation stuff you simply type\n./manage.py compilemessages \n\nand that should do the trick.\n",
"I18n in Django\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002144319_django_python.txt
|
Q:
my pythonpath has 'register2',why i can't import it
import sys
print sys.path
['D:\\zjm_code\\register2', 'C:\\WINDOWS\\system32\\python25.zip', 'D:\\Python25\\DLLs', 'D:\\Python25\\lib', 'D:\\Python25\\lib\\plat-win', 'D:\\Python25\\lib\\lib-tk', 'D:\\Python25', 'D:\\Python25\\lib\\site-packages']
and
#from django.core.management import setup_environ
from register2 import settings
#setup_environ(settings)
Traceback (most recent call last):
File "D:\zjm_code\register2\b.py", line 4, in <module>
from register2 import settings
ImportError: No module named register2
why ,
thanks
A:
When directory 'D:\\zjm_code\\register2' is on sys.path, this means you can import modules and packages that are INSIDE that directory.
To import the directory register2 itself, two conditions:
its parent, 'D:\\zjm_code', must be on sys.path; and
file 'D:\\zjm_code\\register2\\__init__.py' must exist
__init__.py is the code that actually executes when you "import the directory".
A:
lol because it tries to import something from register2 but it cannot since there isn't D:\zjm_code on the path..
|
my pythonpath has 'register2',why i can't import it
|
import sys
print sys.path
['D:\\zjm_code\\register2', 'C:\\WINDOWS\\system32\\python25.zip', 'D:\\Python25\\DLLs', 'D:\\Python25\\lib', 'D:\\Python25\\lib\\plat-win', 'D:\\Python25\\lib\\lib-tk', 'D:\\Python25', 'D:\\Python25\\lib\\site-packages']
and
#from django.core.management import setup_environ
from register2 import settings
#setup_environ(settings)
Traceback (most recent call last):
File "D:\zjm_code\register2\b.py", line 4, in <module>
from register2 import settings
ImportError: No module named register2
why ,
thanks
|
[
"When directory 'D:\\\\zjm_code\\\\register2' is on sys.path, this means you can import modules and packages that are INSIDE that directory.\nTo import the directory register2 itself, two conditions:\n\nits parent, 'D:\\\\zjm_code', must be on sys.path; and\nfile 'D:\\\\zjm_code\\\\register2\\\\__init__.py' must exist\n\n__init__.py is the code that actually executes when you \"import the directory\".\n",
"lol because it tries to import something from register2 but it cannot since there isn't D:\\zjm_code on the path..\n"
] |
[
5,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002144451_django_python.txt
|
Q:
Why can't I use 'django-admin.py makemessages -l cn'
print :
D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm
in.py makemessages -l cn
Error: This script should be run from the Django SVN tree or your project or app
tree. If you did indeed run it from the SVN checkout or your project or applica
tion, maybe you are just missing the conf/locale (in the django tree) or locale
(for project and application) directory? It is not created automatically, you ha
ve to create it by hand if you want to enable i18n for your project or applicati
on.
2.i made a locale directory ,and
D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm
in.py makemessages -l cn
processing language cn
Error: errors happened while running xgettext on __init__.py
'xgettext' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
D:\Python25\lib\site-packages\django\core\management\base.py:234: RuntimeWarning
: tp_compare didn't return -1 or -2 for exception
sys.exit(1)
3.
ok
http://hi.baidu.com/zjm1126/blog/item/f28e09deced15353ccbf1a82.html
A:
is register2 your project or app tree?
did you make directory register2\\locale?
|
Why can't I use 'django-admin.py makemessages -l cn'
|
print :
D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm
in.py makemessages -l cn
Error: This script should be run from the Django SVN tree or your project or app
tree. If you did indeed run it from the SVN checkout or your project or applica
tion, maybe you are just missing the conf/locale (in the django tree) or locale
(for project and application) directory? It is not created automatically, you ha
ve to create it by hand if you want to enable i18n for your project or applicati
on.
2.i made a locale directory ,and
D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm
in.py makemessages -l cn
processing language cn
Error: errors happened while running xgettext on __init__.py
'xgettext' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
D:\Python25\lib\site-packages\django\core\management\base.py:234: RuntimeWarning
: tp_compare didn't return -1 or -2 for exception
sys.exit(1)
3.
ok
http://hi.baidu.com/zjm1126/blog/item/f28e09deced15353ccbf1a82.html
|
[
"\nis register2 your project or app tree?\ndid you make directory register2\\\\locale?\n\n"
] |
[
8
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002144503_django_python.txt
|
Q:
best way to add file way to my pythpath.which can be saved
import sys
print sys.path
sys.path+=['D:\\zjm_code']
print sys.path
it can't be save,how does do it.
A:
Where is environment variable PYTHONPATH defined in your working environment?
In Unix-like systems it would be in a bash script such as ~/.bashrc.
In Windows it could be a .BAT or .CMD file but more often will be in the registry.
"Saving" a setting of PYTHONPATH to a file is easy.
Writing to the Windows registry is much harder, alas. Doable, yes, but, if you get it in the least wrong, you're likely to make your whole machine unusable.
In your site-packages directory (which should itself be in sys.path) you can create a file named sitecustomize.py that is automatically imported, if it exists, each time a Python program starts. I suggest that this is simpler and less risky than messing with the registry. So, write your sys.path manipulations to such a sitecustomize.py file.
A:
you can use append()
import sys
sys.path.append("/mypath")
to save it permanently, you can export PYTHONPATH in the user shell initialization file (eg .bash_profile)
PYTHONPATH=/path/to/module/directory:/path/to/module2/dir2
on Windows systems, you can follow instructions here.
|
best way to add file way to my pythpath.which can be saved
|
import sys
print sys.path
sys.path+=['D:\\zjm_code']
print sys.path
it can't be save,how does do it.
|
[
"Where is environment variable PYTHONPATH defined in your working environment?\nIn Unix-like systems it would be in a bash script such as ~/.bashrc.\nIn Windows it could be a .BAT or .CMD file but more often will be in the registry.\n\"Saving\" a setting of PYTHONPATH to a file is easy.\nWriting to the Windows registry is much harder, alas. Doable, yes, but, if you get it in the least wrong, you're likely to make your whole machine unusable.\nIn your site-packages directory (which should itself be in sys.path) you can create a file named sitecustomize.py that is automatically imported, if it exists, each time a Python program starts. I suggest that this is simpler and less risky than messing with the registry. So, write your sys.path manipulations to such a sitecustomize.py file.\n",
"you can use append()\nimport sys\nsys.path.append(\"/mypath\")\n\nto save it permanently, you can export PYTHONPATH in the user shell initialization file (eg .bash_profile)\nPYTHONPATH=/path/to/module/directory:/path/to/module2/dir2\n\non Windows systems, you can follow instructions here.\n"
] |
[
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002144530_python.txt
|
Q:
How can I access the current URI in python's mako templating system?
I'd like to submit the form to the current URI, like this:
<form action="${CURRENT_URI}" method="post">
<input type="text" name="email" />
</form>
from within a mako template. But I am not sure what variable holds the current uri information.
Thanks.
A:
Actually, you don't need it.
<form action="" method="post">
<input type="text" name="email" />
</form>
If you leave the action empty, it will be posted to the current url.
However, if you need the current url for some other reason, it can be retrieved by calling pylons.url.current()
|
How can I access the current URI in python's mako templating system?
|
I'd like to submit the form to the current URI, like this:
<form action="${CURRENT_URI}" method="post">
<input type="text" name="email" />
</form>
from within a mako template. But I am not sure what variable holds the current uri information.
Thanks.
|
[
"Actually, you don't need it. \n<form action=\"\" method=\"post\">\n<input type=\"text\" name=\"email\" />\n</form>\n\nIf you leave the action empty, it will be posted to the current url.\nHowever, if you need the current url for some other reason, it can be retrieved by calling pylons.url.current() \n"
] |
[
1
] |
[] |
[] |
[
"mako",
"pylons",
"python"
] |
stackoverflow_0002144284_mako_pylons_python.txt
|
Q:
Nested Choices in a python program
I have a script that I wrote in python for testing out the sorting algorithms that I've implemented. The main part of the program asks the user to select one of the sort algorithms from a list. And then whether they would like to sort from a file of numbers or select a list of random numbers. I have it set up (I think) so that typing a number that's not in the first list of choices will just print "Bad choice" and try getting the number again.
[Edit] After taking the advice of the answer I changed a couple of the inputs to raw inputs. And I changed the structure of the program. It now works perfectly except it still prints out "Bad Choice" even after a success.
def fileOrRandom():
return raw_input("Would you like to read from file or random list? (A or B): ")
choices = {1:SelectionSorter,2:ComparisonSorter}
print "Please enter the type of sort you would like to perform."
print "1. Selection Sort\n2. Comparison Sort"
while(True):
try:
choice=input("Your choice: ")
for i in range(2):
if(choice==i+1):
choice2=fileOrRandom()
if(choice2=='A'):
fileName=raw_input("Please Enter The Name of the File to sort: ")
sorter = choices[choice](fileName)
sorter.timedSort(sorter.sort)
elif(choice2=='B'):
num = input("How many random numbers would you like to sort: ")
sorter = choices[choice](None,num)
sorter.timedSort(sorter.sort)
else:
raise Exception
else:
raise Exception
break
except Exception:
print "Bad Choice"
My issue is that it works as expected for the first part where it will return "bad choice" for a number that's not in the list, and it will get fileOrRandom(), but it still prints "Bad Choice" when selecting good values that should print out my results because sorter.timedSort(sorter.sort) executes my sorting algorithm and prints out a bunch of other things to the screen. Am I just missing something simple or is there a better way to deal with these nested options in a Python program?
A:
use raw_input()
def fileOrRandom():
return raw_input("Would you like to read from file or random list? (A or B): ")
your while loop should look like this (after fixing the indentation)
while True :
choice=raw_input("Your choice: ")
for i in range(2):
if choice==i+1 and fileOrRandom()=="A" :
fileName=raw_input("Please Enter The Name of the File to sort: ")
sorter = choices[choice](fileName)
sorter.timedSort(sorter.sort)
elif choice==i+1 and fileOrRandom()=="B" :
num = raw_input("How many random numbers would you like to sort: ")
sorter = choices[choice](None,num)
sorter.timedSort(sorter.sort)
elif choice in ['q','Q']: break
else: print "Bad choice"
|
Nested Choices in a python program
|
I have a script that I wrote in python for testing out the sorting algorithms that I've implemented. The main part of the program asks the user to select one of the sort algorithms from a list. And then whether they would like to sort from a file of numbers or select a list of random numbers. I have it set up (I think) so that typing a number that's not in the first list of choices will just print "Bad choice" and try getting the number again.
[Edit] After taking the advice of the answer I changed a couple of the inputs to raw inputs. And I changed the structure of the program. It now works perfectly except it still prints out "Bad Choice" even after a success.
def fileOrRandom():
return raw_input("Would you like to read from file or random list? (A or B): ")
choices = {1:SelectionSorter,2:ComparisonSorter}
print "Please enter the type of sort you would like to perform."
print "1. Selection Sort\n2. Comparison Sort"
while(True):
try:
choice=input("Your choice: ")
for i in range(2):
if(choice==i+1):
choice2=fileOrRandom()
if(choice2=='A'):
fileName=raw_input("Please Enter The Name of the File to sort: ")
sorter = choices[choice](fileName)
sorter.timedSort(sorter.sort)
elif(choice2=='B'):
num = input("How many random numbers would you like to sort: ")
sorter = choices[choice](None,num)
sorter.timedSort(sorter.sort)
else:
raise Exception
else:
raise Exception
break
except Exception:
print "Bad Choice"
My issue is that it works as expected for the first part where it will return "bad choice" for a number that's not in the list, and it will get fileOrRandom(), but it still prints "Bad Choice" when selecting good values that should print out my results because sorter.timedSort(sorter.sort) executes my sorting algorithm and prints out a bunch of other things to the screen. Am I just missing something simple or is there a better way to deal with these nested options in a Python program?
|
[
"use raw_input()\ndef fileOrRandom():\n return raw_input(\"Would you like to read from file or random list? (A or B): \")\n\nyour while loop should look like this (after fixing the indentation)\nwhile True :\n choice=raw_input(\"Your choice: \")\n for i in range(2):\n if choice==i+1 and fileOrRandom()==\"A\" :\n fileName=raw_input(\"Please Enter The Name of the File to sort: \")\n sorter = choices[choice](fileName)\n sorter.timedSort(sorter.sort)\n elif choice==i+1 and fileOrRandom()==\"B\" :\n num = raw_input(\"How many random numbers would you like to sort: \")\n sorter = choices[choice](None,num)\n sorter.timedSort(sorter.sort)\n elif choice in ['q','Q']: break\n else: print \"Bad choice\"\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002144630_python.txt
|
Q:
Python C interoperability
I wish to wrap an existing C (pure C that is. No C++) library into Python so that I can call it from Python scripts. Which approach among the various available (C Api, SWIG etc.) would be the most suitable?
A:
go with Ctypes, it is part of standard distribution and works very well.
basically you can wrap C structures and types in python classes, as well as functions. Some types and functionality is already provided by library.
ctypes
couple caveats though: passing triple pointers to C routines is not obvious (if you have to), and I could not get it to work with static libraries on Linux, DLL and shared objects are fine.
A:
SWIG is great for doing this. Here is a sample tutorial: http://www.swig.org/Doc1.3/Python.html.
A:
Since your code is "pure" C you might consider using Pyrex/Cython. This is not a voting issue and Cython has already been mentioned. I am just clarifying why it is a better choice for pure C.
|
Python C interoperability
|
I wish to wrap an existing C (pure C that is. No C++) library into Python so that I can call it from Python scripts. Which approach among the various available (C Api, SWIG etc.) would be the most suitable?
|
[
"go with Ctypes, it is part of standard distribution and works very well.\nbasically you can wrap C structures and types in python classes, as well as functions. Some types and functionality is already provided by library. \nctypes\ncouple caveats though: passing triple pointers to C routines is not obvious (if you have to), and I could not get it to work with static libraries on Linux, DLL and shared objects are fine.\n",
"SWIG is great for doing this. Here is a sample tutorial: http://www.swig.org/Doc1.3/Python.html.\n",
"Since your code is \"pure\" C you might consider using Pyrex/Cython. This is not a voting issue and Cython has already been mentioned. I am just clarifying why it is a better choice for pure C.\n"
] |
[
8,
4,
0
] |
[] |
[] |
[
"c",
"interop",
"python"
] |
stackoverflow_0002144542_c_interop_python.txt
|
Q:
sqlite python insert with where condition
from this post sqlite python insert I learned inserting into tables but now I need to use where something like
cursor.execute("insert into table1(id) values (?) where ip=? and address=?",(id,),(ip,),(addr,));
A:
INSERT does not have a WHERE clause. I think you mean UPDATE.
A:
You can't use a WHERE clause in an INSERT. If you want to specify the values for particular fields to insert, put them in the values clause:
cursor.execute("INSERT INTO table1(id, ip, address) VALUES (?, ?, ?)", (id, ip, addr))
|
sqlite python insert with where condition
|
from this post sqlite python insert I learned inserting into tables but now I need to use where something like
cursor.execute("insert into table1(id) values (?) where ip=? and address=?",(id,),(ip,),(addr,));
|
[
"INSERT does not have a WHERE clause. I think you mean UPDATE.\n",
"You can't use a WHERE clause in an INSERT. If you want to specify the values for particular fields to insert, put them in the values clause:\ncursor.execute(\"INSERT INTO table1(id, ip, address) VALUES (?, ?, ?)\", (id, ip, addr))\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"insert",
"python",
"sqlite"
] |
stackoverflow_0002144840_insert_python_sqlite.txt
|
Q:
Creating very large images using Python Image Library
I'm trying to create a very large image (25000x25000) by pasting together many smaller images. Upon calling Image.new() with such large dimensions, python runs out of memory and I get a MemoryError.
Is there a way to write out an image like this incrementally, without having the whole thing resident in RAM?
EDIT:
Using ImageMagick's montage command, it seems possible to create arbitrarily sized images. It looks like it's not trying loading the final image into RAM (it uses very little memory during the process) but rather streaming it out to disk, which is ideal.
A:
You may try to use GDAL library. It provides bindings to Python. Here is combined tutorial presenting how to read and write images using C++, C and Python APIs
Depending on GDAL operations and functions being used, GDAL can handle very large images and process images which are too large to be held in RAM.
A:
Not too suprising you're running out of memory; that image will take over 2gig in memory and depending on the system you're using your OS might not be able to allocate enough virtual memory to python to run it, regardless of your actual RAM.
You are definitely going to need to write it out incrementally. If you're using a raw format you could probably do this per row of images, if they are all of the same dimensions. Then you could concatenate the files, otherwise you'd have to be a bit more careful with how you encode the data.
A:
It's just a matter of understanding the binary file format. Compressed formats are going to be more difficult.
Assuming you want a bitmap/DIB, this code:
#incremental_write_bmp.py
import binascii
data='''
0h -2 -42 4D -"BM" -Magic Number (unsigned integer 66, 77)
2h -4 -46 00 00 00 -70 Bytes -Size of the BMP file
6h -2 -00 00 -Unused -Application Specific
8h -2 -00 00 -Unused -Application Specific
Ah -4 -36 00 00 00 -54 bytes -The offset where the bitmap data (pixels) can be found.
Eh -4 -28 00 00 00 -40 bytes -The number of bytes in the header (from this point).
12h -4 -02 00 00 00 -2 pixels -The width of the bitmap in pixels
16h -4 -02 00 00 00 -2 pixels -The height of the bitmap in pixels
1Ah -2 -01 00 -1 plane -Number of color planes being used.
1Ch -2 -18 00 -24 bits -The number of bits/pixel.
1Eh -4 -00 00 00 00 -0 -BI_RGB, No compression used
22h -4 -10 00 00 00 -16 bytes -The size of the raw BMP data (after this header)
26h -4 -13 0B 00 00 -2,835 pixels/meter -The horizontal resolution of the image
2Ah -4 -13 0B 00 00 -2,835 pixels/meter -The vertical resolution of the image
2Eh -4 -00 00 00 00 -0 colors -Number of colors in the palette
32h -4 -00 00 00 00 -0 important colors -Means all colors are important
36h -3 -00 00 FF -0 0 255 -Red, Pixel (1,0)
39h -3 -FF FF FF -255 255 255 -White, Pixel (1,1)
3Ch -2 -00 00 -0 0 -Padding for 4 byte alignment (Could be a value other than zero)
3Eh -3 -FF 00 00 -255 0 0 -Blue, Pixel (0,0)
41h -3 -00 FF 00 -0 255 0 -Green, Pixel (0,1)
44h -2 -00 00 -0 0 -Padding for 4 byte alignment (Could be a value other than zero)
'''.strip().split('\n')
open('test.bmp','wb')
for l in data:
b = l.split('-')[2].strip()
d = ''.join(b.split())
x = binascii.a2b_hex(d)
# this re-opens the file and appends each iteration
open('test.bmp','ab').write(x)
...will incrementally write the example 2x2 bitmap found here. Now it's just a matter of setting the headers to the size you want and reading (and sometimes re-reading) your tiles in the right order. I tried it with a very large file and did not see python's memory spike. I assume the OS can append to a file without reading the whole thing.
A:
Check if your system runs out of virtual memory when you do this. If it does, try adding more. That way, you offload the entire problem onto the virtual memory subsystem, which might be quicker.
A:
mayby You could try out OIIO python bindings that was created by one of the GSoC student? OpenImageIO itself can read big images using small memory - but I didn't use it by myself
OIIO: http://openimageio.org
How to use python bindings: http://openimageio.org/wiki/index.php?title=Python_bindings
There is also a small script called "isticher" that is doing what You want (at least I think so)
|
Creating very large images using Python Image Library
|
I'm trying to create a very large image (25000x25000) by pasting together many smaller images. Upon calling Image.new() with such large dimensions, python runs out of memory and I get a MemoryError.
Is there a way to write out an image like this incrementally, without having the whole thing resident in RAM?
EDIT:
Using ImageMagick's montage command, it seems possible to create arbitrarily sized images. It looks like it's not trying loading the final image into RAM (it uses very little memory during the process) but rather streaming it out to disk, which is ideal.
|
[
"You may try to use GDAL library. It provides bindings to Python. Here is combined tutorial presenting how to read and write images using C++, C and Python APIs\nDepending on GDAL operations and functions being used, GDAL can handle very large images and process images which are too large to be held in RAM.\n",
"Not too suprising you're running out of memory; that image will take over 2gig in memory and depending on the system you're using your OS might not be able to allocate enough virtual memory to python to run it, regardless of your actual RAM.\nYou are definitely going to need to write it out incrementally. If you're using a raw format you could probably do this per row of images, if they are all of the same dimensions. Then you could concatenate the files, otherwise you'd have to be a bit more careful with how you encode the data.\n",
"It's just a matter of understanding the binary file format. Compressed formats are going to be more difficult.\nAssuming you want a bitmap/DIB, this code:\n#incremental_write_bmp.py\nimport binascii\n\ndata='''\n0h -2 -42 4D -\"BM\" -Magic Number (unsigned integer 66, 77)\n2h -4 -46 00 00 00 -70 Bytes -Size of the BMP file\n6h -2 -00 00 -Unused -Application Specific\n8h -2 -00 00 -Unused -Application Specific\nAh -4 -36 00 00 00 -54 bytes -The offset where the bitmap data (pixels) can be found.\nEh -4 -28 00 00 00 -40 bytes -The number of bytes in the header (from this point).\n12h -4 -02 00 00 00 -2 pixels -The width of the bitmap in pixels\n16h -4 -02 00 00 00 -2 pixels -The height of the bitmap in pixels\n1Ah -2 -01 00 -1 plane -Number of color planes being used.\n1Ch -2 -18 00 -24 bits -The number of bits/pixel.\n1Eh -4 -00 00 00 00 -0 -BI_RGB, No compression used\n22h -4 -10 00 00 00 -16 bytes -The size of the raw BMP data (after this header)\n26h -4 -13 0B 00 00 -2,835 pixels/meter -The horizontal resolution of the image\n2Ah -4 -13 0B 00 00 -2,835 pixels/meter -The vertical resolution of the image\n2Eh -4 -00 00 00 00 -0 colors -Number of colors in the palette\n32h -4 -00 00 00 00 -0 important colors -Means all colors are important\n36h -3 -00 00 FF -0 0 255 -Red, Pixel (1,0)\n39h -3 -FF FF FF -255 255 255 -White, Pixel (1,1)\n3Ch -2 -00 00 -0 0 -Padding for 4 byte alignment (Could be a value other than zero)\n3Eh -3 -FF 00 00 -255 0 0 -Blue, Pixel (0,0)\n41h -3 -00 FF 00 -0 255 0 -Green, Pixel (0,1)\n44h -2 -00 00 -0 0 -Padding for 4 byte alignment (Could be a value other than zero)\n'''.strip().split('\\n')\n\nopen('test.bmp','wb')\nfor l in data:\n b = l.split('-')[2].strip()\n d = ''.join(b.split())\n x = binascii.a2b_hex(d)\n # this re-opens the file and appends each iteration\n open('test.bmp','ab').write(x)\n\n...will incrementally write the example 2x2 bitmap found here. Now it's just a matter of setting the headers to the size you want and reading (and sometimes re-reading) your tiles in the right order. I tried it with a very large file and did not see python's memory spike. I assume the OS can append to a file without reading the whole thing.\n",
"Check if your system runs out of virtual memory when you do this. If it does, try adding more. That way, you offload the entire problem onto the virtual memory subsystem, which might be quicker.\n",
"mayby You could try out OIIO python bindings that was created by one of the GSoC student? OpenImageIO itself can read big images using small memory - but I didn't use it by myself\nOIIO: http://openimageio.org\nHow to use python bindings: http://openimageio.org/wiki/index.php?title=Python_bindings\nThere is also a small script called \"isticher\" that is doing what You want (at least I think so)\n"
] |
[
3,
2,
2,
0,
0
] |
[
"Use numpy.memmap and the png module.\n"
] |
[
-1
] |
[
"python",
"python_imaging_library"
] |
stackoverflow_0002109109_python_python_imaging_library.txt
|
Q:
Python: multiple calls to __init__() on the same instance
The __init__() function gets called when object is created.
Is it ok to call an object __init__() function again, after its been created?
instance = cls(p1=1, p2=2)
# some code
instance.__init__(p1=123, p2=234)
# some more code
instance.__init__(p1=23, p2=24)
why would anyone wanna call __init__() on an object that is already created?
good question. i wanna re-initialize the instance's fields.
A:
It's fine to call __init__ more than once on an object, as long as __init__ is coded with the effect you want to obtain (whatever that may be). A typical case where it happens (so you'd better code __init__ appropriately!-) is when your class's __new__ method returns an instance of the class: that does cause __init__ to be called on the returned instance (for what might be the second, or twentieth, time, if you keep "recycling" instances via your __new__!-).
A:
You can, but it's kind of breaking what __init__ is intended to do. A lot of Python is really just convention, so you might as well follow then and expect __init__ to only be called once. I'd recommend creating a function called init or reset or something which sets the instance variables, use that when you want to reset the instance, and have __init__ just call init. This definitely looks more sane:
x = Pt(1,2)
x.set(3,4)
x.set(5,10)
A:
As far as I know, it does not cause any problems (edit: as suggested by the kosher usage of super(...).__init__(...)), but I think having a reset() method and calling it both in __init__() and when you need to reset would be cleaner.
|
Python: multiple calls to __init__() on the same instance
|
The __init__() function gets called when object is created.
Is it ok to call an object __init__() function again, after its been created?
instance = cls(p1=1, p2=2)
# some code
instance.__init__(p1=123, p2=234)
# some more code
instance.__init__(p1=23, p2=24)
why would anyone wanna call __init__() on an object that is already created?
good question. i wanna re-initialize the instance's fields.
|
[
"It's fine to call __init__ more than once on an object, as long as __init__ is coded with the effect you want to obtain (whatever that may be). A typical case where it happens (so you'd better code __init__ appropriately!-) is when your class's __new__ method returns an instance of the class: that does cause __init__ to be called on the returned instance (for what might be the second, or twentieth, time, if you keep \"recycling\" instances via your __new__!-).\n",
"You can, but it's kind of breaking what __init__ is intended to do. A lot of Python is really just convention, so you might as well follow then and expect __init__ to only be called once. I'd recommend creating a function called init or reset or something which sets the instance variables, use that when you want to reset the instance, and have __init__ just call init. This definitely looks more sane:\nx = Pt(1,2)\nx.set(3,4)\nx.set(5,10)\n\n",
"As far as I know, it does not cause any problems (edit: as suggested by the kosher usage of super(...).__init__(...)), but I think having a reset() method and calling it both in __init__() and when you need to reset would be cleaner.\n"
] |
[
15,
6,
1
] |
[] |
[] |
[
"initialization",
"python"
] |
stackoverflow_0002144988_initialization_python.txt
|
Q:
Archiving (tar and compress) with metadata (user id, and ctime) in Python
I am in the process of backing up a filesystem and I need to make sure that the metadata is conserved (the file owner and creation time).
The tarfile module in Python is really helpful, and I use it extensively in my solution. However, I cannot create the tar file with files conserving their metadata (presumably because copy and copy2 cannot do this).
How would you approach this problem from within Python?
EDIT:
Just to make it clear to the community: the tarfile module in Python does provide means to store metadata via the Tarinfo object. Essentially, a Tarinfo object is the member of a Tar object, and it has all the information you may need. Please refer to the accepted post.
Thanks!
A:
"Presumably"? You mean you don't know? Have you tried? That said, as far as I know, tarfiles doesn't preserve ctime, and there would be little point in it, as ctime should be reset when you unpack. mtime is preserved, though, and the tarfile module handles mtime.
The python tarfile module uses TarInfo objects when you add files. Like so:
TarFile.addfile(tarinfo, fileobj=None)
The TarInfo object contains the file information:
TarInfo.mtime
Time of last modification.
TarInfo.uid
User ID of the user who originally stored this member.
TarInfo.gid
Group ID of the user who originally stored this member.
And loads of other metadata. See http://docs.python.org/library/tarfile.html
|
Archiving (tar and compress) with metadata (user id, and ctime) in Python
|
I am in the process of backing up a filesystem and I need to make sure that the metadata is conserved (the file owner and creation time).
The tarfile module in Python is really helpful, and I use it extensively in my solution. However, I cannot create the tar file with files conserving their metadata (presumably because copy and copy2 cannot do this).
How would you approach this problem from within Python?
EDIT:
Just to make it clear to the community: the tarfile module in Python does provide means to store metadata via the Tarinfo object. Essentially, a Tarinfo object is the member of a Tar object, and it has all the information you may need. Please refer to the accepted post.
Thanks!
|
[
"\"Presumably\"? You mean you don't know? Have you tried? That said, as far as I know, tarfiles doesn't preserve ctime, and there would be little point in it, as ctime should be reset when you unpack. mtime is preserved, though, and the tarfile module handles mtime.\nThe python tarfile module uses TarInfo objects when you add files. Like so:\nTarFile.addfile(tarinfo, fileobj=None)\n\nThe TarInfo object contains the file information:\nTarInfo.mtime\nTime of last modification.\n\nTarInfo.uid\nUser ID of the user who originally stored this member.\n\nTarInfo.gid\nGroup ID of the user who originally stored this member.\n\nAnd loads of other metadata. See http://docs.python.org/library/tarfile.html\n"
] |
[
2
] |
[] |
[] |
[
"archiving",
"backup",
"metadata",
"python",
"tar"
] |
stackoverflow_0002145182_archiving_backup_metadata_python_tar.txt
|
Q:
Have a Python CGI call a Perl CGI, passing original info (to limit searching private Mailman archives to logged-in users)
I need to have a Python CGI script do some stuff (a little bit of security checking), and then end up calling a Perl CGI script, passing anything it received (e.g., POST info) onto the Perl script.
For background, my reason for doing this is that I'm trying to integrate Swish searching with Mailman list archives.
Swish searching uses swish.cgi, a Perl script, but because these are private list archives I can't just allow people to call swish.cgi directly as recommended on this page: http://wpkg.org/Integrating_Mailman_with_a_Swish-e_search_engine#Mailman_configuration
I believe what I need to do is have the Mailman "private" cgi-bin file (written in Python) do its regular security checking (which calls a few Mailman/python modules) and THEN call on swish.cgi to do the search (after having verified that the user is on the mailing list).
Essentially, I believe the simplest solution would just be to protect access to the swish.cgi Perl script with a variant of the standard mailman cgi-bin/private Python script.
(I considered the idea that people could search with a non-protected swish.cgi, and people wouldn't be able to view the full results because those posts are already password-protected by default Mailman setup... but the problem is that even showing the Swish post excerpts in the search results could expose confidential information, so I must restrict access to even the search itself to just subscribers.)
If someone has a better idea of how to solve the overall problem without doing the Python-CGI-calls-Perl-CGI I'll be happy to consider that the "answer".
Just know that my goal is to make little (ideally no) changes to the standard Mailman installation. Copying the "private" cgi-bin script (whose source is mailman-2.1.12/Mailman/Cgi/private.py) and making changes to call swish.cgi is cool, but modifying the existing private cgi-bin script wouldn't really be cool.
Here's what I did to test the answer (using os.execv to replace the python script with the perl script, so that the perl script will inherit the python script's environment):
I created a pythontest script with:
import os
os.environ['FOO'] = 'BAR'
mydir = os.path.dirname(os.environ.get('SCRIPT_FILENAME'))
childprog = mydir + '/perltest'
childargs = []
os.execv(childprog, childargs)
Then a perltest script with:
print "Content-type: text/html\n\n";
while (($key,$value) = each %ENV) {
print "<p>$key=$value</p>\n";
}
Then I called http://myserver.com/cgi-bin/pythontest and saw that the environment printout included the custom FOO variable so the child perltest process had successfully inherited all the environment variables.
A:
I'm just going to state the obvious here because I don't have any detailed knowledge about your specific environment.
If your python script is a genuine CGI and not a mod_python script or similar then it is just a regular process spawned to handle the one request. You can use os.execv to replace it with another process (e.g. the perl CGI) and the new process will inherit the current process' environment, stdin, stdout and stderr. This assumes that you don't need to read stdin for your security checks. It may also depend on whether your CGI is running in a restricted environment. execv is potentially dangerous and might be blocked in such an environment.
If you're running from a mod_python environment or if you need to peek at posted data (i.e. stdin) then the execv approach isn't available to you. You have two main alternatives.
You could run the perl CGI directly (e.g. look at the subprocess module) handing it a correct environment and feeding it the correct data to its stdin. You can the spool the returned data from its stdout raw (or cooked if needed) directly back to the web server.
Otherwise, you could make a local web request to run the CGI. This is likely to require a bit less knowledge about the server setup, but a bit more work in the python CGI to make and handle the HTTP request.
|
Have a Python CGI call a Perl CGI, passing original info (to limit searching private Mailman archives to logged-in users)
|
I need to have a Python CGI script do some stuff (a little bit of security checking), and then end up calling a Perl CGI script, passing anything it received (e.g., POST info) onto the Perl script.
For background, my reason for doing this is that I'm trying to integrate Swish searching with Mailman list archives.
Swish searching uses swish.cgi, a Perl script, but because these are private list archives I can't just allow people to call swish.cgi directly as recommended on this page: http://wpkg.org/Integrating_Mailman_with_a_Swish-e_search_engine#Mailman_configuration
I believe what I need to do is have the Mailman "private" cgi-bin file (written in Python) do its regular security checking (which calls a few Mailman/python modules) and THEN call on swish.cgi to do the search (after having verified that the user is on the mailing list).
Essentially, I believe the simplest solution would just be to protect access to the swish.cgi Perl script with a variant of the standard mailman cgi-bin/private Python script.
(I considered the idea that people could search with a non-protected swish.cgi, and people wouldn't be able to view the full results because those posts are already password-protected by default Mailman setup... but the problem is that even showing the Swish post excerpts in the search results could expose confidential information, so I must restrict access to even the search itself to just subscribers.)
If someone has a better idea of how to solve the overall problem without doing the Python-CGI-calls-Perl-CGI I'll be happy to consider that the "answer".
Just know that my goal is to make little (ideally no) changes to the standard Mailman installation. Copying the "private" cgi-bin script (whose source is mailman-2.1.12/Mailman/Cgi/private.py) and making changes to call swish.cgi is cool, but modifying the existing private cgi-bin script wouldn't really be cool.
Here's what I did to test the answer (using os.execv to replace the python script with the perl script, so that the perl script will inherit the python script's environment):
I created a pythontest script with:
import os
os.environ['FOO'] = 'BAR'
mydir = os.path.dirname(os.environ.get('SCRIPT_FILENAME'))
childprog = mydir + '/perltest'
childargs = []
os.execv(childprog, childargs)
Then a perltest script with:
print "Content-type: text/html\n\n";
while (($key,$value) = each %ENV) {
print "<p>$key=$value</p>\n";
}
Then I called http://myserver.com/cgi-bin/pythontest and saw that the environment printout included the custom FOO variable so the child perltest process had successfully inherited all the environment variables.
|
[
"I'm just going to state the obvious here because I don't have any detailed knowledge about your specific environment.\nIf your python script is a genuine CGI and not a mod_python script or similar then it is just a regular process spawned to handle the one request. You can use os.execv to replace it with another process (e.g. the perl CGI) and the new process will inherit the current process' environment, stdin, stdout and stderr. This assumes that you don't need to read stdin for your security checks. It may also depend on whether your CGI is running in a restricted environment. execv is potentially dangerous and might be blocked in such an environment.\nIf you're running from a mod_python environment or if you need to peek at posted data (i.e. stdin) then the execv approach isn't available to you. You have two main alternatives.\nYou could run the perl CGI directly (e.g. look at the subprocess module) handing it a correct environment and feeding it the correct data to its stdin. You can the spool the returned data from its stdout raw (or cooked if needed) directly back to the web server.\nOtherwise, you could make a local web request to run the CGI. This is likely to require a bit less knowledge about the server setup, but a bit more work in the python CGI to make and handle the HTTP request.\n"
] |
[
1
] |
[] |
[] |
[
"cgi",
"mailman",
"python"
] |
stackoverflow_0002145097_cgi_mailman_python.txt
|
Q:
Can Moblin run (and compile) Python scripts?
I want to develop an app for Moblin for a competition.
The development environment needed by Moblin is too complicated to setup. It uses Anjuta as its IDE, but I could never make sense of the entire compilation toolchain.
However, I would like to know if Moblin could compile and run Python scripts. If I could write the app in Python instead of Anjuta, then my work would be a lot easier.
Please let me know..
--Rishi.
A:
It does not need to compile them, as it contains a Python interpreter already.
|
Can Moblin run (and compile) Python scripts?
|
I want to develop an app for Moblin for a competition.
The development environment needed by Moblin is too complicated to setup. It uses Anjuta as its IDE, but I could never make sense of the entire compilation toolchain.
However, I would like to know if Moblin could compile and run Python scripts. If I could write the app in Python instead of Anjuta, then my work would be a lot easier.
Please let me know..
--Rishi.
|
[
"It does not need to compile them, as it contains a Python interpreter already.\n"
] |
[
0
] |
[] |
[] |
[
"development_environment",
"python"
] |
stackoverflow_0002145334_development_environment_python.txt
|
Q:
Python / Django: Is it wise to use "Item" as a class name in Python (in Django in this case)?
I'm creating this:
# models.py
class Item(models.Model):
sku = models.CharField(max_length=20)
class Attribute(models.Model):
item = models.ForeignKey(Item, related_name='items')
Is that going to cause naming collisions in Python? Like:
# views.py
some_object.items.create(sku='123abc')
# Is there a place / way that this could cause errors, like:
# AttributeError: Bound method 'items' has no attribute "create"
# Since items() on a dict-like object could be a method to return a list,
# and Django could add support for .items() on a queryset right?
If it's a bad idea, I could change the name.
A:
It does seem a bit generic, but no more so than "Attribute". I would give it a prefix based on the app if possible.
A:
It's really not a problem. If you have some random object and feel 'items' is a suitable name for a method, then go ahead. It is not going to cause any collisions with names that happen to be used on other objects.
As long as you think the method name is not misleading and does not cause confusion, go ahead.
A:
A model isn't the same thing as a queryset, and neither of them is documented as being dict-like. There shouldn't be any problem with doing this.
If you are really worried, then make as much of this code public as possible, and get people using it :) If nothing else, the Django core team is really diligent about checking as much "in-the-wild" code as they can before extending the documented APIs in any way. They really do care about not breaking people's existing code, as much as possible.
If making it public isn't an option, then at least watch the mailing lists, so that when somebody proposes "Hey, let's add an .items method to Model!", you can at least chime in with a "that'll break my code" at the right time.
A:
go with default item_set, problem-free :)
|
Python / Django: Is it wise to use "Item" as a class name in Python (in Django in this case)?
|
I'm creating this:
# models.py
class Item(models.Model):
sku = models.CharField(max_length=20)
class Attribute(models.Model):
item = models.ForeignKey(Item, related_name='items')
Is that going to cause naming collisions in Python? Like:
# views.py
some_object.items.create(sku='123abc')
# Is there a place / way that this could cause errors, like:
# AttributeError: Bound method 'items' has no attribute "create"
# Since items() on a dict-like object could be a method to return a list,
# and Django could add support for .items() on a queryset right?
If it's a bad idea, I could change the name.
|
[
"It does seem a bit generic, but no more so than \"Attribute\". I would give it a prefix based on the app if possible.\n",
"It's really not a problem. If you have some random object and feel 'items' is a suitable name for a method, then go ahead. It is not going to cause any collisions with names that happen to be used on other objects.\nAs long as you think the method name is not misleading and does not cause confusion, go ahead.\n",
"A model isn't the same thing as a queryset, and neither of them is documented as being dict-like. There shouldn't be any problem with doing this.\nIf you are really worried, then make as much of this code public as possible, and get people using it :) If nothing else, the Django core team is really diligent about checking as much \"in-the-wild\" code as they can before extending the documented APIs in any way. They really do care about not breaking people's existing code, as much as possible.\nIf making it public isn't an option, then at least watch the mailing lists, so that when somebody proposes \"Hey, let's add an .items method to Model!\", you can at least chime in with a \"that'll break my code\" at the right time.\n",
"go with default item_set, problem-free :)\n"
] |
[
3,
2,
2,
1
] |
[] |
[] |
[
"django",
"naming",
"naming_conventions",
"python"
] |
stackoverflow_0002145282_django_naming_naming_conventions_python.txt
|
Q:
How can I set up Celery to call a custom initialization function before running my tasks?
I have a Django project and I'm trying to use Celery to submit tasks for background processing ( http://ask.github.com/celery/introduction.html ). Celery integrates well with Django and I've been able to submit my custom tasks and get back results.
The only problem is that I can't find a sane way of performing custom initialization in the daemon process. I need to call an expensive function that loads a lot of memory before I start processing the tasks, and I can't afford to call that function every time.
Has anyone had this problem before? Any ideas how to work around it without modifying the Celery source code?
Thanks
A:
You can either write a custom loader, or use the signals.
Loaders have the on_task_init method, which is called when a task is about to be executed,
and on_worker_init which is called by the celery+celerybeat main process.
Using signals is probably the easiest, the signals available are:
0.8.x:
task_prerun(task_id, task, args, kwargs)
Dispatched when a task is about to be executed by the worker (or locally
if using apply/or if CELERY_ALWAYS_EAGER has been set).
task_postrun(task_id, task, args, kwargs, retval)
Dispatched after a task has been executed in the same conditions as above.
task_sent(task_id, task, args, kwargs, eta, taskset)
Called when a task is applied (not good for long-running operations)
Additional signals available in 0.9.x (current master branch on github):
worker_init()
Called when celeryd has started (before the task is initialized, so if on a
system supporting fork, any memory changes would be copied to the child
worker processes).
worker_ready()
Called when celeryd is able to receive tasks.
worker_shutdown()
Called when celeryd is shutting down.
Here's an example precalculating something the first time a task is run in the process:
from celery.task import Task
from celery.registry import tasks
from celery.signals import task_prerun
_precalc_table = {}
class PowersOfTwo(Task):
def run(self, x):
if x in _precalc_table:
return _precalc_table[x]
else:
return x ** 2
tasks.register(PowersOfTwo)
def _precalc_numbers(**kwargs):
if not _precalc_table: # it's empty, so haven't been generated yet
for i in range(1024):
_precalc_table[i] = i ** 2
# need to use registered instance for sender argument.
task_prerun.connect(_precalc_numbers, sender=tasks[PowerOfTwo.name])
If you want the function to be run for all tasks, just skip the sender argument.
|
How can I set up Celery to call a custom initialization function before running my tasks?
|
I have a Django project and I'm trying to use Celery to submit tasks for background processing ( http://ask.github.com/celery/introduction.html ). Celery integrates well with Django and I've been able to submit my custom tasks and get back results.
The only problem is that I can't find a sane way of performing custom initialization in the daemon process. I need to call an expensive function that loads a lot of memory before I start processing the tasks, and I can't afford to call that function every time.
Has anyone had this problem before? Any ideas how to work around it without modifying the Celery source code?
Thanks
|
[
"You can either write a custom loader, or use the signals.\nLoaders have the on_task_init method, which is called when a task is about to be executed,\nand on_worker_init which is called by the celery+celerybeat main process.\nUsing signals is probably the easiest, the signals available are:\n0.8.x:\n\ntask_prerun(task_id, task, args, kwargs)\nDispatched when a task is about to be executed by the worker (or locally\nif using apply/or if CELERY_ALWAYS_EAGER has been set). \ntask_postrun(task_id, task, args, kwargs, retval)\nDispatched after a task has been executed in the same conditions as above.\ntask_sent(task_id, task, args, kwargs, eta, taskset)\nCalled when a task is applied (not good for long-running operations)\n\nAdditional signals available in 0.9.x (current master branch on github):\n\nworker_init()\nCalled when celeryd has started (before the task is initialized, so if on a\nsystem supporting fork, any memory changes would be copied to the child\nworker processes).\nworker_ready()\nCalled when celeryd is able to receive tasks.\nworker_shutdown()\nCalled when celeryd is shutting down.\n\nHere's an example precalculating something the first time a task is run in the process:\nfrom celery.task import Task\nfrom celery.registry import tasks\nfrom celery.signals import task_prerun\n\n_precalc_table = {}\n\nclass PowersOfTwo(Task):\n\n def run(self, x):\n if x in _precalc_table:\n return _precalc_table[x]\n else:\n return x ** 2\ntasks.register(PowersOfTwo)\n\n\ndef _precalc_numbers(**kwargs):\n if not _precalc_table: # it's empty, so haven't been generated yet\n for i in range(1024):\n _precalc_table[i] = i ** 2\n\n\n# need to use registered instance for sender argument.\ntask_prerun.connect(_precalc_numbers, sender=tasks[PowerOfTwo.name])\n\nIf you want the function to be run for all tasks, just skip the sender argument.\n"
] |
[
21
] |
[] |
[] |
[
"amqp",
"celery",
"daemon",
"django",
"python"
] |
stackoverflow_0002129820_amqp_celery_daemon_django_python.txt
|
Q:
Convert Unicode/UTF-8 string to lower/upper case using pure & pythonic library
I use Google App Engine and cannot use any C/C++ extension, just pure & pythonic library to do conversion of Unicode/UTF-8 strings to lower/upper case. str.lower() and string.lowercase() don't.
A:
str encoded in UTF-8 and unicode are two different types. Don't use string, use the appropriate method on the unicode object:
>>> print u'ĉ'.upper()
Ĉ
Decode str to unicode before using:
>>> print 'ĉ'.decode('utf-8').upper()
Ĉ
|
Convert Unicode/UTF-8 string to lower/upper case using pure & pythonic library
|
I use Google App Engine and cannot use any C/C++ extension, just pure & pythonic library to do conversion of Unicode/UTF-8 strings to lower/upper case. str.lower() and string.lowercase() don't.
|
[
"str encoded in UTF-8 and unicode are two different types. Don't use string, use the appropriate method on the unicode object:\n>>> print u'ĉ'.upper()\nĈ\n\nDecode str to unicode before using:\n>>> print 'ĉ'.decode('utf-8').upper()\nĈ\n\n"
] |
[
26
] |
[] |
[] |
[
"case_conversion",
"google_app_engine",
"python"
] |
stackoverflow_0002145826_case_conversion_google_app_engine_python.txt
|
Q:
Escape @ from python line command
I don't know if this is a problem with python or with the shell (zsh on linux), I've an argument like this: "@xyz" that starts with a "@"
python the_script.py first_argument @second_argument third_arg
I tried to escape @ with \ or \\, or use "" but the program doesn't start. If I leave the @ from @second_arguments everything's ok.
A:
Perhaps the "@" is a glob character in zsh, expanding to all symbolic links in the current directory. Try escaping it with "@@"?
Try running the argument list with echo, i.e:
echo the_script.py first_argument @second_argument third_arg
That way, you can figure out if it was expanded or passed as-is to the script.
|
Escape @ from python line command
|
I don't know if this is a problem with python or with the shell (zsh on linux), I've an argument like this: "@xyz" that starts with a "@"
python the_script.py first_argument @second_argument third_arg
I tried to escape @ with \ or \\, or use "" but the program doesn't start. If I leave the @ from @second_arguments everything's ok.
|
[
"\nPerhaps the \"@\" is a glob character in zsh, expanding to all symbolic links in the current directory. Try escaping it with \"@@\"?\nTry running the argument list with echo, i.e:\necho the_script.py first_argument @second_argument third_arg\n\nThat way, you can figure out if it was expanded or passed as-is to the script.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"zsh"
] |
stackoverflow_0002145901_python_zsh.txt
|
Q:
__cmp__ method is this not working as expected in Python 2.x?
class x:
def __init__(self,name):
self.name=name
def __str__(self):
return self.name
def __cmp__(self,other):
print("cmp method called with self="+str(self)+",other="+str(other))
return self.name==other.name
# return False
instance1=x("hello")
instance2=x("there")
print(instance1==instance2)
print(instance1.name==instance2.name)
The output here is:
cmp method called with self=hello,other=there
True
False
Which is not what I expected: I'm trying to say 'two instances are equal if the name fields are equal'.
If I simply return False from the __cmp__ function, this reports as True as well!!
If I return -1, then I get False - but since I'm trying to compare strings, this doesn't feel right.
What am I doing wrong here?
A:
__cmp__(x,y) should return a negative number (e.g. -1) if x < y, a positive number (e.g. 1) if x > y and 0 if x == y. You should never return a boolean with it.
What you're overloading is __eq__(x, y).
A:
the __cmp__ method should return -1, 0 or 1, when self < other, self == other, self > other respectvelly.
You can do
return cmp(self.name, other.name)
in your code for a proper result
A:
You're confusing __cmp__ with __eq__.
From the documentation of __cmp__:
Should return a negative integer if self < other, zero if self == other, a positive integer if self > other.
__eq__ returns a boolean which determines if two objects are equal, __cmp__ returns an integer which determines if the two objects are greater or less than each other, and so is called unless you have specific __eq__, __ne__, __le__, __ge__, __lt__ and __gt__ methods.
In your case you do want a __cmp__ method rather than __eq__ as it will save you implementing the other 5 methods for the other comparisons.
You could use the cmp() function and put the following in your __cmp__ method:
return cmp(self.name,other.name)
Note, as highlighted by Ignacio is this isn't the preferred method in Python 3.0, but in Python 2.x __cmp__ is the way to go.
A:
__cmp__() is obsolescent. Define __lt__(), __eq__(), and __gt__() instead.
Even so, you're doing it wrong. You're supposed to return an integer.
A:
Lookup the documentation for __cmp__, youre supposed to return an integer:
Should return a negative integer if
self < other, zero if self == other, a
positive integer if self > other.
|
__cmp__ method is this not working as expected in Python 2.x?
|
class x:
def __init__(self,name):
self.name=name
def __str__(self):
return self.name
def __cmp__(self,other):
print("cmp method called with self="+str(self)+",other="+str(other))
return self.name==other.name
# return False
instance1=x("hello")
instance2=x("there")
print(instance1==instance2)
print(instance1.name==instance2.name)
The output here is:
cmp method called with self=hello,other=there
True
False
Which is not what I expected: I'm trying to say 'two instances are equal if the name fields are equal'.
If I simply return False from the __cmp__ function, this reports as True as well!!
If I return -1, then I get False - but since I'm trying to compare strings, this doesn't feel right.
What am I doing wrong here?
|
[
"__cmp__(x,y) should return a negative number (e.g. -1) if x < y, a positive number (e.g. 1) if x > y and 0 if x == y. You should never return a boolean with it.\nWhat you're overloading is __eq__(x, y).\n",
"the __cmp__ method should return -1, 0 or 1, when self < other, self == other, self > other respectvelly.\nYou can do\nreturn cmp(self.name, other.name)\n\nin your code for a proper result\n",
"You're confusing __cmp__ with __eq__.\nFrom the documentation of __cmp__:\n\nShould return a negative integer if self < other, zero if self == other, a positive integer if self > other.\n\n__eq__ returns a boolean which determines if two objects are equal, __cmp__ returns an integer which determines if the two objects are greater or less than each other, and so is called unless you have specific __eq__, __ne__, __le__, __ge__, __lt__ and __gt__ methods. \nIn your case you do want a __cmp__ method rather than __eq__ as it will save you implementing the other 5 methods for the other comparisons.\nYou could use the cmp() function and put the following in your __cmp__ method:\nreturn cmp(self.name,other.name)\n\nNote, as highlighted by Ignacio is this isn't the preferred method in Python 3.0, but in Python 2.x __cmp__ is the way to go.\n",
"__cmp__() is obsolescent. Define __lt__(), __eq__(), and __gt__() instead.\nEven so, you're doing it wrong. You're supposed to return an integer.\n",
"Lookup the documentation for __cmp__, youre supposed to return an integer:\n\nShould return a negative integer if\n self < other, zero if self == other, a\n positive integer if self > other.\n\n"
] |
[
10,
5,
4,
2,
0
] |
[] |
[] |
[
"cmp",
"python",
"python_2.x"
] |
stackoverflow_0002146225_cmp_python_python_2.x.txt
|
Q:
Python image processing of picture directly from the web
I am writing python code to take an image from the web and calculate the standard deviation, ... and do other image processing with it. I have the following code:
from scipy import ndimage
from urllib2 import urlopen
from urllib import urlretrieve
import urllib2
import Image
import ImageFilter
def imagesd(imagelist):
for imageurl in imagelist:
opener1 = urllib2.build_opener()
page1 = opener1.open(imageurl)
im = page1.read()
#localfile = urlretrieve(
#img = Image.fromstring("RGBA", (1,1), page1.read())
#img = list(im.getdata())
# page1.read()
print img
#standard_deviation(p
Now I keep going back and forth because I am not sure how to take the image directly from the web, without saving it to disk, and passing it to the standard deviation function.
Any hints/help would be greatly appreciated.
Thanks.
A:
PIL (Python Imaging Library) methods "fromstring" and "frombuffer" expect the image data in a raw, uncompacted, format.
When you do page1.read() you get the binary file data. In order to have PIL understanding it, you have to make this data mimick a file, and pass it to the "Image.open" method, which understands the file format as it is read from the web (i.e., the .jpg, gif, or .png data instead of raw pixel values)
Try something like this:
from cStringIO import StringIO
(...)
data = StringIO(page1.read())
img = Image.open(data)
|
Python image processing of picture directly from the web
|
I am writing python code to take an image from the web and calculate the standard deviation, ... and do other image processing with it. I have the following code:
from scipy import ndimage
from urllib2 import urlopen
from urllib import urlretrieve
import urllib2
import Image
import ImageFilter
def imagesd(imagelist):
for imageurl in imagelist:
opener1 = urllib2.build_opener()
page1 = opener1.open(imageurl)
im = page1.read()
#localfile = urlretrieve(
#img = Image.fromstring("RGBA", (1,1), page1.read())
#img = list(im.getdata())
# page1.read()
print img
#standard_deviation(p
Now I keep going back and forth because I am not sure how to take the image directly from the web, without saving it to disk, and passing it to the standard deviation function.
Any hints/help would be greatly appreciated.
Thanks.
|
[
"PIL (Python Imaging Library) methods \"fromstring\" and \"frombuffer\" expect the image data in a raw, uncompacted, format. \nWhen you do page1.read() you get the binary file data. In order to have PIL understanding it, you have to make this data mimick a file, and pass it to the \"Image.open\" method, which understands the file format as it is read from the web (i.e., the .jpg, gif, or .png data instead of raw pixel values)\nTry something like this:\nfrom cStringIO import StringIO\n(...)\n data = StringIO(page1.read())\n img = Image.open(data)\n\n"
] |
[
4
] |
[] |
[] |
[
"image",
"image_processing",
"python",
"urllib2"
] |
stackoverflow_0002145955_image_image_processing_python_urllib2.txt
|
Q:
Help parsing a page with python
I would like to parse a webpage to can get the url of the video download. I use python and firebug but I cant get the url link.
Example:
The url where I have to get the video link is:
hxxp://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.shtml"
The video is
hxxp://www.rtve.es/resources/TE_SSAC011/flv/8/2/1264426362028.flv
Could you help me please?
Many thanks and sorry for my english!
A:
Use BeautifulSoup or lxml.
A:
import re
from urllib2 import urlopen
text = urlopen('http://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.shtm').read()
reg = re.compile(r'http://www\.rtv.*flv')
reg.findall(text)
Normallly you can use this one. But there is no your link inside.
A:
@OP, those videos are generated by javascript. For this topic, see here. Or search google for references.
|
Help parsing a page with python
|
I would like to parse a webpage to can get the url of the video download. I use python and firebug but I cant get the url link.
Example:
The url where I have to get the video link is:
hxxp://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.shtml"
The video is
hxxp://www.rtve.es/resources/TE_SSAC011/flv/8/2/1264426362028.flv
Could you help me please?
Many thanks and sorry for my english!
|
[
"Use BeautifulSoup or lxml.\n",
"import re \nfrom urllib2 import urlopen\ntext = urlopen('http://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.shtm').read()\nreg = re.compile(r'http://www\\.rtv.*flv')\nreg.findall(text)\n\nNormallly you can use this one. But there is no your link inside.\n",
"@OP, those videos are generated by javascript. For this topic, see here. Or search google for references.\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"parsing",
"python",
"screen_scraping"
] |
stackoverflow_0002146110_parsing_python_screen_scraping.txt
|
Q:
Leading and Trailing '0' gives error
random.randint(50,9)
or
random.randint(5,09)
give errors, although just
random.randint(5,9)
..works!
Leading and trailing zero's aren't allowed in python without converting it to string or using x.f formatting?
A:
oh, dear. "Trailing" zero gives error because first argument to randint should be smaller than the second.
Leading zeros are used to represent octal numbers in python-2.x as in many other languages.
A:
A leading 0 means that the value is an octal literal, but 09 is not a valid octal number.
A:
09 is not a valid dec integer in the second case
and in the first case - you have to give the function the lower number first
|
Leading and Trailing '0' gives error
|
random.randint(50,9)
or
random.randint(5,09)
give errors, although just
random.randint(5,9)
..works!
Leading and trailing zero's aren't allowed in python without converting it to string or using x.f formatting?
|
[
"oh, dear. \"Trailing\" zero gives error because first argument to randint should be smaller than the second.\nLeading zeros are used to represent octal numbers in python-2.x as in many other languages.\n",
"A leading 0 means that the value is an octal literal, but 09 is not a valid octal number.\n",
"09 is not a valid dec integer in the second case\nand in the first case - you have to give the function the lower number first\n"
] |
[
6,
0,
0
] |
[] |
[] |
[
"integer",
"octal",
"python"
] |
stackoverflow_0002146381_integer_octal_python.txt
|
Q:
Python globals, locals, and UnboundLocalError
I ran across this case of UnboundLocalError recently, which seems strange:
import pprint
def main():
if 'pprint' in globals(): print 'pprint is in globals()'
pprint.pprint('Spam')
from pprint import pprint
pprint('Eggs')
if __name__ == '__main__': main()
Which produces:
pprint is in globals()
Traceback (most recent call last):
File "weird.py", line 9, in <module>
if __name__ == '__main__': main()
File "weird.py", line 5, in main
pprint.pprint('Spam')
UnboundLocalError: local variable 'pprint' referenced before assignment
pprint is clearly bound in globals, and is going to be bound in locals in the following statement. Can someone offer an explanation of why it isn't happy resolving pprint to the binding in globals here?
Edit: Thanks to the good responses I can clarify my question with relevant terminology:
At compile time the identifier pprint is marked as local to the frame. Does the execution model have no distinction where within the frame the local identifier is bound? Can it say, "refer to the global binding up until this bytecode instruction, at which point it has been rebound to a local binding," or does the execution model not account for this?
A:
Where's the surprise? Any variable global to a scope that you reassign within that scope is marked local to that scope by the compiler.
If imports would be handled differently, that would be surprising imho.
It may make a case for not naming modules after symbols used therein, or vice versa, though.
A:
Well, that was interesting enough for me to experiment a bit and I read through http://docs.python.org/reference/executionmodel.html
Then did some tinkering with your code here and there, this is what i could find:
code:
import pprint
def two():
from pprint import pprint
print globals()['pprint']
pprint('Eggs')
print globals()['pprint']
def main():
if 'pprint' in globals():
print 'pprint is in globals()'
global pprint
print globals()['pprint']
pprint.pprint('Spam')
from pprint import pprint
print globals()['pprint']
pprint('Eggs')
def three():
print globals()['pprint']
pprint.pprint('Spam')
if __name__ == '__main__':
two()
print('\n')
three()
print('\n')
main()
output:
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Eggs'
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Spam'
pprint is in globals()
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Spam'
<function pprint at 0xb7d596f4>
'Eggs'
In the method two() from pprint import pprint but does not override the name pprint in globals, since the global keyword is not used in the scope of two().
In method three() since there is no declaration of pprint name in local scope it defaults to the global name pprint which is a module
Whereas in main(), at first the keyword global is used so all references to pprint in the scope of method main() will refer to the global name pprint. Which as we can see is a module at first and is overriden in the global namespace with a method as we do the from pprint import pprint
Though this may not be answering the question as such, but nevertheless its some interesting fact I think.
=====================
Edit Another interesting thing.
If you have a module say:
mod1
from datetime import datetime
def foo():
print "bar"
and another method say:
mod2
import datetime
from mod1 import *
if __name__ == '__main__':
print datetime.datetime.now()
which at first sight is seemingly correct since you have imported the module datetime in mod2.
now if you try to run mod2 as a script it will throw an error:
Traceback (most recent call last):
File "mod2.py", line 5, in <module>
print datetime.datetime.now()
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
because the second import from mod2 import * has overriden the name datetime in the namespace, hence the first import datetime is not valid anymore.
Moral: Thus the order of imports, the nature of imports (from x import *) and the awareness of imports within imported modules - matters.
A:
Looks like Python sees the from pprint import pprint line and marks pprint as a name local to main() before executing any code. Since Python thinks pprint ought to be a local variable, referencing it with pprint.pprint() before "assigning" it with the from..import statement, it throws that error.
That's as much sense as I can make of that.
The moral, of course, is to always put those import statements at the top of the scope.
A:
This question got answered several weeks ago, but I think I can clarify the answers a little. First some facts.
1: In Python,
import foo
is almost exactly the same as
foo = __import__("foo", globals(), locals(), [], -1)
2: When executing code in a function, if Python encounters a variable that hasn't been defined in the function yet, it looks in the global scope.
3: Python has an optimization it uses for functions called "locals". When Python tokenizes a function, it keeps track of all the variables you assign to. It assigns each of these variables a number from a local monotonically increasing integer. When Python runs the function, it creates an array with as many slots as there are local variables, and it assigns each slot a special value that means "has not been assigned to yet", and that's where the values for those variables are stored. If you reference a local that hasn't been assigned to yet, Python sees that special value and throws an UnboundLocalValue exception.
The stage is now set. Your "from pprint import pprint" is really a form of assignment. So Python creates a local variable called "pprint" which occludes the global variable. Then, when you refer to "pprint.pprint" in the function, you hit the special value and Python throws the exception. If you didn't have that import statement in the function, Python would use the normal look-in-locals-first-then-look-in-globals resolution and find the pprint module in globals.
To disambiguate this you can use the "global" keyword. Of course by now you've already worked past your problem, and I don't know whether you really needed "global" or if some other approach was called for.
|
Python globals, locals, and UnboundLocalError
|
I ran across this case of UnboundLocalError recently, which seems strange:
import pprint
def main():
if 'pprint' in globals(): print 'pprint is in globals()'
pprint.pprint('Spam')
from pprint import pprint
pprint('Eggs')
if __name__ == '__main__': main()
Which produces:
pprint is in globals()
Traceback (most recent call last):
File "weird.py", line 9, in <module>
if __name__ == '__main__': main()
File "weird.py", line 5, in main
pprint.pprint('Spam')
UnboundLocalError: local variable 'pprint' referenced before assignment
pprint is clearly bound in globals, and is going to be bound in locals in the following statement. Can someone offer an explanation of why it isn't happy resolving pprint to the binding in globals here?
Edit: Thanks to the good responses I can clarify my question with relevant terminology:
At compile time the identifier pprint is marked as local to the frame. Does the execution model have no distinction where within the frame the local identifier is bound? Can it say, "refer to the global binding up until this bytecode instruction, at which point it has been rebound to a local binding," or does the execution model not account for this?
|
[
"Where's the surprise? Any variable global to a scope that you reassign within that scope is marked local to that scope by the compiler. \nIf imports would be handled differently, that would be surprising imho.\nIt may make a case for not naming modules after symbols used therein, or vice versa, though.\n",
"Well, that was interesting enough for me to experiment a bit and I read through http://docs.python.org/reference/executionmodel.html\nThen did some tinkering with your code here and there, this is what i could find:\ncode:\nimport pprint\n\ndef two():\n from pprint import pprint\n print globals()['pprint']\n pprint('Eggs')\n print globals()['pprint']\n\ndef main():\n if 'pprint' in globals():\n print 'pprint is in globals()'\n global pprint\n print globals()['pprint']\n pprint.pprint('Spam')\n from pprint import pprint\n print globals()['pprint']\n pprint('Eggs')\n\ndef three():\n print globals()['pprint']\n pprint.pprint('Spam')\n\nif __name__ == '__main__':\n two()\n print('\\n')\n three()\n print('\\n')\n main()\n\noutput:\n<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>\n'Eggs'\n<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>\n\n<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>\n'Spam'\n\npprint is in globals()\n<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>\n'Spam'\n<function pprint at 0xb7d596f4>\n'Eggs'\n\nIn the method two() from pprint import pprint but does not override the name pprint in globals, since the global keyword is not used in the scope of two().\nIn method three() since there is no declaration of pprint name in local scope it defaults to the global name pprint which is a module\nWhereas in main(), at first the keyword global is used so all references to pprint in the scope of method main() will refer to the global name pprint. Which as we can see is a module at first and is overriden in the global namespace with a method as we do the from pprint import pprint \nThough this may not be answering the question as such, but nevertheless its some interesting fact I think.\n=====================\nEdit Another interesting thing.\nIf you have a module say:\nmod1\nfrom datetime import datetime\n\ndef foo():\n print \"bar\"\n\nand another method say:\nmod2\nimport datetime\nfrom mod1 import *\n\nif __name__ == '__main__':\n print datetime.datetime.now()\n\nwhich at first sight is seemingly correct since you have imported the module datetime in mod2.\nnow if you try to run mod2 as a script it will throw an error:\nTraceback (most recent call last):\n File \"mod2.py\", line 5, in <module>\n print datetime.datetime.now()\nAttributeError: type object 'datetime.datetime' has no attribute 'datetime'\n\nbecause the second import from mod2 import * has overriden the name datetime in the namespace, hence the first import datetime is not valid anymore. \nMoral: Thus the order of imports, the nature of imports (from x import *) and the awareness of imports within imported modules - matters.\n",
"Looks like Python sees the from pprint import pprint line and marks pprint as a name local to main() before executing any code. Since Python thinks pprint ought to be a local variable, referencing it with pprint.pprint() before \"assigning\" it with the from..import statement, it throws that error. \nThat's as much sense as I can make of that. \nThe moral, of course, is to always put those import statements at the top of the scope.\n",
"This question got answered several weeks ago, but I think I can clarify the answers a little. First some facts.\n1: In Python,\nimport foo\n\nis almost exactly the same as\nfoo = __import__(\"foo\", globals(), locals(), [], -1)\n\n2: When executing code in a function, if Python encounters a variable that hasn't been defined in the function yet, it looks in the global scope.\n3: Python has an optimization it uses for functions called \"locals\". When Python tokenizes a function, it keeps track of all the variables you assign to. It assigns each of these variables a number from a local monotonically increasing integer. When Python runs the function, it creates an array with as many slots as there are local variables, and it assigns each slot a special value that means \"has not been assigned to yet\", and that's where the values for those variables are stored. If you reference a local that hasn't been assigned to yet, Python sees that special value and throws an UnboundLocalValue exception.\nThe stage is now set. Your \"from pprint import pprint\" is really a form of assignment. So Python creates a local variable called \"pprint\" which occludes the global variable. Then, when you refer to \"pprint.pprint\" in the function, you hit the special value and Python throws the exception. If you didn't have that import statement in the function, Python would use the normal look-in-locals-first-then-look-in-globals resolution and find the pprint module in globals.\nTo disambiguate this you can use the \"global\" keyword. Of course by now you've already worked past your problem, and I don't know whether you really needed \"global\" or if some other approach was called for.\n"
] |
[
6,
5,
4,
4
] |
[] |
[] |
[
"binding",
"identifier",
"python",
"scope"
] |
stackoverflow_0000404534_binding_identifier_python_scope.txt
|
Q:
Can I use WSGI with a URI that has spaces?
I wrote a small WSGI App:
def foo(environ, start_response):
bar = 'Your request is %s' % environ['PATH_INFO']
status = '200 OK'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(bar)))]
start_response(status, response_headers)
return [bar]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
server = make_server('localhost', 8000, foo)
print "Running..."
server.serve_forever()
And another script to test:
import urllib2
checkURL = 'http://localhost:8000/foo bar'
print urllib2.urlopen(checkURL).read()
I run script 1 (WSGI App). When run script 2, I has a problem here. WSGI doesn't retrieve request from script 2 (checkURL has a space between foo and bar) and all other request to my WSGI not responding.
Now, how do I correct this problem when url request has spaces?
A:
From http://www.ietf.org/rfc/rfc2396.txt
The space character is excluded because significant spaces may
disappear and insignificant spaces may be introduced when URI are
transcribed or typeset or subjected to the treatment of word-
processing programs. Whitespace is also used to delimit URI in many
contexts.
space = <US-ASCII coded character 20 hexadecimal>
Bottom line. No, you cannot use a space. It is not a problem with the WSGI server. It is a problem with your URI.
Further, you should not be using the WSGI server stand-alone. You should be using it embedded in Apache via mod_wsgi. When you do this, Apache will handle the illegal URI requests for you.
A:
Update
Typically a WSGI URI will look something like localhost:8000/foo/bar/baz or localhost:8000/?foo=bar and not use spaces, so I suspect that the server is timing out because it doesn't have built-in handling for spaces.
Maybe your question is really "Can I use WSGI with a URI that has spaces?" -- I think the answer is No, as @S.Lott explains that server's front-end should handle this for you; you shouldn't need to worry about spaces in your WSGI app.
Original answer
If replacing spaces is a fix (your reply to my comment seems like it is) , then you can use urllib2.quote() to replace the spaces in your URL with %20, like this:
checkURL = 'http://localhost:8000/%s' % urllib2.quote('foo bar')
A:
I moved from wsgiref.simple_server to cherrypy and it work well. Client request will time out after about 1s. Thanks jcoon and S.Lott very much!
|
Can I use WSGI with a URI that has spaces?
|
I wrote a small WSGI App:
def foo(environ, start_response):
bar = 'Your request is %s' % environ['PATH_INFO']
status = '200 OK'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(bar)))]
start_response(status, response_headers)
return [bar]
if __name__ == '__main__':
from wsgiref.simple_server import make_server
server = make_server('localhost', 8000, foo)
print "Running..."
server.serve_forever()
And another script to test:
import urllib2
checkURL = 'http://localhost:8000/foo bar'
print urllib2.urlopen(checkURL).read()
I run script 1 (WSGI App). When run script 2, I has a problem here. WSGI doesn't retrieve request from script 2 (checkURL has a space between foo and bar) and all other request to my WSGI not responding.
Now, how do I correct this problem when url request has spaces?
|
[
"From http://www.ietf.org/rfc/rfc2396.txt\nThe space character is excluded because significant spaces may\n disappear and insignificant spaces may be introduced when URI are\n transcribed or typeset or subjected to the treatment of word-\n processing programs. Whitespace is also used to delimit URI in many\n contexts.\nspace = <US-ASCII coded character 20 hexadecimal>\nBottom line. No, you cannot use a space. It is not a problem with the WSGI server. It is a problem with your URI.\nFurther, you should not be using the WSGI server stand-alone. You should be using it embedded in Apache via mod_wsgi. When you do this, Apache will handle the illegal URI requests for you.\n",
"Update\nTypically a WSGI URI will look something like localhost:8000/foo/bar/baz or localhost:8000/?foo=bar and not use spaces, so I suspect that the server is timing out because it doesn't have built-in handling for spaces. \nMaybe your question is really \"Can I use WSGI with a URI that has spaces?\" -- I think the answer is No, as @S.Lott explains that server's front-end should handle this for you; you shouldn't need to worry about spaces in your WSGI app. \n\nOriginal answer\nIf replacing spaces is a fix (your reply to my comment seems like it is) , then you can use urllib2.quote() to replace the spaces in your URL with %20, like this:\ncheckURL = 'http://localhost:8000/%s' % urllib2.quote('foo bar')\n\n",
"I moved from wsgiref.simple_server to cherrypy and it work well. Client request will time out after about 1s. Thanks jcoon and S.Lott very much!\n"
] |
[
1,
0,
0
] |
[
"You should use \"%20\" in URL's to encode spaces into then -- but don't do that manually:\nuse urllib.quote function, like:\n\n\n\nimport urllib\n base = \"http://localhost:8000/\"\n path = urllib.quote(\"foo bar\")\n checkURL = base + path\n\n\n\n(there is also the \"unquote\" function for you to use serverside)\n"
] |
[
-1
] |
[
"python",
"spaces",
"wsgi"
] |
stackoverflow_0002139613_python_spaces_wsgi.txt
|
Q:
Should a class or method which processes a file close the file as a side effect?
I'm wondering which is the more 'Pythonic' / better way to write methods which process files. Should the method which processes the file close that file as a side effect? Should the concept of the data being a 'file' be completely abstracted from the method which is processing the data, meaning it should expect some 'stream' but not necessarily a file?:
As an example, is it OK to do this:
process(open('somefile','r'))
... carry on
Where process() closes the file handle:
def process(somefile):
# do some stuff with somefile
somefile.close()
Or is this better:
file = open('somefile','r')
process(file)
file.close()
For what it's worth, I generally am using Python to write relatively simple scripts that are extremely specifically purposed, where I'll likely be the only one ever using them. That said, I don't want to teach myself any bad practices, and I'd rather learn the best way to do things, as even a small job is worth doing well.
A:
Generally, it is better practice for the opener of a file to close the file. In your question, the second example is better.
This is to prevent possible confusion and invalid operations.
Edit: If your real code isn't any more complex than your example code, then it might be better just to have process() open and close the file, since the caller doesn't use the file for anything else. Just pass in the path/name of the file. But if it is conceivable that a caller to process() will use the file before the file should be closed, then leave the file open and close operations outside of process().
A:
Using with means not having to worry about this.
At least, not on 2.5+.
A:
No, because it reduces flexibility: if function doesn't close file and caller doesn't need it - caller can close file. If it does but caller still need file open - caller stuck with reopening file, using StringIO, or something else.
Also closing file object require additional assumptions on it's real type (object can support .read() or .write(), but have no meaningful .close()), hindering duck-typing.
And files-left-open is not a problem for CPython - it will be closed on garbage collection instantly after something(open('somefile')). (other implementation will gc and close file too, but at unspecified moment)
|
Should a class or method which processes a file close the file as a side effect?
|
I'm wondering which is the more 'Pythonic' / better way to write methods which process files. Should the method which processes the file close that file as a side effect? Should the concept of the data being a 'file' be completely abstracted from the method which is processing the data, meaning it should expect some 'stream' but not necessarily a file?:
As an example, is it OK to do this:
process(open('somefile','r'))
... carry on
Where process() closes the file handle:
def process(somefile):
# do some stuff with somefile
somefile.close()
Or is this better:
file = open('somefile','r')
process(file)
file.close()
For what it's worth, I generally am using Python to write relatively simple scripts that are extremely specifically purposed, where I'll likely be the only one ever using them. That said, I don't want to teach myself any bad practices, and I'd rather learn the best way to do things, as even a small job is worth doing well.
|
[
"Generally, it is better practice for the opener of a file to close the file. In your question, the second example is better.\nThis is to prevent possible confusion and invalid operations.\n\nEdit: If your real code isn't any more complex than your example code, then it might be better just to have process() open and close the file, since the caller doesn't use the file for anything else. Just pass in the path/name of the file. But if it is conceivable that a caller to process() will use the file before the file should be closed, then leave the file open and close operations outside of process().\n\n",
"Using with means not having to worry about this.\nAt least, not on 2.5+.\n",
"No, because it reduces flexibility: if function doesn't close file and caller doesn't need it - caller can close file. If it does but caller still need file open - caller stuck with reopening file, using StringIO, or something else.\nAlso closing file object require additional assumptions on it's real type (object can support .read() or .write(), but have no meaningful .close()), hindering duck-typing.\nAnd files-left-open is not a problem for CPython - it will be closed on garbage collection instantly after something(open('somefile')). (other implementation will gc and close file too, but at unspecified moment)\n"
] |
[
4,
4,
0
] |
[] |
[] |
[
"file_io",
"python"
] |
stackoverflow_0002147153_file_io_python.txt
|
Q:
csv.reader turning commas into periods throwing errors
Here is a sample of the first row:
link,Title,Description,Keywords
It is made from an excel workbook, I tried saving in all CSV formats (window, ms-dos, and comma delimited list) I even tried saving in 2 txt file formats (window, ms-dos)
k...
here is the code:
csvReader = csv.reader(file('files/my_file.csv', "rU"), delimiter=',')
I must have the U otherwise I get the universal new line error
k...
here is the error:
16:56:25,085 ERROR [__main__] Script Error: syntax error at or near "."
LINE 1: ...escription, meta_keywords) VALUES ('link', 'Title'. 'Descrip...
^
16:56:25,085 ERROR [__main__] Script Error: syntax error at or near "."
LINE 1: ...escription, meta_keywords) VALUES ('link', 'Title'. 'Descrip...
grumbles
Do you see...for some reason, when it goes through the csv.reader function, first comma is OK, second comma becomes a period!
Anyone ever run into this?
A:
Dalkes comment above dropped the coin for me:
You are reading from a CSV file, and taking that data and inserting in an SQL database, evidently, although you did not say so. You have a syntax error in your SQL-statement.
Note that most SQL databases have CSV imports, so you don't need to write them.
Also note that you evidently are trying to import the first row, which contains column headings. That's surely incorrect.
This all shows that it's important on Stackoverflow to show real code that has the problem.
Narrow down the code until you can show your problem in code that's small enough to paste here.
99% of the time you'll find the error while doing that.
A:
it is the values statement! geez, but I did a log.debug and didn't see it output which was before the sql ...but that is most def what it is. I wasn't trying to import the first row, I plugged that in there purposely to not show actual data. Sorry for the inconvenience. I didn't think the code was making it past that line I did post. And it is the real code all but the file name. I am new to Python, not SQL, so I was sure it was the csv.reader since it is so foreign to me. Thank you guys for your help.
A:
The csv.reader is not responsible for constructing the SQL statement whose fragment is being shown in the error message you posted -- some other part of your code must be the one that constructs this statement, and it's doing that in the wrong way. So don't think about csv.reader, but about what you do with the tuples it's returning to the rest of your code!-)
|
csv.reader turning commas into periods throwing errors
|
Here is a sample of the first row:
link,Title,Description,Keywords
It is made from an excel workbook, I tried saving in all CSV formats (window, ms-dos, and comma delimited list) I even tried saving in 2 txt file formats (window, ms-dos)
k...
here is the code:
csvReader = csv.reader(file('files/my_file.csv', "rU"), delimiter=',')
I must have the U otherwise I get the universal new line error
k...
here is the error:
16:56:25,085 ERROR [__main__] Script Error: syntax error at or near "."
LINE 1: ...escription, meta_keywords) VALUES ('link', 'Title'. 'Descrip...
^
16:56:25,085 ERROR [__main__] Script Error: syntax error at or near "."
LINE 1: ...escription, meta_keywords) VALUES ('link', 'Title'. 'Descrip...
grumbles
Do you see...for some reason, when it goes through the csv.reader function, first comma is OK, second comma becomes a period!
Anyone ever run into this?
|
[
"Dalkes comment above dropped the coin for me:\nYou are reading from a CSV file, and taking that data and inserting in an SQL database, evidently, although you did not say so. You have a syntax error in your SQL-statement.\nNote that most SQL databases have CSV imports, so you don't need to write them.\nAlso note that you evidently are trying to import the first row, which contains column headings. That's surely incorrect.\nThis all shows that it's important on Stackoverflow to show real code that has the problem.\nNarrow down the code until you can show your problem in code that's small enough to paste here.\n99% of the time you'll find the error while doing that.\n",
"it is the values statement! geez, but I did a log.debug and didn't see it output which was before the sql ...but that is most def what it is. I wasn't trying to import the first row, I plugged that in there purposely to not show actual data. Sorry for the inconvenience. I didn't think the code was making it past that line I did post. And it is the real code all but the file name. I am new to Python, not SQL, so I was sure it was the csv.reader since it is so foreign to me. Thank you guys for your help.\n",
"The csv.reader is not responsible for constructing the SQL statement whose fragment is being shown in the error message you posted -- some other part of your code must be the one that constructs this statement, and it's doing that in the wrong way. So don't think about csv.reader, but about what you do with the tuples it's returning to the rest of your code!-)\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"csv",
"period",
"python",
"syntax_error"
] |
stackoverflow_0002143371_csv_period_python_syntax_error.txt
|
Q:
Connecting to a Multicast Server in Python
This is my code for connecting to a multicast server, is this the best way of handling the exception. What I would like to do is to retry to connect if an exception occurs
def initialiseMulticastTrackerComms():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.bind((ANY, MCAST_PORT))
host = socket.gethostbyname(socket.gethostname())
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))
sock.setblocking(False)
except socket.error, (value,message):
print "Could not open socket: " + message
sys.exit(1)
else:
print 'Connected to multicast server'
return sock
Could someone offer any advice on how to do this
Thanks in advance
A:
The simplest solution would be to wrap your try-except-else block in a loop.
Something like this
def initSock():
message = ""
for i in range(MAX_TRIES):
try:
#...socket opening code
except socket.error, (value, message):
message = message
else:
print "Connected"
return sock
print "Could not open socket: " + message
sys.exit(1)
|
Connecting to a Multicast Server in Python
|
This is my code for connecting to a multicast server, is this the best way of handling the exception. What I would like to do is to retry to connect if an exception occurs
def initialiseMulticastTrackerComms():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.bind((ANY, MCAST_PORT))
host = socket.gethostbyname(socket.gethostname())
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))
sock.setblocking(False)
except socket.error, (value,message):
print "Could not open socket: " + message
sys.exit(1)
else:
print 'Connected to multicast server'
return sock
Could someone offer any advice on how to do this
Thanks in advance
|
[
"The simplest solution would be to wrap your try-except-else block in a loop.\nSomething like this\ndef initSock():\n message = \"\"\n for i in range(MAX_TRIES):\n try:\n #...socket opening code\n except socket.error, (value, message):\n message = message\n else:\n print \"Connected\"\n return sock\n print \"Could not open socket: \" + message\n sys.exit(1)\n\n"
] |
[
1
] |
[] |
[] |
[
"exception",
"multicast",
"python",
"sockets"
] |
stackoverflow_0002147501_exception_multicast_python_sockets.txt
|
Q:
Raising an exception vs printing?
Whats the difference between raising an exception and simply printing an error.
For example, whats the benefit of using the following:
if size < 0:
raise ValueError('number must be non-negative')
instead of simply:
if size < 0:
print 'number must be non-negative'
I'm a newbie, please take it easy on me. :)
A:
Raising an error halts the entire program at that point (unless the exception is caught), whereas printing the message just writes something to stdout -- the output might be piped to another tool, or someone might not be running your application from the command line, and the print output may never be seen.
For example, what if your code is like:
if size < 0:
print 'size must be non-negative'
else:
print size * 4
and I call your script like:
yours.py number_source.txt | sum_all_lines.sh
If yours.py outputs plain text in between numbers, then maybe my sum_all_lines.sh will fail because it was expecting all numbers. However, if yours.py quits due to an exception, then sum_all_lines.sh will not finish, and it will be clear to me why the sum failed.
Of course, that's just one example, and your particular case may be completely different.
A:
It depends if you can handle size < 0 at the point where size < 0 is detected.
If you can handle it by printing straight away, then print, otherwise, raise an exception, to delegate the handling of that condition to something further up the callstack, like this:
def divide_three_by(val):
if val == 0:
raise ValueError("Can't divide by 0")
return 3/val
try:
divide_three_by(some_value_from_user)
except ValueError:
print "You gave stupid input"
In the (admittedly very contrived) example above, the divide_three_by function doesn't know what to do if you pass in 0 - sometimes you might just want to print a message (e.g. if val came from user input), sometimes you might want to just ignore it, and assign a default value. Since the function doesn't know what to do, it should pass responsibility for handling that condition up the callstack to whatever called it (and if it can't be handled there, it'll keep being passed up the callstack until something handles it, or until it reaches the top-level, at which point your program will terminate).
For more on handling exceptions in Python - take a look at the Errors and Exceptions tutorial in the Python documentation.
A:
Another consideration is when developing a module that maybe used in other programs. In that case it is preferable to throw an exception and let the calling code handle the error. The caller should know that something went wrong and act accordingly.
...richie
A:
The key difference is whether or not the program will continue to run after your error checking.
For this case:
if size < 0:
print 'number must be non-negative'
This will just print the message to standard output and the program will continue past your check. So if at some point later in your code you uses size and it is less that 0 you may get an error.
For the other case:
if size < 0:
raise ValueError('number must be non-negative'
In this case the program will not continue past your check, an exception will be raised. If it is not handled then the entire program will terminate.
Most of the time you will want to raise an exception and have an outer exception handler that catches the exception and tells the use about the error and if possible allows them to re-enter the input.
|
Raising an exception vs printing?
|
Whats the difference between raising an exception and simply printing an error.
For example, whats the benefit of using the following:
if size < 0:
raise ValueError('number must be non-negative')
instead of simply:
if size < 0:
print 'number must be non-negative'
I'm a newbie, please take it easy on me. :)
|
[
"Raising an error halts the entire program at that point (unless the exception is caught), whereas printing the message just writes something to stdout -- the output might be piped to another tool, or someone might not be running your application from the command line, and the print output may never be seen.\nFor example, what if your code is like:\nif size < 0:\n print 'size must be non-negative'\nelse:\n print size * 4\n\nand I call your script like:\nyours.py number_source.txt | sum_all_lines.sh\nIf yours.py outputs plain text in between numbers, then maybe my sum_all_lines.sh will fail because it was expecting all numbers. However, if yours.py quits due to an exception, then sum_all_lines.sh will not finish, and it will be clear to me why the sum failed.\nOf course, that's just one example, and your particular case may be completely different.\n",
"It depends if you can handle size < 0 at the point where size < 0 is detected.\nIf you can handle it by printing straight away, then print, otherwise, raise an exception, to delegate the handling of that condition to something further up the callstack, like this:\ndef divide_three_by(val):\n if val == 0:\n raise ValueError(\"Can't divide by 0\")\n return 3/val\n\ntry:\n divide_three_by(some_value_from_user)\nexcept ValueError:\n print \"You gave stupid input\"\n\nIn the (admittedly very contrived) example above, the divide_three_by function doesn't know what to do if you pass in 0 - sometimes you might just want to print a message (e.g. if val came from user input), sometimes you might want to just ignore it, and assign a default value. Since the function doesn't know what to do, it should pass responsibility for handling that condition up the callstack to whatever called it (and if it can't be handled there, it'll keep being passed up the callstack until something handles it, or until it reaches the top-level, at which point your program will terminate).\nFor more on handling exceptions in Python - take a look at the Errors and Exceptions tutorial in the Python documentation.\n",
"Another consideration is when developing a module that maybe used in other programs. In that case it is preferable to throw an exception and let the calling code handle the error. The caller should know that something went wrong and act accordingly.\n...richie\n",
"The key difference is whether or not the program will continue to run after your error checking.\nFor this case:\nif size < 0:\n print 'number must be non-negative'\n\nThis will just print the message to standard output and the program will continue past your check. So if at some point later in your code you uses size and it is less that 0 you may get an error.\nFor the other case:\nif size < 0:\n raise ValueError('number must be non-negative'\n\nIn this case the program will not continue past your check, an exception will be raised. If it is not handled then the entire program will terminate. \nMost of the time you will want to raise an exception and have an outer exception handler that catches the exception and tells the use about the error and if possible allows them to re-enter the input.\n"
] |
[
11,
6,
3,
2
] |
[] |
[] |
[
"exception",
"printing",
"python"
] |
stackoverflow_0002146618_exception_printing_python.txt
|
Q:
Qt: Python tcp client sends data over socket. How to read these bytes with Qt?
Situation:
I have tcp client made with Python and tcp server made with Qt. I try to send bytes with my client but I can't get Qt server to read these bytes.
Using Python made client and server, everything works fine. Also I can get my Python client work with C# server with no problems.
Code for Python client:
import socket
import sys
HOST = 'localhost'
PORT = 50505
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as msg:
sys.stderr.write("[ERROR] %s\n" % msg)
sys.exit(1)
try:
sock.connect((HOST, PORT))
except socket.error as msg:
sys.stderr.write("[ERROR] %s\n" % msg)
sys.exit(2)
sock.send(b'Hello World!\r\n')
I have tried e.q fortuneserver/fortuneclient code examples but they didn't work. Bytesavailable() is always 0.
So the question is how can I read in my Qt application that "Hello World!" line ? I just need that function which starts when a server emits newConnection() signal.
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(startRead()));
UPDATE:
Part of the code for Qt server:
void Server::startRead()
{
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
QString ipAddress;
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> blockSize;
}
if (tcpSocket->bytesAvailable() < blockSize)
return;
QString nextFortune;
in >> nextFortune;
statusLabel->setText(nextFortune);
ABOVE IS FROM FORTUNE CLIENT EXAMPLE.
BELOW IS FROM ANOTHER EXAMPLE.
/*
char buffer[128] = {0};
QTcpSocket *client = tcpServer->nextPendingConnection();
qDebug() << client->bytesAvailable();
for (int i=0; i<100; i++)
{
client->read(buffer, client->bytesAvailable());
qDebug() << buffer;
std::string sString(buffer);
QString qString(sString.c_str());
statusLabel->setText(qString);
}
*/
}
That last part is rather bad. I tried to make something but I have no clue what I'm doing with Qt :)
A:
You need to arrange for your code to read when there is data available. From your description, there is not data available yet when startRead() runs.
I assume you called QTcpServer::nextPendingConnection to get your tcpSocket in startRead()? If not, you need to do so.
Just connect the readyRead signal from your tcpSocket or client to a doRead() slot, and check bytesAvailable() and read in that slot.
This slot will get called whenever new data arrives.
You might also be interested in the disconnected() signal from your TCP socket to know when it is done sending data.
A:
The server code you attached works this way: Every 'packet' (logical one) is consisted of a size field, and following that size worth of data.
Basically it goes like this:
Read a quint16, if there aren't
enough bytes to be read, wait for
more.
quint16 read, wait until we have
atleast the amount of the quint16
to be read.
Once we have enough, we can read in
the data.
After we understood that, even if you write the packet length like the server expects, what you're trying to do still won't work. This is because the way the server reads the QString from the socket. The client is writing a raw python string, I'm guessing it's just writing a plain old ASCII to the socket. The server is using a QDataStream to read from the socket (this is the standard way to serialize in Qt). If you look at the implementation of QString's operator<< here, it's doing much more than reading an ASCII string.
If you can't change your server, change your client. You can see the implementation of the fortune client in the examples that come with PyQt.
|
Qt: Python tcp client sends data over socket. How to read these bytes with Qt?
|
Situation:
I have tcp client made with Python and tcp server made with Qt. I try to send bytes with my client but I can't get Qt server to read these bytes.
Using Python made client and server, everything works fine. Also I can get my Python client work with C# server with no problems.
Code for Python client:
import socket
import sys
HOST = 'localhost'
PORT = 50505
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as msg:
sys.stderr.write("[ERROR] %s\n" % msg)
sys.exit(1)
try:
sock.connect((HOST, PORT))
except socket.error as msg:
sys.stderr.write("[ERROR] %s\n" % msg)
sys.exit(2)
sock.send(b'Hello World!\r\n')
I have tried e.q fortuneserver/fortuneclient code examples but they didn't work. Bytesavailable() is always 0.
So the question is how can I read in my Qt application that "Hello World!" line ? I just need that function which starts when a server emits newConnection() signal.
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(startRead()));
UPDATE:
Part of the code for Qt server:
void Server::startRead()
{
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
QString ipAddress;
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> blockSize;
}
if (tcpSocket->bytesAvailable() < blockSize)
return;
QString nextFortune;
in >> nextFortune;
statusLabel->setText(nextFortune);
ABOVE IS FROM FORTUNE CLIENT EXAMPLE.
BELOW IS FROM ANOTHER EXAMPLE.
/*
char buffer[128] = {0};
QTcpSocket *client = tcpServer->nextPendingConnection();
qDebug() << client->bytesAvailable();
for (int i=0; i<100; i++)
{
client->read(buffer, client->bytesAvailable());
qDebug() << buffer;
std::string sString(buffer);
QString qString(sString.c_str());
statusLabel->setText(qString);
}
*/
}
That last part is rather bad. I tried to make something but I have no clue what I'm doing with Qt :)
|
[
"You need to arrange for your code to read when there is data available. From your description, there is not data available yet when startRead() runs.\nI assume you called QTcpServer::nextPendingConnection to get your tcpSocket in startRead()? If not, you need to do so.\nJust connect the readyRead signal from your tcpSocket or client to a doRead() slot, and check bytesAvailable() and read in that slot.\nThis slot will get called whenever new data arrives.\nYou might also be interested in the disconnected() signal from your TCP socket to know when it is done sending data.\n",
"The server code you attached works this way: Every 'packet' (logical one) is consisted of a size field, and following that size worth of data.\nBasically it goes like this:\n\nRead a quint16, if there aren't\nenough bytes to be read, wait for\nmore.\nquint16 read, wait until we have\natleast the amount of the quint16\nto be read.\nOnce we have enough, we can read in\nthe data.\n\nAfter we understood that, even if you write the packet length like the server expects, what you're trying to do still won't work. This is because the way the server reads the QString from the socket. The client is writing a raw python string, I'm guessing it's just writing a plain old ASCII to the socket. The server is using a QDataStream to read from the socket (this is the standard way to serialize in Qt). If you look at the implementation of QString's operator<< here, it's doing much more than reading an ASCII string.\nIf you can't change your server, change your client. You can see the implementation of the fortune client in the examples that come with PyQt.\n"
] |
[
1,
0
] |
[] |
[] |
[
"debugging",
"python",
"qt",
"sockets",
"tcp"
] |
stackoverflow_0002130757_debugging_python_qt_sockets_tcp.txt
|
Q:
Open a PyGTK program but do not activate it
I have a PyGTK program which is hidden most of the time, but with a keypress it shall come up as a popup. Therefore I want the program not to be activated when its opened. I tried several options to to that, with no success:
self.window.show()
self.window.set_focus(None)
Activates the program, but sets no focus.
self.window.set_accept_focus(False)
self.window.show()
self.window.set_accept_focus(True)
With the last command, the window gets activated.
self.window.show()
self.window.unset_flags(gtk.HAS_FOCUS)
Does nothing...
Btw. I am using Ubuntu 9.10 (metacity)
A:
Build the window but don't call show() on it until it is ready to be activated. Then use self.window.present().
EDIT:
If you never want the window to be activated, why not try a notification popup? You need libnotify for this. There are Python bindings. Here is an example: http://roscidus.com/desktop/node/336
In combination with a toolbar applet, this could do what you want -- i.e. the notification is raised when the user either clicks on the applet or presses the key combination.
A:
I figured out how to do it. See the example below:
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
import gobject
class HelloWorld:
window=None
def hello(self, widget, data=None, data2=None):
HelloWorld.window.set_accept_focus(True)
HelloWorld.window.present()
def __init__(self):
HelloWorld.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.button = gtk.Entry(50)
self.button.connect("focus-in-event", self.hello, None)
HelloWorld.window.add(self.button)
self.button.show()
HelloWorld.window.set_accept_focus(False)
self.button.connect('button-press-event', self.hello)
HelloWorld.window.show()
def main(self):
gtk.main()
if __name__ == "__main__":
hello = HelloWorld()
hello.main()
|
Open a PyGTK program but do not activate it
|
I have a PyGTK program which is hidden most of the time, but with a keypress it shall come up as a popup. Therefore I want the program not to be activated when its opened. I tried several options to to that, with no success:
self.window.show()
self.window.set_focus(None)
Activates the program, but sets no focus.
self.window.set_accept_focus(False)
self.window.show()
self.window.set_accept_focus(True)
With the last command, the window gets activated.
self.window.show()
self.window.unset_flags(gtk.HAS_FOCUS)
Does nothing...
Btw. I am using Ubuntu 9.10 (metacity)
|
[
"Build the window but don't call show() on it until it is ready to be activated. Then use self.window.present().\nEDIT:\nIf you never want the window to be activated, why not try a notification popup? You need libnotify for this. There are Python bindings. Here is an example: http://roscidus.com/desktop/node/336\nIn combination with a toolbar applet, this could do what you want -- i.e. the notification is raised when the user either clicks on the applet or presses the key combination.\n",
"I figured out how to do it. See the example below:\n\n\n#!/usr/bin/env python\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport gobject\n\nclass HelloWorld:\n window=None\n def hello(self, widget, data=None, data2=None):\n HelloWorld.window.set_accept_focus(True)\n HelloWorld.window.present()\n\n def __init__(self):\n HelloWorld.window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n self.button = gtk.Entry(50)\n self.button.connect(\"focus-in-event\", self.hello, None)\n HelloWorld.window.add(self.button)\n self.button.show()\n HelloWorld.window.set_accept_focus(False)\n self.button.connect('button-press-event', self.hello)\n HelloWorld.window.show()\n def main(self):\n gtk.main()\n\nif __name__ == \"__main__\":\n hello = HelloWorld()\n hello.main()\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"gtk",
"pygtk",
"python"
] |
stackoverflow_0002143152_gtk_pygtk_python.txt
|
Q:
How to retrieve the values for only one table field in Django
If I have following database fields: id, name, emp_id.
How do I make a query in Django to get the values of column name only with a where clause.
Thanks...
A:
Model.objects.filter(...).values('name')
A:
In addition to the answer provided by Ignacio Vazquez-Abrams, you could also use values_list to get the names in a flat list (instead of a dictionary).
Model.objects.filter(...).values_list('name', flat=True)
See the documentation for values_list.
|
How to retrieve the values for only one table field in Django
|
If I have following database fields: id, name, emp_id.
How do I make a query in Django to get the values of column name only with a where clause.
Thanks...
|
[
"Model.objects.filter(...).values('name')\n\n",
"In addition to the answer provided by Ignacio Vazquez-Abrams, you could also use values_list to get the names in a flat list (instead of a dictionary). \nModel.objects.filter(...).values_list('name', flat=True)\n\nSee the documentation for values_list.\n"
] |
[
7,
5
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002147882_django_python.txt
|
Q:
How to avoid gcc warning in Python C extension when using Py_BEGIN_ALLOW_THREADS
The simplest way to manipulate the GIL in Python C extensions is to use the macros provided:
my_awesome_C_function()
{
blah;
Py_BEGIN_ALLOW_THREADS
// do stuff that doesn't need the GIL
if (should_i_call_back) {
Py_BLOCK_THREADS
// do stuff that needs the GIL
Py_UNBLOCK_THREADS
}
Py_END_ALLOW_THREADS
return blah blah;
}
This works great, letting me release the GIL for the bulk of my code, but re-grabbing it for small bits of code that need it.
The problem is when I compile this with gcc, I get:
ext/engine.c:548: warning: '_save' might be used uninitialized in this function
because Py_BEGIN_ALLOW_THREADS is defined like this:
#define Py_BEGIN_ALLOW_THREADS { \
PyThreadState *_save; \
_save = PyEval_SaveThread();
So, three questions:
Is it possible to suppress gcc's warning,
Does anyone have any idea why gcc thinks _save might be used uninitialized, since it is assigned to immediately after its declaration, and
Why wouldn't the macro have been defined to declare and initialize the variable in one statement to avoid the issue?
(the last two are really just for my own curiosity).
I can avoid the issue by not using the macros and doing it all myself, but I'd rather not.
A:
Yes, it is possible to suppress uninitialized warnings using the -Wno- prefix.
-Wall -Wno-uninitialized
If you want to remove just this warning, you could simply initialize _save to a null pointer so that it doesn't rely on a function return value... that one line of code and a comment makes sense to me:
PyThreadState *_save;
_save = 0; /* init as null pointer value */
_save = PyEval_SaveThread();
A:
My two cents:
You can suppress specific warnings, but I guess you already knew that.
It says might be uninitialized :-)
The only reason I can imagine is compatibility with older C compilers.
I tried digging into the source, but couldn't find any good clues.
A:
Ned, you can try one of these:
#pragma GCC diagnostic warning "-Wno-unitialized"
#pragma GCC diagnostic error "-Wno-uninitialized"
#pragma GCC diagnostic ignored "-Wno-uninialized"
Or ignore -Wuninitialized? According to the documentation, you have to do this before any data or functions are defined. Maybe it will let you disable the warning just for that file?
|
How to avoid gcc warning in Python C extension when using Py_BEGIN_ALLOW_THREADS
|
The simplest way to manipulate the GIL in Python C extensions is to use the macros provided:
my_awesome_C_function()
{
blah;
Py_BEGIN_ALLOW_THREADS
// do stuff that doesn't need the GIL
if (should_i_call_back) {
Py_BLOCK_THREADS
// do stuff that needs the GIL
Py_UNBLOCK_THREADS
}
Py_END_ALLOW_THREADS
return blah blah;
}
This works great, letting me release the GIL for the bulk of my code, but re-grabbing it for small bits of code that need it.
The problem is when I compile this with gcc, I get:
ext/engine.c:548: warning: '_save' might be used uninitialized in this function
because Py_BEGIN_ALLOW_THREADS is defined like this:
#define Py_BEGIN_ALLOW_THREADS { \
PyThreadState *_save; \
_save = PyEval_SaveThread();
So, three questions:
Is it possible to suppress gcc's warning,
Does anyone have any idea why gcc thinks _save might be used uninitialized, since it is assigned to immediately after its declaration, and
Why wouldn't the macro have been defined to declare and initialize the variable in one statement to avoid the issue?
(the last two are really just for my own curiosity).
I can avoid the issue by not using the macros and doing it all myself, but I'd rather not.
|
[
"\nYes, it is possible to suppress uninitialized warnings using the -Wno- prefix. \n\n-Wall -Wno-uninitialized\nIf you want to remove just this warning, you could simply initialize _save to a null pointer so that it doesn't rely on a function return value... that one line of code and a comment makes sense to me:\nPyThreadState *_save; \n_save = 0; /* init as null pointer value */\n_save = PyEval_SaveThread();\n\n",
"My two cents:\n\nYou can suppress specific warnings, but I guess you already knew that.\nIt says might be uninitialized :-)\nThe only reason I can imagine is compatibility with older C compilers.\n\nI tried digging into the source, but couldn't find any good clues.\n",
"Ned, you can try one of these:\n#pragma GCC diagnostic warning \"-Wno-unitialized\"\n#pragma GCC diagnostic error \"-Wno-uninitialized\"\n#pragma GCC diagnostic ignored \"-Wno-uninialized\"\n\nOr ignore -Wuninitialized? According to the documentation, you have to do this before any data or functions are defined. Maybe it will let you disable the warning just for that file?\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"cextension",
"gcc",
"gil",
"python"
] |
stackoverflow_0002147029_cextension_gcc_gil_python.txt
|
Q:
Virtualenv problem
I have created a new environement in virtualenv with --no-site-packages and executed activate file. So, shouldn't my current Django app show any error? Environement doesn't have Django installed. I think, my site is using my old python with Django. How can I change it?
Maybe it's because my .htaccess file, here it is:
SetHandler mod_python
PythonPath "['/home/usr/PythonEnvs/Django/bin/python', 'home/usr/apps'] + sys.path"
PythonOption mod_python.importer.path "['/home/usr/PythonEnvs/Django/bin/python']+ sys.path"
PythonHandler django.core.handlers.modpython
PythonDebug On
SetEnv DJANGO_SETTINGS_MODULE application.settings
SetEnv PYTHON_EGG_CACHE /tmp/egg-cache
What else should I do to use my environement?
A:
With mod_wsgi, you can set WSGIPythonHome to where your virtualenv is. mod_python doesn't let you set the interpreter easily, however (there may be a way involving setting PYTHONEXECUTABLE at apache startup).
See what bin/python (next to bin/activate) does to sys.path, and mimick it in the PythonPath directive. Write a page that displays the current sys.path and make sure the system python path doesn't appear; if it does, edit it further with PythonPath.
|
Virtualenv problem
|
I have created a new environement in virtualenv with --no-site-packages and executed activate file. So, shouldn't my current Django app show any error? Environement doesn't have Django installed. I think, my site is using my old python with Django. How can I change it?
Maybe it's because my .htaccess file, here it is:
SetHandler mod_python
PythonPath "['/home/usr/PythonEnvs/Django/bin/python', 'home/usr/apps'] + sys.path"
PythonOption mod_python.importer.path "['/home/usr/PythonEnvs/Django/bin/python']+ sys.path"
PythonHandler django.core.handlers.modpython
PythonDebug On
SetEnv DJANGO_SETTINGS_MODULE application.settings
SetEnv PYTHON_EGG_CACHE /tmp/egg-cache
What else should I do to use my environement?
|
[
"With mod_wsgi, you can set WSGIPythonHome to where your virtualenv is. mod_python doesn't let you set the interpreter easily, however (there may be a way involving setting PYTHONEXECUTABLE at apache startup).\nSee what bin/python (next to bin/activate) does to sys.path, and mimick it in the PythonPath directive. Write a page that displays the current sys.path and make sure the system python path doesn't appear; if it does, edit it further with PythonPath.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python",
"virtualenv"
] |
stackoverflow_0002148213_django_python_virtualenv.txt
|
Q:
Using getcwd when running in Eclipse
When running a project in eclipse the eclipse saves a copy of the .py file inside the workspace defined in project creation. But the file that imported to project can be in other location.
If using os.getcwd() and running the script from the command line, the return value would be the real path of the script file, but when running the script from inside eclipse, the return value would be the path of the workspace, where eclipse saves a copy of the original file.
So the question is, since I run my script during debugging from eclipse, how can I verify that it works before moving to real environment? Is there other way other than getcwd()?
Thanks,
Isaac
A:
os.getcwd() returns the current working directory.
When running a Python program from Eclipse you can specify what the working directory should be on the Arguments tab of the Run Configuration. This will let you override the value from the project folder (or whatever the default might be.)
|
Using getcwd when running in Eclipse
|
When running a project in eclipse the eclipse saves a copy of the .py file inside the workspace defined in project creation. But the file that imported to project can be in other location.
If using os.getcwd() and running the script from the command line, the return value would be the real path of the script file, but when running the script from inside eclipse, the return value would be the path of the workspace, where eclipse saves a copy of the original file.
So the question is, since I run my script during debugging from eclipse, how can I verify that it works before moving to real environment? Is there other way other than getcwd()?
Thanks,
Isaac
|
[
"os.getcwd() returns the current working directory.\nWhen running a Python program from Eclipse you can specify what the working directory should be on the Arguments tab of the Run Configuration. This will let you override the value from the project folder (or whatever the default might be.)\n\n"
] |
[
1
] |
[] |
[] |
[
"eclipse",
"python"
] |
stackoverflow_0002147575_eclipse_python.txt
|
Q:
Python: Rar Brute Forcer
I am trying to brute force a RAR archive which is protected by a password with 3 characters:
import os
Alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for a in range(0,26):
for b in range(0,26):
for c in range(0,26):
Brute = Alphabets[a] + Alphabets[b] + Alphabets[c]
os.popen4("Rar.exe x -p" + Brute + " Protected.rar")
# raw_input()
raw_input("Done !")
The code works fine, except: it is very slow !!
i think what makes it slow is the multi-opening by "popen4". because i tried to stored the generated words in a txt file, and the program finished in less than 5 seconds.
Any ideas to increase the performance?
A:
You could use (or learn from) rarcrack. It is written in C and compiles without problems on Linux (Windows with lots of changes).
In general, opening a process for every single tested password is very expensive. You should try and open the archive yourself, and then test against all passwords. Anyway you need to test the return value of rar.exe to find out whether extraction succeeded.
For best performance, you should write the program in C (or similar). There's a Linux package called "libunrar" that might help you with opening RAR files.
A:
you might consider using some stdlib modules:
>>> import string
>>> import itertools
>>> from subprocess import Popen, PIPE
>>> for i in itertools.product(string.ascii_uppercase, repeat=3):
pr = Popen(['rar.exe', 'x', '-p', ''.join(i), 'protected.rar'], stdin=PIPE, stdout=PIPE)
pr.communicate()
It might not necessarily improve performance, but it does make your code cleaner.
A:
The generating of the passwords is trivial, that's why it takes only 5 seconds to create the 26^3 = 17576 passwords. What takes the most time is opening and attempting to decrypt the archive - and you don't have control over that.
There isn't much you can do about speeding this up - the rar binary and the input file will be cached in memory after the first few tries: just let it run overnight or over the week-end as need be.
A:
What about generating the passwords first an then parallelize the rar.exe process call(which seems to be the bottleneck)?
A:
You may not be able to cut down on the time it takes to make the attempt to decrypt the archive, but, assuming that the password is not completely random (which it may be), you may get to the correct password more quickly if you order the letters in decreasing likelihood of use.
For example, in Linux Journal, the shell script column analyzed a few large texts to determine that e, t, a, o, n, i, s, r, h, and d were the most common letters in those texts (and presumably this is close to English as a whole). So changing your second line to:
Alphabets = "ETAONIBSRHDCFGJKLMPQUVWXYZ" could cause your algorithm to arrive at the password in fewer iterations.
Edit: Second thoughts
If the password is, as someone indicated, "cat", the original ordering will require 3 passes through the outer loop, whereas the new version will require 11 pass, so in this case it won't solve it faster. So maybe you need to optimize the list for the outer loop by trying to predict the most likely first letter.
|
Python: Rar Brute Forcer
|
I am trying to brute force a RAR archive which is protected by a password with 3 characters:
import os
Alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for a in range(0,26):
for b in range(0,26):
for c in range(0,26):
Brute = Alphabets[a] + Alphabets[b] + Alphabets[c]
os.popen4("Rar.exe x -p" + Brute + " Protected.rar")
# raw_input()
raw_input("Done !")
The code works fine, except: it is very slow !!
i think what makes it slow is the multi-opening by "popen4". because i tried to stored the generated words in a txt file, and the program finished in less than 5 seconds.
Any ideas to increase the performance?
|
[
"You could use (or learn from) rarcrack. It is written in C and compiles without problems on Linux (Windows with lots of changes).\nIn general, opening a process for every single tested password is very expensive. You should try and open the archive yourself, and then test against all passwords. Anyway you need to test the return value of rar.exe to find out whether extraction succeeded.\nFor best performance, you should write the program in C (or similar). There's a Linux package called \"libunrar\" that might help you with opening RAR files.\n",
"you might consider using some stdlib modules:\n>>> import string\n>>> import itertools\n>>> from subprocess import Popen, PIPE\n>>> for i in itertools.product(string.ascii_uppercase, repeat=3):\n pr = Popen(['rar.exe', 'x', '-p', ''.join(i), 'protected.rar'], stdin=PIPE, stdout=PIPE)\n pr.communicate()\n\nIt might not necessarily improve performance, but it does make your code cleaner.\n",
"The generating of the passwords is trivial, that's why it takes only 5 seconds to create the 26^3 = 17576 passwords. What takes the most time is opening and attempting to decrypt the archive - and you don't have control over that.\nThere isn't much you can do about speeding this up - the rar binary and the input file will be cached in memory after the first few tries: just let it run overnight or over the week-end as need be.\n",
"What about generating the passwords first an then parallelize the rar.exe process call(which seems to be the bottleneck)?\n",
"You may not be able to cut down on the time it takes to make the attempt to decrypt the archive, but, assuming that the password is not completely random (which it may be), you may get to the correct password more quickly if you order the letters in decreasing likelihood of use.\nFor example, in Linux Journal, the shell script column analyzed a few large texts to determine that e, t, a, o, n, i, s, r, h, and d were the most common letters in those texts (and presumably this is close to English as a whole). So changing your second line to:\nAlphabets = \"ETAONIBSRHDCFGJKLMPQUVWXYZ\" could cause your algorithm to arrive at the password in fewer iterations.\nEdit: Second thoughts\nIf the password is, as someone indicated, \"cat\", the original ordering will require 3 passes through the outer loop, whereas the new version will require 11 pass, so in this case it won't solve it faster. So maybe you need to optimize the list for the outer loop by trying to predict the most likely first letter.\n"
] |
[
9,
6,
4,
1,
1
] |
[] |
[] |
[
"performance",
"python"
] |
stackoverflow_0002148393_performance_python.txt
|
Q:
I'm using Hadoop for data processing with python, what file format should be used?
I'm using Hadoop for data processing with python, what file format should be used?
I have project with a substantial amount of text pages.
Each text file has some header information that I need to preserve during the processing; however, I don't want the headers to interfere with the clustering algorithms.
I'm using python on Hadoop (or is there a sub package better suited?)
How should I format my text files, and store those text files in Hadoop for processing?
A:
1) Files
If you use Hadoop Streaming, you have to use line-based text-files, data up to the first tab is passed to your mapper as key.
Just look at the documentation for streaming.
You can also put you input-files into HDFS, which would be recommendable for big files. Just look at the "Large Files"-section in the above link.
2) Metadata-preservation
The problem I see is that your header information (metadata) will only be treated as such data, so you have to filter it out by yourself (first step). To pass it along is more difficult, as the data of all input files will just be joined after the map-step.
You will have to add the metadata somewhere to the data itself (second step) to be able to relate it later. You could emit (key, data+metadata) for each data-line of file and thus be able to preserve the metadata for each data-line. Might be a huge overhead, but we are talking MapReduce, means: pfffrrrr ;)
Now comes the part where I don't know how much streaming really differs from a Java-implemented job.
IF streaming invokes one mapper per file, you could spare yourself the following trouble, just take the first input of map() as metadata and add it (or a placeholder) to all following data-emits. If not, the next is about Java-Jobs:
At least with a JAR-mapper you can relate the data to its input-file (see here). But you would have to extract the metadata first, as the map-function just might be invoked on a partition of the file not containing the metadata. I'd propose something like that:
create a metadata-file beforehand, containing an placeholder-index: keyx:filex, metadatax
put this metadata-index into the HDFS
use a JAR-mapper, load during setup() the metadata-index-file
see org.apache.hadoop.hdfs.DFSClient
match filex, set keyx for this mapper
add to each emitted data-line in map() the used keyx
A:
If you're using Hadoop Streaming, your input can be in any line-based format; your mapper and reducer input comes from sys.stdin, which you read any way you want. You don't need to use the default tab-deliminated fields (although in my experience, one format should be used among all tasks for consistency when possible).
However, with the default splitter and partitioner, you cannot control how your input and output is partitioned or sorted, so you your mappers and reducers must decide whether any particular line is a header line or a data line using only that line - they won't know the original file boundaries.
You may be able to specify a partitioner which lets a mapper assume that the first input line is the first line in a file, or even move away from a line-based format. This was hard to do the last time I tried with Streaming, and in my opinion mapper and reducer tasks should be input agnostic for efficiency and reusability - it's best to think of a stream of input records, rather than keeping track of file boundaries.
Another option with Streaming is to ship header information in a separate file, which is included with your data. It will be available to your mappers and reducers in their working directories. One idea would be to associate each line with the appropriate header information in an inital task, perhaps by using three fields per line instead of two, rather than associating them by file.
In general, try and treat the input as a stream and don't rely on file boundaries, input size, or order. All of these restrictions can be implemented, but at the cost of complexity. If you do need to implement them, do so at the beginning or end of your task chain.
If you're using Jython or SWIG, you may have other options, but I found those harder to work with than Streaming.
|
I'm using Hadoop for data processing with python, what file format should be used?
|
I'm using Hadoop for data processing with python, what file format should be used?
I have project with a substantial amount of text pages.
Each text file has some header information that I need to preserve during the processing; however, I don't want the headers to interfere with the clustering algorithms.
I'm using python on Hadoop (or is there a sub package better suited?)
How should I format my text files, and store those text files in Hadoop for processing?
|
[
"1) Files\nIf you use Hadoop Streaming, you have to use line-based text-files, data up to the first tab is passed to your mapper as key.\nJust look at the documentation for streaming.\nYou can also put you input-files into HDFS, which would be recommendable for big files. Just look at the \"Large Files\"-section in the above link.\n2) Metadata-preservation\nThe problem I see is that your header information (metadata) will only be treated as such data, so you have to filter it out by yourself (first step). To pass it along is more difficult, as the data of all input files will just be joined after the map-step.\nYou will have to add the metadata somewhere to the data itself (second step) to be able to relate it later. You could emit (key, data+metadata) for each data-line of file and thus be able to preserve the metadata for each data-line. Might be a huge overhead, but we are talking MapReduce, means: pfffrrrr ;)\nNow comes the part where I don't know how much streaming really differs from a Java-implemented job. \nIF streaming invokes one mapper per file, you could spare yourself the following trouble, just take the first input of map() as metadata and add it (or a placeholder) to all following data-emits. If not, the next is about Java-Jobs: \nAt least with a JAR-mapper you can relate the data to its input-file (see here). But you would have to extract the metadata first, as the map-function just might be invoked on a partition of the file not containing the metadata. I'd propose something like that:\n\ncreate a metadata-file beforehand, containing an placeholder-index: keyx:filex, metadatax\nput this metadata-index into the HDFS\nuse a JAR-mapper, load during setup() the metadata-index-file\n\n\nsee org.apache.hadoop.hdfs.DFSClient\n\nmatch filex, set keyx for this mapper\nadd to each emitted data-line in map() the used keyx\n\n",
"If you're using Hadoop Streaming, your input can be in any line-based format; your mapper and reducer input comes from sys.stdin, which you read any way you want. You don't need to use the default tab-deliminated fields (although in my experience, one format should be used among all tasks for consistency when possible). \nHowever, with the default splitter and partitioner, you cannot control how your input and output is partitioned or sorted, so you your mappers and reducers must decide whether any particular line is a header line or a data line using only that line - they won't know the original file boundaries.\nYou may be able to specify a partitioner which lets a mapper assume that the first input line is the first line in a file, or even move away from a line-based format. This was hard to do the last time I tried with Streaming, and in my opinion mapper and reducer tasks should be input agnostic for efficiency and reusability - it's best to think of a stream of input records, rather than keeping track of file boundaries.\nAnother option with Streaming is to ship header information in a separate file, which is included with your data. It will be available to your mappers and reducers in their working directories. One idea would be to associate each line with the appropriate header information in an inital task, perhaps by using three fields per line instead of two, rather than associating them by file.\nIn general, try and treat the input as a stream and don't rely on file boundaries, input size, or order. All of these restrictions can be implemented, but at the cost of complexity. If you do need to implement them, do so at the beginning or end of your task chain.\nIf you're using Jython or SWIG, you may have other options, but I found those harder to work with than Streaming.\n"
] |
[
4,
1
] |
[] |
[] |
[
"hadoop",
"python"
] |
stackoverflow_0002144171_hadoop_python.txt
|
Q:
What's the difference between OneToOne and Subclassing a model in Django
For example:
class Subdomain(Site):
#fields here
and
class Subdomain(models.Model):
site = models.OneToOne(Site)
#fields here
A:
Models with a OneToOne have an independent PK; submodels always use the PK of their supermodel.
|
What's the difference between OneToOne and Subclassing a model in Django
|
For example:
class Subdomain(Site):
#fields here
and
class Subdomain(models.Model):
site = models.OneToOne(Site)
#fields here
|
[
"Models with a OneToOne have an independent PK; submodels always use the PK of their supermodel.\n"
] |
[
6
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002149567_django_django_models_python.txt
|
Q:
py2exe and win32com
Can py2exe create standalone executables even ones requiring the win32com package?
I've googled / searched SO to no avail.
A:
I've used py2exe for a project that depended on win32com as well as pysvn. It worked fine, no hassles.
That was using Python 2.5 and later 2.6. Note that py2exe doesn't support Python 3.x.
A:
Yes, it can. But you may need to add a refereneces to DLL that your application needs.
Check the bottom of http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules . It contains useful resources to build Python apps that uses win32com.
Also if you use typelibs, check that the version is the same on all Windows versions you want to deploy. Otherwise, your app may fail
|
py2exe and win32com
|
Can py2exe create standalone executables even ones requiring the win32com package?
I've googled / searched SO to no avail.
|
[
"I've used py2exe for a project that depended on win32com as well as pysvn. It worked fine, no hassles.\nThat was using Python 2.5 and later 2.6. Note that py2exe doesn't support Python 3.x.\n",
"Yes, it can. But you may need to add a refereneces to DLL that your application needs.\nCheck the bottom of http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules . It contains useful resources to build Python apps that uses win32com.\nAlso if you use typelibs, check that the version is the same on all Windows versions you want to deploy. Otherwise, your app may fail\n"
] |
[
4,
3
] |
[] |
[] |
[
"py2exe",
"python",
"win32com"
] |
stackoverflow_0002113863_py2exe_python_win32com.txt
|
Q:
Python-MySQLdb problem: wrong ELF class: ELFCLASS32
As part of trying out django CMS (http://www.django-cms.org/), I'm struggling with getting Python-MySQLdb to work (http://pypi.python.org/pypi/MySQL-python/).
I have installed Django CMS and all of its dependencies (Python 2.5, Django, django-south, MySQL server)
I'm trying out the example code within Django CMS code with MySQL as chosen database type
When I execute python manage.py syncdb, the following error occurs:
django.core.exceptions.ImproperlyConfigured:
Error loading MySQLdb module:
/root/.python-eggs/MySQL_python-1.2.3c1-py2.5-linux-i686.egg-tmp/_mysql.so:
wrong ELF class: ELFCLASS32
I have been able to trace the problem specifically to python-mySQLdb (as also visible in the stack trace). Other than that, I am completely puzzled. I don't have a clue what ELFCLASS32 means, or what ELF class is anyway.
I suspect that this error could have something to do with the fact that I am running 64-bit version of Debian 5 (on a VPS).
Any good ideas how to troubleshoot?
A:
Yes, the bit difference is what's causing this. Find or build a 64-bit version of MySQLdb.
ELF is the Executable and Linkable Format. ELFCLASS32 means that it's a 32-bit ELF file.
|
Python-MySQLdb problem: wrong ELF class: ELFCLASS32
|
As part of trying out django CMS (http://www.django-cms.org/), I'm struggling with getting Python-MySQLdb to work (http://pypi.python.org/pypi/MySQL-python/).
I have installed Django CMS and all of its dependencies (Python 2.5, Django, django-south, MySQL server)
I'm trying out the example code within Django CMS code with MySQL as chosen database type
When I execute python manage.py syncdb, the following error occurs:
django.core.exceptions.ImproperlyConfigured:
Error loading MySQLdb module:
/root/.python-eggs/MySQL_python-1.2.3c1-py2.5-linux-i686.egg-tmp/_mysql.so:
wrong ELF class: ELFCLASS32
I have been able to trace the problem specifically to python-mySQLdb (as also visible in the stack trace). Other than that, I am completely puzzled. I don't have a clue what ELFCLASS32 means, or what ELF class is anyway.
I suspect that this error could have something to do with the fact that I am running 64-bit version of Debian 5 (on a VPS).
Any good ideas how to troubleshoot?
|
[
"Yes, the bit difference is what's causing this. Find or build a 64-bit version of MySQLdb.\nELF is the Executable and Linkable Format. ELFCLASS32 means that it's a 32-bit ELF file.\n"
] |
[
8
] |
[] |
[] |
[
"django",
"django_cms",
"linux",
"mysql",
"python"
] |
stackoverflow_0002149782_django_django_cms_linux_mysql_python.txt
|
Q:
Django and fcgi - logging question
I have a site running in Django. Frontend is lighttpd and is using fcgi to host django.
I start my fcgi processes as follows:
python2.6 /<snip>/manage.py runfcgi maxrequests=10 host=127.0.0.1 port=8000 pidfile=django.pid
For logging, I have a RotatingFileHandler defined as follows:
file_handler = RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5,encoding='utf-8')
The logging is working. However, it looks like the files are rotating when they do not even get up to 10Kb, let alone 10Mb. My guess is that each fcgi instance is only handling 10 requests, and then re-spawning. Each respawn of fcgi creates a new file. I confirm that fcgi is starting up under new process id every so often (hard to tell time exactly, but under a minute).
Is there any way to get around this issues? I would like all fcgi instances logging to one file until it reaches the size limit, at which point a log file rotation would take place.
A:
As Alex stated, logging is thread-safe, but the standard handlers cannot be safely used to log from multiple processes into a single file.
ConcurrentLogHandler uses file locking to allow for logging from within multiple processes.
A:
In your shoes I'd switch to a TimedRotatingFileHandler -- I'm surprised that the size-based rotating file handles is giving this problem (as it should be impervious to what processes are producing the log entries), but the timed version (though not controlled on exactly the parameter you prefer) should solve it. Or, write your own, more solid, rotating file handler (you can take a lot from the standard library sources) that ensures varying processes are not a problem (as they should never be).
A:
As you appear to be using the default file opening mode of append ("a") rather than write ("w"), if a process re-spawns it should append to the existing file, then rollover when the size limit is reached. So I am not sure that what you are seeing is caused by re-spawning CGI processes. (This of course assumes that the filename remains the same when the process re-spawns).
Although the logging package is thread-safe, it does not handle concurrent access to the same file from multiple processes - because there is no standard way to do it in the stdlib. My normal advice is to set up a separate daemon process which implements a socket server and logs events received across it to file - the other processes then just implement a SocketHandler to communicate with the logging daemon. Then all events will get serialised to disk properly. The Python documentation contains a working socket server which could serve as a basis for this need.
|
Django and fcgi - logging question
|
I have a site running in Django. Frontend is lighttpd and is using fcgi to host django.
I start my fcgi processes as follows:
python2.6 /<snip>/manage.py runfcgi maxrequests=10 host=127.0.0.1 port=8000 pidfile=django.pid
For logging, I have a RotatingFileHandler defined as follows:
file_handler = RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5,encoding='utf-8')
The logging is working. However, it looks like the files are rotating when they do not even get up to 10Kb, let alone 10Mb. My guess is that each fcgi instance is only handling 10 requests, and then re-spawning. Each respawn of fcgi creates a new file. I confirm that fcgi is starting up under new process id every so often (hard to tell time exactly, but under a minute).
Is there any way to get around this issues? I would like all fcgi instances logging to one file until it reaches the size limit, at which point a log file rotation would take place.
|
[
"As Alex stated, logging is thread-safe, but the standard handlers cannot be safely used to log from multiple processes into a single file.\nConcurrentLogHandler uses file locking to allow for logging from within multiple processes.\n",
"In your shoes I'd switch to a TimedRotatingFileHandler -- I'm surprised that the size-based rotating file handles is giving this problem (as it should be impervious to what processes are producing the log entries), but the timed version (though not controlled on exactly the parameter you prefer) should solve it. Or, write your own, more solid, rotating file handler (you can take a lot from the standard library sources) that ensures varying processes are not a problem (as they should never be).\n",
"As you appear to be using the default file opening mode of append (\"a\") rather than write (\"w\"), if a process re-spawns it should append to the existing file, then rollover when the size limit is reached. So I am not sure that what you are seeing is caused by re-spawning CGI processes. (This of course assumes that the filename remains the same when the process re-spawns).\nAlthough the logging package is thread-safe, it does not handle concurrent access to the same file from multiple processes - because there is no standard way to do it in the stdlib. My normal advice is to set up a separate daemon process which implements a socket server and logs events received across it to file - the other processes then just implement a SocketHandler to communicate with the logging daemon. Then all events will get serialised to disk properly. The Python documentation contains a working socket server which could serve as a basis for this need.\n"
] |
[
6,
2,
0
] |
[] |
[] |
[
"django",
"fastcgi",
"lighttpd",
"logging",
"python"
] |
stackoverflow_0001203896_django_fastcgi_lighttpd_logging_python.txt
|
Q:
"NOTICE AUTH" notifications when connecting to IRC server
As a learning exercise, I'm writing a Python program to connect to a channel on an IRC network, so I can output messages in the channel to stdout. I'm using asynchat and manually sending the protocol messages, rather than using something like Twisted or existing bot code from the net - again, it's a more useful learning experience that way.
I can send JOIN and USER commands quite happily, and can PING/PONG away as required. However, I've noticed when opening a socket to port 6667, I'll receive some messages:
NOTICE AUTH :*** Looking up your hostname...
NOTICE AUTH :*** Checking ident
NOTICE AUTH :*** Found your hostname
NOTICE AUTH :*** No identd (auth) response
even if I've not yet sent the JOIN/USER commands.
So, is this opening sequence of notifications specified anywhere? As far as I can see, the RFC doesn't specify for anything in particular to happen before the client sends the JOIN command, and I wasn't sure whether to wait for receipt of these notices before sending the JOIN command, and if so how do I detect that I've received all of the notices?
A:
There's no RFC requirement to do this, it's just a common thing that servers in the wild do. Observe that they're plain old NOTICE commands (i.e. just messages). Just treat them as messages sent to a psuedo-user "AUTH" (since the server doesn't have a better name for you yet). You're not required to wait for them, and the server is not required to send them.
|
"NOTICE AUTH" notifications when connecting to IRC server
|
As a learning exercise, I'm writing a Python program to connect to a channel on an IRC network, so I can output messages in the channel to stdout. I'm using asynchat and manually sending the protocol messages, rather than using something like Twisted or existing bot code from the net - again, it's a more useful learning experience that way.
I can send JOIN and USER commands quite happily, and can PING/PONG away as required. However, I've noticed when opening a socket to port 6667, I'll receive some messages:
NOTICE AUTH :*** Looking up your hostname...
NOTICE AUTH :*** Checking ident
NOTICE AUTH :*** Found your hostname
NOTICE AUTH :*** No identd (auth) response
even if I've not yet sent the JOIN/USER commands.
So, is this opening sequence of notifications specified anywhere? As far as I can see, the RFC doesn't specify for anything in particular to happen before the client sends the JOIN command, and I wasn't sure whether to wait for receipt of these notices before sending the JOIN command, and if so how do I detect that I've received all of the notices?
|
[
"There's no RFC requirement to do this, it's just a common thing that servers in the wild do. Observe that they're plain old NOTICE commands (i.e. just messages). Just treat them as messages sent to a psuedo-user \"AUTH\" (since the server doesn't have a better name for you yet). You're not required to wait for them, and the server is not required to send them.\n"
] |
[
4
] |
[] |
[] |
[
"irc",
"python",
"rfc"
] |
stackoverflow_0002149895_irc_python_rfc.txt
|
Q:
Python: How does regex re.compile(r'^[-\w]+$') search? Or, how does regex work in this context?
By reading the documentation here it seems to me that
re.compile(r'^[-\w]+$')
would just search whether there was any character that is alphanumeric, an underscore, or a hyphen. But really this returns a match only if all the characters fit that description (ie, it fails if there is a space or a dollar sign or asterisk, etc).
I don't really understand how this is working to check all of the characters when it says:
"The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible.".
Doesn't that mean that if there's a space character in at the 6th character it'll match as much as possible and then stop and return the match it found in the first 5 characters (rather than saying "sorry, I found nothing" essentially when it reaches a non-match).
Thanks in advance (I'm such a noob at regex and each time I learn it again I just get confused).
A:
The two characters ^ and $ mark the start and the end of the string respectively. So ^[-\w]+$ will only match if there are only one or more word characters or a hyphen ([-\w]+) between the start (^) and the end of the string ($).
A:
The ^ and $ anchor the regex at the beginning and ending of the string, therefore all characters would have to match the pattern in between.
A:
just as per answers above, ^ and $ enclose all charactes in between and they represent line start and end respectively. If in doubt re any expression try debug mode, that usually explains a lot:
>>> p = re.compile("^[-\w]+$", re.DEBUG)
at at_beginning
max_repeat 1 65535
in
literal 45
category category_word
at at_end
>>>
|
Python: How does regex re.compile(r'^[-\w]+$') search? Or, how does regex work in this context?
|
By reading the documentation here it seems to me that
re.compile(r'^[-\w]+$')
would just search whether there was any character that is alphanumeric, an underscore, or a hyphen. But really this returns a match only if all the characters fit that description (ie, it fails if there is a space or a dollar sign or asterisk, etc).
I don't really understand how this is working to check all of the characters when it says:
"The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible.".
Doesn't that mean that if there's a space character in at the 6th character it'll match as much as possible and then stop and return the match it found in the first 5 characters (rather than saying "sorry, I found nothing" essentially when it reaches a non-match).
Thanks in advance (I'm such a noob at regex and each time I learn it again I just get confused).
|
[
"The two characters ^ and $ mark the start and the end of the string respectively. So ^[-\\w]+$ will only match if there are only one or more word characters or a hyphen ([-\\w]+) between the start (^) and the end of the string ($).\n",
"The ^ and $ anchor the regex at the beginning and ending of the string, therefore all characters would have to match the pattern in between.\n",
"just as per answers above, ^ and $ enclose all charactes in between and they represent line start and end respectively. If in doubt re any expression try debug mode, that usually explains a lot:\n>>> p = re.compile(\"^[-\\w]+$\", re.DEBUG)\nat at_beginning\nmax_repeat 1 65535\n in\n literal 45\n category category_word\nat at_end\n>>>\n\n"
] |
[
4,
3,
2
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002149898_python_regex.txt
|
Q:
How to download a file behind a HTTPS login?
How would you go about downloading a webpage file behind an HTTPS login via a language such as python? More specifically I am talking about the page behind the login from http://www.cnbtn.com.
A:
https will not matter. HTTPS just says that the data going over the wire is securely encrypted. Rather you need to learn more about how the login actually works. For instance is it Basic Auth (where a popup shows up for user/pass)? you can then make a request like https://user:pass@foo.com/my_file.gif
More likely it is some other authentication, that could do basically anything. You'll need to reverse engineer it to figure out what you need to do to get in. But most likely you'll need to use an HTTPS client library that maintains state (like it keeps cookies, etc).
Good luck
|
How to download a file behind a HTTPS login?
|
How would you go about downloading a webpage file behind an HTTPS login via a language such as python? More specifically I am talking about the page behind the login from http://www.cnbtn.com.
|
[
"https will not matter. HTTPS just says that the data going over the wire is securely encrypted. Rather you need to learn more about how the login actually works. For instance is it Basic Auth (where a popup shows up for user/pass)? you can then make a request like https://user:pass@foo.com/my_file.gif\nMore likely it is some other authentication, that could do basically anything. You'll need to reverse engineer it to figure out what you need to do to get in. But most likely you'll need to use an HTTPS client library that maintains state (like it keeps cookies, etc).\nGood luck\n"
] |
[
2
] |
[] |
[] |
[
"https",
"python"
] |
stackoverflow_0002149980_https_python.txt
|
Q:
Alpha masks with OpenGL
I want to use an alpha mask in OpenGL so that white(1)=visible and black(0)=hidden.
So what I do is I write something in the alpha component of the framebuffer using glColorMask(False, False, False, True) (I'm using python, you see) and then draw some geometry above it using blending.
But it isn't working:
I tried filling the alpha buffer completly with 0 and then drawing some geometry that should thus not be visible. But it always shows up, the alpha buffer is completly ignored.
# Clear alpha buffer to 0, and clear color buffer.
# After this, the alpha buffer should probaby be filled with 0.
glClearColor(0, 0, 0, 0)
glClear(GL_COLOR_BUFFER_BIT)
# Disable blending.
glDisable(GL_BLEND)
# Disable color writing.
glColorMask(False, False, False, True)
# Set color to a white with alpha 0.
glColor4f(1, 1, 1, 0)
# Now draw a fullscreen quad.
# After this, the alpha buffer should really be filled with 0.
# Shouldn't it?
glBegin(GL_QUADS)
glVertex2f(0, 0)
glVertex2f(320, 0)
glVertex2f(320, 480)
glVertex2f(0, 480)
glEnd()
# Enable color writing.
glColorMask(True, True, True, True)
# Enable blending so that incoming fragments are multiplied
# by alpha values already in the buffer.
glEnable(GL_BLEND)
glBlendFunc(GL_DST_ALPHA, GL_ONE)
# Set color to a white with alpha 1.
glColor4f(1, 1, 1, 1)
# Now draw a triangle.
# It should not be visible because alpha in framebuffer is 0
# and 0 * 1 = 0.
glBegin(GL_TRIANGLES)
glVertex2f(20, 50)
glVertex2f(300, 50)
glVertex2f(160, 210)
glEnd()
(Yes, the projection matrices are right so my screen ranges from 0/0 to 320/240.)
The triangle shouldn't be visible, what did I do wrong?
A:
Try asking for an alpha buffer when you create your GL context, if you aren't already.
A:
Use glAlphaFunc( GL_GREATER, 0.5 );
|
Alpha masks with OpenGL
|
I want to use an alpha mask in OpenGL so that white(1)=visible and black(0)=hidden.
So what I do is I write something in the alpha component of the framebuffer using glColorMask(False, False, False, True) (I'm using python, you see) and then draw some geometry above it using blending.
But it isn't working:
I tried filling the alpha buffer completly with 0 and then drawing some geometry that should thus not be visible. But it always shows up, the alpha buffer is completly ignored.
# Clear alpha buffer to 0, and clear color buffer.
# After this, the alpha buffer should probaby be filled with 0.
glClearColor(0, 0, 0, 0)
glClear(GL_COLOR_BUFFER_BIT)
# Disable blending.
glDisable(GL_BLEND)
# Disable color writing.
glColorMask(False, False, False, True)
# Set color to a white with alpha 0.
glColor4f(1, 1, 1, 0)
# Now draw a fullscreen quad.
# After this, the alpha buffer should really be filled with 0.
# Shouldn't it?
glBegin(GL_QUADS)
glVertex2f(0, 0)
glVertex2f(320, 0)
glVertex2f(320, 480)
glVertex2f(0, 480)
glEnd()
# Enable color writing.
glColorMask(True, True, True, True)
# Enable blending so that incoming fragments are multiplied
# by alpha values already in the buffer.
glEnable(GL_BLEND)
glBlendFunc(GL_DST_ALPHA, GL_ONE)
# Set color to a white with alpha 1.
glColor4f(1, 1, 1, 1)
# Now draw a triangle.
# It should not be visible because alpha in framebuffer is 0
# and 0 * 1 = 0.
glBegin(GL_TRIANGLES)
glVertex2f(20, 50)
glVertex2f(300, 50)
glVertex2f(160, 210)
glEnd()
(Yes, the projection matrices are right so my screen ranges from 0/0 to 320/240.)
The triangle shouldn't be visible, what did I do wrong?
|
[
"Try asking for an alpha buffer when you create your GL context, if you aren't already.\n",
"Use glAlphaFunc( GL_GREATER, 0.5 );\n"
] |
[
3,
0
] |
[] |
[] |
[
"alpha",
"blending",
"opengl",
"python"
] |
stackoverflow_0002134970_alpha_blending_opengl_python.txt
|
Q:
Database for web crawler in python?
Hi im writing a web crawler in python to extract news articles from news websites like nytimes.com. i want to know what would be a good db to use as a backend for this project?
Thanks in advance!
A:
This could be a great project to use a document database like CouchDB, MongoDB, or SimpleDB.
MongoDB has a hosted solution: http://mongohq.com. There is also a binding for Python (Pymongo).
SimpleDB is a great choice if you are hosting this on Amazon Web Services
CouchDB is an open source package from the Apache Foundation.
A:
Personally, I love PostGreSQL -- but other free DBs such as MySql (or, if you have reasonably small amounts of data -- a few GB at most -- even the SQLite that comes with Python) will be fine too.
A:
I think the database itself will probably be one of the easier aspects of a web crawler like this.
If expect high load reading or writing the database (for example if you intend to run many crawlers at the same time) then you will want to steer in the direction of MySql, otherwise something like Sqlite will probably do you just fine.
A:
You can take a look at Firebird
Firebird python driver are developped by the core team
|
Database for web crawler in python?
|
Hi im writing a web crawler in python to extract news articles from news websites like nytimes.com. i want to know what would be a good db to use as a backend for this project?
Thanks in advance!
|
[
"This could be a great project to use a document database like CouchDB, MongoDB, or SimpleDB.\nMongoDB has a hosted solution: http://mongohq.com. There is also a binding for Python (Pymongo).\nSimpleDB is a great choice if you are hosting this on Amazon Web Services\nCouchDB is an open source package from the Apache Foundation.\n",
"Personally, I love PostGreSQL -- but other free DBs such as MySql (or, if you have reasonably small amounts of data -- a few GB at most -- even the SQLite that comes with Python) will be fine too.\n",
"I think the database itself will probably be one of the easier aspects of a web crawler like this.\nIf expect high load reading or writing the database (for example if you intend to run many crawlers at the same time) then you will want to steer in the direction of MySql, otherwise something like Sqlite will probably do you just fine.\n",
"You can take a look at Firebird\nFirebird python driver are developped by the core team\n"
] |
[
7,
3,
1,
0
] |
[] |
[] |
[
"database",
"python",
"web_crawler"
] |
stackoverflow_0002143702_database_python_web_crawler.txt
|
Q:
Parsing All Mail from Mailbox File in Python
Maybe I'm going about this the wrong way, but I want to parse a single "catch all" email inbox via Python. I see the email module and I can make it parse an individual email, but what I want to do is open (for example) /var/spool/mail/catchall and parse all of the individual messages inside it. Opening that file and running the parser over it treats the whole thing as one giant email. How would I break it into individual messages?
Alternatively: is this A Bad Idea, given I'm going to want to delete the messages when I'm done with them? I'm tying this route instead of POP/ IMAP only because the server support isn't available right now.
A:
You'll want to use mailbox to actually go through the mailbox.
|
Parsing All Mail from Mailbox File in Python
|
Maybe I'm going about this the wrong way, but I want to parse a single "catch all" email inbox via Python. I see the email module and I can make it parse an individual email, but what I want to do is open (for example) /var/spool/mail/catchall and parse all of the individual messages inside it. Opening that file and running the parser over it treats the whole thing as one giant email. How would I break it into individual messages?
Alternatively: is this A Bad Idea, given I'm going to want to delete the messages when I'm done with them? I'm tying this route instead of POP/ IMAP only because the server support isn't available right now.
|
[
"You'll want to use mailbox to actually go through the mailbox.\n"
] |
[
2
] |
[] |
[] |
[
"email",
"parsing",
"python"
] |
stackoverflow_0002150177_email_parsing_python.txt
|
Q:
best way to build time series server using python
I'm interested to build a fast server that serves queries on time series. For example, say I have 1000 time series identified by category name x. The server will take a query submitted by a client process and immediately return the last value associated with a particular timestamp.
For example on the client script, someone would call the following function from a time series library:
def get_ts_value( id, timestamp )
// send message (something like message queue, remote procedure call?)
// send blocks until value comes back
return request_ts_value( id, timestamp )
On the server side, the process will keep most if not all of the time series file open or at least preload everything into memory so queries can be fast. Along with some sort of index information loaded into memory for quick searches.
My question is, which ones are the easiest library/modules to build the above or if there are any existing free frameworks available?
Thanks!
A:
As far as communication goes, do you have a protocol in mind? HTTP? raw TCP?
I would personally recommend an HTTP server using http://docs.python.org/library/wsgiref.html , although there's a chance that even that is not fast enough.
You could also use an SQL server.
|
best way to build time series server using python
|
I'm interested to build a fast server that serves queries on time series. For example, say I have 1000 time series identified by category name x. The server will take a query submitted by a client process and immediately return the last value associated with a particular timestamp.
For example on the client script, someone would call the following function from a time series library:
def get_ts_value( id, timestamp )
// send message (something like message queue, remote procedure call?)
// send blocks until value comes back
return request_ts_value( id, timestamp )
On the server side, the process will keep most if not all of the time series file open or at least preload everything into memory so queries can be fast. Along with some sort of index information loaded into memory for quick searches.
My question is, which ones are the easiest library/modules to build the above or if there are any existing free frameworks available?
Thanks!
|
[
"As far as communication goes, do you have a protocol in mind? HTTP? raw TCP?\nI would personally recommend an HTTP server using http://docs.python.org/library/wsgiref.html , although there's a chance that even that is not fast enough.\nYou could also use an SQL server.\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002150095_python.txt
|
Q:
Customary To Inherit Metaclasses From type?
I have been trying to understand python metaclasses, and so have been going through some sample code. As far as I understand it, a Python metaclass can be any callable. So, I can have my metaclass like
def metacls(clsName, bases, atts):
....
return type(clsName, bases, atts)
However, I have seen a lot of people write their metaclasses in the following way:
class Metacls(type):
def __new__(meta, clsName, bases, atts):
....
return type.__new__(meta, clsName, bases, atts)
As far as I can see, these would both do the same thing. Is there any reason to use the base class instead? Is it customary?
A:
There are subtle differences, mostly relating to inheritance. When using a
function as a metaclass, the resulting class is really an instance of type,
and can be inherited from without restriction; however, the metaclass function
will never be called for such subclasses. When using a subclass of type as a
metaclass, the resulting class will be an instance of that metaclass, as will
any of its subclasses; however, multiple inheritance will be restricted.
Illustrating the differences:
>>> def m1(name, bases, atts):
>>> print "m1 called for " + name
>>> return type(name, bases, atts)
>>>
>>> def m2(name, bases, atts):
>>> print "m2 called for " + name
>>> return type(name, bases, atts)
>>>
>>> class c1(object):
>>> __metaclass__ = m1
m1 called for c1
>>> type(c1)
<type 'type'>
>>> class sub1(c1):
>>> pass
>>> type(sub1)
<type 'type'>
>>> class c2(object):
>>> __metaclass__ = m2
m2 called for c2
>>> class sub2(c1, c2):
>>> pass
>>> type(sub2)
<type 'type'>
Note that when defining sub1 and sub2, no metaclass functions were called.
They will be created exactly as if c1 and c2 had no metaclasses, but instead
had been manipulated after creation.
>>> class M1(type):
>>> def __new__(meta, name, bases, atts):
>>> print "M1 called for " + name
>>> return super(M1, meta).__new__(meta, name, bases, atts)
>>> class C1(object):
>>> __metaclass__ = M1
M1 called for C1
>>> type(C1)
<class '__main__.M1'>
>>> class Sub1(C1):
>>> pass
M1 called for Sub1
>>> type(Sub1)
<class '__main__.M1'>
Note the differences already: M1 was called when creating Sub1, and both
classes are instances of M1. I'm using super() for the actual creation here,
for reasons which will become clear later.
>>> class M2(type):
>>> def __new__(meta, name, bases, atts):
>>> print "M2 called for " + name
>>> return super(M2, meta).__new__(meta, name, bases, atts)
>>> class C2(object):
>>> __metaclass__ = M2
M2 called for C2
>>> type(C2)
<class '__main__.M2'>
>>> class Sub2(C1, C2):
>>> pass
M1 called for Sub2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 23, in __new__
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
This is the major restriction on multiple inheritance with metaclasses.
Python doesn't know whether M1 and M2 are compatible metaclasses,
so it forces you to create a new one to guarantee that it does what you need.
>>> class M3(M1, M2):
>>> def __new__(meta, name, bases, atts):
>>> print "M3 called for " + name
>>> return super(M3, meta).__new__(meta, name, bases, atts)
>>> class C3(C1, C2):
>>> __metaclass__ = M3
M3 called for C3
M1 called for C3
M2 called for C3
>>> type(C3)
<class '__main__.M3'>
This is why I used super() in the metaclass __new__ functions: so each one
can call the next one in the MRO.
Certain use cases might need your classes to be of type type, or might want
to avoid the inheritance issues, in which case a metaclass function is probably
the way to go. In other cases, the type of the class might be truly important,
or you might want to operate on all subclasses, in which case subclassing
type would be a better idea. Feel free to use the style that fits best in
any given situation.
|
Customary To Inherit Metaclasses From type?
|
I have been trying to understand python metaclasses, and so have been going through some sample code. As far as I understand it, a Python metaclass can be any callable. So, I can have my metaclass like
def metacls(clsName, bases, atts):
....
return type(clsName, bases, atts)
However, I have seen a lot of people write their metaclasses in the following way:
class Metacls(type):
def __new__(meta, clsName, bases, atts):
....
return type.__new__(meta, clsName, bases, atts)
As far as I can see, these would both do the same thing. Is there any reason to use the base class instead? Is it customary?
|
[
"There are subtle differences, mostly relating to inheritance. When using a\nfunction as a metaclass, the resulting class is really an instance of type,\nand can be inherited from without restriction; however, the metaclass function\nwill never be called for such subclasses. When using a subclass of type as a\nmetaclass, the resulting class will be an instance of that metaclass, as will\nany of its subclasses; however, multiple inheritance will be restricted.\nIllustrating the differences:\n>>> def m1(name, bases, atts):\n>>> print \"m1 called for \" + name\n>>> return type(name, bases, atts)\n>>>\n\n>>> def m2(name, bases, atts):\n>>> print \"m2 called for \" + name\n>>> return type(name, bases, atts)\n>>>\n\n>>> class c1(object):\n>>> __metaclass__ = m1\nm1 called for c1\n\n>>> type(c1)\n<type 'type'>\n\n>>> class sub1(c1):\n>>> pass\n\n>>> type(sub1)\n<type 'type'>\n\n>>> class c2(object):\n>>> __metaclass__ = m2\nm2 called for c2\n\n>>> class sub2(c1, c2):\n>>> pass\n\n>>> type(sub2)\n<type 'type'>\n\nNote that when defining sub1 and sub2, no metaclass functions were called.\nThey will be created exactly as if c1 and c2 had no metaclasses, but instead\nhad been manipulated after creation.\n>>> class M1(type):\n>>> def __new__(meta, name, bases, atts):\n>>> print \"M1 called for \" + name\n>>> return super(M1, meta).__new__(meta, name, bases, atts)\n\n>>> class C1(object):\n>>> __metaclass__ = M1\nM1 called for C1\n\n>>> type(C1)\n<class '__main__.M1'>\n\n>>> class Sub1(C1):\n>>> pass\nM1 called for Sub1\n\n>>> type(Sub1)\n<class '__main__.M1'>\n\nNote the differences already: M1 was called when creating Sub1, and both\nclasses are instances of M1. I'm using super() for the actual creation here,\nfor reasons which will become clear later.\n>>> class M2(type):\n>>> def __new__(meta, name, bases, atts):\n>>> print \"M2 called for \" + name\n>>> return super(M2, meta).__new__(meta, name, bases, atts)\n\n>>> class C2(object):\n>>> __metaclass__ = M2\nM2 called for C2\n\n>>> type(C2)\n<class '__main__.M2'>\n\n>>> class Sub2(C1, C2):\n>>> pass\nM1 called for Sub2\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 23, in __new__\nTypeError: Error when calling the metaclass bases\n metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases\n\nThis is the major restriction on multiple inheritance with metaclasses.\nPython doesn't know whether M1 and M2 are compatible metaclasses,\nso it forces you to create a new one to guarantee that it does what you need.\n>>> class M3(M1, M2):\n>>> def __new__(meta, name, bases, atts):\n>>> print \"M3 called for \" + name\n>>> return super(M3, meta).__new__(meta, name, bases, atts)\n\n>>> class C3(C1, C2):\n>>> __metaclass__ = M3\nM3 called for C3\nM1 called for C3\nM2 called for C3\n\n>>> type(C3)\n<class '__main__.M3'>\n\nThis is why I used super() in the metaclass __new__ functions: so each one\ncan call the next one in the MRO.\nCertain use cases might need your classes to be of type type, or might want\nto avoid the inheritance issues, in which case a metaclass function is probably\nthe way to go. In other cases, the type of the class might be truly important,\nor you might want to operate on all subclasses, in which case subclassing\ntype would be a better idea. Feel free to use the style that fits best in\nany given situation.\n"
] |
[
46
] |
[] |
[] |
[
"metaclass",
"python"
] |
stackoverflow_0002149846_metaclass_python.txt
|
Q:
Emptying the datastore in GAE
I know what you're thinking, 'O not that again!', but here we are since Google have not yet provided a simpler method.
I have been using a queue based solution which worked fine:
import datetime
from models import *
DELETABLE_MODELS = [Alpha, Beta, AlphaBeta]
def initiate_purge():
for e in config.DELETABLE_MODELS:
deferred.defer(delete_entities, e, 'purging', _queue = 'purging')
class NotEmptyException(Exception): pass
def delete_entities(e, queue):
try:
q = e.all(keys_only=True)
db.delete(q.fetch(200))
ct = q.count(1)
if ct > 0:
raise NotEmptyException('there are still entities to be deleted')
else:
logging.info('processing %s completed' % queue)
except Exception, err:
deferred.defer(delete_entities, e, then, queue, _queue = queue)
logging.info('processing %s deferred: %s' % (queue, err))
All this does is queue a request to delete some data (once for each class) and then if the queued process either fails or knows there is still some stuff to delete, it re-queues itself.
This beats the heck out of hitting the refresh on a browser for 10 minutes.
However, I'm having trouble deleting AlphaBeta entities, there are always a few left at the end. I think because it contains Reference Properties:
class AlphaBeta(db.Model):
alpha = db.ReferenceProperty(Alpha, required=True, collection_name='betas')
beta = db.ReferenceProperty(Beta, required=True, collection_name='alphas')
I have tried deleting the indexes relating to these entity types, but that did not make any difference.
Any advice would be appreciated please.
A:
I don't believe that trying to delete an entity that has references to still-existing entities is really a problem, but you can always rules this out be re-writing your task to delete the entities serially instead of in parallel:
def initiate_purge():
deferred.defer(delete_entities, Alpha, _queue = 'purging')
def delete_entities(e):
try:
q = e.all(keys_only=True)
db.delete(q.fetch(200))
ct = q.count(1)
if ct > 0:
raise NotEmptyException('there are still entities to be deleted')
else:
logging.info('processing completed')
if type(e) == Alpha:
logging.info('spawning delete Beta task.')
deferred.defer(delete_entities, Beta, _queue = 'purging')
else if type(e) == Beta:
logging.info('spawning delete AlphaBeta task.')
deferred.defer(delete_entities, AlphaBeta, _queue = 'purging')
except Exception, err:
deferred.defer(delete_entities, e, _queue = 'purging')
logging.info('processing deferred: %s' % (err))
|
Emptying the datastore in GAE
|
I know what you're thinking, 'O not that again!', but here we are since Google have not yet provided a simpler method.
I have been using a queue based solution which worked fine:
import datetime
from models import *
DELETABLE_MODELS = [Alpha, Beta, AlphaBeta]
def initiate_purge():
for e in config.DELETABLE_MODELS:
deferred.defer(delete_entities, e, 'purging', _queue = 'purging')
class NotEmptyException(Exception): pass
def delete_entities(e, queue):
try:
q = e.all(keys_only=True)
db.delete(q.fetch(200))
ct = q.count(1)
if ct > 0:
raise NotEmptyException('there are still entities to be deleted')
else:
logging.info('processing %s completed' % queue)
except Exception, err:
deferred.defer(delete_entities, e, then, queue, _queue = queue)
logging.info('processing %s deferred: %s' % (queue, err))
All this does is queue a request to delete some data (once for each class) and then if the queued process either fails or knows there is still some stuff to delete, it re-queues itself.
This beats the heck out of hitting the refresh on a browser for 10 minutes.
However, I'm having trouble deleting AlphaBeta entities, there are always a few left at the end. I think because it contains Reference Properties:
class AlphaBeta(db.Model):
alpha = db.ReferenceProperty(Alpha, required=True, collection_name='betas')
beta = db.ReferenceProperty(Beta, required=True, collection_name='alphas')
I have tried deleting the indexes relating to these entity types, but that did not make any difference.
Any advice would be appreciated please.
|
[
"I don't believe that trying to delete an entity that has references to still-existing entities is really a problem, but you can always rules this out be re-writing your task to delete the entities serially instead of in parallel:\ndef initiate_purge():\n deferred.defer(delete_entities, Alpha, _queue = 'purging')\n\ndef delete_entities(e):\n try:\n q = e.all(keys_only=True)\n db.delete(q.fetch(200))\n ct = q.count(1)\n if ct > 0:\n raise NotEmptyException('there are still entities to be deleted')\n else:\n logging.info('processing completed')\n if type(e) == Alpha:\n logging.info('spawning delete Beta task.')\n deferred.defer(delete_entities, Beta, _queue = 'purging')\n else if type(e) == Beta:\n logging.info('spawning delete AlphaBeta task.')\n deferred.defer(delete_entities, AlphaBeta, _queue = 'purging')\n except Exception, err:\n deferred.defer(delete_entities, e, _queue = 'purging')\n logging.info('processing deferred: %s' % (err))\n\n"
] |
[
1
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002147787_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Can somebody explain a money regex that just checks if the value matches some pattern?
There are multiple posts on here that capture value, but I'm just looking to check to see if the value is something. More vaguely put; I'm looking to understand the difference between checking a value, and "capturing" a value. In the current case the value would be the following acceptable money formats:
Here is a post that explains some about a money regex but I don't understand it a bit.
.50
50
50.00
50.0
$5000.00
$.50
I don't want commas (people should know that's ridiculous).
The thing I'm having trouble with are:
Allowing for a $ at the starting of the value (but still optional)
Allowing for only 1 decimal point (but not allowing it at the end)
Understanding how it's working inside
Also understanding out to get a normalized version (only digits and a the optional decimal point) out of it that strips the dollar sign.
My current regex (which obviously doesn't work right) is:
# I'm checking the Boolean of the following:
re.compile(r'^[\$][\d\.]$').search(value)
(Note: I'm working in Python)
A:
Assuming you want to allow $5. but not 5., the following will accept your language:
money = re.compile('|'.join([
r'^\$?(\d*\.\d{1,2})$', # e.g., $.50, .50, $1.50, $.5, .5
r'^\$?(\d+)$', # e.g., $500, $5, 500, 5
r'^\$(\d+\.?)$', # e.g., $5.
]))
Important pieces to understand:
^ and $ match only at the beginning and end of the input string, respectively.
\. matches a literal dot
\$ matches a literal dollar sign
\$? matches a dollar sign or nothing (i.e., an optional dollar sign)
\d matches any single digit (0-9)
\d* matches runs of zero or more digits
\d+ matches runs of one or more digits
\d{1,2} matches any single digit or a run of two digits
The parenthesized subpatterns are capture groups: all text in the input matched by the subexpression in a capture group will be available in matchobj.group(index). The dollar sign won't be captured because it's outside the parentheses.
Because Python doesn't support multiple capture groups with the same name (!!!) we must search through matchobj.groups() for the one that isn't None. This also means you have to be careful when modifying the pattern to use (?:...) for every group except the amount.
Tweaking Mark's nice test harness, we get
for test, expected in tests:
result = money.match(test)
is_match = result is not None
if is_match == expected:
status = 'OK'
if result:
amt = [x for x in result.groups() if x is not None].pop()
status += ' (%s)' % amt
else:
status = 'Fail'
print test + '\t' + status
Output:
.50 OK (.50)
50 OK (50)
50.00 OK (50.00)
50.0 OK (50.0)
$5000 OK (5000)
$.50 OK (.50)
$5. OK (5.)
5. OK
$5.000 OK
5000$ OK
$5.00$ OK
$-5.00 OK
$5,00 OK
OK
$ OK
. OK
.5 OK (.5)
A:
Here's a regex you can use:
regex = re.compile(r'^\$?(\d*(\d\.?|\.\d{1,2}))$')
Here's a test-bed I used to test it. I've included all your tests, plus some of my own. I've also included some negative tests, as making sure that it doesn't match when it shouldn't is just as important as making sure that it does match when it should.
tests = [
('.50', True),
('50', True),
('50.00', True),
('50.0', True),
('$5000', True),
('$.50', True),
('$5.', True),
('$5.000', False),
('5000$', False),
('$5.00$', False),
('$-5.00', False),
('$5,00', False),
('', False),
('$', False),
('.', False),
]
import re
regex = re.compile(r'^\$?(\d*(\d\.?|\.\d{1,2}))$')
for test, expected in tests:
result = regex.match(test)
is_match = result is not None
print test + '\t' + ('OK' if is_match == expected else 'Fail')
To get the value without the $, you can use the captured group:
print result.group(1)
A:
Also understanding out to get a normalized version (only digits and a the optional decimal point) out of it that strips the dollar sign.
This is also known as "capturing" the value ;)
Working off Aaron's base example:
/^\$?(\d+(?:\.\d{1,2})?)$/
Then the amount (without the dollar sign) will be in capture group 1.
A:
I believe the following regex will meet your needs:
/^\$?(\d*(\.\d\d?)?|\d+)$/
It allows for an optional '$'. It allows for an optional decimal, but requires at least one but not more than two digits after the decimal if the decimal is present.
Edit: The outer parentheses will catch the whole numeric value for you.
|
Can somebody explain a money regex that just checks if the value matches some pattern?
|
There are multiple posts on here that capture value, but I'm just looking to check to see if the value is something. More vaguely put; I'm looking to understand the difference between checking a value, and "capturing" a value. In the current case the value would be the following acceptable money formats:
Here is a post that explains some about a money regex but I don't understand it a bit.
.50
50
50.00
50.0
$5000.00
$.50
I don't want commas (people should know that's ridiculous).
The thing I'm having trouble with are:
Allowing for a $ at the starting of the value (but still optional)
Allowing for only 1 decimal point (but not allowing it at the end)
Understanding how it's working inside
Also understanding out to get a normalized version (only digits and a the optional decimal point) out of it that strips the dollar sign.
My current regex (which obviously doesn't work right) is:
# I'm checking the Boolean of the following:
re.compile(r'^[\$][\d\.]$').search(value)
(Note: I'm working in Python)
|
[
"Assuming you want to allow $5. but not 5., the following will accept your language:\nmoney = re.compile('|'.join([\n r'^\\$?(\\d*\\.\\d{1,2})$', # e.g., $.50, .50, $1.50, $.5, .5\n r'^\\$?(\\d+)$', # e.g., $500, $5, 500, 5\n r'^\\$(\\d+\\.?)$', # e.g., $5.\n]))\n\nImportant pieces to understand:\n\n^ and $ match only at the beginning and end of the input string, respectively.\n\\. matches a literal dot\n\\$ matches a literal dollar sign\n\n\n\\$? matches a dollar sign or nothing (i.e., an optional dollar sign)\n\n\\d matches any single digit (0-9)\n\n\n\\d* matches runs of zero or more digits\n\\d+ matches runs of one or more digits\n\\d{1,2} matches any single digit or a run of two digits\n\n\nThe parenthesized subpatterns are capture groups: all text in the input matched by the subexpression in a capture group will be available in matchobj.group(index). The dollar sign won't be captured because it's outside the parentheses.\nBecause Python doesn't support multiple capture groups with the same name (!!!) we must search through matchobj.groups() for the one that isn't None. This also means you have to be careful when modifying the pattern to use (?:...) for every group except the amount.\nTweaking Mark's nice test harness, we get\nfor test, expected in tests:\n result = money.match(test) \n is_match = result is not None\n if is_match == expected:\n status = 'OK'\n if result:\n amt = [x for x in result.groups() if x is not None].pop()\n status += ' (%s)' % amt\n else:\n status = 'Fail'\n print test + '\\t' + status\n\nOutput:\n\n.50 OK (.50)\n50 OK (50)\n50.00 OK (50.00)\n50.0 OK (50.0)\n$5000 OK (5000)\n$.50 OK (.50)\n$5. OK (5.)\n5. OK\n$5.000 OK\n5000$ OK\n$5.00$ OK\n$-5.00 OK\n$5,00 OK\n OK\n$ OK\n. OK\n.5 OK (.5)\n",
"Here's a regex you can use:\nregex = re.compile(r'^\\$?(\\d*(\\d\\.?|\\.\\d{1,2}))$')\n\nHere's a test-bed I used to test it. I've included all your tests, plus some of my own. I've also included some negative tests, as making sure that it doesn't match when it shouldn't is just as important as making sure that it does match when it should.\ntests = [\n ('.50', True),\n ('50', True),\n ('50.00', True),\n ('50.0', True),\n ('$5000', True),\n ('$.50', True),\n ('$5.', True),\n ('$5.000', False),\n ('5000$', False),\n ('$5.00$', False),\n ('$-5.00', False),\n ('$5,00', False),\n ('', False),\n ('$', False),\n ('.', False),\n]\n\nimport re\nregex = re.compile(r'^\\$?(\\d*(\\d\\.?|\\.\\d{1,2}))$')\nfor test, expected in tests:\n result = regex.match(test) \n is_match = result is not None\n print test + '\\t' + ('OK' if is_match == expected else 'Fail')\n\nTo get the value without the $, you can use the captured group:\nprint result.group(1)\n\n",
"\nAlso understanding out to get a normalized version (only digits and a the optional decimal point) out of it that strips the dollar sign.\n\nThis is also known as \"capturing\" the value ;)\nWorking off Aaron's base example:\n/^\\$?(\\d+(?:\\.\\d{1,2})?)$/\n\nThen the amount (without the dollar sign) will be in capture group 1.\n",
"I believe the following regex will meet your needs:\n/^\\$?(\\d*(\\.\\d\\d?)?|\\d+)$/\n\nIt allows for an optional '$'. It allows for an optional decimal, but requires at least one but not more than two digits after the decimal if the decimal is present.\nEdit: The outer parentheses will catch the whole numeric value for you.\n"
] |
[
17,
8,
4,
3
] |
[] |
[] |
[
"currency",
"python",
"regex"
] |
stackoverflow_0002150205_currency_python_regex.txt
|
Q:
Finding Signed Angle Between Vectors
How would you find the signed angle theta from vector a to b?
And yes, I know that theta = arccos((a.b)/(|a||b|)).
However, this does not contain a sign (i.e. it doesn't distinguish between a clockwise or counterclockwise rotation).
I need something that can tell me the minimum angle to rotate from a to b. A positive sign indicates a rotation from +x-axis towards +y-axis. Conversely, a negative sign indicates a rotation from +x-axis towards -y-axis.
assert angle((1,0),(0,1)) == pi/2.
assert angle((0,1),(1,0)) == -pi/2.
A:
What you want to use is often called the “perp dot product”, that is, find the vector perpendicular to one of the vectors, and then find the dot product with the other vector.
if(a.x*b.y - a.y*b.x < 0)
angle = -angle;
You can also do this:
angle = atan2( a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y );
A:
If you have an atan2() function in your math library of choice:
signed_angle = atan2(b.y,b.x) - atan2(a.y,a.x)
|
Finding Signed Angle Between Vectors
|
How would you find the signed angle theta from vector a to b?
And yes, I know that theta = arccos((a.b)/(|a||b|)).
However, this does not contain a sign (i.e. it doesn't distinguish between a clockwise or counterclockwise rotation).
I need something that can tell me the minimum angle to rotate from a to b. A positive sign indicates a rotation from +x-axis towards +y-axis. Conversely, a negative sign indicates a rotation from +x-axis towards -y-axis.
assert angle((1,0),(0,1)) == pi/2.
assert angle((0,1),(1,0)) == -pi/2.
|
[
"What you want to use is often called the “perp dot product”, that is, find the vector perpendicular to one of the vectors, and then find the dot product with the other vector.\nif(a.x*b.y - a.y*b.x < 0)\n angle = -angle;\n\nYou can also do this:\nangle = atan2( a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y );\n\n",
"If you have an atan2() function in your math library of choice:\nsigned_angle = atan2(b.y,b.x) - atan2(a.y,a.x)\n\n"
] |
[
71,
38
] |
[] |
[] |
[
"angle",
"java",
"math",
"python",
"trigonometry"
] |
stackoverflow_0002150050_angle_java_math_python_trigonometry.txt
|
Q:
django - inlineformset_factory with more than one ForeignKey
Im trying to do a formset with the following models (boost is the primary):
class boost(models.Model):
creator = models.ForeignKey(userInfo)
game = models.ForeignKey(gameInfo)
name = models.CharField(max_length=200)
desc = models.CharField(max_length=500)
rules = models.CharField(max_length=500)
subscribe = models.IntegerField(default=0)
class userInfo(models.Model):
pic_url= models.URLField(default=0, blank=True)
auth = models.ForeignKey(User, unique=True)
birth = models.DateTimeField(default=0, blank=True)
country= models.IntegerField(default=0, blank=True)
class gameInfo(models.Model):
psn_id = models.CharField(max_length=100)
name = models.CharField(max_length=200)
publisher = models.CharField(max_length=200, default=0)
developer = models.CharField(max_length=200, default=0)
release_date = models.DateTimeField(blank=True, null=True)
I want to display a form to add a Boost item, trying to do in this way :
TrophyFormSet = inlineformset_factory(db.gameInfo, db.boost, extra=1)
formset = TrophyFormSet()
Here is my questions :
1 - When renderized, the combo box for "Creator" show a list of "db.userInfo" (literally) ! I want this to display db.userInfo.auth.username that are already in the database... how to do this ?
2 - In this way, where is my "db.gameInfo" to choose ?
thank you ! =D
======
czarchaic answered my question very well !
Bu now i need just a little question:
When i use the modelform to create a form for the boost_trophy model :
class boost_trophy(models.Model):
boost = models.ForeignKey(boost)
trophy = models.ForeignKey(gameTrophyInfo)
# 0 - Obtiveis
# 1 - Requisitos minimos
type = models.IntegerField(default=0)
class gameTrophyInfo(models.Model):
game = models.ForeignKey(gameInfo)
name = models.CharField(max_length=500)
desc = models.CharField(max_length=500)
type = models.CharField(max_length=20)
its work nice , but i want to the form to show in the "game" box only a realy small set of itens, only the : gameTrophyInfo(game__name="Game_A") results. How can i do this ?
A:
If I understand you correctly:
To change what is displayed set the model's __unicode__ function
class userInfo(models.Model):
#model fields
def __unicode__(self):
return self.auth.username
|
django - inlineformset_factory with more than one ForeignKey
|
Im trying to do a formset with the following models (boost is the primary):
class boost(models.Model):
creator = models.ForeignKey(userInfo)
game = models.ForeignKey(gameInfo)
name = models.CharField(max_length=200)
desc = models.CharField(max_length=500)
rules = models.CharField(max_length=500)
subscribe = models.IntegerField(default=0)
class userInfo(models.Model):
pic_url= models.URLField(default=0, blank=True)
auth = models.ForeignKey(User, unique=True)
birth = models.DateTimeField(default=0, blank=True)
country= models.IntegerField(default=0, blank=True)
class gameInfo(models.Model):
psn_id = models.CharField(max_length=100)
name = models.CharField(max_length=200)
publisher = models.CharField(max_length=200, default=0)
developer = models.CharField(max_length=200, default=0)
release_date = models.DateTimeField(blank=True, null=True)
I want to display a form to add a Boost item, trying to do in this way :
TrophyFormSet = inlineformset_factory(db.gameInfo, db.boost, extra=1)
formset = TrophyFormSet()
Here is my questions :
1 - When renderized, the combo box for "Creator" show a list of "db.userInfo" (literally) ! I want this to display db.userInfo.auth.username that are already in the database... how to do this ?
2 - In this way, where is my "db.gameInfo" to choose ?
thank you ! =D
======
czarchaic answered my question very well !
Bu now i need just a little question:
When i use the modelform to create a form for the boost_trophy model :
class boost_trophy(models.Model):
boost = models.ForeignKey(boost)
trophy = models.ForeignKey(gameTrophyInfo)
# 0 - Obtiveis
# 1 - Requisitos minimos
type = models.IntegerField(default=0)
class gameTrophyInfo(models.Model):
game = models.ForeignKey(gameInfo)
name = models.CharField(max_length=500)
desc = models.CharField(max_length=500)
type = models.CharField(max_length=20)
its work nice , but i want to the form to show in the "game" box only a realy small set of itens, only the : gameTrophyInfo(game__name="Game_A") results. How can i do this ?
|
[
"If I understand you correctly:\nTo change what is displayed set the model's __unicode__ function\nclass userInfo(models.Model):\n #model fields\n\n def __unicode__(self):\n return self.auth.username\n\n"
] |
[
11
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002149697_django_python.txt
|
Q:
Is PHP the only choice re: massive and rapid uptake of a re-deployable, extensible web application?
My own answer to this question is YES, but I'd like to hear from others. Put another way the question could be: Would the success of 1-click-install WordPress (not WordPress.com, which is SaaS) be possible if it weren't written in PHP, all other things being equal?
The critical associated requirements I believe support PHP are:
hosting/deployment flexibility
developer reach
flexibility and depth of knowledge around server performance tuning
Items #1 and #2 are equally critical, and both are far more important than #3.
FWIW, I'm not a particular fan of PHP - can anyone truly be? - but the goals of re-deployment and extensibility point wherever they point. Please, please do not pollute this space if you do not grok the question. This is not about PHP and it's relative merits, or lack of merit, compared to other programming languages out of context. I am looking for insight specifically around language choice as it relates to deployment/uptake/extensibility strategy as outlined.
Thanks.
A:
As far as points #1 and #2 go, you are probably right. No other platform is so widely, easily and cheaply available in terms of hosting companies and packages like the LAMP stack. Plus, most incompatibilities that can occur when deploying an application to a completely unknown web space are well documented, their number is limited, and can mostly be checked beforehand (register_globals, safe mode, allocated script memory, etc.)
If I were thinking about developing a web application that I want to see spreading as quickly and as far as possible also among non-professionals and end users, PHP would be my platform of choice for these reasons. I must add that I am deeply familiar only with the hosting market in Germany, but I'm quite sure the basic characteristics are the same.
As for developer availability: People who claim to be able to speak PHP are easy to find. Those who will actually do a good job for you, less so. Still, I think it is safe to say that PHP developers are easier to find than, say, Pythonists or Ruby developers.
I don't expect this to stay this way forever, though. Other languages are gaining popularity, and in the end, developers and which languages they like influences the hosting market massively in the long term.
|
Is PHP the only choice re: massive and rapid uptake of a re-deployable, extensible web application?
|
My own answer to this question is YES, but I'd like to hear from others. Put another way the question could be: Would the success of 1-click-install WordPress (not WordPress.com, which is SaaS) be possible if it weren't written in PHP, all other things being equal?
The critical associated requirements I believe support PHP are:
hosting/deployment flexibility
developer reach
flexibility and depth of knowledge around server performance tuning
Items #1 and #2 are equally critical, and both are far more important than #3.
FWIW, I'm not a particular fan of PHP - can anyone truly be? - but the goals of re-deployment and extensibility point wherever they point. Please, please do not pollute this space if you do not grok the question. This is not about PHP and it's relative merits, or lack of merit, compared to other programming languages out of context. I am looking for insight specifically around language choice as it relates to deployment/uptake/extensibility strategy as outlined.
Thanks.
|
[
"As far as points #1 and #2 go, you are probably right. No other platform is so widely, easily and cheaply available in terms of hosting companies and packages like the LAMP stack. Plus, most incompatibilities that can occur when deploying an application to a completely unknown web space are well documented, their number is limited, and can mostly be checked beforehand (register_globals, safe mode, allocated script memory, etc.) \nIf I were thinking about developing a web application that I want to see spreading as quickly and as far as possible also among non-professionals and end users, PHP would be my platform of choice for these reasons. I must add that I am deeply familiar only with the hosting market in Germany, but I'm quite sure the basic characteristics are the same.\nAs for developer availability: People who claim to be able to speak PHP are easy to find. Those who will actually do a good job for you, less so. Still, I think it is safe to say that PHP developers are easier to find than, say, Pythonists or Ruby developers.\nI don't expect this to stay this way forever, though. Other languages are gaining popularity, and in the end, developers and which languages they like influences the hosting market massively in the long term.\n"
] |
[
3
] |
[] |
[] |
[
"deployment",
"hosting",
"php",
"python",
"wordpress"
] |
stackoverflow_0002150947_deployment_hosting_php_python_wordpress.txt
|
Q:
How do you create flash images on the fly at the server side?
The question just came up!
I have seen in web apps we get flash images generated on the fly how is it achieved? Any api for programming languages (Java Python)?
PS: It's adobe flash movie / image or swf
A:
If by Flash images you mean JPG, PNG and GIF files then you use any of the standard server side software packages or language specific libraries that utilize these packages.
Here are the two most popular:
ImageMagick
GD
Python has PIL (Python Imaging Library)
If you are referring to generating swfs then update the question and perhaps you can get some help on that too.
A:
Open Flash Chart
Flex
|
How do you create flash images on the fly at the server side?
|
The question just came up!
I have seen in web apps we get flash images generated on the fly how is it achieved? Any api for programming languages (Java Python)?
PS: It's adobe flash movie / image or swf
|
[
"If by Flash images you mean JPG, PNG and GIF files then you use any of the standard server side software packages or language specific libraries that utilize these packages.\nHere are the two most popular:\nImageMagick\nGD\nPython has PIL (Python Imaging Library) \nIf you are referring to generating swfs then update the question and perhaps you can get some help on that too.\n",
"Open Flash Chart\nFlex\n"
] |
[
1,
0
] |
[] |
[] |
[
"flash",
"java",
"python"
] |
stackoverflow_0002075432_flash_java_python.txt
|
Q:
replacing node text using lxml.objectify while preserving attributes
Using lxml.objectify like so:
from lxml import objectify
o = objectify.fromstring("<a><b atr='someatr'>oldtext</b></a>")
o.b = 'newtext'
results in <a><b>newtext</b></a>, losing the node attribute. It seems to be directly replacing the element with a newly created one, rather than simply replacing the text of the element.
If I try to use o.b.text = 'newtext', it tells me that
attribute 'text' of 'StringElement' objects is not writable.
Is there a way to do this within objectify without having to split it out into a different element and involving etree? I simply want to replace the inner text while leaving the rest of the node alone. I feel like I'm missing something simple here.
A:
>>> type(o.b)
<type 'lxml.objectify.StringElement'>
You are replacing an element with a plain string. You need to replace it with a new string element.
>>> o.b = objectify.E.b('newtext', atr='someatr')
For some reason you can't just do:
>>> o.b.text = 'newtext'
However, this seems to work:
>>> o.b._setText('newtext')
|
replacing node text using lxml.objectify while preserving attributes
|
Using lxml.objectify like so:
from lxml import objectify
o = objectify.fromstring("<a><b atr='someatr'>oldtext</b></a>")
o.b = 'newtext'
results in <a><b>newtext</b></a>, losing the node attribute. It seems to be directly replacing the element with a newly created one, rather than simply replacing the text of the element.
If I try to use o.b.text = 'newtext', it tells me that
attribute 'text' of 'StringElement' objects is not writable.
Is there a way to do this within objectify without having to split it out into a different element and involving etree? I simply want to replace the inner text while leaving the rest of the node alone. I feel like I'm missing something simple here.
|
[
">>> type(o.b)\n<type 'lxml.objectify.StringElement'>\n\nYou are replacing an element with a plain string. You need to replace it with a new string element.\n>>> o.b = objectify.E.b('newtext', atr='someatr')\n\nFor some reason you can't just do:\n>>> o.b.text = 'newtext'\n\nHowever, this seems to work:\n>>> o.b._setText('newtext')\n\n"
] |
[
10
] |
[] |
[] |
[
"lxml",
"python",
"xml"
] |
stackoverflow_0002150838_lxml_python_xml.txt
|
Q:
Reduce strings in python to a specific point
I have strings in my python application that look this way:
test1/test2/foo/
Everytime I get such a string, I want to reduce it, beginning from the tail and reduced until the fist "/" is reached.
test1/test2/
More examples:
foo/foo/foo/foo/foo/ => foo/foo/foo/foo/
test/test/ => test/
how/to/implement/this => how/to/implement/
How can I implement this in python?
Thanks in advance!
A:
It sounds like the os.path.dirname function might be what you're looking for. You may need to call it more than once:
>>> import os.path
>>> os.path.dirname("test1/test2/")
'test1/test2'
>>> os.path.dirname("test1/test2")
'test1'
A:
str.rsplit() with the maxsplit argument. Or if this is a path, look in os.path or urlparse.
A:
newString = oldString[:oldString[:-1].rfind('/')]
# strip out trailing slash ----^ ^---- find last remaining slash
A:
>>> import os
>>> path="how/to/implement/this"
>>> os.path.split(path)
('how/to/implement', 'this')
>>> os.path.split(path)[0]
'how/to/implement'
A:
>>> os.path.split('how/to/implement/this'.rstrip('/'))
('how/to/implement', 'this')
>>> os.path.split('how/to/implement/this/'.rstrip('/'))
('how/to/implement', 'this')
A:
'/'.join(s.split('/')[:-1]+[''])
A:
If you mean "/" as in path separator, the function you want is:
os.path.dirname(your_argument)
If not, then you want:
def your_function(your_argument):
result= your_argument.rstrip("/").rpartition("/")[0]
if result:
return result + "/"
return result
Please specify what should be the result when "test/" is used as an argument: should it be "/" or ""? I assumed the second in my code above.
|
Reduce strings in python to a specific point
|
I have strings in my python application that look this way:
test1/test2/foo/
Everytime I get such a string, I want to reduce it, beginning from the tail and reduced until the fist "/" is reached.
test1/test2/
More examples:
foo/foo/foo/foo/foo/ => foo/foo/foo/foo/
test/test/ => test/
how/to/implement/this => how/to/implement/
How can I implement this in python?
Thanks in advance!
|
[
"It sounds like the os.path.dirname function might be what you're looking for. You may need to call it more than once:\n>>> import os.path\n>>> os.path.dirname(\"test1/test2/\")\n'test1/test2'\n>>> os.path.dirname(\"test1/test2\")\n'test1'\n\n",
"str.rsplit() with the maxsplit argument. Or if this is a path, look in os.path or urlparse.\n",
" newString = oldString[:oldString[:-1].rfind('/')]\n # strip out trailing slash ----^ ^---- find last remaining slash\n\n",
">>> import os\n>>> path=\"how/to/implement/this\"\n>>> os.path.split(path)\n('how/to/implement', 'this')\n>>> os.path.split(path)[0]\n'how/to/implement'\n\n",
">>> os.path.split('how/to/implement/this'.rstrip('/'))\n('how/to/implement', 'this')\n>>> os.path.split('how/to/implement/this/'.rstrip('/'))\n('how/to/implement', 'this')\n\n",
"'/'.join(s.split('/')[:-1]+[''])\n\n",
"If you mean \"/\" as in path separator, the function you want is:\nos.path.dirname(your_argument)\n\nIf not, then you want:\ndef your_function(your_argument):\n result= your_argument.rstrip(\"/\").rpartition(\"/\")[0]\n if result:\n return result + \"/\"\n return result\n\nPlease specify what should be the result when \"test/\" is used as an argument: should it be \"/\" or \"\"? I assumed the second in my code above.\n"
] |
[
6,
5,
5,
1,
0,
0,
0
] |
[] |
[] |
[
"path",
"python",
"string"
] |
stackoverflow_0002145371_path_python_string.txt
|
Q:
How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?
How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?
A:
Use SoupStrainer,
from BeautifulSoup import BeautifulSoup, SoupStrainer
import re
# Find all links
links = SoupStrainer('a')
[tag for tag in BeautifulSoup(doc, parseOnlyThese=links)]
linkstodomain = SoupStrainer('a', href=re.compile('example.com/'))
Edit: Modified example from official doc.
|
How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?
|
How can I use BeautifulSoup to find all the links in a page pointing to a specific domain?
|
[
"Use SoupStrainer,\nfrom BeautifulSoup import BeautifulSoup, SoupStrainer\nimport re\n\n# Find all links\nlinks = SoupStrainer('a')\n[tag for tag in BeautifulSoup(doc, parseOnlyThese=links)]\n\nlinkstodomain = SoupStrainer('a', href=re.compile('example.com/'))\n\nEdit: Modified example from official doc.\n"
] |
[
8
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0002151365_beautifulsoup_python.txt
|
Q:
Problem with jQuery Ajax...how do I update two DIVs with ONE ajax call?
function ajaxCall(query){
$.ajax({
method:"get",
url:"/main/",
data:"q="+query,
beforeSend:function() {},
success:function(html){
$("#main").html(html);
}
});
};
This is the entire code that will populate #main:
<p>{{ num_results }}, you just searched for {{ query }}</p>
Suppose I have another div called $("secondary") ....how would I populate that with {{ num_results }}, which is a part of the code, instead of all of it?
A:
One option is to return json with the data you need for each area.
$.ajax({
method:"get",
url:"/main/",
dataType: "json",
data:"q="+query,
beforeSend:function() {},
success:function(json){
$("#main").html(json.main);
$("#secondary").html(json.secondary);
}
});
What you would be returning is:
{
"main": "<p>{{ num_results }}, you just searched for {{ query }}</p>",
"secondary": "{{ num_results }}"
}
A:
You will need to return a XML or JSON object from the request which will the be used to fill in only the relevant parts. Try something like this:
function ajaxCall(query){
$.ajax({
method:"get",
url:"/main/",
data:"q="+query,
beforeSend:function() {},
success:function(html){
$("#main").html(html.main);
$("#secondary").html(html.secondary);
}
});
};
You will also need to update the server-side to return a JSON object.
A:
Use a regular expression
success:function(html){
$("#main").html(html);
$("secondary").html( /.*?(?=,)/.exec(html) );
}
A:
$('#secondary').html($('#main p').html().split(',')[0]);
|
Problem with jQuery Ajax...how do I update two DIVs with ONE ajax call?
|
function ajaxCall(query){
$.ajax({
method:"get",
url:"/main/",
data:"q="+query,
beforeSend:function() {},
success:function(html){
$("#main").html(html);
}
});
};
This is the entire code that will populate #main:
<p>{{ num_results }}, you just searched for {{ query }}</p>
Suppose I have another div called $("secondary") ....how would I populate that with {{ num_results }}, which is a part of the code, instead of all of it?
|
[
"One option is to return json with the data you need for each area.\n$.ajax({\n method:\"get\",\n url:\"/main/\",\n dataType: \"json\",\n data:\"q=\"+query,\n beforeSend:function() {},\n success:function(json){\n $(\"#main\").html(json.main);\n $(\"#secondary\").html(json.secondary);\n }\n});\n\nWhat you would be returning is: \n{\n \"main\": \"<p>{{ num_results }}, you just searched for {{ query }}</p>\",\n \"secondary\": \"{{ num_results }}\"\n}\n\n",
"You will need to return a XML or JSON object from the request which will the be used to fill in only the relevant parts. Try something like this: \nfunction ajaxCall(query){\n$.ajax({\n method:\"get\",\n url:\"/main/\",\n data:\"q=\"+query,\n beforeSend:function() {},\n success:function(html){\n $(\"#main\").html(html.main);\n $(\"#secondary\").html(html.secondary);\n }\n });\n };\n\nYou will also need to update the server-side to return a JSON object.\n",
"Use a regular expression\nsuccess:function(html){\n $(\"#main\").html(html);\n $(\"secondary\").html( /.*?(?=,)/.exec(html) );\n }\n\n",
"$('#secondary').html($('#main p').html().split(',')[0]);\n\n"
] |
[
6,
1,
0,
0
] |
[] |
[] |
[
"ajax",
"django",
"javascript",
"jquery",
"python"
] |
stackoverflow_0002151490_ajax_django_javascript_jquery_python.txt
|
Q:
Depth-First search in Python
Okay so basically I'm trying to do a depth-first search for a mini-peg solitaire game. For those unfamiliar with the game it's pretty simple.
There's a board with 10 holes and 9 pegs, a peg is represented by a 1 and an empty spot by a 0. You can move a peg backwards or forwards two holes at a time (but you can only move to an empty hole), and if you jump over another peg in the process you take it out and it becomes a hole.
So here's what a game looks like:
[1, 1, 1, 1, 1, 0, 1, 1, 1, 1]
[1, 1, 1, 0, 0, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 0, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 1, 0, 0, 1, 1, 1]
[1, 0, 0, 0, 0, 1, 0, 1, 1, 1]
[1, 0, 0, 0, 0, 1, 1, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1, 0, 1] #etc until only 1 peg left
So, I have a generator function here that finds all legal moves for a certain "node", or a game board:
def succ(self, node):
size = len(node)
# find all legal moves going forward
for pos in range(0, size-1):
new_node = list(node)
if ((node[pos] == 1) and (pos < (size - 2)) and (node[pos+2] == 0)):
new_node[pos] = 0 # we're moving now
new_node[pos+2] = 1 # this is where we're moving the peg to
new_node[pos+1] = 0 # take out the peg here if there was one
yield new_node
# find all legal moves going backwards
for pos in range(0, size-1):
new_node = list(node)
if ((node[pos] == 1) and (pos > 1) and (node[pos-2] == 0)):
new_node[pos] = 0 # we're moving now
new_node[pos-2] = 1 # this is where we're moving the peg
new_node[pos-1] = 0 # take out the peg here if there was one
yield new_node
Now if you know depth-first search, this seems like a GREAT generator to use when solving this puzzle. Or is it? (I think it is, maybe you can help come up with a more Pythonic way?)
Well, my recursive puzzle solver function that will use the generator isn't working, maybe you can help me out?
def goal(self, node):
pegs = 0
for pos in node:
if pos == 1:
pegs += 1
return (pegs == 1) # returns True if there is only 1 peg
def solve_board(dfs_obj, node):
if goal(node): # only 1 peg!
print node
return node
for new_node in succ(node):
print new_node
return solve_board(new_node)
if __name__ == "__main__":
solve_board([1, 1, 1, 1, 1, 0, 1, 1, 1, 1])
So basically I think my succ() function is doing the right thing (maybe it's not?), but my solve_board() recursion might be funky, because the board doesn't solve.
A:
Since you are allowed to jump over empty holes, you'll have to keep track of any nodes you have already visited. Otherwise you will have an infinite loop.
You also need to not shortcircuit the for loop unless you have found a goal
tested_nodes=set()
def solve_board(dfs_obj, node):
if goal(node): # only 1 peg!
print node
return node
for new_node in succ(node):
if tuple(new_node) not in tested_nodes:
tested_nodes.add(tuple(new_node))
print new_node
result = solve_board(new_node)
if result: # True if it's a goal, None otherwise
return result
You have the range wrong in your succ function too, you should not subtrace 1 from the size for the range. You could also rewrite it like this to remove one of the conditions from the if
def succ(self, node):
size = len(node)
# find all legal moves going forward
for pos in range(size-2):
new_node = list(node)
if ((node[pos] == 1) and (node[pos+2] == 0)):
new_node[pos] = 0 # we're moving now
new_node[pos+2] = 1 # this is where we're moving the peg to
new_node[pos+1] = 0 # take out the peg here if there was one
yield new_node
# find all legal moves going backwards
for pos in range(1,size):
new_node = list(node)
if ((node[pos] == 1) and (node[pos-2] == 0)):
new_node[pos] = 0 # we're moving now
new_node[pos-2] = 1 # this is where we're moving the peg
new_node[pos-1] = 0 # take out the peg here if there was one
yield new_node
Another way to write the succ funtion would be
def succ(self, node):
for i in range(len(node)-2):
j=i+3
if node[i:j]==[1,1,0]:
yield node[:i]+[0,0,1]+node[j:]
if node[i:j]==[0,1,1]:
yield node[:i]+[1,0,0]+node[j:]
if node[i:j]==[1,0,0]:
yield node[:i]+[0,0,1]+node[j:]
if node[i:j]==[0,0,1]:
yield node[:i]+[1,0,0]+node[j:]
This tunes the depth first slightly by preferring moves that remove a peg
A:
I haven't decyphered your succ() function, but assuming it works then the rest of the program indeed does depth-first search. I take it that the code doesn't terminate? If succ can return a state that was previously encountered then you might have an infinite decision tree and depth-first search could get stuck going down the infinite branch and miss the correct solution on another branch. In this case you need to use breadth-first search.
|
Depth-First search in Python
|
Okay so basically I'm trying to do a depth-first search for a mini-peg solitaire game. For those unfamiliar with the game it's pretty simple.
There's a board with 10 holes and 9 pegs, a peg is represented by a 1 and an empty spot by a 0. You can move a peg backwards or forwards two holes at a time (but you can only move to an empty hole), and if you jump over another peg in the process you take it out and it becomes a hole.
So here's what a game looks like:
[1, 1, 1, 1, 1, 0, 1, 1, 1, 1]
[1, 1, 1, 0, 0, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 0, 1, 1, 1, 1, 1]
[1, 0, 0, 1, 1, 0, 0, 1, 1, 1]
[1, 0, 0, 0, 0, 1, 0, 1, 1, 1]
[1, 0, 0, 0, 0, 1, 1, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1, 0, 1] #etc until only 1 peg left
So, I have a generator function here that finds all legal moves for a certain "node", or a game board:
def succ(self, node):
size = len(node)
# find all legal moves going forward
for pos in range(0, size-1):
new_node = list(node)
if ((node[pos] == 1) and (pos < (size - 2)) and (node[pos+2] == 0)):
new_node[pos] = 0 # we're moving now
new_node[pos+2] = 1 # this is where we're moving the peg to
new_node[pos+1] = 0 # take out the peg here if there was one
yield new_node
# find all legal moves going backwards
for pos in range(0, size-1):
new_node = list(node)
if ((node[pos] == 1) and (pos > 1) and (node[pos-2] == 0)):
new_node[pos] = 0 # we're moving now
new_node[pos-2] = 1 # this is where we're moving the peg
new_node[pos-1] = 0 # take out the peg here if there was one
yield new_node
Now if you know depth-first search, this seems like a GREAT generator to use when solving this puzzle. Or is it? (I think it is, maybe you can help come up with a more Pythonic way?)
Well, my recursive puzzle solver function that will use the generator isn't working, maybe you can help me out?
def goal(self, node):
pegs = 0
for pos in node:
if pos == 1:
pegs += 1
return (pegs == 1) # returns True if there is only 1 peg
def solve_board(dfs_obj, node):
if goal(node): # only 1 peg!
print node
return node
for new_node in succ(node):
print new_node
return solve_board(new_node)
if __name__ == "__main__":
solve_board([1, 1, 1, 1, 1, 0, 1, 1, 1, 1])
So basically I think my succ() function is doing the right thing (maybe it's not?), but my solve_board() recursion might be funky, because the board doesn't solve.
|
[
"Since you are allowed to jump over empty holes, you'll have to keep track of any nodes you have already visited. Otherwise you will have an infinite loop.\nYou also need to not shortcircuit the for loop unless you have found a goal\ntested_nodes=set()\ndef solve_board(dfs_obj, node):\n if goal(node): # only 1 peg!\n print node\n return node\n\n for new_node in succ(node):\n if tuple(new_node) not in tested_nodes:\n tested_nodes.add(tuple(new_node))\n print new_node\n result = solve_board(new_node)\n if result: # True if it's a goal, None otherwise\n return result\n\nYou have the range wrong in your succ function too, you should not subtrace 1 from the size for the range. You could also rewrite it like this to remove one of the conditions from the if\ndef succ(self, node):\n size = len(node)\n\n # find all legal moves going forward\n for pos in range(size-2):\n new_node = list(node)\n if ((node[pos] == 1) and (node[pos+2] == 0)):\n new_node[pos] = 0 # we're moving now\n new_node[pos+2] = 1 # this is where we're moving the peg to\n new_node[pos+1] = 0 # take out the peg here if there was one\n yield new_node\n\n # find all legal moves going backwards\n for pos in range(1,size):\n new_node = list(node)\n if ((node[pos] == 1) and (node[pos-2] == 0)):\n new_node[pos] = 0 # we're moving now\n new_node[pos-2] = 1 # this is where we're moving the peg\n new_node[pos-1] = 0 # take out the peg here if there was one\n yield new_node\n\nAnother way to write the succ funtion would be\ndef succ(self, node):\n for i in range(len(node)-2):\n j=i+3\n if node[i:j]==[1,1,0]:\n yield node[:i]+[0,0,1]+node[j:]\n if node[i:j]==[0,1,1]:\n yield node[:i]+[1,0,0]+node[j:]\n if node[i:j]==[1,0,0]:\n yield node[:i]+[0,0,1]+node[j:]\n if node[i:j]==[0,0,1]:\n yield node[:i]+[1,0,0]+node[j:]\n\nThis tunes the depth first slightly by preferring moves that remove a peg\n",
"I haven't decyphered your succ() function, but assuming it works then the rest of the program indeed does depth-first search. I take it that the code doesn't terminate? If succ can return a state that was previously encountered then you might have an infinite decision tree and depth-first search could get stuck going down the infinite branch and miss the correct solution on another branch. In this case you need to use breadth-first search.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002151354_python.txt
|
Q:
What to put for a commonName when making an OpenSSL key?
I have an application application framework that works in a peer-to-peer manner between unnamed hosts on a network. I want to have the traffic be encrypted, so I've implemented a setup with M2Crypto, but I've run into a snag. I have no idea what to put down for 'commonName' when creating the cert. It seems to want a domain name, but none of the computers running this will have one. I just put 'temphost' for the commonName, but apparently this an important parameter. I got this when trying to test it:
M2Crypto.SSL.Checker.WrongHost: Peer
certificate commonName does not match
host, expected 127.0.0.1, got temphost
Is there a way to generalize the commonName?
A:
In your use case the default host name checking is not appropriate. You might want to try just doing certificate fingerprint checking. First, get the fingerprints of each certificate (openssl x509 -fingerprint). Let's say you have peer A and peer B, with fingerprint A and fingerprint B, respectively.
On peer A side, you will make the following calls early on in your script:
from M2Crypto import SSL
SSL.Connection.clientPostConnectionCheck = SSL.Checker(peerCertHash='fingerprint B')
On peer B side you do the same, except use fingerprint A. Now the certificate checker will only check to make sure that the fingerprints match, and won't do further checks.
This approach does mean that it will override the post connection check for ALL SSL connections, so it is not suitable in all use cases. If you can control the creation of the SSL.Connection object, you could also call set_post_connection_check_callback() per instance, which would allow different checker to be used when needed.
A:
So based on your comment to my first answer I decided to offer another solution that might work for your case. Create your own CA cert and key. Then in your peers tell M2Crypto to accept only certificates that were signed by this CA (see this older stackoverflow question for APIs to use: What is the difference between M2Crypto's set_client_CA_list_from_file() and load_verify_info() and when would you use each?).
Then early on in your scripts do this:
from M2Crypto import SSL
SSL.Connection.clientPostConnectionCheck = None
or if you need to be able to make other kinds of SSL connections, see if you can control the creation of SSL.Connection objects and call their set_post_connection_check_callback() with suitable checker.
After this your peers should accept any other peer as long as the peer's certificate was signed with your CA only.
If you can think of any extra information you could verify in a post connection check, you could put that info in the certs (maybe in commonName) and write your own checker to use (instead of None above).
|
What to put for a commonName when making an OpenSSL key?
|
I have an application application framework that works in a peer-to-peer manner between unnamed hosts on a network. I want to have the traffic be encrypted, so I've implemented a setup with M2Crypto, but I've run into a snag. I have no idea what to put down for 'commonName' when creating the cert. It seems to want a domain name, but none of the computers running this will have one. I just put 'temphost' for the commonName, but apparently this an important parameter. I got this when trying to test it:
M2Crypto.SSL.Checker.WrongHost: Peer
certificate commonName does not match
host, expected 127.0.0.1, got temphost
Is there a way to generalize the commonName?
|
[
"In your use case the default host name checking is not appropriate. You might want to try just doing certificate fingerprint checking. First, get the fingerprints of each certificate (openssl x509 -fingerprint). Let's say you have peer A and peer B, with fingerprint A and fingerprint B, respectively.\nOn peer A side, you will make the following calls early on in your script:\nfrom M2Crypto import SSL\nSSL.Connection.clientPostConnectionCheck = SSL.Checker(peerCertHash='fingerprint B')\n\nOn peer B side you do the same, except use fingerprint A. Now the certificate checker will only check to make sure that the fingerprints match, and won't do further checks.\nThis approach does mean that it will override the post connection check for ALL SSL connections, so it is not suitable in all use cases. If you can control the creation of the SSL.Connection object, you could also call set_post_connection_check_callback() per instance, which would allow different checker to be used when needed.\n",
"So based on your comment to my first answer I decided to offer another solution that might work for your case. Create your own CA cert and key. Then in your peers tell M2Crypto to accept only certificates that were signed by this CA (see this older stackoverflow question for APIs to use: What is the difference between M2Crypto's set_client_CA_list_from_file() and load_verify_info() and when would you use each?).\nThen early on in your scripts do this:\nfrom M2Crypto import SSL\nSSL.Connection.clientPostConnectionCheck = None\n\nor if you need to be able to make other kinds of SSL connections, see if you can control the creation of SSL.Connection objects and call their set_post_connection_check_callback() with suitable checker.\nAfter this your peers should accept any other peer as long as the peer's certificate was signed with your CA only.\nIf you can think of any extra information you could verify in a post connection check, you could put that info in the certs (maybe in commonName) and write your own checker to use (instead of None above).\n"
] |
[
1,
1
] |
[] |
[] |
[
"m2crypto",
"python",
"ssl"
] |
stackoverflow_0002150048_m2crypto_python_ssl.txt
|
Q:
How can I make Sphinx's inheritance_diagram readable?
Similar to this chap's post, I'm seeing Sphinx generate unreadable graphviz output:
How can I generate readable output?
Nothing happens if I add -Gfontsize=140
If I tell it to use neato instead of dot it produces readable output, but the graphs aren't tree-like.
A:
I figured out the answer from this thread. In the graphviz.py code, they have a default value for the size of the graph at 8.0x12.0. If you want to allow Graphviz to determine the size you need to put this in conf.py so the Sphinx graphviz extension uses your empty string instead of its default:
inheritance_graph_attrs = dict(size='""')
Also, if you're hitting this issue then the graph may be too wide once you allow the size to be determined by Graphviz. You'll additionally want attribute rankdir="TB" so the tree goes from top to bottom instead of left to right:
inheritance_graph_attrs = dict(rankdir="TB", size='""')
|
How can I make Sphinx's inheritance_diagram readable?
|
Similar to this chap's post, I'm seeing Sphinx generate unreadable graphviz output:
How can I generate readable output?
Nothing happens if I add -Gfontsize=140
If I tell it to use neato instead of dot it produces readable output, but the graphs aren't tree-like.
|
[
"I figured out the answer from this thread. In the graphviz.py code, they have a default value for the size of the graph at 8.0x12.0. If you want to allow Graphviz to determine the size you need to put this in conf.py so the Sphinx graphviz extension uses your empty string instead of its default:\ninheritance_graph_attrs = dict(size='\"\"')\n\nAlso, if you're hitting this issue then the graph may be too wide once you allow the size to be determined by Graphviz. You'll additionally want attribute rankdir=\"TB\" so the tree goes from top to bottom instead of left to right:\ninheritance_graph_attrs = dict(rankdir=\"TB\", size='\"\"')\n\n"
] |
[
7
] |
[] |
[] |
[
"graphviz",
"python",
"python_sphinx"
] |
stackoverflow_0002151711_graphviz_python_python_sphinx.txt
|
Q:
Approaching refactoring
I have a very data-centric application, written in Python / PyQt. I'm planning
to do some refactoring to really separate the UI from the core, mainly because
there aren't any real tests in place yet, and that clearly has to change.
There is some separation already, and I think I've done quite a few things the right way, but it's far from perfect. Two examples, to show you what kind of things are bothering me:
When the user right-clicks on the representation of a data object, the context menu
that pops up is created by the data object, although this data object (essentially the
ORM representation of a database row) should clearly have nothing to do with the UI.
When something is written to the database, but the write fails (e.g. because the database record is
locked by a different user), the classical "retry / abort" message box is presented to the user. This
dialog is created by the data provider*, although the provider should obviously not have any UI functionality.
Clearly, the provider can instead raise an exception or otherwise indicate failure, and the UI can catch
that and act accordingly.
* that's the word I use for the object that basically represents a database table and mediates
between its data objects and the database engine; I'm not sure whether that's what is usually called
a "provider"
I don't have experience with testing, so I don't easily "feel" testability problems or the like, but before I get into that, some reorganizing has to be done.
There is no complicated business logic involved (it's mainly just CRUD, yes, even without the D), and this would be much more reorganizing than rewriting, so I'm not really concerned about introducing regression bugs like discussed in this question.
My plan is to start refactoring with the idea in mind that the UI part could easily be ripped out to be
replaced by, say, a web frontend or a text-based interface instead of the Qt interface. On the other hand,
Qt itself would still be used by the core, because the signal/slot mechanism is used in quite a few places,
e.g. data objects emit a changed signal to indicate, well, you know what.
So, my question: Is that a feasible approach to increase testability and maintainability? Any other remarks, especially with Python in mind?
A:
If you have not done so already, read "Working Effectively with Legacy Code" by Michael Feathers - it deals with exactly this sort of situation, and offers a wealth of techniques for dealing with it.
One key point he makes is to try and get some tests in place before refactoring. Since it is not suitable for unit tests, try to get some end-to-end tests in place. I believe that Qt has its own testing framework for driving the GUI, so add tests that manipulate the GUI against a known database and verifies the result. As you clean up the code you can replace or augment the end-to-end tests with unit tests.
A:
If you want to extract all GUI parts of your application from all the other parts in order to tests all your application, you should use the Model-View-Presenter: You can find some explanation here and here.
With this model, all your services of your application uses the presenters whereas only the user can interact directly with the views (GUI parts). The presenters are managing the views from the application. You will have a GUI part independent from your application in the case you want to modify the GUI framework. The only thing you will have to modify are the presenters and the views themselves.
For the GUI tests you want, you just have to write unit tests for presenters. If you want to test GUI uses, you need to create integration tests.
Hope that helps!
A:
I have done refactoring for large legacy code aiming UI/backend separation before. It's fun and rewarding.
/praise ;)
Whatever pattern one calls it or be it part of MVC it's invaluable to have a very clear API layer. If possible you may route all the UI requests through a dispatcher that would offer you greater control over UI<->Logic communication eg. implementing caching, auth etc.
To visualize:
[QT Frontend]
[CLIs] <=======> [Dispatcher] <=> [API] <==> [Core/Model]
[SOAP/XMPRPC/Json]
[API Test Suite]
This way
it's easier to add test suite to test your APIs.
Also it makes adding more UIs uniform way and easier.
API Documentation: Say if you want to document and expose APIs though some RPC interface, it' easier to generate API documentation.
If somebody don't agree with importance of API documentation can always look at Twitter API and it's success.
You can quickly import API layer to python shell and play with it
API designing can happen well before you start coding for API layer. Depending on the application you might want to take help of packages like zinterfaces.
This is general approach I take even while writing very small apps and it has never failed for me.
Do look at
http://www.feld.com/wp/archives/2008/05/no-api-you-suck.html
One distinct advantage of this approach is after you have API layer and new UI, you can now go back to legacy code and fix/refactor it in perhaps smaller steps.
Other suggestions is to have your testing suite ready. See interstar's advice at What are the first tasks for implementing Unit Testing in Brownfield Applications? .
A:
One point, not mentioned so far and not really answering the question, but very important: Wherever possible you should put in the test now, before you start refactoring. The main point of test is that to detect if you break something.
Refactoring is something where it is really valuable to exactly see where the effect of some operation changed and where the same call produces a different result. That's what all this testing is about: You want to see if you break something, you want to see all the unintentional changes.
So, make tests now for all the parts that still should produce the same results after refactoring. Tests aren't for perfect code that will stay the same forever, tests are for the code that needs to change, the code that needs to be modified, the code that will be refactored. Tests are there to make sure your refactoring really does what you intend it to do.
|
Approaching refactoring
|
I have a very data-centric application, written in Python / PyQt. I'm planning
to do some refactoring to really separate the UI from the core, mainly because
there aren't any real tests in place yet, and that clearly has to change.
There is some separation already, and I think I've done quite a few things the right way, but it's far from perfect. Two examples, to show you what kind of things are bothering me:
When the user right-clicks on the representation of a data object, the context menu
that pops up is created by the data object, although this data object (essentially the
ORM representation of a database row) should clearly have nothing to do with the UI.
When something is written to the database, but the write fails (e.g. because the database record is
locked by a different user), the classical "retry / abort" message box is presented to the user. This
dialog is created by the data provider*, although the provider should obviously not have any UI functionality.
Clearly, the provider can instead raise an exception or otherwise indicate failure, and the UI can catch
that and act accordingly.
* that's the word I use for the object that basically represents a database table and mediates
between its data objects and the database engine; I'm not sure whether that's what is usually called
a "provider"
I don't have experience with testing, so I don't easily "feel" testability problems or the like, but before I get into that, some reorganizing has to be done.
There is no complicated business logic involved (it's mainly just CRUD, yes, even without the D), and this would be much more reorganizing than rewriting, so I'm not really concerned about introducing regression bugs like discussed in this question.
My plan is to start refactoring with the idea in mind that the UI part could easily be ripped out to be
replaced by, say, a web frontend or a text-based interface instead of the Qt interface. On the other hand,
Qt itself would still be used by the core, because the signal/slot mechanism is used in quite a few places,
e.g. data objects emit a changed signal to indicate, well, you know what.
So, my question: Is that a feasible approach to increase testability and maintainability? Any other remarks, especially with Python in mind?
|
[
"If you have not done so already, read \"Working Effectively with Legacy Code\" by Michael Feathers - it deals with exactly this sort of situation, and offers a wealth of techniques for dealing with it. \nOne key point he makes is to try and get some tests in place before refactoring. Since it is not suitable for unit tests, try to get some end-to-end tests in place. I believe that Qt has its own testing framework for driving the GUI, so add tests that manipulate the GUI against a known database and verifies the result. As you clean up the code you can replace or augment the end-to-end tests with unit tests.\n",
"If you want to extract all GUI parts of your application from all the other parts in order to tests all your application, you should use the Model-View-Presenter: You can find some explanation here and here.\nWith this model, all your services of your application uses the presenters whereas only the user can interact directly with the views (GUI parts). The presenters are managing the views from the application. You will have a GUI part independent from your application in the case you want to modify the GUI framework. The only thing you will have to modify are the presenters and the views themselves.\nFor the GUI tests you want, you just have to write unit tests for presenters. If you want to test GUI uses, you need to create integration tests.\nHope that helps!\n",
"I have done refactoring for large legacy code aiming UI/backend separation before. It's fun and rewarding.\n/praise ;)\nWhatever pattern one calls it or be it part of MVC it's invaluable to have a very clear API layer. If possible you may route all the UI requests through a dispatcher that would offer you greater control over UI<->Logic communication eg. implementing caching, auth etc.\nTo visualize:\n[QT Frontend]\n[CLIs] <=======> [Dispatcher] <=> [API] <==> [Core/Model]\n[SOAP/XMPRPC/Json]\n[API Test Suite]\n\nThis way\n\nit's easier to add test suite to test your APIs.\nAlso it makes adding more UIs uniform way and easier.\nAPI Documentation: Say if you want to document and expose APIs though some RPC interface, it' easier to generate API documentation.\nIf somebody don't agree with importance of API documentation can always look at Twitter API and it's success.\nYou can quickly import API layer to python shell and play with it\n\nAPI designing can happen well before you start coding for API layer. Depending on the application you might want to take help of packages like zinterfaces.\nThis is general approach I take even while writing very small apps and it has never failed for me. \nDo look at\n\nhttp://www.feld.com/wp/archives/2008/05/no-api-you-suck.html\n\nOne distinct advantage of this approach is after you have API layer and new UI, you can now go back to legacy code and fix/refactor it in perhaps smaller steps.\nOther suggestions is to have your testing suite ready. See interstar's advice at What are the first tasks for implementing Unit Testing in Brownfield Applications? .\n",
"One point, not mentioned so far and not really answering the question, but very important: Wherever possible you should put in the test now, before you start refactoring. The main point of test is that to detect if you break something.\nRefactoring is something where it is really valuable to exactly see where the effect of some operation changed and where the same call produces a different result. That's what all this testing is about: You want to see if you break something, you want to see all the unintentional changes.\nSo, make tests now for all the parts that still should produce the same results after refactoring. Tests aren't for perfect code that will stay the same forever, tests are for the code that needs to change, the code that needs to be modified, the code that will be refactored. Tests are there to make sure your refactoring really does what you intend it to do.\n"
] |
[
7,
2,
1,
1
] |
[] |
[] |
[
"python",
"qt",
"refactoring",
"separation_of_concerns",
"unit_testing"
] |
stackoverflow_0002081745_python_qt_refactoring_separation_of_concerns_unit_testing.txt
|
Q:
possible in sqlalchemy to join table based on a column value?
I am trying to create a table to hold user actions on my web app. Take a simple case where a user adds a new story, and comments on it. This will add two entries to the user_action table. In the user_action table I would like to store the module name associated with each action and the items id. In this cause I would store the modules as News, and Comment (and the ids of the two items in the modules). Is something like this possible:
SELECT * FROM user_action JOIN user_action.module m ON m.id==user_action.item_id
WHERE user_action.user_id = 1
Thanks
A:
What you want are polymorphic models. Read SQLAlchemy docs about this topic or Google them.
|
possible in sqlalchemy to join table based on a column value?
|
I am trying to create a table to hold user actions on my web app. Take a simple case where a user adds a new story, and comments on it. This will add two entries to the user_action table. In the user_action table I would like to store the module name associated with each action and the items id. In this cause I would store the modules as News, and Comment (and the ids of the two items in the modules). Is something like this possible:
SELECT * FROM user_action JOIN user_action.module m ON m.id==user_action.item_id
WHERE user_action.user_id = 1
Thanks
|
[
"What you want are polymorphic models. Read SQLAlchemy docs about this topic or Google them.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0002149659_python_sqlalchemy.txt
|
Q:
Making a Python/GTK CheckMenuItem, when clicked, not close the menu
Using Python and PyGTK I've got a GtkMenu with various GtkCheckMenuItems in it. When the user clicks one of the checkboxes the menu closes. I'd like for the user to be able to check a series of checkboxes without the menu closing each time.
I've looked at using the activate callback to show the menu but this doesn't seem to work. Any suggestions?
A:
I see the problem here, the "activate" signal does not allow you to return a boolean as to whether you wish the signal to propagate onwards. It sounds like you may need to poke around the gtk.CheckMenuItem internals, fire a signal that "reopens" the menu at the current position to be processed immediately after the "activate" signal has closed down the menu, or try the mailing list.
It's probably worth noting this is more of a GTK+ question than a PyGTK, as I believe the PyGTK API reflects the GTK+ one closely on this issue.
|
Making a Python/GTK CheckMenuItem, when clicked, not close the menu
|
Using Python and PyGTK I've got a GtkMenu with various GtkCheckMenuItems in it. When the user clicks one of the checkboxes the menu closes. I'd like for the user to be able to check a series of checkboxes without the menu closing each time.
I've looked at using the activate callback to show the menu but this doesn't seem to work. Any suggestions?
|
[
"I see the problem here, the \"activate\" signal does not allow you to return a boolean as to whether you wish the signal to propagate onwards. It sounds like you may need to poke around the gtk.CheckMenuItem internals, fire a signal that \"reopens\" the menu at the current position to be processed immediately after the \"activate\" signal has closed down the menu, or try the mailing list.\nIt's probably worth noting this is more of a GTK+ question than a PyGTK, as I believe the PyGTK API reflects the GTK+ one closely on this issue.\n"
] |
[
2
] |
[
"Try digging into source and it's documentation. I have found this to be the easiest way and best shortcut.\n"
] |
[
-1
] |
[
"gtk",
"menu",
"pygtk",
"python"
] |
stackoverflow_0002150899_gtk_menu_pygtk_python.txt
|
Q:
Deleting erroneous ReferenceProperty properties in AppEngine
Most of the time, the errors you get from your model properties will happen when you're saving data. For instance, if you try saving a string as an IntegerProperty, that will result in an error.
The one exception (no pun intended) is ReferenceProperty. If you have lots of references and you're not completely careful about leaving in bad references, it's common to be greeted with an error like "TemplateSyntaxError: Caught an exception while rendering: ReferenceProperty failed to be resolved".
And this is if there's only one bad reference in the view. D'oh.
I could write a try/except block to try to access all the reference properties and delete them if an exception is raised, but this functionality could surely be useful to many other developers if there was a more generic method than the one I'd be capable of writing. I imagine it would take a list of model types and try to access each reference property of each entity in each model, setting the property to None if an exception is raised.
I'll see if I can do this myself, but it would definitely help to have some suggestions/snippets to get me started.
A:
I'm having similar difficulties for my project. As I code the beta version of my application, I do create a lot of dead link and its trully a pain to untangle things afterward. Ideally, this tool would have to also report of the offending reference so that you could pin-point problems in the code.
A:
You could extend and customize ReferenceProperty to not throw this exception, but then it'll need to return something - presumably None - in which case your template will simply throw an exception when it attempts to access properties on the returned object.
A better approach is to fetch the referenceproperty and check it's valid before rendering the template. ReferenceProperties cache their references, so prefetching won't result in extra datastore calls.
A:
That exception is actually a bug that's been waiting to be fixed for a while (see http://code.google.com/p/googleappengine/issues/detail?id=426). Ideally you should be able to test whether the reference is valid like this(from app engine documentation):
obj1 = db.get(obj2.reference)
if not obj1:
# Referenced entity was deleted.
|
Deleting erroneous ReferenceProperty properties in AppEngine
|
Most of the time, the errors you get from your model properties will happen when you're saving data. For instance, if you try saving a string as an IntegerProperty, that will result in an error.
The one exception (no pun intended) is ReferenceProperty. If you have lots of references and you're not completely careful about leaving in bad references, it's common to be greeted with an error like "TemplateSyntaxError: Caught an exception while rendering: ReferenceProperty failed to be resolved".
And this is if there's only one bad reference in the view. D'oh.
I could write a try/except block to try to access all the reference properties and delete them if an exception is raised, but this functionality could surely be useful to many other developers if there was a more generic method than the one I'd be capable of writing. I imagine it would take a list of model types and try to access each reference property of each entity in each model, setting the property to None if an exception is raised.
I'll see if I can do this myself, but it would definitely help to have some suggestions/snippets to get me started.
|
[
"I'm having similar difficulties for my project. As I code the beta version of my application, I do create a lot of dead link and its trully a pain to untangle things afterward. Ideally, this tool would have to also report of the offending reference so that you could pin-point problems in the code.\n",
"You could extend and customize ReferenceProperty to not throw this exception, but then it'll need to return something - presumably None - in which case your template will simply throw an exception when it attempts to access properties on the returned object.\nA better approach is to fetch the referenceproperty and check it's valid before rendering the template. ReferenceProperties cache their references, so prefetching won't result in extra datastore calls.\n",
"That exception is actually a bug that's been waiting to be fixed for a while (see http://code.google.com/p/googleappengine/issues/detail?id=426). Ideally you should be able to test whether the reference is valid like this(from app engine documentation): \nobj1 = db.get(obj2.reference)\n\nif not obj1:\n # Referenced entity was deleted.\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"google_app_engine",
"model",
"python",
"referenceproperty"
] |
stackoverflow_0000367029_google_app_engine_model_python_referenceproperty.txt
|
Q:
Returning an instance of a class from a file in python
In my program I have a package filled with various .py files each containing a class definition. I want to make a list where each entry is an instance of one of those classes. In addition, my program doesn't know how many files are in the package or what the files or classes are called, so I can't just import each file. Ideally, I should be able to modify the contents of the package (take out files, put new ones in, etc.) without having to rewrite other parts of the program. Is there a way to do this?
Originally, I had a 'if __name__ == '__main__': return foo()' line in each file and tried to append to the list using execfile(), but obviously this doesn't work. Any ideas?
Sorry if this is kinda vague. I'll try to clarify if needed. I'm using Python 2.5.4.
EDIT:
My program is a random character generator for Dungeons and Dragons. I made a package for every major data type the program needs. I have a package for Classes, Races, Items, etc. and when making a character, my program makes a list of each data type that it can sort through when making a character. For example, when equipping a character, the program can look at the Weapon list and filter out all the weapons that are unsuitable for that character and then randomly choose from the ones that remain.
I don't want to specify file names because I would like the ability to easily add to this program later. If later on down the road I wanted to add more weapon types to the program, I could just write a few new class descriptions and drop them in the Weapons package, and the program could use them without me needing to edit any other code.
A:
This sounds like a bit of a bad design. It would probably be better if you elaborate on the problem and we can help you to solve it some other way. However, what you want isn't hard:
import types
import my_package
my_package_members = [getattr(my_package, i) for i in dir(my_package)]
my_modules = [i for i in my_package_members if type(i) == types.ModuleType]
instances = []
for my_module in my_modules:
my_module_members = [getattr(my_module, i) for i in dir(my_module)]
my_classes = [i for i in my_module_members
if type(i) in (types.TypeType, types.ClassType)]
for my_class in my_classes:
instances.append(my_class())
EDIT: Simplified the code a bit.
A:
To acheive this you are going to need to do the following things:
Have your code enumerate the source files containing your code.
For each source file, import the code specified in the file into a new module.
For each module, locate all the classes contained, instantiate each one and add it to your final list.
To take each part in turn:
To enumerate the source files, use os.walk and os.path to find the files and build full paths to the source.
To import code from a given source file dynamically, you can do execfile(my_file) in my_dict where my_file is the full path to your source file and my_dict is a dictionary to return the resulting code in (any classes declared in the source file would become members of this dict for example). Note you only need to use this method if the files you are importing are not part of a valid python module/package hierarchy (with an init.py file in the package) - if they are you can use import() instead.
To enumerate the classes declared in a given module you could use inspect.getmembers().
A:
If you're willing to do a bit more work, you can use pkg_resource's entry points to advertise and discover the relevant classes. The Fedora Account System uses this to provide plugin functionality.
A:
Assuming, first, that all your modules exist as .py files in the package's directory:
import inspect, glob, os, sys
def thelistyouwant(pathtothepackage):
sys.path.insert(0, pathtothepackage)
result = []
for fn in glob.glob(os.path.join(pathtothepackage, '*.py')):
if fn.startswith('_'): continue # no __init__ or other private modules
m = __import__(fn[:-3])
classes = inspect.getmembers(m, inspect.isclass)
if len(classes) != 1:
print>>sys.stderr, "Skipping %s (%d != 1 classes!)" % (fn, len(classes))
continue
n, c = classes[0]
try:
result.append(c())
except TypeError:
print>>sys.stderr, "Skipping %s, can't build a %s()" % (fn, n)
del sys.path[0]
return result
Further assumptions: each module should have exactly 1 class (otherwise it's skipped with a warning) instantiable without arguments (ditto ditto); you don't want to look at __init__.py (if any; actually this code does not require the path to be an actual package, any directory will do, so __init__.py may or may not be present) nor any module whose name starts with an underscore ("private" modules of the package).
|
Returning an instance of a class from a file in python
|
In my program I have a package filled with various .py files each containing a class definition. I want to make a list where each entry is an instance of one of those classes. In addition, my program doesn't know how many files are in the package or what the files or classes are called, so I can't just import each file. Ideally, I should be able to modify the contents of the package (take out files, put new ones in, etc.) without having to rewrite other parts of the program. Is there a way to do this?
Originally, I had a 'if __name__ == '__main__': return foo()' line in each file and tried to append to the list using execfile(), but obviously this doesn't work. Any ideas?
Sorry if this is kinda vague. I'll try to clarify if needed. I'm using Python 2.5.4.
EDIT:
My program is a random character generator for Dungeons and Dragons. I made a package for every major data type the program needs. I have a package for Classes, Races, Items, etc. and when making a character, my program makes a list of each data type that it can sort through when making a character. For example, when equipping a character, the program can look at the Weapon list and filter out all the weapons that are unsuitable for that character and then randomly choose from the ones that remain.
I don't want to specify file names because I would like the ability to easily add to this program later. If later on down the road I wanted to add more weapon types to the program, I could just write a few new class descriptions and drop them in the Weapons package, and the program could use them without me needing to edit any other code.
|
[
"This sounds like a bit of a bad design. It would probably be better if you elaborate on the problem and we can help you to solve it some other way. However, what you want isn't hard:\nimport types\nimport my_package\n\nmy_package_members = [getattr(my_package, i) for i in dir(my_package)]\nmy_modules = [i for i in my_package_members if type(i) == types.ModuleType]\n\ninstances = []\n\nfor my_module in my_modules:\n my_module_members = [getattr(my_module, i) for i in dir(my_module)]\n my_classes = [i for i in my_module_members\n if type(i) in (types.TypeType, types.ClassType)]\n for my_class in my_classes:\n instances.append(my_class())\n\nEDIT: Simplified the code a bit.\n",
"To acheive this you are going to need to do the following things:\n\nHave your code enumerate the source files containing your code.\nFor each source file, import the code specified in the file into a new module.\nFor each module, locate all the classes contained, instantiate each one and add it to your final list.\n\nTo take each part in turn:\n\nTo enumerate the source files, use os.walk and os.path to find the files and build full paths to the source.\nTo import code from a given source file dynamically, you can do execfile(my_file) in my_dict where my_file is the full path to your source file and my_dict is a dictionary to return the resulting code in (any classes declared in the source file would become members of this dict for example). Note you only need to use this method if the files you are importing are not part of a valid python module/package hierarchy (with an init.py file in the package) - if they are you can use import() instead.\nTo enumerate the classes declared in a given module you could use inspect.getmembers().\n\n",
"If you're willing to do a bit more work, you can use pkg_resource's entry points to advertise and discover the relevant classes. The Fedora Account System uses this to provide plugin functionality.\n",
"Assuming, first, that all your modules exist as .py files in the package's directory:\nimport inspect, glob, os, sys\n\ndef thelistyouwant(pathtothepackage):\n sys.path.insert(0, pathtothepackage)\n result = []\n for fn in glob.glob(os.path.join(pathtothepackage, '*.py')):\n if fn.startswith('_'): continue # no __init__ or other private modules\n m = __import__(fn[:-3])\n classes = inspect.getmembers(m, inspect.isclass)\n if len(classes) != 1:\n print>>sys.stderr, \"Skipping %s (%d != 1 classes!)\" % (fn, len(classes))\n continue\n n, c = classes[0]\n try:\n result.append(c())\n except TypeError:\n print>>sys.stderr, \"Skipping %s, can't build a %s()\" % (fn, n)\n\n del sys.path[0] \n return result\n\nFurther assumptions: each module should have exactly 1 class (otherwise it's skipped with a warning) instantiable without arguments (ditto ditto); you don't want to look at __init__.py (if any; actually this code does not require the path to be an actual package, any directory will do, so __init__.py may or may not be present) nor any module whose name starts with an underscore (\"private\" modules of the package).\n"
] |
[
2,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002151499_python.txt
|
Q:
How can I run Python code on a windows system?
I am used to using PHP and it is easy to set up, I can just run an exe package like Xampp and have apache and PHP running in 5 minutes on my windows system. Is there something similar to Python?
A:
Unlike PHP, Python's primary purpose is a general-purpose tool for running on the desktop/server, not necessarily as a web application. It has bindings to many powerful GUI toolkits (Qt and wx are two examples of free and popular toolkits that work great on Windows), and so on. Therefore you just download it (either from python.org or from activestate), install it, and run it. That's it.
That said, Python is actually great for web apps too. See the Django tutorial for running a simple web-app on your PC in just a few minutes. Python actually comes with a simple web-server built-in, and it supports SQLite out of the box as well, so you can have a fully functional DB-backed web-application running without actually installing anything else. Naturally, if you need to use tools like MySQL and Apache, these are easy to connect to Python on the desktop too. Just start with that Django tutorial and everything will be clear.
A:
Yes, you can find python from http://python.org
and If you like to make executable files from .py source file you may use py2exe
A:
You don't say in your question what you are going to use Python for, so most answers above are completely correct in pointing out that you install Python by downloading it from Python.org. But you seem to expect more. Is it correct to assume you are going to use it to do web development?
In that case, prepare for a shock, because Python doesn't do things like PHP does at all. You want to use a web framework. There are loads of them for Python. Which on to use depends both on what you are going to do, and your personal taste.
The only "Download as one file and install to run" web system I know of that's based on Python is Plone. And Plone is great, but it's not a webframework, it's a content management system. But hey, maybe that's what you want? :-)
The other frameworks are usually easy to install as well.
(In the long run: If you are going to do web development, you'll be happier with something Unix based. Just saying.)
A:
Download python installer and run python.
A:
Nope no easy way out for you yet, Python is obviously not popular enough in Web dev. You should install mod_python and django. There are some nice step here.
A:
Here's my opinionated answer:
Download and install ActivePython
Open Command Prompt and type pypm install django
Follow the Django tutorial
Note that Django does not necessarily require a webserver like Apache, as it already includes one for development purposes. Nor do you necessarily have to install MySQL as Python already includes SQLite which is supported by Django.
|
How can I run Python code on a windows system?
|
I am used to using PHP and it is easy to set up, I can just run an exe package like Xampp and have apache and PHP running in 5 minutes on my windows system. Is there something similar to Python?
|
[
"Unlike PHP, Python's primary purpose is a general-purpose tool for running on the desktop/server, not necessarily as a web application. It has bindings to many powerful GUI toolkits (Qt and wx are two examples of free and popular toolkits that work great on Windows), and so on. Therefore you just download it (either from python.org or from activestate), install it, and run it. That's it.\nThat said, Python is actually great for web apps too. See the Django tutorial for running a simple web-app on your PC in just a few minutes. Python actually comes with a simple web-server built-in, and it supports SQLite out of the box as well, so you can have a fully functional DB-backed web-application running without actually installing anything else. Naturally, if you need to use tools like MySQL and Apache, these are easy to connect to Python on the desktop too. Just start with that Django tutorial and everything will be clear.\n",
"Yes, you can find python from http://python.org\nand If you like to make executable files from .py source file you may use py2exe\n",
"You don't say in your question what you are going to use Python for, so most answers above are completely correct in pointing out that you install Python by downloading it from Python.org. But you seem to expect more. Is it correct to assume you are going to use it to do web development?\nIn that case, prepare for a shock, because Python doesn't do things like PHP does at all. You want to use a web framework. There are loads of them for Python. Which on to use depends both on what you are going to do, and your personal taste.\nThe only \"Download as one file and install to run\" web system I know of that's based on Python is Plone. And Plone is great, but it's not a webframework, it's a content management system. But hey, maybe that's what you want? :-)\nThe other frameworks are usually easy to install as well. \n(In the long run: If you are going to do web development, you'll be happier with something Unix based. Just saying.)\n",
"Download python installer and run python.\n",
"Nope no easy way out for you yet, Python is obviously not popular enough in Web dev. You should install mod_python and django. There are some nice step here.\n",
"Here's my opinionated answer:\n\nDownload and install ActivePython\nOpen Command Prompt and type pypm install django\nFollow the Django tutorial\n\nNote that Django does not necessarily require a webserver like Apache, as it already includes one for development purposes. Nor do you necessarily have to install MySQL as Python already includes SQLite which is supported by Django.\n"
] |
[
6,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"python",
"windows"
] |
stackoverflow_0002145232_python_windows.txt
|
Q:
Running a Django test server under twisted web
As I'm writing an application which uses twisted web for serving async requests and Django for normal content delivery, I thought it would have been nice to have both run under the same twisted reactor through the WSGI interface of Django.
I also wanted to test my app using the nice test server facility that Django offers. At first I simply created the test db and fired the WSGIHandler under the reactor but this didn't work as the WSGIHandler doesn't see the test db created during the initialization.
Hence, I decided to write a work around and have the db created and fixtures loaded on the first request, which is fine for a test server. Here's the (stripped down) script I'm using:
import os, sys
import django.core.handlers.wsgi
from django.core.management import call_command
from django.db import connection
from twisted.web.wsgi import WSGIResource
from twisted.internet import reactor
from twisted.web.server import Site
sys.path.append('/path/to/myapp')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
_app = django.core.handlers.wsgi.WSGIHandler()
initialized = False
fixtures = (...) # Put your fixtures path here
def app(e,sr):
global initialized
if not initialized:
connection.creation.create_test_db(verbosity=1)
call_command('loaddata', *fixtures, verbosity=1)
initialized = True
return _app(e,sr)
res = WSGIResource(reactor, reactor.getThreadPool(), app)
factory = Site(res)
reactor.listenTCP(8888, factory)
reactor.run()
I know this is a bit of a hack so if you've a better solution please report it here.
Thanks.
A:
This might be exactly what you are looking for: http://github.com/clemesha/twisted-wsgi-django
|
Running a Django test server under twisted web
|
As I'm writing an application which uses twisted web for serving async requests and Django for normal content delivery, I thought it would have been nice to have both run under the same twisted reactor through the WSGI interface of Django.
I also wanted to test my app using the nice test server facility that Django offers. At first I simply created the test db and fired the WSGIHandler under the reactor but this didn't work as the WSGIHandler doesn't see the test db created during the initialization.
Hence, I decided to write a work around and have the db created and fixtures loaded on the first request, which is fine for a test server. Here's the (stripped down) script I'm using:
import os, sys
import django.core.handlers.wsgi
from django.core.management import call_command
from django.db import connection
from twisted.web.wsgi import WSGIResource
from twisted.internet import reactor
from twisted.web.server import Site
sys.path.append('/path/to/myapp')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
_app = django.core.handlers.wsgi.WSGIHandler()
initialized = False
fixtures = (...) # Put your fixtures path here
def app(e,sr):
global initialized
if not initialized:
connection.creation.create_test_db(verbosity=1)
call_command('loaddata', *fixtures, verbosity=1)
initialized = True
return _app(e,sr)
res = WSGIResource(reactor, reactor.getThreadPool(), app)
factory = Site(res)
reactor.listenTCP(8888, factory)
reactor.run()
I know this is a bit of a hack so if you've a better solution please report it here.
Thanks.
|
[
"This might be exactly what you are looking for: http://github.com/clemesha/twisted-wsgi-django\n"
] |
[
2
] |
[] |
[] |
[
"asynchronous",
"django",
"integration",
"python",
"twisted"
] |
stackoverflow_0002148890_asynchronous_django_integration_python_twisted.txt
|
Q:
Python: Obtain edge end points of the graph
I need the edge end points from a graph. I have installed networkx. I have some idea how to proceed.
networkx.Graph.edges_iter() returns all the edges in the graph
[e for e in G.edges_iter()]
[(0, 1), (1, 2), (2, 3)]
What I want is a list [0,1,1,2,2,3]
How do I get this from the above data?
A:
>>> import itertools
>>> list(itertools.chain(*[(0, 1), (1, 2), (2, 3)]))
[0, 1, 1, 2, 2, 3]
You may not need list(...) because its already iterable.
And you may also try itertools.chain(G.edges_iter()) directly
A:
edgeList = []
for (a,b) in G.edges_iter():
edgeList.append(a)
edgeList.append(b)
|
Python: Obtain edge end points of the graph
|
I need the edge end points from a graph. I have installed networkx. I have some idea how to proceed.
networkx.Graph.edges_iter() returns all the edges in the graph
[e for e in G.edges_iter()]
[(0, 1), (1, 2), (2, 3)]
What I want is a list [0,1,1,2,2,3]
How do I get this from the above data?
|
[
">>> import itertools\n>>> list(itertools.chain(*[(0, 1), (1, 2), (2, 3)]))\n[0, 1, 1, 2, 2, 3]\n\nYou may not need list(...) because its already iterable.\nAnd you may also try itertools.chain(G.edges_iter()) directly\n",
"edgeList = []\nfor (a,b) in G.edges_iter():\n edgeList.append(a)\n edgeList.append(b)\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002152325_python.txt
|
Q:
Displaying dictionary value in django template
All,
I have the following in my views.py
def getgradeform(request):
id1=request.user.get_pf().id
sc=Sc.objects.filter(id=id1)
logging.debug(sc)
logging.debug("++++")
dict={}
dict.update({'sc': sc})
return render_to_response('content/add.html',dict)
Logging.debug gives an output as [<sc: Robert>]
My question is that how do i display Robert in the template .
I have tried the following in the template:<input type ="text" value={{sc}}/> //This gives me the dictionary itself
<input type ="text" value={{dict.sc}}/> //This also doesnt work.
Thanks......
A:
If you want any value in a dictionary, you have to do it on the way
dict.key
(On python you'll write it as dict['key'])
So, to present the value stored with key 'name'
{{ sc.name }}
Anyway, I think this is not you're case. I think you're not seeing a dictionary, but an object defined from models (as is a entry on the database).
You're storing in dict (don't call that value as dict , you're masking a keyword) a key 'sc' with value variable sc, which is returned from a model. I'm having to guess, because I don't know how this model is. Maybe 'Robert' is stored in the attribute name, id or something similar?
You need to show then the proper attribute, something like
{{ sc.name }}
{{ sc.id }}
|
Displaying dictionary value in django template
|
All,
I have the following in my views.py
def getgradeform(request):
id1=request.user.get_pf().id
sc=Sc.objects.filter(id=id1)
logging.debug(sc)
logging.debug("++++")
dict={}
dict.update({'sc': sc})
return render_to_response('content/add.html',dict)
Logging.debug gives an output as [<sc: Robert>]
My question is that how do i display Robert in the template .
I have tried the following in the template:<input type ="text" value={{sc}}/> //This gives me the dictionary itself
<input type ="text" value={{dict.sc}}/> //This also doesnt work.
Thanks......
|
[
"If you want any value in a dictionary, you have to do it on the way\ndict.key\n\n(On python you'll write it as dict['key'])\nSo, to present the value stored with key 'name' \n{{ sc.name }}\n\nAnyway, I think this is not you're case. I think you're not seeing a dictionary, but an object defined from models (as is a entry on the database).\nYou're storing in dict (don't call that value as dict , you're masking a keyword) a key 'sc' with value variable sc, which is returned from a model. I'm having to guess, because I don't know how this model is. Maybe 'Robert' is stored in the attribute name, id or something similar?\nYou need to show then the proper attribute, something like\n{{ sc.name }}\n{{ sc.id }}\n\n"
] |
[
6
] |
[] |
[] |
[
"django",
"python",
"templates"
] |
stackoverflow_0002152652_django_python_templates.txt
|
Q:
Filtering a list of strings based on contents
Given the list ['a','ab','abc','bac'], I want to compute a list with strings that have 'ab' in them. I.e. the result is ['ab','abc']. How can this be done in Python?
A:
This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:
>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']
Another way is to use the filter function. In Python 2:
>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']
In Python 3, it returns an iterator instead of a list, but you can cast it:
>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']
Though it's better practice to use a comprehension.
A:
[x for x in L if 'ab' in x]
A:
# To support matches from the beginning, not any matches:
items = ['a', 'ab', 'abc', 'bac']
prefix = 'ab'
filter(lambda x: x.startswith(prefix), items)
A:
Tried this out quickly in the interactive shell:
>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>
Why does this work? Because the in operator is defined for strings to mean: "is substring of".
Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:
l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
if 'ab' in s:
result.append(s)
|
Filtering a list of strings based on contents
|
Given the list ['a','ab','abc','bac'], I want to compute a list with strings that have 'ab' in them. I.e. the result is ['ab','abc']. How can this be done in Python?
|
[
"This simple filtering can be achieved in many ways with Python. The best approach is to use \"list comprehensions\" as follows:\n>>> lst = ['a', 'ab', 'abc', 'bac']\n>>> [k for k in lst if 'ab' in k]\n['ab', 'abc']\n\nAnother way is to use the filter function. In Python 2:\n>>> filter(lambda k: 'ab' in k, lst)\n['ab', 'abc']\n\nIn Python 3, it returns an iterator instead of a list, but you can cast it:\n>>> list(filter(lambda k: 'ab' in k, lst))\n['ab', 'abc']\n\nThough it's better practice to use a comprehension.\n",
"[x for x in L if 'ab' in x]\n\n",
"# To support matches from the beginning, not any matches:\n\nitems = ['a', 'ab', 'abc', 'bac']\nprefix = 'ab'\n\nfilter(lambda x: x.startswith(prefix), items)\n\n",
"Tried this out quickly in the interactive shell:\n>>> l = ['a', 'ab', 'abc', 'bac']\n>>> [x for x in l if 'ab' in x]\n['ab', 'abc']\n>>>\n\nWhy does this work? Because the in operator is defined for strings to mean: \"is substring of\".\nAlso, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:\nl = ['a', 'ab', 'abc', 'bac']\nresult = []\nfor s in l:\n if 'ab' in s:\n result.append(s)\n\n"
] |
[
248,
25,
22,
7
] |
[
"mylist = ['a', 'ab', 'abc']\nassert 'ab' in mylist\n\n"
] |
[
-3
] |
[
"list",
"python"
] |
stackoverflow_0002152898_list_python.txt
|
Q:
How can I install Easy_Install for Python 2.6.4 in Mac OSX 10.4.11
I get the following errors, I've placed [my name] for anonymity:
>>> python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py
File "<stdin>", line 1
python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py
^
SyntaxError: invalid syntax
If you can't see the ^ is under the 11.
Or I get this error:
>>> python /Users/[myname]/Desktop/EZ_tutorial/ez_setup.py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
A:
The ez_setup.py script may or may not work depending on your environment. If not, follow the instructions here. In particular, from the shell, make sure that the python 2.6 you installed is now invoked by the command python:
$ python
Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
If not, modify your shell's PATH environment variable. Then download the setuptools 2.6 python egg from here, change to your brower's download directory, and run the downloaded script:
$ cd ~/Downloads # substitute the appropriate directory name
$ sh setuptools-0.6c11-py2.6.egg
A:
Try running that command from a shell (i.e. straight from Terminal.app), not from inside the python interpreter.
|
How can I install Easy_Install for Python 2.6.4 in Mac OSX 10.4.11
|
I get the following errors, I've placed [my name] for anonymity:
>>> python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py
File "<stdin>", line 1
python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py
^
SyntaxError: invalid syntax
If you can't see the ^ is under the 11.
Or I get this error:
>>> python /Users/[myname]/Desktop/EZ_tutorial/ez_setup.py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
|
[
"The ez_setup.py script may or may not work depending on your environment. If not, follow the instructions here. In particular, from the shell, make sure that the python 2.6 you installed is now invoked by the command python:\n$ python\nPython 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) \n[GCC 4.0.1 (Apple Inc. build 5493)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> ^D\n\nIf not, modify your shell's PATH environment variable. Then download the setuptools 2.6 python egg from here, change to your brower's download directory, and run the downloaded script:\n$ cd ~/Downloads # substitute the appropriate directory name\n$ sh setuptools-0.6c11-py2.6.egg\n\n",
"Try running that command from a shell (i.e. straight from Terminal.app), not from inside the python interpreter.\n"
] |
[
4,
2
] |
[] |
[] |
[
"easy_install",
"python"
] |
stackoverflow_0002152463_easy_install_python.txt
|
Q:
how to find time at particular timezone from anywhere
I need to know the current time at CDT when my Python script is run. However this script will be run in multiple different timezones so a simple offset won't work.
I only need a solution for Linux, but a cross platform solution would be ideal.
A:
pytz or dateutil.tz is the trick here. Basically it's something like this:
>>> from pytz import timezone
>>> mytz = timezone('Europe/Paris')
>>> yourtz = timezone('US/Eastern')
>>> from datetime import datetime
>>> now = datetime.now(mytz)
>>> alsonow = now.astimezone(yourtz)
The difficulty actually lies in figuring out which timezone you are in. dateutil.tz is better at that.
>>> from dateutil.tz import tzlocal, gettz
>>> mytz = tzlocal()
>>> yourtz = gettz('US/Eastern')
If you want all the nitty gritty details of why timezones are evil, they are here:
http://regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/
http://regebro.wordpress.com/2008/05/10/python-and-time-zones-part-2-the-beast-returns/
http://regebro.wordpress.com/2008/05/13/thanks-for-the-testing-help-conclusions/
A:
You can use time.gmtime() to get time GMT (UTC) from any machine no matter the timezone, then you can apply your offset.
A:
A simple offset will work, you just need to offset from UTC.
Using datetime you can get the current utc (gmt) time and use datetime objects:
datetime.datetime.utcnow() - Provides time at UTC
datetime.datetime.now() - Provides time at local machine
To get the CT time from any system you need to know the CT time offset from UTC.
Then to account for daylight savings time code a function to get the current offset.
>>> import datetime
>>> utc = datetime.datetime.utcnow()
>>> current_ct_offset = get_current_ct_offset()
>>> ct_datetime = utc + datetime.timedelta(hours=current_ct_offset)
I could be overlooking something here, but if your only concerned about one timezone and your not doing tz name handling, it's pretty straight forward.
|
how to find time at particular timezone from anywhere
|
I need to know the current time at CDT when my Python script is run. However this script will be run in multiple different timezones so a simple offset won't work.
I only need a solution for Linux, but a cross platform solution would be ideal.
|
[
"pytz or dateutil.tz is the trick here. Basically it's something like this:\n>>> from pytz import timezone\n>>> mytz = timezone('Europe/Paris')\n>>> yourtz = timezone('US/Eastern')\n\n>>> from datetime import datetime\n>>> now = datetime.now(mytz)\n>>> alsonow = now.astimezone(yourtz)\n\nThe difficulty actually lies in figuring out which timezone you are in. dateutil.tz is better at that.\n>>> from dateutil.tz import tzlocal, gettz\n>>> mytz = tzlocal()\n>>> yourtz = gettz('US/Eastern')\n\nIf you want all the nitty gritty details of why timezones are evil, they are here:\nhttp://regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/\nhttp://regebro.wordpress.com/2008/05/10/python-and-time-zones-part-2-the-beast-returns/\nhttp://regebro.wordpress.com/2008/05/13/thanks-for-the-testing-help-conclusions/\n",
"You can use time.gmtime() to get time GMT (UTC) from any machine no matter the timezone, then you can apply your offset.\n",
"A simple offset will work, you just need to offset from UTC.\nUsing datetime you can get the current utc (gmt) time and use datetime objects:\ndatetime.datetime.utcnow() - Provides time at UTC\ndatetime.datetime.now() - Provides time at local machine \nTo get the CT time from any system you need to know the CT time offset from UTC.\nThen to account for daylight savings time code a function to get the current offset.\n>>> import datetime\n>>> utc = datetime.datetime.utcnow()\n>>> current_ct_offset = get_current_ct_offset()\n>>> ct_datetime = utc + datetime.timedelta(hours=current_ct_offset)\n\nI could be overlooking something here, but if your only concerned about one timezone and your not doing tz name handling, it's pretty straight forward.\n"
] |
[
9,
4,
1
] |
[] |
[] |
[
"datetime",
"linux",
"python",
"timezone"
] |
stackoverflow_0002152471_datetime_linux_python_timezone.txt
|
Q:
Handle 404 throw by code in appengine
I manage the "real" 404 errors in this way:
application = webapp.WSGIApplication([
('/', MainPage),
#Some others urls
('/.*',Trow404) #I got the 404 page
],debug=False)
But in some parts of my code i throw a 404 error
self.error(404)
and i wanna show the same page that mentioned before, ¿there is any way to catch the 404 error and manage it?
I can redirect to some inexistent url, but looks ugly
A:
The easiest way to do this is to override the error() method on your base handler (presuming you have one) to generate the 404 page, and call that from your regular handlers and your 404 handler. For example:
class BaseHandler(webapp.RequestHandler):
def error(self, code):
super(BaseHandler, self).error(code)
if code == 404:
# Output 404 page
class MyHandler(BaseHandler):
def get(self, some_id):
some_obj = SomeModel.get_by_id(some_id)
if not some_obj:
self.error(404)
return
# ...
class Error404Handler(BaseHandler):
def get(self):
self.error(404)
A:
Piggy backing on Derek Dahmer's answer (I don't have the karma to leave comments), you can then add this to Throw404 to send the proper header:
class Throw404(webapp.RequestHandler):
def get(self):
self.error(404)
# your 404 handler goes here
|
Handle 404 throw by code in appengine
|
I manage the "real" 404 errors in this way:
application = webapp.WSGIApplication([
('/', MainPage),
#Some others urls
('/.*',Trow404) #I got the 404 page
],debug=False)
But in some parts of my code i throw a 404 error
self.error(404)
and i wanna show the same page that mentioned before, ¿there is any way to catch the 404 error and manage it?
I can redirect to some inexistent url, but looks ugly
|
[
"The easiest way to do this is to override the error() method on your base handler (presuming you have one) to generate the 404 page, and call that from your regular handlers and your 404 handler. For example:\nclass BaseHandler(webapp.RequestHandler):\n def error(self, code):\n super(BaseHandler, self).error(code)\n if code == 404:\n # Output 404 page\n\nclass MyHandler(BaseHandler):\n def get(self, some_id):\n some_obj = SomeModel.get_by_id(some_id)\n if not some_obj:\n self.error(404)\n return\n # ...\n\nclass Error404Handler(BaseHandler):\n def get(self):\n self.error(404)\n\n",
"Piggy backing on Derek Dahmer's answer (I don't have the karma to leave comments), you can then add this to Throw404 to send the proper header:\nclass Throw404(webapp.RequestHandler):\n def get(self):\n self.error(404)\n # your 404 handler goes here\n\n"
] |
[
9,
0
] |
[] |
[] |
[
"google_app_engine",
"http_status_code_404",
"python"
] |
stackoverflow_0002142198_google_app_engine_http_status_code_404_python.txt
|
Q:
Efficient reordering of coordinate pairs (2-tuples) in a list of pairs in Python
I am wanting to zip up a list of entities with a new entity to generate a list of coordinates (2-tuples), but I want to assure that for (i, j) that i < j is always true.
However, I am not extremely pleased with my current solutions:
from itertools import repeat
mems = range(1, 10, 2)
mem = 8
def ij(i, j):
if i < j:
return (i, j)
else:
return (j, i)
def zipij(m=mem, ms=mems, f=ij):
return map(lambda i: f(i, m), ms)
def zipij2(m=mem, ms=mems):
return map(lambda i: tuple(sorted([i, m])), ms)
def zipij3(m=mem, ms=mems):
return [tuple(sorted([i, m])) for i in ms]
def zipij4(m=mem, ms=mems):
mems = zip(ms, repeat(m))
half1 = [(i, j) for i, j in mems if i < j]
half2 = [(j, i) for i, j in mems[len(half1):]]
return half1 + half2
def zipij5(m=mem, ms=mems):
mems = zip(ms, repeat(m))
return [(i, j) for i, j in mems if i < j] + [(j, i) for i, j in mems if i > j]
Output for above:
>>> print zipij() # or zipij{2-5}
[(1, 8), (3, 8), (5, 8), (7, 8), (8, 9)]
Instead of normally:
>>> print zip(mems, repeat(mem))
[(1, 8), (3, 8), (5, 8), (7, 8), (9, 8)]
Timings: snipped (no longer relevant, see much faster results in answers below)
For len(mems) == 5, there is no real issue with any solution, but for zipij5() for instance, the second list comprehension is needlessly going back over the first four values when i > j was already evaluated to be True for those in the first comprehension.
For my purposes, I'm positive that len(mems) will never exceed ~10000, if that helps form any answers for what solution is best. To explain my use case a bit (I find it interesting), I will be storing a sparse, upper-triangular, similarity matrix of sorts, and so I need the coordinate (i, j) to not be duplicated at (j, i). I say of sorts because I will be utilizing the new Counter() object in 2.7 to perform quasi matrix-matrix and matrix-vector addition. I then simply feed counter_obj.update() a list of 2-tuples and it increments those coordinates how many times they occur. SciPy sparse matrices ran about 50x slower, to my dismay, for my use cases... so I quickly ditched those.
So anyway, I was surprised by my results... The first methods I came up with were zipij4 and zipij5, and yet they are still the fastest, despite building a normal zip() and then generating a new zip after changing the values. I'm still rather new to Python, relatively speaking (Alex Martelli, can you hear me?), so here are my naive conclusions:
tuple(sorted([i, j])) is extremely expensive (Why is that?)
map(lambda ...) seems to always do worse than a list comp (I think I've read this and it makes sense)
Somehow zipij5() isn't much slower despite going over the list twice to check for i-j inequality. (Why is this?)
And lastly, I would like to know which is considered most efficient... or if there are any other fast and memory-inexpensive ways that I haven't yet thought of. Thank you.
Current Best Solutions
## Most BRIEF, Quickest with UNSORTED input list:
## truppo's
def zipij9(m=mem, ms=mems):
return [(i, m) if i < m else (m, i) for i in ms]
## Quickest with pre-SORTED input list:
## Michal's
def zipij10(m=mem, ms=mems):
i = binsearch(m, ms) ## See Michal's answer for binsearch()
return zip(ms[:i], repeat(m)) + zip(repeat(m), ms[i:])
Timings
# Michal's
Presorted - 410µs per loop
Unsorted - 2.09ms per loop ## Due solely to the expensive sorted()
# truppo's
Presorted - 880µs per loop
Unsorted - 896µs per loop ## No sorted() needed
Timings were using mems = range(1, 10000, 2), which is only ~5000 in length. sorted() will probably become worse at higher values, and with lists that are more shuffled. random.shuffle() was used for the "Unsorted" timings.
A:
Current version:
(Fastest at the time of posting with Python 2.6.4 on my machine.)
Update 3: Since we're going all out, let's do a binary search -- in a way which doesn't require injecting m into mems:
def binsearch(x, lst):
low, high = -1, len(lst)
while low < high:
i = (high - low) // 2
if i > 0:
i += low
if lst[i] < x:
low = i
else:
high = i
else:
i = high
high = low
return i
def zipij(m=mem, ms=mems):
i = binsearch(m, ms)
return zip(ms[:i], repeat(m)) + zip(repeat(m), ms[i:])
This runs in 828 µs = 0.828 ms on my machine vs the OP's current solution's 1.14 ms. Input list assumed sorted (and the test case is the usual one, of course).
This binary search implementation returns the index of the first element in the given list which is not smaller than the object being searched for. Thus there's no need to inject m into mems and sort the whole thing (like in the OP's current solution with .index(m)) or walk through the beginning of the list step by step (like I did previously) to find the offset at which it should be divided.
Earlier attempts:
How about this? (Proposed solution next to In [25] below, 2.42 ms to zipij5's 3.13 ms.)
In [24]: timeit zipij5(m = mem, ms = mems)
100 loops, best of 3: 3.13 ms per loop
In [25]: timeit [(i, j) if i < j else (j, i) for (i, j) in zip(mems, repeat(mem))]
100 loops, best of 3: 2.42 ms per loop
In [27]: [(i, j) if i < j else (j, i) for (i, j) in zip(mems, repeat(mem))] == zipij5(m=mem, ms=mems)
Out[27]: True
Update: This appears to be just about exactly as fast as the OP's self-answer. Seems more straighforward, though.
Update 2: An implementation of the OP's proposed simplified solution:
def zipij(m=mem, ms=mems):
split_at = 0
for item in ms:
if item < m:
split_at += 1
else:
break
return [(item, m) for item in mems[:split_at]] + [(m, item) for item in mems[split_at:]]
In [54]: timeit zipij()
1000 loops, best of 3: 1.15 ms per loop
Also, truppo's solution runs in 1.36 ms on my machine. I guess the above is the fastest so far. Note you need to sort mems before passing them into this function! If you're generating it with range, it is of course already sorted, though.
A:
Why not just inline your ij()-function?
def zipij(m=mem, ms=mems):
return [(i, m) if i < m else (m, i) for i in ms]
(This runs in 0.64 ms instead of 2.12 ms on my computer)
Some benchmarks:
zipit.py:
from itertools import repeat
mems = range(1, 50000, 2)
mem = 8
def zipij7(m=mem, ms=mems):
cpy = sorted(ms + [m])
loc = cpy.index(m)
return zip(ms[:(loc)], repeat(m)) + zip(repeat(m), ms[(loc):])
def zipinline(m=mem, ms=mems):
return [(i, m) if i < m else (m, i) for i in ms]
Sorted:
>python -m timeit -s "import zipit" "zipit.zipinline()"
100 loops, best of 3: 4.44 msec per loop
>python -m timeit -s "import zipit" "zipit.zipij7()"
100 loops, best of 3: 4.8 msec per loop
Unsorted:
>python -m timeit -s "import zipit, random; random.shuffle(zipit.mems)" "zipit.zipinline()"
100 loops, best of 3: 4.65 msec per loop
p>python -m timeit -s "import zipit, random; random.shuffle(zipit.mems)" "zipit.zipij7()"
100 loops, best of 3: 17.1 msec per loop
A:
Most recent version:
def zipij7(m=mem, ms=mems):
cpy = sorted(ms + [m])
loc = cpy.index(m)
return zip(ms[:(loc)], repeat(m)) + zip(repeat(m), ms[(loc):])
Benches slightly faster for me than truppo's, slower by 30% than Michal's. (Looking into that now)
I may have found my answer (for now). It seems I forgot about making a list comp version for `zipij()``:
def zipij1(m=mem, ms=mems, f=ij):
return [f(i, m) for i in ms]
It still relies on my silly ij() helper function, so it doesn't win the award for brevity, certainly, but timings have improved:
# 10000
1.27s
# 50000
6.74s
So it is now my current "winner", and also does not need to generate more than one list, or use a lot of function calls, other than the ij() helper, so I believe it would also be the most efficient.
However, I think this could still be improved... I think that making N ij() function calls (where N is the length of the resultant list) is not needed:
Find at what index mem would fit into mems when ordered
Split mems at that index into two parts
Do zip(part1, repeat(mem))
Add zip(repeat(mem), part2) to it
It'd basically be an improvement on zipij4(), and this avoids N extra function calls, but I am not sure of the speed/memory benefits over the cost of brevity. I will maybe add that version to this answer if I figure it out.
|
Efficient reordering of coordinate pairs (2-tuples) in a list of pairs in Python
|
I am wanting to zip up a list of entities with a new entity to generate a list of coordinates (2-tuples), but I want to assure that for (i, j) that i < j is always true.
However, I am not extremely pleased with my current solutions:
from itertools import repeat
mems = range(1, 10, 2)
mem = 8
def ij(i, j):
if i < j:
return (i, j)
else:
return (j, i)
def zipij(m=mem, ms=mems, f=ij):
return map(lambda i: f(i, m), ms)
def zipij2(m=mem, ms=mems):
return map(lambda i: tuple(sorted([i, m])), ms)
def zipij3(m=mem, ms=mems):
return [tuple(sorted([i, m])) for i in ms]
def zipij4(m=mem, ms=mems):
mems = zip(ms, repeat(m))
half1 = [(i, j) for i, j in mems if i < j]
half2 = [(j, i) for i, j in mems[len(half1):]]
return half1 + half2
def zipij5(m=mem, ms=mems):
mems = zip(ms, repeat(m))
return [(i, j) for i, j in mems if i < j] + [(j, i) for i, j in mems if i > j]
Output for above:
>>> print zipij() # or zipij{2-5}
[(1, 8), (3, 8), (5, 8), (7, 8), (8, 9)]
Instead of normally:
>>> print zip(mems, repeat(mem))
[(1, 8), (3, 8), (5, 8), (7, 8), (9, 8)]
Timings: snipped (no longer relevant, see much faster results in answers below)
For len(mems) == 5, there is no real issue with any solution, but for zipij5() for instance, the second list comprehension is needlessly going back over the first four values when i > j was already evaluated to be True for those in the first comprehension.
For my purposes, I'm positive that len(mems) will never exceed ~10000, if that helps form any answers for what solution is best. To explain my use case a bit (I find it interesting), I will be storing a sparse, upper-triangular, similarity matrix of sorts, and so I need the coordinate (i, j) to not be duplicated at (j, i). I say of sorts because I will be utilizing the new Counter() object in 2.7 to perform quasi matrix-matrix and matrix-vector addition. I then simply feed counter_obj.update() a list of 2-tuples and it increments those coordinates how many times they occur. SciPy sparse matrices ran about 50x slower, to my dismay, for my use cases... so I quickly ditched those.
So anyway, I was surprised by my results... The first methods I came up with were zipij4 and zipij5, and yet they are still the fastest, despite building a normal zip() and then generating a new zip after changing the values. I'm still rather new to Python, relatively speaking (Alex Martelli, can you hear me?), so here are my naive conclusions:
tuple(sorted([i, j])) is extremely expensive (Why is that?)
map(lambda ...) seems to always do worse than a list comp (I think I've read this and it makes sense)
Somehow zipij5() isn't much slower despite going over the list twice to check for i-j inequality. (Why is this?)
And lastly, I would like to know which is considered most efficient... or if there are any other fast and memory-inexpensive ways that I haven't yet thought of. Thank you.
Current Best Solutions
## Most BRIEF, Quickest with UNSORTED input list:
## truppo's
def zipij9(m=mem, ms=mems):
return [(i, m) if i < m else (m, i) for i in ms]
## Quickest with pre-SORTED input list:
## Michal's
def zipij10(m=mem, ms=mems):
i = binsearch(m, ms) ## See Michal's answer for binsearch()
return zip(ms[:i], repeat(m)) + zip(repeat(m), ms[i:])
Timings
# Michal's
Presorted - 410µs per loop
Unsorted - 2.09ms per loop ## Due solely to the expensive sorted()
# truppo's
Presorted - 880µs per loop
Unsorted - 896µs per loop ## No sorted() needed
Timings were using mems = range(1, 10000, 2), which is only ~5000 in length. sorted() will probably become worse at higher values, and with lists that are more shuffled. random.shuffle() was used for the "Unsorted" timings.
|
[
"Current version:\n(Fastest at the time of posting with Python 2.6.4 on my machine.)\nUpdate 3: Since we're going all out, let's do a binary search -- in a way which doesn't require injecting m into mems:\ndef binsearch(x, lst):\n low, high = -1, len(lst)\n while low < high: \n i = (high - low) // 2\n if i > 0:\n i += low\n if lst[i] < x:\n low = i\n else:\n high = i\n else:\n i = high\n high = low\n return i\n\ndef zipij(m=mem, ms=mems):\n i = binsearch(m, ms)\n return zip(ms[:i], repeat(m)) + zip(repeat(m), ms[i:])\n\nThis runs in 828 µs = 0.828 ms on my machine vs the OP's current solution's 1.14 ms. Input list assumed sorted (and the test case is the usual one, of course).\nThis binary search implementation returns the index of the first element in the given list which is not smaller than the object being searched for. Thus there's no need to inject m into mems and sort the whole thing (like in the OP's current solution with .index(m)) or walk through the beginning of the list step by step (like I did previously) to find the offset at which it should be divided.\n\nEarlier attempts:\nHow about this? (Proposed solution next to In [25] below, 2.42 ms to zipij5's 3.13 ms.)\nIn [24]: timeit zipij5(m = mem, ms = mems)\n100 loops, best of 3: 3.13 ms per loop\n\nIn [25]: timeit [(i, j) if i < j else (j, i) for (i, j) in zip(mems, repeat(mem))]\n100 loops, best of 3: 2.42 ms per loop\n\nIn [27]: [(i, j) if i < j else (j, i) for (i, j) in zip(mems, repeat(mem))] == zipij5(m=mem, ms=mems)\nOut[27]: True\n\nUpdate: This appears to be just about exactly as fast as the OP's self-answer. Seems more straighforward, though.\nUpdate 2: An implementation of the OP's proposed simplified solution:\ndef zipij(m=mem, ms=mems):\n split_at = 0\n for item in ms:\n if item < m:\n split_at += 1\n else:\n break\n return [(item, m) for item in mems[:split_at]] + [(m, item) for item in mems[split_at:]]\n\nIn [54]: timeit zipij()\n1000 loops, best of 3: 1.15 ms per loop\n\nAlso, truppo's solution runs in 1.36 ms on my machine. I guess the above is the fastest so far. Note you need to sort mems before passing them into this function! If you're generating it with range, it is of course already sorted, though.\n",
"Why not just inline your ij()-function?\ndef zipij(m=mem, ms=mems):\n return [(i, m) if i < m else (m, i) for i in ms]\n\n(This runs in 0.64 ms instead of 2.12 ms on my computer)\nSome benchmarks:\nzipit.py:\nfrom itertools import repeat\n\nmems = range(1, 50000, 2)\nmem = 8\n\ndef zipij7(m=mem, ms=mems):\n cpy = sorted(ms + [m])\n loc = cpy.index(m)\n\n return zip(ms[:(loc)], repeat(m)) + zip(repeat(m), ms[(loc):])\n\ndef zipinline(m=mem, ms=mems):\n return [(i, m) if i < m else (m, i) for i in ms]\n\nSorted:\n>python -m timeit -s \"import zipit\" \"zipit.zipinline()\"\n100 loops, best of 3: 4.44 msec per loop\n\n>python -m timeit -s \"import zipit\" \"zipit.zipij7()\"\n100 loops, best of 3: 4.8 msec per loop\n\nUnsorted:\n>python -m timeit -s \"import zipit, random; random.shuffle(zipit.mems)\" \"zipit.zipinline()\"\n100 loops, best of 3: 4.65 msec per loop\n\np>python -m timeit -s \"import zipit, random; random.shuffle(zipit.mems)\" \"zipit.zipij7()\"\n100 loops, best of 3: 17.1 msec per loop\n\n",
"Most recent version:\ndef zipij7(m=mem, ms=mems):\n cpy = sorted(ms + [m])\n loc = cpy.index(m)\n\n return zip(ms[:(loc)], repeat(m)) + zip(repeat(m), ms[(loc):])\n\nBenches slightly faster for me than truppo's, slower by 30% than Michal's. (Looking into that now)\n\nI may have found my answer (for now). It seems I forgot about making a list comp version for `zipij()``:\ndef zipij1(m=mem, ms=mems, f=ij):\n return [f(i, m) for i in ms]\n\nIt still relies on my silly ij() helper function, so it doesn't win the award for brevity, certainly, but timings have improved:\n# 10000\n1.27s\n# 50000\n6.74s\n\nSo it is now my current \"winner\", and also does not need to generate more than one list, or use a lot of function calls, other than the ij() helper, so I believe it would also be the most efficient.\nHowever, I think this could still be improved... I think that making N ij() function calls (where N is the length of the resultant list) is not needed:\n\nFind at what index mem would fit into mems when ordered\nSplit mems at that index into two parts\nDo zip(part1, repeat(mem))\nAdd zip(repeat(mem), part2) to it\n\nIt'd basically be an improvement on zipij4(), and this avoids N extra function calls, but I am not sure of the speed/memory benefits over the cost of brevity. I will maybe add that version to this answer if I figure it out.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"python",
"sorting",
"tuples"
] |
stackoverflow_0002153976_python_sorting_tuples.txt
|
Q:
Parsing a range of integers in a list
I've just began learning Python and I've ran into a small problem.
I need to parse a text file, more specifically an HTML file (but it's syntax is so weird - divs after divs after divs, the result of a Google's 'View as HTML' for a certain PDF i can't seem to extract the text because it has a messy table done in m$ word).
Anyway, I chose a rather low-level approach because i just need the data asap and since I'm beginning to learn Python, I figured learning the basics would do me some good too.
I've got everything done except for a small part in which i need to retrieve a set of integers from a set of divs. Here's an example:
<div style="position:absolute;top:522;left:1020"><nobr>*88</nobr></div>
Now the numbers i want to retrieve all the ones inside <nobr></nobr> (in that case, '588') and, since it's quite a messy file, i have to make sure that what I am getting is correct. To do so, that number inside <nobr></nobr> must be preceded by "left:1020", "left:1024" or "left:1028". This is because of the automatic conversion and the best choice would be to get all the number preceded by left:102[0-] in my opinion.
To do so, I was trying to use:
for o in re.finditer('left:102[0-9]"><nobr>(.*?)</nobr></div>', words[index])
out = o.group(1)
But so far, no such luck... How can I get those numbers?
Thanks in advance,
J.
A:
Don't use regular expressions to parse HTML. BeautifulSoup will make light work of this.
As for your specific problem, it might be that you are missing a colon at the end of the first line:
for o in re.finditer('left:102[0-9]"><nobr>(.*?)</nobr></div>', words[index]):
out = o.group(1)
If this isn't the problem, please post the error you are getting, at what you expect the output to be.
|
Parsing a range of integers in a list
|
I've just began learning Python and I've ran into a small problem.
I need to parse a text file, more specifically an HTML file (but it's syntax is so weird - divs after divs after divs, the result of a Google's 'View as HTML' for a certain PDF i can't seem to extract the text because it has a messy table done in m$ word).
Anyway, I chose a rather low-level approach because i just need the data asap and since I'm beginning to learn Python, I figured learning the basics would do me some good too.
I've got everything done except for a small part in which i need to retrieve a set of integers from a set of divs. Here's an example:
<div style="position:absolute;top:522;left:1020"><nobr>*88</nobr></div>
Now the numbers i want to retrieve all the ones inside <nobr></nobr> (in that case, '588') and, since it's quite a messy file, i have to make sure that what I am getting is correct. To do so, that number inside <nobr></nobr> must be preceded by "left:1020", "left:1024" or "left:1028". This is because of the automatic conversion and the best choice would be to get all the number preceded by left:102[0-] in my opinion.
To do so, I was trying to use:
for o in re.finditer('left:102[0-9]"><nobr>(.*?)</nobr></div>', words[index])
out = o.group(1)
But so far, no such luck... How can I get those numbers?
Thanks in advance,
J.
|
[
"Don't use regular expressions to parse HTML. BeautifulSoup will make light work of this.\nAs for your specific problem, it might be that you are missing a colon at the end of the first line:\nfor o in re.finditer('left:102[0-9]\"><nobr>(.*?)</nobr></div>', words[index]):\n out = o.group(1)\n\nIf this isn't the problem, please post the error you are getting, at what you expect the output to be.\n"
] |
[
1
] |
[] |
[] |
[
"parsing",
"python",
"regex",
"syntax_error"
] |
stackoverflow_0002154116_parsing_python_regex_syntax_error.txt
|
Q:
How to enter item into Google AppEngine Datastore?
I want to check if an email is in my database in Appengine, and if not: then enter it into the datastore.
I am new to python.
Why is this simple code not working? (Also If there is a better way/more efficient way to write this, please tell me)
(I get the error: BadArgumentError: Unused positional arguments [1])
class EmailAdd(webapp.RequestHandler):
def get(self):
query = db.GqlQuery("SELECT * FROM EmailDatabase WHERE emailaddress=':1'", self.request.get('emailaddress'))
result = query.get()
if result is None:
newemail = EmailDatabase()
newemail.emailaddress = self.request.get('emailaddress')
newemail.put()
And for reference, this is my db class:
class EmailDatabase(db.Model):
emailaddress = db.StringProperty()
date = db.DateTimeProperty(auto_now_add=True)
A:
You don't need to use quotes when binding a parameter to the query:
query = db.GqlQuery("SELECT * FROM EmailDatabase WHERE emailaddress = :1", self.request.get('emailaddress'))
Otherwise it will read it as a string and actually only return objects that have :1 as their emailaddress value.
Also, make sure you validate the user input (self.request.get('emailaddress')) before inserting it into the query.
|
How to enter item into Google AppEngine Datastore?
|
I want to check if an email is in my database in Appengine, and if not: then enter it into the datastore.
I am new to python.
Why is this simple code not working? (Also If there is a better way/more efficient way to write this, please tell me)
(I get the error: BadArgumentError: Unused positional arguments [1])
class EmailAdd(webapp.RequestHandler):
def get(self):
query = db.GqlQuery("SELECT * FROM EmailDatabase WHERE emailaddress=':1'", self.request.get('emailaddress'))
result = query.get()
if result is None:
newemail = EmailDatabase()
newemail.emailaddress = self.request.get('emailaddress')
newemail.put()
And for reference, this is my db class:
class EmailDatabase(db.Model):
emailaddress = db.StringProperty()
date = db.DateTimeProperty(auto_now_add=True)
|
[
"You don't need to use quotes when binding a parameter to the query:\nquery = db.GqlQuery(\"SELECT * FROM EmailDatabase WHERE emailaddress = :1\", self.request.get('emailaddress'))\n\nOtherwise it will read it as a string and actually only return objects that have :1 as their emailaddress value.\nAlso, make sure you validate the user input (self.request.get('emailaddress')) before inserting it into the query.\n"
] |
[
6
] |
[] |
[] |
[
"google_app_engine",
"gql",
"python"
] |
stackoverflow_0002154110_google_app_engine_gql_python.txt
|
Q:
Python: Visualization tool for graphs
Guys I have asked this question before but did not receive a single comment or answer
I want to simulate a search algorithm on a power law graph and want to visually see the algorithm move from one node to another on the graph. How do I do that?
A:
You can adapt this completely different code I happen to have written for Find the most points enclosed in a fixed size circle :)
The useful bit is:
It uses the basic windowing system tkinter to create a frame containing a canvas; it then does some algorithm, calling it's own 'draw()' to change the canvas and then 'update()' to redraw the screen, with a delay. From seeing how easy it is to chart in tkinter, you can perhaps move on to interactive versions etc.
import random, math, time
from Tkinter import * # our UI
def sqr(x):
return x*x
class Point:
def __init__(self,x,y):
self.x = float(x)
self.y = float(y)
self.left = 0
self.right = []
def __repr__(self):
return "("+str(self.x)+","+str(self.y)+")"
def distance(self,other):
return math.sqrt(sqr(self.x-other.x)+sqr(self.y-other.y))
def equidist(left,right,dist):
u = (right.x-left.x)
v = (right.y-left.y)
if 0 != u:
r = math.sqrt(sqr(dist)-((sqr(u)+sqr(v))/4.))
theta = math.atan(v/u)
x = left.x+(u/2)-(r*math.sin(theta))
if x < left.x:
x = left.x+(u/2)+(r*math.sin(theta))
y = left.y+(v/2)-(r*math.cos(theta))
else:
y = left.y+(v/2)+(r*math.cos(theta))
else:
theta = math.asin(v/(2*dist))
x = left.x-(dist*math.cos(theta))
y = left.y + (v/2)
return Point(x,y)
class Vis:
def __init__(self):
self.frame = Frame(root)
self.canvas = Canvas(self.frame,bg="white",width=width,height=height)
self.canvas.pack()
self.frame.pack()
self.run()
def run(self):
self.count_calc0 = 0
self.count_calc1 = 0
self.count_calc2 = 0
self.count_calc3 = 0
self.count_calc4 = 0
self.count_calc5 = 0
self.prev_x = 0
self.best = -1
self.best_centre = []
for self.sweep in xrange(0,len(points)):
self.count_calc0 += 1
if len(points[self.sweep].right) <= self.best:
break
self.calc(points[self.sweep])
self.sweep = len(points) # so that draw() stops highlighting it
print "BEST",self.best+1, self.best_centre # count left-most point too
print "counts",self.count_calc0, self.count_calc1,self.count_calc2,self.count_calc3,self.count_calc4,self.count_calc5
self.draw()
def calc(self,p):
for self.right in p.right:
self.count_calc1 += 1
if (self.right.left + len(self.right.right)) < self.best:
# this can never help us
continue
self.count_calc2 += 1
self.centre = equidist(p,self.right,radius)
assert abs(self.centre.distance(p)-self.centre.distance(self.right)) < 1
count = 0
for p2 in p.right:
self.count_calc3 += 1
if self.centre.distance(p2) <= radius:
count += 1
if self.best < count:
self.count_calc4 += 4
self.best = count
self.best_centre = [self.centre]
elif self.best == count:
self.count_calc5 += 5
self.best_centre.append(self.centre)
self.draw()
self.frame.update()
time.sleep(0.1)
def draw(self):
self.canvas.delete(ALL)
# draw best circle
for best in self.best_centre:
self.canvas.create_oval(best.x-radius,best.y-radius,\
best.x+radius+1,best.y+radius+1,fill="red",\
outline="red")
# draw current circle
if self.sweep < len(points):
self.canvas.create_oval(self.centre.x-radius,self.centre.y-radius,\
self.centre.x+radius+1,self.centre.y+radius+1,fill="pink",\
outline="pink")
# draw all the connections
for p in points:
for p2 in p.right:
self.canvas.create_line(p.x,p.y,p2.x,p2.y,fill="lightGray")
# plot visited points
for i in xrange(0,self.sweep):
p = points[i]
self.canvas.create_line(p.x-2,p.y,p.x+3,p.y,fill="blue")
self.canvas.create_line(p.x,p.y-2,p.x,p.y+3,fill="blue")
# plot current point
if self.sweep < len(points):
p = points[self.sweep]
self.canvas.create_line(p.x-2,p.y,p.x+3,p.y,fill="red")
self.canvas.create_line(p.x,p.y-2,p.x,p.y+3,fill="red")
self.canvas.create_line(p.x,p.y,self.right.x,self.right.y,fill="red")
self.canvas.create_line(p.x,p.y,self.centre.x,self.centre.y,fill="cyan")
self.canvas.create_line(self.right.x,self.right.y,self.centre.x,self.centre.y,fill="cyan")
# plot unvisited points
for i in xrange(self.sweep+1,len(points)):
p = points[i]
self.canvas.create_line(p.x-2,p.y,p.x+3,p.y,fill="green")
self.canvas.create_line(p.x,p.y-2,p.x,p.y+3,fill="green")
radius = 60
diameter = radius*2
width = 800
height = 600
points = []
# make some points
for i in xrange(0,100):
points.append(Point(random.randrange(width),random.randrange(height)))
# sort points for find-the-right sweep
points.sort(lambda a, b: int(a.x)-int(b.x))
# work out those points to the right of each point
for i in xrange(0,len(points)):
p = points[i]
for j in xrange(i+1,len(points)):
p2 = points[j]
if p2.x > (p.x+diameter):
break
if (abs(p.y-p2.y) <= diameter) and \
p.distance(p2) < diameter:
p.right.append(p2)
p2.left += 1
# sort points in potential order for sweep, point with most right first
points.sort(lambda a, b: len(b.right)-len(a.right))
# debug
for p in points:
print p, p.left, p.right
# show it
root = Tk()
vis = Vis()
root.mainloop()
A:
You can use matplotlib for that.
Here is a simlple example of a mesh with an animated highlighted point:
import matplotlib.pyplot as plt
import time
x_size = 4
y_size = 3
# create the points and edges of the mesh
points = [(x,y) for y in range(y_size) for x in range(x_size)]
vert_edges = [((i_y*x_size)+i_x,(i_y*x_size)+i_x+1)
for i_x in range(x_size-1) for i_y in range(y_size)]
horz_edges = [((i_y*x_size)+i_x,((i_y+1)*x_size)+i_x)
for i_x in range(x_size) for i_y in range(y_size-1)]
edges = vert_edges + horz_edges
# plot all the points and edges
lines = []
for edge in edges:
x_coords, y_coords = zip(points[edge[0]], points[edge[1]])
lines.extend((x_coords, y_coords, 'g'))
plt.plot(linewidth=1, *lines)
x, y = zip(*points)
plt.plot(x, y, 'o')
# create the highlighted point
point_plot = plt.plot([0], [0], 'ro')[0]
# turn on interactive plotting mode
plt.ion()
plt.ylim(-1, y_size)
plt.xlim(-1, x_size)
# animate the highlighted point
for i_point in range(1, len(x)):
point_plot.set_xdata([x[i_point]])
point_plot.set_ydata([y[i_point]])
plt.draw()
time.sleep(0.5)
plt.show()
|
Python: Visualization tool for graphs
|
Guys I have asked this question before but did not receive a single comment or answer
I want to simulate a search algorithm on a power law graph and want to visually see the algorithm move from one node to another on the graph. How do I do that?
|
[
"You can adapt this completely different code I happen to have written for Find the most points enclosed in a fixed size circle :)\nThe useful bit is:\nIt uses the basic windowing system tkinter to create a frame containing a canvas; it then does some algorithm, calling it's own 'draw()' to change the canvas and then 'update()' to redraw the screen, with a delay. From seeing how easy it is to chart in tkinter, you can perhaps move on to interactive versions etc.\nimport random, math, time\nfrom Tkinter import * # our UI\n\ndef sqr(x):\n return x*x\n\nclass Point:\n def __init__(self,x,y):\n self.x = float(x)\n self.y = float(y)\n self.left = 0\n self.right = []\n def __repr__(self):\n return \"(\"+str(self.x)+\",\"+str(self.y)+\")\"\n def distance(self,other):\n return math.sqrt(sqr(self.x-other.x)+sqr(self.y-other.y))\n\ndef equidist(left,right,dist):\n u = (right.x-left.x)\n v = (right.y-left.y)\n if 0 != u:\n r = math.sqrt(sqr(dist)-((sqr(u)+sqr(v))/4.))\n theta = math.atan(v/u)\n x = left.x+(u/2)-(r*math.sin(theta))\n if x < left.x:\n x = left.x+(u/2)+(r*math.sin(theta))\n y = left.y+(v/2)-(r*math.cos(theta))\n else:\n y = left.y+(v/2)+(r*math.cos(theta))\n else:\n theta = math.asin(v/(2*dist))\n x = left.x-(dist*math.cos(theta))\n y = left.y + (v/2)\n return Point(x,y)\n\nclass Vis:\n def __init__(self):\n self.frame = Frame(root)\n self.canvas = Canvas(self.frame,bg=\"white\",width=width,height=height)\n self.canvas.pack()\n self.frame.pack()\n self.run()\n def run(self):\n self.count_calc0 = 0\n self.count_calc1 = 0\n self.count_calc2 = 0\n self.count_calc3 = 0\n self.count_calc4 = 0\n self.count_calc5 = 0\n self.prev_x = 0\n self.best = -1\n self.best_centre = []\n for self.sweep in xrange(0,len(points)):\n self.count_calc0 += 1\n if len(points[self.sweep].right) <= self.best:\n break\n self.calc(points[self.sweep])\n self.sweep = len(points) # so that draw() stops highlighting it\n print \"BEST\",self.best+1, self.best_centre # count left-most point too\n print \"counts\",self.count_calc0, self.count_calc1,self.count_calc2,self.count_calc3,self.count_calc4,self.count_calc5\n self.draw()\n def calc(self,p):\n for self.right in p.right:\n self.count_calc1 += 1\n if (self.right.left + len(self.right.right)) < self.best:\n # this can never help us\n continue\n self.count_calc2 += 1\n self.centre = equidist(p,self.right,radius)\n assert abs(self.centre.distance(p)-self.centre.distance(self.right)) < 1\n count = 0\n for p2 in p.right:\n self.count_calc3 += 1\n if self.centre.distance(p2) <= radius:\n count += 1\n if self.best < count:\n self.count_calc4 += 4\n self.best = count\n self.best_centre = [self.centre]\n elif self.best == count:\n self.count_calc5 += 5\n self.best_centre.append(self.centre)\n self.draw()\n self.frame.update()\n time.sleep(0.1)\n def draw(self):\n self.canvas.delete(ALL)\n # draw best circle\n for best in self.best_centre:\n self.canvas.create_oval(best.x-radius,best.y-radius,\\\n best.x+radius+1,best.y+radius+1,fill=\"red\",\\\n outline=\"red\")\n # draw current circle\n if self.sweep < len(points):\n self.canvas.create_oval(self.centre.x-radius,self.centre.y-radius,\\\n self.centre.x+radius+1,self.centre.y+radius+1,fill=\"pink\",\\\n outline=\"pink\")\n # draw all the connections\n for p in points:\n for p2 in p.right:\n self.canvas.create_line(p.x,p.y,p2.x,p2.y,fill=\"lightGray\")\n # plot visited points\n for i in xrange(0,self.sweep):\n p = points[i]\n self.canvas.create_line(p.x-2,p.y,p.x+3,p.y,fill=\"blue\")\n self.canvas.create_line(p.x,p.y-2,p.x,p.y+3,fill=\"blue\")\n # plot current point\n if self.sweep < len(points):\n p = points[self.sweep]\n self.canvas.create_line(p.x-2,p.y,p.x+3,p.y,fill=\"red\")\n self.canvas.create_line(p.x,p.y-2,p.x,p.y+3,fill=\"red\")\n self.canvas.create_line(p.x,p.y,self.right.x,self.right.y,fill=\"red\")\n self.canvas.create_line(p.x,p.y,self.centre.x,self.centre.y,fill=\"cyan\")\n self.canvas.create_line(self.right.x,self.right.y,self.centre.x,self.centre.y,fill=\"cyan\")\n # plot unvisited points\n for i in xrange(self.sweep+1,len(points)):\n p = points[i]\n self.canvas.create_line(p.x-2,p.y,p.x+3,p.y,fill=\"green\")\n self.canvas.create_line(p.x,p.y-2,p.x,p.y+3,fill=\"green\")\n\nradius = 60\ndiameter = radius*2\nwidth = 800\nheight = 600\n\npoints = []\n\n# make some points\nfor i in xrange(0,100):\n points.append(Point(random.randrange(width),random.randrange(height)))\n\n# sort points for find-the-right sweep\npoints.sort(lambda a, b: int(a.x)-int(b.x))\n\n# work out those points to the right of each point\nfor i in xrange(0,len(points)):\n p = points[i]\n for j in xrange(i+1,len(points)):\n p2 = points[j]\n if p2.x > (p.x+diameter):\n break\n if (abs(p.y-p2.y) <= diameter) and \\\n p.distance(p2) < diameter:\n p.right.append(p2)\n p2.left += 1\n\n# sort points in potential order for sweep, point with most right first\npoints.sort(lambda a, b: len(b.right)-len(a.right))\n\n# debug\nfor p in points:\n print p, p.left, p.right\n\n# show it\nroot = Tk()\nvis = Vis()\nroot.mainloop()\n\n",
"You can use matplotlib for that.\nHere is a simlple example of a mesh with an animated highlighted point:\nimport matplotlib.pyplot as plt\nimport time\n\nx_size = 4\ny_size = 3\n\n# create the points and edges of the mesh\npoints = [(x,y) for y in range(y_size) for x in range(x_size)]\nvert_edges = [((i_y*x_size)+i_x,(i_y*x_size)+i_x+1)\n for i_x in range(x_size-1) for i_y in range(y_size)]\nhorz_edges = [((i_y*x_size)+i_x,((i_y+1)*x_size)+i_x)\n for i_x in range(x_size) for i_y in range(y_size-1)]\nedges = vert_edges + horz_edges\n\n# plot all the points and edges\nlines = []\nfor edge in edges:\n x_coords, y_coords = zip(points[edge[0]], points[edge[1]])\n lines.extend((x_coords, y_coords, 'g'))\nplt.plot(linewidth=1, *lines)\nx, y = zip(*points)\nplt.plot(x, y, 'o')\n\n# create the highlighted point\npoint_plot = plt.plot([0], [0], 'ro')[0]\n\n# turn on interactive plotting mode\nplt.ion()\nplt.ylim(-1, y_size)\nplt.xlim(-1, x_size)\n\n# animate the highlighted point\nfor i_point in range(1, len(x)):\n point_plot.set_xdata([x[i_point]])\n point_plot.set_ydata([y[i_point]])\n plt.draw()\n time.sleep(0.5)\n\nplt.show()\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002153878_python.txt
|
Q:
Log onto a Website and select options using Python
I am trying to log onto a website using Python. I have written the code to connect to the target but I need to login and select a button on the website and wait for a response. I have looked at the HTTP Protocol in Python and was thinking of using 'HTTPConnection.putrequest'. I am not sure how to do this, I have the code I have so far below:
def testHTTPS(self):
c = httplib.HTTPSConnection(ip)
c.request("GET", "/")
response = c.getresponse()
self.assertEqual(response.status, 200) # '200' is success code
conn.close()
And the code for the logon function on the website is:
<td align="right" id="lgn_userName"></td>
<td><input type="text" class="button" name="username" id="username" size="24" maxlength="16" accesskey="u" tabindex="1" value=""/></td>
</tr>
<tr>
<td align="right" id="lgn_userPwd"></td>
<td><input type="password" class="button" name="password" id="password" size="24" maxlength="20" accesskey="p" tabindex="2" value=""/></td>
</tr>
<tr>
<td align="right"> </td>
<td>
<input type="submit" id="lgn_button" class="button" tabindex="3" accesskey="s" />
</td>
Does anyone know how to go about this?
Thanks
A:
Yes, you use mechanize, which a sort of a "webbrowser" for Python. With it you can easily open web pages, find forms, fill in form values and submit the forms from Python. I use it (via Zopes testbrowser module) for testing web applications.
A:
Use urllib2 and create a POST request.
For more information, read:
urllib2: submitting a form and then redirecting
How to make python urllib2 follow redirect and keep post method
How do I send a HTTP POST value to a (PHP) page using Python?.
|
Log onto a Website and select options using Python
|
I am trying to log onto a website using Python. I have written the code to connect to the target but I need to login and select a button on the website and wait for a response. I have looked at the HTTP Protocol in Python and was thinking of using 'HTTPConnection.putrequest'. I am not sure how to do this, I have the code I have so far below:
def testHTTPS(self):
c = httplib.HTTPSConnection(ip)
c.request("GET", "/")
response = c.getresponse()
self.assertEqual(response.status, 200) # '200' is success code
conn.close()
And the code for the logon function on the website is:
<td align="right" id="lgn_userName"></td>
<td><input type="text" class="button" name="username" id="username" size="24" maxlength="16" accesskey="u" tabindex="1" value=""/></td>
</tr>
<tr>
<td align="right" id="lgn_userPwd"></td>
<td><input type="password" class="button" name="password" id="password" size="24" maxlength="20" accesskey="p" tabindex="2" value=""/></td>
</tr>
<tr>
<td align="right"> </td>
<td>
<input type="submit" id="lgn_button" class="button" tabindex="3" accesskey="s" />
</td>
Does anyone know how to go about this?
Thanks
|
[
"Yes, you use mechanize, which a sort of a \"webbrowser\" for Python. With it you can easily open web pages, find forms, fill in form values and submit the forms from Python. I use it (via Zopes testbrowser module) for testing web applications.\n",
"Use urllib2 and create a POST request.\nFor more information, read:\n\nurllib2: submitting a form and then redirecting\nHow to make python urllib2 follow redirect and keep post method\nHow do I send a HTTP POST value to a (PHP) page using Python?.\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"httplib",
"https",
"python",
"web_services"
] |
stackoverflow_0002154095_httplib_https_python_web_services.txt
|
Q:
Reading XML DOCTYPE info with Python
I need to parse a version of an XML file as follows.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE twReport [
<!ELEMENT twReport (twHead?, (twWarn | twDebug | twInfo)*, twBody, twSum?,
twDebug*, twFoot?, twClientInfo?)>
<!ATTLIST twReport version CDATA "10,4"> <----- VERSION INFO HERE
I use xml.dom.minidom for parsing XML file, and I need to parse the version of the XML file written in embedded DTD.
Can I use xml.dom.minidom for this purpose?
Is there any python XML parser for that purposes?
A:
How about xmlproc's DTD api?
Here's a random snippet of code I wrote years and years ago to do some work with DTDs from Python, which might give you an idea of what it's like to work with this library:
from xml.parsers.xmlproc import dtdparser
attr_separator = '_'
child_separator = '_'
dtd = dtdparser.load_dtd('schedule.dtd')
for name, element in dtd.elems.items():
for attr in element.attrlist:
output = '%s%s%s = ' % (name, attr_separator, attr)
print output
for child in element.get_valid_elements(element.get_start_state()):
output = '%s%s%s = ' % (name, child_separator, child)
print output
(FYI, this was the first result when searching for "python dtd parser")
A:
Because both of the the standard library XML libraries (xml.dom.minidom and xml.etree) use the same parser (xml.parsers.expat) you are limited in the "quality" of XML data you are able to successfully parse.
You're better off using the tried-and-true 3rd party modules out there like lxml or BeautifulSoup that are not only more resilient to errors, but will also give you exactly what you are looking for with little trouble.
|
Reading XML DOCTYPE info with Python
|
I need to parse a version of an XML file as follows.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE twReport [
<!ELEMENT twReport (twHead?, (twWarn | twDebug | twInfo)*, twBody, twSum?,
twDebug*, twFoot?, twClientInfo?)>
<!ATTLIST twReport version CDATA "10,4"> <----- VERSION INFO HERE
I use xml.dom.minidom for parsing XML file, and I need to parse the version of the XML file written in embedded DTD.
Can I use xml.dom.minidom for this purpose?
Is there any python XML parser for that purposes?
|
[
"How about xmlproc's DTD api?\nHere's a random snippet of code I wrote years and years ago to do some work with DTDs from Python, which might give you an idea of what it's like to work with this library:\nfrom xml.parsers.xmlproc import dtdparser\n\nattr_separator = '_'\nchild_separator = '_'\n\ndtd = dtdparser.load_dtd('schedule.dtd')\n\nfor name, element in dtd.elems.items():\n for attr in element.attrlist:\n output = '%s%s%s = ' % (name, attr_separator, attr)\n print output\n for child in element.get_valid_elements(element.get_start_state()):\n output = '%s%s%s = ' % (name, child_separator, child)\n print output\n\n(FYI, this was the first result when searching for \"python dtd parser\")\n",
"Because both of the the standard library XML libraries (xml.dom.minidom and xml.etree) use the same parser (xml.parsers.expat) you are limited in the \"quality\" of XML data you are able to successfully parse. \nYou're better off using the tried-and-true 3rd party modules out there like lxml or BeautifulSoup that are not only more resilient to errors, but will also give you exactly what you are looking for with little trouble.\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002147436_python_xml.txt
|
Q:
pygtk: determine key is a modifier
I've got key-press-event handler and i need to determine which kind of key was pressed: modifier or not?
It's not in event.state, because this field works only when modifier was pressed with something else, but i need this for single key (i.e. simply pressing control or alt, ...).
A:
If your version of GTK+/PyGTK is recent enough, key events have a is_modifier attribute. It's not documented in the PyGTK reference, but it's in the GDK API documentation and is exposed through PyGTK. It was added in GDK 2.10.
A:
You'll find what you're looking for in event.keyval. For example, the following code works for me:
def key_press_event(widget, event):
keyname = gtk.gdk.keyval_name(event.keyval)
if "Control" in keyname or "Alt" in keyname:
print "You pressed a modifier!"
|
pygtk: determine key is a modifier
|
I've got key-press-event handler and i need to determine which kind of key was pressed: modifier or not?
It's not in event.state, because this field works only when modifier was pressed with something else, but i need this for single key (i.e. simply pressing control or alt, ...).
|
[
"If your version of GTK+/PyGTK is recent enough, key events have a is_modifier attribute. It's not documented in the PyGTK reference, but it's in the GDK API documentation and is exposed through PyGTK. It was added in GDK 2.10.\n",
"You'll find what you're looking for in event.keyval. For example, the following code works for me:\ndef key_press_event(widget, event):\n keyname = gtk.gdk.keyval_name(event.keyval)\n if \"Control\" in keyname or \"Alt\" in keyname:\n print \"You pressed a modifier!\"\n\n"
] |
[
4,
2
] |
[] |
[] |
[
"gtk",
"pygtk",
"python",
"user_interface"
] |
stackoverflow_0002150159_gtk_pygtk_python_user_interface.txt
|
Q:
python dictionary question
All,
This is the request from the template that i get
u'subjects': [u'7', u'4', u'5', u'3', u'2', u'1']
In my views how to extract the values like 7 4 5 3 2 1
How do i extract the above sequence from
new_subjects=request.POST.get('subjects')
Thanks.
A:
Something like the following:
try:
int_subjects = [int(x) for x in new_subjects]
except ValueError:
#There was an error parsing.
A:
request.POST is an instance of QueryDict which have a method named getlist that returns a list of values for the given key.
Example:
>>> new_subjects = request.POST.getlist('subjects')
>>> print new_subjects
[u'7', u'4', u'5', u'3', u'2', u'1']
See gnibbler's response for converting the list items to integers.
A:
try:
int_subjects = map(int, new_subjects)
except ValueError:
#There was an error parsing.
Using timeit in ipython shows that map is slightly faster than the comprehension in this case
In [99]: timeit map(int,new_subjects)
100000 loops, best of 3: 7.81 µs per loop
In [100]: timeit [int(x) for x in new_subjects]
100000 loops, best of 3: 8.8 µs per loop
|
python dictionary question
|
All,
This is the request from the template that i get
u'subjects': [u'7', u'4', u'5', u'3', u'2', u'1']
In my views how to extract the values like 7 4 5 3 2 1
How do i extract the above sequence from
new_subjects=request.POST.get('subjects')
Thanks.
|
[
"Something like the following:\ntry:\n int_subjects = [int(x) for x in new_subjects]\nexcept ValueError:\n #There was an error parsing.\n\n",
"request.POST is an instance of QueryDict which have a method named getlist that returns a list of values for the given key.\nExample:\n>>> new_subjects = request.POST.getlist('subjects')\n>>> print new_subjects\n[u'7', u'4', u'5', u'3', u'2', u'1']\n\nSee gnibbler's response for converting the list items to integers.\n",
"try:\n int_subjects = map(int, new_subjects)\nexcept ValueError:\n #There was an error parsing.\n\nUsing timeit in ipython shows that map is slightly faster than the comprehension in this case\nIn [99]: timeit map(int,new_subjects)\n100000 loops, best of 3: 7.81 µs per loop\n\nIn [100]: timeit [int(x) for x in new_subjects]\n100000 loops, best of 3: 8.8 µs per loop\n\n"
] |
[
5,
4,
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002155246_django_python.txt
|
Q:
Basics of string based protocol security
I wasn't sure how to phrase this question, so apologies in advance if it's a duplicate of something else.
I wanted to sanity check how I've secured my twisted based application and think I've done a good job at it, but it's been over a decade since I've written anything that uses raw or managed sockets.
Authentication transaction:
Client connects and immediately a challenge response is sent back with a 16 character hex string.
Client side takes user name & password, password is converted sha1( salt + sha1(password)) and credentials are sent back to the server as { username, password }. On the server side, authentication does standard lookup pattern ( if user exists and has password equal to input then grant ).
If the connection between user & client is lost, the protocol class marks itself as dirty and disconnects itself from the user object. Any time after this point, to get access to the user object again, the client would have to repeat the authentication process with a new salt.
Am I missing something? Is there a better/more secure approach for a character stream based protocol?
A:
The protocol you described addresses one attack, that is the a replay attack. However, you are very vulnerable to MITM attacks. The TCP connection won't drop when the attacker moves in on the protocol. Further more anything transferred over this system can be sniffed. If you are on the wireless at a cafe everyone in the area will be able to sniff everything that is transmitted and then MITM the authenticated session. Another point is that sha1() is proven to be insecure you should use sha256 for anything security related.
NEVER REINVENT THE WHEEL, especially when it comes to security.
Use SSL! Everyone uses SSL and it has a LONG history of proven secuirty, and that is something you can't build. SSL Not only solved Man in the Middle Attacks but you can also use Certificates instead of passwords to authenticate both client and server which makes you immune to brute force. The sun will burn out before an attacker can brute force a 2048bit RSA certificate. Father more you don't have to worry about an eve dropper sniffing the transmission.
Keep in mind that OpenSSL is FREE, generating certificates is FREE, and the singing of certificates is FREE. Although the only reason why you would want to sign a certificate is if you want to implement a PKI, which is probably not necessary. The client can have the server's public key hard coded to verify the connection. The server could have a database of client public keys. This system would be self contained and not require OCSP or CRL or any other part of a Public Key Infrastructure.
A:
Your authentication seems solid but prone to man in the middle attacks as it does not ensure the integrity of the connection to the server.
I'd suggest to implement the SRP 6 protocol instead. It is proven to be secure, ensures the integrity of the connection and even creates a common secret that can be used to establish some form symmetric encryption. The protocol looks a bit difficult at first sight but is actually quite easy to implement. There is also a JavaScript Demo available on the project website and links to several implementations in different languages.
|
Basics of string based protocol security
|
I wasn't sure how to phrase this question, so apologies in advance if it's a duplicate of something else.
I wanted to sanity check how I've secured my twisted based application and think I've done a good job at it, but it's been over a decade since I've written anything that uses raw or managed sockets.
Authentication transaction:
Client connects and immediately a challenge response is sent back with a 16 character hex string.
Client side takes user name & password, password is converted sha1( salt + sha1(password)) and credentials are sent back to the server as { username, password }. On the server side, authentication does standard lookup pattern ( if user exists and has password equal to input then grant ).
If the connection between user & client is lost, the protocol class marks itself as dirty and disconnects itself from the user object. Any time after this point, to get access to the user object again, the client would have to repeat the authentication process with a new salt.
Am I missing something? Is there a better/more secure approach for a character stream based protocol?
|
[
"The protocol you described addresses one attack, that is the a replay attack. However, you are very vulnerable to MITM attacks. The TCP connection won't drop when the attacker moves in on the protocol. Further more anything transferred over this system can be sniffed. If you are on the wireless at a cafe everyone in the area will be able to sniff everything that is transmitted and then MITM the authenticated session. Another point is that sha1() is proven to be insecure you should use sha256 for anything security related. \nNEVER REINVENT THE WHEEL, especially when it comes to security.\nUse SSL! Everyone uses SSL and it has a LONG history of proven secuirty, and that is something you can't build. SSL Not only solved Man in the Middle Attacks but you can also use Certificates instead of passwords to authenticate both client and server which makes you immune to brute force. The sun will burn out before an attacker can brute force a 2048bit RSA certificate. Father more you don't have to worry about an eve dropper sniffing the transmission. \nKeep in mind that OpenSSL is FREE, generating certificates is FREE, and the singing of certificates is FREE. Although the only reason why you would want to sign a certificate is if you want to implement a PKI, which is probably not necessary. The client can have the server's public key hard coded to verify the connection. The server could have a database of client public keys. This system would be self contained and not require OCSP or CRL or any other part of a Public Key Infrastructure. \n",
"Your authentication seems solid but prone to man in the middle attacks as it does not ensure the integrity of the connection to the server.\nI'd suggest to implement the SRP 6 protocol instead. It is proven to be secure, ensures the integrity of the connection and even creates a common secret that can be used to establish some form symmetric encryption. The protocol looks a bit difficult at first sight but is actually quite easy to implement. There is also a JavaScript Demo available on the project website and links to several implementations in different languages.\n"
] |
[
6,
1
] |
[] |
[] |
[
"cryptography",
"encryption",
"networking",
"python",
"twisted"
] |
stackoverflow_0002155509_cryptography_encryption_networking_python_twisted.txt
|
Q:
How to launch winpdb from a Python script?
When I have to deal with bugs in Python code, I often insert breakpoints so during execution I'm being dropped into the debuger when a breakpoint is reached. I've been mostly using pdb (command line) and pudb (ncurses interface).
Is it possible to launch winpdb instead in such situation? What's the breakpoint code I shall include in my python script so winpdb would get started?
Edit: I'm using a simple text editor (vim) for writing code. Please do not suggest me to use an IDE instead, which has winpdb integrated or has its own GUI debuger that is similar to winpdb.
A:
Winpdb is normally used so that you run the script with winpdb:
winpdb myscript.py
If you want to start it from "inside" python instead, the documentation on how to do that is here: http://winpdb.org/docs/embedded-debugging/
|
How to launch winpdb from a Python script?
|
When I have to deal with bugs in Python code, I often insert breakpoints so during execution I'm being dropped into the debuger when a breakpoint is reached. I've been mostly using pdb (command line) and pudb (ncurses interface).
Is it possible to launch winpdb instead in such situation? What's the breakpoint code I shall include in my python script so winpdb would get started?
Edit: I'm using a simple text editor (vim) for writing code. Please do not suggest me to use an IDE instead, which has winpdb integrated or has its own GUI debuger that is similar to winpdb.
|
[
"Winpdb is normally used so that you run the script with winpdb:\n winpdb myscript.py\n\nIf you want to start it from \"inside\" python instead, the documentation on how to do that is here: http://winpdb.org/docs/embedded-debugging/\n"
] |
[
4
] |
[] |
[] |
[
"debugging",
"python"
] |
stackoverflow_0002155375_debugging_python.txt
|
Q:
Passing multiple arguments to C function within Python
Let's say I have a c library that manipulates a world somehow.
I want to use this library with python. I want to be able to write simple python scripts that represent different scenarios of world management.
I have functions that create and destroy a world:
void* create(void);
int destroy(void* world);
Here is some python code:
import ctypes
lib = ctypes.CDLL('manage_world.so')
_create = lib.create
_create.restype = ctypes.c_void_p
_destroy = lib.destroy
_destroy.argtypes = [ctypes.c_void_p,]
_destroy.restype = ctypes.c_int
def create_world():
res = _create()
res = ctypes.cast(res, ctypes.c_void_p)
return res
def destroy_world(world):
return _destroy(world)
new_world = create_world()
print type(new_world)
print destroy_world(new_world)
Now I want to add functions like:
int set_world_feature(void* world, feature_t f, ...);
int get_world_feature(void* world, feature_t f, ...);
The thing is that in my python wrapper I don't know how to pass variously multiple arguments.
Because sometimes set_world_feature() is called with 3 or 4 arguments.
In Python again:
def set_world_feature(world, *features):
res = lib.set_world_feature(world, *features)
return world_error[res]
How to fix this in order for it to work?
A:
When you do:
def create_world():
return _create
You don't call _create, so create_world returns the function pointer. If you want the pointer to your world instance you should write instead:
def create_world():
return _create()
|
Passing multiple arguments to C function within Python
|
Let's say I have a c library that manipulates a world somehow.
I want to use this library with python. I want to be able to write simple python scripts that represent different scenarios of world management.
I have functions that create and destroy a world:
void* create(void);
int destroy(void* world);
Here is some python code:
import ctypes
lib = ctypes.CDLL('manage_world.so')
_create = lib.create
_create.restype = ctypes.c_void_p
_destroy = lib.destroy
_destroy.argtypes = [ctypes.c_void_p,]
_destroy.restype = ctypes.c_int
def create_world():
res = _create()
res = ctypes.cast(res, ctypes.c_void_p)
return res
def destroy_world(world):
return _destroy(world)
new_world = create_world()
print type(new_world)
print destroy_world(new_world)
Now I want to add functions like:
int set_world_feature(void* world, feature_t f, ...);
int get_world_feature(void* world, feature_t f, ...);
The thing is that in my python wrapper I don't know how to pass variously multiple arguments.
Because sometimes set_world_feature() is called with 3 or 4 arguments.
In Python again:
def set_world_feature(world, *features):
res = lib.set_world_feature(world, *features)
return world_error[res]
How to fix this in order for it to work?
|
[
"When you do:\ndef create_world():\n return _create\n\nYou don't call _create, so create_world returns the function pointer. If you want the pointer to your world instance you should write instead:\ndef create_world():\n return _create()\n\n"
] |
[
1
] |
[] |
[] |
[
"arguments",
"ctypes",
"python"
] |
stackoverflow_0002155808_arguments_ctypes_python.txt
|
Q:
Python: Need to replace a series of different substrings in HTML template with additional HTML or database results
Situation:
I am writing a basic templating system in Python/mod_python that reads in a main HTML template and replaces instances of ":value:" throughout the document with additional HTML or db results and then returns it as a view to the user.
I am not trying to replace all instances of 1 substring. Values can vary. There is a finite list of what's acceptable. It is not unlimited. The syntax for the values is [colon]value[colon]. Examples might be ":gallery: , :related: , :comments:". The replacement may be additional static HTML or a call to a function. The functions may vary as well.
Question:
What's the most efficient way to read in the main HTML file and replace the unknown combination of values with their appropriate replacement?
Thanks in advance for any thoughts/solutions,
c
A:
There are dozens of templating options that already exist. Consider genshi, mako, jinja2, django templates, or more.
You'll find that you're reinventing the wheel with little/no benefit.
A:
If you can't use an existing templating system for whatever reason, your problem seems best tackled with regular expressions:
import re
valre = re.compile(r':\w+:')
def dosub(correspvals, correspfuns, lastditch):
def f(value):
v = value.group()[1:-1]
if v in correspvals:
return correspvals[v]
if v in correspfuns:
return correspfuns[v]() # or whatever args you need
# what if a value has neither a corresponding value to
# substitute, NOR a function to call? Whatever...:
return lastditch(v)
return f
replacer = dosub(adict, another, somefun)
thehtml = valre.sub(replacer, thehtml)
Basically you'll need two dictionaries (one mapping values to corresponding values, another mapping values to corresponding functions to be called) and a function to be called as a last-ditch attempt for values that can't be found in either dictionary; the code above shows you how to put these things together (I'm using a closure, a class would of course do just as well) and how to apply them for the required replacement task.
A:
This is probably a job for a templating engine and for Python there are a number of choices. In this stackoveflow question people have listed their favourites and some helpfully explain why: What is your single favorite Python templating engine?
|
Python: Need to replace a series of different substrings in HTML template with additional HTML or database results
|
Situation:
I am writing a basic templating system in Python/mod_python that reads in a main HTML template and replaces instances of ":value:" throughout the document with additional HTML or db results and then returns it as a view to the user.
I am not trying to replace all instances of 1 substring. Values can vary. There is a finite list of what's acceptable. It is not unlimited. The syntax for the values is [colon]value[colon]. Examples might be ":gallery: , :related: , :comments:". The replacement may be additional static HTML or a call to a function. The functions may vary as well.
Question:
What's the most efficient way to read in the main HTML file and replace the unknown combination of values with their appropriate replacement?
Thanks in advance for any thoughts/solutions,
c
|
[
"There are dozens of templating options that already exist. Consider genshi, mako, jinja2, django templates, or more.\nYou'll find that you're reinventing the wheel with little/no benefit.\n",
"If you can't use an existing templating system for whatever reason, your problem seems best tackled with regular expressions:\nimport re\n\nvalre = re.compile(r':\\w+:')\n\ndef dosub(correspvals, correspfuns, lastditch):\n def f(value):\n v = value.group()[1:-1]\n if v in correspvals:\n return correspvals[v]\n if v in correspfuns:\n return correspfuns[v]() # or whatever args you need\n # what if a value has neither a corresponding value to\n # substitute, NOR a function to call? Whatever...:\n return lastditch(v)\n return f\n\nreplacer = dosub(adict, another, somefun)\n\nthehtml = valre.sub(replacer, thehtml)\n\nBasically you'll need two dictionaries (one mapping values to corresponding values, another mapping values to corresponding functions to be called) and a function to be called as a last-ditch attempt for values that can't be found in either dictionary; the code above shows you how to put these things together (I'm using a closure, a class would of course do just as well) and how to apply them for the required replacement task.\n",
"This is probably a job for a templating engine and for Python there are a number of choices. In this stackoveflow question people have listed their favourites and some helpfully explain why: What is your single favorite Python templating engine?\n"
] |
[
4,
1,
1
] |
[] |
[] |
[
"mod_python",
"python",
"replace",
"substring",
"templating"
] |
stackoverflow_0002156045_mod_python_python_replace_substring_templating.txt
|
Q:
Downloading a File Protected by NTLM/SSPI Without Prompting For Credentials Using Python on Win32?
I need to download a file on a corporate Sharepoint site using CPython. Existing codebase prevents me from using Ironpython without porting the code, so .NET's WebClient library is out. I also want to download the file without prompting the user to save and without prompting the user for network credentials. I tried other libraries, but they all had short-comings:
urllib2 plus python-ntlm: requires user/pass to be provided
COM automation of Internet Explorer: requires the user to click 'Save'
subprocess using wget or cURL: couldn't get either to authenticate without requesting user/pass
I couldn't find anything in pywin32 that looks like it hooks into urllib2 or provides equivalent functionality. So, is there a way to download the file without requesting credentials and without prompting the user to click 'Save'?
A:
I ended up finding some VB code from a Microsoft support page that uses a function from urlmon.dll I replicated it with a single line of ctypes code and it accomplished exactly what I needed it to do.
ctypes.windll.urlmon.URLDownloadToFileA(0,url,local_file_name,0,0)
url is the location of the resource (in this case, an Excel file on a Sharepoint site)
local_file_name is the local path and name of the file to be saved.
This passed credentials across the wire with no prompts.
|
Downloading a File Protected by NTLM/SSPI Without Prompting For Credentials Using Python on Win32?
|
I need to download a file on a corporate Sharepoint site using CPython. Existing codebase prevents me from using Ironpython without porting the code, so .NET's WebClient library is out. I also want to download the file without prompting the user to save and without prompting the user for network credentials. I tried other libraries, but they all had short-comings:
urllib2 plus python-ntlm: requires user/pass to be provided
COM automation of Internet Explorer: requires the user to click 'Save'
subprocess using wget or cURL: couldn't get either to authenticate without requesting user/pass
I couldn't find anything in pywin32 that looks like it hooks into urllib2 or provides equivalent functionality. So, is there a way to download the file without requesting credentials and without prompting the user to click 'Save'?
|
[
"I ended up finding some VB code from a Microsoft support page that uses a function from urlmon.dll I replicated it with a single line of ctypes code and it accomplished exactly what I needed it to do.\nctypes.windll.urlmon.URLDownloadToFileA(0,url,local_file_name,0,0)\n\n\nurl is the location of the resource (in this case, an Excel file on a Sharepoint site)\nlocal_file_name is the local path and name of the file to be saved.\n\nThis passed credentials across the wire with no prompts.\n"
] |
[
4
] |
[] |
[] |
[
"curl",
"python",
"pywin32",
"winapi"
] |
stackoverflow_0002149496_curl_python_pywin32_winapi.txt
|
Q:
Django thumbnails from urls
I have this Wordpress.com site with thumbnails of themes. I thought about creating a similar site with Django. Instead of using the thumbnail images from the Wordpress gallery as in the page above, I want to have thumbnails of actual blogs. Is there a way to display thumbnails from urls?
Thank you.
A:
There's nothing django-related here, consider this question
How can I take a screenshot/image of a website using Python?
|
Django thumbnails from urls
|
I have this Wordpress.com site with thumbnails of themes. I thought about creating a similar site with Django. Instead of using the thumbnail images from the Wordpress gallery as in the page above, I want to have thumbnails of actual blogs. Is there a way to display thumbnails from urls?
Thank you.
|
[
"There's nothing django-related here, consider this question\nHow can I take a screenshot/image of a website using Python?\n"
] |
[
2
] |
[] |
[] |
[
"python",
"thumbnails"
] |
stackoverflow_0002156553_python_thumbnails.txt
|
Q:
Accessing an attribute using a variable in Python
How do I reference this_prize.left or this_prize.right using a variable?
from collections import namedtuple
import random
Prize = namedtuple("Prize", ["left", "right"])
this_prize = Prize("FirstPrize", "SecondPrize")
if random.random() > .5:
choice = "left"
else:
choice = "right"
# retrieve the value of "left" or "right" depending on the choice
print("You won", this_prize.choice)
AttributeError: 'Prize' object has no attribute 'choice'
A:
The expression this_prize.choice is telling the interpreter that you want to access an attribute of this_prize with the name "choice". But this attribute does not exist in this_prize.
What you actually want is to return the attribute of this_prize identified by the value of choice. So you just need to change your last line using the getattr() method...
from collections import namedtuple
import random
Prize = namedtuple("Prize", ["left", "right" ])
this_prize = Prize("FirstPrize", "SecondPrize")
if random.random() > .5:
choice = "left"
else:
choice = "right"
# retrieve the value of "left" or "right" depending on the choice
print "You won", getattr(this_prize, choice)
A:
getattr(this_prize, choice)
From http://docs.python.org/library/functions.html#getattr:
getattr(object, name) returns the value of the named attribute of object. name must be a string
|
Accessing an attribute using a variable in Python
|
How do I reference this_prize.left or this_prize.right using a variable?
from collections import namedtuple
import random
Prize = namedtuple("Prize", ["left", "right"])
this_prize = Prize("FirstPrize", "SecondPrize")
if random.random() > .5:
choice = "left"
else:
choice = "right"
# retrieve the value of "left" or "right" depending on the choice
print("You won", this_prize.choice)
AttributeError: 'Prize' object has no attribute 'choice'
|
[
"The expression this_prize.choice is telling the interpreter that you want to access an attribute of this_prize with the name \"choice\". But this attribute does not exist in this_prize.\nWhat you actually want is to return the attribute of this_prize identified by the value of choice. So you just need to change your last line using the getattr() method...\nfrom collections import namedtuple\n\nimport random\n\nPrize = namedtuple(\"Prize\", [\"left\", \"right\" ])\n\nthis_prize = Prize(\"FirstPrize\", \"SecondPrize\")\n\nif random.random() > .5:\n choice = \"left\"\nelse:\n choice = \"right\"\n\n# retrieve the value of \"left\" or \"right\" depending on the choice\n\nprint \"You won\", getattr(this_prize, choice)\n\n",
"getattr(this_prize, choice)\n\nFrom http://docs.python.org/library/functions.html#getattr:\n\ngetattr(object, name) returns the value of the named attribute of object. name must be a string\n\n"
] |
[
105,
101
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002157035_python.txt
|
Q:
Google App Engine Patch - How to use stylesheets?
Struggling with an install of GAE-Patch and using my stylesheets. My settings.py has the following lines included already, but the media generator is not compiling and packaging it properly:
'combined-%(LANGUAGE_DIR)s.css': (
'global/look.css',
),
'combined-%(LANGUAGE_DIR)s.css': (
'global/base-%(LANGUAGE_DIR)s.css',
'owr/main.css',
),
and
INSTALLED_APPS = (
'owr',
)
Where is the stylesheet supposed to go, in which folder? Under owr/media?
A:
You should look at the app.yaml file:
It should look like this:
handlers:
- url: /media
static_dir: _generated_media
This means that you need to put your css, etc in the _generated_media folder.
|
Google App Engine Patch - How to use stylesheets?
|
Struggling with an install of GAE-Patch and using my stylesheets. My settings.py has the following lines included already, but the media generator is not compiling and packaging it properly:
'combined-%(LANGUAGE_DIR)s.css': (
'global/look.css',
),
'combined-%(LANGUAGE_DIR)s.css': (
'global/base-%(LANGUAGE_DIR)s.css',
'owr/main.css',
),
and
INSTALLED_APPS = (
'owr',
)
Where is the stylesheet supposed to go, in which folder? Under owr/media?
|
[
"You should look at the app.yaml file:\nIt should look like this:\nhandlers:\n- url: /media\n static_dir: _generated_media\n\nThis means that you need to put your css, etc in the _generated_media folder.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"google_app_engine",
"python"
] |
stackoverflow_0002151776_django_google_app_engine_python.txt
|
Q:
Use getControl to control objects other than the name variable
I am using the Zope testbrowser which has been recommended in my last question. The problem that I am facing is that I can use the getControl function to control different objects like: password, username etc.
I am trying to submit the page to get to the next page but the submit button has no 'name' variable, just an 'id' variable. 'Submit' is written as follows:
<input type="submit" id="lgn_button" class="button" tabindex="3" accesskey="s" />
and the other objects are written as:
<input type="password" class="button" name="password" id="password" size="24" maxlength="20" accesskey="p" tabindex="2" value=""/></td>
I have no access to change this. The python zope code I am using to gain control of the 'password' object is:
browser.getControl(name='password')
The submit button doesn't have 'name' so I have written:
browser.getControl(id='lgn_button')
This prints out the error that 'id' is invalid:
TypeError: getControl() got an unexpected keyword argument 'id'
Is there any way to gain control of one of the other values in 'submit'.
Thanks for any help.
A:
I assume that, for one reason or another, you can't add a 'name' attribute to your tag, but if it's only a 'name' that you can't add, you can explicitly set a 'value=Submit' (instead of relying on the default one, which is Submit) and then use browser.getControl('Submit')
Failing that, you can do something along the lines of
for form in browser.mech_browser.forms():
for control in form.controls:
if control.id == 'lgn_button':
return control
You might even want to extend Browser.getControl() with that and contribute it back to zope.testbrowser. ;)
|
Use getControl to control objects other than the name variable
|
I am using the Zope testbrowser which has been recommended in my last question. The problem that I am facing is that I can use the getControl function to control different objects like: password, username etc.
I am trying to submit the page to get to the next page but the submit button has no 'name' variable, just an 'id' variable. 'Submit' is written as follows:
<input type="submit" id="lgn_button" class="button" tabindex="3" accesskey="s" />
and the other objects are written as:
<input type="password" class="button" name="password" id="password" size="24" maxlength="20" accesskey="p" tabindex="2" value=""/></td>
I have no access to change this. The python zope code I am using to gain control of the 'password' object is:
browser.getControl(name='password')
The submit button doesn't have 'name' so I have written:
browser.getControl(id='lgn_button')
This prints out the error that 'id' is invalid:
TypeError: getControl() got an unexpected keyword argument 'id'
Is there any way to gain control of one of the other values in 'submit'.
Thanks for any help.
|
[
"I assume that, for one reason or another, you can't add a 'name' attribute to your tag, but if it's only a 'name' that you can't add, you can explicitly set a 'value=Submit' (instead of relying on the default one, which is Submit) and then use browser.getControl('Submit')\nFailing that, you can do something along the lines of\n\nfor form in browser.mech_browser.forms():\n for control in form.controls:\n if control.id == 'lgn_button':\n return control\n\nYou might even want to extend Browser.getControl() with that and contribute it back to zope.testbrowser. ;)\n"
] |
[
0
] |
[] |
[] |
[
"https",
"mechanize",
"python",
"testing",
"zope"
] |
stackoverflow_0002155403_https_mechanize_python_testing_zope.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.