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:
Not able to pass multiple override parameters using nose-testconfig 0.6 plugin in nosetests
I am able to override multiple config parameters using the nose-testconfig plugin only if I pass the overriding parameters on the command line, e.g.
nosetests -c nose.cfg -s --tc=jack.env1:asl --tc=server2.env2:abc
But when I define the same thing inside nose.cfg, than only the value for the last parameter is modified. e.g.
tc = server2.env2:abc
tc = jack.env1:asl
I checked the plugin code. It looks fine to me. Here is part of the plugin code:
parser.add_option(
"--tc", action="append",
dest="overrides",
default = [],
help="Option:Value specific overrides.")
configure:
if options.overrides:
self.overrides = []
overrides = tolist(options.overrides)
for override in overrides:
keys, val = override.split(":")
if options.exact:
config[keys] = val
else:
ns = ''.join(['["%s"]' % i for i in keys.split(".") ])
# BUG: Breaks if the config value you're overriding is not
# defined in the configuration file already. TBD
exec('config%s = "%s"' % (ns, val))
Let me know if any one has any clue.
A:
Please find my nose.cfg file below:
[nosetests]
verbosity=2
tc-file = setup_config.py
tc-format = python
all-modules = True
tc = server2.env2:abc
tc = jack.env1:asl
and my config file looks like:
[server2]
env2=server2
[jack]
env1=server1
In the above example only jack.env1:as1 value is effective (i.e last value). But when I specify the same on command line than both values are effective
| Not able to pass multiple override parameters using nose-testconfig 0.6 plugin in nosetests | I am able to override multiple config parameters using the nose-testconfig plugin only if I pass the overriding parameters on the command line, e.g.
nosetests -c nose.cfg -s --tc=jack.env1:asl --tc=server2.env2:abc
But when I define the same thing inside nose.cfg, than only the value for the last parameter is modified. e.g.
tc = server2.env2:abc
tc = jack.env1:asl
I checked the plugin code. It looks fine to me. Here is part of the plugin code:
parser.add_option(
"--tc", action="append",
dest="overrides",
default = [],
help="Option:Value specific overrides.")
configure:
if options.overrides:
self.overrides = []
overrides = tolist(options.overrides)
for override in overrides:
keys, val = override.split(":")
if options.exact:
config[keys] = val
else:
ns = ''.join(['["%s"]' % i for i in keys.split(".") ])
# BUG: Breaks if the config value you're overriding is not
# defined in the configuration file already. TBD
exec('config%s = "%s"' % (ns, val))
Let me know if any one has any clue.
| [
"Please find my nose.cfg file below:\n[nosetests]\nverbosity=2\n\ntc-file = setup_config.py\n\ntc-format = python\n\nall-modules = True\n\ntc = server2.env2:abc\n\ntc = jack.env1:asl\n\n\nand my config file looks like:\n[server2]\n\nenv2=server2\n\n[jack]\n\nenv1=server1\n\n\nIn the above example only jack.env1:as1 value is effective (i.e last value). But when I specify the same on command line than both values are effective\n"
] | [
0
] | [] | [] | [
"nosetests",
"python"
] | stackoverflow_0002886590_nosetests_python.txt |
Q:
Queue remote calls to a Python Twisted perspective broker?
The strength of Twisted (for python) is its asynchronous framework (I think). I've written an image processing server that takes requests via Perspective Broker. It works great as long as I feed it less than a couple hundred images at a time. However, sometimes it gets spiked with hundreds of images at virtually the same time. Because it tries to process them all concurrently the server crashes.
As a solution I'd like to queue up the remote_calls on the server so that it only processes ~100 images at a time. It seems like this might be something that Twisted already does, but I can't seem to find it. Any ideas on how to start implementing this? A point in the right direction? Thanks!
A:
One ready-made option that might help with this is twisted.internet.defer.DeferredSemaphore. This is the asynchronous version of the normal (counting) semaphore you might already know if you've done much threaded programming.
A (counting) semaphore is a lot like a mutex (a lock). But where a mutex can only be acquired once until a corresponding release, a (counting) semaphore can be configured to allow an arbitrary (but specified) number of acquisitions to succeed before any corresponding releases are required.
Here's an example of using DeferredSemaphore to run ten asynchronous operations, but to run at most three of them at once:
from twisted.internet.defer import DeferredSemaphore, gatherResults
from twisted.internet.task import deferLater
from twisted.internet import reactor
def async(n):
print 'Starting job', n
d = deferLater(reactor, n, lambda: None)
def cbFinished(ignored):
print 'Finishing job', n
d.addCallback(cbFinished)
return d
def main():
sem = DeferredSemaphore(3)
jobs = []
for i in range(10):
jobs.append(sem.run(async, i))
d = gatherResults(jobs)
d.addCallback(lambda ignored: reactor.stop())
reactor.run()
if __name__ == '__main__':
main()
DeferredSemaphore also has explicit acquire and release methods, but the run method is so convenient it's almost always what you want. It calls the acquire method, which returns a Deferred. To that first Deferred, it adds a callback which calls the function you passed in (along with any positional or keyword arguments). If that function returns a Deferred, then to that second Deferred a callback is added which calls the release method.
The synchronous case is handled as well, by immediately calling release. Errors are also handled, by allowing them to propagate but making sure the necessary release is done to leave the DeferredSemaphore in a consistent state. The result of the function passed to run (or the result of the Deferred it returns) becomes the result of the Deferred returned by run.
Another possible approach might be based on DeferredQueue and cooperate. DeferredQueue is mostly like a normal queue, but its get method returns a Deferred. If there happen to be no items in the queue at the time of the call, the Deferred will not fire until an item is added.
Here's an example:
from random import randrange
from twisted.internet.defer import DeferredQueue
from twisted.internet.task import deferLater, cooperate
from twisted.internet import reactor
def async(n):
print 'Starting job', n
d = deferLater(reactor, n, lambda: None)
def cbFinished(ignored):
print 'Finishing job', n
d.addCallback(cbFinished)
return d
def assign(jobs):
# Create new jobs to be processed
jobs.put(randrange(10))
reactor.callLater(randrange(10), assign, jobs)
def worker(jobs):
while True:
yield jobs.get().addCallback(async)
def main():
jobs = DeferredQueue()
for i in range(10):
jobs.put(i)
assign(jobs)
for i in range(3):
cooperate(worker(jobs))
reactor.run()
if __name__ == '__main__':
main()
Note that the async worker function is the same as the one from the first example. However, this time, there's also a worker function which is explicitly pulling jobs out of the DeferredQueue and processing them with async (by adding async as a callback to the Deferred returned by get). The worker generator is driven by cooperate, which iterates it once after each Deferred it yields fires. The main loop, then, starts three of these worker generators so that three jobs will be in progress at any given time.
This approach involves a bit more code than the DeferredSemaphore approach, but has some benefits which may be interesting. First, cooperate returns a CooperativeTask instance which has useful methods like pause, resume, and a couple others. Also, all jobs assigned to the same cooperator will cooperate with each other in scheduling, so as not to overload the event loop (and this is what gives the API its name). On the DeferredQueue side, it's also possible to set limits on how many items are pending processing, so you can avoid completely overloading your server (for example, if your image processors get stuck and stop completing tasks). If the code calling put handles the queue overflow exception, you can use this as pressure to try to stop accepting new jobs (perhaps shunting them to another server, or alerting an administrator). Doing similar things with DeferredSemaphore is a bit trickier, since there's no way to limit how many jobs are waiting to be able to acquire the semaphore.
| Queue remote calls to a Python Twisted perspective broker? | The strength of Twisted (for python) is its asynchronous framework (I think). I've written an image processing server that takes requests via Perspective Broker. It works great as long as I feed it less than a couple hundred images at a time. However, sometimes it gets spiked with hundreds of images at virtually the same time. Because it tries to process them all concurrently the server crashes.
As a solution I'd like to queue up the remote_calls on the server so that it only processes ~100 images at a time. It seems like this might be something that Twisted already does, but I can't seem to find it. Any ideas on how to start implementing this? A point in the right direction? Thanks!
| [
"One ready-made option that might help with this is twisted.internet.defer.DeferredSemaphore. This is the asynchronous version of the normal (counting) semaphore you might already know if you've done much threaded programming.\nA (counting) semaphore is a lot like a mutex (a lock). But where a mutex can only be acquired once until a corresponding release, a (counting) semaphore can be configured to allow an arbitrary (but specified) number of acquisitions to succeed before any corresponding releases are required.\nHere's an example of using DeferredSemaphore to run ten asynchronous operations, but to run at most three of them at once:\nfrom twisted.internet.defer import DeferredSemaphore, gatherResults\nfrom twisted.internet.task import deferLater\nfrom twisted.internet import reactor\n\n\ndef async(n):\n print 'Starting job', n\n d = deferLater(reactor, n, lambda: None)\n def cbFinished(ignored):\n print 'Finishing job', n\n d.addCallback(cbFinished)\n return d\n\n\ndef main():\n sem = DeferredSemaphore(3)\n\n jobs = []\n for i in range(10):\n jobs.append(sem.run(async, i))\n\n d = gatherResults(jobs)\n d.addCallback(lambda ignored: reactor.stop())\n reactor.run()\n\n\nif __name__ == '__main__':\n main()\n\nDeferredSemaphore also has explicit acquire and release methods, but the run method is so convenient it's almost always what you want. It calls the acquire method, which returns a Deferred. To that first Deferred, it adds a callback which calls the function you passed in (along with any positional or keyword arguments). If that function returns a Deferred, then to that second Deferred a callback is added which calls the release method.\nThe synchronous case is handled as well, by immediately calling release. Errors are also handled, by allowing them to propagate but making sure the necessary release is done to leave the DeferredSemaphore in a consistent state. The result of the function passed to run (or the result of the Deferred it returns) becomes the result of the Deferred returned by run.\nAnother possible approach might be based on DeferredQueue and cooperate. DeferredQueue is mostly like a normal queue, but its get method returns a Deferred. If there happen to be no items in the queue at the time of the call, the Deferred will not fire until an item is added.\nHere's an example:\nfrom random import randrange\n\nfrom twisted.internet.defer import DeferredQueue\nfrom twisted.internet.task import deferLater, cooperate\nfrom twisted.internet import reactor\n\n\ndef async(n):\n print 'Starting job', n\n d = deferLater(reactor, n, lambda: None)\n def cbFinished(ignored):\n print 'Finishing job', n\n d.addCallback(cbFinished)\n return d\n\n\ndef assign(jobs):\n # Create new jobs to be processed\n jobs.put(randrange(10))\n reactor.callLater(randrange(10), assign, jobs)\n\n\ndef worker(jobs):\n while True:\n yield jobs.get().addCallback(async)\n\n\ndef main():\n jobs = DeferredQueue()\n\n for i in range(10):\n jobs.put(i)\n\n assign(jobs)\n\n for i in range(3):\n cooperate(worker(jobs))\n\n reactor.run()\n\n\nif __name__ == '__main__':\n main()\n\nNote that the async worker function is the same as the one from the first example. However, this time, there's also a worker function which is explicitly pulling jobs out of the DeferredQueue and processing them with async (by adding async as a callback to the Deferred returned by get). The worker generator is driven by cooperate, which iterates it once after each Deferred it yields fires. The main loop, then, starts three of these worker generators so that three jobs will be in progress at any given time.\nThis approach involves a bit more code than the DeferredSemaphore approach, but has some benefits which may be interesting. First, cooperate returns a CooperativeTask instance which has useful methods like pause, resume, and a couple others. Also, all jobs assigned to the same cooperator will cooperate with each other in scheduling, so as not to overload the event loop (and this is what gives the API its name). On the DeferredQueue side, it's also possible to set limits on how many items are pending processing, so you can avoid completely overloading your server (for example, if your image processors get stuck and stop completing tasks). If the code calling put handles the queue overflow exception, you can use this as pressure to try to stop accepting new jobs (perhaps shunting them to another server, or alerting an administrator). Doing similar things with DeferredSemaphore is a bit trickier, since there's no way to limit how many jobs are waiting to be able to acquire the semaphore.\n"
] | [
29
] | [
"You might also like the txRDQ (Resizable Dispatch Queue) I wrote. Google it, it's in the tx collection on LaunchPad. Sorry I don't have more time to reply - about to go onstage.\nTerry\n"
] | [
-2
] | [
"asynchronous",
"python",
"twisted"
] | stackoverflow_0002861858_asynchronous_python_twisted.txt |
Q:
What mock object framework should I use when developing in Python on the Google App Engine?
I am developing an application on the Google App Engine using Python (and Django, if that matters).
Which mock object framework should I help to assist with unit tests? I see there are a number of standalone projects (i.e. http://python-mock.sourceforge.net), but I'm not sure if there's something built-in that I can use.
Any ideas?
A:
We use this mock library extensively and very happy with it. It is small, simple and expressive.
And yes, there is no mock-framework in the standard Python library.
| What mock object framework should I use when developing in Python on the Google App Engine? | I am developing an application on the Google App Engine using Python (and Django, if that matters).
Which mock object framework should I help to assist with unit tests? I see there are a number of standalone projects (i.e. http://python-mock.sourceforge.net), but I'm not sure if there's something built-in that I can use.
Any ideas?
| [
"We use this mock library extensively and very happy with it. It is small, simple and expressive.\nAnd yes, there is no mock-framework in the standard Python library.\n"
] | [
4
] | [] | [] | [
"django",
"google_app_engine",
"mocking",
"python"
] | stackoverflow_0002899303_django_google_app_engine_mocking_python.txt |
Q:
Python problem with resize animate GIF
I'm want to resize animated GIF with save animate. I'm try use PIL and PythonMagickWand (ImageMagick) and with some GIF's get bad frame. When I'm use PIL, it mar frame in read frame. For test, I'm use this code:
from PIL import Image
im = Image.open('d:/box_opens_closes.gif')
im.seek(im.tell()+1)
im.seek(im.tell()+1)
im.seek(im.tell()+1)
im.show()
When I'm use MagickWand with this code:
wand = NewMagickWand()
MagickReadImage(wand, 'd:/Box_opens_closes.gif')
MagickSetLastIterator(wand)
length = MagickGetIteratorIndex(wand)
MagickSetFirstIterator(wand)
for i in range(0, length+1):
MagickSetIteratorIndex(wand,i)
MagickScaleImage(wand, 87, 58)
MagickWriteImages(wand, 'path', 1)
My GIF where I'm get bad frame this: test gif
In GIF editor software, all frames are ok. Where is the problem? Thanks.
A:
I'm complete this. Must use:
wand2 = MagickCoalesceImages(wand)
MagickWriteImages(wand2, 'save_path', 1)
| Python problem with resize animate GIF | I'm want to resize animated GIF with save animate. I'm try use PIL and PythonMagickWand (ImageMagick) and with some GIF's get bad frame. When I'm use PIL, it mar frame in read frame. For test, I'm use this code:
from PIL import Image
im = Image.open('d:/box_opens_closes.gif')
im.seek(im.tell()+1)
im.seek(im.tell()+1)
im.seek(im.tell()+1)
im.show()
When I'm use MagickWand with this code:
wand = NewMagickWand()
MagickReadImage(wand, 'd:/Box_opens_closes.gif')
MagickSetLastIterator(wand)
length = MagickGetIteratorIndex(wand)
MagickSetFirstIterator(wand)
for i in range(0, length+1):
MagickSetIteratorIndex(wand,i)
MagickScaleImage(wand, 87, 58)
MagickWriteImages(wand, 'path', 1)
My GIF where I'm get bad frame this: test gif
In GIF editor software, all frames are ok. Where is the problem? Thanks.
| [
"I'm complete this. Must use:\n\nwand2 = MagickCoalesceImages(wand)\nMagickWriteImages(wand2, 'save_path', 1)\n\n"
] | [
0
] | [] | [] | [
"animation",
"gif",
"python",
"python_imaging_library"
] | stackoverflow_0002896031_animation_gif_python_python_imaging_library.txt |
Q:
Getting rid of the encoding in lxml
I am trying to print a XML file using lxml and Python.
Here is the code:
>>> from lxml import etree
>>> root = etree.Element('root')
>>> child = etree.SubElement(root, 'child')
>>> print etree.tostring(root, pretty_print = True, xml_declaration = True, encoding = None)
Output:
<?xml version='1.0' encoding='ASCII'?>
<root>
<child/>
</root>
As you can see, I have declared encoding = None, however it still shows encoding = 'ASCII' in the final output. Which I guess is expected. If I don't put in the encoding tag, it still shows ASCII.
Is there any way I can just get the XML version tag and not the encoding part? I want the output to be like this:
<?xml version='1.0'>
A:
It shouldn't matter what lxml.etree outputs as long as it's valid XML. If you really want to, you can glue strings together:
'<?xml version="1.0"?>\n' + etree.tostring(root, pretty_print = True, encoding = 'ASCII')
It's unclear why you want to remove it, since ultimately XML needs to know what charset it's in to make sense of anything. The XML 1.0 spec includes a method of guessing charsets, and seems to encourage the use of encoding declarations:
In the absence of [external information], it is a fatal error ... for an entity which begins with neither a Byte Order Mark nor an encoding declaration to use an encoding other than UTF-8.
...
Unless an encoding is determined by a higher-level protocol, it is also a fatal error if an XML entity contains no encoding declaration and its content is not legal UTF-8 or UTF-16.
| Getting rid of the encoding in lxml | I am trying to print a XML file using lxml and Python.
Here is the code:
>>> from lxml import etree
>>> root = etree.Element('root')
>>> child = etree.SubElement(root, 'child')
>>> print etree.tostring(root, pretty_print = True, xml_declaration = True, encoding = None)
Output:
<?xml version='1.0' encoding='ASCII'?>
<root>
<child/>
</root>
As you can see, I have declared encoding = None, however it still shows encoding = 'ASCII' in the final output. Which I guess is expected. If I don't put in the encoding tag, it still shows ASCII.
Is there any way I can just get the XML version tag and not the encoding part? I want the output to be like this:
<?xml version='1.0'>
| [
"It shouldn't matter what lxml.etree outputs as long as it's valid XML. If you really want to, you can glue strings together:\n'<?xml version=\"1.0\"?>\\n' + etree.tostring(root, pretty_print = True, encoding = 'ASCII')\n\nIt's unclear why you want to remove it, since ultimately XML needs to know what charset it's in to make sense of anything. The XML 1.0 spec includes a method of guessing charsets, and seems to encourage the use of encoding declarations:\n\nIn the absence of [external information], it is a fatal error ... for an entity which begins with neither a Byte Order Mark nor an encoding declaration to use an encoding other than UTF-8.\n...\nUnless an encoding is determined by a higher-level protocol, it is also a fatal error if an XML entity contains no encoding declaration and its content is not legal UTF-8 or UTF-16.\n\n"
] | [
-3
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0002899425_lxml_python.txt |
Q:
Constructor does weird things with optional parameters
Possible Duplicate:
least astonishment in python: the mutable default argument
I want to understand of the behavior and implications of the python __init__ constructor. It seems like when there is an optional parameter and you try and set an existing object to a new object the optional value of the existing object is preserved and copied.
Look at an example:
In the code below I am trying to make a tree structure with nodes and possibly many children . In the first class NodeBad, the constructor has two parameters, the value and any possible children. The second class NodeGood only takes the value of the node as a parameter. Both have an addchild method to add a child to a node.
When creating a tree with the NodeGood class, it works as expected. However, when doing the same thing with the NodeBad class, it seems as though a child can only be added once!
The code below will result in the following output:
Good Tree
1
2
3
[< 3 >]
Bad Tree
1
2
2
[< 2 >, < 3 >]
Que Pasa?
Here is the Example:
#!/usr/bin/python
class NodeBad:
def __init__(self, value, c=[]):
self.value = value
self.children = c
def addchild(self, node):
self.children.append(node)
def __str__(self):
return '< %s >' % self.value
def __repr__(self):
return '< %s >' % self.value
class NodeGood:
def __init__(self, value):
self.value = value
self.children = []
def addchild(self, node):
self.children.append(node)
def __str__(self):
return '< %s >' % self.value
def __repr__(self):
return '< %s >' % self.value
if __name__ == '__main__':
print 'Good Tree'
ng = NodeGood(1) # Root Node
rootgood = ng
ng.addchild(NodeGood(2)) # 1nd Child
ng = ng.children[0]
ng.addchild(NodeGood(3)) # 2nd Child
print rootgood.value
print rootgood.children[0].value
print rootgood.children[0].children[0].value
print rootgood.children[0].children
print 'Bad Tree'
nb = NodeBad(1) # Root Node
rootbad = nb
nb.addchild(NodeBad(2)) # 1st Child
nb = nb.children[0]
nb.addchild(NodeBad(3)) # 2nd Child
print rootbad.value
print rootbad.children[0].value
print rootbad.children[0].children[0].value
print rootbad.children[0].children
A:
The problem is, the default value of an optional argument is only a single instance. So for example, if you say def __init__(self, value, c=[]):, that same list [] will be passed into the method each time an optional argument is used by calling code.
So basically you should only use immutable date types such as None for the default value of an optional argument. For example:
def __init__(self, value, c=None):
Then you could just create a new list in the method body:
if c == None:
c = []
A:
Mutable default arguments are a source of confusion.
See this answer: "Least Astonishment" and the Mutable Default Argument
| Constructor does weird things with optional parameters |
Possible Duplicate:
least astonishment in python: the mutable default argument
I want to understand of the behavior and implications of the python __init__ constructor. It seems like when there is an optional parameter and you try and set an existing object to a new object the optional value of the existing object is preserved and copied.
Look at an example:
In the code below I am trying to make a tree structure with nodes and possibly many children . In the first class NodeBad, the constructor has two parameters, the value and any possible children. The second class NodeGood only takes the value of the node as a parameter. Both have an addchild method to add a child to a node.
When creating a tree with the NodeGood class, it works as expected. However, when doing the same thing with the NodeBad class, it seems as though a child can only be added once!
The code below will result in the following output:
Good Tree
1
2
3
[< 3 >]
Bad Tree
1
2
2
[< 2 >, < 3 >]
Que Pasa?
Here is the Example:
#!/usr/bin/python
class NodeBad:
def __init__(self, value, c=[]):
self.value = value
self.children = c
def addchild(self, node):
self.children.append(node)
def __str__(self):
return '< %s >' % self.value
def __repr__(self):
return '< %s >' % self.value
class NodeGood:
def __init__(self, value):
self.value = value
self.children = []
def addchild(self, node):
self.children.append(node)
def __str__(self):
return '< %s >' % self.value
def __repr__(self):
return '< %s >' % self.value
if __name__ == '__main__':
print 'Good Tree'
ng = NodeGood(1) # Root Node
rootgood = ng
ng.addchild(NodeGood(2)) # 1nd Child
ng = ng.children[0]
ng.addchild(NodeGood(3)) # 2nd Child
print rootgood.value
print rootgood.children[0].value
print rootgood.children[0].children[0].value
print rootgood.children[0].children
print 'Bad Tree'
nb = NodeBad(1) # Root Node
rootbad = nb
nb.addchild(NodeBad(2)) # 1st Child
nb = nb.children[0]
nb.addchild(NodeBad(3)) # 2nd Child
print rootbad.value
print rootbad.children[0].value
print rootbad.children[0].children[0].value
print rootbad.children[0].children
| [
"The problem is, the default value of an optional argument is only a single instance. So for example, if you say def __init__(self, value, c=[]):, that same list [] will be passed into the method each time an optional argument is used by calling code. \nSo basically you should only use immutable date types such as None for the default value of an optional argument. For example:\ndef __init__(self, value, c=None):\n\nThen you could just create a new list in the method body:\nif c == None:\n c = []\n\n",
"Mutable default arguments are a source of confusion.\nSee this answer: \"Least Astonishment\" and the Mutable Default Argument\n"
] | [
17,
3
] | [] | [] | [
"constructor",
"optional_parameters",
"python"
] | stackoverflow_0002899643_constructor_optional_parameters_python.txt |
Q:
Inlines in Django Admin
I have two models, Order and UserProfile. Each Order has a ForeignKey to UserProfile, to associate it with that user.
On the django admin page for each Order, I'd like to display the UserProfile associated with it, for easy processing of information.
I have tried inlines:
class UserInline(admin.TabularInline):
model = UserProfile
class ValuationRequestAdmin(admin.ModelAdmin):
list_display = ('address1', 'address2', 'town', 'date_added')
list_filter = ('town', 'date_added')
ordering = ('-date_updated',)
inlines = [
UserInline,
]
But it complains that UserProfile "has no ForeignKey to" Order - which it doesn't, it's the other way around.
Is there a way to do what I want?
A:
How about making the UserProfile read only? Django Foreign Keys Read Only
There are other ideas in this post also.
| Inlines in Django Admin | I have two models, Order and UserProfile. Each Order has a ForeignKey to UserProfile, to associate it with that user.
On the django admin page for each Order, I'd like to display the UserProfile associated with it, for easy processing of information.
I have tried inlines:
class UserInline(admin.TabularInline):
model = UserProfile
class ValuationRequestAdmin(admin.ModelAdmin):
list_display = ('address1', 'address2', 'town', 'date_added')
list_filter = ('town', 'date_added')
ordering = ('-date_updated',)
inlines = [
UserInline,
]
But it complains that UserProfile "has no ForeignKey to" Order - which it doesn't, it's the other way around.
Is there a way to do what I want?
| [
"How about making the UserProfile read only? Django Foreign Keys Read Only\nThere are other ideas in this post also. \n"
] | [
1
] | [] | [] | [
"admin",
"django",
"inlines",
"python"
] | stackoverflow_0002898547_admin_django_inlines_python.txt |
Q:
Python - Strange Behavior in re.sub
Here's the code I'm running:
import re
FIND_TERM = r'C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec\.exe'
rfind_term = re.compile(FIND_TERM,re.I)
REPLACE_TERM = 'C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\DTExec.exe'
test = r'something C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTExec.exe something'
print rfind_term.sub(REPLACE_TERM,test)
And the result I get is:
something C:\Program Files\Microsoft SQL Server@\DTS\Binn\DTExec.exe something
Why is there an @ sign?
A:
You're mixing raw ( r'' ) and normal strings.
>>> FIND_TERM = r'C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec\.exe'
>>> REPLACE_TERM = r'C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\DTExec.exe'
>>> rfind_term = re.compile(FIND_TERM,re.I)
>>> test = r'something C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTExec.exe something'
>>> print rfind_term.sub(REPLACE_TERM,test)
something C:\Program Files\Microsoft SQL Server\100\DTS\Binn\DTExec.exe something
A:
The RE engine is treating the \100 in REPLACE_TERM as an octal escape code. You need to escape the backslash so that it's treated as desired.
| Python - Strange Behavior in re.sub | Here's the code I'm running:
import re
FIND_TERM = r'C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec\.exe'
rfind_term = re.compile(FIND_TERM,re.I)
REPLACE_TERM = 'C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\DTExec.exe'
test = r'something C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTExec.exe something'
print rfind_term.sub(REPLACE_TERM,test)
And the result I get is:
something C:\Program Files\Microsoft SQL Server@\DTS\Binn\DTExec.exe something
Why is there an @ sign?
| [
"You're mixing raw ( r'' ) and normal strings.\n>>> FIND_TERM = r'C:\\\\Program Files\\\\Microsoft SQL Server\\\\90\\\\DTS\\\\Binn\\\\DTExec\\.exe'\n>>> REPLACE_TERM = r'C:\\\\Program Files\\\\Microsoft SQL Server\\\\100\\\\DTS\\\\Binn\\\\DTExec.exe' \n>>> rfind_term = re.compile(FIND_TERM,re.I)\n>>> test = r'something C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec.exe something'\n>>> print rfind_term.sub(REPLACE_TERM,test) \nsomething C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\DTExec.exe something\n\n",
"The RE engine is treating the \\100 in REPLACE_TERM as an octal escape code. You need to escape the backslash so that it's treated as desired.\n"
] | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002899805_python_regex.txt |
Q:
cherrypy keeps object between page update
i'm writing web-server that responds me with a list of files in some folder:
test_folder = 'somefolder'
class TestLoader(object):
data = []
index = 0
def __init__(self, dir):
for sub in os.listdir(dir):
self.data.append(sub)
class TesterServer(object):
@cherrypy.expose
def index(self):
return "Test server works!"
@cherrypy.expose
def test(self):
tm = helper.TestManager(test_folder)
msg = ''
for i in tm:
msg += "\t %s" % i
return msg
cherrypy.quickstart(TesterServer())
The problem is: when i'm reloading page, the data on are being duplicated, not refreshed.
i.e.:
page load: aaa bsbt bstat bump.py cherry.py helper.py
page reload: aaa bsbt bstat bump.py cherry.py helper.py aaa bsbt bstat bump.py cherry.py helper.py
page reload #2: aaa bsbt bstat bump.py cherry.py helper.py aaa bsbt bstat bump.py cherry.py helper.py aaa bsbt bstat bump.py cherry.py helper.py
etcetera
What am i doing wrong?
Thanks in advance
A:
You've made data a class attribute. Assign in __init__() instead.
self.data = []
| cherrypy keeps object between page update | i'm writing web-server that responds me with a list of files in some folder:
test_folder = 'somefolder'
class TestLoader(object):
data = []
index = 0
def __init__(self, dir):
for sub in os.listdir(dir):
self.data.append(sub)
class TesterServer(object):
@cherrypy.expose
def index(self):
return "Test server works!"
@cherrypy.expose
def test(self):
tm = helper.TestManager(test_folder)
msg = ''
for i in tm:
msg += "\t %s" % i
return msg
cherrypy.quickstart(TesterServer())
The problem is: when i'm reloading page, the data on are being duplicated, not refreshed.
i.e.:
page load: aaa bsbt bstat bump.py cherry.py helper.py
page reload: aaa bsbt bstat bump.py cherry.py helper.py aaa bsbt bstat bump.py cherry.py helper.py
page reload #2: aaa bsbt bstat bump.py cherry.py helper.py aaa bsbt bstat bump.py cherry.py helper.py aaa bsbt bstat bump.py cherry.py helper.py
etcetera
What am i doing wrong?
Thanks in advance
| [
"You've made data a class attribute. Assign in __init__() instead.\nself.data = []\n\n"
] | [
1
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0002900437_cherrypy_python.txt |
Q:
how to set MATLABPATH in Python and using mlabwrap?
I tried to use mlab.path(path,'/my/path') but failed. Got NameError: name 'path' is not defined in python. Anyone has an idea?
A:
Never mind. I found out how. Use mlab.addpath().
| how to set MATLABPATH in Python and using mlabwrap? | I tried to use mlab.path(path,'/my/path') but failed. Got NameError: name 'path' is not defined in python. Anyone has an idea?
| [
"Never mind. I found out how. Use mlab.addpath().\n"
] | [
3
] | [] | [] | [
"matlab",
"mlabwrap",
"python"
] | stackoverflow_0002900358_matlab_mlabwrap_python.txt |
Q:
How to find links and modify an Html using BeautifulSoup in Python
Starting from an Html input like this:
<p>
<a href="http://www.foo.com">this if foo</a>
<a href="http://www.bar.com">this if bar</a>
</p>
using BeautifulSoup, i would like to change this Html in:
<p>
<a href="http://www.foo.com">this if foo[1]</a>
<a href="http://www.bar.com">this if bar[2]</a>
</p>
saving parsed links in a dictionary with a result like this:
links_dict = {"1":"http://www.foo.com","2":"http://www.bar.com"}
Is it possible to do this using BeautifulSoup? Any valid alternative?
A:
This should be easy in Beautiful Soup.
Something like:
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import Tag
count = 1
links_dict = {}
soup = BeautifulSoup(text)
for link_tag in soup.findAll('a'):
if link_tag['href'] and len(link_tag['href']) > 0:
links_dict[count] = link_tag['href']
newTag = Tag(soup, "a", link_tag.attrs)
newTag.insert(0, ''.join([''.join(link_tag.contents), "[%s]" % str(count)]))
link_tag.replaceWith(newTag)
count += 1
Result of executing this on your text:
>>> soup
<p>
<a href="http://www.foo.com">this if foo[1]</a>
<a href="http://www.bar.com">this if bar[2]</a>
</p>
>>> links_dict
{1: u'http://www.foo.com', 2: u'http://www.bar.com'}
The only problem I can foresee with this solution is if your link text contains subtags; then you couldn't do ''.join(link_tag.contents); instead you would need to navigate to the rightmost text element.
| How to find links and modify an Html using BeautifulSoup in Python | Starting from an Html input like this:
<p>
<a href="http://www.foo.com">this if foo</a>
<a href="http://www.bar.com">this if bar</a>
</p>
using BeautifulSoup, i would like to change this Html in:
<p>
<a href="http://www.foo.com">this if foo[1]</a>
<a href="http://www.bar.com">this if bar[2]</a>
</p>
saving parsed links in a dictionary with a result like this:
links_dict = {"1":"http://www.foo.com","2":"http://www.bar.com"}
Is it possible to do this using BeautifulSoup? Any valid alternative?
| [
"This should be easy in Beautiful Soup.\nSomething like:\nfrom BeautifulSoup import BeautifulSoup\nfrom BeautifulSoup import Tag\n\ncount = 1\nlinks_dict = {}\nsoup = BeautifulSoup(text)\nfor link_tag in soup.findAll('a'):\n if link_tag['href'] and len(link_tag['href']) > 0:\n links_dict[count] = link_tag['href'] \n newTag = Tag(soup, \"a\", link_tag.attrs)\n newTag.insert(0, ''.join([''.join(link_tag.contents), \"[%s]\" % str(count)]))\n link_tag.replaceWith(newTag)\n count += 1\n\nResult of executing this on your text:\n>>> soup\n<p>\n <a href=\"http://www.foo.com\">this if foo[1]</a>\n <a href=\"http://www.bar.com\">this if bar[2]</a>\n</p>\n\n>>> links_dict\n{1: u'http://www.foo.com', 2: u'http://www.bar.com'}\n\nThe only problem I can foresee with this solution is if your link text contains subtags; then you couldn't do ''.join(link_tag.contents); instead you would need to navigate to the rightmost text element.\n"
] | [
4
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0002900373_beautifulsoup_python.txt |
Q:
Ctypes "symbol not found" for dynamic library in OSX
I have made a C++ library and have built a .dylib dynamic library from it. However when I load it with ctypes, it fails. Something doesn't seem to have linked properly. I have no idea why. The error (The relevant part):
cscalelib.setup_framebuffer(flip,surface.frame_buffer,surface.texture,surface._scale[0],surface._scale[1])
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 325, in __getattr__
func = self.__getitem__(name)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 330, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: dlsym(0x56ecd0, setup_framebuffer): symbol not found
Here's the C++ code which is still in progress but should work with what I have so far.
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <vector.h>
void setup_framebuffer(bool flip,GLuint frame_buffer_id,GLuint texture_id,int width,int height){
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frame_buffer_id);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture_id, 0);
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); //Load the projection matrix
if (flip){
gluOrtho2D(0,width,height,0);
}else{
gluOrtho2D(0,width,0,height);
}
}
void end_framebuffer(){
glPopAttrib();
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); //Load the projection matrix
gluOrtho2D(0,1280,720,0); //Set an orthorgraphic view
}
void add_lines(bool antialias,vector< vector<double> > coordinates,double w,double r,double g, double b,double a){
glDisable(GL_TEXTURE_2D);
if (antialias){
glEnable(GL_LINE_SMOOTH); //Enable line smoothing.
}
glColor4d(r,g,b,a);
glLineWidth(w);
glBegin(GL_LINE_STRIP);
for (int x = 0; x < coordinates.size(); x++) {
glVertex2d(coordinates[x][0],coordinates[x][1]);
}
glEnd();
if (antialias){
glDisable(GL_LINE_SMOOTH); //Disable line smoothing.
}
glEnable(GL_TEXTURE_2D);
}
I compiled it with:
g++ -dynamiclib CPPEXTSCALELIB.cp -framework opengl -arch i386 -o CPPEXTSCALELIB.dylib
Here's the Python code with "..." to represent irrelevant parts.
...
from ctypes import *
...
cscalelib = CDLL(os.path.dirname(sys.argv[0]) + "/CPPEXTSCALELIB.dylib")
...
def setup_framebuffer(surface,flip=False):
#Create texture if not done already
if surface.texture is None:
create_texture(surface)
#Render child to parent
if surface.frame_buffer is None:
surface.frame_buffer = glGenFramebuffersEXT(1)
cscalelib.setup_framebuffer(flip,surface.frame_buffer,surface.texture,surface._scale[0],surface._scale[1])
...
Thank you.
A:
The problem is most likely the fact that you are using C++, and hence the function name will be mangled and use C++ calling conventions. If you declare the function with extern "C" then it should be exported in such a way as to callable from C code (and from Python's CTypes module).
| Ctypes "symbol not found" for dynamic library in OSX | I have made a C++ library and have built a .dylib dynamic library from it. However when I load it with ctypes, it fails. Something doesn't seem to have linked properly. I have no idea why. The error (The relevant part):
cscalelib.setup_framebuffer(flip,surface.frame_buffer,surface.texture,surface._scale[0],surface._scale[1])
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 325, in __getattr__
func = self.__getitem__(name)
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/__init__.py", line 330, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: dlsym(0x56ecd0, setup_framebuffer): symbol not found
Here's the C++ code which is still in progress but should work with what I have so far.
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <vector.h>
void setup_framebuffer(bool flip,GLuint frame_buffer_id,GLuint texture_id,int width,int height){
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frame_buffer_id);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture_id, 0);
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); //Load the projection matrix
if (flip){
gluOrtho2D(0,width,height,0);
}else{
gluOrtho2D(0,width,0,height);
}
}
void end_framebuffer(){
glPopAttrib();
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); //Load the projection matrix
gluOrtho2D(0,1280,720,0); //Set an orthorgraphic view
}
void add_lines(bool antialias,vector< vector<double> > coordinates,double w,double r,double g, double b,double a){
glDisable(GL_TEXTURE_2D);
if (antialias){
glEnable(GL_LINE_SMOOTH); //Enable line smoothing.
}
glColor4d(r,g,b,a);
glLineWidth(w);
glBegin(GL_LINE_STRIP);
for (int x = 0; x < coordinates.size(); x++) {
glVertex2d(coordinates[x][0],coordinates[x][1]);
}
glEnd();
if (antialias){
glDisable(GL_LINE_SMOOTH); //Disable line smoothing.
}
glEnable(GL_TEXTURE_2D);
}
I compiled it with:
g++ -dynamiclib CPPEXTSCALELIB.cp -framework opengl -arch i386 -o CPPEXTSCALELIB.dylib
Here's the Python code with "..." to represent irrelevant parts.
...
from ctypes import *
...
cscalelib = CDLL(os.path.dirname(sys.argv[0]) + "/CPPEXTSCALELIB.dylib")
...
def setup_framebuffer(surface,flip=False):
#Create texture if not done already
if surface.texture is None:
create_texture(surface)
#Render child to parent
if surface.frame_buffer is None:
surface.frame_buffer = glGenFramebuffersEXT(1)
cscalelib.setup_framebuffer(flip,surface.frame_buffer,surface.texture,surface._scale[0],surface._scale[1])
...
Thank you.
| [
"The problem is most likely the fact that you are using C++, and hence the function name will be mangled and use C++ calling conventions. If you declare the function with extern \"C\" then it should be exported in such a way as to callable from C code (and from Python's CTypes module).\n"
] | [
3
] | [] | [] | [
"c++",
"ctypes",
"g++",
"linker",
"python"
] | stackoverflow_0002900512_c++_ctypes_g++_linker_python.txt |
Q:
File Sharing Site in Python
I wanted to design a simple site where one person can upload a file, and pass off the random webaddress to someone, who can then download it.
At this point, I have a webpage where someone can successfully upload a file which gets stored under /files/ on my webserver.
The python script also generates a unique, random 5 letter code that gets stored in a database identifying the file
I have another page called retrieve, where a person should go, put in the 5 letter code, and it should pop up a filebox asking where to save the file.
My Problem is that: 1) How do I retrieve the file for download? At this point my retrieve script, takes the code, gets the location of the file on my server, but how do I get the brower to start downloading?
2)How do I stop people from directly going to the file? Should I change permissions on the file?
A:
How do you serve the file-upload page, and how do you let your users upload files?
If you are using Python's built-in HTTP server modules you shouldn't have any problems.
Anyway, here's how the file serving part is done using Python's built-in modules (just the basic idea).
Regarding your second question, if you were using these modules in the first place you probably wouldn't have asked it because you'd have to explicitly serve specific files.
import SocketServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
# The URL the client requested
print self.path
# analyze self.path, map the local file location...
# open the file, load the data
with open('test.py') as f: data = f.read()
# send the headers
self.send_response(200)
self.send_header('Content-type', 'application/octet-stream') # you may change the content type
self.end_headers()
# If the file is not found, send error code 404 instead of 200 and display a message accordingly, as you wish.
# wfile is a file-like object. writing data to it will send it to the client
self.wfile.write(data)
# XXX: Obviously, you might want to send the file in segments instead of loading it as a whole
if __name__ == '__main__':
PORT = 8080 # XXX
try:
server = SocketServer.ThreadingTCPServer(('', 8080), RequestHandler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
A:
You should send the right HTTP Response, containing the binary data and making the browser react on it.
Try this (I haven't) if you're using Django:
response = HttpResponse()
response['X-Sendfile'] = os.path.join(settings.MEDIA_ROOT, file.file.path)
content_type, encoding = mimetypes.guess_type(file.file.read())
if not content_type:
content_type = 'application/octet-stream'
response['Content-Type'] = content_type
response['Content-Length'] = file.file.size
response['Content-Disposition'] = 'attachment; filename="%s"' % file.file.name
return response
Source: http://www.chicagodjango.com/blog/permission-based-file-serving/
| File Sharing Site in Python | I wanted to design a simple site where one person can upload a file, and pass off the random webaddress to someone, who can then download it.
At this point, I have a webpage where someone can successfully upload a file which gets stored under /files/ on my webserver.
The python script also generates a unique, random 5 letter code that gets stored in a database identifying the file
I have another page called retrieve, where a person should go, put in the 5 letter code, and it should pop up a filebox asking where to save the file.
My Problem is that: 1) How do I retrieve the file for download? At this point my retrieve script, takes the code, gets the location of the file on my server, but how do I get the brower to start downloading?
2)How do I stop people from directly going to the file? Should I change permissions on the file?
| [
"How do you serve the file-upload page, and how do you let your users upload files?\nIf you are using Python's built-in HTTP server modules you shouldn't have any problems.\nAnyway, here's how the file serving part is done using Python's built-in modules (just the basic idea).\nRegarding your second question, if you were using these modules in the first place you probably wouldn't have asked it because you'd have to explicitly serve specific files.\nimport SocketServer\nimport BaseHTTPServer\n\n\nclass RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n\n def do_GET(self):\n # The URL the client requested\n print self.path\n\n # analyze self.path, map the local file location...\n\n # open the file, load the data\n with open('test.py') as f: data = f.read()\n\n # send the headers\n self.send_response(200)\n self.send_header('Content-type', 'application/octet-stream') # you may change the content type\n self.end_headers()\n # If the file is not found, send error code 404 instead of 200 and display a message accordingly, as you wish.\n\n # wfile is a file-like object. writing data to it will send it to the client\n self.wfile.write(data)\n\n # XXX: Obviously, you might want to send the file in segments instead of loading it as a whole\n\n\nif __name__ == '__main__':\n\n PORT = 8080 # XXX\n\n try:\n server = SocketServer.ThreadingTCPServer(('', 8080), RequestHandler)\n server.serve_forever()\n except KeyboardInterrupt:\n server.socket.close()\n\n",
"You should send the right HTTP Response, containing the binary data and making the browser react on it.\nTry this (I haven't) if you're using Django:\nresponse = HttpResponse()\nresponse['X-Sendfile'] = os.path.join(settings.MEDIA_ROOT, file.file.path)\ncontent_type, encoding = mimetypes.guess_type(file.file.read()) \nif not content_type:\n content_type = 'application/octet-stream' \nresponse['Content-Type'] = content_type \nresponse['Content-Length'] = file.file.size \nresponse['Content-Disposition'] = 'attachment; filename=\"%s\"' % file.file.name\nreturn response\n\nSource: http://www.chicagodjango.com/blog/permission-based-file-serving/\n"
] | [
2,
0
] | [] | [] | [
"cgi",
"file_upload",
"python"
] | stackoverflow_0002900514_cgi_file_upload_python.txt |
Q:
running a python script where dependencies are not avail: distributed computing
I have access to a grid (running condor) that would (potentially) allow to very substantially reduce how long by nltk based nlp tasks take. unfortunately, i dont have root access on the cluster so cannot install new packages, only run whatever is available on the linux boxes.
python is of course available, but nltk isnt - i was wondering however, if there might be a way around this somehow ? is there a way i can somehow still distribute the task in a self-contained 'package' of some sort?
Thanks for your hel
A:
If you can get a standard user account, you could use virtualenv to create a sandbox in that user-account, where you can install nltk.
| running a python script where dependencies are not avail: distributed computing | I have access to a grid (running condor) that would (potentially) allow to very substantially reduce how long by nltk based nlp tasks take. unfortunately, i dont have root access on the cluster so cannot install new packages, only run whatever is available on the linux boxes.
python is of course available, but nltk isnt - i was wondering however, if there might be a way around this somehow ? is there a way i can somehow still distribute the task in a self-contained 'package' of some sort?
Thanks for your hel
| [
"If you can get a standard user account, you could use virtualenv to create a sandbox in that user-account, where you can install nltk.\n"
] | [
2
] | [] | [] | [
"distributed",
"python"
] | stackoverflow_0002900660_distributed_python.txt |
Q:
How do I encode Unicode strings using pyodbc to save to a SAS dataset?
I'm using Python to read and write SAS datasets, using pyodbc and the SAS ODBC drivers. I can load the data perfectly well, but when I save the data, using something like:
cursor.execute('insert into dataset.test VALUES (?)', u'testing')
... I get a pyodbc.Error: ('HY004', '[HY004] [Microsoft][ODBC Driver Manager] SQL data type out of range (0) (SQLBindParameter)') error.
The problem seems to be the fact I'm passing a unicode string; what do I need to do to handle this?
A:
Do you know what character encoding your database is expecting? If so, you could try encoding your Unicode string before executing the query. So if your database is expecting utf-8 strings, you could try something like:
encoding = 'utf-8' # or latin1 or cp1252 or something
s = u'testing'.encode(encoding)
cursor.execute('insert into dataset.test VALUES (?)', s)
A:
You say "I can load the data perfectly well" ... does this mean that you can load data that contains characters that are NOT in the native encoding used on your platform (presumably cp1252 on Windows, but please confirm)? What is the SAS datatype of the first column of your SAS dataset?
This article in the SAS docs purports to show how you can find out the encoding used in a SAS dataset.
Encoding is mentioned in the SAS ODBC documentation. However you don't appear to be using SAS ODBC (i.e. SAS-language script accessing non-SAS data).
| How do I encode Unicode strings using pyodbc to save to a SAS dataset? | I'm using Python to read and write SAS datasets, using pyodbc and the SAS ODBC drivers. I can load the data perfectly well, but when I save the data, using something like:
cursor.execute('insert into dataset.test VALUES (?)', u'testing')
... I get a pyodbc.Error: ('HY004', '[HY004] [Microsoft][ODBC Driver Manager] SQL data type out of range (0) (SQLBindParameter)') error.
The problem seems to be the fact I'm passing a unicode string; what do I need to do to handle this?
| [
"Do you know what character encoding your database is expecting? If so, you could try encoding your Unicode string before executing the query. So if your database is expecting utf-8 strings, you could try something like:\nencoding = 'utf-8' # or latin1 or cp1252 or something\ns = u'testing'.encode(encoding)\ncursor.execute('insert into dataset.test VALUES (?)', s)\n\n",
"You say \"I can load the data perfectly well\" ... does this mean that you can load data that contains characters that are NOT in the native encoding used on your platform (presumably cp1252 on Windows, but please confirm)? What is the SAS datatype of the first column of your SAS dataset?\nThis article in the SAS docs purports to show how you can find out the encoding used in a SAS dataset.\nEncoding is mentioned in the SAS ODBC documentation. However you don't appear to be using SAS ODBC (i.e. SAS-language script accessing non-SAS data).\n"
] | [
1,
0
] | [] | [] | [
"odbc",
"pyodbc",
"python",
"sas"
] | stackoverflow_0002900214_odbc_pyodbc_python_sas.txt |
Q:
speed up calling lot of entities, and getting unique values, google app engine python
OK this is a 2 part question, I've seen and searched for several methods to get a list of unique values for a class and haven't been practically happy with any method so far.
So anyone have a simple example code of getting unique values for instance for this code. Here is my super slow example.
class LinkRating2(db.Model):
user = db.StringProperty()
link = db.StringProperty()
rating2 = db.FloatProperty()
def uniqueLinkGet(tabl):
start = time.time()
dic = {}
query = tabl.all()
for obj in query:
dic[obj.link]=1
end = time.time()
print end-start
return dic
My second question is calling for instance an iterator instead of fetch slower? Is there a faster method to do this code below? Especially if the number of elements called be larger than 1000?
query = LinkRating2.all()
link1 = 'some random string'
a = query.filter('link = ', link1)
adic ={}
for itema in a:
adic[itema.user]=itema.rating2
A:
1) One trick to make this query fast is to denormalize your data. Specifically, create another model which simply stores a link as the key. Then you can get a list of unique links by simply reading everything in that table. Assuming that you have many LinkRating2 entities for each link, then this will save you a lot of time. Example:
class Link(db.Model):
pass # the only data in this model will be stored in its key
# Whenever a link is added, you can try to add it to the datastore. If it already
# exists, then this is functionally a no-op - it will just overwrite the old copy of
# the same link. Using link as the key_name ensures there will be no duplicates.
Link(key_name=link).put()
# Get all the unique links by simply retrieving all of its entities and extracting
# the link field. You'll need to use cursors if you have >1,000 entities.
unique_links = [x.key().name() for Link.all().fetch(1000)]
Another idea: If you need to do this query frequently, then keep a copy of the results in memcache so you don't have to read all of this data from the datastore all the time. A single memcache entry can only store 1MB of data, so you may have to split your links data into chunks to store it in memcache.
2) It is faster to use fetch() instead of using the iterator. The iterator causes entities to be fetched in "small batches" - each "small batch" results in a round-trip to the datastore to get more data. If you use fetch(), then you'll get all the data at once with just one round-trip to the datastore. In short, use fetch() if you know you are going to need lots of results.
| speed up calling lot of entities, and getting unique values, google app engine python | OK this is a 2 part question, I've seen and searched for several methods to get a list of unique values for a class and haven't been practically happy with any method so far.
So anyone have a simple example code of getting unique values for instance for this code. Here is my super slow example.
class LinkRating2(db.Model):
user = db.StringProperty()
link = db.StringProperty()
rating2 = db.FloatProperty()
def uniqueLinkGet(tabl):
start = time.time()
dic = {}
query = tabl.all()
for obj in query:
dic[obj.link]=1
end = time.time()
print end-start
return dic
My second question is calling for instance an iterator instead of fetch slower? Is there a faster method to do this code below? Especially if the number of elements called be larger than 1000?
query = LinkRating2.all()
link1 = 'some random string'
a = query.filter('link = ', link1)
adic ={}
for itema in a:
adic[itema.user]=itema.rating2
| [
"1) One trick to make this query fast is to denormalize your data. Specifically, create another model which simply stores a link as the key. Then you can get a list of unique links by simply reading everything in that table. Assuming that you have many LinkRating2 entities for each link, then this will save you a lot of time. Example:\nclass Link(db.Model):\n pass # the only data in this model will be stored in its key\n\n# Whenever a link is added, you can try to add it to the datastore. If it already\n# exists, then this is functionally a no-op - it will just overwrite the old copy of\n# the same link. Using link as the key_name ensures there will be no duplicates.\nLink(key_name=link).put()\n\n# Get all the unique links by simply retrieving all of its entities and extracting\n# the link field. You'll need to use cursors if you have >1,000 entities.\nunique_links = [x.key().name() for Link.all().fetch(1000)]\n\nAnother idea: If you need to do this query frequently, then keep a copy of the results in memcache so you don't have to read all of this data from the datastore all the time. A single memcache entry can only store 1MB of data, so you may have to split your links data into chunks to store it in memcache.\n2) It is faster to use fetch() instead of using the iterator. The iterator causes entities to be fetched in \"small batches\" - each \"small batch\" results in a round-trip to the datastore to get more data. If you use fetch(), then you'll get all the data at once with just one round-trip to the datastore. In short, use fetch() if you know you are going to need lots of results.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002900362_google_app_engine_python.txt |
Q:
manage.py runserver throws an ImportError with my appname, MacPorts issue on OSX?
I've been developing a Django app for weeks locally on OSX 10.6.3. Recently, I rebooted my machine and went to start my development environment up.
Here's the error:
cm:myApp cm$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 11, in execute_manager(settings)
File "/Library/Python/2.6/site-packages/django/core/management/init.py", line 360, in execute_manager
setup_environ(settings_mod)
File "/Library/Python/2.6/site-packages/django/core/management/init.py", line 343, in setup_environ
project_module = import_module(project_name)
File "/Library/Python/2.6/site-packages/django/utils/importlib.py", line 35, in import_module
import(name)
ImportError: No module named myapp
I'm pretty new to Django / Python.
Digging around, it's possible that this might be due to MacPorts. Initially, I had a rough time getting Django up and running and I no longer remember if I'm using the Django from a MacPorts install or from easy_install. How do I tell? (I'd prefer not to reinstall everything).
Also, why is the camel casing in my app name gone in the ImportError message? When I search for "myapp" in my django project, I don't find it without camelcase anywhere.
And what causes MacPorts to work for a while but then break?
As a few other details, from settings.py:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'south',
'registration',
'pypaypal',
'notifier',
'myApp.batches',
)
A:
To tell where you're currently running Django from, open up a Python shell and do:
import django
print django.__path__
which should show you the path to the Django directory.
You might also want to do this from with the Python shell:
import sys
print sys.path
This should show you all the directories on the current PythonPath, which might help in your debugging.
A:
Okay, so this is very bizarre and I don't know what happened... but here's what fixed:
I open terminal and bash isn't recognizing any commands (python, vi, etc)
I restart machine, still not recognizing any commands
I look at my $PATH and /usr/bin is missing
I add /usr/bin to $PATH
I open vi and modify my profile to add /usr/bin
vi works, python works
python manage.py runserver works
How did /usr/bin get removed from my bash profile?
| manage.py runserver throws an ImportError with my appname, MacPorts issue on OSX? | I've been developing a Django app for weeks locally on OSX 10.6.3. Recently, I rebooted my machine and went to start my development environment up.
Here's the error:
cm:myApp cm$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 11, in execute_manager(settings)
File "/Library/Python/2.6/site-packages/django/core/management/init.py", line 360, in execute_manager
setup_environ(settings_mod)
File "/Library/Python/2.6/site-packages/django/core/management/init.py", line 343, in setup_environ
project_module = import_module(project_name)
File "/Library/Python/2.6/site-packages/django/utils/importlib.py", line 35, in import_module
import(name)
ImportError: No module named myapp
I'm pretty new to Django / Python.
Digging around, it's possible that this might be due to MacPorts. Initially, I had a rough time getting Django up and running and I no longer remember if I'm using the Django from a MacPorts install or from easy_install. How do I tell? (I'd prefer not to reinstall everything).
Also, why is the camel casing in my app name gone in the ImportError message? When I search for "myapp" in my django project, I don't find it without camelcase anywhere.
And what causes MacPorts to work for a while but then break?
As a few other details, from settings.py:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'south',
'registration',
'pypaypal',
'notifier',
'myApp.batches',
)
| [
"To tell where you're currently running Django from, open up a Python shell and do:\nimport django\nprint django.__path__\n\nwhich should show you the path to the Django directory.\nYou might also want to do this from with the Python shell:\nimport sys\nprint sys.path\n\nThis should show you all the directories on the current PythonPath, which might help in your debugging.\n",
"Okay, so this is very bizarre and I don't know what happened... but here's what fixed:\n\nI open terminal and bash isn't recognizing any commands (python, vi, etc) \nI restart machine, still not recognizing any commands \nI look at my $PATH and /usr/bin is missing \nI add /usr/bin to $PATH \nI open vi and modify my profile to add /usr/bin \nvi works, python works \npython manage.py runserver works \n\nHow did /usr/bin get removed from my bash profile?\n"
] | [
0,
0
] | [] | [] | [
"django",
"macos",
"python"
] | stackoverflow_0002894344_django_macos_python.txt |
Q:
Best practice for string substitution with gettext using Python
Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally?
I can think of at least 3 string techniques:
1) Classic "%" based formatting:
"My name is %(name)s" % locals()
2) .format() based formatting:
"My name is {name}".format( locals() )
3) string.Template.safe_substitute()
import string
template = string.Template( "My name is ${name}" )
template.safe_substitute( locals() )
The advantage of the string.Template technique is that a translated string with with an incorrectly spelled variable reference can still yield a usable string value while the other techniques unconditionally raise an exception. The downside of the string.Template technique appears to be the inability for one to customize how a variable is formatted (padding, justification, width, etc).
A:
Actually I would prefer to get an exception during my tests, to fix the error as soon as possible -- "errors should not pass silently". So I consider that approach (2) is the best one in modern Python (which supports the readable and flexible format), and approach (1) a probably inevitable fall-back if you're stuck supporting older Python releases (where % was "the" way to do flexible formatting -- finding, or coding, some backport of format would be the main alternative).
A:
Don't have incorrectly spelled variable names - that's what testing is for.
On the face of it, displaying something seems better than throwing an exception, but sooner or later one of those mistranslations is bound to cause offence to some user.
.format() is the way to go these days.
Reconsider passing locals() straight into the translation. It will save you worrying about what happens if someone works out a way to do something sneaky with self in one of the translations.
| Best practice for string substitution with gettext using Python | Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally?
I can think of at least 3 string techniques:
1) Classic "%" based formatting:
"My name is %(name)s" % locals()
2) .format() based formatting:
"My name is {name}".format( locals() )
3) string.Template.safe_substitute()
import string
template = string.Template( "My name is ${name}" )
template.safe_substitute( locals() )
The advantage of the string.Template technique is that a translated string with with an incorrectly spelled variable reference can still yield a usable string value while the other techniques unconditionally raise an exception. The downside of the string.Template technique appears to be the inability for one to customize how a variable is formatted (padding, justification, width, etc).
| [
"Actually I would prefer to get an exception during my tests, to fix the error as soon as possible -- \"errors should not pass silently\". So I consider that approach (2) is the best one in modern Python (which supports the readable and flexible format), and approach (1) a probably inevitable fall-back if you're stuck supporting older Python releases (where % was \"the\" way to do flexible formatting -- finding, or coding, some backport of format would be the main alternative).\n",
"Don't have incorrectly spelled variable names - that's what testing is for.\nOn the face of it, displaying something seems better than throwing an exception, but sooner or later one of those mistranslations is bound to cause offence to some user.\n.format() is the way to go these days.\nReconsider passing locals() straight into the translation. It will save you worrying about what happens if someone works out a way to do something sneaky with self in one of the translations.\n"
] | [
3,
2
] | [] | [] | [
"gettext",
"python",
"string",
"string_formatting"
] | stackoverflow_0002901082_gettext_python_string_string_formatting.txt |
Q:
In Python, can an object have another object as an attribute?
In Python, can an object have another object as an attribute? For example, can a class called car have a class called tire as an attribute?
A:
Do you mean a class tire or an instance of class tire? It can have both although the latter is probably more useful. If you're looking for an object of class Mary to has-a object of type Fred you'd want the classinst variety of assignment:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
>>> class Fred(object): pass
...
>>> class Mary(object):
... def __init__(self):
... self.classref = Fred
... self.classinst = Fred()
...
>>> x = Mary()
>>> dir(x)
[... 'classinst', 'classref']
>>> x.classref
<class '__main__.Fred'>
>>> x.classinst
<__main__.Fred object at 0xb76eed0c>
A:
Yes.
>>> class tire:
... pass
...
>>> class car:
... def __init__(self, tire):
... self.tire = tire
...
>>> t = tire()
>>> t.brand = 'Goodyear'
>>> c = car(t)
>>> c.tire.brand
'Goodyear'
A:
You can have both instances and classes as attributes of both classes and instances -- all four combinations work just fine (and can be combined freely). However, do keep in mind the distinction between a class and an instance thereof -- the way you phrase your question suggests some confusion. Anyway, taking your question literally:
can a class called car have a class
called tire as an attribute?
class tire(object):
...class body here...
class car(object):
thetire = tire
...rest of class body here...
A tire = tire assignment in the body of car would not work (naming confusion!-) so you need to name the class attribute differently than the class that's its value. (This does not apply to instance attributes, since their syntax, e.g. self.tire, is that of qualified names, not barenames, so there's no naming confusion -- only to class attributes). Was that perchance the source of the problem that led you to ask this question?
A:
Sure; classes, like any other value, can be either class or instance attributes:
class A(object):
pass
class B(object):
class_attr = A
def __init__(self):
self.instance_attr = A
With this code, you could use B.class_attr or B().instance_attr to access A.
| In Python, can an object have another object as an attribute? | In Python, can an object have another object as an attribute? For example, can a class called car have a class called tire as an attribute?
| [
"Do you mean a class tire or an instance of class tire? It can have both although the latter is probably more useful. If you're looking for an object of class Mary to has-a object of type Fred you'd want the classinst variety of assignment: \nPython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n>>> class Fred(object): pass\n... \n>>> class Mary(object):\n... def __init__(self):\n... self.classref = Fred\n... self.classinst = Fred()\n... \n>>> x = Mary()\n>>> dir(x)\n[... 'classinst', 'classref']\n>>> x.classref\n<class '__main__.Fred'>\n>>> x.classinst\n<__main__.Fred object at 0xb76eed0c>\n\n",
"Yes.\n>>> class tire:\n... pass\n...\n>>> class car:\n... def __init__(self, tire):\n... self.tire = tire\n...\n>>> t = tire()\n>>> t.brand = 'Goodyear'\n>>> c = car(t)\n>>> c.tire.brand\n'Goodyear'\n\n",
"You can have both instances and classes as attributes of both classes and instances -- all four combinations work just fine (and can be combined freely). However, do keep in mind the distinction between a class and an instance thereof -- the way you phrase your question suggests some confusion. Anyway, taking your question literally:\n\ncan a class called car have a class\n called tire as an attribute?\n\nclass tire(object):\n ...class body here...\n\nclass car(object):\n thetire = tire\n ...rest of class body here...\n\nA tire = tire assignment in the body of car would not work (naming confusion!-) so you need to name the class attribute differently than the class that's its value. (This does not apply to instance attributes, since their syntax, e.g. self.tire, is that of qualified names, not barenames, so there's no naming confusion -- only to class attributes). Was that perchance the source of the problem that led you to ask this question?\n",
"Sure; classes, like any other value, can be either class or instance attributes:\nclass A(object):\n pass\n\nclass B(object):\n class_attr = A\n\n def __init__(self):\n self.instance_attr = A\n\nWith this code, you could use B.class_attr or B().instance_attr to access A.\n"
] | [
3,
2,
2,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0002900821_oop_python.txt |
Q:
regex numeric data processing: match a series of numbers greater than X
Say I have some data like this:
number_stream = [0,0,0,7,8,0,0,2,5,6,10,11,10,13,5,0,1,0,...]
I want to process it looking for "bumps" that meet a certain pattern.
Imagine I have my own customized regex language for working on numbers, where [[ >=5 ]] represents any number >= 5. I want to capture this case:
([[ >=5 ]]{3,})[[ <3 ]]{2,}
In other words, I want to begin capturing any time I look ahead and see 3 or more values >= 5 in a row, and stop capturing any time I look ahead and see 2+ values < 3. So my output should be:
>>> stream_processor.process(number_stream)
[[5,6,10,11,10,13,5],...]
Note that the first 7,8,... is ignored because it's not long enough, and that the capture ends before the 0,1,0....
I'd also like a stream_processor object I can incrementally pass more data into in subsequent process calls, and return captured chunks as they're completed.
I've written some code to do it, but it was hideous and state-machiney, and I can't help feeling like I'm missing something obvious. Any ideas to do this cleanly?
A:
State machines (enriched with quite a few extras, since regexes can match a broader range of languages than FSMs can) are a typical approach to implementing regular expression engines, so why shouldn't similar approaches emerge in looking for good implementations of your desired "regex-like" constructs?
Indeed, I would consider starting with the code for an actual RE engine (there's a Python-coded one in the PyPy sources, the mercurial tree for which is here), changing only the "primitives" (you don't need e.g. \w or \s, but you need <5, >3, etc) and keeping most syntax and implementation for *, +, and so on. Such a project would be well worth open-sourcing, by the way.
A:
A state machine is the appropriate solution here. There are two common ways to implement one:
Hardwired in the form of a set of mutually-recursive functions where the function that is running represents the current state. This can be very efficient but requires tail call elimination, trampolines or goto.
Emulated in the form of a data structure representing the current state and a function of that state and a new input datum that updates the state.
This stuff is the bread and butter of functional programming. Here is an elegant solution to your problem written in the former style in F# and run on your own data set:
> let rec skip = function
| _, yss, [] -> yss
| [_; _; _] as ys, yss, xs -> record ([], ys, yss, xs)
| ys, yss, x::xs when x >= 5 -> skip (x::ys, yss, xs)
| ys, yss, x::xs -> skip ([], yss, xs)
and record = function
| ys', ys, yss, [] -> (ys' @ ys) :: yss
| [_; _], ys, yss, xs -> skip ([], ys :: yss, xs)
| ys', ys, yss, x::xs when x < 3 -> record (x::ys', ys, yss, xs)
| ys', ys, yss, x::xs -> record ([], x::ys' @ ys, yss, xs);;
val skip : int list * int list list * int list -> int list list
val record : int list * int list * int list list * int list -> int list list
> let run xs = skip([], [], xs) |> List.map List.rev |> List.rev;;
val run : int list -> int list list
> run [0;0;0;7;8;0;0;2;5;6;10;11;10;13;5;0;1;0];;
val it : int list list = [[5; 6; 10; 11; 10; 13; 5]]
and here is the same solution written in the latter style:
> type 'a state =
| Skip of 'a list
| Record of 'a list * 'a list;;
type 'a state =
| Skip of 'a list
| Record of 'a list * 'a list
> let rec apply (state, yss) x =
match state, yss with
| Skip([_; _; _] as ys), yss -> apply (Record([], ys), yss) x
| Skip ys, yss when x >= 5 -> Skip(x::ys), yss
| Skip ys, yss -> Skip[], yss
| Record([_; _], ys), yss -> apply (Skip[], ys :: yss) x
| Record(ys', ys), yss when x < 3 -> Record (x::ys', ys), yss
| Record(ys', ys), yss -> Record ([], x::ys' @ ys), yss;;
val apply : int state * int list list -> int -> int state * int list list
> let run xs =
match List.fold apply (Skip [], []) xs with
| Skip _, yss -> yss
| Record(ys', ys), yss -> (ys' @ ys) :: yss
|> List.map List.rev |> List.rev;;
val run : int list -> int list list
> run [0;0;0;7;8;0;0;2;5;6;10;11;10;13;5;0;1;0];;
val it : int list list = [[5; 6; 10; 11; 10; 13; 5]]
Note how the first solution eats the entire input at once whereas the latter bites off a single datum at a time and returns a new state ready to eat another datum. Consequently, the latter is applied to each datum in turn using a fold and the final half-eaten state must be consumed appropriately before returning.
| regex numeric data processing: match a series of numbers greater than X | Say I have some data like this:
number_stream = [0,0,0,7,8,0,0,2,5,6,10,11,10,13,5,0,1,0,...]
I want to process it looking for "bumps" that meet a certain pattern.
Imagine I have my own customized regex language for working on numbers, where [[ >=5 ]] represents any number >= 5. I want to capture this case:
([[ >=5 ]]{3,})[[ <3 ]]{2,}
In other words, I want to begin capturing any time I look ahead and see 3 or more values >= 5 in a row, and stop capturing any time I look ahead and see 2+ values < 3. So my output should be:
>>> stream_processor.process(number_stream)
[[5,6,10,11,10,13,5],...]
Note that the first 7,8,... is ignored because it's not long enough, and that the capture ends before the 0,1,0....
I'd also like a stream_processor object I can incrementally pass more data into in subsequent process calls, and return captured chunks as they're completed.
I've written some code to do it, but it was hideous and state-machiney, and I can't help feeling like I'm missing something obvious. Any ideas to do this cleanly?
| [
"State machines (enriched with quite a few extras, since regexes can match a broader range of languages than FSMs can) are a typical approach to implementing regular expression engines, so why shouldn't similar approaches emerge in looking for good implementations of your desired \"regex-like\" constructs?\nIndeed, I would consider starting with the code for an actual RE engine (there's a Python-coded one in the PyPy sources, the mercurial tree for which is here), changing only the \"primitives\" (you don't need e.g. \\w or \\s, but you need <5, >3, etc) and keeping most syntax and implementation for *, +, and so on. Such a project would be well worth open-sourcing, by the way.\n",
"A state machine is the appropriate solution here. There are two common ways to implement one:\n\nHardwired in the form of a set of mutually-recursive functions where the function that is running represents the current state. This can be very efficient but requires tail call elimination, trampolines or goto.\nEmulated in the form of a data structure representing the current state and a function of that state and a new input datum that updates the state.\n\nThis stuff is the bread and butter of functional programming. Here is an elegant solution to your problem written in the former style in F# and run on your own data set:\n> let rec skip = function\n | _, yss, [] -> yss\n | [_; _; _] as ys, yss, xs -> record ([], ys, yss, xs)\n | ys, yss, x::xs when x >= 5 -> skip (x::ys, yss, xs)\n | ys, yss, x::xs -> skip ([], yss, xs)\n and record = function\n | ys', ys, yss, [] -> (ys' @ ys) :: yss\n | [_; _], ys, yss, xs -> skip ([], ys :: yss, xs)\n | ys', ys, yss, x::xs when x < 3 -> record (x::ys', ys, yss, xs)\n | ys', ys, yss, x::xs -> record ([], x::ys' @ ys, yss, xs);;\nval skip : int list * int list list * int list -> int list list\nval record : int list * int list * int list list * int list -> int list list\n\n> let run xs = skip([], [], xs) |> List.map List.rev |> List.rev;;\nval run : int list -> int list list\n\n> run [0;0;0;7;8;0;0;2;5;6;10;11;10;13;5;0;1;0];;\nval it : int list list = [[5; 6; 10; 11; 10; 13; 5]]\n\nand here is the same solution written in the latter style:\n> type 'a state =\n | Skip of 'a list\n | Record of 'a list * 'a list;;\ntype 'a state =\n | Skip of 'a list\n | Record of 'a list * 'a list\n\n> let rec apply (state, yss) x =\n match state, yss with\n | Skip([_; _; _] as ys), yss -> apply (Record([], ys), yss) x\n | Skip ys, yss when x >= 5 -> Skip(x::ys), yss\n | Skip ys, yss -> Skip[], yss\n | Record([_; _], ys), yss -> apply (Skip[], ys :: yss) x\n | Record(ys', ys), yss when x < 3 -> Record (x::ys', ys), yss\n | Record(ys', ys), yss -> Record ([], x::ys' @ ys), yss;;\nval apply : int state * int list list -> int -> int state * int list list\n\n> let run xs =\n match List.fold apply (Skip [], []) xs with\n | Skip _, yss -> yss\n | Record(ys', ys), yss -> (ys' @ ys) :: yss\n |> List.map List.rev |> List.rev;;\nval run : int list -> int list list\n\n> run [0;0;0;7;8;0;0;2;5;6;10;11;10;13;5;0;1;0];;\nval it : int list list = [[5; 6; 10; 11; 10; 13; 5]]\n\nNote how the first solution eats the entire input at once whereas the latter bites off a single datum at a time and returns a new state ready to eat another datum. Consequently, the latter is applied to each datum in turn using a fold and the final half-eaten state must be consumed appropriately before returning.\n"
] | [
3,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002901101_python_regex.txt |
Q:
is there a facebook user login framework for gae
I want to enable someone login using facebook,
Is there a framework that you have used to do this?
Thanks
A:
Coincidentally, I gave an answer to a similar question just a couple of hours ago. Please use Rpx, which requires minimal work from your part.
how to make it easy for users to register at my site?
| is there a facebook user login framework for gae | I want to enable someone login using facebook,
Is there a framework that you have used to do this?
Thanks
| [
"Coincidentally, I gave an answer to a similar question just a couple of hours ago. Please use Rpx, which requires minimal work from your part.\nhow to make it easy for users to register at my site?\n"
] | [
1
] | [] | [] | [
"facebook",
"google_app_engine",
"python"
] | stackoverflow_0002901397_facebook_google_app_engine_python.txt |
Q:
The "correct" way to define an exception in Python without PyLint complaining
I'm trying to define my own (very simple) exception class in Python 2.6, but no matter how I do it I get some warning.
First, the simplest way:
class MyException(Exception):
pass
This works, but prints out a warning at runtime: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 OK, so that's not the way. I then tried:
class MyException(Exception):
def __init__(self, message):
self.message = message
This also works, but PyLint reports a warning: W0231: MyException.__init__: __init__ method from base class 'Exception' is not called. So I tried calling it:
class MyException(Exception):
def __init__(self, message):
super(Exception, self).__init__(message)
self.message = message
This works, too! But now PyLint reports an error: E1003: MyException.__init__: Bad first argument 'Exception' given to super class
How the hell do I do such a simple thing without any warnings?
A:
When you call super, you need the subclass/derived class as the first argument, not the main/base class.
From the Python online documentation:
class C(B):
def method(self, arg):
super(C, self).method(arg)
So your exception would be defined as follows:
class MyException(Exception):
def __init__(self, message):
super(MyException, self).__init__(message)
self.message = message
A:
Alright, I think I figured it out. This seems to keep PyLint happy:
class MyException(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
A:
Your first way should work. I use it myself all the time in Python 2.6.5. I don't use the "message" attribute, however; maybe that's why you're getting a runtime warning in the first example.
The following code, for example, runs without any errors or runtime warnings:
class MyException(Exception):
pass
def thrower():
error_value = 3
raise MyException("My message", error_value)
return 4
def catcher():
try:
print thrower()
except MyException as (message, error_value):
print message, "error value:", error_value
The result:
>>> catcher()
My message error value: 3
I don't know if PyLint would have a problem with the above.
| The "correct" way to define an exception in Python without PyLint complaining | I'm trying to define my own (very simple) exception class in Python 2.6, but no matter how I do it I get some warning.
First, the simplest way:
class MyException(Exception):
pass
This works, but prints out a warning at runtime: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 OK, so that's not the way. I then tried:
class MyException(Exception):
def __init__(self, message):
self.message = message
This also works, but PyLint reports a warning: W0231: MyException.__init__: __init__ method from base class 'Exception' is not called. So I tried calling it:
class MyException(Exception):
def __init__(self, message):
super(Exception, self).__init__(message)
self.message = message
This works, too! But now PyLint reports an error: E1003: MyException.__init__: Bad first argument 'Exception' given to super class
How the hell do I do such a simple thing without any warnings?
| [
"When you call super, you need the subclass/derived class as the first argument, not the main/base class.\nFrom the Python online documentation:\nclass C(B):\n def method(self, arg):\n super(C, self).method(arg)\n\nSo your exception would be defined as follows:\nclass MyException(Exception):\n def __init__(self, message):\n super(MyException, self).__init__(message)\n self.message = message\n\n",
"Alright, I think I figured it out. This seems to keep PyLint happy:\nclass MyException(Exception):\n def __init__(self, message):\n Exception.__init__(self, message)\n self.message = message\n\n",
"Your first way should work. I use it myself all the time in Python 2.6.5. I don't use the \"message\" attribute, however; maybe that's why you're getting a runtime warning in the first example.\nThe following code, for example, runs without any errors or runtime warnings:\nclass MyException(Exception):\n pass\n\ndef thrower():\n error_value = 3\n raise MyException(\"My message\", error_value)\n return 4\n\ndef catcher():\n try:\n print thrower()\n except MyException as (message, error_value):\n print message, \"error value:\", error_value\n\nThe result:\n>>> catcher()\nMy message error value: 3\n\nI don't know if PyLint would have a problem with the above.\n"
] | [
44,
7,
0
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0002901000_exception_python.txt |
Q:
Multiple python scripts sending messages to a single central script
I have a number of scripts written in Python 2.6 that can be run arbitrarily. I would like to have a single central script that collects the output and displays it in a single log.
Ideally it would satisfy these requirements:
Every script sends its messages to the same "receiver" for display.
If the receiver is not running when the first script tries to send a message, it is started.
The receiver can also be launched and ended manually. (Though if ended, it will restart if another script tries to send a message.)
The scripts can be run in any order, even simultaneously.
Runs on Windows. Multiplatform is better, but at least it needs to work on Windows.
I've come across some hints:
os.pipe()
multiprocess
Occupying a port
mutex
logging.handlers.SocketHandler (thanks @Dan Head)
From those pieces, I think I could cobble something together. Just wondering if there is an obviously 'right' way of doing this, or if I could learn from anyone's mistakes.
A:
I'd consider using logging.handlers.SocketHandler for the message passing parts of this, it sounds like you have a logging type use case in mind already.
The standard libraries logging facilities are very flexible and configuration driven so you should be able to adapt them to your requirements.
This doesn't handle the automatic restarting part of your question. For UNIX you'd probably just use pid files and os.kill(pid, 0) to check if it's running, but I don't know what their equivalents in the Windows world would be.
A:
I built a server to use a Windows named pipe, using the following key code:
def run( self ):
# This is the main server loop for the Win32 platform
import win32pipe
import win32file
self.pipeHandle = win32pipe.CreateNamedPipe(
'\\\\.\\pipe\\myapp_requests',
win32pipe.PIPE_ACCESS_DUPLEX,
win32pipe.PIPE_TYPE_BYTE |
win32pipe.PIPE_READMODE_BYTE |
win32pipe.PIPE_WAIT,
1,
4096,
4096,
10000,
None)
if self.pipeHandle == win32file.INVALID_HANDLE_VALUE:
print 'Failed to create named pipe %s!' % self.pipeName
print 'Exiting...'
sys.exit(1)
while True:
# Open file connection
win32pipe.ConnectNamedPipe( self.pipeHandle )
# Run the main message loop until it exits, usually because
# of a loss of communication on the pipe
try:
self.messageLoop()
except ServerKillSignal:
break
# Return the pipes to their disconnected condition and try again
try: win32pipe.DisconnectNamedPipe( self.pipeHandle )
except: pass
win32file.CloseHandle( self.pipeHandle )
print "Exiting server"
The method messageLoop() reads data from the pipe, using win32file.ReadFile(), until win32file.error is thrown. Then it exits, allowing run() to restart it.
In my implementation, the users were not likely to have administrator access, so this could not be started as a system service. Instead, I coded the client to check for the existence of the pipe at '\.\pipe\pyccf_requests'. If it doesn't exist, then the client starts a new server process.
A:
Dan Head's answer is exactly what you want.
Item #2, "If the receiver is not running when the first script tries to send a message, it is started", probably won't work. Something has to be running to receive a message. I suggest writing a demon process which starts on bootup, and tell Windows to restart it if it dies.
| Multiple python scripts sending messages to a single central script | I have a number of scripts written in Python 2.6 that can be run arbitrarily. I would like to have a single central script that collects the output and displays it in a single log.
Ideally it would satisfy these requirements:
Every script sends its messages to the same "receiver" for display.
If the receiver is not running when the first script tries to send a message, it is started.
The receiver can also be launched and ended manually. (Though if ended, it will restart if another script tries to send a message.)
The scripts can be run in any order, even simultaneously.
Runs on Windows. Multiplatform is better, but at least it needs to work on Windows.
I've come across some hints:
os.pipe()
multiprocess
Occupying a port
mutex
logging.handlers.SocketHandler (thanks @Dan Head)
From those pieces, I think I could cobble something together. Just wondering if there is an obviously 'right' way of doing this, or if I could learn from anyone's mistakes.
| [
"I'd consider using logging.handlers.SocketHandler for the message passing parts of this, it sounds like you have a logging type use case in mind already.\nThe standard libraries logging facilities are very flexible and configuration driven so you should be able to adapt them to your requirements.\nThis doesn't handle the automatic restarting part of your question. For UNIX you'd probably just use pid files and os.kill(pid, 0) to check if it's running, but I don't know what their equivalents in the Windows world would be.\n",
"I built a server to use a Windows named pipe, using the following key code:\n def run( self ):\n # This is the main server loop for the Win32 platform\n import win32pipe\n import win32file\n self.pipeHandle = win32pipe.CreateNamedPipe(\n '\\\\\\\\.\\\\pipe\\\\myapp_requests',\n win32pipe.PIPE_ACCESS_DUPLEX,\n win32pipe.PIPE_TYPE_BYTE |\n win32pipe.PIPE_READMODE_BYTE |\n win32pipe.PIPE_WAIT,\n 1,\n 4096,\n 4096,\n 10000,\n None)\n if self.pipeHandle == win32file.INVALID_HANDLE_VALUE:\n print 'Failed to create named pipe %s!' % self.pipeName\n print 'Exiting...'\n sys.exit(1)\n while True:\n # Open file connection\n win32pipe.ConnectNamedPipe( self.pipeHandle )\n\n # Run the main message loop until it exits, usually because\n # of a loss of communication on the pipe\n try:\n self.messageLoop()\n except ServerKillSignal:\n break\n\n # Return the pipes to their disconnected condition and try again\n try: win32pipe.DisconnectNamedPipe( self.pipeHandle )\n except: pass\n win32file.CloseHandle( self.pipeHandle )\n print \"Exiting server\"\n\nThe method messageLoop() reads data from the pipe, using win32file.ReadFile(), until win32file.error is thrown. Then it exits, allowing run() to restart it.\nIn my implementation, the users were not likely to have administrator access, so this could not be started as a system service. Instead, I coded the client to check for the existence of the pipe at '\\.\\pipe\\pyccf_requests'. If it doesn't exist, then the client starts a new server process.\n",
"Dan Head's answer is exactly what you want.\nItem #2, \"If the receiver is not running when the first script tries to send a message, it is started\", probably won't work. Something has to be running to receive a message. I suggest writing a demon process which starts on bootup, and tell Windows to restart it if it dies.\n"
] | [
5,
1,
0
] | [] | [] | [
"interprocess",
"multiprocessing",
"python"
] | stackoverflow_0002853682_interprocess_multiprocessing_python.txt |
Q:
Python DictReader - Skipping rows with missing columns?
I have a Excel .CSV file I'm attempting to read in with DictReader.
All seems to be well, except it seems to omit rows, specifically those with missing columns.
Our input looks like:
mail,givenName,sn,lorem,ipsum,dolor,telephoneNumber
ian.bay@blah.com,ian,bay,3424,8403,2535,+65(2)34523534545
mike.gibson@blah.com,mike,gibson,3424,8403,2535,+65(2)34523534545
ross.martin@blah.com,ross,martin,,,,+65(2)34523534545
david.connor@blah.com,david,connor,,,,+65(2)34523534545
chris.call@blah.com,chris,call,3424,8403,2535,+65(2)34523534545
So some of the rows have missing lorem/ipsum/dolor columns, and it's just a string of commas for those.
We're reading it in with:
def read_gd_dump(input_file="blah 20100423.csv"):
gd_extract = csv.DictReader(open('blah 20100423.csv'), restval='missing', dialect='excel')
return dict([(row['something'], row) for row in gd_extract])
And I checked that "something" (the key for our dict) isn't one of the missing columns, I had originally suspected it might be that. It's one of the columns after that.
However, DictReader seems to completely skip over the rows. I tried setting restval to something, didn't seem to make any difference. I can't seem to find anything in Python's CSV docs (http://docs.python.org/library/csv.html) that would explain this behaviour, but I may have misread something.
A:
Can't reproduce your problem -- when I save that data and then assign list(gd_extract), I see:
[{'telephoneNumber': '+65(2)34523534545', 'ipsum': '8403', 'sn': 'bay', 'dolor': '2535', 'mail': 'ian.bay@blah.com', 'givenName': 'ian', 'lorem': '3424'}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '8403', 'sn': 'gibson', 'dolor': '2535', 'mail': 'mike.gibson@blah.com', 'givenName': 'mike', 'lorem': '3424'}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '', 'sn': 'martin', 'dolor': '', 'mail': 'ross.martin@blah.com', 'givenName': 'ross', 'lorem': ''}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '', 'sn': 'connor', 'dolor': '', 'mail': 'david.connor@blah.com', 'givenName': 'david', 'lorem': ''}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '8403', 'sn': 'call', 'dolor': '2535', 'mail': 'chris.call@blah.com', 'givenName': 'chris', 'lorem': '3424'}]
five dicts, including those with missing ipsum etc. I fear that in your laudable attempt at simplifying the problem you've simplified it excessively, so that your bug has gone away.
If you have duplicates in column something (can't check, since you don't have that column in your sample data) that would of course explain the "apparently missing" rows -- they're not missing from the csv reader's returned stream, they get "overwritten" in the dict you're returning. Could that be the issue?
A:
This may be nothing to do with your problem, and Alex's analysis is quite plausible given the lack of information, but you should ALWAYS open a csv file with "rb" or "wb" mode (assuming Python 2.X). If you don't, you run the risk of various mysterious happenings. A csv file is not a text file, it's a BINARY file.
In any case, please edit your question to show:
(1) (a) a sample file (b) a script (c) output -- which together demonstrate the alleged problem
(2) what version of Python you are running
(3) what OS
Update: For Python 3.X, do as the blessed manual says: """If csvfile is a file object, it should be opened with newline=''. Although this advice is included only with csv.reader, it applies equally to csv.writer, csv.DictReader, and csv.DictWriter.
| Python DictReader - Skipping rows with missing columns? | I have a Excel .CSV file I'm attempting to read in with DictReader.
All seems to be well, except it seems to omit rows, specifically those with missing columns.
Our input looks like:
mail,givenName,sn,lorem,ipsum,dolor,telephoneNumber
ian.bay@blah.com,ian,bay,3424,8403,2535,+65(2)34523534545
mike.gibson@blah.com,mike,gibson,3424,8403,2535,+65(2)34523534545
ross.martin@blah.com,ross,martin,,,,+65(2)34523534545
david.connor@blah.com,david,connor,,,,+65(2)34523534545
chris.call@blah.com,chris,call,3424,8403,2535,+65(2)34523534545
So some of the rows have missing lorem/ipsum/dolor columns, and it's just a string of commas for those.
We're reading it in with:
def read_gd_dump(input_file="blah 20100423.csv"):
gd_extract = csv.DictReader(open('blah 20100423.csv'), restval='missing', dialect='excel')
return dict([(row['something'], row) for row in gd_extract])
And I checked that "something" (the key for our dict) isn't one of the missing columns, I had originally suspected it might be that. It's one of the columns after that.
However, DictReader seems to completely skip over the rows. I tried setting restval to something, didn't seem to make any difference. I can't seem to find anything in Python's CSV docs (http://docs.python.org/library/csv.html) that would explain this behaviour, but I may have misread something.
| [
"Can't reproduce your problem -- when I save that data and then assign list(gd_extract), I see:\n[{'telephoneNumber': '+65(2)34523534545', 'ipsum': '8403', 'sn': 'bay', 'dolor': '2535', 'mail': 'ian.bay@blah.com', 'givenName': 'ian', 'lorem': '3424'}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '8403', 'sn': 'gibson', 'dolor': '2535', 'mail': 'mike.gibson@blah.com', 'givenName': 'mike', 'lorem': '3424'}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '', 'sn': 'martin', 'dolor': '', 'mail': 'ross.martin@blah.com', 'givenName': 'ross', 'lorem': ''}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '', 'sn': 'connor', 'dolor': '', 'mail': 'david.connor@blah.com', 'givenName': 'david', 'lorem': ''}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '8403', 'sn': 'call', 'dolor': '2535', 'mail': 'chris.call@blah.com', 'givenName': 'chris', 'lorem': '3424'}]\n\nfive dicts, including those with missing ipsum etc. I fear that in your laudable attempt at simplifying the problem you've simplified it excessively, so that your bug has gone away.\nIf you have duplicates in column something (can't check, since you don't have that column in your sample data) that would of course explain the \"apparently missing\" rows -- they're not missing from the csv reader's returned stream, they get \"overwritten\" in the dict you're returning. Could that be the issue?\n",
"This may be nothing to do with your problem, and Alex's analysis is quite plausible given the lack of information, but you should ALWAYS open a csv file with \"rb\" or \"wb\" mode (assuming Python 2.X). If you don't, you run the risk of various mysterious happenings. A csv file is not a text file, it's a BINARY file.\nIn any case, please edit your question to show:\n(1) (a) a sample file (b) a script (c) output -- which together demonstrate the alleged problem\n(2) what version of Python you are running\n(3) what OS \nUpdate: For Python 3.X, do as the blessed manual says: \"\"\"If csvfile is a file object, it should be opened with newline=''. Although this advice is included only with csv.reader, it applies equally to csv.writer, csv.DictReader, and csv.DictWriter.\n"
] | [
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0002901422_csv_python.txt |
Q:
Difficulty using stackless python, cannot write to a dict
I have simple map-reduce type algorithm, which I want to implement in python and make use of multiple cores.
I read somewhere that threads using native thread module in 2.6 dont make use of multiple cores. is that true?
I even implemented it using stackless python however i am getting into weird errors
[Update: a quick search showed that the stack less does not allows multiple cores
So are their any other alternatives?]
def Propagate(start,end):
print "running Thread with range: ",start,end
def maxVote(nLabels):
count = {}
maxList = []
maxCount = 0
for nLabel in nLabels:
if nLabel in count:
count[nLabel] += 1
else:
count[nLabel] = 1
#Check if the count is max
if count[nLabel] > maxCount:
maxCount = count[nLabel];
maxList = [nLabel,]
elif count[nLabel]==maxCount:
maxList.append(nLabel)
return random.choice(maxList)
for num in range(start,end):
node=MapList[num]
nLabels = [Label[k] for k in Adj[node]]
if (nLabels!=[]):
Label[node] = maxVote(nLabels)
else:
Label[node]=node
However in above code the values assigned to Label, that is the change in dictionary are lost.
Above propagate function is used as callable for MicroThreads (i.e. TaskLets)
A:
Use the multiprocessing module of the standard library -- it mimics the interface of the threading module (to ease porting of existing multithreaded code) and can fully use all the cores you have. threading and stackless are both single-core (and indeed, stackless is non-preemptive, so programming for it is quite different than programming for either threading or multiprocessing).
| Difficulty using stackless python, cannot write to a dict | I have simple map-reduce type algorithm, which I want to implement in python and make use of multiple cores.
I read somewhere that threads using native thread module in 2.6 dont make use of multiple cores. is that true?
I even implemented it using stackless python however i am getting into weird errors
[Update: a quick search showed that the stack less does not allows multiple cores
So are their any other alternatives?]
def Propagate(start,end):
print "running Thread with range: ",start,end
def maxVote(nLabels):
count = {}
maxList = []
maxCount = 0
for nLabel in nLabels:
if nLabel in count:
count[nLabel] += 1
else:
count[nLabel] = 1
#Check if the count is max
if count[nLabel] > maxCount:
maxCount = count[nLabel];
maxList = [nLabel,]
elif count[nLabel]==maxCount:
maxList.append(nLabel)
return random.choice(maxList)
for num in range(start,end):
node=MapList[num]
nLabels = [Label[k] for k in Adj[node]]
if (nLabels!=[]):
Label[node] = maxVote(nLabels)
else:
Label[node]=node
However in above code the values assigned to Label, that is the change in dictionary are lost.
Above propagate function is used as callable for MicroThreads (i.e. TaskLets)
| [
"Use the multiprocessing module of the standard library -- it mimics the interface of the threading module (to ease porting of existing multithreaded code) and can fully use all the cores you have. threading and stackless are both single-core (and indeed, stackless is non-preemptive, so programming for it is quite different than programming for either threading or multiprocessing).\n"
] | [
1
] | [] | [] | [
"multithreading",
"python",
"python_stackless",
"stackless"
] | stackoverflow_0002901633_multithreading_python_python_stackless_stackless.txt |
Q:
Confusion Matrix with number of classified/misclassified instances on it (Python/Matplotlib)
I am plotting a confusion matrix with matplotlib with the following code:
from numpy import *
import matplotlib.pyplot as plt
from pylab import *
conf_arr = [[33,2,0,0,0,0,0,0,0,1,3], [3,31,0,0,0,0,0,0,0,0,0], [0,4,41,0,0,0,0,0,0,0,1], [0,1,0,30,0,6,0,0,0,0,1], [0,0,0,0,38,10,0,0,0,0,0], [0,0,0,3,1,39,0,0,0,0,4], [0,2,2,0,4,1,31,0,0,0,2], [0,1,0,0,0,0,0,36,0,2,0], [0,0,0,0,0,0,1,5,37,5,1], [3,0,0,0,0,0,0,0,0,39,0], [0,0,0,0,0,0,0,0,0,0,38] ]
norm_conf = []
for i in conf_arr:
a = 0
tmp_arr = []
a = sum(i,0)
for j in i:
tmp_arr.append(float(j)/float(a))
norm_conf.append(tmp_arr)
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111)
res = ax.imshow(array(norm_conf), cmap=cm.jet, interpolation='nearest')
cb = fig.colorbar(res)
savefig("confmat.png", format="png")
But I want to the confusion matrix to show the numbers on it like this graphic (the right one). How can I plot the conf_arr on the graphic?
A:
You can use text to put arbitrary text in your plot. For example, inserting the following lines into your code will write the numbers (note the first and last lines are from your code to show you where to insert my lines):
res = ax.imshow(array(norm_conf), cmap=cm.jet, interpolation='nearest')
for i, cas in enumerate(conf_arr):
for j, c in enumerate(cas):
if c>0:
plt.text(j-.2, i+.2, c, fontsize=14)
cb = fig.colorbar(res)
A:
The only way I could really see of doing it was to use annotations. Try these lines:
for i,j in ((x,y) for x in xrange(len(conf_arr))
for y in xrange(len(conf_arr[0]))):
ax.annotate(str(conf_arr[i][j]),xy=(i,j))
before saving the figure. It adds the numbers, but I'll let you figure out how to get the sizes of the numbers how you want them.
| Confusion Matrix with number of classified/misclassified instances on it (Python/Matplotlib) | I am plotting a confusion matrix with matplotlib with the following code:
from numpy import *
import matplotlib.pyplot as plt
from pylab import *
conf_arr = [[33,2,0,0,0,0,0,0,0,1,3], [3,31,0,0,0,0,0,0,0,0,0], [0,4,41,0,0,0,0,0,0,0,1], [0,1,0,30,0,6,0,0,0,0,1], [0,0,0,0,38,10,0,0,0,0,0], [0,0,0,3,1,39,0,0,0,0,4], [0,2,2,0,4,1,31,0,0,0,2], [0,1,0,0,0,0,0,36,0,2,0], [0,0,0,0,0,0,1,5,37,5,1], [3,0,0,0,0,0,0,0,0,39,0], [0,0,0,0,0,0,0,0,0,0,38] ]
norm_conf = []
for i in conf_arr:
a = 0
tmp_arr = []
a = sum(i,0)
for j in i:
tmp_arr.append(float(j)/float(a))
norm_conf.append(tmp_arr)
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111)
res = ax.imshow(array(norm_conf), cmap=cm.jet, interpolation='nearest')
cb = fig.colorbar(res)
savefig("confmat.png", format="png")
But I want to the confusion matrix to show the numbers on it like this graphic (the right one). How can I plot the conf_arr on the graphic?
| [
"You can use text to put arbitrary text in your plot. For example, inserting the following lines into your code will write the numbers (note the first and last lines are from your code to show you where to insert my lines):\nres = ax.imshow(array(norm_conf), cmap=cm.jet, interpolation='nearest')\nfor i, cas in enumerate(conf_arr):\n for j, c in enumerate(cas):\n if c>0:\n plt.text(j-.2, i+.2, c, fontsize=14)\ncb = fig.colorbar(res)\n\n\n",
"The only way I could really see of doing it was to use annotations. Try these lines:\nfor i,j in ((x,y) for x in xrange(len(conf_arr))\n for y in xrange(len(conf_arr[0]))):\n ax.annotate(str(conf_arr[i][j]),xy=(i,j))\n\nbefore saving the figure. It adds the numbers, but I'll let you figure out how to get the sizes of the numbers how you want them.\n"
] | [
10,
1
] | [] | [] | [
"confusion_matrix",
"matplotlib",
"python"
] | stackoverflow_0002897826_confusion_matrix_matplotlib_python.txt |
Q:
Do you have suggestions for these assembly mnemonics?
Last semester in college, my teacher in the Computer Languages class taught us the esoteric language named Whitespace. In the interest of learning the language better with a very busy schedule (midterms), I wrote an interpreter and assembler in Python. An assembly language was designed to facilitate writing programs easily, and a sample program was written with the given assembly mnemonics.
Now that it is summer, a new project has begun with the objective being to rewrite the interpreter and assembler for Whitespace 0.3, with further developments coming afterwards. Since there is so much extra time than before to work on its design, you are presented here with an outline that provides a revised set of mnemonics for the assembly language. This post is marked as a wiki for their discussion.
Have you ever had any experience with assembly languages in the past? Were there some instructions that you thought should have been renamed to something different? Did you find yourself thinking outside the box and with a different paradigm than in which the mnemonics were named? If you can answer yes to any of those questions, you are most welcome here. Subjective answers are appreciated!
Stack Manipulation (IMP: [Space])
Stack manipulation is one of the more common operations, hence the shortness of the IMP [Space]. There are four stack instructions.
hold N Push the number onto the stack
copy Duplicate the top item on the stack
copy N Copy the nth item on the stack (given by the argument) onto the top of the stack
swap Swap the top two items on the stack
drop Discard the top item on the stack
drop N Slide n items off the stack, keeping the top item
Arithmetic (IMP: [Tab][Space])
Arithmetic commands operate on the top two items on the stack, and replace them with the result of the operation. The first item pushed is considered to be left of the operator.
add Addition
sub Subtraction
mul Multiplication
div Integer Division
mod Modulo
Heap Access (IMP: [Tab][Tab])
Heap access commands look at the stack to find the address of items to be stored or retrieved. To store an item, push the address then the value and run the store command. To retrieve an item, push the address and run the retrieve command, which will place the value stored in the location at the top of the stack.
save Store
load Retrieve
Flow Control (IMP: [LF])
Flow control operations are also common. Subroutines are marked by labels, as well as the targets of conditional and unconditional jumps, by which loops can be implemented. Programs must be ended by means of [LF][LF][LF] so that the interpreter can exit cleanly.
L: Mark a location in the program
call L Call a subroutine
goto L Jump unconditionally to a label
if=0 L Jump to a label if the top of the stack is zero
if<0 L Jump to a label if the top of the stack is negative
return End a subroutine and transfer control back to the caller
halt End the program
I/O (IMP: [Tab][LF])
Finally, we need to be able to interact with the user. There are IO instructions for reading and writing numbers and individual characters. With these, string manipulation routines can be written. The read instructions take the heap address in which to store the result from the top of the stack.
print chr Output the character at the top of the stack
print int Output the number at the top of the stack
input chr Read a character and place it in the location given by the top of the stack
input int Read a number and place it in the location given by the top of the stack
Question: How would you redesign, rewrite, or rename the previous mnemonics and for what reasons?
A:
I think the first change I'd propose is changing hold and drop to push and pop respectively.
Then maybe I'd rename copy to dup (I think that's the most common name for this operation in stack oriented languages).
I'm a little puzzled why often you have short one word explanations that are different to the mnemonic. For example mnemonic is Save, explanation is Store. Mnemonic is Load, explanation is Retrieve. Incidentally those are the two mnemonics that aren't sufficiently explained to me. Save what where? Load what from where? (Edit the question has subsequently been edited to make these meanings clear)
Thanks for the interesting post.
A:
push #n, to make it clear that n is an immediate.
"swap" is sometimes "exc" or "exch" I think.
"save" is usually "st" (store)
"load" is usually "ld"
"call" could also be "jsr" or "bl".
"goto" is usually "jmp" or "bra"
"if=0" is usually "beq"
"if<0" is usually "blt"
"return" is usually "ret" or "blr"
"exit" is usually "halt"/"hlt" in the context of a CPU.
"print chr" and "print int" could be "print.c" and "print.i". There are many ways to specify instruction variants, but usually it's not in the operands.
EDIT:
If you don't mind conflating opcodes and addressing modes, using CISCy syntax,
"push (sp)" instead of "copy"
"push N(sp)" instead of "copy N" (modulo multiplying by the word size)
"push *(sp)" instead of "load" (except it does a pop before pushing the loaded values)
"pop *1(sp)" instead of "push" (except it actually pops twice)
On the other hand, stack-based code usually treats push and pop as implicit. In that case, "imm n" (immediate) instead of "push". Then all stack operations are purely stack operations, which is nice and consistent.
I'm not sure how I'd write "drop N" — the description makes it sound like "drop 1" isn't equivalent to "drop" which seems odd.
A:
I'm not sure I completely understand your question, so if I'm off base, forgive me.
In addition to your stack, I would probably add a "status register" that contains a variety of different flags (like Carry, Overflow, and Zero) that are set by the arithmatic operators.
I would then add "if" forms that test those flags.
I would add bit shift and rotate (both left and right) instructions, as well as AND/OR/XOR/NOT operations that operate on bits.
You will most likely want to have some sort of memory access, unless you intend the I/O instructions to treat memory as a stream of values for that good ol' fashioned Turing Machine feel.
| Do you have suggestions for these assembly mnemonics? | Last semester in college, my teacher in the Computer Languages class taught us the esoteric language named Whitespace. In the interest of learning the language better with a very busy schedule (midterms), I wrote an interpreter and assembler in Python. An assembly language was designed to facilitate writing programs easily, and a sample program was written with the given assembly mnemonics.
Now that it is summer, a new project has begun with the objective being to rewrite the interpreter and assembler for Whitespace 0.3, with further developments coming afterwards. Since there is so much extra time than before to work on its design, you are presented here with an outline that provides a revised set of mnemonics for the assembly language. This post is marked as a wiki for their discussion.
Have you ever had any experience with assembly languages in the past? Were there some instructions that you thought should have been renamed to something different? Did you find yourself thinking outside the box and with a different paradigm than in which the mnemonics were named? If you can answer yes to any of those questions, you are most welcome here. Subjective answers are appreciated!
Stack Manipulation (IMP: [Space])
Stack manipulation is one of the more common operations, hence the shortness of the IMP [Space]. There are four stack instructions.
hold N Push the number onto the stack
copy Duplicate the top item on the stack
copy N Copy the nth item on the stack (given by the argument) onto the top of the stack
swap Swap the top two items on the stack
drop Discard the top item on the stack
drop N Slide n items off the stack, keeping the top item
Arithmetic (IMP: [Tab][Space])
Arithmetic commands operate on the top two items on the stack, and replace them with the result of the operation. The first item pushed is considered to be left of the operator.
add Addition
sub Subtraction
mul Multiplication
div Integer Division
mod Modulo
Heap Access (IMP: [Tab][Tab])
Heap access commands look at the stack to find the address of items to be stored or retrieved. To store an item, push the address then the value and run the store command. To retrieve an item, push the address and run the retrieve command, which will place the value stored in the location at the top of the stack.
save Store
load Retrieve
Flow Control (IMP: [LF])
Flow control operations are also common. Subroutines are marked by labels, as well as the targets of conditional and unconditional jumps, by which loops can be implemented. Programs must be ended by means of [LF][LF][LF] so that the interpreter can exit cleanly.
L: Mark a location in the program
call L Call a subroutine
goto L Jump unconditionally to a label
if=0 L Jump to a label if the top of the stack is zero
if<0 L Jump to a label if the top of the stack is negative
return End a subroutine and transfer control back to the caller
halt End the program
I/O (IMP: [Tab][LF])
Finally, we need to be able to interact with the user. There are IO instructions for reading and writing numbers and individual characters. With these, string manipulation routines can be written. The read instructions take the heap address in which to store the result from the top of the stack.
print chr Output the character at the top of the stack
print int Output the number at the top of the stack
input chr Read a character and place it in the location given by the top of the stack
input int Read a number and place it in the location given by the top of the stack
Question: How would you redesign, rewrite, or rename the previous mnemonics and for what reasons?
| [
"I think the first change I'd propose is changing hold and drop to push and pop respectively.\nThen maybe I'd rename copy to dup (I think that's the most common name for this operation in stack oriented languages).\nI'm a little puzzled why often you have short one word explanations that are different to the mnemonic. For example mnemonic is Save, explanation is Store. Mnemonic is Load, explanation is Retrieve. Incidentally those are the two mnemonics that aren't sufficiently explained to me. Save what where? Load what from where? (Edit the question has subsequently been edited to make these meanings clear)\nThanks for the interesting post.\n",
"\npush #n, to make it clear that n is an immediate.\n\"swap\" is sometimes \"exc\" or \"exch\" I think.\n\"save\" is usually \"st\" (store)\n\"load\" is usually \"ld\"\n\"call\" could also be \"jsr\" or \"bl\".\n\"goto\" is usually \"jmp\" or \"bra\"\n\"if=0\" is usually \"beq\"\n\"if<0\" is usually \"blt\"\n\"return\" is usually \"ret\" or \"blr\"\n\"exit\" is usually \"halt\"/\"hlt\" in the context of a CPU.\n\"print chr\" and \"print int\" could be \"print.c\" and \"print.i\". There are many ways to specify instruction variants, but usually it's not in the operands.\n\nEDIT:\nIf you don't mind conflating opcodes and addressing modes, using CISCy syntax,\n\n\"push (sp)\" instead of \"copy\"\n\"push N(sp)\" instead of \"copy N\" (modulo multiplying by the word size)\n\"push *(sp)\" instead of \"load\" (except it does a pop before pushing the loaded values)\n\"pop *1(sp)\" instead of \"push\" (except it actually pops twice)\n\nOn the other hand, stack-based code usually treats push and pop as implicit. In that case, \"imm n\" (immediate) instead of \"push\". Then all stack operations are purely stack operations, which is nice and consistent.\nI'm not sure how I'd write \"drop N\" — the description makes it sound like \"drop 1\" isn't equivalent to \"drop\" which seems odd.\n",
"I'm not sure I completely understand your question, so if I'm off base, forgive me.\nIn addition to your stack, I would probably add a \"status register\" that contains a variety of different flags (like Carry, Overflow, and Zero) that are set by the arithmatic operators.\nI would then add \"if\" forms that test those flags.\nI would add bit shift and rotate (both left and right) instructions, as well as AND/OR/XOR/NOT operations that operate on bits.\nYou will most likely want to have some sort of memory access, unless you intend the I/O instructions to treat memory as a stream of values for that good ol' fashioned Turing Machine feel.\n"
] | [
4,
3,
1
] | [] | [] | [
"assembly",
"esoteric_languages",
"mnemonics",
"python",
"whitespace"
] | stackoverflow_0002901274_assembly_esoteric_languages_mnemonics_python_whitespace.txt |
Q:
What's the best way to send user-inputted text via AJAX to Google App Engine?
I'm developing in Google App Engine (python sdk) and I want to use jQuery to send an Ajax request to store an answer to a question.
What is the best way to send this data to the server? Currently I have:
function storeItem(question_id) {
var answerInputControl = ".input_answer_"+question_id;
var answer_text = $(answerInputControl).text();
$.ajax({
type: "POST",
url: "store_answer.html",
data: "question="+question_id,
success: function(responseText){
alert("Retrieved: " + responseText);
}
});
}
This takes a question Id and provides it to the server via the query string. But on the server-side, I'm unable to access the content of the answer control which I want to store. Without Ajax, I'm able to perform this operation with the following:
class StoreAnswers(webapp.RequestHandler):
def post(self):
question_id = self.request.get("question_id")
answer_text = self.request.get("input_answer" + question_id)
But when doing this call through Ajax, my answer_text is empty.
Do I need to send the contents of this control as part of the data with the Ajax request?
Do I add the control itself to the query string? Its contents? Does it matter that the content might be a few hundred characters long? Is this the most-recommended practice?
If sending it as a query string, what's the best way to escape the content so that a malicious user doesn't harm the system?
A:
The data in your ajax call must include all the data you want to send -- posting a few hundred characters is absolutely no problem and it's most definitely the recommended approach.
Do not use a GET in lieu of POST -- that (which I suspect is what you mean by "send as a query string") would only buy you trouble of all sorts, and is a violation of the semantics of GET (which should be limited to "read-only" queries, ones with no side effects).
A:
Your data is incorrectly formatted:
data: {
question_id: question_id,
input_answer: $(answerInputControl).text()
}
| What's the best way to send user-inputted text via AJAX to Google App Engine? | I'm developing in Google App Engine (python sdk) and I want to use jQuery to send an Ajax request to store an answer to a question.
What is the best way to send this data to the server? Currently I have:
function storeItem(question_id) {
var answerInputControl = ".input_answer_"+question_id;
var answer_text = $(answerInputControl).text();
$.ajax({
type: "POST",
url: "store_answer.html",
data: "question="+question_id,
success: function(responseText){
alert("Retrieved: " + responseText);
}
});
}
This takes a question Id and provides it to the server via the query string. But on the server-side, I'm unable to access the content of the answer control which I want to store. Without Ajax, I'm able to perform this operation with the following:
class StoreAnswers(webapp.RequestHandler):
def post(self):
question_id = self.request.get("question_id")
answer_text = self.request.get("input_answer" + question_id)
But when doing this call through Ajax, my answer_text is empty.
Do I need to send the contents of this control as part of the data with the Ajax request?
Do I add the control itself to the query string? Its contents? Does it matter that the content might be a few hundred characters long? Is this the most-recommended practice?
If sending it as a query string, what's the best way to escape the content so that a malicious user doesn't harm the system?
| [
"The data in your ajax call must include all the data you want to send -- posting a few hundred characters is absolutely no problem and it's most definitely the recommended approach.\nDo not use a GET in lieu of POST -- that (which I suspect is what you mean by \"send as a query string\") would only buy you trouble of all sorts, and is a violation of the semantics of GET (which should be limited to \"read-only\" queries, ones with no side effects).\n",
"Your data is incorrectly formatted:\ndata: {\n question_id: question_id,\n input_answer: $(answerInputControl).text()\n}\n\n"
] | [
2,
1
] | [] | [] | [
"ajax",
"google_app_engine",
"jquery",
"python"
] | stackoverflow_0002901793_ajax_google_app_engine_jquery_python.txt |
Q:
Internal Server Error with mod_wsgi [django] on windows xp
when i run development server it works very well, even an empty project runing in mod_wsgi i have no problem but when i want to put my own project i get an Internal Server Error (500)
in my apache conf i put
WSGIScriptAlias /codevents C:/django/apache/CODEvents.wsgi
<Directory "C:/django/apache">
Order allow,deny
Allow from all
</Directory>
Alias /codevents/media C:/django/projects/CODEvents/html
<Directory "C:/django/projects/CODEvents/html">
Order allow,deny
Allow from all
</Directory>
in CODEvents.wsgi
import os, sys
sys.path.append('C:\\Python26\\Lib\\site-packages\\django')
sys.path.append('C:\\django\\projects')
sys.path.append('C:\\django\\apps')
sys.path.append('C:\\django\\projects\\CODEvents')
os.environ['DJANGO_SETTINGS_MODULE'] = 'CODEvents.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
and in my error_log it said:
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] mod_wsgi (pid=1848): Exception occurred processing WSGI script 'C:/django/apache/CODEvents.wsgi'.
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] Traceback (most recent call last):
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\core\\handlers\\wsgi.py", line 241, in __call__
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] response = self.get_response(request)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\core\\handlers\\base.py", line 142, in get_response
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self.handle_uncaught_exception(request, resolver, exc_info)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\core\\handlers\\base.py", line 166, in handle_uncaught_exception
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return debug.technical_500_response(request, *exc_info)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\views\\debug.py", line 58, in technical_500_response
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] html = reporter.get_traceback_html()
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\views\\debug.py", line 137, in get_traceback_html
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return t.render(c)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\__init__.py", line 173, in render
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self._render(context)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\__init__.py", line 167, in _render
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self.nodelist.render(context)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\__init__.py", line 796, in render
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] bits.append(self.render_node(node, context))
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\debug.py", line 72, in render_node
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] result = node.render(context)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\debug.py", line 89, in render
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] output = self.filter_expression.resolve(context)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\__init__.py", line 579, in resolve
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] new_obj = func(obj, *arg_vals)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\defaultfilters.py", line 693, in date
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return format(value, arg)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\dateformat.py", line 281, in format
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return df.format(format_string)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\dateformat.py", line 30, in format
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] pieces.append(force_unicode(getattr(self, piece)()))
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\dateformat.py", line 187, in r
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self.format('D, j M Y H:i:s O')
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\dateformat.py", line 30, in format
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] pieces.append(force_unicode(getattr(self, piece)()))
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\encoding.py", line 66, in force_unicode
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] s = unicode(s)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\functional.py", line 206, in __unicode_cast
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self.__func(*self.__args, **self.__kw)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\__init__.py", line 55, in ugettext
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return real_ugettext(message)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\functional.py", line 55, in _curried
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\__init__.py", line 36, in delayed_loader
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return getattr(trans, real_name)(*args, **kwargs)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\trans_real.py", line 276, in ugettext
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return do_translate(message, 'ugettext')
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\trans_real.py", line 266, in do_translate
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] _default = translation(settings.LANGUAGE_CODE)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\trans_real.py", line 176, in translation
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] default_translation = _fetch(settings.LANGUAGE_CODE)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\trans_real.py", line 159, in _fetch
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] app = import_module(appname)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\importlib.py", line 35, in import_module
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] __import__(name)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\contrib\\admin\\__init__.py", line 1, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\contrib\\admin\\helpers.py", line 1, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] from django import forms
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\forms\\__init__.py", line 17, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] from models import *
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\forms\\models.py", line 6, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] from django.db import connections
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\db\\__init__.py", line 75, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] connection = connections[DEFAULT_DB_ALIAS]
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\db\\utils.py", line 91, in __getitem__
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] backend = load_backend(db['ENGINE'])
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\db\\utils.py", line 49, in load_backend
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] raise ImproperlyConfigured(error_msg)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] TemplateSyntaxError: Caught ImproperlyConfigured while rendering: 'django.db.backends.postgresql_psycopg2' isn't an available database backend.
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] Try using django.db.backends.XXX, where XXX is one of:
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] 'dummy', 'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3'
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] Error was: cannot import name utils
please help me!!
A:
The error says that Python module for PostgreSQL client isn't found or failed to import. Where did you install it? Are the files accessible by Apache service, which runs as a distinct user to yourself?
A:
Well in fact my problem was pyscopg2 windows version, i was using the latest (2.2.1) and i just downgrade to 2.0.14 and it's alive!!!
| Internal Server Error with mod_wsgi [django] on windows xp | when i run development server it works very well, even an empty project runing in mod_wsgi i have no problem but when i want to put my own project i get an Internal Server Error (500)
in my apache conf i put
WSGIScriptAlias /codevents C:/django/apache/CODEvents.wsgi
<Directory "C:/django/apache">
Order allow,deny
Allow from all
</Directory>
Alias /codevents/media C:/django/projects/CODEvents/html
<Directory "C:/django/projects/CODEvents/html">
Order allow,deny
Allow from all
</Directory>
in CODEvents.wsgi
import os, sys
sys.path.append('C:\\Python26\\Lib\\site-packages\\django')
sys.path.append('C:\\django\\projects')
sys.path.append('C:\\django\\apps')
sys.path.append('C:\\django\\projects\\CODEvents')
os.environ['DJANGO_SETTINGS_MODULE'] = 'CODEvents.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
and in my error_log it said:
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] mod_wsgi (pid=1848): Exception occurred processing WSGI script 'C:/django/apache/CODEvents.wsgi'.
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] Traceback (most recent call last):
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\core\\handlers\\wsgi.py", line 241, in __call__
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] response = self.get_response(request)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\core\\handlers\\base.py", line 142, in get_response
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self.handle_uncaught_exception(request, resolver, exc_info)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\core\\handlers\\base.py", line 166, in handle_uncaught_exception
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return debug.technical_500_response(request, *exc_info)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\views\\debug.py", line 58, in technical_500_response
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] html = reporter.get_traceback_html()
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\views\\debug.py", line 137, in get_traceback_html
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return t.render(c)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\__init__.py", line 173, in render
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self._render(context)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\__init__.py", line 167, in _render
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self.nodelist.render(context)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\__init__.py", line 796, in render
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] bits.append(self.render_node(node, context))
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\debug.py", line 72, in render_node
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] result = node.render(context)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\debug.py", line 89, in render
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] output = self.filter_expression.resolve(context)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\__init__.py", line 579, in resolve
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] new_obj = func(obj, *arg_vals)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\template\\defaultfilters.py", line 693, in date
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return format(value, arg)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\dateformat.py", line 281, in format
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return df.format(format_string)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\dateformat.py", line 30, in format
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] pieces.append(force_unicode(getattr(self, piece)()))
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\dateformat.py", line 187, in r
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self.format('D, j M Y H:i:s O')
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\dateformat.py", line 30, in format
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] pieces.append(force_unicode(getattr(self, piece)()))
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\encoding.py", line 66, in force_unicode
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] s = unicode(s)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\functional.py", line 206, in __unicode_cast
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return self.__func(*self.__args, **self.__kw)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\__init__.py", line 55, in ugettext
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return real_ugettext(message)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\functional.py", line 55, in _curried
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\__init__.py", line 36, in delayed_loader
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return getattr(trans, real_name)(*args, **kwargs)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\trans_real.py", line 276, in ugettext
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] return do_translate(message, 'ugettext')
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\trans_real.py", line 266, in do_translate
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] _default = translation(settings.LANGUAGE_CODE)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\trans_real.py", line 176, in translation
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] default_translation = _fetch(settings.LANGUAGE_CODE)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\translation\\trans_real.py", line 159, in _fetch
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] app = import_module(appname)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\utils\\importlib.py", line 35, in import_module
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] __import__(name)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\contrib\\admin\\__init__.py", line 1, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\contrib\\admin\\helpers.py", line 1, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] from django import forms
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\forms\\__init__.py", line 17, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] from models import *
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\forms\\models.py", line 6, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] from django.db import connections
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\db\\__init__.py", line 75, in <module>
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] connection = connections[DEFAULT_DB_ALIAS]
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\db\\utils.py", line 91, in __getitem__
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] backend = load_backend(db['ENGINE'])
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] File "C:\\Python26\\lib\\site-packages\\django\\db\\utils.py", line 49, in load_backend
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] raise ImproperlyConfigured(error_msg)
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] TemplateSyntaxError: Caught ImproperlyConfigured while rendering: 'django.db.backends.postgresql_psycopg2' isn't an available database backend.
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] Try using django.db.backends.XXX, where XXX is one of:
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] 'dummy', 'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3'
[Mon May 24 23:31:39 2010] [error] [client 127.0.0.1] Error was: cannot import name utils
please help me!!
| [
"The error says that Python module for PostgreSQL client isn't found or failed to import. Where did you install it? Are the files accessible by Apache service, which runs as a distinct user to yourself?\n",
"Well in fact my problem was pyscopg2 windows version, i was using the latest (2.2.1) and i just downgrade to 2.0.14 and it's alive!!!\n"
] | [
1,
0
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0002901631_apache_django_mod_wsgi_python.txt |
Q:
programs hangs during socket interaction
I have two programs, sendfile.py and recvfile.py that are supposed to interact to send a file across the network. They communicate over TCP sockets. The communication is supposed to go something like this:
sender =====filename=====> receiver
sender <===== 'ok' ======= receiver
or
sender <===== 'no' ======= receiver
if ok:
sender ====== file ======> receiver
I've got
The sender and receiver code is here:
Sender:
import sys
from jmm_sockets import *
if len(sys.argv) != 4:
print "Usage:", sys.argv[0], "<host> <port> <filename>"
sys.exit(1)
s = getClientSocket(sys.argv[1], int(sys.argv[2]))
try:
f = open(sys.argv[3])
except IOError, msg:
print "couldn't open file"
sys.exit(1)
# send filename
s.send(sys.argv[3])
# receive 'ok'
buffer = None
response = str()
while 1:
buffer = s.recv(1)
if buffer == '':
break
else:
response = response + buffer
if response == 'ok':
print 'receiver acknowledged receipt of filename'
# send file
s.send(f.read())
elif response == 'no':
print "receiver doesn't want the file"
# cleanup
f.close()
s.close()
Receiver:
from jmm_sockets import *
s = getServerSocket(None, 16001)
conn, addr = s.accept()
buffer = None
filename = str()
# receive filename
while 1:
buffer = conn.recv(1)
if buffer == '':
break
else:
filename = filename + buffer
print "sender wants to send", filename, "is that ok?"
user_choice = raw_input("ok/no: ")
if user_choice == 'ok':
# send ok
conn.send('ok')
#receive file
data = str()
while 1:
buffer = conn.recv(1)
if buffer=='':
break
else:
data = data + buffer
print data
else:
conn.send('no')
conn.close()
I'm sure I'm missing something here in the sorts of a deadlock, but don't know what it is.
A:
With blocking sockets, which are the default and I assume are what you're using (can't be sure since you're using a mysterious module jmm_sockets), the recv method is blocking -- it will not return an empty string when it has "nothing more to return for the moment", as you seem to assume.
You could work around this, for example, by sending an explicit terminator character (that must never occur within a filename), e.g. '\xff', after the actual string you want to send, and waiting for it at the other end as the indication that all the string has now been received.
A:
TCP is a streaming protocol. It has no concept of message boundaries. For a blocking socket, recv(n) will return a zero-length string only when the sender has closed the socket or explicitly called shutdown(SHUT_WR). Otherwise it can return a string from one to n bytes in length, and will block until it has at least one byte to return.
It is up to you to design a protocol to determine when you have a complete message. A few ways are:
Use a fixed-length message.
Send a fixed-length message indicating the total message length, followed by the variable portion of the message.
Send the message, followed by a unique termination message that will never occur in the message.
Another issue you may face is that send() is not guaranteed to send all the data. The return value indicates how many bytes were actually sent, and it is the sender's responsibility to keep calling send with the remaining message bytes until they are all sent. You may rather use the sendall() method.
| programs hangs during socket interaction | I have two programs, sendfile.py and recvfile.py that are supposed to interact to send a file across the network. They communicate over TCP sockets. The communication is supposed to go something like this:
sender =====filename=====> receiver
sender <===== 'ok' ======= receiver
or
sender <===== 'no' ======= receiver
if ok:
sender ====== file ======> receiver
I've got
The sender and receiver code is here:
Sender:
import sys
from jmm_sockets import *
if len(sys.argv) != 4:
print "Usage:", sys.argv[0], "<host> <port> <filename>"
sys.exit(1)
s = getClientSocket(sys.argv[1], int(sys.argv[2]))
try:
f = open(sys.argv[3])
except IOError, msg:
print "couldn't open file"
sys.exit(1)
# send filename
s.send(sys.argv[3])
# receive 'ok'
buffer = None
response = str()
while 1:
buffer = s.recv(1)
if buffer == '':
break
else:
response = response + buffer
if response == 'ok':
print 'receiver acknowledged receipt of filename'
# send file
s.send(f.read())
elif response == 'no':
print "receiver doesn't want the file"
# cleanup
f.close()
s.close()
Receiver:
from jmm_sockets import *
s = getServerSocket(None, 16001)
conn, addr = s.accept()
buffer = None
filename = str()
# receive filename
while 1:
buffer = conn.recv(1)
if buffer == '':
break
else:
filename = filename + buffer
print "sender wants to send", filename, "is that ok?"
user_choice = raw_input("ok/no: ")
if user_choice == 'ok':
# send ok
conn.send('ok')
#receive file
data = str()
while 1:
buffer = conn.recv(1)
if buffer=='':
break
else:
data = data + buffer
print data
else:
conn.send('no')
conn.close()
I'm sure I'm missing something here in the sorts of a deadlock, but don't know what it is.
| [
"With blocking sockets, which are the default and I assume are what you're using (can't be sure since you're using a mysterious module jmm_sockets), the recv method is blocking -- it will not return an empty string when it has \"nothing more to return for the moment\", as you seem to assume.\nYou could work around this, for example, by sending an explicit terminator character (that must never occur within a filename), e.g. '\\xff', after the actual string you want to send, and waiting for it at the other end as the indication that all the string has now been received.\n",
"TCP is a streaming protocol. It has no concept of message boundaries. For a blocking socket, recv(n) will return a zero-length string only when the sender has closed the socket or explicitly called shutdown(SHUT_WR). Otherwise it can return a string from one to n bytes in length, and will block until it has at least one byte to return.\nIt is up to you to design a protocol to determine when you have a complete message. A few ways are:\n\nUse a fixed-length message.\nSend a fixed-length message indicating the total message length, followed by the variable portion of the message.\nSend the message, followed by a unique termination message that will never occur in the message.\n\nAnother issue you may face is that send() is not guaranteed to send all the data. The return value indicates how many bytes were actually sent, and it is the sender's responsibility to keep calling send with the remaining message bytes until they are all sent. You may rather use the sendall() method.\n"
] | [
3,
2
] | [] | [] | [
"communication_protocol",
"network_programming",
"python",
"sockets"
] | stackoverflow_0002901350_communication_protocol_network_programming_python_sockets.txt |
Q:
python read utf8 text file problem
I have a problem with python about reading and print utf8 text file.
I have a test.txt in utf8 encoding without BOM. This file has two characters in it:
大声
The first character "大" is Chinese and the second "声" is Japanese. Now, When I use Ulipad (a python editor) to run the following code to read the txt file, and print these two characters.
import codecs
infile = "C:\\test.txt"
f = codecs.open(infile, "r", "utf-8")
s = f.read()
print(s)
I got this error,
"UnicodeEncodeError: 'cp950' codec can't encode character '\u58f0' in position 1:
illegal multibyte sequence"
I found it caused from the second character "声" .
But when I use the same code to test in python default GUI IDLE, it works to print the two characters with no error. So, how can I fix the problem.
My running environment is python 3.1 , windows xp traditional Chinese.
A:
You get the error when you are printing because:
(1) Ulipad is printing to sys.stdout which is the stdout of the legacy MS-DOS Command Prompt window.
(2) Your traditional chinese Windows XP uses cp950 encoding, which is big5 plus Microsoftian fiddling.
(3) You say your 2nd character is Japanese by which you probably mean that it's not also Chinese and thus unlikely to be a valid character in big5+.
On the other hand IDLE is writing to its own window and is not bound on the MS-DOS wheel :-) ... so there's a much greater repertoire of characters that it can print.
A:
声 may be Japanese, but it is also the Simplified Chinese for "sound" (traditional 聲). cp950 is Traditional Chinese and doesn't support that simplified character.
Since you are using a Chinese version of Windows, you may be able to change your default code page to cp936 (Unified Chinese) and see the output.
I'm unfamiliar with Ulipad, but try running in a Windows console:
chcp 936
and then running your script. If that doesn't work, you can change the default language for non-Unicode programs through Control Panel, Regional and Language Options, Advanced tab. This is how I was able to print Chinese in a console on my US English-based Windows.
Update
Reading about Ulipad, it says:
Multilanguage support Currently
supports 4 languages: English,
Spanish, Simplified Chinese and
Traditional Chinese, which can be
auto-detected.
Perhaps you can override the auto-detected Traditional Chinese to Simplified Chinese, which may select a code page and/or font that supports that particular character. Since it doesn't support Japanese, there will probably still be characters you can't display properly.
| python read utf8 text file problem | I have a problem with python about reading and print utf8 text file.
I have a test.txt in utf8 encoding without BOM. This file has two characters in it:
大声
The first character "大" is Chinese and the second "声" is Japanese. Now, When I use Ulipad (a python editor) to run the following code to read the txt file, and print these two characters.
import codecs
infile = "C:\\test.txt"
f = codecs.open(infile, "r", "utf-8")
s = f.read()
print(s)
I got this error,
"UnicodeEncodeError: 'cp950' codec can't encode character '\u58f0' in position 1:
illegal multibyte sequence"
I found it caused from the second character "声" .
But when I use the same code to test in python default GUI IDLE, it works to print the two characters with no error. So, how can I fix the problem.
My running environment is python 3.1 , windows xp traditional Chinese.
| [
"You get the error when you are printing because:\n(1) Ulipad is printing to sys.stdout which is the stdout of the legacy MS-DOS Command Prompt window.\n(2) Your traditional chinese Windows XP uses cp950 encoding, which is big5 plus Microsoftian fiddling.\n(3) You say your 2nd character is Japanese by which you probably mean that it's not also Chinese and thus unlikely to be a valid character in big5+.\nOn the other hand IDLE is writing to its own window and is not bound on the MS-DOS wheel :-) ... so there's a much greater repertoire of characters that it can print.\n",
"声 may be Japanese, but it is also the Simplified Chinese for \"sound\" (traditional 聲). cp950 is Traditional Chinese and doesn't support that simplified character.\nSince you are using a Chinese version of Windows, you may be able to change your default code page to cp936 (Unified Chinese) and see the output.\nI'm unfamiliar with Ulipad, but try running in a Windows console:\nchcp 936\n\nand then running your script. If that doesn't work, you can change the default language for non-Unicode programs through Control Panel, Regional and Language Options, Advanced tab. This is how I was able to print Chinese in a console on my US English-based Windows.\nUpdate\nReading about Ulipad, it says:\n\nMultilanguage support Currently\n supports 4 languages: English,\n Spanish, Simplified Chinese and\n Traditional Chinese, which can be\n auto-detected.\n\nPerhaps you can override the auto-detected Traditional Chinese to Simplified Chinese, which may select a code page and/or font that supports that particular character. Since it doesn't support Japanese, there will probably still be characters you can't display properly.\n"
] | [
7,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0002896786_python_unicode.txt |
Q:
Python doctests / sphinx : style guide, how to use those and have a readable code?
I love doctests, it is the only testing framwork I use, because it is so quick to write, and because used with sphinx it makes such great documentations with almost no effort...
However, very often, I end-up doing things like this :
"""
Descriptions
=============
bla bla bla ...
>>> test
1
bla bla bla + tests tests tests * 200 lines = poor readability of the actual code
"""
What I mean is that I put all my tests with documentation explanations on the top of the module, so you have to scroll stupidly to find the actual code, and this is quite ugly (in my opinion). However, I think that the doctests should still stay in the module, because you should be able to read them while reading the source code.
So here comes my question : sphinx/doctests lovers, how do you organize your doctests, such as the code readability doesn't suffer ? Is there a style guide for doctests, for sphinx ? For docstring with sphinx, do you use google or sphinx style-guide or something else ?
A:
I think there are two sorts of doctest.
You can put something in the docstring for the function, but if so keep it short and simple.
The other option is full documentation/tutorial, and I do that as a separate file.
Unlike ordinary documentation, the beauty of doctesting is that you can be sure they are going to stay in sync with the code even if they aren't in the same screen. When reading the code you want to see code, perhaps with a little descriptive text. When reading a tutorial you don't want to see the code just the examples.
| Python doctests / sphinx : style guide, how to use those and have a readable code? | I love doctests, it is the only testing framwork I use, because it is so quick to write, and because used with sphinx it makes such great documentations with almost no effort...
However, very often, I end-up doing things like this :
"""
Descriptions
=============
bla bla bla ...
>>> test
1
bla bla bla + tests tests tests * 200 lines = poor readability of the actual code
"""
What I mean is that I put all my tests with documentation explanations on the top of the module, so you have to scroll stupidly to find the actual code, and this is quite ugly (in my opinion). However, I think that the doctests should still stay in the module, because you should be able to read them while reading the source code.
So here comes my question : sphinx/doctests lovers, how do you organize your doctests, such as the code readability doesn't suffer ? Is there a style guide for doctests, for sphinx ? For docstring with sphinx, do you use google or sphinx style-guide or something else ?
| [
"I think there are two sorts of doctest.\n\nYou can put something in the docstring for the function, but if so keep it short and simple.\nThe other option is full documentation/tutorial, and I do that as a separate file.\n\nUnlike ordinary documentation, the beauty of doctesting is that you can be sure they are going to stay in sync with the code even if they aren't in the same screen. When reading the code you want to see code, perhaps with a little descriptive text. When reading a tutorial you don't want to see the code just the examples.\n"
] | [
3
] | [] | [] | [
"doctest",
"python",
"python_sphinx",
"readability"
] | stackoverflow_0002902476_doctest_python_python_sphinx_readability.txt |
Q:
Using Memcached in Python/Django - questions
I am starting use Memcached to make my website faster.
For constant data in my database I use this:
from django.core.cache import cache
cache_key = 'regions'
regions = cache.get(cache_key)
if result is None:
"""Not Found in Cache"""
regions = Regions.objects.all()
cache.set(cache_key, regions, 2592000) #(2592000sekund = 30 dni)
return regions
For seldom data changes I use signals:
from django.core.cache import cache
from django.db.models import signals
def nuke_social_network_cache(self, instance, **kwargs):
cache_key = 'networks_for_%s' % (self.instance.user_id,)
cache.delete(cache_key)
signals.post_save.connect(nuke_social_network_cache, sender=SocialNetworkProfile)
signals.post_delete.connect(nuke_social_network_cache, sender=SocialNetworkProfile)
Is it correct way?
I have installed django-memcached-0.1.2, which show me:
Memcached Server Stats
Server Keys Hits Gets Hit_Rate Traffic_In Traffic_Out Usage Uptime
127.0.0.1 15 220 276 79% 83.1 KB 364.1 KB 18.4 KB 22:21:25
Can somebody explain what columns means?
And the last question.
I have templates where I am getting many records from a few table (relationships).
So in my view I get records from one table and in templates show it and related info from others.
Generating page last a few seconds for very small table (<100 records).
Is it some easy way to cache queries from templates or all page?
Have I to do some big structure in my view (with all related tables), cache it and send to template? It is some more easy way?
A:
For second question (about django-memcached-0.1.2 status):
http://effbot.org/zone/django-memcached-view.htm#more-statistics
http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt
| Using Memcached in Python/Django - questions | I am starting use Memcached to make my website faster.
For constant data in my database I use this:
from django.core.cache import cache
cache_key = 'regions'
regions = cache.get(cache_key)
if result is None:
"""Not Found in Cache"""
regions = Regions.objects.all()
cache.set(cache_key, regions, 2592000) #(2592000sekund = 30 dni)
return regions
For seldom data changes I use signals:
from django.core.cache import cache
from django.db.models import signals
def nuke_social_network_cache(self, instance, **kwargs):
cache_key = 'networks_for_%s' % (self.instance.user_id,)
cache.delete(cache_key)
signals.post_save.connect(nuke_social_network_cache, sender=SocialNetworkProfile)
signals.post_delete.connect(nuke_social_network_cache, sender=SocialNetworkProfile)
Is it correct way?
I have installed django-memcached-0.1.2, which show me:
Memcached Server Stats
Server Keys Hits Gets Hit_Rate Traffic_In Traffic_Out Usage Uptime
127.0.0.1 15 220 276 79% 83.1 KB 364.1 KB 18.4 KB 22:21:25
Can somebody explain what columns means?
And the last question.
I have templates where I am getting many records from a few table (relationships).
So in my view I get records from one table and in templates show it and related info from others.
Generating page last a few seconds for very small table (<100 records).
Is it some easy way to cache queries from templates or all page?
Have I to do some big structure in my view (with all related tables), cache it and send to template? It is some more easy way?
| [
"For second question (about django-memcached-0.1.2 status):\nhttp://effbot.org/zone/django-memcached-view.htm#more-statistics\nhttp://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt\n"
] | [
1
] | [] | [] | [
"database",
"django",
"memcached",
"python",
"templates"
] | stackoverflow_0002899178_database_django_memcached_python_templates.txt |
Q:
Doing a count over a filter query efficiently in django
Django newbie here, I need to do a count over a certain filter in a django model. If I do it like so: my_model.objects.filter(...).count() I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count. To my knowledge it's much more efficient to do the count without retrieving those rows like so "SELECT COUNT(*) FROM ...". Is there a way to do so in django?
A:
I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count
This is wrong assumption. From Django query set API reference for count()
count() performs a SELECT COUNT(*) behind the scenes
In general, QuerySets are lazy -- the act of creating a QuerySet doesn't involve any database activity. You can stack filters together all day long, and Django won't actually run the query until the QuerySet is evaluated.
| Doing a count over a filter query efficiently in django | Django newbie here, I need to do a count over a certain filter in a django model. If I do it like so: my_model.objects.filter(...).count() I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count. To my knowledge it's much more efficient to do the count without retrieving those rows like so "SELECT COUNT(*) FROM ...". Is there a way to do so in django?
| [
"\nI'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count\n\nThis is wrong assumption. From Django query set API reference for count()\n\ncount() performs a SELECT COUNT(*) behind the scenes\n\nIn general, QuerySets are lazy -- the act of creating a QuerySet doesn't involve any database activity. You can stack filters together all day long, and Django won't actually run the query until the QuerySet is evaluated.\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002903047_django_django_models_python.txt |
Q:
django sync db question
In django models say this model exist in details/models.py
class OccDetails(models.Model):
title = models.CharField(max_length = 255)
occ = models.ForeignKey(Occ)
So when sync db is made the following fields get created
and later to this of two more fields are added and sync db is made the new fields doesnt get created.How is this to be solved,Also what is auto_now=true in the below
these are the new fields
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True, auto_now=True)
A:
syncdb creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created.
Syncdb will not alter existing tables
syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.
you can either
Issue a manual ALTER TABLE command
DROP TABLE the particular table (will lose data) and run syncdb again
run django-admin sqlclear to get a list of sql statements to clear the entire db and run those commands (will flush the db - you'll lose all existing data) or
DateField.auto_now: automatically set the field to NOW() every time the object is saved. Useful for "last-modified" timestamps. Note that the current date is always used; it's not just a default value that you can override.
Thus, the modified_date column will be automatically updated every time you call object.save()
A:
This is a common problem with Django. As said by Amarghosh, syncdb can not modify the schema of existing tables.
South has been created to solve this problem.
I do recommend it.
| django sync db question | In django models say this model exist in details/models.py
class OccDetails(models.Model):
title = models.CharField(max_length = 255)
occ = models.ForeignKey(Occ)
So when sync db is made the following fields get created
and later to this of two more fields are added and sync db is made the new fields doesnt get created.How is this to be solved,Also what is auto_now=true in the below
these are the new fields
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True, auto_now=True)
| [
"\nsyncdb creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created. \nSyncdb will not alter existing tables\nsyncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.\n\nyou can either \n\nIssue a manual ALTER TABLE command\nDROP TABLE the particular table (will lose data) and run syncdb again\nrun django-admin sqlclear to get a list of sql statements to clear the entire db and run those commands (will flush the db - you'll lose all existing data) or \n\n\n\nDateField.auto_now: automatically set the field to NOW() every time the object is saved. Useful for \"last-modified\" timestamps. Note that the current date is always used; it's not just a default value that you can override.\n\nThus, the modified_date column will be automatically updated every time you call object.save()\n",
"This is a common problem with Django. As said by Amarghosh, syncdb can not modify the schema of existing tables.\nSouth has been created to solve this problem.\nI do recommend it.\n"
] | [
7,
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002902800_django_django_models_python.txt |
Q:
python private attribute
class A():
def __init__(self):
self.__var = 5
def get_var(self):
return self.__var
def set_var(self, value):
self.__var = value
var = property(get_var, set_var)
a = A()
a.var = 10
print a.var == a._A__var
Can anyone explain why result is False?
A:
The property decorator only works on new-style classes. In Python 2.x, you have to extend the object class:
class A(object):
def __init__(self):
self.__var = 5
def get_var(self):
return self.__var
def set_var(self, value):
self.__var = value
var = property(get_var, set_var)
Without the behavior of the new-style class, the assignment a.var = 10 just binds a new value (10) to a new member attribute a.var.
| python private attribute | class A():
def __init__(self):
self.__var = 5
def get_var(self):
return self.__var
def set_var(self, value):
self.__var = value
var = property(get_var, set_var)
a = A()
a.var = 10
print a.var == a._A__var
Can anyone explain why result is False?
| [
"The property decorator only works on new-style classes. In Python 2.x, you have to extend the object class:\nclass A(object):\n\n def __init__(self):\n self.__var = 5\n\n def get_var(self):\n return self.__var\n\n def set_var(self, value):\n self.__var = value\n\n var = property(get_var, set_var)\n\nWithout the behavior of the new-style class, the assignment a.var = 10 just binds a new value (10) to a new member attribute a.var.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0002903217_python.txt |
Q:
Base class deleted before subclass during python __del__ processing
Context
I am aware that if I ask a question about Python destructors, the standard argument will be to use contexts instead. Let me start by explaining why I am not doing that.
I am writing a subclass to logging.Handler. When an instance is closed, it posts a sentinel value to a Queue.Queue. If it doesn't, a second thread will be left running forever, waiting for Queue.Queue.get() to complete.
I am writing this with other developers in mind, so I don't want a failure to call close() on a handler object to cause the program to hang.
Therefore, I am adding a check in __del__() to ensure the object was closed properly.
I understand circular references may cause it to fail in some circumstances. There's not a lot I can do about that.
Problem
Here is some simple example code:
explicit_delete = True
class Base:
def __del__(self):
print "Base class cleaning up."
class Sub(Base):
def __del__(self):
print "Sub-class cleaning up."
Base.__del__(self)
x = Sub()
if explicit_delete:
del x
print "End of thread"
When I run this I get, as expected:
Sub-class cleaning up.
Base class cleaning up.
End of thread
If I set explicit_delete to False in the first line, I get:
End of thread
Sub-class cleaning up.
Exception AttributeError: "'NoneType' object has no attribute '__del__'" in <bound method Sub.__del__ of <__main__.Sub instance at 0x00F0B698>> ignored
It seems the definition of Base is removed before the x.__del__() is called.
The Python Documentation on __del__() warns that the subclass needs to call the base-class to get a clean deletion, but here that appears to be impossible.
Can you see where I made a bad step?
A:
Your code is slightly misleading, I tried it and it failed just as you described. But then I wrote something like this:
import threading
class Base( object ):
def __del__(self):
print "Base class cleaning up."
class Sub(Base):
def __del__(self):
print "Sub-class cleaning up."
Base.__del__( self )
def f():
x = Sub()
print "End of thread"
t = threading.Thread( target = f )
t.start()
t.join()
and the output was:
End of thread
Sub-class cleaning up.
Base class cleaning up.
End of main thread.
So I guess you cannot rely on __del__ methods during interpreter shutdown (I think that class objects are collected before instances?), but before that point they work just as expected.
Maybe keeping main thread alive until others are dead and not creating your Handler subclass instances in main thread would be enough?
A:
One solution that works but that might not be the best:
explicit_delete = False
class Base(object):
def __del__(self):
print "Base class cleaning up."
class Sub(Base):
base = Base
def __init__(self):
print 'stating'
def __del__(self):
print "Sub-class cleaning up."
self.base.__del__(self)
x = Sub()
if explicit_delete:
del x
print "End of thread"
Where you keep a second reference to the base class
| Base class deleted before subclass during python __del__ processing | Context
I am aware that if I ask a question about Python destructors, the standard argument will be to use contexts instead. Let me start by explaining why I am not doing that.
I am writing a subclass to logging.Handler. When an instance is closed, it posts a sentinel value to a Queue.Queue. If it doesn't, a second thread will be left running forever, waiting for Queue.Queue.get() to complete.
I am writing this with other developers in mind, so I don't want a failure to call close() on a handler object to cause the program to hang.
Therefore, I am adding a check in __del__() to ensure the object was closed properly.
I understand circular references may cause it to fail in some circumstances. There's not a lot I can do about that.
Problem
Here is some simple example code:
explicit_delete = True
class Base:
def __del__(self):
print "Base class cleaning up."
class Sub(Base):
def __del__(self):
print "Sub-class cleaning up."
Base.__del__(self)
x = Sub()
if explicit_delete:
del x
print "End of thread"
When I run this I get, as expected:
Sub-class cleaning up.
Base class cleaning up.
End of thread
If I set explicit_delete to False in the first line, I get:
End of thread
Sub-class cleaning up.
Exception AttributeError: "'NoneType' object has no attribute '__del__'" in <bound method Sub.__del__ of <__main__.Sub instance at 0x00F0B698>> ignored
It seems the definition of Base is removed before the x.__del__() is called.
The Python Documentation on __del__() warns that the subclass needs to call the base-class to get a clean deletion, but here that appears to be impossible.
Can you see where I made a bad step?
| [
"Your code is slightly misleading, I tried it and it failed just as you described. But then I wrote something like this:\nimport threading\n\nclass Base( object ):\n def __del__(self):\n print \"Base class cleaning up.\"\n\nclass Sub(Base):\n def __del__(self):\n print \"Sub-class cleaning up.\"\n Base.__del__( self )\n\ndef f():\n x = Sub()\n print \"End of thread\"\n\nt = threading.Thread( target = f )\nt.start()\nt.join()\n\nand the output was:\nEnd of thread\nSub-class cleaning up.\nBase class cleaning up.\nEnd of main thread.\n\nSo I guess you cannot rely on __del__ methods during interpreter shutdown (I think that class objects are collected before instances?), but before that point they work just as expected.\nMaybe keeping main thread alive until others are dead and not creating your Handler subclass instances in main thread would be enough?\n",
"One solution that works but that might not be the best:\nexplicit_delete = False\n\nclass Base(object):\n def __del__(self):\n print \"Base class cleaning up.\"\n\nclass Sub(Base):\n base = Base\n def __init__(self):\n print 'stating'\n\n def __del__(self):\n print \"Sub-class cleaning up.\"\n self.base.__del__(self)\n\nx = Sub()\nif explicit_delete:\n del x\n\nprint \"End of thread\"\n\nWhere you keep a second reference to the base class\n"
] | [
2,
1
] | [] | [] | [
"destructor",
"python"
] | stackoverflow_0002902853_destructor_python.txt |
Q:
Checking for membership inside nested dict
This is a followup questions to this one:
Python DictReader - Skipping rows with missing columns?
Turns out I was being silly, and using the wrong ID field.
I'm using Python 3.x here, btw.
I have a dict of employees, indexed by a string, "directory_id". Each value is a nested dict with employee attributes (phone number, surname etc.). One of these values is a secondary ID, say "internal_id", and another is their manager, call it "manager_internal_id". The "internal_id" field is non-mandatory, and not every employee has one.
{'6443410501': {'manager_internal_id': '989634', 'givenName': 'Mary', 'phoneNumber': '+65 3434 3434', 'sn': 'Jones', 'internal_id': '434214'}
'8117062158': {'manager_internal_id': '180682', 'givenName': 'John', 'phoneNumber': '+65 3434 3434', 'sn': 'Ashmore', 'internal_id': ''}
'9227629067': {'manager_internal_id': '347394', 'givenName': 'Wright', 'phoneNumber': '+65 3434 3434', 'sn': 'Earl', 'internal_id': '257839'}
'1724696976': {'manager_internal_id': '907239', 'givenName': 'Jane', 'phoneNumber': '+65 3434 3434', 'sn': 'Bronte', 'internal_id': '629067'}
}
(I've simplified the fields a little, both to make it easier to read, and also for privacy/compliance reasons).
The issue here is that we index (key) each employee by their directory_id, but when we lookup their manager, we need to find managers by their "internal_id".
Before, when our dict was using internal_id as the key, employee.keys() was a list of internal_ids, and I was using a membership check on this. Now, the last part of my if statement won't work, since the internal_ids is part of the dict values, instead of the key itself.
def lookup_supervisor(manager_internal_id, employees):
if manager_internal_id is not None and manager_internal_id != "" and manager_internal_id in employees.keys():
return (employees[manager_internal_id]['mail'], employees[manager_internal_id]['givenName'], employees[manager_internal_id]['sn'])
else:
return ('Supervisor Not Found', 'Supervisor Not Found', 'Supervisor Not Found')
So the first question is, how do I fix the if statement to check whether the manager_internal_id is present in the dict's list of internal_ids?
I've tried substituting employee.keys() with employee.values(), that didn't work. Also, I'm hoping for something a little more efficient, not sure if there's a way to get a subset of the values, specifically, all the entries for employees[directory_id]['internal_id'].
Hopefully there's some Pythonic way of doing this, without using a massive heap of nested for/if loops.
My second question is, how do I then cleanly return the required employee attributes (mail, givenname, surname etc.). My for loop is iterating over each employee, and calling lookup_supervisor. I'm feeling a bit stupid/stumped here.
def tidy_data(employees):
for directory_id, data in employees.items():
# We really shouldnt' be passing employees back and forth like this - hmm, classes?
data['SupervisorEmail'], data['SupervisorFirstName'], data['SupervisorSurname'] = lookup_supervisor(data['manager_internal_id'], employees)
Should I redesign my data-structure? Or is there another way?
EDIT: I've tweaked the code slightly, see below:
class Employees:
def import_gd_dump(self, input_file="test.csv"):
gd_extract = csv.DictReader(open(input_file), dialect='excel')
self.employees = {row['directory_id']:row for row in gd_extract}
def write_gd_formatted(self, output_file="gd_formatted.csv"):
gd_output_fieldnames = ('internal_id', 'mail', 'givenName', 'sn', 'dbcostcenter', 'directory_id', 'manager_internal_id', 'PHFull', 'PHFull_message', 'SupervisorEmail', 'SupervisorFirstName', 'SupervisorSurname')
try:
gd_formatted = csv.DictWriter(open(output_file, 'w', newline=''), fieldnames=gd_output_fieldnames, extrasaction='ignore', dialect='excel')
except IOError:
print('Unable to open file, IO error (Is it locked?)')
sys.exit(1)
headers = {n:n for n in gd_output_fieldnames}
gd_formatted.writerow(headers)
for internal_id, data in self.employees.items():
gd_formatted.writerow(data)
def tidy_data(self):
for directory_id, data in self.employees.items():
data['PHFull'], data['PHFull_message'] = self.clean_phone_number(data['telephoneNumber'])
data['SupervisorEmail'], data['SupervisorFirstName'], data['SupervisorSurname'] = self.lookup_supervisor(data['manager_internal_id'])
def clean_phone_number(self, original_telephone_number):
standard_format = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<area_code>\d)\)(?P<local_first_half>\d{4})-(?P<local_second_half>\d{4})')
extra_zero = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{4})-(?P<local_second_half>\d{4})')
missing_hyphen = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{4})(?P<local_second_half>\d{4})')
if standard_format.search(original_telephone_number):
result = standard_format.search(original_telephone_number)
return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), ''
elif extra_zero.search(original_telephone_number):
result = extra_zero.search(original_telephone_number)
return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), 'Extra zero in area code - ask user to remediate. '
elif missing_hyphen.search(original_telephone_number):
result = missing_hyphen.search(original_telephone_number)
return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), 'Missing hyphen in local component - ask user to remediate. '
else:
return '', "Number didn't match format. Original text is: " + original_telephone_number
def lookup_supervisor(self, manager_internal_id):
if manager_internal_id is not None and manager_internal_id != "":# and manager_internal_id in self.employees.values():
return (employees[manager_internal_id]['mail'], employees[manager_internal_id]['givenName'], employees[manager_internal_id]['sn'])
else:
return ('Supervisor Not Found', 'Supervisor Not Found', 'Supervisor Not Found')
if __name__ == '__main__':
our_employees = Employees()
our_employees.import_gd_dump('test.csv')
our_employees.tidy_data()
our_employees.write_gd_formatted()
I guess (1). I'm looking for a better way to structure/store Employee/Employees, and (2) I'm having issues in particular with lookup_supervisor().\
Should I be creating an Employee Class, and nesting these inside Employees?
And should I even be doing what I'm doing with tidy_data(), and calling clean_phone_number() and lookup_supervisor() on a for loop on the dict's items? Urgh. confused.
A:
You probably will need to do some iteration to get the data. I assume you don't want an extra dict that can get out of date, so it won't be worth it trying to store everything keyed on internal ids.
Try this on for size:
def lookup_supervisor(manager_internal_id, employees):
if manager_internal_id is not None and manager_internal_id != "":
manager_dir_ids = [dir_id for dir_id in employees if employees[dir_id].get('internal_id') == manager_internal_id]
assert(len(manager_dir_ids) <= 1)
if len(manager_dir_ids) == 1:
return manager_dir_ids[0]
return None
def tidy_data(employees):
for emp_data in employees.values():
manager_dir_id = lookup_supervisor(emp_data.get('manager_internal_id'), employees)
for (field, sup_key) in [('Email', 'mail'), ('FirstName', 'givenName'), ('Surname', 'sn')]:
emp_data['Supervisor'+field] = (employees[manager_dir_id][sup_key] if manager_dir_id is not None else 'Supervisor Not Found')
And you're definitely right that a class is the answer for passing employees around. In fact, I'd recommend against storing the 'Supervisor' keys in the employee dict, and suggest instead getting the supervisor dict fresh whenever you need it, perhaps with a get_supervisor_data method.
Your new OO version all looks reasonable except for the changes I already mentioned and some tweaks to clean_phone_number.
def clean_phone_number(self, original_telephone_number):
phone_re = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<extra_zero>0?)(?P<area_code>\d)\)(?P<local_first_half>\d{4})(?P<hyph>-?)(?P<local_second_half>\d{4})')
result = phone_re.search(original_telephone_number)
if result is None:
return '', "Number didn't match format. Original text is: " + original_telephone_number
msg = ''
if result.group('extra_zero'):
msg += 'Extra zero in area code - ask user to remediate. '
if result.group('hyph'): # Note: can have both errors at once
msg += 'Missing hyphen in local component - ask user to remediate. '
return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), msg
You could definitely make an individual object for each employee, but seeing how you're using the data and what you need from it, I'm guessing it wouldn't have that much payoff.
A:
My python skills are poor, so I am far too ignorant to write out what I have in mind in any kind of reasonable time. But I do know how to do OO decomposition.
Why does the Employees class to do all the work? There are several types of things that your monolithic Employees class does:
Read and write data from a file - aka serialization
Manage and access data from individual employees
Manage relationships between exmployees.
I suggest that you create a class to handle each task group listed.
Define an Employee class to keep track or employee data and handle field processing/tidying tasks.
Use the Employees class as a container for employee objects. It can handle tasks like tracking down an Employee's supervisor.
Define a virtual base class EmployeeLoader to define an interface (load, store, ?? ). Then implement a subclass for CSV file serialization. (The virtual base class is optional--I'm not sure how Python handles virtual classes, so this may not even make sense.)
So:
create an instance of EmployeeCSVLoader with a file name to work with.
The loader can then build an Employees object and parse the file.
As each record is read, a new Employee object will be created and stored in the Employees object.
Now ask the Employees object to populate supervisor links.
Iterate over the Employees object's collection of employees and ask each one to tidy itself.
Finally, let the serialization object handle updating the data file.
Why is this design worth the effort?
It makes things easier to understand. Smaller, task focused objects are easier to create clean, consistent APIs for.
If you find that you need an XML serialization format, it becomes trivial to add the new format. Subclass your virtual loader class to handle the XML parsing/generation. Now you can seamlessly move between CSV and XML formats.
In summary, use objects to simplify and structure your data. Section off common data and behaviors into separate classes. Keep each class tightly focused on a single type of ability. If your class is a collection, accessor, factory, kitchen sink, the API can never be usable: it will be too big and loaded with dissimilar groups of methods. But if your classes stay on topic, they will be easy to test, maintain, use, reuse, and extend.
| Checking for membership inside nested dict | This is a followup questions to this one:
Python DictReader - Skipping rows with missing columns?
Turns out I was being silly, and using the wrong ID field.
I'm using Python 3.x here, btw.
I have a dict of employees, indexed by a string, "directory_id". Each value is a nested dict with employee attributes (phone number, surname etc.). One of these values is a secondary ID, say "internal_id", and another is their manager, call it "manager_internal_id". The "internal_id" field is non-mandatory, and not every employee has one.
{'6443410501': {'manager_internal_id': '989634', 'givenName': 'Mary', 'phoneNumber': '+65 3434 3434', 'sn': 'Jones', 'internal_id': '434214'}
'8117062158': {'manager_internal_id': '180682', 'givenName': 'John', 'phoneNumber': '+65 3434 3434', 'sn': 'Ashmore', 'internal_id': ''}
'9227629067': {'manager_internal_id': '347394', 'givenName': 'Wright', 'phoneNumber': '+65 3434 3434', 'sn': 'Earl', 'internal_id': '257839'}
'1724696976': {'manager_internal_id': '907239', 'givenName': 'Jane', 'phoneNumber': '+65 3434 3434', 'sn': 'Bronte', 'internal_id': '629067'}
}
(I've simplified the fields a little, both to make it easier to read, and also for privacy/compliance reasons).
The issue here is that we index (key) each employee by their directory_id, but when we lookup their manager, we need to find managers by their "internal_id".
Before, when our dict was using internal_id as the key, employee.keys() was a list of internal_ids, and I was using a membership check on this. Now, the last part of my if statement won't work, since the internal_ids is part of the dict values, instead of the key itself.
def lookup_supervisor(manager_internal_id, employees):
if manager_internal_id is not None and manager_internal_id != "" and manager_internal_id in employees.keys():
return (employees[manager_internal_id]['mail'], employees[manager_internal_id]['givenName'], employees[manager_internal_id]['sn'])
else:
return ('Supervisor Not Found', 'Supervisor Not Found', 'Supervisor Not Found')
So the first question is, how do I fix the if statement to check whether the manager_internal_id is present in the dict's list of internal_ids?
I've tried substituting employee.keys() with employee.values(), that didn't work. Also, I'm hoping for something a little more efficient, not sure if there's a way to get a subset of the values, specifically, all the entries for employees[directory_id]['internal_id'].
Hopefully there's some Pythonic way of doing this, without using a massive heap of nested for/if loops.
My second question is, how do I then cleanly return the required employee attributes (mail, givenname, surname etc.). My for loop is iterating over each employee, and calling lookup_supervisor. I'm feeling a bit stupid/stumped here.
def tidy_data(employees):
for directory_id, data in employees.items():
# We really shouldnt' be passing employees back and forth like this - hmm, classes?
data['SupervisorEmail'], data['SupervisorFirstName'], data['SupervisorSurname'] = lookup_supervisor(data['manager_internal_id'], employees)
Should I redesign my data-structure? Or is there another way?
EDIT: I've tweaked the code slightly, see below:
class Employees:
def import_gd_dump(self, input_file="test.csv"):
gd_extract = csv.DictReader(open(input_file), dialect='excel')
self.employees = {row['directory_id']:row for row in gd_extract}
def write_gd_formatted(self, output_file="gd_formatted.csv"):
gd_output_fieldnames = ('internal_id', 'mail', 'givenName', 'sn', 'dbcostcenter', 'directory_id', 'manager_internal_id', 'PHFull', 'PHFull_message', 'SupervisorEmail', 'SupervisorFirstName', 'SupervisorSurname')
try:
gd_formatted = csv.DictWriter(open(output_file, 'w', newline=''), fieldnames=gd_output_fieldnames, extrasaction='ignore', dialect='excel')
except IOError:
print('Unable to open file, IO error (Is it locked?)')
sys.exit(1)
headers = {n:n for n in gd_output_fieldnames}
gd_formatted.writerow(headers)
for internal_id, data in self.employees.items():
gd_formatted.writerow(data)
def tidy_data(self):
for directory_id, data in self.employees.items():
data['PHFull'], data['PHFull_message'] = self.clean_phone_number(data['telephoneNumber'])
data['SupervisorEmail'], data['SupervisorFirstName'], data['SupervisorSurname'] = self.lookup_supervisor(data['manager_internal_id'])
def clean_phone_number(self, original_telephone_number):
standard_format = re.compile(r'^\+(?P<intl_prefix>\d{2})\((?P<area_code>\d)\)(?P<local_first_half>\d{4})-(?P<local_second_half>\d{4})')
extra_zero = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{4})-(?P<local_second_half>\d{4})')
missing_hyphen = re.compile(r'^\+(?P<intl_prefix>\d{2})\(0(?P<area_code>\d)\)(?P<local_first_half>\d{4})(?P<local_second_half>\d{4})')
if standard_format.search(original_telephone_number):
result = standard_format.search(original_telephone_number)
return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), ''
elif extra_zero.search(original_telephone_number):
result = extra_zero.search(original_telephone_number)
return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), 'Extra zero in area code - ask user to remediate. '
elif missing_hyphen.search(original_telephone_number):
result = missing_hyphen.search(original_telephone_number)
return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), 'Missing hyphen in local component - ask user to remediate. '
else:
return '', "Number didn't match format. Original text is: " + original_telephone_number
def lookup_supervisor(self, manager_internal_id):
if manager_internal_id is not None and manager_internal_id != "":# and manager_internal_id in self.employees.values():
return (employees[manager_internal_id]['mail'], employees[manager_internal_id]['givenName'], employees[manager_internal_id]['sn'])
else:
return ('Supervisor Not Found', 'Supervisor Not Found', 'Supervisor Not Found')
if __name__ == '__main__':
our_employees = Employees()
our_employees.import_gd_dump('test.csv')
our_employees.tidy_data()
our_employees.write_gd_formatted()
I guess (1). I'm looking for a better way to structure/store Employee/Employees, and (2) I'm having issues in particular with lookup_supervisor().\
Should I be creating an Employee Class, and nesting these inside Employees?
And should I even be doing what I'm doing with tidy_data(), and calling clean_phone_number() and lookup_supervisor() on a for loop on the dict's items? Urgh. confused.
| [
"You probably will need to do some iteration to get the data. I assume you don't want an extra dict that can get out of date, so it won't be worth it trying to store everything keyed on internal ids.\nTry this on for size:\ndef lookup_supervisor(manager_internal_id, employees):\n if manager_internal_id is not None and manager_internal_id != \"\":\n manager_dir_ids = [dir_id for dir_id in employees if employees[dir_id].get('internal_id') == manager_internal_id]\n assert(len(manager_dir_ids) <= 1)\n if len(manager_dir_ids) == 1:\n return manager_dir_ids[0]\n return None\n\ndef tidy_data(employees):\n for emp_data in employees.values():\n manager_dir_id = lookup_supervisor(emp_data.get('manager_internal_id'), employees)\n for (field, sup_key) in [('Email', 'mail'), ('FirstName', 'givenName'), ('Surname', 'sn')]:\n emp_data['Supervisor'+field] = (employees[manager_dir_id][sup_key] if manager_dir_id is not None else 'Supervisor Not Found')\n\nAnd you're definitely right that a class is the answer for passing employees around. In fact, I'd recommend against storing the 'Supervisor' keys in the employee dict, and suggest instead getting the supervisor dict fresh whenever you need it, perhaps with a get_supervisor_data method.\nYour new OO version all looks reasonable except for the changes I already mentioned and some tweaks to clean_phone_number.\ndef clean_phone_number(self, original_telephone_number):\n phone_re = re.compile(r'^\\+(?P<intl_prefix>\\d{2})\\((?P<extra_zero>0?)(?P<area_code>\\d)\\)(?P<local_first_half>\\d{4})(?P<hyph>-?)(?P<local_second_half>\\d{4})')\n result = phone_re.search(original_telephone_number)\n if result is None:\n return '', \"Number didn't match format. Original text is: \" + original_telephone_number\n msg = ''\n if result.group('extra_zero'):\n msg += 'Extra zero in area code - ask user to remediate. '\n if result.group('hyph'): # Note: can have both errors at once\n msg += 'Missing hyphen in local component - ask user to remediate. '\n return '0' + result.group('area_code') + result.group('local_first_half') + result.group('local_second_half'), msg\n\nYou could definitely make an individual object for each employee, but seeing how you're using the data and what you need from it, I'm guessing it wouldn't have that much payoff.\n",
"My python skills are poor, so I am far too ignorant to write out what I have in mind in any kind of reasonable time. But I do know how to do OO decomposition.\nWhy does the Employees class to do all the work? There are several types of things that your monolithic Employees class does:\n\nRead and write data from a file - aka serialization\nManage and access data from individual employees\nManage relationships between exmployees.\n\nI suggest that you create a class to handle each task group listed.\nDefine an Employee class to keep track or employee data and handle field processing/tidying tasks.\nUse the Employees class as a container for employee objects. It can handle tasks like tracking down an Employee's supervisor. \nDefine a virtual base class EmployeeLoader to define an interface (load, store, ?? ). Then implement a subclass for CSV file serialization. (The virtual base class is optional--I'm not sure how Python handles virtual classes, so this may not even make sense.)\nSo:\n\ncreate an instance of EmployeeCSVLoader with a file name to work with.\nThe loader can then build an Employees object and parse the file.\nAs each record is read, a new Employee object will be created and stored in the Employees object.\nNow ask the Employees object to populate supervisor links.\nIterate over the Employees object's collection of employees and ask each one to tidy itself.\nFinally, let the serialization object handle updating the data file.\n\nWhy is this design worth the effort? \nIt makes things easier to understand. Smaller, task focused objects are easier to create clean, consistent APIs for.\nIf you find that you need an XML serialization format, it becomes trivial to add the new format. Subclass your virtual loader class to handle the XML parsing/generation. Now you can seamlessly move between CSV and XML formats.\nIn summary, use objects to simplify and structure your data. Section off common data and behaviors into separate classes. Keep each class tightly focused on a single type of ability. If your class is a collection, accessor, factory, kitchen sink, the API can never be usable: it will be too big and loaded with dissimilar groups of methods. But if your classes stay on topic, they will be easy to test, maintain, use, reuse, and extend.\n"
] | [
2,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002901872_dictionary_python.txt |
Q:
How would you solve this graph theory handshake problem in python?
I graduated college last year with a degree in Psychology, but I also took a lot of math for fun. I recently got the book "Introductory Graph Theory" by Gary Chartrand to brush up on my math and have some fun. Here is an exercise from the book that I'm finding particularly befuddling:
Suppose you and your husband attended
a party with three other married
couples. Several handshakes took
place. No one shook hands with himself
(or herself) or with his (or her)
spouse, and no one shook hands with
the same person more than once. After
all the handshaking was completed,
suppose you asked each person,
including your husband, how many hands
he or she had shaken. Each person gave
a different answer. a) How many hands
did you shake? b) How many hands did
your husband shake?
Now, I've been reasoning about this for a while, and trying to draw sample graphs that could illustrate a solution, but I'm coming up empty-handed. My logic is this: there are 8 different vertices in the graph, and 7 of them have different degrees. The values for the degrees must therefore be 0, 1, 2, 3, 4, 5, 6, and x. The # of degrees for one married couple is (0, 6). Since all graphs have an even number of odd vertices, x must be either 5, 3, or 1.
What's your solution to this problem? And, if you could solve it in python, how would you do it?
(python is fun.)
Cheers.
A:
I think this adjacency list represents a solution:
1 -> {}
2 -> {3, 4, 5, 6, 7, 8}
3 -> {2, 5, 6, 7, 8}
4 -> {2}
5 -> {2, 3, 7, 8}
6 -> {2, 3}
7 -> {2, 3, 5}
8 -> {2, 3, 5}
Note that each even vertex is married to the vertex one less than itself. You are 8.
I kind of intuited the solution. Thought about it for a few minutes and then realized that each couple must have a combined degree of 6 for this to work. Then just figured out how that should work.
What Steven is saying is that you've deduced that there must be a couple with degrees (0,6) and everyone else (1, 2, 3, 4, 5, x). Now consider the subgraph created by removing that first couple. The "husband" didn't shake anyone's hand, so he'll have no effect. The "wife" shook everyone's, so you'll need to subtract 1 from all other degrees. So, you have a graph with (0, 1, 2, 3, 4, x-1), where the same rules apply. From here, you can use the same thought process you used to determine the existence of the (0,6) couple to figure out the existence of a (1,5) couple. It'll actually be (0,4), but you need to add 1 at the end because this is the subgraph not counting the first couple.
Just keep repeating until you're down to someone and the x term, and you should get x = 3.
A:
The nice thing about this problem is you don't really need to solve the graph if you don't want to. You are actually very close. You figured that one couple has multiplicities (6,0). The remainder of the vertices are undifferentiated from each other with respect to the first couple and you have the same rules for that subgraph. So the sub-graph multiplicities are 0,1,2,3,4,x and there is some couple with multiplicities (4,0). That couple has multiplicities (5,1) in the full graph. So as you iterate through the process you will conclude your couples have multiplicities (6,0), (5,1), (4,2), (3,3). And of course you must have multiplicity x=3 so your husband shook 3 hands.
| How would you solve this graph theory handshake problem in python? | I graduated college last year with a degree in Psychology, but I also took a lot of math for fun. I recently got the book "Introductory Graph Theory" by Gary Chartrand to brush up on my math and have some fun. Here is an exercise from the book that I'm finding particularly befuddling:
Suppose you and your husband attended
a party with three other married
couples. Several handshakes took
place. No one shook hands with himself
(or herself) or with his (or her)
spouse, and no one shook hands with
the same person more than once. After
all the handshaking was completed,
suppose you asked each person,
including your husband, how many hands
he or she had shaken. Each person gave
a different answer. a) How many hands
did you shake? b) How many hands did
your husband shake?
Now, I've been reasoning about this for a while, and trying to draw sample graphs that could illustrate a solution, but I'm coming up empty-handed. My logic is this: there are 8 different vertices in the graph, and 7 of them have different degrees. The values for the degrees must therefore be 0, 1, 2, 3, 4, 5, 6, and x. The # of degrees for one married couple is (0, 6). Since all graphs have an even number of odd vertices, x must be either 5, 3, or 1.
What's your solution to this problem? And, if you could solve it in python, how would you do it?
(python is fun.)
Cheers.
| [
"I think this adjacency list represents a solution:\n1 -> {}\n2 -> {3, 4, 5, 6, 7, 8}\n3 -> {2, 5, 6, 7, 8}\n4 -> {2}\n5 -> {2, 3, 7, 8}\n6 -> {2, 3}\n7 -> {2, 3, 5}\n8 -> {2, 3, 5}\nNote that each even vertex is married to the vertex one less than itself. You are 8.\nI kind of intuited the solution. Thought about it for a few minutes and then realized that each couple must have a combined degree of 6 for this to work. Then just figured out how that should work.\nWhat Steven is saying is that you've deduced that there must be a couple with degrees (0,6) and everyone else (1, 2, 3, 4, 5, x). Now consider the subgraph created by removing that first couple. The \"husband\" didn't shake anyone's hand, so he'll have no effect. The \"wife\" shook everyone's, so you'll need to subtract 1 from all other degrees. So, you have a graph with (0, 1, 2, 3, 4, x-1), where the same rules apply. From here, you can use the same thought process you used to determine the existence of the (0,6) couple to figure out the existence of a (1,5) couple. It'll actually be (0,4), but you need to add 1 at the end because this is the subgraph not counting the first couple.\nJust keep repeating until you're down to someone and the x term, and you should get x = 3.\n",
"The nice thing about this problem is you don't really need to solve the graph if you don't want to. You are actually very close. You figured that one couple has multiplicities (6,0). The remainder of the vertices are undifferentiated from each other with respect to the first couple and you have the same rules for that subgraph. So the sub-graph multiplicities are 0,1,2,3,4,x and there is some couple with multiplicities (4,0). That couple has multiplicities (5,1) in the full graph. So as you iterate through the process you will conclude your couples have multiplicities (6,0), (5,1), (4,2), (3,3). And of course you must have multiplicity x=3 so your husband shook 3 hands.\n"
] | [
1,
1
] | [] | [] | [
"discrete_mathematics",
"graph_theory",
"math",
"python"
] | stackoverflow_0002902660_discrete_mathematics_graph_theory_math_python.txt |
Q:
KeyError this says that key(partner) is not in dict?
I am trying to make an chat application using python and django. I almost complete it and its working fine for 8-10 minutes when two persons are chatting after that certain time it shows an error.
here is the traceback : -
Traceback (most recent call last):
File "\Django_chat\django_chat\chat\views.py", line 55, in receive
message = chatSession.getMessage(request.session['partner'],request.session['uid'],afterTime)
File "C:\Python26\lib\site-packages\django\contrib\sessions\backends\base.py", line 47, in __getitem__
return self._session[key]
KeyError: 'partner'
here is the receive module :-
def receive(request):
# message received by this user
chatSession = chat()
data = request.POST
afterTime = data['lastMsgTime']
try:
message = chatSession.getMessage(
request.session['partner'],
request.session['uid'],
afterTime)
except:
#partnerId = virtual_users.objects.get(id=request.session['uid']).partner
print('there is an error in receive request')
traceback.print_exc(file=open("/myapp.log","a"))
msg = serializers.serialize("json", message)
return HttpResponse(msg)
Please Help me :(
thanks
Ansh J
A:
I assume that the user's session got timed-out and hence the request.session doesn't have partner or uid values in it.
Sessions get timed out based on the (lack of) activity on them. Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified. By default, Django only saves to the session database when the session has been modified -- that is if any of its dictionary values have been assigned or deleted. To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST setting to True. If SESSION_SAVE_EVERY_REQUEST is True, Django will save the session to the database on every single request.
A:
Try
print 'request.session contains ', repr(request.session)
in your except suite. Is the dictionary missing anything other than an item with 'partner' as key? Is it empty? Whatever, try to work out how/why it became like that.
| KeyError this says that key(partner) is not in dict? | I am trying to make an chat application using python and django. I almost complete it and its working fine for 8-10 minutes when two persons are chatting after that certain time it shows an error.
here is the traceback : -
Traceback (most recent call last):
File "\Django_chat\django_chat\chat\views.py", line 55, in receive
message = chatSession.getMessage(request.session['partner'],request.session['uid'],afterTime)
File "C:\Python26\lib\site-packages\django\contrib\sessions\backends\base.py", line 47, in __getitem__
return self._session[key]
KeyError: 'partner'
here is the receive module :-
def receive(request):
# message received by this user
chatSession = chat()
data = request.POST
afterTime = data['lastMsgTime']
try:
message = chatSession.getMessage(
request.session['partner'],
request.session['uid'],
afterTime)
except:
#partnerId = virtual_users.objects.get(id=request.session['uid']).partner
print('there is an error in receive request')
traceback.print_exc(file=open("/myapp.log","a"))
msg = serializers.serialize("json", message)
return HttpResponse(msg)
Please Help me :(
thanks
Ansh J
| [
"I assume that the user's session got timed-out and hence the request.session doesn't have partner or uid values in it. \nSessions get timed out based on the (lack of) activity on them. Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified. By default, Django only saves to the session database when the session has been modified -- that is if any of its dictionary values have been assigned or deleted. To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST setting to True. If SESSION_SAVE_EVERY_REQUEST is True, Django will save the session to the database on every single request. \n",
"Try \nprint 'request.session contains ', repr(request.session) \nin your except suite. Is the dictionary missing anything other than an item with 'partner' as key? Is it empty? Whatever, try to work out how/why it became like that.\n"
] | [
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002903329_django_python.txt |
Q:
An unhandled exception was thrown by the application
I've created my new site using DjANGO
AT FIRST Everything is okay startapp,syncdb......Etc
but the problems its this massage
Unhandled Exception
An unhandled exception was thrown by the application.
you can see
http://www.daqiqten.com/
this is my index.fsgi and .htacces
index.fcgi
#!/usr/bin/python
import sys, os
# Add a custom Python path. (optional)
sys.path.insert(0, "/home/daq")
# Switch to the directory of your project.
os.chdir("/home/daq/newproject")
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "newproject.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
___________
.htacces
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
A:
Do you have 'DEBUG' turned on in your app's settings? Maybe you will get some more information about the Exception that was raised.
| An unhandled exception was thrown by the application | I've created my new site using DjANGO
AT FIRST Everything is okay startapp,syncdb......Etc
but the problems its this massage
Unhandled Exception
An unhandled exception was thrown by the application.
you can see
http://www.daqiqten.com/
this is my index.fsgi and .htacces
index.fcgi
#!/usr/bin/python
import sys, os
# Add a custom Python path. (optional)
sys.path.insert(0, "/home/daq")
# Switch to the directory of your project.
os.chdir("/home/daq/newproject")
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "newproject.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
___________
.htacces
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
| [
"Do you have 'DEBUG' turned on in your app's settings? Maybe you will get some more information about the Exception that was raised.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002901649_django_python.txt |
Q:
installing Python application with Python under windows
My application uses many Python libraries (Django, Twisted, xmlrpc). I cannot expect that the end user has the Python installed with all needed libraries.
I've created a fancy installer for my application using Inno Setup, but I don't think that it is a good solution to execute 5 other setup programs from my installer. It would be annoying to the user to click "Next" button 15 times. Is there any way to do that quietly?
A:
May be you should try to make your application running standalone with py2exe or pyInstaller.
It will generate an application which doesn't expect anything from the target machine. You 'll have an exe file that the user can execute without knowing that Python is used. The Python interpreter and the needed libs will be included.
Then you can use Inno Setup to make a windows installer that will copy all the needed files.
I am not sure if Django is very easy to include in such a standalone version.
I hope it helps
A:
Perhaps you can set the whole application and libraries up in a virtual environment and then package all that up together. I've never tried this however!
| installing Python application with Python under windows | My application uses many Python libraries (Django, Twisted, xmlrpc). I cannot expect that the end user has the Python installed with all needed libraries.
I've created a fancy installer for my application using Inno Setup, but I don't think that it is a good solution to execute 5 other setup programs from my installer. It would be annoying to the user to click "Next" button 15 times. Is there any way to do that quietly?
| [
"May be you should try to make your application running standalone with py2exe or pyInstaller.\nIt will generate an application which doesn't expect anything from the target machine. You 'll have an exe file that the user can execute without knowing that Python is used. The Python interpreter and the needed libs will be included.\nThen you can use Inno Setup to make a windows installer that will copy all the needed files.\nI am not sure if Django is very easy to include in such a standalone version.\nI hope it helps\n",
"Perhaps you can set the whole application and libraries up in a virtual environment and then package all that up together. I've never tried this however!\n"
] | [
1,
0
] | [] | [] | [
"deployment",
"python"
] | stackoverflow_0002903507_deployment_python.txt |
Q:
Handling text menu in Python
I am trying to create a text based menu in Python.
Here is the code:
#!/usr/bin/env python
def testcaseOutput():
print '1. Add. 2. Subtract. 3. Divide. 4. Multiply'
try:
answer = int(raw_input('Enter a value (1 - 4) >. '))
except ValueError:
print 'Invalid input. Enter a value between 1 -4 .'
testcaseOutput()
if answer in range(1, 5):
return answer
else:
print 'Invalid input. Enter a value between 1 - 4.'
testcaseOutput()
My question:
When the user enters an invalid input, i.e. not a number, I want this function to get called again. So I used the recursive approach which I think is bad design. I use that approach again in the
if answer in range(1, 5).
Is there any other way to handle this? I need the prompt called again when there is an invalid input.
Also, is there any way I can club the two constraints: check whether input is a number and check whether the number is in the range(1,5) together? As you can see, I am checking that individually.
A:
One possible refactoring is to use a loop, that continues to print the instructions and read input until acceptable input has been given:
def testcaseOutput():
while True:
print '1. Add. 2. Subtract. 3. Divide. 4. Multiply'
try:
answer = int(raw_input('Enter a value (1 - 4) >. '))
except ValueError:
print 'Invalid input. Enter a value between 1 -4 .'
continue
if not answer in range(1, 5):
print 'Invalid input. Enter a value between 1 - 4.'
continue
return answer
A:
def testcaseOutput():
answer = None
legal_answers = ['1','2','3','4']
tried = False
while answer not in legal_answers:
print "%s1. Add. 2. Subtract. 3. Divide. 4. Multiply" % \
"Invalid input. " if tried else ""
answer = raw_input('Enter a value (1 - 4) >. ')
tried = True
return answer #int(answer) if you really do want integers
A:
Place the entire body of the function in a while True: loop (removing the recursive call, of course).
| Handling text menu in Python | I am trying to create a text based menu in Python.
Here is the code:
#!/usr/bin/env python
def testcaseOutput():
print '1. Add. 2. Subtract. 3. Divide. 4. Multiply'
try:
answer = int(raw_input('Enter a value (1 - 4) >. '))
except ValueError:
print 'Invalid input. Enter a value between 1 -4 .'
testcaseOutput()
if answer in range(1, 5):
return answer
else:
print 'Invalid input. Enter a value between 1 - 4.'
testcaseOutput()
My question:
When the user enters an invalid input, i.e. not a number, I want this function to get called again. So I used the recursive approach which I think is bad design. I use that approach again in the
if answer in range(1, 5).
Is there any other way to handle this? I need the prompt called again when there is an invalid input.
Also, is there any way I can club the two constraints: check whether input is a number and check whether the number is in the range(1,5) together? As you can see, I am checking that individually.
| [
"One possible refactoring is to use a loop, that continues to print the instructions and read input until acceptable input has been given:\ndef testcaseOutput():\n while True:\n print '1. Add. 2. Subtract. 3. Divide. 4. Multiply'\n\n try:\n answer = int(raw_input('Enter a value (1 - 4) >. ')) \n except ValueError:\n print 'Invalid input. Enter a value between 1 -4 .'\n continue\n\n if not answer in range(1, 5):\n print 'Invalid input. Enter a value between 1 - 4.'\n continue\n\n return answer\n\n",
"def testcaseOutput():\n\n answer = None\n legal_answers = ['1','2','3','4']\n tried = False\n while answer not in legal_answers:\n print \"%s1. Add. 2. Subtract. 3. Divide. 4. Multiply\" % \\ \n \"Invalid input. \" if tried else \"\"\n answer = raw_input('Enter a value (1 - 4) >. ')\n tried = True\n\n return answer #int(answer) if you really do want integers\n\n",
"Place the entire body of the function in a while True: loop (removing the recursive call, of course).\n"
] | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002903617_python.txt |
Q:
python-like Java IO library?
Java is not my main programming language so I might be asking the obvious.
But is there a simple file-handling library in Java, like in python?
For example I just want to say:
File f = Open('file.txt', 'w')
for(String line:f){
//do something with the line from file
}
Thanks!
UPDATE: Well, the stackoverflow auto-accepted a weird answer. It has to do with bounty that I placed - so if you want to see other answers, just scroll down!
A:
I was thinking something more along the lines of:
File f = File.open("C:/Users/File.txt");
for(String s : f){
System.out.println(s);
}
Here is my source code for it:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
public abstract class File implements Iterable<String>{
public final static String READ = "r";
public final static String WRITE = "w";
public static File open(String filepath) throws IOException{
return open(filepath, READ);
}
public static File open(String filepath, String mode) throws IOException{
if(mode == READ){
return new ReadableFile(filepath);
}else if(mode == WRITE){
return new WritableFile(filepath);
}
throw new IllegalArgumentException("Invalid File Write mode '" + mode + "'");
}
//common methods
public abstract void close() throws IOException;
// writer specific
public abstract void write(String s) throws IOException;
}
class WritableFile extends File{
String filepath;
Writer writer;
public WritableFile(String filepath){
this.filepath = filepath;
}
private Writer writer() throws IOException{
if(this.writer == null){
writer = new BufferedWriter(new FileWriter(this.filepath));
}
return writer;
}
public void write(String chars) throws IOException{
writer().write(chars);
}
public void close() throws IOException{
writer().close();
}
@Override
public Iterator<String> iterator() {
return null;
}
}
class ReadableFile extends File implements Iterator<String>{
private BufferedReader reader;
private String line;
private String read_ahead;
public ReadableFile(String filepath) throws IOException{
this.reader = new BufferedReader(new FileReader(filepath));
this.read_ahead = this.reader.readLine();
}
private Reader reader() throws IOException{
if(reader == null){
reader = new BufferedReader(new FileReader(filepath));
}
return reader;
}
@Override
public Iterator<String> iterator() {
return this;
}
@Override
public void close() throws IOException {
reader().close();
}
@Override
public void write(String s) throws IOException {
throw new IOException("Cannot write to a read-only file.");
}
@Override
public boolean hasNext() {
return this.read_ahead != null;
}
@Override
public String next() {
if(read_ahead == null)
line = null;
else
line = new String(this.read_ahead);
try {
read_ahead = this.reader.readLine();
} catch (IOException e) {
read_ahead = null;
reader.close()
}
return line;
}
@Override
public void remove() {
// do nothing
}
}
and here is the unit-test for it:
import java.io.IOException;
import org.junit.Test;
public class FileTest {
@Test
public void testFile(){
File f;
try {
f = File.open("File.java");
for(String s : f){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testReadAndWriteFile(){
File from;
File to;
try {
from = File.open("File.java");
to = File.open("Out.txt", "w");
for(String s : from){
to.write(s + System.getProperty("line.separator"));
}
to.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
A:
Reading a file line by line in Java:
BufferedReader in = new BufferedReader(new FileReader("myfile.txt"));
String line;
while ((line = in.readLine()) != null) {
// Do something with this line
System.out.println(line);
}
in.close();
Most of the classes for I/O are in the package java.io. See the API documentation for that package. Have a look at Sun's Java I/O tutorial for more detailed information.
addition: The example above will use the default character encoding of your system to read the text file. If you want to explicitly specify the character encoding, for example UTF-8, change the first line to this:
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("myfile.txt"), "UTF-8"));
A:
If you already have dependencies to Apache commons lang and commons io this could be an alternative:
String[] lines = StringUtils.split(FileUtils.readFileToString(new File("myfile.txt")), '\n');
for(String line: lines){
//do something with the line from file
}
(I would prefer Jesper's answer)
A:
If you want to iterate through a file by strings, a class you might find useful is the Scanner class.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("myFile.txt")));
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
The API is pretty useful: http://java.sun.com/javase/7/docs/api/java/util/Scanner.html
You can also parse the file using regular expressions.
A:
I never get tired of pimping Google's guava-libraries, which takes a lot of the pain out of... well, most things in Java.
How about:
for (String line : Files.readLines(new File("file.txt"), Charsets.UTF_8)) {
// Do something
}
In the case where you have a large file, and want a line-by-line callback (rather than reading the whole thing into memory) you can use a LineProcessor, which adds a bit of boilerplate (due to the lack of closures... sigh) but still shields you from dealing with the reading itself, and all associated Exceptions:
int matching = Files.readLines(new File("file.txt"), Charsets.UTF_8, new LineProcessor<Integer>(){
int count;
Integer getResult() {return count;}
boolean processLine(String line) {
if (line.equals("foo")
count++;
return true;
}
});
If you don't actually want a result back out of the processor, and you never abort early (the reason for the boolean return from processLine) you could then do something like:
class SimpleLineCallback extends LineProcessor<Void> {
Void getResult{ return null; }
boolean processLine(String line) {
doProcess(line);
return true;
}
abstract void doProcess(String line);
}
and then your code might be:
Files.readLines(new File("file.txt"), Charsets.UTF_8, new SimpleLineProcessor(){
void doProcess(String line) {
if (line.equals("foo");
throw new FooException("File shouldn't contain 'foo'!");
}
});
which is correspondingly cleaner.
A:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("scan.txt"));
try {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
scanner.close();
}
}
Some caveats:
That uses the default system encoding, but you should specify the file encoding
Scanner swallows I/O exceptions, so you may want to check ioException() at the end for proper error handling
A:
Simple example using Files.readLines() from guava-io with a LineProcessor callback:
import java.io.File;
import java.io.IOException;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class GuavaIoDemo {
public static void main(String[] args) throws Exception {
int result = Files.readLines(new File("/home/pascal/.vimrc"), //
Charsets.UTF_8, //
new LineProcessor<Integer>() {
int counter;
public Integer getResult() {
return counter;
}
public boolean processLine(String line) throws IOException {
counter++;
System.out.println(line);
return true;
}
});
}
}
A:
You could use jython which lets you run Python syntax in Java.
A:
Nice example here: Line by line iteration
A:
Try looking at groovy!
Its a superset of Java that runs in hte JVM. Most valid Java code is also valid Groovy so you have access any of the million java APIs directly.
In addition it has many of the higher level contructs familiar to Pythonists, plus
a number of extensions to take the pain out of Maps, Lists, sql, xml and you guessed it -- file IO.
| python-like Java IO library? | Java is not my main programming language so I might be asking the obvious.
But is there a simple file-handling library in Java, like in python?
For example I just want to say:
File f = Open('file.txt', 'w')
for(String line:f){
//do something with the line from file
}
Thanks!
UPDATE: Well, the stackoverflow auto-accepted a weird answer. It has to do with bounty that I placed - so if you want to see other answers, just scroll down!
| [
"I was thinking something more along the lines of:\nFile f = File.open(\"C:/Users/File.txt\");\n\nfor(String s : f){\n System.out.println(s);\n}\n\nHere is my source code for it:\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.util.Iterator;\n\npublic abstract class File implements Iterable<String>{\n public final static String READ = \"r\";\n public final static String WRITE = \"w\";\n\n public static File open(String filepath) throws IOException{\n return open(filepath, READ);\n } \n\n public static File open(String filepath, String mode) throws IOException{\n if(mode == READ){\n return new ReadableFile(filepath);\n }else if(mode == WRITE){\n return new WritableFile(filepath);\n }\n throw new IllegalArgumentException(\"Invalid File Write mode '\" + mode + \"'\");\n }\n\n //common methods\n public abstract void close() throws IOException;\n\n // writer specific\n public abstract void write(String s) throws IOException;\n\n}\n\nclass WritableFile extends File{\n String filepath;\n Writer writer;\n\n public WritableFile(String filepath){\n this.filepath = filepath;\n }\n\n private Writer writer() throws IOException{\n if(this.writer == null){\n writer = new BufferedWriter(new FileWriter(this.filepath));\n }\n return writer;\n }\n\n public void write(String chars) throws IOException{\n writer().write(chars);\n }\n\n public void close() throws IOException{\n writer().close();\n }\n\n @Override\n public Iterator<String> iterator() { \n return null;\n }\n}\n\nclass ReadableFile extends File implements Iterator<String>{\n private BufferedReader reader;\n private String line; \n private String read_ahead;\n\n public ReadableFile(String filepath) throws IOException{ \n this.reader = new BufferedReader(new FileReader(filepath)); \n this.read_ahead = this.reader.readLine();\n }\n\n private Reader reader() throws IOException{\n if(reader == null){\n reader = new BufferedReader(new FileReader(filepath)); \n }\n return reader;\n }\n\n @Override\n public Iterator<String> iterator() {\n return this;\n }\n\n @Override\n public void close() throws IOException {\n reader().close();\n }\n\n @Override\n public void write(String s) throws IOException {\n throw new IOException(\"Cannot write to a read-only file.\");\n }\n\n @Override\n public boolean hasNext() { \n return this.read_ahead != null;\n }\n\n @Override\n public String next() {\n if(read_ahead == null)\n line = null;\n else\n line = new String(this.read_ahead);\n\n try {\n read_ahead = this.reader.readLine();\n } catch (IOException e) {\n read_ahead = null;\n reader.close()\n }\n return line;\n }\n\n @Override\n public void remove() {\n // do nothing \n }\n}\n\nand here is the unit-test for it:\nimport java.io.IOException;\nimport org.junit.Test;\n\npublic class FileTest {\n @Test\n public void testFile(){\n File f;\n try {\n f = File.open(\"File.java\");\n for(String s : f){\n System.out.println(s);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n @Test\n public void testReadAndWriteFile(){\n File from;\n File to;\n try {\n from = File.open(\"File.java\");\n to = File.open(\"Out.txt\", \"w\");\n for(String s : from){ \n to.write(s + System.getProperty(\"line.separator\"));\n }\n to.close();\n } catch (IOException e1) {\n e1.printStackTrace();\n } \n }\n}\n\n",
"Reading a file line by line in Java:\nBufferedReader in = new BufferedReader(new FileReader(\"myfile.txt\"));\n\nString line;\nwhile ((line = in.readLine()) != null) {\n // Do something with this line\n System.out.println(line);\n}\n\nin.close();\n\nMost of the classes for I/O are in the package java.io. See the API documentation for that package. Have a look at Sun's Java I/O tutorial for more detailed information.\naddition: The example above will use the default character encoding of your system to read the text file. If you want to explicitly specify the character encoding, for example UTF-8, change the first line to this:\nBufferedReader in = new BufferedReader(\n new InputStreamReader(new FileInputStream(\"myfile.txt\"), \"UTF-8\"));\n\n",
"If you already have dependencies to Apache commons lang and commons io this could be an alternative:\nString[] lines = StringUtils.split(FileUtils.readFileToString(new File(\"myfile.txt\")), '\\n');\nfor(String line: lines){\n //do something with the line from file\n}\n\n(I would prefer Jesper's answer)\n",
"If you want to iterate through a file by strings, a class you might find useful is the Scanner class.\nimport java.io.*;\nimport java.util.Scanner;\n\n public class ScanXan {\n public static void main(String[] args) throws IOException {\n Scanner s = null;\n try {\n s = new Scanner(new BufferedReader(new FileReader(\"myFile.txt\")));\n\n while (s.hasNextLine()) {\n System.out.println(s.nextLine());\n }\n } finally {\n if (s != null) {\n s.close();\n }\n }\n }\n }\n\nThe API is pretty useful: http://java.sun.com/javase/7/docs/api/java/util/Scanner.html\nYou can also parse the file using regular expressions.\n",
"I never get tired of pimping Google's guava-libraries, which takes a lot of the pain out of... well, most things in Java.\nHow about:\nfor (String line : Files.readLines(new File(\"file.txt\"), Charsets.UTF_8)) {\n // Do something\n}\n\nIn the case where you have a large file, and want a line-by-line callback (rather than reading the whole thing into memory) you can use a LineProcessor, which adds a bit of boilerplate (due to the lack of closures... sigh) but still shields you from dealing with the reading itself, and all associated Exceptions:\nint matching = Files.readLines(new File(\"file.txt\"), Charsets.UTF_8, new LineProcessor<Integer>(){\n int count;\n\n Integer getResult() {return count;}\n\n boolean processLine(String line) {\n if (line.equals(\"foo\")\n count++;\n return true;\n }\n});\n\nIf you don't actually want a result back out of the processor, and you never abort early (the reason for the boolean return from processLine) you could then do something like:\nclass SimpleLineCallback extends LineProcessor<Void> {\n Void getResult{ return null; }\n\n boolean processLine(String line) {\n doProcess(line);\n return true;\n }\n\n abstract void doProcess(String line);\n}\n\nand then your code might be:\nFiles.readLines(new File(\"file.txt\"), Charsets.UTF_8, new SimpleLineProcessor(){\n void doProcess(String line) {\n if (line.equals(\"foo\");\n throw new FooException(\"File shouldn't contain 'foo'!\");\n }\n});\n\nwhich is correspondingly cleaner.\n",
" public static void main(String[] args) throws FileNotFoundException {\n Scanner scanner = new Scanner(new File(\"scan.txt\"));\n try {\n while (scanner.hasNextLine()) {\n System.out.println(scanner.nextLine());\n }\n } finally {\n scanner.close();\n }\n }\n\nSome caveats:\n\nThat uses the default system encoding, but you should specify the file encoding\nScanner swallows I/O exceptions, so you may want to check ioException() at the end for proper error handling\n\n",
"Simple example using Files.readLines() from guava-io with a LineProcessor callback: \nimport java.io.File;\nimport java.io.IOException;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Files;\nimport com.google.common.io.LineProcessor;\n\npublic class GuavaIoDemo {\n\n public static void main(String[] args) throws Exception {\n int result = Files.readLines(new File(\"/home/pascal/.vimrc\"), //\n Charsets.UTF_8, // \n new LineProcessor<Integer>() {\n int counter;\n\n public Integer getResult() {\n return counter;\n }\n\n public boolean processLine(String line) throws IOException {\n counter++;\n System.out.println(line);\n return true;\n }\n });\n }\n}\n\n",
"You could use jython which lets you run Python syntax in Java.\n",
"Nice example here: Line by line iteration\n",
"Try looking at groovy!\nIts a superset of Java that runs in hte JVM. Most valid Java code is also valid Groovy so you have access any of the million java APIs directly.\nIn addition it has many of the higher level contructs familiar to Pythonists, plus\na number of extensions to take the pain out of Maps, Lists, sql, xml and you guessed it -- file IO.\n"
] | [
19,
11,
4,
4,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"file_io",
"java",
"python"
] | stackoverflow_0002802711_file_io_java_python.txt |
Q:
in python how to remove this \n from string or list
this is my main string
"action","employee_id","name"
"absent","pritesh",2010/09/15 00:00:00
so after name coolumn its goes to new line but here i append to list a new line character is added and make it like this way
data_list***** ['"action","employee_id","name"\n"absent","pritesh",2010/09/15 00:00:00\n']
here its append the new line character with absent but actually its a new line strarting but its appended i want to make it like
data_list***** ['"action","employee_id","name","absent","pritesh",2010/09/15 00:00:00']
A:
Davide's answer can be written even simpler as:
data_list = [word.strip() for word in data_list]
But I'm not sure it's what you want. Please write some sample in python.
A:
replaces = inString.replace("\n", "");
A:
First, you can use strip() to get rid of '\n':
>>> data = line.strip().split(',')
Secondly, you may want to use the csv module to do that:
>>> import csv
>>> f = open("test")
>>> r = csv.reader(f)
>>> print(r.next())
['action', 'employee_id', 'name']
A:
I'd do like that:
in_string.replace('\n', ',', 1).split(',')
A:
def f(word):
return word.strip()
data_list = map(f, data_list)
| in python how to remove this \n from string or list | this is my main string
"action","employee_id","name"
"absent","pritesh",2010/09/15 00:00:00
so after name coolumn its goes to new line but here i append to list a new line character is added and make it like this way
data_list***** ['"action","employee_id","name"\n"absent","pritesh",2010/09/15 00:00:00\n']
here its append the new line character with absent but actually its a new line strarting but its appended i want to make it like
data_list***** ['"action","employee_id","name","absent","pritesh",2010/09/15 00:00:00']
| [
"Davide's answer can be written even simpler as:\ndata_list = [word.strip() for word in data_list]\n\nBut I'm not sure it's what you want. Please write some sample in python.\n",
"replaces = inString.replace(\"\\n\", \"\");\n\n",
"First, you can use strip() to get rid of '\\n':\n>>> data = line.strip().split(',')\n\nSecondly, you may want to use the csv module to do that:\n>>> import csv\n>>> f = open(\"test\")\n>>> r = csv.reader(f)\n>>> print(r.next())\n['action', 'employee_id', 'name']\n\n",
"I'd do like that:\nin_string.replace('\\n', ',', 1).split(',')\n\n",
"def f(word):\n return word.strip()\ndata_list = map(f, data_list)\n\n"
] | [
9,
8,
3,
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002903523_python_string.txt |
Q:
Receiving XML document with python via HTTP
I want to do a very simple webserver in python able to receive XML document over HTTP and then to send as response XML document.
Do you have any example?
just to understand How arrange the work...
many thanks!
UPDATE:
I need something like this:
a client do a post with an xml document:
< request >
< name>plus< /name>
< param>2< /param>
< param>3< /param>
< /request>'
the python server answers:
< response>
< result>OK< /result>
< outcome>5< /outcome>
< /response >
Do you have an example for such kind of things??
A:
You can use XMLRPC :
SimpleXMLRPCServer Example (from the Python Docs)
Server code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
requestHandler=RequestHandler)
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name
def adder_function(x,y):
return x + y
server.register_function(adder_function, 'add')
# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
def div(self, x, y):
return x // y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
The following client code will call the methods made available by the preceding server:
import xmlrpclib
s = xmlrpclib.ServerProxy('http://localhost:8000')
print s.pow(2,3) # Returns 2**3 = 8
print s.add(2,3) # Returns 5
print s.div(5,2) # Returns 5//2 = 2
# Print list of available methods
print s.system.listMethods()
A:
Example with standard library:
http://fragments.turtlemeat.com/pythonwebserver.php
Or use some lightweight web framework:
web.py
| Receiving XML document with python via HTTP | I want to do a very simple webserver in python able to receive XML document over HTTP and then to send as response XML document.
Do you have any example?
just to understand How arrange the work...
many thanks!
UPDATE:
I need something like this:
a client do a post with an xml document:
< request >
< name>plus< /name>
< param>2< /param>
< param>3< /param>
< /request>'
the python server answers:
< response>
< result>OK< /result>
< outcome>5< /outcome>
< /response >
Do you have an example for such kind of things??
| [
"You can use XMLRPC :\nSimpleXMLRPCServer Example (from the Python Docs)\nServer code:\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\nfrom SimpleXMLRPCServer import SimpleXMLRPCRequestHandler\n\n# Restrict to a particular path.\nclass RequestHandler(SimpleXMLRPCRequestHandler):\n rpc_paths = ('/RPC2',)\n\n# Create server\nserver = SimpleXMLRPCServer((\"localhost\", 8000),\n requestHandler=RequestHandler)\nserver.register_introspection_functions()\n\n# Register pow() function; this will use the value of\n# pow.__name__ as the name, which is just 'pow'.\nserver.register_function(pow)\n\n# Register a function under a different name\ndef adder_function(x,y):\n return x + y\nserver.register_function(adder_function, 'add')\n\n# Register an instance; all the methods of the instance are\n# published as XML-RPC methods (in this case, just 'div').\nclass MyFuncs:\n def div(self, x, y):\n return x // y\n\nserver.register_instance(MyFuncs())\n\n# Run the server's main loop\nserver.serve_forever()\n\nThe following client code will call the methods made available by the preceding server:\nimport xmlrpclib\n\ns = xmlrpclib.ServerProxy('http://localhost:8000')\nprint s.pow(2,3) # Returns 2**3 = 8\nprint s.add(2,3) # Returns 5\nprint s.div(5,2) # Returns 5//2 = 2\n\n# Print list of available methods\nprint s.system.listMethods()\n\n",
"Example with standard library:\n\nhttp://fragments.turtlemeat.com/pythonwebserver.php\n\nOr use some lightweight web framework:\n\nweb.py\n\n"
] | [
1,
0
] | [] | [] | [
"http",
"python",
"xml"
] | stackoverflow_0002903952_http_python_xml.txt |
Q:
A problem with assertRaises function in Python
I am trying to run the following test
self.assertRaises(Exception,lambda:
unit_test.testBasic())
where
test.testBasic()
is
class IsPrimeTest(unittest.TestCase):
def assertRaises(self,exception,callable,*args,**kwargs):
print('dfdf')
temp = callable
super().assertRaises(exception,temp,*args,**kwargs)
def testBasic_helper(self):
self.failIf(is_prime(2))
self.assertTrue(is_prime(1))
where prime is a function,and
but in
self.assertRaises(Exception,lambda:
unit_test.testBasic())
the lambda function doesnt throws an exception after
the test
def testBasic_helper(self):
self.failIf(is_prime(2))
self.assertTrue(is_prime(1))
fails
Can somebody offers a solution to the problem?
I'll try to explain my problem ,again ,because in my first post i didn't explain it very well
So here is the source
is_prime(x) is just a function for checking for prime numbers
def is_prime(number):
PRIME, NOT_PRIME = not is_prime.broken, is_prime.broken
if number == 2:
return PRIME
if not isinstance(number, int) and not isinstance(number, float):
raise Exception
if number % 2 == 0 or number < 2 or isinstance(number, float):
return NOT_PRIME
max = int(number**0.5) + 1
for i in range(3, max, 2):
if number % i == 0:
return NOT_PRIME
return PRIME
is_prime.broken = False
class IsPrimeTest(unittest.TestCase):
def testBasic_helper(self):
self.failIf(is_prime(1))
self.assertTrue(is_prime(2))
self.failIf(is_prime(4))
self.failIf(is_prime(6))
self.assertTrue(is_prime(7))
def testBasic(self):
return self.testBasic_helper()
def testNegative(self):
self.failIf(is_prime(-2))
self.failIf(is_prime(-11 ** 3))
def testNonNumber(self):
self.assertRaises(Exception,is_prime,'asd')
self.assertRaises(Exception,is_prime,self.__class__.__name__)
def testRandom(self):
for i in range(0,10000):
rand = randint(-10000,10000)
self.assertEquals(prime(rand),is_prime(rand))
and here is Test,we can say that the test tests the program which is a test - a test over test
class MetaProgrammingTest(unittest.TestCase):
def test_decorator(self):
from p10 import unit_converter
def celsius_function(val):
return val
self.assertTrue(hasattr(unit_converter(1,2),'__call__'))
decorated = unit_converter(1.8, 32)(celsius_function)
self.assertTrue(hasattr(decorated, '__call__'))
self.assertAlmostEquals(64.4, decorated(val = 18.0))
def test_unit_test(self):
import p10
from p10sample import is_prime as is_prime_actual
unit_test = p10.IsPrimeTest('testBasic')
unit_test.setUp()
is_prime_actual.broken = False
self.assertEquals(None, unit_test.testBasic())
self.assertEquals(None, unit_test.testNegative())
self.assertEquals(None, unit_test.testNonNumber())
self.assertEquals(None, unit_test.testRandom())
is_prime_actual.broken = True
self.assertRaises(Exception,lambda: unit_test.testBasic())
self.assertRaises(Exception, lambda: unit_test.testNegative())
self.assertRaises(Exception, lambda: unit_test.testRandom())
unit_test.tearDown()
I,cant change the second test - the test over the test
So the expression self.assertRaises(Exception,lambda: unit_test.testBasic())
has to stay unchaged
My problem is that when testBasic() function fails ,for example if we have
self.assertFailIf(is_prime(2)) ,self.assertfailIf throws an exception,unit_test.testBasic()
throws the same exception to the upper scope,but lambda:unit_test.testBasic() doesnt throws the exception and
the check
self.assertRaises(Exception,lambda: unit_test.testBasic())
fails
My question is how to make the testBasic() function so that lambda: unit_test.testBasic() will thorw the exceotion and selfassertRaises won't fail,any ideas??
A:
Do I understand you correctly in that you're asking why the testBasic_helper method doesn't raise an exception when the test runs?
I don't see why it should, the is_prime should return a bool value against which the test checks for failure. If the test fails, it simply fails, neither your code nor the unittest framework throws in exception.
P.S. "unit_test.testBasic" is already a callable, the "lambda: unit_test.testBasic()" is superfluous, so you can just write self.assertRaises(Exception, unit_test.testBasic).
| A problem with assertRaises function in Python | I am trying to run the following test
self.assertRaises(Exception,lambda:
unit_test.testBasic())
where
test.testBasic()
is
class IsPrimeTest(unittest.TestCase):
def assertRaises(self,exception,callable,*args,**kwargs):
print('dfdf')
temp = callable
super().assertRaises(exception,temp,*args,**kwargs)
def testBasic_helper(self):
self.failIf(is_prime(2))
self.assertTrue(is_prime(1))
where prime is a function,and
but in
self.assertRaises(Exception,lambda:
unit_test.testBasic())
the lambda function doesnt throws an exception after
the test
def testBasic_helper(self):
self.failIf(is_prime(2))
self.assertTrue(is_prime(1))
fails
Can somebody offers a solution to the problem?
I'll try to explain my problem ,again ,because in my first post i didn't explain it very well
So here is the source
is_prime(x) is just a function for checking for prime numbers
def is_prime(number):
PRIME, NOT_PRIME = not is_prime.broken, is_prime.broken
if number == 2:
return PRIME
if not isinstance(number, int) and not isinstance(number, float):
raise Exception
if number % 2 == 0 or number < 2 or isinstance(number, float):
return NOT_PRIME
max = int(number**0.5) + 1
for i in range(3, max, 2):
if number % i == 0:
return NOT_PRIME
return PRIME
is_prime.broken = False
class IsPrimeTest(unittest.TestCase):
def testBasic_helper(self):
self.failIf(is_prime(1))
self.assertTrue(is_prime(2))
self.failIf(is_prime(4))
self.failIf(is_prime(6))
self.assertTrue(is_prime(7))
def testBasic(self):
return self.testBasic_helper()
def testNegative(self):
self.failIf(is_prime(-2))
self.failIf(is_prime(-11 ** 3))
def testNonNumber(self):
self.assertRaises(Exception,is_prime,'asd')
self.assertRaises(Exception,is_prime,self.__class__.__name__)
def testRandom(self):
for i in range(0,10000):
rand = randint(-10000,10000)
self.assertEquals(prime(rand),is_prime(rand))
and here is Test,we can say that the test tests the program which is a test - a test over test
class MetaProgrammingTest(unittest.TestCase):
def test_decorator(self):
from p10 import unit_converter
def celsius_function(val):
return val
self.assertTrue(hasattr(unit_converter(1,2),'__call__'))
decorated = unit_converter(1.8, 32)(celsius_function)
self.assertTrue(hasattr(decorated, '__call__'))
self.assertAlmostEquals(64.4, decorated(val = 18.0))
def test_unit_test(self):
import p10
from p10sample import is_prime as is_prime_actual
unit_test = p10.IsPrimeTest('testBasic')
unit_test.setUp()
is_prime_actual.broken = False
self.assertEquals(None, unit_test.testBasic())
self.assertEquals(None, unit_test.testNegative())
self.assertEquals(None, unit_test.testNonNumber())
self.assertEquals(None, unit_test.testRandom())
is_prime_actual.broken = True
self.assertRaises(Exception,lambda: unit_test.testBasic())
self.assertRaises(Exception, lambda: unit_test.testNegative())
self.assertRaises(Exception, lambda: unit_test.testRandom())
unit_test.tearDown()
I,cant change the second test - the test over the test
So the expression self.assertRaises(Exception,lambda: unit_test.testBasic())
has to stay unchaged
My problem is that when testBasic() function fails ,for example if we have
self.assertFailIf(is_prime(2)) ,self.assertfailIf throws an exception,unit_test.testBasic()
throws the same exception to the upper scope,but lambda:unit_test.testBasic() doesnt throws the exception and
the check
self.assertRaises(Exception,lambda: unit_test.testBasic())
fails
My question is how to make the testBasic() function so that lambda: unit_test.testBasic() will thorw the exceotion and selfassertRaises won't fail,any ideas??
| [
"Do I understand you correctly in that you're asking why the testBasic_helper method doesn't raise an exception when the test runs?\nI don't see why it should, the is_prime should return a bool value against which the test checks for failure. If the test fails, it simply fails, neither your code nor the unittest framework throws in exception.\nP.S. \"unit_test.testBasic\" is already a callable, the \"lambda: unit_test.testBasic()\" is superfluous, so you can just write self.assertRaises(Exception, unit_test.testBasic).\n"
] | [
1
] | [] | [] | [
"assertraises",
"python"
] | stackoverflow_0002904073_assertraises_python.txt |
Q:
First parameter of os.exec*
From the python docs:
The various exec*() functions take a
list of arguments for the new program
loaded into the process. In each case,
the first of these arguments is passed
to the new program as its own name
rather than as an argument a user may
have typed on a command line. For the
C programmer, this is the argv[0]
passed to a program’s main(). For
example, os.execv('/bin/echo', ['foo',
'bar']) will only print bar on
standard output; foo will seem to be
ignored.
Can someone please help me understand this? What do I need to do if I want to run my own program with some parameters?
A:
UNIX, where all these exec things come from, separated the program executable file from the program name, so that your process could have any arbitrary name.
The first argument is the program that will run. This must exist. The next argument is what your process running the program will be called, what will be in argv[0], and what comes up in the ps (process list) output.
So, if I did (in C, but it maps to Python as well):
execl ("/usr/bin/sleep", "notsleep", "60", NULL);
This would run the program /usr/bin/sleep but it would show up in the process list as notsleep. argv[0] would be notsleep and argv[1] (the actual argument) would be 60. Often, the first two parameters will be identical but it's by no means required.
That's why the first argument of your list is (seemingly) ignored. It's the name to give to the process, not the first argument to it.
A more correct way to do it would be:
os.execv('/bin/echo', ['echo', 'foo', 'bar'])
| First parameter of os.exec* | From the python docs:
The various exec*() functions take a
list of arguments for the new program
loaded into the process. In each case,
the first of these arguments is passed
to the new program as its own name
rather than as an argument a user may
have typed on a command line. For the
C programmer, this is the argv[0]
passed to a program’s main(). For
example, os.execv('/bin/echo', ['foo',
'bar']) will only print bar on
standard output; foo will seem to be
ignored.
Can someone please help me understand this? What do I need to do if I want to run my own program with some parameters?
| [
"UNIX, where all these exec things come from, separated the program executable file from the program name, so that your process could have any arbitrary name.\nThe first argument is the program that will run. This must exist. The next argument is what your process running the program will be called, what will be in argv[0], and what comes up in the ps (process list) output.\nSo, if I did (in C, but it maps to Python as well):\nexecl (\"/usr/bin/sleep\", \"notsleep\", \"60\", NULL);\n\nThis would run the program /usr/bin/sleep but it would show up in the process list as notsleep. argv[0] would be notsleep and argv[1] (the actual argument) would be 60. Often, the first two parameters will be identical but it's by no means required.\nThat's why the first argument of your list is (seemingly) ignored. It's the name to give to the process, not the first argument to it.\nA more correct way to do it would be:\nos.execv('/bin/echo', ['echo', 'foo', 'bar'])\n\n"
] | [
21
] | [] | [] | [
"command_line_arguments",
"exec",
"python"
] | stackoverflow_0002904171_command_line_arguments_exec_python.txt |
Q:
python dict update diff
Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:
>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
I am looking to get a dictionary of the changed values as shown in the result of a.diff(b)
A:
No, but you can subclass dict to provide notification on change.
class ObservableDict( dict ):
def __init__( self, *args, **kw ):
self.observers= []
super( ObservableDict, self ).__init__( *args, **kw )
def observe( self, observer ):
self.observers.append( observer )
def __setitem__( self, key, value ):
for o in self.observers:
o.notify( self, key, self[key], value )
super( ObservableDict, self ).__setitem__( key, value )
def update( self, anotherDict ):
for k in anotherDict:
self[k]= anotherDict[k]
class Watcher( object ):
def notify( self, observable, key, old, new ):
print "Change to ", observable, "at", key
w= Watcher()
a= ObservableDict( {'a':'hamburger', 'b':'fries', 'c':'coke'} )
a.observe( w )
b = {'b':'fries', 'c':'pepsi'}
a.update( b )
Note that the superclass Watcher defined here doesn't check to see if there was a "real" change or not; it simply notes that there was a change.
A:
one year later
I like the following solution:
>>> def dictdiff(d1, d2):
return dict(set(d2.iteritems()) - set(d1.iteritems()))
...
>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> dictdiff(a, b)
{'c': 'pepsi', 'd': 'ice cream'}
A:
No, it doesn't. But it's not hard to write a dictionary diff function:
def diff(a, b):
diff = {}
for key in b.keys():
if (not a.has_key(key)) or (a.has_key(key) and a[key] != b[key]):
diff[key] = b[key]
return diff
A:
A simple diffing function is easy to write. Depending on how often you need it, it may be faster than the more elegant ObservableDict by S.Lott.
def dict_diff(a, b):
"""Return differences from dictionaries a to b.
Return a tuple of three dicts: (removed, added, changed).
'removed' has all keys and values removed from a. 'added' has
all keys and values that were added to b. 'changed' has all
keys and their values in b that are different from the corresponding
key in a.
"""
removed = dict()
added = dict()
changed = dict()
for key, value in a.iteritems():
if key not in b:
removed[key] = value
elif b[key] != value:
changed[key] = b[key]
for key, value in b.iteritems():
if key not in a:
added[key] = value
return removed, added, changed
if __name__ == "__main__":
print dict_diff({'foo': 1, 'bar': 2, 'yo': 4 },
{'foo': 0, 'foobar': 3, 'yo': 4 })
A:
def diff_update(dict_to_update, updater):
changes=dict((k,updater[k]) for k in filter(lambda k:(k not in dict_to_update or updater[k] != dict_to_update[k]), updater.iterkeys()))
dict_to_update.update(updater)
return changes
a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
b = {'b':'fries', 'c':'pepsi'}
>>> print diff_update(a, b)
{'c': 'pepsi'}
>>> print a
{'a': 'hamburger', 'c': 'pepsi', 'b': 'fries'}
A:
Not built in, but you could iterate on the keys of the dict and do comparisons. Could be slow though.
Better solution is probably to build a more complex datastructure and use a dictionary as the underlying representation.
| python dict update diff | Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:
>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
I am looking to get a dictionary of the changed values as shown in the result of a.diff(b)
| [
"No, but you can subclass dict to provide notification on change. \nclass ObservableDict( dict ):\n def __init__( self, *args, **kw ):\n self.observers= []\n super( ObservableDict, self ).__init__( *args, **kw )\n def observe( self, observer ):\n self.observers.append( observer )\n def __setitem__( self, key, value ):\n for o in self.observers:\n o.notify( self, key, self[key], value )\n super( ObservableDict, self ).__setitem__( key, value )\n def update( self, anotherDict ):\n for k in anotherDict:\n self[k]= anotherDict[k]\n\nclass Watcher( object ):\n def notify( self, observable, key, old, new ):\n print \"Change to \", observable, \"at\", key\n\nw= Watcher()\na= ObservableDict( {'a':'hamburger', 'b':'fries', 'c':'coke'} )\na.observe( w )\nb = {'b':'fries', 'c':'pepsi'}\na.update( b )\n\nNote that the superclass Watcher defined here doesn't check to see if there was a \"real\" change or not; it simply notes that there was a change.\n",
"one year later\nI like the following solution:\n>>> def dictdiff(d1, d2): \n return dict(set(d2.iteritems()) - set(d1.iteritems()))\n... \n>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}\n>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}\n>>> dictdiff(a, b)\n{'c': 'pepsi', 'd': 'ice cream'}\n\n",
"No, it doesn't. But it's not hard to write a dictionary diff function:\ndef diff(a, b):\n diff = {}\n for key in b.keys():\n if (not a.has_key(key)) or (a.has_key(key) and a[key] != b[key]):\n diff[key] = b[key]\n return diff\n\n",
"A simple diffing function is easy to write. Depending on how often you need it, it may be faster than the more elegant ObservableDict by S.Lott.\ndef dict_diff(a, b):\n \"\"\"Return differences from dictionaries a to b.\n\n Return a tuple of three dicts: (removed, added, changed).\n 'removed' has all keys and values removed from a. 'added' has\n all keys and values that were added to b. 'changed' has all\n keys and their values in b that are different from the corresponding\n key in a.\n\n \"\"\"\n\n removed = dict()\n added = dict()\n changed = dict()\n\n for key, value in a.iteritems():\n if key not in b:\n removed[key] = value\n elif b[key] != value:\n changed[key] = b[key]\n for key, value in b.iteritems():\n if key not in a:\n added[key] = value\n return removed, added, changed\n\nif __name__ == \"__main__\":\n print dict_diff({'foo': 1, 'bar': 2, 'yo': 4 }, \n {'foo': 0, 'foobar': 3, 'yo': 4 })\n\n",
"def diff_update(dict_to_update, updater):\n changes=dict((k,updater[k]) for k in filter(lambda k:(k not in dict_to_update or updater[k] != dict_to_update[k]), updater.iterkeys()))\n dict_to_update.update(updater)\n return changes\n\na = {'a':'hamburger', 'b':'fries', 'c':'coke'}\nb = {'b':'fries', 'c':'pepsi'}\n>>> print diff_update(a, b)\n{'c': 'pepsi'}\n>>> print a\n{'a': 'hamburger', 'c': 'pepsi', 'b': 'fries'}\n\n",
"Not built in, but you could iterate on the keys of the dict and do comparisons. Could be slow though.\nBetter solution is probably to build a more complex datastructure and use a dictionary as the underlying representation.\n"
] | [
11,
9,
2,
2,
1,
0
] | [] | [] | [
"dictionary",
"diff",
"python"
] | stackoverflow_0000715234_dictionary_diff_python.txt |
Q:
How exactly can Python complement your C# skills for windows based development?
I'm looking for a fun challenge, and am thinking about learning Python. I've heard really good things about the language. My question is, how (if at all) can Python complement the skills of a typical C# developer working mainly with MS technologies on a Windows Platform.
Some examples of typical C# dev on windows would be (SOA applications, web applications, windows services, automation, xml handling)
Surely there must be some scenarios where knowing Python would help you get certain tasks done quicker or more efficiently than using traditional C# / MS technologies.
If you know of any specific scenarios, then please share.
A:
At first, if you don't know a dymanic, non static-typed language, it will certainly help you to learn one. You will find out new programming paradigms and will affect your coding style and even if you don't use for a proper project, there are benefits in it for you. This of course applies for any new language you learn.
Specifically for C# and Python, have a look at IronPython. You can use it interchangeably with C# code and select to program specific bits in it.
One interesting application will be add scripting functionality in an existing application. You can embed IronPython to it and build a scripting environment with it.
| How exactly can Python complement your C# skills for windows based development? | I'm looking for a fun challenge, and am thinking about learning Python. I've heard really good things about the language. My question is, how (if at all) can Python complement the skills of a typical C# developer working mainly with MS technologies on a Windows Platform.
Some examples of typical C# dev on windows would be (SOA applications, web applications, windows services, automation, xml handling)
Surely there must be some scenarios where knowing Python would help you get certain tasks done quicker or more efficiently than using traditional C# / MS technologies.
If you know of any specific scenarios, then please share.
| [
"At first, if you don't know a dymanic, non static-typed language, it will certainly help you to learn one. You will find out new programming paradigms and will affect your coding style and even if you don't use for a proper project, there are benefits in it for you. This of course applies for any new language you learn.\nSpecifically for C# and Python, have a look at IronPython. You can use it interchangeably with C# code and select to program specific bits in it.\nOne interesting application will be add scripting functionality in an existing application. You can embed IronPython to it and build a scripting environment with it. \n"
] | [
4
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0002904299_c#_python.txt |
Q:
How to turn a list of tuples into a string?
I have a list of tuples that I'm trying to incorporate into a SQL query but I can't figure out how to join them together without adding slashes. My like this:
list = [('val', 'val'), ('val', 'val'), ('val', 'val')]
If I turn each tuple into a string and try to join them with a a comma I'll get something like
' (\'val\, \'val\'), ... '
What's the right way to do this, so I can get the list (without brackets) as a string?
I want to end up with::
q = """INSERT INTO test (feed,site) VALUES %s;""" % string
string = " ('val', 'val'), ('val', 'val'), ('val', 'val') "
A:
Like this?
>>> l=[('val', 'val'), ('val', 'val'), ('val', 'val')]
>>> ','.join(map(','.join,l))
'val,val,val,val,val,val'
A:
Using MySQLdb, executemany does this.
cursor = db.cursor()
vals = [(1,2,3), (4,5,6), (7,8,9), (2,5,6)]
q = """INSERT INTO first (comments, feed, keyword) VALUES (%s, %s, %s)"""
cursor.executemany(q, vals)
A:
This:
",".join( x+","+y for x,y in lst )
will produce:
'val,val,val,val,val,val'
A:
You shouldn't be doing this. Have a look at definition of the functions that are used to execute your SQL statement. They'll take care of formatting. SQL statement itself should only contain placeholders.
For example, official docs for MySQLdb show how to do exactly what you want.
A:
>>> L = [('val', 'val'), ('val', 'val'), ('val', 'val')]
>>> ','.join([repr(tup) for tup in L])
"('val', 'val'),('val', 'val'),('val', 'val')"
Though, as others have pointed out, doing this in a string placeholder meant to be sent to MySQL is rather unsafe.
| How to turn a list of tuples into a string? | I have a list of tuples that I'm trying to incorporate into a SQL query but I can't figure out how to join them together without adding slashes. My like this:
list = [('val', 'val'), ('val', 'val'), ('val', 'val')]
If I turn each tuple into a string and try to join them with a a comma I'll get something like
' (\'val\, \'val\'), ... '
What's the right way to do this, so I can get the list (without brackets) as a string?
I want to end up with::
q = """INSERT INTO test (feed,site) VALUES %s;""" % string
string = " ('val', 'val'), ('val', 'val'), ('val', 'val') "
| [
"Like this?\n>>> l=[('val', 'val'), ('val', 'val'), ('val', 'val')]\n>>> ','.join(map(','.join,l))\n'val,val,val,val,val,val'\n\n",
"Using MySQLdb, executemany does this.\ncursor = db.cursor()\nvals = [(1,2,3), (4,5,6), (7,8,9), (2,5,6)]\nq = \"\"\"INSERT INTO first (comments, feed, keyword) VALUES (%s, %s, %s)\"\"\" \ncursor.executemany(q, vals)\n\n",
"This:\n\",\".join( x+\",\"+y for x,y in lst )\n\nwill produce:\n'val,val,val,val,val,val'\n\n",
"You shouldn't be doing this. Have a look at definition of the functions that are used to execute your SQL statement. They'll take care of formatting. SQL statement itself should only contain placeholders.\nFor example, official docs for MySQLdb show how to do exactly what you want.\n",
">>> L = [('val', 'val'), ('val', 'val'), ('val', 'val')]\n>>> ','.join([repr(tup) for tup in L])\n\"('val', 'val'),('val', 'val'),('val', 'val')\"\n\nThough, as others have pointed out, doing this in a string placeholder meant to be sent to MySQL is rather unsafe.\n"
] | [
4,
2,
1,
1,
1
] | [] | [] | [
"formatting",
"python",
"sql"
] | stackoverflow_0002897082_formatting_python_sql.txt |
Q:
just-in-time list
I'd like to know if there is a class available, either in the standard library or in pypi, that fits this description.
The constructor would take an iterator.
It would implement the container protocol (ie __getitem__, __len__, etc), so that slices, length, etc., would work. In doing so, it would iterate and retain just enough values from its constructor argument to provide whatever information was requested.
So if jitlist[6] was requested, it would call self.source.next() 7 times, save those elements in its list, and return the last one.
This would allow downstream code to use it as a list, but avoid unnecessarily instantiating a list for cases where list functionality was not needed, and avoid allocating memory for the entire list if only a few members ended up being requested.
It seems like a pretty easy one to write, but it also seems useful enough that it's likely that someone would have already made it available in a module.
A:
import itertools
class Indexable(object):
def __init__(self,it):
self.it=it
self.already_computed=[]
def __iter__(self):
for elt in self.it:
self.already_computed.append(elt)
yield elt
def __getitem__(self,index):
try:
max_idx=index.stop
except AttributeError:
max_idx=index
n=max_idx-len(self.already_computed)+1
if n>0:
self.already_computed.extend(itertools.islice(self.it,n))
return self.already_computed[index]
| just-in-time list | I'd like to know if there is a class available, either in the standard library or in pypi, that fits this description.
The constructor would take an iterator.
It would implement the container protocol (ie __getitem__, __len__, etc), so that slices, length, etc., would work. In doing so, it would iterate and retain just enough values from its constructor argument to provide whatever information was requested.
So if jitlist[6] was requested, it would call self.source.next() 7 times, save those elements in its list, and return the last one.
This would allow downstream code to use it as a list, but avoid unnecessarily instantiating a list for cases where list functionality was not needed, and avoid allocating memory for the entire list if only a few members ended up being requested.
It seems like a pretty easy one to write, but it also seems useful enough that it's likely that someone would have already made it available in a module.
| [
"import itertools\nclass Indexable(object):\n def __init__(self,it):\n self.it=it\n self.already_computed=[]\n def __iter__(self):\n for elt in self.it:\n self.already_computed.append(elt)\n yield elt\n def __getitem__(self,index):\n try:\n max_idx=index.stop\n except AttributeError:\n max_idx=index\n n=max_idx-len(self.already_computed)+1\n if n>0:\n self.already_computed.extend(itertools.islice(self.it,n))\n return self.already_computed[index] \n\n"
] | [
2
] | [] | [] | [
"iterator",
"list",
"python"
] | stackoverflow_0002904459_iterator_list_python.txt |
Q:
Django models & Python class attributes
The tutorial on the django website shows this code for the models:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Now, each of those attribute, is a class attribute, right? So, the same attribute should be shared by all instances of the class. A bit later, they present this code:
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
How did they turn from class attributes into instance attributes? Did I get class attributes wrong?
A:
Have a look at the Model class under django/db/models.py. There the class attributes are turned to instance attributes via something like
setattr(self, field.attname, val)
One might recommend the whole file (ModelBase and Model class) as an excellent hands-on example on metaclasses.
A:
It's done with metaclasses - very clever stuff. I'd recommend Marty Alchin's excellent book Pro Django if you want to learn more.
A:
In Python, a class attribute is always also an instance attribute:
class C(object):
a = 1
def show_a(self):
print self.a # <- works
But in django it is further complicated by the fact that Model classes have special metaclasses, so be careful to your assumptions!
A:
A class instance has a namespace
implemented as a dictionary which is
the first place in which attribute
references are searched.
http://docs.python.org/reference/datamodel.html
| Django models & Python class attributes | The tutorial on the django website shows this code for the models:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Now, each of those attribute, is a class attribute, right? So, the same attribute should be shared by all instances of the class. A bit later, they present this code:
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
How did they turn from class attributes into instance attributes? Did I get class attributes wrong?
| [
"Have a look at the Model class under django/db/models.py. There the class attributes are turned to instance attributes via something like\nsetattr(self, field.attname, val)\n\nOne might recommend the whole file (ModelBase and Model class) as an excellent hands-on example on metaclasses.\n",
"It's done with metaclasses - very clever stuff. I'd recommend Marty Alchin's excellent book Pro Django if you want to learn more.\n",
"In Python, a class attribute is always also an instance attribute:\nclass C(object):\n a = 1\n def show_a(self):\n print self.a # <- works\n\nBut in django it is further complicated by the fact that Model classes have special metaclasses, so be careful to your assumptions!\n",
"\nA class instance has a namespace\n implemented as a dictionary which is\n the first place in which attribute\n references are searched.\n\nhttp://docs.python.org/reference/datamodel.html\n"
] | [
7,
2,
2,
0
] | [] | [] | [
"attributes",
"django",
"python"
] | stackoverflow_0002903671_attributes_django_python.txt |
Q:
python: multiline regular expression
I have a piece of text and I've got to parse usernames and hashes out of it. Right now I'm doing it with two regular expressions. Could I do it with just one multiline regular expression?
#!/usr/bin/env python
import re
test_str = """
Hello, UserName.
Please read this looooooooooooooooong text. hash
Now, write down this hash: fdaf9399jef9qw0j.
Then keep reading this loooooooooong text.
Hello, UserName2.
Please read this looooooooooooooooong text. hash
Now, write down this hash: gtwnhton340gjr2g.
Then keep reading this loooooooooong text.
"""
logins = re.findall('Hello, (?P<login>.+).',test_str)
hashes = re.findall('hash: (?P<hash>.+).',test_str)
A:
Try this:
re.findall(r'Hello, (?P<login>[^.]+)\..+?hash: (?P<hash>[^.]+)', test_str, re.S)
A:
name_hash_pair = re.findall('Hello, ([^.]+).*?hash: ([^.]+)', test_str, re.DOTALL)
#gives [('UserName', 'fdaf9399jef9qw0j'), ('UserName2', 'gtwnhton340gjr2g')]
A:
A simple pyparsing version:
from pyparsing import *
username = Word(alphas,alphanums+"_")
hash = Word(alphanums)
patt = ("Hello," + username("username") + '.' +
SkipTo("write down this hash:", include=True) +
hash("hash"))
for tokens,start,end in patt.scanString(test_str):
print tokens.hash, '->', tokens.username
# or to build a dict
hashNameLookup = dict((t.hash, t.username)
for t,s,e in patt.scanString(test_str))
Prints:
fdaf9399jef9qw0j -> UserName
gtwnhton340gjr2g -> UserName2
| python: multiline regular expression | I have a piece of text and I've got to parse usernames and hashes out of it. Right now I'm doing it with two regular expressions. Could I do it with just one multiline regular expression?
#!/usr/bin/env python
import re
test_str = """
Hello, UserName.
Please read this looooooooooooooooong text. hash
Now, write down this hash: fdaf9399jef9qw0j.
Then keep reading this loooooooooong text.
Hello, UserName2.
Please read this looooooooooooooooong text. hash
Now, write down this hash: gtwnhton340gjr2g.
Then keep reading this loooooooooong text.
"""
logins = re.findall('Hello, (?P<login>.+).',test_str)
hashes = re.findall('hash: (?P<hash>.+).',test_str)
| [
"Try this:\nre.findall(r'Hello, (?P<login>[^.]+)\\..+?hash: (?P<hash>[^.]+)', test_str, re.S)\n\n",
"name_hash_pair = re.findall('Hello, ([^.]+).*?hash: ([^.]+)', test_str, re.DOTALL)\n#gives [('UserName', 'fdaf9399jef9qw0j'), ('UserName2', 'gtwnhton340gjr2g')]\n\n",
"A simple pyparsing version:\nfrom pyparsing import *\n\nusername = Word(alphas,alphanums+\"_\")\nhash = Word(alphanums)\n\npatt = (\"Hello,\" + username(\"username\") + '.' + \n SkipTo(\"write down this hash:\", include=True) + \n hash(\"hash\"))\n\nfor tokens,start,end in patt.scanString(test_str):\n print tokens.hash, '->', tokens.username\n\n# or to build a dict\nhashNameLookup = dict((t.hash, t.username) \n for t,s,e in patt.scanString(test_str))\n\nPrints:\nfdaf9399jef9qw0j -> UserName\ngtwnhton340gjr2g -> UserName2\n\n"
] | [
5,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002903309_python_regex.txt |
Q:
Find out 20th, 30th, nth prime number. (I'm getting 20th but not 30th?) [Python]
The question is to find the 1000th prime number. I wrote the following python code for this. The problem is, I get the right answer for the 10th , 20th prime but after that each increment of 10 leaves me one off the mark. I can't catch the bug here :(
count=1 #to keep count of prime numbers
primes=() #tuple to hold primes
candidate=3 #variable to test for primes
while count<20:
for x in range(2,candidate):
if candidate%x==0:
candidate=candidate+2
else : pass
primes=primes+(candidate,)
candidate=candidate+2
count=count+1
print primes
print "20th prime is ", primes[-1]
In case you're wondering, count is initialised as 1 because I am not testing for 2 as a prime number(I'm starting from 3) and candidate is being incremented by 2 because only odd numbers can be prime numbers. I know there are other ways of solving this problem, such as the prime number theorem but I wanna know what's wrong with this approach. Also if there are any optimisations you have in mind, please suggest.
Thank You
A:
There is a nice Sieve of Eratosthenes generator implementation in test_generators.py:
def intsfrom(i):
while 1:
yield i
i += 1
def firstn(g, n):
return [g.next() for i in range(n)]
def exclude_multiples(n, ints):
for i in ints:
if i % n:
yield i
def sieve(ints):
prime = ints.next()
yield prime
not_divisible_by_prime = exclude_multiples(prime, ints)
for p in sieve(not_divisible_by_prime):
yield p
primes = sieve(intsfrom(2))
>>> print firstn(primes, 20)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
A:
There is lots (!) to be improved with your Python code, but to answer your specific question:
When you have found a divisor (candidate % x == 0), you increment the candidate, but you don't do anything about x. This can lead to two problems:
candidate might have a divisor, but it's smaller than any x that gets tested -- because testing in the next iteration of the loop starts with x being one higher than the value x had before; not at 2.
candidate might have a divisor, but it's larger than x ever gets, because you take x from the values from 2 to the value candidate had when you started the loop.
A:
I don't think this is testing what you think it's testing. It looks like you're trying to say "for each number between 2 and my candidate, check to see if the candidate is evenly divisible by that number". However, when you find a prime (candidate%x == 0), you're only incrementing the candidate-- you still need to start your "for x in ..." loop over again, since the candidate has changed.
That's what I can see from the code as written; there are of course lots of other ways and other optimizations to use here.
A:
It's good to know that every prime number bigger than 3 can be written as:
6k-1/+1.
When you are looking for the next candidate, you can always write something like this (code snippet is in C):
a=1;
...
candidate=6*k+(a=(a==-1)?1:-1);
if(a==1){
k++;
}
And a function I've used not so long ago to determine the nth prime number, where LIM is the nth number you are looking for (C code):
int sol2(){
int res,cnt,i,k,a;
res=-1;
i=1;
cnt=3;
k=1;
a=1;
while (1){
if (util_isprime(cnt)){
i++;
if (i==LIM){
res=cnt;
break;
}
}
/* 6k+/-1 starting from 6*1-1 */
cnt=6*k+(a=(a==-1)?1:-1);
if(a==1){
k++;
}
}
return res;
}
A:
in the statement:
for x in range(2,candidate)
you can reduce the number of iterations by scanning up to sqrt(candidate)
If candidate is divisible by x, then we
can write candidate=x*b for some b. If x
is less than or equal to b, then x
must be smaller than or equal to the
square root of candidate
A:
As for optimizations, if you're definite that you want to follow this implementation, you could avoid looking at numbers that:
end in 5, since they are divisible by 5.
are comprised by the same digits, e.g. 22, 33, 44, 55, 66, etc., since they are divisible by 11.
Don't forget to add 5 and 11 as primes though!
A:
Unless I'm very much mistaken, you are always adding the current candidate to the list of primes, regardless of whether a divisor has been found or not. Your code to append to the list of primes (putting aside the immutable tuple comment made earlier) is outside of the test for integer divisors, and therefore always run.
A:
If you want anything remotely efficient, do the Sieve of Eratosthenes - it's as simple as it's old.
MAX = 10000
candidates = [True] * MAX
candidates[0] = False
candidates[1] = False
primelist = []
for p,isprime in enumerate(candidates):
if isprime:
primelist.append(p)
for n in range(2*p,MAX,p):
candidates[n] = False
print primelist[1001]
A:
FYI... I solved it with the following code, though it can be optimised much much more, I just wanted to solve it in this manner first. Thanks everyone for your help.
from math import *
primes=[2,3]
count=2
testnumber=5
while count<1000:
flag=0
for x in range(2,testnumber):
if x<=sqrt(testnumber):
if testnumber%x==0:
#print testnumber , "is not a prime"
flag=1
else : pass
if flag!=1:
#print testnumber , "is a prime"
primes=primes+[testnumber]
count=count+1
testnumber=testnumber+2
#print primes
print "1000th prime is ", primes[-1]
I will now look at all the other algorithms mentioned by you all
A:
c beginner
#include<stdio.h>
int main ()
{
int a,s,c,v,f,p,z;
while(scanf("%d",&f) !=EOF){
p=0;
for(z=1;p<f;z++){
s=2;
a=z;
while(s<a){
if(a%s==0)s=a+1;
else s=s+1;
}
if (s!=a+1)p++;
}
printf("%d\n",a);
}
return 0;
}
| Find out 20th, 30th, nth prime number. (I'm getting 20th but not 30th?) [Python] | The question is to find the 1000th prime number. I wrote the following python code for this. The problem is, I get the right answer for the 10th , 20th prime but after that each increment of 10 leaves me one off the mark. I can't catch the bug here :(
count=1 #to keep count of prime numbers
primes=() #tuple to hold primes
candidate=3 #variable to test for primes
while count<20:
for x in range(2,candidate):
if candidate%x==0:
candidate=candidate+2
else : pass
primes=primes+(candidate,)
candidate=candidate+2
count=count+1
print primes
print "20th prime is ", primes[-1]
In case you're wondering, count is initialised as 1 because I am not testing for 2 as a prime number(I'm starting from 3) and candidate is being incremented by 2 because only odd numbers can be prime numbers. I know there are other ways of solving this problem, such as the prime number theorem but I wanna know what's wrong with this approach. Also if there are any optimisations you have in mind, please suggest.
Thank You
| [
"There is a nice Sieve of Eratosthenes generator implementation in test_generators.py:\ndef intsfrom(i):\n while 1:\n yield i\n i += 1\n\ndef firstn(g, n):\n return [g.next() for i in range(n)]\n\ndef exclude_multiples(n, ints):\n for i in ints:\n if i % n:\n yield i \n\ndef sieve(ints):\n prime = ints.next()\n yield prime\n not_divisible_by_prime = exclude_multiples(prime, ints)\n for p in sieve(not_divisible_by_prime):\n yield p\n\nprimes = sieve(intsfrom(2))\n\n>>> print firstn(primes, 20)\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]\n\n\n",
"There is lots (!) to be improved with your Python code, but to answer your specific question: \nWhen you have found a divisor (candidate % x == 0), you increment the candidate, but you don't do anything about x. This can lead to two problems:\n\ncandidate might have a divisor, but it's smaller than any x that gets tested -- because testing in the next iteration of the loop starts with x being one higher than the value x had before; not at 2.\ncandidate might have a divisor, but it's larger than x ever gets, because you take x from the values from 2 to the value candidate had when you started the loop.\n\n",
"I don't think this is testing what you think it's testing. It looks like you're trying to say \"for each number between 2 and my candidate, check to see if the candidate is evenly divisible by that number\". However, when you find a prime (candidate%x == 0), you're only incrementing the candidate-- you still need to start your \"for x in ...\" loop over again, since the candidate has changed.\nThat's what I can see from the code as written; there are of course lots of other ways and other optimizations to use here.\n",
"It's good to know that every prime number bigger than 3 can be written as:\n6k-1/+1. \nWhen you are looking for the next candidate, you can always write something like this (code snippet is in C):\na=1;\n...\ncandidate=6*k+(a=(a==-1)?1:-1);\nif(a==1){\n k++;\n}\n\nAnd a function I've used not so long ago to determine the nth prime number, where LIM is the nth number you are looking for (C code):\nint sol2(){\n int res,cnt,i,k,a;\n res=-1;\n i=1;\n cnt=3;\n k=1;\n a=1;\n while (1){\n if (util_isprime(cnt)){\n i++;\n if (i==LIM){\n res=cnt;\n break;\n }\n }\n /* 6k+/-1 starting from 6*1-1 */\n cnt=6*k+(a=(a==-1)?1:-1);\n if(a==1){\n k++;\n }\n }\n return res;\n}\n\n",
"in the statement:\nfor x in range(2,candidate)\n\nyou can reduce the number of iterations by scanning up to sqrt(candidate) \n\nIf candidate is divisible by x, then we\n can write candidate=x*b for some b. If x\n is less than or equal to b, then x \n must be smaller than or equal to the\n square root of candidate\n\n",
"As for optimizations, if you're definite that you want to follow this implementation, you could avoid looking at numbers that:\n\nend in 5, since they are divisible by 5.\nare comprised by the same digits, e.g. 22, 33, 44, 55, 66, etc., since they are divisible by 11.\n\nDon't forget to add 5 and 11 as primes though!\n",
"Unless I'm very much mistaken, you are always adding the current candidate to the list of primes, regardless of whether a divisor has been found or not. Your code to append to the list of primes (putting aside the immutable tuple comment made earlier) is outside of the test for integer divisors, and therefore always run.\n",
"If you want anything remotely efficient, do the Sieve of Eratosthenes - it's as simple as it's old.\nMAX = 10000\ncandidates = [True] * MAX\ncandidates[0] = False\ncandidates[1] = False\n\nprimelist = []\nfor p,isprime in enumerate(candidates):\n if isprime:\n primelist.append(p)\n for n in range(2*p,MAX,p):\n candidates[n] = False\n\nprint primelist[1001]\n\n",
"FYI... I solved it with the following code, though it can be optimised much much more, I just wanted to solve it in this manner first. Thanks everyone for your help.\nfrom math import *\nprimes=[2,3]\ncount=2\ntestnumber=5\nwhile count<1000:\n\n flag=0\n for x in range(2,testnumber):\n if x<=sqrt(testnumber):\n if testnumber%x==0:\n #print testnumber , \"is not a prime\"\n flag=1\n\n else : pass\n if flag!=1:\n #print testnumber , \"is a prime\"\n primes=primes+[testnumber]\n count=count+1\n testnumber=testnumber+2\n\n\n#print primes\nprint \"1000th prime is \", primes[-1]\n\nI will now look at all the other algorithms mentioned by you all\n",
"c beginner \n#include<stdio.h>\nint main ()\n\n{\nint a,s,c,v,f,p,z;\n\nwhile(scanf(\"%d\",&f) !=EOF){\np=0;\nfor(z=1;p<f;z++){\n s=2;\n a=z;\n while(s<a){\n if(a%s==0)s=a+1;\n else s=s+1;\n }\n if (s!=a+1)p++;\n\n }\nprintf(\"%d\\n\",a);\n }\n\nreturn 0;\n}\n\n"
] | [
8,
5,
3,
2,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"primes",
"python"
] | stackoverflow_0001995890_primes_python.txt |
Q:
web2py external libraries
how can i import other external libraries in web2py? is it possible to
load up libs in the static file?
can somebody give me an example?
thanks
peter
A:
If the library is shipped with python, then you can just use import as you would do in regular python script. You can place your import statements into your models, controllers and views, as well as your own python modules (stored in modules folder). For example, I often use traceback module to log stack traces in my controllers:
import traceback
def myaction():
try:
...
except Exception as exc:
logging.error(traceback.format_exc())
return dict(error=str(exc))
If the library is not shipped with python (for example, pyodbc), then you will have to install that library (using distutils or easy_install or pip) so that python can find it and run web2py from the source code: python web2py.py. Then you will be able to use regular import statement as described above. Before you do this make sure you installed the library properly: run python interpreter and type "import library_name". If you don't get any errors you are good to go.
If you have a third party python module or package, you can place it to modules folder and import it as shown below:
mymodule = local_import('module_name')
You can also force web2py to reload the module every time local_import is executed by setting reload option:
mymodule = local_import('module_name', reload=True)
See http://web2py.com/book/default/section/4/18?search=site-packages for more information.
A:
In web2py you import external library as you normally do in Python
import module_name
or
from module_name import object_name
I am not sure what you mean by "in the static file"
| web2py external libraries | how can i import other external libraries in web2py? is it possible to
load up libs in the static file?
can somebody give me an example?
thanks
peter
| [
"If the library is shipped with python, then you can just use import as you would do in regular python script. You can place your import statements into your models, controllers and views, as well as your own python modules (stored in modules folder). For example, I often use traceback module to log stack traces in my controllers:\nimport traceback\n\ndef myaction():\n try:\n ...\n except Exception as exc:\n logging.error(traceback.format_exc())\n return dict(error=str(exc))\n\nIf the library is not shipped with python (for example, pyodbc), then you will have to install that library (using distutils or easy_install or pip) so that python can find it and run web2py from the source code: python web2py.py. Then you will be able to use regular import statement as described above. Before you do this make sure you installed the library properly: run python interpreter and type \"import library_name\". If you don't get any errors you are good to go.\nIf you have a third party python module or package, you can place it to modules folder and import it as shown below:\nmymodule = local_import('module_name')\n\nYou can also force web2py to reload the module every time local_import is executed by setting reload option:\nmymodule = local_import('module_name', reload=True)\n\nSee http://web2py.com/book/default/section/4/18?search=site-packages for more information.\n",
"In web2py you import external library as you normally do in Python\nimport module_name\n\nor\nfrom module_name import object_name\n\nI am not sure what you mean by \"in the static file\"\n"
] | [
5,
0
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0002904498_python_web2py.txt |
Q:
How can I convert data encoded in WE8MSWIN1252 to utf8 for use in Python scripts?
This data comes from an Oracle database and is extracted to flatfiles in encoding 'WE8MSWIN1252'.
I want to parse the data and do some analysis. I want to see the text fields but do not need to publish the results to any other system so if some characters do not get converted perfectly I do not have a problem with that.
I just do not want my parsing to fail with a decode error which is what I get if I use:
inputFile = codecs.open( dataFileName, "r", "utf-8'")
A:
From the last few characters, I'd guess that this encoding is what the rest of the world calls windows-1252. So try:
inputFile = codecs.open(dataFileName, "r", "windows-1252")
| How can I convert data encoded in WE8MSWIN1252 to utf8 for use in Python scripts? | This data comes from an Oracle database and is extracted to flatfiles in encoding 'WE8MSWIN1252'.
I want to parse the data and do some analysis. I want to see the text fields but do not need to publish the results to any other system so if some characters do not get converted perfectly I do not have a problem with that.
I just do not want my parsing to fail with a decode error which is what I get if I use:
inputFile = codecs.open( dataFileName, "r", "utf-8'")
| [
"From the last few characters, I'd guess that this encoding is what the rest of the world calls windows-1252. So try:\ninputFile = codecs.open(dataFileName, \"r\", \"windows-1252\")\n\n"
] | [
2
] | [] | [] | [
"oracle",
"python",
"utf_8"
] | stackoverflow_0002904873_oracle_python_utf_8.txt |
Q:
What the heck kind of timestamp is this: 1267488000000
And how do I convert it to a datetime.datetime instance in python?
It's the output from the New York State Senate's API: http://open.nysenate.gov/legislation/.
A:
It looks like Unix time, but with milliseconds instead of seconds?
>>> import time
>>> time.gmtime(1267488000000 / 1000)
time.struct_time(tm_year=2010, tm_mon=3, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=61, tm_isdst=0)
March 2nd, 2010?
And if you want a datetime object:
>>> import datetime
>>> datetime.datetime.fromtimestamp(1267488000000 / 1000)
datetime.datetime(2010, 3, 1, 19, 0)
Note that the datetime is using the local timezone while the time.struct_time is using UTC.
A:
Maybe milliseconds?
>>> import time
>>> time.gmtime(1267488000000/1000)
time.struct_time(tm_year=2010, tm_mon=3, tm_mday=2, \
tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=61, tm_isdst=0)
A:
Try this:
import datetime
datetime.datetime.fromtimestamp(1267488000000/1000)
A:
It's in miliseconds from epoch (but rounded to tousends of seconds). Try using:
datetime.datetime.fromtimestamp(timestamp / 1000)
A:
This is pretty informative. I think you have a time stamp in milliseconds since Thursday, January 1st, 1970.
A:
1267488000000 is a epoch timestamp with milliseconds. It is "Tue Mar 02 2010 08:00:00 GMT+0800 (WST)" (where I live, at least)
A:
Note that the Javascript Date object and the Java Date class both use milliseconds since Jan 1 1970 GMT. Both languages are commonly used in web services.
A:
This is almost certainly a timestamp (the number of milliseconds since the epoch). You want date.fromtimestamp(timestamp) to make sense of it.
A:
This is probably a Unix timestamp. See here for some time conversions in python.
| What the heck kind of timestamp is this: 1267488000000 | And how do I convert it to a datetime.datetime instance in python?
It's the output from the New York State Senate's API: http://open.nysenate.gov/legislation/.
| [
"It looks like Unix time, but with milliseconds instead of seconds?\n>>> import time\n>>> time.gmtime(1267488000000 / 1000)\ntime.struct_time(tm_year=2010, tm_mon=3, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=61, tm_isdst=0)\n\nMarch 2nd, 2010?\nAnd if you want a datetime object:\n>>> import datetime\n>>> datetime.datetime.fromtimestamp(1267488000000 / 1000)\ndatetime.datetime(2010, 3, 1, 19, 0)\n\nNote that the datetime is using the local timezone while the time.struct_time is using UTC.\n",
"Maybe milliseconds?\n>>> import time\n>>> time.gmtime(1267488000000/1000)\ntime.struct_time(tm_year=2010, tm_mon=3, tm_mday=2, \\\n tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=61, tm_isdst=0)\n\n",
"Try this:\nimport datetime\ndatetime.datetime.fromtimestamp(1267488000000/1000)\n\n",
"It's in miliseconds from epoch (but rounded to tousends of seconds). Try using:\ndatetime.datetime.fromtimestamp(timestamp / 1000)\n\n",
"This is pretty informative. I think you have a time stamp in milliseconds since Thursday, January 1st, 1970.\n",
"1267488000000 is a epoch timestamp with milliseconds. It is \"Tue Mar 02 2010 08:00:00 GMT+0800 (WST)\" (where I live, at least)\n",
"Note that the Javascript Date object and the Java Date class both use milliseconds since Jan 1 1970 GMT. Both languages are commonly used in web services.\n",
"This is almost certainly a timestamp (the number of milliseconds since the epoch). You want date.fromtimestamp(timestamp) to make sense of it.\n",
"This is probably a Unix timestamp. See here for some time conversions in python.\n"
] | [
15,
5,
4,
3,
3,
2,
2,
1,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002904847_datetime_python.txt |
Q:
How to tell process id within Python
I am working with a cluster system over linux (www.mosix.org) that allows me to run jobs and have the system run them on different computers. Jobs are run like so:
mosrun ls &
This will naturally create the process and run it on the background, returning the process id, like so:
[1] 29199
Later it will return. I am writing a Python infrastructure that would run jobs and control them. For that I want to run jobs using the mosrun program as above, and save the process ID of the spawned process (29199 in this case). This naturally cannot be done using os.system or commands.getoutput, as the printed ID is not what the process prints to output... Any clues?
Edit:
Since the python script is only meant to initially run the script, the scripts need to run longer than the python shell. I guess it means the mosrun process cannot be the script's child process. Any suggestions?
Thanks
A:
Use subprocess module. Popen instances have a pid attribute.
A:
Looks like you want to ensure the child process is daemonized -- PEP 3143, which I'm pointing to, documents and points to a reference implementation for that, and points to others too.
Once your process (still running Python code) is daemonized, be it by the means offered in PEP 3143 or others, you can os.execl (or other os.exec... function) your target code -- this runs said target code in exactly the same process which we just said is daemonized, and so it keeps being daemonized, as desired.
The last step cannot use subprocess because it needs to run in the same (daemonized) process, overlaying its executable code -- exactly what os.execl and friends are for.
The first step, before daemonization, might conceivably be done via subprocess, but that's somewhat inconvenient (you need to put the daemonize-then-os.exec code in a separate .py): most commonly you'd just want to os.fork and immediately daemonize the child process.
subprocess is quite convenient as a mostly-cross-platform way to run other processes, but it can't really replace Unix's good old "fork and exec" approach for advanced uses (such as daemonization, in this case) -- which is why it's a good thing that the Python standard library also lets you do the latter via those functions in module os!-)
A:
Thanks all for the help. Here's what I did in the end, and seems to work ok. The code uses python-daemon. Maybe something smarter should be done about transferring the process id from the child to the father, but that's the easier part.
import daemon
def run_in_background(command, tmp_dir="/tmp"):
# Decide on a temp file beforehand
warnings.filterwarnings("ignore", "tempnam is a potential security")
tmp_filename = os.tempnam(tmp_dir)
# Duplicate the process
pid = os.fork()
# If we're child, daemonize and run
if pid == 0:
with daemon.DaemonContext():
child_id = os.getpid()
file(tmp_filename,'w').write(str(child_id))
sp = command.split(' ')
os.execl(*([sp[0]]+sp))
else:
# If we're a parent, poll for the new file
n_iter = 0
while True:
if os.path.exists(tmp_filename):
child_id = int(file(tmp_filename, 'r').read().strip())
break
if n_iter == 100:
raise Exception("Cannot read process id from temp file %s" % tmp_filename)
n_iter += 1
time.sleep(0.1)
return child_id
| How to tell process id within Python | I am working with a cluster system over linux (www.mosix.org) that allows me to run jobs and have the system run them on different computers. Jobs are run like so:
mosrun ls &
This will naturally create the process and run it on the background, returning the process id, like so:
[1] 29199
Later it will return. I am writing a Python infrastructure that would run jobs and control them. For that I want to run jobs using the mosrun program as above, and save the process ID of the spawned process (29199 in this case). This naturally cannot be done using os.system or commands.getoutput, as the printed ID is not what the process prints to output... Any clues?
Edit:
Since the python script is only meant to initially run the script, the scripts need to run longer than the python shell. I guess it means the mosrun process cannot be the script's child process. Any suggestions?
Thanks
| [
"Use subprocess module. Popen instances have a pid attribute.\n",
"Looks like you want to ensure the child process is daemonized -- PEP 3143, which I'm pointing to, documents and points to a reference implementation for that, and points to others too.\nOnce your process (still running Python code) is daemonized, be it by the means offered in PEP 3143 or others, you can os.execl (or other os.exec... function) your target code -- this runs said target code in exactly the same process which we just said is daemonized, and so it keeps being daemonized, as desired.\nThe last step cannot use subprocess because it needs to run in the same (daemonized) process, overlaying its executable code -- exactly what os.execl and friends are for.\nThe first step, before daemonization, might conceivably be done via subprocess, but that's somewhat inconvenient (you need to put the daemonize-then-os.exec code in a separate .py): most commonly you'd just want to os.fork and immediately daemonize the child process.\nsubprocess is quite convenient as a mostly-cross-platform way to run other processes, but it can't really replace Unix's good old \"fork and exec\" approach for advanced uses (such as daemonization, in this case) -- which is why it's a good thing that the Python standard library also lets you do the latter via those functions in module os!-)\n",
"Thanks all for the help. Here's what I did in the end, and seems to work ok. The code uses python-daemon. Maybe something smarter should be done about transferring the process id from the child to the father, but that's the easier part.\nimport daemon\ndef run_in_background(command, tmp_dir=\"/tmp\"):\n\n # Decide on a temp file beforehand\n warnings.filterwarnings(\"ignore\", \"tempnam is a potential security\")\n tmp_filename = os.tempnam(tmp_dir)\n\n # Duplicate the process\n pid = os.fork()\n\n\n # If we're child, daemonize and run\n if pid == 0:\n with daemon.DaemonContext():\n child_id = os.getpid()\n file(tmp_filename,'w').write(str(child_id))\n sp = command.split(' ')\n os.execl(*([sp[0]]+sp))\n else:\n # If we're a parent, poll for the new file\n n_iter = 0\n while True:\n if os.path.exists(tmp_filename):\n child_id = int(file(tmp_filename, 'r').read().strip())\n break\n\n if n_iter == 100:\n raise Exception(\"Cannot read process id from temp file %s\" % tmp_filename)\n n_iter += 1\n\n time.sleep(0.1)\n\n return child_id\n\n"
] | [
3,
2,
0
] | [] | [] | [
"mosix",
"process",
"python"
] | stackoverflow_0002884711_mosix_process_python.txt |
Q:
Is it possibile to modify a link value with Beautifulsoup without recreating the all link?
Starting from an Html input like this:
<p>
<a href="http://www.foo.com" rel="nofollow">this is foo</a>
<a href="http://www.bar.com" rel="nofollow">this is bar</a>
</p>
is it possible to modify the <a> node values ("this i foo" and "this is bar") adding the suffix "PARSED" to the value without recreating the all link?
The result need to be like this:
<p>
<a href="http://www.foo.com" rel="nofollow">this is foo_PARSED</a>
<a href="http://www.bar.com" rel="nofollow">this is bar_PARSED</a>
</p>
And code should be something like:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for link_tag in soup.findAll('a'):
link_tag.string = link_tag.string + '_PARSED' #This obviously does not work
A:
If I understand you correctly then you're nearly there.
Change your code to
for link_tag in soup.findAll('a'):
link_tag.string = link_tag.string + '_PARSED'
html_out = soup.renderContents()
If we print out html_out we get:
>>> print html_out
<p>
<a href="http://www.foo.com" rel="nofollow">this is foo_PARSED</a>
<a href="http://www.bar.com" rel="nofollow">this is bar_PARSED</a>
</p>
which I think is what you wanted.
| Is it possibile to modify a link value with Beautifulsoup without recreating the all link? | Starting from an Html input like this:
<p>
<a href="http://www.foo.com" rel="nofollow">this is foo</a>
<a href="http://www.bar.com" rel="nofollow">this is bar</a>
</p>
is it possible to modify the <a> node values ("this i foo" and "this is bar") adding the suffix "PARSED" to the value without recreating the all link?
The result need to be like this:
<p>
<a href="http://www.foo.com" rel="nofollow">this is foo_PARSED</a>
<a href="http://www.bar.com" rel="nofollow">this is bar_PARSED</a>
</p>
And code should be something like:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for link_tag in soup.findAll('a'):
link_tag.string = link_tag.string + '_PARSED' #This obviously does not work
| [
"If I understand you correctly then you're nearly there.\nChange your code to \nfor link_tag in soup.findAll('a'):\n link_tag.string = link_tag.string + '_PARSED'\nhtml_out = soup.renderContents()\n\nIf we print out html_out we get:\n>>> print html_out\n<p>\n<a href=\"http://www.foo.com\" rel=\"nofollow\">this is foo_PARSED</a>\n<a href=\"http://www.bar.com\" rel=\"nofollow\">this is bar_PARSED</a>\n</p>\n\nwhich I think is what you wanted.\n"
] | [
3
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0002904542_beautifulsoup_python.txt |
Q:
python c extension, problems with dlopen on mac os
I've taken a library that is distributed as a binary lib (.a) and header, written some c++ code against it, and want to wrap the results up in a python module.
I've done this here.
The problem is that when importing this module on Mac OSX (I've tried 10.5 and 10.6), I get the following error:
dlopen(/Library/Python/2.5/site-packages/dirac.so, 2): Symbol not found: _DisposePtr
Referenced from: /Library/Python/2.5/site-packages/dirac.so
Expected in: dynamic lookup
This looks like symbols defined in the Carbon framework aren't being properly resolved, but I'm not sure what to do about that. I am supplying -framework Carbon to distutil.core.Extension's extra_link_args parameter, so I'm not sure what else I should do.
Any help would be much appreciated.
Update:
The compile line generated by setup.py looks like this:
gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe -Isource -I/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/numpy/core/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/numpy/numarray -I/usr/lib/python/2.5/site-packages/numpy/numarray/numpy -I/usr/lib/python/2.5/site-packages/numpy/numarray -I/usr/lib/python/2.5/site-packages/numpy/core/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c source/Dirac_LE.cpp -o build/temp.macosx-10.5-i386-2.5/source/Dirac_LE.o
The linker line looks like this:
g++ -Wl,-F. -bundle -undefined dynamic_lookup -arch i386 -arch ppc build/temp.macosx-10.5-i386-2.5/diracmodule.o build/temp.macosx-10.5-i386-2.5/source/Dirac_LE.o -Llibs/MacOSX -lDiracLE -o build/lib.macosx-10.5-i386-2.5/dirac.so -framework Carbon
otool reports:
dirac.so:
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.4.0)
/usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 111.1.5)
Update 2:
On MacOS 10.5, modifying the dlopen flags from the default of RTLD_NOW to RTLD_LAZY solves the problem. However, this does not work on Mac OS 10.6.
On 10.6, the following sequence allows the library to run properly, although I'm not sure why:
python setup.py build -v
run the linker line (printed to console by setup.py) again, manually.
python setup.py install
I'm still looking for a good answer as to how to get this to work properly. Thanks!
A:
You're going to kick yourself when you see the answer to this! Try changing this:
link_args = ['-framework Carbon'] if platform == 'Darwin' else []
to this:
link_args = ['-framework', 'Carbon'] if platform == 'Darwin' else []
Once I made this change I was able to do a clean build and import the module straight away :)
| python c extension, problems with dlopen on mac os | I've taken a library that is distributed as a binary lib (.a) and header, written some c++ code against it, and want to wrap the results up in a python module.
I've done this here.
The problem is that when importing this module on Mac OSX (I've tried 10.5 and 10.6), I get the following error:
dlopen(/Library/Python/2.5/site-packages/dirac.so, 2): Symbol not found: _DisposePtr
Referenced from: /Library/Python/2.5/site-packages/dirac.so
Expected in: dynamic lookup
This looks like symbols defined in the Carbon framework aren't being properly resolved, but I'm not sure what to do about that. I am supplying -framework Carbon to distutil.core.Extension's extra_link_args parameter, so I'm not sure what else I should do.
Any help would be much appreciated.
Update:
The compile line generated by setup.py looks like this:
gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe -Isource -I/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/numpy/core/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/numpy/numarray -I/usr/lib/python/2.5/site-packages/numpy/numarray/numpy -I/usr/lib/python/2.5/site-packages/numpy/numarray -I/usr/lib/python/2.5/site-packages/numpy/core/include -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c source/Dirac_LE.cpp -o build/temp.macosx-10.5-i386-2.5/source/Dirac_LE.o
The linker line looks like this:
g++ -Wl,-F. -bundle -undefined dynamic_lookup -arch i386 -arch ppc build/temp.macosx-10.5-i386-2.5/diracmodule.o build/temp.macosx-10.5-i386-2.5/source/Dirac_LE.o -Llibs/MacOSX -lDiracLE -o build/lib.macosx-10.5-i386-2.5/dirac.so -framework Carbon
otool reports:
dirac.so:
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.4.0)
/usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 111.1.5)
Update 2:
On MacOS 10.5, modifying the dlopen flags from the default of RTLD_NOW to RTLD_LAZY solves the problem. However, this does not work on Mac OS 10.6.
On 10.6, the following sequence allows the library to run properly, although I'm not sure why:
python setup.py build -v
run the linker line (printed to console by setup.py) again, manually.
python setup.py install
I'm still looking for a good answer as to how to get this to work properly. Thanks!
| [
"You're going to kick yourself when you see the answer to this! Try changing this:\nlink_args = ['-framework Carbon'] if platform == 'Darwin' else []\n\nto this:\nlink_args = ['-framework', 'Carbon'] if platform == 'Darwin' else []\n\nOnce I made this change I was able to do a clean build and import the module straight away :)\n"
] | [
4
] | [] | [] | [
"dlopen",
"linker",
"python",
"python_c_extension",
"setup.py"
] | stackoverflow_0002790186_dlopen_linker_python_python_c_extension_setup.py.txt |
Q:
httplib2 giving internal server error 500 with proxy
Following is the code and error it throws. It works fine without the proxy http = httplib2.Http() .
When I try the same http proxy in Firefox, it works fine.
Any pointers are highly appreciated!
Usage :
http = httplib2.Http(proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, '68.48.25.158', 25681))
main_url = 'http://www.mywebsite.com'
response, content = http.request(main_url, 'GET')
Error :
File "testproxy.py", line 17, in <module>
response, content = http.request(main_url, 'GET')
File "/home/kk/bin/pythonlib/httplib2/__init__.py", line 1129, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/home/kk/bin/pythonlib/httplib2/__init__.py", line 901, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/home/kk/bin/pythonlib/httplib2/__init__.py", line 862, in _conn_request
conn.request(method, request_uri, body, headers)
File "/usr/lib/python2.5/httplib.py", line 866, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.5/httplib.py", line 889, in _send_request
self.endheaders()
File "/usr/lib/python2.5/httplib.py", line 860, in endheaders
self._send_output()
File "/usr/lib/python2.5/httplib.py", line 732, in _send_output
self.send(msg)
File "/usr/lib/python2.5/httplib.py", line 699, in send
self.connect()
File "/home/kk/bin/pythonlib/httplib2/__init__.py", line 740, in connect
self.sock.connect(sa)
File "/home/kk/bin/pythonlib/socks.py", line 383, in connect
self.__negotiatehttp(destpair[0],destpair[1])
File "/home/kk/bin/pythonlib/socks.py", line 349, in __negotiatehttp
raise HTTPError((statuscode,statusline[2]))
socks.HTTPError: (500, 'Internal Server Error')
A:
Make sure the proxy isn't transparent. I don't know too much about this, but evidently a transparent proxy enables the server to see you're using a proxy, and perhaps even access your IP. Some websites will definitely shut down any requests that appear to originate from a proxy (for fear of bots). That may mean either throwing a fake internal server error or actually encountering an error. For me, using an anonymous proxy has always solved that problem. Since you said it works without the proxy, I would start there.
A:
Is the SOCKS client library installed and available to your code? The proxy support only works if the SOCKS library is installed.
| httplib2 giving internal server error 500 with proxy | Following is the code and error it throws. It works fine without the proxy http = httplib2.Http() .
When I try the same http proxy in Firefox, it works fine.
Any pointers are highly appreciated!
Usage :
http = httplib2.Http(proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, '68.48.25.158', 25681))
main_url = 'http://www.mywebsite.com'
response, content = http.request(main_url, 'GET')
Error :
File "testproxy.py", line 17, in <module>
response, content = http.request(main_url, 'GET')
File "/home/kk/bin/pythonlib/httplib2/__init__.py", line 1129, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/home/kk/bin/pythonlib/httplib2/__init__.py", line 901, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/home/kk/bin/pythonlib/httplib2/__init__.py", line 862, in _conn_request
conn.request(method, request_uri, body, headers)
File "/usr/lib/python2.5/httplib.py", line 866, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.5/httplib.py", line 889, in _send_request
self.endheaders()
File "/usr/lib/python2.5/httplib.py", line 860, in endheaders
self._send_output()
File "/usr/lib/python2.5/httplib.py", line 732, in _send_output
self.send(msg)
File "/usr/lib/python2.5/httplib.py", line 699, in send
self.connect()
File "/home/kk/bin/pythonlib/httplib2/__init__.py", line 740, in connect
self.sock.connect(sa)
File "/home/kk/bin/pythonlib/socks.py", line 383, in connect
self.__negotiatehttp(destpair[0],destpair[1])
File "/home/kk/bin/pythonlib/socks.py", line 349, in __negotiatehttp
raise HTTPError((statuscode,statusline[2]))
socks.HTTPError: (500, 'Internal Server Error')
| [
"Make sure the proxy isn't transparent. I don't know too much about this, but evidently a transparent proxy enables the server to see you're using a proxy, and perhaps even access your IP. Some websites will definitely shut down any requests that appear to originate from a proxy (for fear of bots). That may mean either throwing a fake internal server error or actually encountering an error. For me, using an anonymous proxy has always solved that problem. Since you said it works without the proxy, I would start there. \n",
"Is the SOCKS client library installed and available to your code? The proxy support only works if the SOCKS library is installed.\n"
] | [
1,
0
] | [] | [] | [
"httplib2",
"proxy",
"python",
"socks"
] | stackoverflow_0002905505_httplib2_proxy_python_socks.txt |
Q:
Perfom python unit tests via a web interface
Is it possible to perform unittest tests via a web interface...and if so how?
EDIT:
For now I want the results...for the tests I want them to be automated...possibly every time I make a change to the code. Sorry I forgot to make this more clear
A:
EDIT:
This answer is outdated at this point:
Use Jenkins instead of Hudson (same thing, new name).
Use django-jenkins instead of xmlrunner.py.
The link to django-jenkins goes to a nice tutorial on how to use Jenkins with Django. I'll leave the text below since it still has some nice information.
As Bryan said, I'd use Hudson to schedule, run, and collect the test results. You can modify your tests to use xmlrunner.py (written by Sebastian Rittau), which will output your test results into an JUnit compatible XML file for Hudson.
Here's an example of how the test code would use xmlrunner:
import unittest
import xmlrunner
class TheTest(unittest.TestCase):
def testOne(self):
self.assertEquals(1, 1)
def testTwo(self):
self.assertEquals(2, 2)
def testThree(self):
self.assertEquals(3, 4)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TheTest)
xmlrunner.XMLTestRunner().run(suite)
Once you install Hudson, you'll create a new project for the source repository you're testing. You'll need to RTFM, but in a nutshell:
Under Source Code Management, you'll enter your repositories information and make it poll the repo periodically (I usually just do * * * * * so it checks every minute)
Add a command that actually runs the test script (like python test.py).
Check the Publish JUnit test result report. If it has an error like 'TEST-*.xml' doesn't match anything you can safely ignore it. It'll look something like this:
(source: snowpeaksoftware.com)
Once that's all done you'll be able to see test results for every time Hudson runs after check-in. It'll look something like this:
(source: snowpeaksoftware.com)
You also get more detailed pages like this page:
(source: snowpeaksoftware.com)
and this page:
(source: snowpeaksoftware.com)
A:
You can use Hudson to schedule the tests to run whenever you check in code. Since Hudson is a web app, you can then see the results via the web (and/or publish them and/or email them to you or your team).
| Perfom python unit tests via a web interface | Is it possible to perform unittest tests via a web interface...and if so how?
EDIT:
For now I want the results...for the tests I want them to be automated...possibly every time I make a change to the code. Sorry I forgot to make this more clear
| [
"EDIT:\nThis answer is outdated at this point:\n\nUse Jenkins instead of Hudson (same thing, new name).\nUse django-jenkins instead of xmlrunner.py.\n\nThe link to django-jenkins goes to a nice tutorial on how to use Jenkins with Django. I'll leave the text below since it still has some nice information.\n\nAs Bryan said, I'd use Hudson to schedule, run, and collect the test results. You can modify your tests to use xmlrunner.py (written by Sebastian Rittau), which will output your test results into an JUnit compatible XML file for Hudson.\nHere's an example of how the test code would use xmlrunner:\nimport unittest\nimport xmlrunner\n\nclass TheTest(unittest.TestCase):\n\n def testOne(self):\n self.assertEquals(1, 1)\n def testTwo(self):\n self.assertEquals(2, 2)\n def testThree(self):\n self.assertEquals(3, 4)\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TheTest)\n xmlrunner.XMLTestRunner().run(suite)\n\nOnce you install Hudson, you'll create a new project for the source repository you're testing. You'll need to RTFM, but in a nutshell:\n\nUnder Source Code Management, you'll enter your repositories information and make it poll the repo periodically (I usually just do * * * * * so it checks every minute)\nAdd a command that actually runs the test script (like python test.py).\nCheck the Publish JUnit test result report. If it has an error like 'TEST-*.xml' doesn't match anything you can safely ignore it. It'll look something like this:\n\n(source: snowpeaksoftware.com) \n\nOnce that's all done you'll be able to see test results for every time Hudson runs after check-in. It'll look something like this:\n\n(source: snowpeaksoftware.com) \nYou also get more detailed pages like this page:\n\n(source: snowpeaksoftware.com) \nand this page:\n\n(source: snowpeaksoftware.com) \n",
"You can use Hudson to schedule the tests to run whenever you check in code. Since Hudson is a web app, you can then see the results via the web (and/or publish them and/or email them to you or your team).\n"
] | [
8,
4
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0002904997_python_unit_testing.txt |
Q:
How do I convert a base 10 float to hex in Python 2.4?
I trying to convert numbers from decimal to hex. How do I convert float values to hex or char in Python 2.4.3?
I would then like to be able to print it as ("\xa5\x (new hex number here)"). How do I do that?
A:
From python 2.6.5 docs in hex(x) definition:
To obtain a hexadecimal string representation for a float, use the float.hex() method.
A:
Judging from this comment:
would you mind please to give an
example of its use? I am trying to
convert this 0.554 to hex by using
float.hex(value)? and how can I write
it as (\x30\x30\x35\x35)? – jordan2010
1 hour ago
what you really want is a hexadecimal representation of the ASCII codes of those numerical characters rather than an actual float represented in hex.
"5" = 53(base 10) = 0x35 (base 16)
You can use ord() to get the ASCII code for each character like this:
>>> [ ord(char) for char in "0.554" ]
[48, 46, 53, 53, 52]
Do you want a human-readable representation? hex() will give you one but it is not in the same format that you asked for:
>>> [ hex(ord(char)) for char in "0.554" ]
['0x30', '0x2e', '0x35', '0x35', '0x34']
# 0 . 5 5 4
Instead you can use string substitution and appropriate formatters
res = "".join( [ "\\x%02X" % ord(char) for char in "0.554" ] )
>>> print res
\x30\x2E\x35\x35\x34
But if you want to serialize the data, look into using the struct module to pack the data into buffers.
edited to answer jordan2010's second comment
Here's a quick addition to pad the number with leading zeroes.
>>> padded_integer_str = "%04d" % 5
>>> print padded_integer_str
0005
>>> res = "".join( [ "\\x%02X" % ord(char) for char in padded_integer_str] )
>>> print res
\x30\x30\x30\x35
See http://docs.python.org/library/stdtypes.html#string-formatting for an explanation on string formatters
A:
You can't convert a float directly to hex. You need to convert to int first.
hex(int(value))
Note that int always rounds down, so you might want to do the rounding explicitly before converting to int:
hex(int(round(value)))
| How do I convert a base 10 float to hex in Python 2.4? | I trying to convert numbers from decimal to hex. How do I convert float values to hex or char in Python 2.4.3?
I would then like to be able to print it as ("\xa5\x (new hex number here)"). How do I do that?
| [
"From python 2.6.5 docs in hex(x) definition:\nTo obtain a hexadecimal string representation for a float, use the float.hex() method.\n",
"Judging from this comment:\n\nwould you mind please to give an\n example of its use? I am trying to\n convert this 0.554 to hex by using\n float.hex(value)? and how can I write\n it as (\\x30\\x30\\x35\\x35)? – jordan2010\n 1 hour ago\n\nwhat you really want is a hexadecimal representation of the ASCII codes of those numerical characters rather than an actual float represented in hex.\n\"5\" = 53(base 10) = 0x35 (base 16)\nYou can use ord() to get the ASCII code for each character like this:\n>>> [ ord(char) for char in \"0.554\" ]\n[48, 46, 53, 53, 52]\n\nDo you want a human-readable representation? hex() will give you one but it is not in the same format that you asked for:\n>>> [ hex(ord(char)) for char in \"0.554\" ]\n['0x30', '0x2e', '0x35', '0x35', '0x34']\n# 0 . 5 5 4\n\nInstead you can use string substitution and appropriate formatters\nres = \"\".join( [ \"\\\\x%02X\" % ord(char) for char in \"0.554\" ] )\n>>> print res\n\\x30\\x2E\\x35\\x35\\x34\n\nBut if you want to serialize the data, look into using the struct module to pack the data into buffers.\nedited to answer jordan2010's second comment\nHere's a quick addition to pad the number with leading zeroes.\n>>> padded_integer_str = \"%04d\" % 5\n>>> print padded_integer_str\n0005\n>>> res = \"\".join( [ \"\\\\x%02X\" % ord(char) for char in padded_integer_str] )\n>>> print res\n\\x30\\x30\\x30\\x35\n\nSee http://docs.python.org/library/stdtypes.html#string-formatting for an explanation on string formatters\n",
"You can't convert a float directly to hex. You need to convert to int first.\nhex(int(value))\n\nNote that int always rounds down, so you might want to do the rounding explicitly before converting to int:\nhex(int(round(value)))\n\n"
] | [
1,
1,
0
] | [] | [] | [
"decimal",
"floating_point",
"python",
"python_2.4"
] | stackoverflow_0002904189_decimal_floating_point_python_python_2.4.txt |
Q:
Can I use Blender to create 3D wall image viewer application under Linux?
Is that possible to use Blender to create Cooliris-like 3D wall image viewer application under Linux?
I don't see many people use Blender (BGE) to create desktop application, so I am wondering if this is possible. People normally use Blender for modeling/movie and game engine.
I can not find a good way to create 3D application in Linux so far.
I was thinking about pyQT+opengl. But I feel that is hard to do. No robust and easy-to-use qt+opengl toolkit available from my research. I know a little bit of Blender, that's why I am asking if Blender is an alternative solution. (python is preferred)
The image viewer doesn't have to be windowed. It can be full screen, like a game?. I would like to add many cool effects into this application. Hopefully cooler than Cooliris which is written in flash.
Thanks a lot.
A:
There's always Clutter. Looks like it has Python bindings.
| Can I use Blender to create 3D wall image viewer application under Linux? | Is that possible to use Blender to create Cooliris-like 3D wall image viewer application under Linux?
I don't see many people use Blender (BGE) to create desktop application, so I am wondering if this is possible. People normally use Blender for modeling/movie and game engine.
I can not find a good way to create 3D application in Linux so far.
I was thinking about pyQT+opengl. But I feel that is hard to do. No robust and easy-to-use qt+opengl toolkit available from my research. I know a little bit of Blender, that's why I am asking if Blender is an alternative solution. (python is preferred)
The image viewer doesn't have to be windowed. It can be full screen, like a game?. I would like to add many cool effects into this application. Hopefully cooler than Cooliris which is written in flash.
Thanks a lot.
| [
"There's always Clutter. Looks like it has Python bindings.\n"
] | [
1
] | [] | [] | [
"blender",
"opengl",
"python",
"user_interface"
] | stackoverflow_0002902933_blender_opengl_python_user_interface.txt |
Q:
What are the differences between Perl, Python, AWK and sed?
What are the main differences among them? And in which typical scenarios is it better to use each language?
A:
In order of appearance, the languages are sed, awk, perl, python.
The sed program is a stream editor and is designed to apply the actions from a script to each line (or, more generally, to specified ranges of lines) of the input file or files. Its language is based on ed, the Unix editor, and although it has conditionals and so on, it is hard to work with for complex tasks. You can work minor miracles with it - but at a cost to the hair on your head. However, it is probably the fastest of the programs when attempting tasks within its remit. (It has the least powerful regular expressions of the programs discussed - adequate for many purposes, but certainly not PCRE - Perl-Compatible Regular Expressions)
The awk program (name from the initials of its authors - Aho, Weinberger, and Kernighan) is a tool initially for formatting reports. It can be used as a souped-up sed; in its more recent versions, it is computationally complete. It uses an interesting idea - the program is based on 'patterns matched' and 'actions taken when the pattern matches'. The patterns are fairly powerful (Extended Regular Expressions). The language for the actions is similar to C. One of the key features of awk is that it splits the input automatically into records and each record into fields.
Perl was written in part as an awk-killer and sed-killer. Two of the programs provided with it are a2p and s2p for converting awk scripts and sed scripts into Perl. Perl is one of the earliest of the next generation of scripting languages (Tcl/Tk can probably claim primacy). It has powerful integrated regular expression handling with a vastly more powerful language. It provides access to almost all system calls and has the extensibility of the CPAN modules. (Neither awk nor sed is extensible.) One of Perl's mottos is "TMTOWTDI - There's more than one way to do it" (pronounced "tim-toady"). Perl has 'objects', but it is more of an add-on than a fundamental part of the language.
Python was written last, and probably in part as a reaction to Perl. It has some interesting syntactic ideas (indenting to indicate levels - no braces or equivalents). It is more fundamentally object-oriented than Perl; it is just as extensible as Perl.
OK - when to use each?
Sed - when you need to do simple text transforms on files.
Awk - when you only need simple formatting and summarisation or transformation of data.
Perl - for almost any task, but especially when the task needs complex regular expressions.
Python - for the same tasks that you could use Perl for.
I'm not aware of anything that Perl can do that Python can't, nor vice versa. The choice between the two would depend on other factors. I learned Perl before there was a Python, so I tend to use it. Python has less accreted syntax and is generally somewhat simpler to learn. Perl 6, when it becomes available, will be a fascinating development.
(Note that the 'overviews' of Perl and Python, in particular, are woefully incomplete; whole books could be written on the topic.)
A:
After mastering a few dozen languages, you get tired of people like S. Lott (see his controversial answer to this question, nearly half as many down-votes as up (+45/-22) six years after answering).
Sed is the best tool for extremely simple command-line pipelines. In the hands of a sed master, it's suitable for one-offs of arbitrary complexity, but it should not be used in production code except in very simple substitution pipelines. Stuff like 's/this/that/.'
Gawk (the GNU awk) is by far the best choice for complex data reformatting when there is only a single input source and a single output (or, multiple outputs sequentially written). Since a great deal of real-world work conforms to this description, and a good programmer can learn gawk in two hours, it is the best choice. On this planet, simpler and faster is better!
Perl or Python are far better than any version of awk or sed when you have very complex input/output scenarios. The more complex the problem is, the better off you are using python, from a maintenance and readability standpoint. Note, however, that a good programmer can write readable code in any language, and a bad programmer can write unmaintainable crap in any useful language, so the choice of perl or python can safely be left to the preferences of the programmer if said programmer is skilled and clever.
A:
I wouldn't call sed a fully-fledged programming language, it is a stream editor with language constructs aimed at editing text files programmatically.
Awk is a little more of a general purpose language but it is still best suited for text processing.
Perl and Python are fully fledged, general purpose programming languages. Perl has its roots in text processing and has a number of awk-like constructs (there is even an awk-to-perl script floating around on the net). There are many differences between Perl and Python, your best bet is probably to read the summaries of both languages on something like Wikipedia to get a good grasp on what they are.
A:
First, there are two unrelated things in the list "Perl, Python awk and sed".
Thing 1 - simplistic text manipulation tools.
sed. It has a fixed, relatively simple scope of work defined by the idea of reading and examining each line of a file. sed is not designed to be particularly readable. It is designed to be very small and very efficient on very tiny unix servers.
awk. It has a slightly less fixed, less simple scope of work. However, the main loop of an awk program is defined by the implicit reading of lines of a source file.
These are not "complete" programming languages. While you can -- with some work -- write fairly sophisticated programs in awk, it rapidly gets complicated and difficult to read.
Thing 2 - general-purposes programming languages. These have a rich variety of statement types, numerous built-in data structures, and no wired-in assumptions or shortcuts to speak of.
Perl.
Python.
When to use them.
sed. Never. It really doesn't have any value in the modern era of computers with more than 32K of memory. Perl or Python do the same things more clearly.
awk. Never. Like sed, it reflects an earlier era of computing. Rather than maintain this language (in addition to all the other required for a successful system), it's more pleasant to simply do everything in one pleasant language.
Perl. Any programming problem of any kind. If you like free-thinking syntax, where there are many, many ways to do the same thing, perl is fun.
Python. Any programming problem of any kind. If you like fairly limited syntax, where there are fewer choices, less subtlety, and (perhaps) more clarity. Python's object-oriented nature makes it more suitable for large, complex problems.
Background -- I'm not bashing sed and awk out of ignorance. I learned awk over 20 years ago. Did many things with it; used to teach it as a core unix skill. I learned Perl about 15 years ago. Did many sophisticated things with it. I've left both behind because I can do the same things in Python -- and it is simpler and more clear.
There are two serious problems with sed and awk, neither of which are their age.
The incompleteness of their implementation. Everything sed and awk do can be done in Python or Perl, often more simply and sometimes faster, too. A shell pipeline has some performance advantages because of its multi-processing. Python offers a subprocess module to allow me to recover those advantages.
The need to learn yet another language. By doing things in Python (or Perl) your implementation depends on fewer languages, with a resulting increase in clarity.
A:
When to use them: awk - never - S. Lott.
I think S. Lott slightly missed the mark with this recommendation. The fact is, on Linux and the other UNIX environments, awk is a useful tool to be used with bash, sh, and ksh for quick text processings. The idea of scripting itself is you solve your problem by gluing together this tool, that tool. Hence in admin scripts, it is common to has ls, grep, |, awk, time, ps, etc. Each is a tool that the scripter combines like a builder brick by brick to finish the building (to solve the problem at hand).
For instance I am a team member of the team managing paintball gear supplies dotcom. This e-commerce site is based on the LAMP stack. For automated processing and normalizing data feeds from various suppliers into the back end database, we employ and maintain a diversified mix of scripts, including bash, perl, php, and even expect. Each has its strengths based on the available modules and API. In the bash scripts we do quick patterns match and appropriate actions on the patterns as needed using awk without the need to switch to PERL. One thing I would also like to point out, which has not been emphasized in the thread, is that a fair number of these scripts were purchased, or gotten from the open source. If the script came as Perl, we maintain it as Perl; if the script came as Php, we maintain it as Php; if it came as bash, we maintain it as bash; we do not re-write it in another language just because we think it is less efficient in the original language.
| What are the differences between Perl, Python, AWK and sed? | What are the main differences among them? And in which typical scenarios is it better to use each language?
| [
"In order of appearance, the languages are sed, awk, perl, python.\nThe sed program is a stream editor and is designed to apply the actions from a script to each line (or, more generally, to specified ranges of lines) of the input file or files. Its language is based on ed, the Unix editor, and although it has conditionals and so on, it is hard to work with for complex tasks. You can work minor miracles with it - but at a cost to the hair on your head. However, it is probably the fastest of the programs when attempting tasks within its remit. (It has the least powerful regular expressions of the programs discussed - adequate for many purposes, but certainly not PCRE - Perl-Compatible Regular Expressions)\nThe awk program (name from the initials of its authors - Aho, Weinberger, and Kernighan) is a tool initially for formatting reports. It can be used as a souped-up sed; in its more recent versions, it is computationally complete. It uses an interesting idea - the program is based on 'patterns matched' and 'actions taken when the pattern matches'. The patterns are fairly powerful (Extended Regular Expressions). The language for the actions is similar to C. One of the key features of awk is that it splits the input automatically into records and each record into fields.\nPerl was written in part as an awk-killer and sed-killer. Two of the programs provided with it are a2p and s2p for converting awk scripts and sed scripts into Perl. Perl is one of the earliest of the next generation of scripting languages (Tcl/Tk can probably claim primacy). It has powerful integrated regular expression handling with a vastly more powerful language. It provides access to almost all system calls and has the extensibility of the CPAN modules. (Neither awk nor sed is extensible.) One of Perl's mottos is \"TMTOWTDI - There's more than one way to do it\" (pronounced \"tim-toady\"). Perl has 'objects', but it is more of an add-on than a fundamental part of the language.\nPython was written last, and probably in part as a reaction to Perl. It has some interesting syntactic ideas (indenting to indicate levels - no braces or equivalents). It is more fundamentally object-oriented than Perl; it is just as extensible as Perl.\nOK - when to use each?\n\nSed - when you need to do simple text transforms on files.\nAwk - when you only need simple formatting and summarisation or transformation of data.\nPerl - for almost any task, but especially when the task needs complex regular expressions.\nPython - for the same tasks that you could use Perl for.\n\nI'm not aware of anything that Perl can do that Python can't, nor vice versa. The choice between the two would depend on other factors. I learned Perl before there was a Python, so I tend to use it. Python has less accreted syntax and is generally somewhat simpler to learn. Perl 6, when it becomes available, will be a fascinating development.\n(Note that the 'overviews' of Perl and Python, in particular, are woefully incomplete; whole books could be written on the topic.)\n",
"After mastering a few dozen languages, you get tired of people like S. Lott (see his controversial answer to this question, nearly half as many down-votes as up (+45/-22) six years after answering).\nSed is the best tool for extremely simple command-line pipelines. In the hands of a sed master, it's suitable for one-offs of arbitrary complexity, but it should not be used in production code except in very simple substitution pipelines. Stuff like 's/this/that/.'\nGawk (the GNU awk) is by far the best choice for complex data reformatting when there is only a single input source and a single output (or, multiple outputs sequentially written). Since a great deal of real-world work conforms to this description, and a good programmer can learn gawk in two hours, it is the best choice. On this planet, simpler and faster is better!\nPerl or Python are far better than any version of awk or sed when you have very complex input/output scenarios. The more complex the problem is, the better off you are using python, from a maintenance and readability standpoint. Note, however, that a good programmer can write readable code in any language, and a bad programmer can write unmaintainable crap in any useful language, so the choice of perl or python can safely be left to the preferences of the programmer if said programmer is skilled and clever.\n",
"I wouldn't call sed a fully-fledged programming language, it is a stream editor with language constructs aimed at editing text files programmatically.\nAwk is a little more of a general purpose language but it is still best suited for text processing.\nPerl and Python are fully fledged, general purpose programming languages. Perl has its roots in text processing and has a number of awk-like constructs (there is even an awk-to-perl script floating around on the net). There are many differences between Perl and Python, your best bet is probably to read the summaries of both languages on something like Wikipedia to get a good grasp on what they are.\n",
"First, there are two unrelated things in the list \"Perl, Python awk and sed\".\nThing 1 - simplistic text manipulation tools.\n\nsed. It has a fixed, relatively simple scope of work defined by the idea of reading and examining each line of a file. sed is not designed to be particularly readable. It is designed to be very small and very efficient on very tiny unix servers.\nawk. It has a slightly less fixed, less simple scope of work. However, the main loop of an awk program is defined by the implicit reading of lines of a source file. \n\nThese are not \"complete\" programming languages. While you can -- with some work -- write fairly sophisticated programs in awk, it rapidly gets complicated and difficult to read.\nThing 2 - general-purposes programming languages. These have a rich variety of statement types, numerous built-in data structures, and no wired-in assumptions or shortcuts to speak of.\n\nPerl.\nPython. \n\nWhen to use them.\n\nsed. Never. It really doesn't have any value in the modern era of computers with more than 32K of memory. Perl or Python do the same things more clearly.\nawk. Never. Like sed, it reflects an earlier era of computing. Rather than maintain this language (in addition to all the other required for a successful system), it's more pleasant to simply do everything in one pleasant language.\nPerl. Any programming problem of any kind. If you like free-thinking syntax, where there are many, many ways to do the same thing, perl is fun.\nPython. Any programming problem of any kind. If you like fairly limited syntax, where there are fewer choices, less subtlety, and (perhaps) more clarity. Python's object-oriented nature makes it more suitable for large, complex problems.\n\nBackground -- I'm not bashing sed and awk out of ignorance. I learned awk over 20 years ago. Did many things with it; used to teach it as a core unix skill. I learned Perl about 15 years ago. Did many sophisticated things with it. I've left both behind because I can do the same things in Python -- and it is simpler and more clear.\nThere are two serious problems with sed and awk, neither of which are their age.\n\nThe incompleteness of their implementation. Everything sed and awk do can be done in Python or Perl, often more simply and sometimes faster, too. A shell pipeline has some performance advantages because of its multi-processing. Python offers a subprocess module to allow me to recover those advantages.\nThe need to learn yet another language. By doing things in Python (or Perl) your implementation depends on fewer languages, with a resulting increase in clarity.\n\n",
"When to use them: awk - never - S. Lott.\nI think S. Lott slightly missed the mark with this recommendation. The fact is, on Linux and the other UNIX environments, awk is a useful tool to be used with bash, sh, and ksh for quick text processings. The idea of scripting itself is you solve your problem by gluing together this tool, that tool. Hence in admin scripts, it is common to has ls, grep, |, awk, time, ps, etc. Each is a tool that the scripter combines like a builder brick by brick to finish the building (to solve the problem at hand). \nFor instance I am a team member of the team managing paintball gear supplies dotcom. This e-commerce site is based on the LAMP stack. For automated processing and normalizing data feeds from various suppliers into the back end database, we employ and maintain a diversified mix of scripts, including bash, perl, php, and even expect. Each has its strengths based on the available modules and API. In the bash scripts we do quick patterns match and appropriate actions on the patterns as needed using awk without the need to switch to PERL. One thing I would also like to point out, which has not been emphasized in the thread, is that a fair number of these scripts were purchased, or gotten from the open source. If the script came as Perl, we maintain it as Perl; if the script came as Php, we maintain it as Php; if it came as bash, we maintain it as bash; we do not re-write it in another language just because we think it is less efficient in the original language.\n"
] | [
594,
102,
22,
18,
16
] | [] | [] | [
"awk",
"language_comparisons",
"perl",
"python",
"sed"
] | stackoverflow_0000366980_awk_language_comparisons_perl_python_sed.txt |
Q:
The confusion on python encoding
I retrieved the data encoded in big5 from database,and I want to send the data as email of html content, the code is like this:
html += """<tr><td>"""
html += unicode(rs[0], 'big5') # rs[0] is data encoded in big5
I run the script, but the error raised: UnicodeDecodeError: 'ascii' codec can't decode byte...... However, I tried the code in interactive python command line, there are no errors raised, could you give me the clue?
A:
If html is not already a unicode object but a normal string, it is converted to unicode when it is concatenated with the converted version of rs[0]. If html now contains special characters you can get a unicode error.
So the other contents of html also need to be correctly decoded to unicode. If the special characters come from string literals, you could use unicode literals (like u"abcä") instead.
A:
Your call to unicode() is working correctly. It is the concatenation, which is adding a unicode object to a byte string, that is causing trouble. If you change the first line to u'''<tr><td>''', (or u'<tr><td>') it should work fine.
Edit: This means your error lies in the data that is already in html by the time python reaches this snippet:
>>> '\x9f<tr><td>' + unicode('\xc3\x60', 'big5')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 0: ordinal not in range(128)
>>> u'\x9f<tr><td>' + unicode('\xc3\x60', 'big5')
u'\x9f<tr><td>\u56a5'
>>>
| The confusion on python encoding | I retrieved the data encoded in big5 from database,and I want to send the data as email of html content, the code is like this:
html += """<tr><td>"""
html += unicode(rs[0], 'big5') # rs[0] is data encoded in big5
I run the script, but the error raised: UnicodeDecodeError: 'ascii' codec can't decode byte...... However, I tried the code in interactive python command line, there are no errors raised, could you give me the clue?
| [
"If html is not already a unicode object but a normal string, it is converted to unicode when it is concatenated with the converted version of rs[0]. If html now contains special characters you can get a unicode error.\nSo the other contents of html also need to be correctly decoded to unicode. If the special characters come from string literals, you could use unicode literals (like u\"abcä\") instead.\n",
"Your call to unicode() is working correctly. It is the concatenation, which is adding a unicode object to a byte string, that is causing trouble. If you change the first line to u'''<tr><td>''', (or u'<tr><td>') it should work fine.\nEdit: This means your error lies in the data that is already in html by the time python reaches this snippet: \n>>> '\\x9f<tr><td>' + unicode('\\xc3\\x60', 'big5')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nUnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 0: ordinal not in range(128)\n>>> u'\\x9f<tr><td>' + unicode('\\xc3\\x60', 'big5')\nu'\\x9f<tr><td>\\u56a5'\n>>> \n\n"
] | [
2,
1
] | [] | [] | [
"ascii",
"encoding",
"python",
"unicode"
] | stackoverflow_0002904037_ascii_encoding_python_unicode.txt |
Q:
AppEngine dev_appserver.py not showing any outputs
I installed Python2.6 and Google App Engine (GAE).
I realized that GAE does not run on 2.6, so I installed 2.5 as well.
Now I have a very basic code as follows and it does not show on the localhost:8080
I typed the following in cmd.exe under my dir testapps.
c:\Users\myname\testapps>"\Program Files\Google\google_appengine\dev_appserver.py" helloworld
I am hoping someone lead me to the right direction.
helloworld/helloworld.py
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'
helloworld/app.yaml
application: helloworld
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: helloworld.py
| AppEngine dev_appserver.py not showing any outputs | I installed Python2.6 and Google App Engine (GAE).
I realized that GAE does not run on 2.6, so I installed 2.5 as well.
Now I have a very basic code as follows and it does not show on the localhost:8080
I typed the following in cmd.exe under my dir testapps.
c:\Users\myname\testapps>"\Program Files\Google\google_appengine\dev_appserver.py" helloworld
I am hoping someone lead me to the right direction.
helloworld/helloworld.py
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'
helloworld/app.yaml
application: helloworld
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: helloworld.py
| [] | [] | [
"I would suggest that you take a look at the guestbook sample program that is included with the SDK. It is located in the demos directory, and I think that looking at the structure of guestbook.py will go a long way towards helping you get a working app.\n"
] | [
-1
] | [
"google_app_engine",
"python"
] | stackoverflow_0002903300_google_app_engine_python.txt |
Q:
Adding anchors to h2 in text using python and regexp
I'm trying to add anchors to all h2's in my html, using python. This code will add those anchors, but I need to fill the name of the anchors too.
Any idea if the name can be the number of the match in the loop or a slugified version of the text between the h2 tags?
Here's the code so far:
regex = '(?P<name><h2>.*?</h2>)'
text = re.sub(regex, "<a name=''/>"+r"\g<name>", text)
A:
You can take advantage of the fact that the second argument to re.sub can be a function to do pretty much anything you'd like. Here's an example that will slugify the text inside the <h2> element:
regex = '(?P<name><h2>(.*?)</h2>)' # Note the extra group inside the <h2>
def slugify(s):
return s.replace(' ', '-') # bare-bones slugify
def anchorize(matchobj):
return '<a name="%s"/>%s' % (slugify(matchob.group(2)), matchobj.group(1))
text = re.sub(regex, anchorize, text)
(That slugify function could obviously use some work.)
You could also implement a counter with a version of anchorize that used a global counter or, better yet, a class that kept track of its own counter and implemented the special __call__ method.
A:
Not sure if I understand correctly, but is placing the author as the name attribute sufficient?
Maybe you could use (as long as the author name doesn't contain invalid chars for an attribute):
regex = '(?P<name><h2>(.*?)</h2>)'
print re.sub(regex, "<a name='\g<2>'/>"+r"\g<name>", text)
If you need a more advanced substitution method, parsing the author name or looking up some sort of related id, you could define a replacement function (see re substitute doc):
def name_substitution(matchobj):
name = matchobj.group(2)
# do some processing on name here ...
name = name.replace(' ', '_')
return "<a name='%s'>%s</a>" % (name, matchobj.group(0))
print re.sub(regex, substitution, text)
| Adding anchors to h2 in text using python and regexp | I'm trying to add anchors to all h2's in my html, using python. This code will add those anchors, but I need to fill the name of the anchors too.
Any idea if the name can be the number of the match in the loop or a slugified version of the text between the h2 tags?
Here's the code so far:
regex = '(?P<name><h2>.*?</h2>)'
text = re.sub(regex, "<a name=''/>"+r"\g<name>", text)
| [
"You can take advantage of the fact that the second argument to re.sub can be a function to do pretty much anything you'd like. Here's an example that will slugify the text inside the <h2> element:\nregex = '(?P<name><h2>(.*?)</h2>)' # Note the extra group inside the <h2>\n\ndef slugify(s):\n return s.replace(' ', '-') # bare-bones slugify\n\ndef anchorize(matchobj):\n return '<a name=\"%s\"/>%s' % (slugify(matchob.group(2)), matchobj.group(1))\n\ntext = re.sub(regex, anchorize, text)\n\n(That slugify function could obviously use some work.)\nYou could also implement a counter with a version of anchorize that used a global counter or, better yet, a class that kept track of its own counter and implemented the special __call__ method.\n",
"Not sure if I understand correctly, but is placing the author as the name attribute sufficient?\nMaybe you could use (as long as the author name doesn't contain invalid chars for an attribute):\nregex = '(?P<name><h2>(.*?)</h2>)'\nprint re.sub(regex, \"<a name='\\g<2>'/>\"+r\"\\g<name>\", text)\n\nIf you need a more advanced substitution method, parsing the author name or looking up some sort of related id, you could define a replacement function (see re substitute doc):\ndef name_substitution(matchobj):\n name = matchobj.group(2)\n # do some processing on name here ...\n name = name.replace(' ', '_')\n return \"<a name='%s'>%s</a>\" % (name, matchobj.group(0))\n\nprint re.sub(regex, substitution, text)\n\n"
] | [
1,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0002905993_html_python.txt |
Q:
SVN hook script conflict
I am trying to write a pre-commit hook script that will alter a specific svn-property of a folder/file.
The script looks fairly similar to the one that is documented in the svn book.
I figured out how to set/change the property of a node and when executing the binding function svn.fs.commit_txn the property of the node actually gets set.
But at the moment tortoise always gives me a conflict on the folder I am altering the property. I wrote my script with Python but am new python and hook scripts.
Hope someone can give me a clue why I am getting this conflict..
A:
After updating a property on a directory you are required to update that directory before committing.
A:
You should never change data in a hook script. You lose the synchronization of the client and the subversion repository.
| SVN hook script conflict | I am trying to write a pre-commit hook script that will alter a specific svn-property of a folder/file.
The script looks fairly similar to the one that is documented in the svn book.
I figured out how to set/change the property of a node and when executing the binding function svn.fs.commit_txn the property of the node actually gets set.
But at the moment tortoise always gives me a conflict on the folder I am altering the property. I wrote my script with Python but am new python and hook scripts.
Hope someone can give me a clue why I am getting this conflict..
| [
"After updating a property on a directory you are required to update that directory before committing.\n",
"You should never change data in a hook script. You lose the synchronization of the client and the subversion repository.\n"
] | [
1,
0
] | [] | [] | [
"conflict",
"pre_commit_hook",
"python",
"svn",
"svn_hooks"
] | stackoverflow_0002905573_conflict_pre_commit_hook_python_svn_svn_hooks.txt |
Q:
What is the difference between "a is b" and "id(a) == id(b)" in Python?
The id() inbuilt function gives...
an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.
The is operator, instead, gives...
object identity
So why is it possible to have two objects that have the same id but return False to an is check? Here is an example:
>>> class Test():
... def test():
... pass
>>> a = Test()
>>> b = Test()
>>> id(a.test) == id(b.test)
True
>>> a.test is b.test
False
A more troubling example: (continuing the above)
>>> b = a
>>> b is a
True
>>> b.test is a.test
False
>>> a.test is a.test
False
However:
>>> new_improved_test_method = lambda: None
>>> a.test = new_improved_test_method
>>> a.test is a.test
True
A:
>>> b.test is a.test
False
>>> a.test is a.test
False
Methods are created on-the-fly each time you look them up. The function object (which is always the same object) implements the descriptor protocol and its __get__ creates the bound method object. No two bound methods would normally be the same object.
>>> id(a.test) == id(b.test)
True
>>> a.test is b.test
False
This example is deceptive. The result of the first is only True by coincidence. a.test creates a bound method and it's garbage collected after computing id(a.test) because there aren't any references to it. (Note that you quote the documentation saying that an id is "unique and constant for this object during its lifetime" (emphasis mine).) b.test happens to have the same id as the bound method you had before and it's allowed to because no other objects have the same id now.
Note that you should seldom use is and even less often use id. id(foo) == id(bar) is always wrong.
Regarding your new example, hopefully you get what it does now:
>>> new_improved_test_method = lambda: None
>>> a.test = new_improved_test_method
>>> a.test is a.test
True
In this case, we aren't making methods on the fly from functions on the class automatically binding self and returning bound method objects. In this case, you simply store a function as an instance attribute. Nothing special happens on lookup (descriptors only get called when you look up a class attribute), so every time you look up the attribute, you get the original object you stored.
| What is the difference between "a is b" and "id(a) == id(b)" in Python? | The id() inbuilt function gives...
an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.
The is operator, instead, gives...
object identity
So why is it possible to have two objects that have the same id but return False to an is check? Here is an example:
>>> class Test():
... def test():
... pass
>>> a = Test()
>>> b = Test()
>>> id(a.test) == id(b.test)
True
>>> a.test is b.test
False
A more troubling example: (continuing the above)
>>> b = a
>>> b is a
True
>>> b.test is a.test
False
>>> a.test is a.test
False
However:
>>> new_improved_test_method = lambda: None
>>> a.test = new_improved_test_method
>>> a.test is a.test
True
| [
">>> b.test is a.test\nFalse\n>>> a.test is a.test\nFalse\n\nMethods are created on-the-fly each time you look them up. The function object (which is always the same object) implements the descriptor protocol and its __get__ creates the bound method object. No two bound methods would normally be the same object.\n>>> id(a.test) == id(b.test)\nTrue\n>>> a.test is b.test\nFalse\n\nThis example is deceptive. The result of the first is only True by coincidence. a.test creates a bound method and it's garbage collected after computing id(a.test) because there aren't any references to it. (Note that you quote the documentation saying that an id is \"unique and constant for this object during its lifetime\" (emphasis mine).) b.test happens to have the same id as the bound method you had before and it's allowed to because no other objects have the same id now.\nNote that you should seldom use is and even less often use id. id(foo) == id(bar) is always wrong.\n\nRegarding your new example, hopefully you get what it does now:\n>>> new_improved_test_method = lambda: None\n>>> a.test = new_improved_test_method\n>>> a.test is a.test\nTrue\n\nIn this case, we aren't making methods on the fly from functions on the class automatically binding self and returning bound method objects. In this case, you simply store a function as an instance attribute. Nothing special happens on lookup (descriptors only get called when you look up a class attribute), so every time you look up the attribute, you get the original object you stored.\n"
] | [
64
] | [] | [] | [
"identity",
"python"
] | stackoverflow_0002906177_identity_python.txt |
Q:
Capturing Mac OS X System Audio output with Python
I've been trying to "hijack" the Mac OS X system audio using PyAudio and save to a wav in python. That is, I do not want to record from an input device such as a microphone. I want to grab the sound output from any or all applications.
I have followed the tutorials on the PyAudio site but these do not appear to cover my use case and when I try to read from the output stream I unsurprisingly get the paCanNotReadFromAnOutputOnlyStream exception. Fair enough! Is there a way to do what I am proposing with the PyAudio or other FOSS Python Library?
A:
I found that an open-source project called SoundFlower got me quickly to the place I needed to be.
I installed the SoundFlower package from Google Code.
Opened System Preferences -> Sound
Chose Soundflower as my Output device
Chose Soundflower as my Input device
I was then able to record system audio from the default device using PyAudio. No sound comes from the speakers/headphones in this situation though. I wonder if you could use Jack OS X to route audio out of SoundFlower to the system audio out.
| Capturing Mac OS X System Audio output with Python | I've been trying to "hijack" the Mac OS X system audio using PyAudio and save to a wav in python. That is, I do not want to record from an input device such as a microphone. I want to grab the sound output from any or all applications.
I have followed the tutorials on the PyAudio site but these do not appear to cover my use case and when I try to read from the output stream I unsurprisingly get the paCanNotReadFromAnOutputOnlyStream exception. Fair enough! Is there a way to do what I am proposing with the PyAudio or other FOSS Python Library?
| [
"I found that an open-source project called SoundFlower got me quickly to the place I needed to be.\n\nI installed the SoundFlower package from Google Code.\nOpened System Preferences -> Sound\nChose Soundflower as my Output device\nChose Soundflower as my Input device\n\nI was then able to record system audio from the default device using PyAudio. No sound comes from the speakers/headphones in this situation though. I wonder if you could use Jack OS X to route audio out of SoundFlower to the system audio out. \n"
] | [
8
] | [] | [] | [
"audio",
"macos",
"python"
] | stackoverflow_0002883090_audio_macos_python.txt |
Q:
Emacs: pass arguments to inferior Python shell during buffer evaluation
recently I started using Emacs as a Python IDE, and it not quite intuitive... The problem I am struggling with right now is how to pass command line arguments to the inferior python shell when the buffer is evaluated with C-c C-c. Thanks for help.
A:
This doesn't appear to be easily possible; the inferior process managed by the python.el module is designed to persist across many invocations of python-send-buffer (and friends). One solution I've found is to write your own function that sets sys.argv programmatically from within the inferior process:
(defun python-send-buffer-with-my-args (args)
(interactive "sPython arguments: ")
(let ((source-buffer (current-buffer)))
(with-temp-buffer
(insert "import sys; sys.argv = '''" args "'''.split()\n")
(insert-buffer-substring source-buffer)
(python-send-buffer))))
Execute this function in your *scratch* buffer and/or save it in your .emacs file, then, if you want, bind it to a convenient key sequence. C-c C-a doesn't seem to be used by python-mode, so perhaps:
(global-set-key "\C-c\C-a" 'python-send-buffer-with-my-args)
The command will prompt you for arguments to use, then copy your source buffer into a temporary buffer, prepending it with a code snippet that sets sys.argv to the list of arguments you supplied, and finally will call python-send-buffer.
The above code will just naively split the string you type on whitespace, so if you need to supply arguments that have whitespace in them, you'll need a more sophisticated algorithm.
| Emacs: pass arguments to inferior Python shell during buffer evaluation | recently I started using Emacs as a Python IDE, and it not quite intuitive... The problem I am struggling with right now is how to pass command line arguments to the inferior python shell when the buffer is evaluated with C-c C-c. Thanks for help.
| [
"This doesn't appear to be easily possible; the inferior process managed by the python.el module is designed to persist across many invocations of python-send-buffer (and friends). One solution I've found is to write your own function that sets sys.argv programmatically from within the inferior process:\n(defun python-send-buffer-with-my-args (args)\n (interactive \"sPython arguments: \")\n (let ((source-buffer (current-buffer)))\n (with-temp-buffer\n (insert \"import sys; sys.argv = '''\" args \"'''.split()\\n\")\n (insert-buffer-substring source-buffer)\n (python-send-buffer))))\n\nExecute this function in your *scratch* buffer and/or save it in your .emacs file, then, if you want, bind it to a convenient key sequence. C-c C-a doesn't seem to be used by python-mode, so perhaps:\n(global-set-key \"\\C-c\\C-a\" 'python-send-buffer-with-my-args)\n\nThe command will prompt you for arguments to use, then copy your source buffer into a temporary buffer, prepending it with a code snippet that sets sys.argv to the list of arguments you supplied, and finally will call python-send-buffer.\nThe above code will just naively split the string you type on whitespace, so if you need to supply arguments that have whitespace in them, you'll need a more sophisticated algorithm.\n"
] | [
7
] | [] | [] | [
"emacs",
"ide",
"python"
] | stackoverflow_0002905575_emacs_ide_python.txt |
Q:
Gmail mail server
I used use Google’s slick interface to get my mail and It’s always going to be here:
https://mail.google.com/a/yourdomainhere.com
I want to write python script that send mail so i failed to configure server settings
smtp = smtplib.SMTP('mail server should be what?', what is the port)
smtp.login('username@yourdomainhere.com', 'pass')
Please could any one help me ??
Thanks
A:
All on gmail's support site, see http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
A:
Look at the help:
http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
Its smtp.gmail.com
A:
The preferred method for SMTP message forwarding is using your ISP's SMTP server. The job of locating Google's Message transfer agent is handled by such servers.
To use Google's servers directly, you need to look up the MX records provided by google via DNS. From a Python program, a DNS library is needed. Here is an example, using dnspython, a A DNS toolkit for Python.
>>> from dns import resolver
>>> mxrecs = resolver.query('gmail.com', 'MX')
>>> [mx for mx in mxrecs]
[<DNS IN MX rdata: 20 alt2.gmail-smtp-in.l.google.com.>,
<DNS IN MX rdata: 40 alt4.gmail-smtp-in.l.google.com.>,
<DNS IN MX rdata: 30 alt3.gmail-smtp-in.l.google.com.>,
<DNS IN MX rdata: 10 alt1.gmail-smtp-in.l.google.com.>,
<DNS IN MX rdata: 5 gmail-smtp-in.l.google.com.>]
>>> mx.exchange.to_text()
'gmail-smtp-in.l.google.com.'
>>> mx.preference
5
>>>
The preferred mail-exchange server here is gmail-smtp-in.l.google.com, which can be used with smtplib to forward messages.
| Gmail mail server | I used use Google’s slick interface to get my mail and It’s always going to be here:
https://mail.google.com/a/yourdomainhere.com
I want to write python script that send mail so i failed to configure server settings
smtp = smtplib.SMTP('mail server should be what?', what is the port)
smtp.login('username@yourdomainhere.com', 'pass')
Please could any one help me ??
Thanks
| [
"All on gmail's support site, see http://mail.google.com/support/bin/answer.py?hl=en&answer=13287\n",
"Look at the help:\nhttp://mail.google.com/support/bin/answer.py?hl=en&answer=13287\nIts smtp.gmail.com\n",
"The preferred method for SMTP message forwarding is using your ISP's SMTP server. The job of locating Google's Message transfer agent is handled by such servers.\nTo use Google's servers directly, you need to look up the MX records provided by google via DNS. From a Python program, a DNS library is needed. Here is an example, using dnspython, a A DNS toolkit for Python.\n>>> from dns import resolver\n>>> mxrecs = resolver.query('gmail.com', 'MX')\n>>> [mx for mx in mxrecs]\n[<DNS IN MX rdata: 20 alt2.gmail-smtp-in.l.google.com.>, \n<DNS IN MX rdata: 40 alt4.gmail-smtp-in.l.google.com.>,\n<DNS IN MX rdata: 30 alt3.gmail-smtp-in.l.google.com.>,\n<DNS IN MX rdata: 10 alt1.gmail-smtp-in.l.google.com.>,\n<DNS IN MX rdata: 5 gmail-smtp-in.l.google.com.>]\n>>> mx.exchange.to_text()\n'gmail-smtp-in.l.google.com.'\n>>> mx.preference\n5\n>>> \n\nThe preferred mail-exchange server here is gmail-smtp-in.l.google.com, which can be used with smtplib to forward messages.\n"
] | [
6,
0,
0
] | [] | [] | [
"gmail",
"python"
] | stackoverflow_0002905987_gmail_python.txt |
Q:
[Python]Xml add a node from another xml document
I have two xml file:
1)model.xml
2)projectionParametersTemplate.xml
I want to extract from 1) Algorithm Node with his child and put it in 2)
I have wrote this code but it doesn't function.
from xml.dom.minidom import Document
from xml.dom import minidom
xmlmodel=minidom.parse("/home/michele/Scrivania/d/model.xml")
xmltemplate=minidom.parse("/home/michele/Scrivania/d/projectionParametersTemplate.xml")
for Node in xmlmodel.getElementsByTagName("Algorithm"):
print "\nNode: "+str(Node)
for Node2 in xmltemplate.getElementsByTagName("ProjectionParameters"):
print "\nNode2: "+str(Node2)
Node2.appendChild(Node)
This is model.xml link text
This is projectionParametersTemplate.xml link text
Thanks a lot.
A:
For me it works, e.g. the algorithm-node from xmlmodel is added to the ProjectionParameters-node from xmltemplate.
My guess is that you want to change the actual file. With your code, only the object in memory is modified, not the file on disk. If you want to change the file, add this line at the end:
xmltemplate.writexml(file("PATH_TO_OUTPUT_FILE.xml","w"))
P.S.: Maybe you get more answers when you improve your accept rate.
| [Python]Xml add a node from another xml document | I have two xml file:
1)model.xml
2)projectionParametersTemplate.xml
I want to extract from 1) Algorithm Node with his child and put it in 2)
I have wrote this code but it doesn't function.
from xml.dom.minidom import Document
from xml.dom import minidom
xmlmodel=minidom.parse("/home/michele/Scrivania/d/model.xml")
xmltemplate=minidom.parse("/home/michele/Scrivania/d/projectionParametersTemplate.xml")
for Node in xmlmodel.getElementsByTagName("Algorithm"):
print "\nNode: "+str(Node)
for Node2 in xmltemplate.getElementsByTagName("ProjectionParameters"):
print "\nNode2: "+str(Node2)
Node2.appendChild(Node)
This is model.xml link text
This is projectionParametersTemplate.xml link text
Thanks a lot.
| [
"For me it works, e.g. the algorithm-node from xmlmodel is added to the ProjectionParameters-node from xmltemplate.\nMy guess is that you want to change the actual file. With your code, only the object in memory is modified, not the file on disk. If you want to change the file, add this line at the end:\nxmltemplate.writexml(file(\"PATH_TO_OUTPUT_FILE.xml\",\"w\"))\n\nP.S.: Maybe you get more answers when you improve your accept rate. \n"
] | [
0
] | [] | [] | [
"add",
"python",
"xml"
] | stackoverflow_0002905659_add_python_xml.txt |
Q:
Correct way to do timer function in Python
I have a GUI application that needs to do something simple in the background (update a wx python progress bar, but that doesn't really matter). I see that there is a threading.timer class.. but there seems to be no way to make it repeat. So if I use the timer, I end up having to make a new thread on every single execution... like :
import threading
import time
def DoTheDew():
print "I did it"
t = threading.Timer(1, function=DoTheDew)
t.daemon = True
t.start()
if __name__ == '__main__':
t = threading.Timer(1, function=DoTheDew)
t.daemon = True
t.start()
time.sleep(10)
This seems like I am making a bunch of threads that do 1 silly thing and die.. why not write it as :
import threading
import time
def DoTheDew():
while True:
print "I did it"
time.sleep(1)
if __name__ == '__main__':
t = threading.Thread(target=DoTheDew)
t.daemon = True
t.start()
time.sleep(10)
Am I missing some way to make a timer keep doing something? Either of these options seems silly... I am looking for a timer more like a java.util.Timer that can schedule the thread to happen every second... If there isn't a way in Python, which of my above methods is better and why?
A:
A pattern more like this is probably what you should be doing, but it's hard to say because you didn't provide many details.
def do_background_work(self):
# do work on a background thread, posting updates to the
# GUI thread with CallAfter
while True:
# do stuff
wx.CallAfter(self.update_progress, percent_complete)
def update_progress(self, percent_complete):
# update the progress bar from the GUI thread
self.gauge.SetValue(percent_complete)
def on_start_button(self, event):
# start doing background work when the user hits a button
thread = threading.Thread(target=self.do_background_work)
thread.setDaemon(True)
thread.start()
A:
wxwindows has its own timer. It supports one shot, and reoccurring events.
| Correct way to do timer function in Python | I have a GUI application that needs to do something simple in the background (update a wx python progress bar, but that doesn't really matter). I see that there is a threading.timer class.. but there seems to be no way to make it repeat. So if I use the timer, I end up having to make a new thread on every single execution... like :
import threading
import time
def DoTheDew():
print "I did it"
t = threading.Timer(1, function=DoTheDew)
t.daemon = True
t.start()
if __name__ == '__main__':
t = threading.Timer(1, function=DoTheDew)
t.daemon = True
t.start()
time.sleep(10)
This seems like I am making a bunch of threads that do 1 silly thing and die.. why not write it as :
import threading
import time
def DoTheDew():
while True:
print "I did it"
time.sleep(1)
if __name__ == '__main__':
t = threading.Thread(target=DoTheDew)
t.daemon = True
t.start()
time.sleep(10)
Am I missing some way to make a timer keep doing something? Either of these options seems silly... I am looking for a timer more like a java.util.Timer that can schedule the thread to happen every second... If there isn't a way in Python, which of my above methods is better and why?
| [
"A pattern more like this is probably what you should be doing, but it's hard to say because you didn't provide many details.\ndef do_background_work(self):\n # do work on a background thread, posting updates to the\n # GUI thread with CallAfter\n while True:\n # do stuff\n wx.CallAfter(self.update_progress, percent_complete)\n\ndef update_progress(self, percent_complete):\n # update the progress bar from the GUI thread\n self.gauge.SetValue(percent_complete)\n\ndef on_start_button(self, event):\n # start doing background work when the user hits a button\n thread = threading.Thread(target=self.do_background_work)\n thread.setDaemon(True)\n thread.start()\n\n",
"wxwindows has its own timer. It supports one shot, and reoccurring events.\n"
] | [
3,
2
] | [] | [] | [
"multithreading",
"python",
"timer"
] | stackoverflow_0002906510_multithreading_python_timer.txt |
Q:
Why is Django testrunner not finding the tests I created?
I had been trying to add tests to a project I'm working on.
The tests are in forum/tests/
When I run manage.py test it doesn't find any of the tests I created, on the tests in Django 1.2
I started with all my tests in their own package but have simplified down to just being in my tests.py file. The current tests.py looks like:
from django.test.client import Client
from django.test import TestCase
from utils import *
from forum.models import *
from forum import auth
class ForumTestCase(TestCase):
def test_root_page(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_signin_page(self):
response = self.client.get("/account/signin/")
self.assertEqual(response.status_code, 200)
I'm sure I am missing something very basic and obvious but I just can't work out what. Any ideas?
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.humanize',
'forum',
'django_authopenid',
)
Why would Django testrunner not be finding the tests I created?
The tests are at forum/tests/:
__init__.py
forum/tests/test_views.py
forum/tests/test_models.py
I also have a __init__.py file in the directory.
A:
As noted in the comment, Django 1.6 introduced backwards-incompatibility with discovery of tests in any test module.
Before Django 1.6, one would have to do the following:
Create file named __init__.py in
forum/tests/__init__.py
And import all test from other moduls inside it.
from test_views import SomeTestCase
from test_models import SomeOtherTestCase
| Why is Django testrunner not finding the tests I created? | I had been trying to add tests to a project I'm working on.
The tests are in forum/tests/
When I run manage.py test it doesn't find any of the tests I created, on the tests in Django 1.2
I started with all my tests in their own package but have simplified down to just being in my tests.py file. The current tests.py looks like:
from django.test.client import Client
from django.test import TestCase
from utils import *
from forum.models import *
from forum import auth
class ForumTestCase(TestCase):
def test_root_page(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_signin_page(self):
response = self.client.get("/account/signin/")
self.assertEqual(response.status_code, 200)
I'm sure I am missing something very basic and obvious but I just can't work out what. Any ideas?
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.humanize',
'forum',
'django_authopenid',
)
Why would Django testrunner not be finding the tests I created?
The tests are at forum/tests/:
__init__.py
forum/tests/test_views.py
forum/tests/test_models.py
I also have a __init__.py file in the directory.
| [
"As noted in the comment, Django 1.6 introduced backwards-incompatibility with discovery of tests in any test module.\nBefore Django 1.6, one would have to do the following:\nCreate file named __init__.py in\nforum/tests/__init__.py\n\nAnd import all test from other moduls inside it.\nfrom test_views import SomeTestCase\nfrom test_models import SomeOtherTestCase\n\n"
] | [
7
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002906285_django_python.txt |
Q:
way to fix number of concurrent sessions allowed at app level. django
How can I fix number of concurrent sessions allowed at app level?
Basically I want a limit to how many concurrent requests to this url to keep the server from getting congested.
I guess some middleware hack?
Thanks.
A:
Don't do this in django, but in Apache / nginx / whatever webserver you have in front of Django. They have specific modules exactly for such tasks.
A possible solution for Apache would be: mod_limitipconn2 - http://dominia.org/djao/limitipconn2.html
A:
Django stores session information in the database by default. You could use a middleware, which checks the number of rows (coarsly speaking) in that table. Keep in mind that django won't purge expired sessions from the DB automatically.
On clearing the session table:
http://docs.djangoproject.com/en/dev/topics/http/sessions/#clearing-the-session-table
A:
You're not asking about sessions, you're asking about requests. What you want is known as throttling. However, it would be quite difficult to do it inside the app, because Apache manages multiple processes and threads, so you'd need some external process to keep track of these in order to enable the throttling.
Basically, this sort of thing is best done within Apache itself, by something like mod_throttle.
| way to fix number of concurrent sessions allowed at app level. django | How can I fix number of concurrent sessions allowed at app level?
Basically I want a limit to how many concurrent requests to this url to keep the server from getting congested.
I guess some middleware hack?
Thanks.
| [
"Don't do this in django, but in Apache / nginx / whatever webserver you have in front of Django. They have specific modules exactly for such tasks.\nA possible solution for Apache would be: mod_limitipconn2 - http://dominia.org/djao/limitipconn2.html\n",
"Django stores session information in the database by default. You could use a middleware, which checks the number of rows (coarsly speaking) in that table. Keep in mind that django won't purge expired sessions from the DB automatically.\nOn clearing the session table:\n\nhttp://docs.djangoproject.com/en/dev/topics/http/sessions/#clearing-the-session-table\n\n",
"You're not asking about sessions, you're asking about requests. What you want is known as throttling. However, it would be quite difficult to do it inside the app, because Apache manages multiple processes and threads, so you'd need some external process to keep track of these in order to enable the throttling.\nBasically, this sort of thing is best done within Apache itself, by something like mod_throttle.\n"
] | [
1,
0,
0
] | [] | [] | [
"django",
"python",
"session"
] | stackoverflow_0002906790_django_python_session.txt |
Q:
Python command line UI
Hey guys/gals I'm writing a python script that fixes some duplicate issues on my database. I would like to display some progress status to the users, currently I just print it like this:
print "Merged " + str(idx) + " out of " + str(totalCount);
The problem is that it prints that in a new line for every record and that does not look so good :) I'd like to either always print the string above on the same line on the screen or use some smart widget that displays it in some sort of progress bar.
I intent to run this on the command line, any suggestions will be much appreciated.
A:
Check out fish.
A:
If you just want to constantly overwrite the same line, use '\r' and print foo, to act as a carriage return and a non-endline-printing print.
while doingStuff:
msg = "\rMerged %s out of %s" % (idx, totalCount)
print msg,
But if you're designing a fancier console app, you maybe should look into using curses (only for Unix though)
| Python command line UI | Hey guys/gals I'm writing a python script that fixes some duplicate issues on my database. I would like to display some progress status to the users, currently I just print it like this:
print "Merged " + str(idx) + " out of " + str(totalCount);
The problem is that it prints that in a new line for every record and that does not look so good :) I'd like to either always print the string above on the same line on the screen or use some smart widget that displays it in some sort of progress bar.
I intent to run this on the command line, any suggestions will be much appreciated.
| [
"Check out fish.\n",
"If you just want to constantly overwrite the same line, use '\\r' and print foo, to act as a carriage return and a non-endline-printing print.\nwhile doingStuff:\n msg = \"\\rMerged %s out of %s\" % (idx, totalCount)\n print msg,\n\nBut if you're designing a fancier console app, you maybe should look into using curses (only for Unix though)\n"
] | [
4,
4
] | [] | [] | [
"command_line",
"python",
"user_interface"
] | stackoverflow_0002907035_command_line_python_user_interface.txt |
Q:
MD5 hash differences between Python and other file hashers
I have been doing a bit of programming in Python (still a n00b at it) and came across something odd. I made a small program to find the MD5 hash of a filename passed to it on the command line. I used a function I found here on SO. When I ran it against a file, I got a hash "58a...113". But when I ran Microsoft's FCIV or the md5sum.py in \Python26\Tools\Scripts\, I get a different hash, "591...ae6". The actual hashing part of the md5sum.py in Scripts is
m = md5.new()
while 1:
data = fp.read(bufsize)
if not data:
break
m.update(data)
out.write('%s %s\n' % (m.hexdigest(), filename))
This looks functionally identical to the code in the function given in the other answer... What am I missing? (This is my first time posting to stackoverflow, please let me know if I am doing it wrong.)
A:
Already resolved in comments, but in case anyone wants to give me points... ;)
Open your file in binary mode!
f = open(path, 'rb')
| MD5 hash differences between Python and other file hashers | I have been doing a bit of programming in Python (still a n00b at it) and came across something odd. I made a small program to find the MD5 hash of a filename passed to it on the command line. I used a function I found here on SO. When I ran it against a file, I got a hash "58a...113". But when I ran Microsoft's FCIV or the md5sum.py in \Python26\Tools\Scripts\, I get a different hash, "591...ae6". The actual hashing part of the md5sum.py in Scripts is
m = md5.new()
while 1:
data = fp.read(bufsize)
if not data:
break
m.update(data)
out.write('%s %s\n' % (m.hexdigest(), filename))
This looks functionally identical to the code in the function given in the other answer... What am I missing? (This is my first time posting to stackoverflow, please let me know if I am doing it wrong.)
| [
"Already resolved in comments, but in case anyone wants to give me points... ;)\nOpen your file in binary mode!\nf = open(path, 'rb')\n\n"
] | [
8
] | [] | [] | [
"hash",
"md5",
"python"
] | stackoverflow_0002906863_hash_md5_python.txt |
Q:
extra newlines at end of file transported over tcp
I have two programs, recvfile.py and sendfile.cpp. They work except that I end up with a bunch of extra newline characters at the end of the new file. I don't know how the extra spaces get there. I know the problem is sender side, because the same doesn't happen when I use python's sendall() function to send the file.
Here are the files:
jmm_sockets.c
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>
int getServerSocket(int port)
{
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0){
fprintf(stderr, "WSAStartup() failed\n");
exit(1);
}
// create socket for incoming connections
int servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(servSock == INVALID_SOCKET){
fprintf(stderr, "Oops: socket() failed %d\n", WSAGetLastError());
exit(1);
}
// construct local address structure
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = INADDR_ANY;
servAddr.sin_port = htons(port);
// bind to the local address
int servAddrLen = sizeof(servAddr);
if(bind(servSock, (SOCKADDR*)&servAddr, servAddrLen) == SOCKET_ERROR){
fprintf(stderr, "Oops: bind() failed %d\n", WSAGetLastError());
exit(1);
}
return servSock;
}
int getClientSocket(char* host, int port)
{
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0){
fprintf(stderr, "Oops: WSAStartup() failed");
exit(1);
}
// create tcp socket
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(socket<0){
fprintf(stderr, "Oops: socket() failed %d\n", WSAGetLastError());
exit(1);
}
// set up serverAddr structure
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(host);
servAddr.sin_port = htons(port);
// connecet to server address
if(connect(sock, (SOCKADDR*)&servAddr, sizeof(servAddr)) < 0){
fprintf(stderr, "Oops: connect() failed. %d\n", WSAGetLastError());
exit(1);
}
return sock;
}
sendfile.cpp:
#include "jmm_sockets.h"
#include <windows.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sys/stat.h>
using namespace std;
int main(int argc, char** argv)
{
int port;
string host;
string filename;
if(argc==2){
cout << "Host: ";
cin >> host;
cout << "Port: ";
cin >> port;
filename = argv[1];
}else if (argc == 4){
host = argv[1];
port = atoi(argv[2]);
filename = argv[3];
}else{
cerr << "Usage: " << argv[0] << " [<host> <port>] <filename>" << endl;
exit(1);
}
// open file for reading
ifstream fin;
fin.open(filename.c_str());
if(fin.fail()){
cerr << "Error: opening " << filename << " failed. " << endl;
exit(1);
}
// get file size
fin.seekg(0, ios::end);
int size = fin.tellg();
fin.seekg(0, ios::beg);
// open socket for sending
int sock = getClientSocket((char*)host.c_str(), port);
// send file size
char buffer[16];
itoa(size, buffer, 10);
int i;
for(i=0; i<strlen(buffer); i++){
if(send(sock, &buffer[i], 1, 0)!=1){
cerr << "Error: send() failed " << WSAGetLastError() << endl;
exit(1);
}
}
char c = '\n';
if(send(sock, &c, 1, 0)!=1){
fprintf(stderr, "Error: send() failed %d\n", WSAGetLastError());
exit(1);
}
// recv y or n
int recvMsgSize = recv(sock, &c, 1, 0);
if(recvMsgSize!=1){
fprintf(stderr, "Error: recv() failed %d\n", WSAGetLastError());
exit(1);
}
if(c=='y'){
// send entire file
int readSoFar = 0;
while(readSoFar < size){
fin.get(c);
if(send(sock, &c, 1, 0)!=1){
cerr << "Error: send() failed " << WSAGetLastError() << endl;
exit(1);
}
readSoFar++;
}
}else if (c=='n'){
// leave
cout << "Remote host declined file." << endl;
}
fin.close();
closesocket(sock);
WSACleanup();
//
return 0;
}
and finally, recvfile.py:
import sys
from jmm_sockets import *
import yesno
if len(sys.argv) != 2:
print "Usage: ", argv[0], "<port>"
s = getServerSocket(None, int(sys.argv[1]))
conn, addr = s.accept()
buffer = None
filelen = str()
# receive filesize
while 1:
buffer = conn.recv(1)
if buffer == '\n':
# give it a rest
break
else:
filelen = filelen + buffer
# prompt user to accept file
filelen = int(filelen)
print "file size = ", filelen,
userChoice = yesno.yesno("Accept?")
conn.send(userChoice)
# conditionally accecpt file
if bool(userChoice):
filename = raw_input("What do you want to call the file? ")
f = open(filename, 'w')
buffer = None
data = str()
recvdBytes = 0
while recvdBytes < filelen:
buffer = conn.recv(1)
recvdBytes = recvdBytes + 1
data = data + buffer
print "File: ",
f.write(data)
print "written"
conn.close()
A:
The reason you're ending up with extra newlines is because you're sending extra newlines across the socket, which is because you try to send more data than you should.
If you checked the fail() state of your input file fin, you'd discover that it's failing on the last several calls to fin.get(c), so the value of c remains unchanged -- it stays as a newline character, which is the last character in the input file.
This is happening because of CRLF translation: the file size you're using (the size variable) is the raw file size on disk, counting all of the CRs. But, when you open it up in text mode and read it in one byte at a time, the standard library silently translates all CRLFs into LFs, so you don't send the CRs across the socket. Hence, the number of extra newlines you get at the end of this process is equal to the number of newlines that were in the original file.
The way to fix this is to open the file in binary mode to disable CRLF translation:
fin.open(filename.c_str(), ios::in | ios::binary);
Furthermore, you shouldn't be sending the file one byte at a time -- this is horrendously slow. If you're unlucky, you'll be sending an entire packet for each byte. If you're lucky, your OS's network stack will accumulate these multiple sends into larger packets (don't depend on that), but even then you're still making a huge number of system calls into the kernel.
Consider refactoring your code to make fewer calls to send() and recv(), where you pass a larger number of bytes per call, e.g.:
// Just use one call to send instead of looping over bytes and sending one
// byte at a time. Simpler and faster!
send(sock, buffer, strlen(buffer), 0);
| extra newlines at end of file transported over tcp | I have two programs, recvfile.py and sendfile.cpp. They work except that I end up with a bunch of extra newline characters at the end of the new file. I don't know how the extra spaces get there. I know the problem is sender side, because the same doesn't happen when I use python's sendall() function to send the file.
Here are the files:
jmm_sockets.c
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>
int getServerSocket(int port)
{
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0){
fprintf(stderr, "WSAStartup() failed\n");
exit(1);
}
// create socket for incoming connections
int servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(servSock == INVALID_SOCKET){
fprintf(stderr, "Oops: socket() failed %d\n", WSAGetLastError());
exit(1);
}
// construct local address structure
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = INADDR_ANY;
servAddr.sin_port = htons(port);
// bind to the local address
int servAddrLen = sizeof(servAddr);
if(bind(servSock, (SOCKADDR*)&servAddr, servAddrLen) == SOCKET_ERROR){
fprintf(stderr, "Oops: bind() failed %d\n", WSAGetLastError());
exit(1);
}
return servSock;
}
int getClientSocket(char* host, int port)
{
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0){
fprintf(stderr, "Oops: WSAStartup() failed");
exit(1);
}
// create tcp socket
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(socket<0){
fprintf(stderr, "Oops: socket() failed %d\n", WSAGetLastError());
exit(1);
}
// set up serverAddr structure
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(host);
servAddr.sin_port = htons(port);
// connecet to server address
if(connect(sock, (SOCKADDR*)&servAddr, sizeof(servAddr)) < 0){
fprintf(stderr, "Oops: connect() failed. %d\n", WSAGetLastError());
exit(1);
}
return sock;
}
sendfile.cpp:
#include "jmm_sockets.h"
#include <windows.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sys/stat.h>
using namespace std;
int main(int argc, char** argv)
{
int port;
string host;
string filename;
if(argc==2){
cout << "Host: ";
cin >> host;
cout << "Port: ";
cin >> port;
filename = argv[1];
}else if (argc == 4){
host = argv[1];
port = atoi(argv[2]);
filename = argv[3];
}else{
cerr << "Usage: " << argv[0] << " [<host> <port>] <filename>" << endl;
exit(1);
}
// open file for reading
ifstream fin;
fin.open(filename.c_str());
if(fin.fail()){
cerr << "Error: opening " << filename << " failed. " << endl;
exit(1);
}
// get file size
fin.seekg(0, ios::end);
int size = fin.tellg();
fin.seekg(0, ios::beg);
// open socket for sending
int sock = getClientSocket((char*)host.c_str(), port);
// send file size
char buffer[16];
itoa(size, buffer, 10);
int i;
for(i=0; i<strlen(buffer); i++){
if(send(sock, &buffer[i], 1, 0)!=1){
cerr << "Error: send() failed " << WSAGetLastError() << endl;
exit(1);
}
}
char c = '\n';
if(send(sock, &c, 1, 0)!=1){
fprintf(stderr, "Error: send() failed %d\n", WSAGetLastError());
exit(1);
}
// recv y or n
int recvMsgSize = recv(sock, &c, 1, 0);
if(recvMsgSize!=1){
fprintf(stderr, "Error: recv() failed %d\n", WSAGetLastError());
exit(1);
}
if(c=='y'){
// send entire file
int readSoFar = 0;
while(readSoFar < size){
fin.get(c);
if(send(sock, &c, 1, 0)!=1){
cerr << "Error: send() failed " << WSAGetLastError() << endl;
exit(1);
}
readSoFar++;
}
}else if (c=='n'){
// leave
cout << "Remote host declined file." << endl;
}
fin.close();
closesocket(sock);
WSACleanup();
//
return 0;
}
and finally, recvfile.py:
import sys
from jmm_sockets import *
import yesno
if len(sys.argv) != 2:
print "Usage: ", argv[0], "<port>"
s = getServerSocket(None, int(sys.argv[1]))
conn, addr = s.accept()
buffer = None
filelen = str()
# receive filesize
while 1:
buffer = conn.recv(1)
if buffer == '\n':
# give it a rest
break
else:
filelen = filelen + buffer
# prompt user to accept file
filelen = int(filelen)
print "file size = ", filelen,
userChoice = yesno.yesno("Accept?")
conn.send(userChoice)
# conditionally accecpt file
if bool(userChoice):
filename = raw_input("What do you want to call the file? ")
f = open(filename, 'w')
buffer = None
data = str()
recvdBytes = 0
while recvdBytes < filelen:
buffer = conn.recv(1)
recvdBytes = recvdBytes + 1
data = data + buffer
print "File: ",
f.write(data)
print "written"
conn.close()
| [
"The reason you're ending up with extra newlines is because you're sending extra newlines across the socket, which is because you try to send more data than you should.\nIf you checked the fail() state of your input file fin, you'd discover that it's failing on the last several calls to fin.get(c), so the value of c remains unchanged -- it stays as a newline character, which is the last character in the input file.\nThis is happening because of CRLF translation: the file size you're using (the size variable) is the raw file size on disk, counting all of the CRs. But, when you open it up in text mode and read it in one byte at a time, the standard library silently translates all CRLFs into LFs, so you don't send the CRs across the socket. Hence, the number of extra newlines you get at the end of this process is equal to the number of newlines that were in the original file.\nThe way to fix this is to open the file in binary mode to disable CRLF translation:\nfin.open(filename.c_str(), ios::in | ios::binary);\n\nFurthermore, you shouldn't be sending the file one byte at a time -- this is horrendously slow. If you're unlucky, you'll be sending an entire packet for each byte. If you're lucky, your OS's network stack will accumulate these multiple sends into larger packets (don't depend on that), but even then you're still making a huge number of system calls into the kernel.\nConsider refactoring your code to make fewer calls to send() and recv(), where you pass a larger number of bytes per call, e.g.:\n// Just use one call to send instead of looping over bytes and sending one\n// byte at a time. Simpler and faster!\nsend(sock, buffer, strlen(buffer), 0);\n\n"
] | [
2
] | [] | [] | [
"c",
"c++",
"python",
"sockets",
"winsockets"
] | stackoverflow_0002907353_c_c++_python_sockets_winsockets.txt |
Q:
Trouble importing a Python module
I have a Python project with 2 files:
epic.py
site.py
in the epic.py I have the lines
from site import *
bark()
in site.py I have the lines
def bark():
print('arf!')
when I try to run epic.py, it returns "bark is not defined"
this is weird.
A:
Try renaming site.py to mysite.py or something like that because there is a standard Python site module.
A:
That's because site is also the name of a built-in module. You weren't really importing your custom site module. If you change the name to, say, site_.py and import accordingly, it'll work.
| Trouble importing a Python module | I have a Python project with 2 files:
epic.py
site.py
in the epic.py I have the lines
from site import *
bark()
in site.py I have the lines
def bark():
print('arf!')
when I try to run epic.py, it returns "bark is not defined"
this is weird.
| [
"Try renaming site.py to mysite.py or something like that because there is a standard Python site module.\n",
"That's because site is also the name of a built-in module. You weren't really importing your custom site module. If you change the name to, say, site_.py and import accordingly, it'll work. \n"
] | [
5,
1
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0002907620_import_module_python.txt |
Q:
How do I rename a process on Linux?
I'm using Python, for what it's worth, but will accept answers in any applicable language.
I've tried writing to /proc/$pid/cmdline, but that's a readonly file.
I've tried assigning a new string to sys.argv[0], but that has no perceptible impact.
Are there any other possibilities? My program is executing processes via os.system (equivalent to system(3)) so a general, *NIX-based solution using an additional spawning process would be fine.
A:
Writing to *argv will change it, but you'll need to do that from C or the like; I don't think Python is going to readily give you access to that memory directly.
I'd also recommend just leaving it alone.
A:
If you use subprocess.Popen instead of os.system you can use the executable argument to specify the path to the actual file to execute, and pass the name you want to show as the first item in the list that is parameter args.
| How do I rename a process on Linux? | I'm using Python, for what it's worth, but will accept answers in any applicable language.
I've tried writing to /proc/$pid/cmdline, but that's a readonly file.
I've tried assigning a new string to sys.argv[0], but that has no perceptible impact.
Are there any other possibilities? My program is executing processes via os.system (equivalent to system(3)) so a general, *NIX-based solution using an additional spawning process would be fine.
| [
"Writing to *argv will change it, but you'll need to do that from C or the like; I don't think Python is going to readily give you access to that memory directly.\nI'd also recommend just leaving it alone.\n",
"If you use subprocess.Popen instead of os.system you can use the executable argument to specify the path to the actual file to execute, and pass the name you want to show as the first item in the list that is parameter args.\n"
] | [
0,
0
] | [] | [] | [
"linux",
"process",
"python",
"shell"
] | stackoverflow_0002907864_linux_process_python_shell.txt |
Q:
hierarchical clustering on correlations in Python scipy/numpy?
How can I run hierarchical clustering on a correlation matrix in scipy/numpy? I have a matrix of 100 rows by 9 columns, and I'd like to hierarchically cluster by correlations of each entry across the 9 conditions. I'd like to use 1-pearson correlation as the distances for clustering. Assuming I have a numpy array X that contains the 100 x 9 matrix, how can I do this?
I tried using hcluster, based on this example:
Y=pdist(X, 'seuclidean')
Z=linkage(Y, 'single')
dendrogram(Z, color_threshold=0)
However, pdist is not what I want, since that's a euclidean distance. Any ideas?
thanks.
A:
Just change the metric to correlation so that the first line becomes:
Y=pdist(X, 'correlation')
However, I believe that the code can be simplified to just:
Z=linkage(X, 'single', 'correlation')
dendrogram(Z, color_threshold=0)
because linkage will take care of the pdist for you.
| hierarchical clustering on correlations in Python scipy/numpy? | How can I run hierarchical clustering on a correlation matrix in scipy/numpy? I have a matrix of 100 rows by 9 columns, and I'd like to hierarchically cluster by correlations of each entry across the 9 conditions. I'd like to use 1-pearson correlation as the distances for clustering. Assuming I have a numpy array X that contains the 100 x 9 matrix, how can I do this?
I tried using hcluster, based on this example:
Y=pdist(X, 'seuclidean')
Z=linkage(Y, 'single')
dendrogram(Z, color_threshold=0)
However, pdist is not what I want, since that's a euclidean distance. Any ideas?
thanks.
| [
"Just change the metric to correlation so that the first line becomes:\nY=pdist(X, 'correlation')\n\nHowever, I believe that the code can be simplified to just:\nZ=linkage(X, 'single', 'correlation')\ndendrogram(Z, color_threshold=0)\n\nbecause linkage will take care of the pdist for you.\n"
] | [
13
] | [] | [] | [
"cluster_analysis",
"machine_learning",
"numpy",
"python",
"scipy"
] | stackoverflow_0002907919_cluster_analysis_machine_learning_numpy_python_scipy.txt |
Q:
How do I add a custom inline admin widget in Django?
This is easy for non-inlines. Just override the following in the your admin.py AdminOptions:
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'photo':
kwargs['widget'] = AdminImageWidget()
return db_field.formfield(**kwargs)
return super(NewsOptions,self).formfield_for_dbfield(db_field,**kwargs)
I can't work out how to adapt this to work for inlines.
A:
It works exactly the same way. The TabularInline and StackedInline classes also have a formfield_for_dbfield method, and you override it the same way in your subclass.
A:
Since Django 1.1, formfield_overrides is also working
formfield_overrides = {
models.ImageField: {'widget': AdminImageWidget},
}
A:
Working example:
class PictureInline(admin.StackedInline):
model = Picture_Gallery
extra = 3
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'name':
kwargs['widget'] = MyWidget()
return super(PictureInline,self).formfield_for_dbfield(db_field,**kwargs)
| How do I add a custom inline admin widget in Django? | This is easy for non-inlines. Just override the following in the your admin.py AdminOptions:
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'photo':
kwargs['widget'] = AdminImageWidget()
return db_field.formfield(**kwargs)
return super(NewsOptions,self).formfield_for_dbfield(db_field,**kwargs)
I can't work out how to adapt this to work for inlines.
| [
"It works exactly the same way. The TabularInline and StackedInline classes also have a formfield_for_dbfield method, and you override it the same way in your subclass.\n",
"Since Django 1.1, formfield_overrides is also working\nformfield_overrides = {\n models.ImageField: {'widget': AdminImageWidget},\n}\n\n",
"Working example:\nclass PictureInline(admin.StackedInline):\n model = Picture_Gallery\n extra = 3\n def formfield_for_dbfield(self, db_field, **kwargs):\n if db_field.name == 'name':\n kwargs['widget'] = MyWidget()\n return super(PictureInline,self).formfield_for_dbfield(db_field,**kwargs)\n\n"
] | [
11,
8,
3
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0000433251_django_django_admin_python.txt |
Q:
Django CSRF failure when form posts to a different frame
I'm building a page where I want to have a form that posts to an iframe on the same page. The Template looks like this:
<form action="form-results" method="post" target="resultspane" >
{% csrf_token %}
<input name="query">
<input type=submit>
</form>
<iframe src="form-results" name="resultspane" width="100%" height="70%">
</iframe>
The view behind form-results is getting CSRF errors. Is there something special needed for cross-frame posting?
A:
Actually, the problem has nothing to do with cross-form POSTing. The template that displays the form needs to be rendered with RequestContext as in
return render_to_response('form_template.html',
context_instance = RequestContext(request))
| Django CSRF failure when form posts to a different frame | I'm building a page where I want to have a form that posts to an iframe on the same page. The Template looks like this:
<form action="form-results" method="post" target="resultspane" >
{% csrf_token %}
<input name="query">
<input type=submit>
</form>
<iframe src="form-results" name="resultspane" width="100%" height="70%">
</iframe>
The view behind form-results is getting CSRF errors. Is there something special needed for cross-frame posting?
| [
"Actually, the problem has nothing to do with cross-form POSTing. The template that displays the form needs to be rendered with RequestContext as in\nreturn render_to_response('form_template.html',\n context_instance = RequestContext(request))\n\n"
] | [
2
] | [] | [] | [
"django",
"django_csrf",
"iframe",
"python"
] | stackoverflow_0002908284_django_django_csrf_iframe_python.txt |
Q:
Are there viable alternatives for Web 2.0 apps besides lots of Javascript?
If you say find C-style syntax to be in the axis of evil are you just hopelessly condemned to suck it up and deal with it if you want to provide your users with cool web 2.0 applications - for example stuff that's generally done using JQuery and Ajax etc? Are there no other choices out there? We're currently building intranet apps using pylons and a bunch of JavaScript along with a bit of Evoque. So obviously for us the world would be a better place if instead something equivalent existed written in like PythonScript. But I've yet to seen anything approaching that aside from the Android system's ASE - but obviously that's something rather unrelated. Still - if browsers could support other scripting languages....
A:
Other language supported by "some" "browsers" is VBScript, but.. you don't want to go there.
The support for other languages is still work in progress.
What you can get today is to have a framework or library to translate one language into JavaScript
Here are some of them along with a small sample:
GWT - Java
// Add a button to remove this stock from the table.
Button removeStockButton = new Button("x");
removeStockButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
int removedIndex = stocks.indexOf(symbol);
stocks.remove(removedIndex);
stocksFlexTable.removeRow(removedIndex + 1);
}
});
stocksFlexTable.setWidget(row, 3, removeStockButton);
Pyjamas - Python
def greet(sender):
Window.alert("Hello, AJAX!")
CofeeScript - ( Ruby like )
square: (x) -> x * x
cube: (x) -> square(x) * x
Pyscript - ( Python like )
// Example One
function triangle(a,b):
function sqroot(x): return Math.pow(x,.5)
return sqroot( a*a + b*b )
From this, GWT is the most robust.
A:
I'm of the opinion that you should just get over it, but there are some non-C-style options that "compile" down to JavaScript:
CoffeeScript is inspired by Ruby and Potion
Pyjamas is a port of Google Web Toolkit (Java) to Python
A:
There's GWT that compiles Java to Javascript. In theory, you could do the same for any language. Additionally, for instance, Python can run on a JVM, so perhaps there's a way to plug Python into GWT.
There's also http://pyjs.org/ and probably other similar projects.
A:
If you want "native" web 2.0 app, try GWT or Pyjamas. Otherwise you can use proprietary plugins: Silverlight, Flash, JavaFX. You can use IronPython (.Net Python implementation) to write Silverlight application.
| Are there viable alternatives for Web 2.0 apps besides lots of Javascript? | If you say find C-style syntax to be in the axis of evil are you just hopelessly condemned to suck it up and deal with it if you want to provide your users with cool web 2.0 applications - for example stuff that's generally done using JQuery and Ajax etc? Are there no other choices out there? We're currently building intranet apps using pylons and a bunch of JavaScript along with a bit of Evoque. So obviously for us the world would be a better place if instead something equivalent existed written in like PythonScript. But I've yet to seen anything approaching that aside from the Android system's ASE - but obviously that's something rather unrelated. Still - if browsers could support other scripting languages....
| [
"Other language supported by \"some\" \"browsers\" is VBScript, but.. you don't want to go there. \nThe support for other languages is still work in progress.\nWhat you can get today is to have a framework or library to translate one language into JavaScript\nHere are some of them along with a small sample:\n\nGWT - Java \n// Add a button to remove this stock from the table.\nButton removeStockButton = new Button(\"x\");\nremoveStockButton.addClickHandler(new ClickHandler() {\n public void onClick(ClickEvent event) {\n int removedIndex = stocks.indexOf(symbol);\n stocks.remove(removedIndex);\n stocksFlexTable.removeRow(removedIndex + 1);\n }\n});\nstocksFlexTable.setWidget(row, 3, removeStockButton);\n\nPyjamas - Python\ndef greet(sender):\n Window.alert(\"Hello, AJAX!\")\n\nCofeeScript - ( Ruby like )\nsquare: (x) -> x * x\ncube: (x) -> square(x) * x\n\nPyscript - ( Python like ) \n// Example One\nfunction triangle(a,b):\n function sqroot(x): return Math.pow(x,.5)\n return sqroot( a*a + b*b )\n\n\nFrom this, GWT is the most robust. \n",
"I'm of the opinion that you should just get over it, but there are some non-C-style options that \"compile\" down to JavaScript:\n\nCoffeeScript is inspired by Ruby and Potion\nPyjamas is a port of Google Web Toolkit (Java) to Python\n\n",
"There's GWT that compiles Java to Javascript. In theory, you could do the same for any language. Additionally, for instance, Python can run on a JVM, so perhaps there's a way to plug Python into GWT.\nThere's also http://pyjs.org/ and probably other similar projects.\n",
"If you want \"native\" web 2.0 app, try GWT or Pyjamas. Otherwise you can use proprietary plugins: Silverlight, Flash, JavaFX. You can use IronPython (.Net Python implementation) to write Silverlight application.\n"
] | [
4,
3,
0,
0
] | [] | [] | [
"ajax",
"pylons",
"python"
] | stackoverflow_0002908108_ajax_pylons_python.txt |
Q:
split a string into a list of tuples
If i have a string like:
"user1:type1,user2:type2,user3:type3"
and I want to convert this to a list of tuples like so:
[('user1','type1'),('user2','type2'),('user3','type3')]
how would i go about doing this? I'm fairly new to python but couldn't find a good example in the documentation to do this.
Thanks!
A:
>>> s = "user1:type1,user2:type2,user3:type3"
>>> [tuple(x.split(':')) for x in s.split(',')]
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
A:
The cleanest way is two splits with a list comprehension:
str = "user1:type1,user2:type2,user3:type3"
res = [tuple(x.split(":")) for x in str.split(",")]
A:
>>> s = "user1:type1,user2:type2,user3:type3"
>>> l = [tuple(user.split(":")) for user in s.split(",")]
>>> l
[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]
>>>
:)
A:
If you want to do it without for loops, you can use map and lambda:
map(lambda x: tuple(x.split(":")), yourString.split(","))
A:
Use the split function twice.
Try this for an example:
s = "user1:type1,user2:type2,user3:type3"
print [i.split(':') for i in s.split(',')]
| split a string into a list of tuples | If i have a string like:
"user1:type1,user2:type2,user3:type3"
and I want to convert this to a list of tuples like so:
[('user1','type1'),('user2','type2'),('user3','type3')]
how would i go about doing this? I'm fairly new to python but couldn't find a good example in the documentation to do this.
Thanks!
| [
">>> s = \"user1:type1,user2:type2,user3:type3\"\n>>> [tuple(x.split(':')) for x in s.split(',')]\n[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]\n\n",
"The cleanest way is two splits with a list comprehension:\nstr = \"user1:type1,user2:type2,user3:type3\"\nres = [tuple(x.split(\":\")) for x in str.split(\",\")]\n\n",
">>> s = \"user1:type1,user2:type2,user3:type3\"\n>>> l = [tuple(user.split(\":\")) for user in s.split(\",\")]\n>>> l\n[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]\n>>>\n\n:)\n",
"If you want to do it without for loops, you can use map and lambda:\nmap(lambda x: tuple(x.split(\":\")), yourString.split(\",\"))\n\n",
"Use the split function twice.\nTry this for an example:\n s = \"user1:type1,user2:type2,user3:type3\"\n print [i.split(':') for i in s.split(',')]\n\n"
] | [
12,
5,
4,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002908308_python.txt |
Q:
How to run perl script with a few arguments from php
My html webpage calls a php script to upload files to the server from a local computer as follows.
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p><b><h3> <font color="#003366"> (1) Upload your reading text file. </font>
</h3> </b> </p>
<INPUT type="file" name="uploaded" size="50" >
<br/>
<input type="submit" name="files" value="upload">
</form>
In order to process with an uploaded file, my php script calls a shell script
$output=system('/bin/sh connector_0.sh');
and my shell script is composed of a series of python/perl scripts.
#!/bin/sh
python main_senselearner_final_0.py
senseLearner.pl -i Uploaded_Files/slinput_0.txt -o Uploaded_Files/presloutput_0
.txt -model modelNNCollocations -model modelJJCollocations -model modelVBColloc
ations -pos
python smutngslout_0.py
python genhtml_0.py
Now, the problem is the following: all the python scripts in shell script worked fine through php. But the perl script didn't work.
When I run the shell script by myself in my server, all four scripts in the shell worked perfectly. However, when I run the shell script from php, only the perl script doesn't work.
Would you please give me any tips to solve this problem?
Many thanks!!!
A:
This is very likely a permissions problem. Try setting the files that the perl script reads to a+rw and see if it works then. If so, then you need to find out the user running php (likely the apache user) and make sure that they can read/write the relevant files.
Also make sure the Perl script is executable by the php user (apache).
A:
There is a possibility that the user that Apache/PHP is running as (usually apache) does not have permissions for Uploaded_Files/slinput_0.txt or Uploaded_Files/presloutput_0.txt.
Just guessing but apache would need read for the slinput_0.txt file, read/write for presloutput_0.txt and read/write/exec for the directory Uploaded_Files
The reason it works when you try it is you are running as your user and most likely have permissions to write to the webroot.
A:
I'd try
senseLearner.pl -i Up ... -pos > /var/log/senseLearner.log 2>&1
(and look to that log file after)
and maybe you can try to specify interpreter like
/path/to/perl senseLearner.pl -i Up ... -pos > /var/log/senseLearner.log 2>&1
| How to run perl script with a few arguments from php | My html webpage calls a php script to upload files to the server from a local computer as follows.
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p><b><h3> <font color="#003366"> (1) Upload your reading text file. </font>
</h3> </b> </p>
<INPUT type="file" name="uploaded" size="50" >
<br/>
<input type="submit" name="files" value="upload">
</form>
In order to process with an uploaded file, my php script calls a shell script
$output=system('/bin/sh connector_0.sh');
and my shell script is composed of a series of python/perl scripts.
#!/bin/sh
python main_senselearner_final_0.py
senseLearner.pl -i Uploaded_Files/slinput_0.txt -o Uploaded_Files/presloutput_0
.txt -model modelNNCollocations -model modelJJCollocations -model modelVBColloc
ations -pos
python smutngslout_0.py
python genhtml_0.py
Now, the problem is the following: all the python scripts in shell script worked fine through php. But the perl script didn't work.
When I run the shell script by myself in my server, all four scripts in the shell worked perfectly. However, when I run the shell script from php, only the perl script doesn't work.
Would you please give me any tips to solve this problem?
Many thanks!!!
| [
"This is very likely a permissions problem. Try setting the files that the perl script reads to a+rw and see if it works then. If so, then you need to find out the user running php (likely the apache user) and make sure that they can read/write the relevant files.\nAlso make sure the Perl script is executable by the php user (apache).\n",
"There is a possibility that the user that Apache/PHP is running as (usually apache) does not have permissions for Uploaded_Files/slinput_0.txt or Uploaded_Files/presloutput_0.txt. \nJust guessing but apache would need read for the slinput_0.txt file, read/write for presloutput_0.txt and read/write/exec for the directory Uploaded_Files\nThe reason it works when you try it is you are running as your user and most likely have permissions to write to the webroot.\n",
"I'd try\nsenseLearner.pl -i Up ... -pos > /var/log/senseLearner.log 2>&1\n(and look to that log file after)\nand maybe you can try to specify interpreter like\n/path/to/perl senseLearner.pl -i Up ... -pos > /var/log/senseLearner.log 2>&1\n"
] | [
1,
0,
0
] | [] | [] | [
"perl",
"php",
"python",
"shell"
] | stackoverflow_0002908274_perl_php_python_shell.txt |
Q:
what does "from MODULE import _" do in python?
In the Getting things gnome code base I stumbled upon this import statement
from GTG import _
and have no idea what it means, never seen this in the documentation and a quick so / google search didn't turn anything up.
A:
from GTG import _ imports the _ function from the GTG module into the "current" namespace.
Usually, the _ function is an alias for gettext.gettext(), a function that shows the localized version of a given message. The documentation gives a picture of what is usually going on somewhere else in a module far, far away:
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')
A:
This imports the function/class/module _ into the current namespace. So instead of having to type GTG._, you just have to type _ to use it.
Here is some documentation:
http://docs.python.org/tutorial/modules.html#more-on-modules
It should be noted that you should use this with care. Doing this too much could pollute the current namespace, making code harder to read, and possibly introducing runtime errors. Also, NEVER NEVER NEVER do this:
from MODULE import *
, as it very much pollutes the current namespace.
This technique is most useful when you know you are only going to use one or two functions/classes/modules from a module, since doing this only imports the listed assets.
For example, if I want to use the imap function from the itertools module, and I know I won't need any other itertools functions, I could write
from itertools import imap
and it would only import the imap function.
Like I said earlier, this should be used with care, since some people may think that
import itertools
# ... more code ...
new_list = itertools.imap(my_func, my_list)
is more readable than
from itertools import imap
# ... more code ...
new_list = imap(my_func, my_list)
as it makes it clear exactly which module the imap function came from.
| what does "from MODULE import _" do in python? | In the Getting things gnome code base I stumbled upon this import statement
from GTG import _
and have no idea what it means, never seen this in the documentation and a quick so / google search didn't turn anything up.
| [
"from GTG import _ imports the _ function from the GTG module into the \"current\" namespace.\nUsually, the _ function is an alias for gettext.gettext(), a function that shows the localized version of a given message. The documentation gives a picture of what is usually going on somewhere else in a module far, far away:\nimport gettext\ngettext.bindtextdomain('myapplication', '/path/to/my/language/directory')\ngettext.textdomain('myapplication')\n_ = gettext.gettext\n# ...\nprint _('This is a translatable string.')\n\n",
"This imports the function/class/module _ into the current namespace. So instead of having to type GTG._, you just have to type _ to use it.\nHere is some documentation:\nhttp://docs.python.org/tutorial/modules.html#more-on-modules\nIt should be noted that you should use this with care. Doing this too much could pollute the current namespace, making code harder to read, and possibly introducing runtime errors. Also, NEVER NEVER NEVER do this:\nfrom MODULE import *\n\n, as it very much pollutes the current namespace.\nThis technique is most useful when you know you are only going to use one or two functions/classes/modules from a module, since doing this only imports the listed assets.\nFor example, if I want to use the imap function from the itertools module, and I know I won't need any other itertools functions, I could write\nfrom itertools import imap\n\nand it would only import the imap function. \nLike I said earlier, this should be used with care, since some people may think that\nimport itertools\n\n# ... more code ...\n\nnew_list = itertools.imap(my_func, my_list)\n\nis more readable than\nfrom itertools import imap\n\n# ... more code ...\n\nnew_list = imap(my_func, my_list)\n\nas it makes it clear exactly which module the imap function came from.\n"
] | [
13,
4
] | [] | [] | [
"import",
"python"
] | stackoverflow_0002908444_import_python.txt |
Q:
Refining data stored in SQLite - how to join several contacts?
I'm storing contacts between different elements. I want to eliminate elements of certain type and store new contacts of elements which were interconnected by the eliminated element.
Problem background
Imagine this problem. You have a water molecule which is in contact with other molecules (if the contact is a hydrogen bond, there can be 4 other molecules around my water). Like in the following picture (A, B, C, D are some other atoms and dots mean the contact).
A B
| |
H H
. .
O
/ \
H H
. .
C D
I have the information about all the dots and I need to eliminate the water in the center and create records describing contacts of A-C, A-D, A-B, B-C, B-D, and C-D.
Database structure
Currently, I have the following structure in the database:
Table atoms:
"id" integer PRIMARY KEY,
"amino" char(3) NOT NULL, (HOH for water or other value)
other columns identifying the atom
Table contacts:
"acceptor_id" integer NOT NULL, (the atom near to my hydrogen, here C or D)
"donor_id" integer NOT NULL, (here A or B)
"directness" char(1) NOT NULL, (this should be D for direct and W for water-mediated)
other columns about the contact, such as the distance
EDIT:
How would look the data in the case depicted earlier.
atoms:
id|atom|amino
1 | O | HOH
2 | N | ARG <- atom A from image
3 | S | CYS <- B
4 | O | SER <- C
5 | N | ARG <- D
contacts:
donor_id|acceptor_id|directness
1 4 D
1 5 D
2 1 D
3 1 D
From which I need to make
contacts:
donor_id|acceptor_id|directness
3 4 W <- B-C
3 5 W <- B-D
2 4 W <- A-C
2 5 W <- A-D
2 3 X <- A-B (These last two rows are escaping me,
4 5 X <- C-D there could be also row D-C, but not
both C-D and D-C. A char 'X' could
be used to mark "no donor/acceptor")
Current solution (insufficient)
Now, I'm going through all the contacts which have donor.amino = "HOH". In this sample case, this would select contacts from C and D. For each of these selected contacts, I look up contacts having the same acceptor_id as is the donor_id in the currently selected contact. From this information, I create the new contact. At the end, I delete all contacts to or from HOH.
This way, I am obviously unable to create C-D and A-B contacts (the other 4 are OK).
If I try a similar approach - trying to find two contacts having the same donor_id, I end up with duplicate contacts (C-D and D-C).
Is there a simple way to retrieve all six contacts without duplicates?
I'm dreaming about some one page long SQL query which retrieves just these six wanted rows. :-)
However, any other ideas are welcome.
It is preferable to conserve information about who is donor (where possible), but not strictly necessary.
Big thanks to all of you who read this question to this point.
A:
There's one difficulty with your explanation.
What you start with is a directed graph where each edge represents a connection X=>Y where X is a donor and Y an acceptor. The table atoms is the SQL representation of that graph.
What you seem to want is something that is undirected. So that a link X-Y means that X and Y are linked via a water molecule (or some other species of course) but that X and Y could both be donors or acceptors. For this reason your last table has an ambiguity (that you note) so that some links could occur either way around. It seems to me that means that the column headings donor_id and acceptor_id on your final column don't have any meaning that you have explained. This may be my confusion of course.
If all you want is a table with all 6 links in it, each as one row, but don't worry too much about keeping track of the donor/acceptor thing then this works for me in sqlite3:
create temporary view hoh_view as
select donor_id as id, atoms.id as hoh_id from contacts, atoms
where acceptor_id=atoms.id and atoms.amino='HOH'
union select acceptor_id as id, atoms.id as hoh_id from contacts, atoms
where donor_id=atoms.id and atoms.amino='HOH';
select a.id, b.id from hoh_view as a, hoh_view as b
where a.id > b.id and a.hoh_id=b.hoh_id;
Where I have used a temporary view to make things clearer. You can put this all into one big query if you like by replacing each reference to hoh_view by the first query. It feels a bit nasty to me and there may be a way of tidying it up.
If you do want to keep track of donor/acceptor relationships you need to explain how you decide what to do when both amino acids are acceptors or donors (i.e. the last two rows in your example).
If that doesn't do what you want, then maybe I can fix it up so it does.
A:
Well, its hard to provide examples in comments, I decided to post an answer:
If you have to following original data, there is no way to distinguish data from the first structure from those of the second. There should be an additional grouping condition to eleminate directions between the first and the second structure.
sqlite> create table atoms (id INT, atom TEXT, amino TEXT);
sqlite> insert into atoms VALUES (1, 'O', 'HOH');
sqlite> insert into atoms VALUES (2, 'A', 'ARG');
sqlite> insert into atoms VALUES (3, 'B', 'CYS');
sqlite> insert into atoms VALUES (4, 'C', 'SER');
sqlite> insert into atoms VALUES (5, 'D', 'ARG');
sqlite> insert into atoms VALUES (6, 'O1', 'HOH');
sqlite> insert into atoms VALUES (7, 'A1', 'ARG');
sqlite> insert into atoms VALUES (8, 'B1', 'CYS');
sqlite> insert into atoms VALUES (9, 'C1', 'SER');
sqlite> insert into atoms VALUES (10, 'D1', 'ARG');
sqlite> select * from atoms;
1|O|HOH
2|A|ARG
3|B|CYS
4|C|SER
5|D|ARG
6|O1|HOH
7|A1|ARG
8|B1|CYS
9|C1|SER
10|D1|ARG
UPD
Here is the original data:
sqlite> .headers ON
sqlite> .mode columns
sqlite> select * from atoms;
id atom amino
---------- ---------- ----------
1 O HOH
2 A ARG
3 B CYS
4 C SER
5 D ARG
6 O1 HOH
7 A1 ARG
8 B1 CYS
9 C1 SER
10 D1 ARG
sqlite> select * from contacts;
donor_id acceptor_id directness
---------- ----------- ----------
1 4 D
1 5 D
2 1 D
3 1 D
6 9 D
6 10 D
7 6 D
8 6 D
Here is the query:
select
c1.donor_id, c2.acceptor_id, 'W' as directness
from
contacts c1, contacts c2, atoms a
where
c1.acceptor_id = c2.donor_id
and c1.acceptor_id=a.id
and a.amino='HOH'
UNION ALL
select
c1.donor_id, c2.donor_id, 'X' as directness
from
contacts c1, contacts c2, atoms a
where
c1.acceptor_id = c2.acceptor_id
and c1.acceptor_id=a.id
and a.amino='HOH'
and c1.donor_id < c2.donor_id
UNION ALL
select
c1.acceptor_id, c2.acceptor_id, 'X' as directness
from
contacts c1, contacts c2, atoms a
where
c1.donor_id = c2.donor_id
and c1.donor_id=a.id
and a.amino='HOH'
and c1.acceptor_id < c2.acceptor_id;
Here is the result:
donor_id acceptor_id directness
---------- ----------- ----------
2 4 W
2 5 W
3 4 W
3 5 W
7 9 W
7 10 W
8 9 W
8 10 W
2 3 X
7 8 X
4 5 X
9 10 X
| Refining data stored in SQLite - how to join several contacts? | I'm storing contacts between different elements. I want to eliminate elements of certain type and store new contacts of elements which were interconnected by the eliminated element.
Problem background
Imagine this problem. You have a water molecule which is in contact with other molecules (if the contact is a hydrogen bond, there can be 4 other molecules around my water). Like in the following picture (A, B, C, D are some other atoms and dots mean the contact).
A B
| |
H H
. .
O
/ \
H H
. .
C D
I have the information about all the dots and I need to eliminate the water in the center and create records describing contacts of A-C, A-D, A-B, B-C, B-D, and C-D.
Database structure
Currently, I have the following structure in the database:
Table atoms:
"id" integer PRIMARY KEY,
"amino" char(3) NOT NULL, (HOH for water or other value)
other columns identifying the atom
Table contacts:
"acceptor_id" integer NOT NULL, (the atom near to my hydrogen, here C or D)
"donor_id" integer NOT NULL, (here A or B)
"directness" char(1) NOT NULL, (this should be D for direct and W for water-mediated)
other columns about the contact, such as the distance
EDIT:
How would look the data in the case depicted earlier.
atoms:
id|atom|amino
1 | O | HOH
2 | N | ARG <- atom A from image
3 | S | CYS <- B
4 | O | SER <- C
5 | N | ARG <- D
contacts:
donor_id|acceptor_id|directness
1 4 D
1 5 D
2 1 D
3 1 D
From which I need to make
contacts:
donor_id|acceptor_id|directness
3 4 W <- B-C
3 5 W <- B-D
2 4 W <- A-C
2 5 W <- A-D
2 3 X <- A-B (These last two rows are escaping me,
4 5 X <- C-D there could be also row D-C, but not
both C-D and D-C. A char 'X' could
be used to mark "no donor/acceptor")
Current solution (insufficient)
Now, I'm going through all the contacts which have donor.amino = "HOH". In this sample case, this would select contacts from C and D. For each of these selected contacts, I look up contacts having the same acceptor_id as is the donor_id in the currently selected contact. From this information, I create the new contact. At the end, I delete all contacts to or from HOH.
This way, I am obviously unable to create C-D and A-B contacts (the other 4 are OK).
If I try a similar approach - trying to find two contacts having the same donor_id, I end up with duplicate contacts (C-D and D-C).
Is there a simple way to retrieve all six contacts without duplicates?
I'm dreaming about some one page long SQL query which retrieves just these six wanted rows. :-)
However, any other ideas are welcome.
It is preferable to conserve information about who is donor (where possible), but not strictly necessary.
Big thanks to all of you who read this question to this point.
| [
"There's one difficulty with your explanation. \nWhat you start with is a directed graph where each edge represents a connection X=>Y where X is a donor and Y an acceptor. The table atoms is the SQL representation of that graph. \nWhat you seem to want is something that is undirected. So that a link X-Y means that X and Y are linked via a water molecule (or some other species of course) but that X and Y could both be donors or acceptors. For this reason your last table has an ambiguity (that you note) so that some links could occur either way around. It seems to me that means that the column headings donor_id and acceptor_id on your final column don't have any meaning that you have explained. This may be my confusion of course.\nIf all you want is a table with all 6 links in it, each as one row, but don't worry too much about keeping track of the donor/acceptor thing then this works for me in sqlite3:\n create temporary view hoh_view as \n select donor_id as id, atoms.id as hoh_id from contacts, atoms \n where acceptor_id=atoms.id and atoms.amino='HOH' \n union select acceptor_id as id, atoms.id as hoh_id from contacts, atoms \n where donor_id=atoms.id and atoms.amino='HOH';\n\n select a.id, b.id from hoh_view as a, hoh_view as b \n where a.id > b.id and a.hoh_id=b.hoh_id;\n\nWhere I have used a temporary view to make things clearer. You can put this all into one big query if you like by replacing each reference to hoh_view by the first query. It feels a bit nasty to me and there may be a way of tidying it up.\nIf you do want to keep track of donor/acceptor relationships you need to explain how you decide what to do when both amino acids are acceptors or donors (i.e. the last two rows in your example).\nIf that doesn't do what you want, then maybe I can fix it up so it does.\n",
"Well, its hard to provide examples in comments, I decided to post an answer:\nIf you have to following original data, there is no way to distinguish data from the first structure from those of the second. There should be an additional grouping condition to eleminate directions between the first and the second structure.\nsqlite> create table atoms (id INT, atom TEXT, amino TEXT);\nsqlite> insert into atoms VALUES (1, 'O', 'HOH');\nsqlite> insert into atoms VALUES (2, 'A', 'ARG');\nsqlite> insert into atoms VALUES (3, 'B', 'CYS');\nsqlite> insert into atoms VALUES (4, 'C', 'SER');\nsqlite> insert into atoms VALUES (5, 'D', 'ARG');\nsqlite> insert into atoms VALUES (6, 'O1', 'HOH');\nsqlite> insert into atoms VALUES (7, 'A1', 'ARG');\nsqlite> insert into atoms VALUES (8, 'B1', 'CYS');\nsqlite> insert into atoms VALUES (9, 'C1', 'SER');\nsqlite> insert into atoms VALUES (10, 'D1', 'ARG');\nsqlite> select * from atoms;\n1|O|HOH\n2|A|ARG\n3|B|CYS\n4|C|SER\n5|D|ARG\n6|O1|HOH\n7|A1|ARG\n8|B1|CYS\n9|C1|SER\n10|D1|ARG\n\nUPD\nHere is the original data:\nsqlite> .headers ON\nsqlite> .mode columns\nsqlite> select * from atoms;\nid atom amino\n---------- ---------- ----------\n1 O HOH\n2 A ARG\n3 B CYS\n4 C SER\n5 D ARG\n6 O1 HOH\n7 A1 ARG\n8 B1 CYS\n9 C1 SER\n10 D1 ARG\nsqlite> select * from contacts;\ndonor_id acceptor_id directness\n---------- ----------- ----------\n1 4 D\n1 5 D\n2 1 D\n3 1 D\n6 9 D\n6 10 D\n7 6 D\n8 6 D\n\nHere is the query:\nselect\n c1.donor_id, c2.acceptor_id, 'W' as directness\nfrom\n contacts c1, contacts c2, atoms a\nwhere\n c1.acceptor_id = c2.donor_id\n and c1.acceptor_id=a.id\n and a.amino='HOH'\nUNION ALL\nselect\n c1.donor_id, c2.donor_id, 'X' as directness\nfrom\n contacts c1, contacts c2, atoms a\nwhere\n c1.acceptor_id = c2.acceptor_id\n and c1.acceptor_id=a.id\n and a.amino='HOH'\n and c1.donor_id < c2.donor_id\nUNION ALL\nselect\n c1.acceptor_id, c2.acceptor_id, 'X' as directness\nfrom\n contacts c1, contacts c2, atoms a\nwhere\n c1.donor_id = c2.donor_id\n and c1.donor_id=a.id\n and a.amino='HOH'\n and c1.acceptor_id < c2.acceptor_id;\n\nHere is the result:\ndonor_id acceptor_id directness\n---------- ----------- ----------\n2 4 W\n2 5 W\n3 4 W\n3 5 W\n7 9 W\n7 10 W\n8 9 W\n8 10 W\n2 3 X\n7 8 X\n4 5 X\n9 10 X\n\n"
] | [
2,
1
] | [] | [] | [
"algorithm",
"bioinformatics",
"python",
"sql",
"sqlite"
] | stackoverflow_0002904205_algorithm_bioinformatics_python_sql_sqlite.txt |
Q:
Can't import pygame to Netbeans on Mac
I am running python 2.6.5 and pygame 1.9.1 It seems to me I've tried everything but it keeps showing 'module not found' errors... Please help!
A:
Well I've just finished installing it on my Mac - you have to watch out for the Python Platform under Tools and File. The default is Jython, but you want to change it to point to your python version in the Frameworks file of your Library.
Does that make sense?
| Can't import pygame to Netbeans on Mac | I am running python 2.6.5 and pygame 1.9.1 It seems to me I've tried everything but it keeps showing 'module not found' errors... Please help!
| [
"Well I've just finished installing it on my Mac - you have to watch out for the Python Platform under Tools and File. The default is Jython, but you want to change it to point to your python version in the Frameworks file of your Library.\nDoes that make sense?\n"
] | [
1
] | [] | [] | [
"import",
"module",
"netbeans",
"pygame",
"python"
] | stackoverflow_0002541254_import_module_netbeans_pygame_python.txt |
Q:
append versus resize for numpy array
I would like to append a value at the end of my numpy.array.
I saw numpy.append function but this performs an exact copy of the original array adding at last my new value. I would like to avoid copies since my arrays are big.
I am using resize method and then set the last index available to the new value.
Can you confirm that resize is the best way to append a value at the end?
Is it not moving memory around someway?
oldSize = myArray,shape(0)
myArray.resize( oldSize + 1 )
myArray[oldSize] = newValue
A:
My simple timing experiment of append vs. resizing showed that resizing is about 3x faster and its the fastest way that I can think of to do this. Also, the answer to this question seems to imply that resizing the array is the way to go because it is in-place.
Verdict:
Use resize
P.S. You also might want to check out this discussion from a numpy mailing list.
| append versus resize for numpy array | I would like to append a value at the end of my numpy.array.
I saw numpy.append function but this performs an exact copy of the original array adding at last my new value. I would like to avoid copies since my arrays are big.
I am using resize method and then set the last index available to the new value.
Can you confirm that resize is the best way to append a value at the end?
Is it not moving memory around someway?
oldSize = myArray,shape(0)
myArray.resize( oldSize + 1 )
myArray[oldSize] = newValue
| [
"My simple timing experiment of append vs. resizing showed that resizing is about 3x faster and its the fastest way that I can think of to do this. Also, the answer to this question seems to imply that resizing the array is the way to go because it is in-place.\nVerdict:\nUse resize\nP.S. You also might want to check out this discussion from a numpy mailing list.\n"
] | [
8
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0002908672_arrays_numpy_python.txt |
Q:
how to fetch more than 1000 entities NON keybased?
If I should be approaching this problem through a different method, please suggest so. I am creating an item based collaborative filter. I populate the db with the LinkRating2 class and for each link there are more than a 1000 users that I need to call and collect their ratings to perform calculations which I then use to create another table. So I need to call more than 1000 entities for a given link.
For instance lets say there are over a 1000 users rated 'link1' there will be over a 1000 instances of this class for the given link property that I need to call.
How would I complete this example?
class LinkRating2(db.Model):
user = db.StringProperty()
link = db.StringProperty()
rating2 = db.FloatProperty()
query =LinkRating2.all()
link1 = 'link string name'
a = query.filter('link = ', link1)
aa = a.fetch(1000)##how would i get more than 1000 for a given link1 as shown?
##keybased over 1000 in other post example i need method for a subset though not key
class MyModel(db.Expando):
@classmethod
def count_all(cls):
"""
Count *all* of the rows (without maxing out at 1000)
"""
count = 0
query = cls.all().order('__key__')
while count % 1000 == 0:
current_count = query.count()
if current_count == 0:
break
count += current_count
if current_count == 1000:
last_key = query.fetch(1, 999)[0].key()
query = query.filter('__key__ > ', last_key)
return count
A:
Wooble points out that the 1,000 entity limit is a thing of the past now, so you actually don't need to use cursors to do this - just fetch everything at once (it'll be faster than getting them in 1,000 entity batches too since there will be fewer round-trips to the datastore, etc.)
The removal of the 1000 entity limit was removed in version 1.3.1: http://googleappengine.blogspot.com/2010/02/app-engine-sdk-131-including-major.html
Old solution using cursors:
Use query cursors to fetch results beyond the first 1,000 entities:
# continuing from your code ... get ALL of the query's results:
more = aa
while len(more) == 1000:
a.with_cusor(a.cursor()) # start the query where we left off
more = a.fetch(1000) # get the next 1000 results
aa = aa + more # copy the additional results into aa
A:
The 1000-entity fetch limit was removed recently; you can fetch as many as you need, provided you can do so within the time limits. Your entities look like they'll be fairly small, so you may be able to fetch significantly more than 1000 in a request.
| how to fetch more than 1000 entities NON keybased? | If I should be approaching this problem through a different method, please suggest so. I am creating an item based collaborative filter. I populate the db with the LinkRating2 class and for each link there are more than a 1000 users that I need to call and collect their ratings to perform calculations which I then use to create another table. So I need to call more than 1000 entities for a given link.
For instance lets say there are over a 1000 users rated 'link1' there will be over a 1000 instances of this class for the given link property that I need to call.
How would I complete this example?
class LinkRating2(db.Model):
user = db.StringProperty()
link = db.StringProperty()
rating2 = db.FloatProperty()
query =LinkRating2.all()
link1 = 'link string name'
a = query.filter('link = ', link1)
aa = a.fetch(1000)##how would i get more than 1000 for a given link1 as shown?
##keybased over 1000 in other post example i need method for a subset though not key
class MyModel(db.Expando):
@classmethod
def count_all(cls):
"""
Count *all* of the rows (without maxing out at 1000)
"""
count = 0
query = cls.all().order('__key__')
while count % 1000 == 0:
current_count = query.count()
if current_count == 0:
break
count += current_count
if current_count == 1000:
last_key = query.fetch(1, 999)[0].key()
query = query.filter('__key__ > ', last_key)
return count
| [
"Wooble points out that the 1,000 entity limit is a thing of the past now, so you actually don't need to use cursors to do this - just fetch everything at once (it'll be faster than getting them in 1,000 entity batches too since there will be fewer round-trips to the datastore, etc.)\nThe removal of the 1000 entity limit was removed in version 1.3.1: http://googleappengine.blogspot.com/2010/02/app-engine-sdk-131-including-major.html\nOld solution using cursors:\nUse query cursors to fetch results beyond the first 1,000 entities:\n# continuing from your code ... get ALL of the query's results:\nmore = aa\nwhile len(more) == 1000:\n a.with_cusor(a.cursor()) # start the query where we left off\n more = a.fetch(1000) # get the next 1000 results\n aa = aa + more # copy the additional results into aa\n\n",
"The 1000-entity fetch limit was removed recently; you can fetch as many as you need, provided you can do so within the time limits. Your entities look like they'll be fairly small, so you may be able to fetch significantly more than 1000 in a request.\n"
] | [
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002907587_google_app_engine_python.txt |
Q:
Which Python XML library should I use?
I am going to handle XML files for a project. I had earlier decided to use lxml but after reading the requirements, I think ElemenTree would be better for my purpose.
The XML files that have to be processed are:
Small in size. Typically < 10 KB.
No namespaces.
Simple XML structure.
Given the small XML size, memory is not an issue. My only concern is fast parsing.
What should I go with? Mostly I have seen people recommend lxml, but given my parsing requirements, do I really stand to benefit from it or would ElementTree serve my purpose better?
A:
As others have pointed out, lxml implements the ElementTree API, so you're safe starting out with ElementTree and migrating to lxml if you need better performance or more advanced features.
The big advantage of using ElementTree, if it meets your needs, is that as of Python 2.5 it is part of the Python standard library, which cuts down on external dependencies and the (possible) headache of dealing with compiling/installing C modules.
A:
lxml is basically a superset of ElementTree so you could start with ElementTree and then if you have performance or functionality issues then you could change to lxml.
Performance issues can only be studied by you using your own data,
A:
I recommend my own recipe
XML to Python data structure « Python recipes « ActiveState Code
It does not speed up parsing. But it provides a really native object style access.
>>> SAMPLE_XML = """<?xml version="1.0" encoding="UTF-8"?>
... <address_book>
... <person gender='m'>
... <name>fred</name>
... <phone type='home'>54321</phone>
... <phone type='cell'>12345</phone>
... <note>"A<!-- comment --><![CDATA[ <note>]]>"</note>
... </person>
... </address_book>
... """
>>> address_book = xml2obj(SAMPLE_XML)
>>> person = address_book.person
person.gender -> 'm' # an attribute
person['gender'] -> 'm' # alternative dictionary syntax
person.name -> 'fred' # shortcut to a text node
person.phone[0].type -> 'home' # multiple elements becomes an list
person.phone[0].data -> '54321' # use .data to get the text value
str(person.phone[0]) -> '54321' # alternative syntax for the text value
person[0] -> person # if there are only one <person>, it can still
# be used as if it is a list of 1 element.
'address' in person -> False # test for existence of an attr or child
person.address -> None # non-exist element returns None
bool(person.address) -> False # has any 'address' data (attr, child or text)
person.note -> '"A <note>"'
| Which Python XML library should I use? | I am going to handle XML files for a project. I had earlier decided to use lxml but after reading the requirements, I think ElemenTree would be better for my purpose.
The XML files that have to be processed are:
Small in size. Typically < 10 KB.
No namespaces.
Simple XML structure.
Given the small XML size, memory is not an issue. My only concern is fast parsing.
What should I go with? Mostly I have seen people recommend lxml, but given my parsing requirements, do I really stand to benefit from it or would ElementTree serve my purpose better?
| [
"As others have pointed out, lxml implements the ElementTree API, so you're safe starting out with ElementTree and migrating to lxml if you need better performance or more advanced features.\nThe big advantage of using ElementTree, if it meets your needs, is that as of Python 2.5 it is part of the Python standard library, which cuts down on external dependencies and the (possible) headache of dealing with compiling/installing C modules.\n",
"lxml is basically a superset of ElementTree so you could start with ElementTree and then if you have performance or functionality issues then you could change to lxml.\nPerformance issues can only be studied by you using your own data,\n",
"I recommend my own recipe\nXML to Python data structure « Python recipes « ActiveState Code\nIt does not speed up parsing. But it provides a really native object style access. \n>>> SAMPLE_XML = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n... <address_book>\n... <person gender='m'>\n... <name>fred</name>\n... <phone type='home'>54321</phone>\n... <phone type='cell'>12345</phone>\n... <note>"A<!-- comment --><![CDATA[ <note>]]>"</note>\n... </person>\n... </address_book>\n... \"\"\"\n>>> address_book = xml2obj(SAMPLE_XML)\n>>> person = address_book.person\n\n\nperson.gender -> 'm' # an attribute\nperson['gender'] -> 'm' # alternative dictionary syntax\nperson.name -> 'fred' # shortcut to a text node\nperson.phone[0].type -> 'home' # multiple elements becomes an list\nperson.phone[0].data -> '54321' # use .data to get the text value\nstr(person.phone[0]) -> '54321' # alternative syntax for the text value\nperson[0] -> person # if there are only one <person>, it can still\n # be used as if it is a list of 1 element.\n'address' in person -> False # test for existence of an attr or child\nperson.address -> None # non-exist element returns None\nbool(person.address) -> False # has any 'address' data (attr, child or text)\nperson.note -> '\"A <note>\"'\n\n"
] | [
3,
0,
0
] | [] | [] | [
"celementtree",
"lxml",
"python"
] | stackoverflow_0002908440_celementtree_lxml_python.txt |
Q:
Looping through a directory on the web and displaying its contents (files and other directories) via Python
In the same vein as Process a set of files from a source directory to a destination directory in Python I'm wondering if it is possible to create a function that when given a web directory it will list out the files in said directory. Something like...
files[]
for file in urllib.listdir(dir):
if file.isdir:
# handle this as directory
else:
# handle as file
I assume I would need to use the urllib library, but there doesn't seem to be an easy way of doing this, that I've seen at least.
A:
What is a web directory?
A web page has links. The page with the links may, or may not be, generated by the web server based on the contents of the directory.
An example of automatically generating links is found here, and is possibly the result of something like mod_dir configuration in the Web server, Apache.
What tools like wget, and curl, do, is take a page and download all links on that page, possibly recursively. I think that is the best you can achieve. And I have the feeling that questions about python + curl are abundant here in SO.
A:
You may got the concept confused. Directory is file system concept. URL do not have a concept of directory. It looks similar to the path name of a file system and often maps to a directory. But there is no requirement for it to be backed by a file system.
For example, Process a set of files from a source directory to a destination directory in Python may map to a directory
/htdocs/questions/2593399/
But more likely it is generated from a database query and does not map to anything in the file system.
| Looping through a directory on the web and displaying its contents (files and other directories) via Python | In the same vein as Process a set of files from a source directory to a destination directory in Python I'm wondering if it is possible to create a function that when given a web directory it will list out the files in said directory. Something like...
files[]
for file in urllib.listdir(dir):
if file.isdir:
# handle this as directory
else:
# handle as file
I assume I would need to use the urllib library, but there doesn't seem to be an easy way of doing this, that I've seen at least.
| [
"What is a web directory? \nA web page has links. The page with the links may, or may not be, generated by the web server based on the contents of the directory. \nAn example of automatically generating links is found here, and is possibly the result of something like mod_dir configuration in the Web server, Apache.\nWhat tools like wget, and curl, do, is take a page and download all links on that page, possibly recursively. I think that is the best you can achieve. And I have the feeling that questions about python + curl are abundant here in SO.\n",
"You may got the concept confused. Directory is file system concept. URL do not have a concept of directory. It looks similar to the path name of a file system and often maps to a directory. But there is no requirement for it to be backed by a file system.\nFor example, Process a set of files from a source directory to a destination directory in Python may map to a directory\n/htdocs/questions/2593399/\nBut more likely it is generated from a database query and does not map to anything in the file system.\n"
] | [
2,
1
] | [] | [] | [
"directory",
"file",
"loops",
"python",
"urllib"
] | stackoverflow_0002907728_directory_file_loops_python_urllib.txt |
Q:
How to append a tag after a link with BeautifulSoup
Starting from an Html input like this:
<p>
<a href="http://www.foo.com">this if foo</a>
<a href="http://www.bar.com">this if bar</a>
</p>
using BeautifulSoup, i would like to change this Html in:
<p>
<a href="http://www.foo.com">this if foo</a><b>OK</b>
<a href="http://www.bar.com">this if bar</a><b>OK</b>
</p>
Is it possible to do this using BeautifulSoup?
Something like:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for link_tag in soup.findAll('a'):
link_tag = link_tag + '<b>OK</b>' #This obviously does not work
A:
You can use BeautifulSoup's insert to add the element in the right place:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for link_tag in soup.findAll('a'):
link_tag_idx = link_tag.parent.contents.index(link_tag)
link_tag.parent.insert(link_tag_idx + 1, '<b>OK</b>')
This works for the example you give, though I'm not sure it's the only or most efficient method.
A:
You have the right idea. Just match up the types, and do replaceWith.
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for link_tag in soup.findAll('a'):
link_tag.replaceWith( link_tag.prettify() + '<b>OK</b>' )
print soup
should give you:
<p>
<a href="http://www.foo.com">
this if foo
</a>
<b>OK</b>
<a href="http://www.bar.com">
this if bar
</a>
<b>OK</b>
</p>
| How to append a tag after a link with BeautifulSoup | Starting from an Html input like this:
<p>
<a href="http://www.foo.com">this if foo</a>
<a href="http://www.bar.com">this if bar</a>
</p>
using BeautifulSoup, i would like to change this Html in:
<p>
<a href="http://www.foo.com">this if foo</a><b>OK</b>
<a href="http://www.bar.com">this if bar</a><b>OK</b>
</p>
Is it possible to do this using BeautifulSoup?
Something like:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for link_tag in soup.findAll('a'):
link_tag = link_tag + '<b>OK</b>' #This obviously does not work
| [
"You can use BeautifulSoup's insert to add the element in the right place:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(html)\n\nfor link_tag in soup.findAll('a'):\n link_tag_idx = link_tag.parent.contents.index(link_tag)\n link_tag.parent.insert(link_tag_idx + 1, '<b>OK</b>')\n\nThis works for the example you give, though I'm not sure it's the only or most efficient method.\n",
"You have the right idea. Just match up the types, and do replaceWith.\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(html)\nfor link_tag in soup.findAll('a'):\n link_tag.replaceWith( link_tag.prettify() + '<b>OK</b>' )\nprint soup\n\nshould give you:\n<p>\n <a href=\"http://www.foo.com\">\nthis if foo\n</a>\n<b>OK</b>\n <a href=\"http://www.bar.com\">\nthis if bar\n</a>\n<b>OK</b>\n</p>\n\n"
] | [
8,
5
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0002908362_beautifulsoup_python.txt |
Q:
Extra characters Extracted with XPath and Python (html)
I have been using XPath with scrapy to extract text from html tags online, but when I do I get extra characters attached. An example is trying to extract a number, like "204" from a <td> tag and getting [u'204']. In some cases its much worse. For instance trying to extract "1 - Mathoverflow" and instead getting [u'\r\n\t\t 1 \u2013 MathOverflow\r\n\t\t ']. Is there a way to prevent this, or trim the strings so that the extra characters arent a part of the string? (using items to store the data). It looks like it has something to do with formatting, so how do I get xpath to not pick up that stuff?
A:
What does the line of code look like that returns [u'204']? It looks like what is being returned is a Python list containing a unicode string with the value you want. Nothing wront there--just subscript. As for the carriage returns, linefeeds and tabs, as Wai Yip Tung just answered, strip will take them out.
Probably
my_answer = item1['Title'][0].strip()
Or if you are expecting several matches
for ans_i in item1['Title']:
do_something_with( ans_i.strip() )
A:
The standard XPath function normalize-space() has exactly the wanted effect.
It deletes the leading and trailing wite space and replaces any inner whitespace with just one space.
So, you could use:
normalize-space(someExpression)
A:
Use strip() to remove the leading and trailing white spaces.
>>> u'\r\n\t\t 1 \u2013 MathOverflow\r\n\t\t '.strip()
u'1 \u2013 MathOverflow'
| Extra characters Extracted with XPath and Python (html) | I have been using XPath with scrapy to extract text from html tags online, but when I do I get extra characters attached. An example is trying to extract a number, like "204" from a <td> tag and getting [u'204']. In some cases its much worse. For instance trying to extract "1 - Mathoverflow" and instead getting [u'\r\n\t\t 1 \u2013 MathOverflow\r\n\t\t ']. Is there a way to prevent this, or trim the strings so that the extra characters arent a part of the string? (using items to store the data). It looks like it has something to do with formatting, so how do I get xpath to not pick up that stuff?
| [
"What does the line of code look like that returns [u'204']? It looks like what is being returned is a Python list containing a unicode string with the value you want. Nothing wront there--just subscript. As for the carriage returns, linefeeds and tabs, as Wai Yip Tung just answered, strip will take them out.\nProbably \nmy_answer = item1['Title'][0].strip()\n\nOr if you are expecting several matches\nfor ans_i in item1['Title']:\n do_something_with( ans_i.strip() )\n\n",
"The standard XPath function normalize-space() has exactly the wanted effect.\nIt deletes the leading and trailing wite space and replaces any inner whitespace with just one space.\nSo, you could use:\nnormalize-space(someExpression)\n",
"Use strip() to remove the leading and trailing white spaces.\n>>> u'\\r\\n\\t\\t 1 \\u2013 MathOverflow\\r\\n\\t\\t '.strip()\nu'1 \\u2013 MathOverflow'\n\n"
] | [
2,
2,
1
] | [] | [] | [
"html",
"python",
"scrapy"
] | stackoverflow_0002909067_html_python_scrapy.txt |
Q:
This is my current way of writing to a file. However, I can't do UTF-8?
f = open("go.txt", "w")
f.write(title)
f.close()
What if "title" is in japanese/utf-8? How do I modify this code to be able to write "title" without having the ascii error?
Edit: Then, how do I read this file in UTF-8?
A:
How to use UTF-8:
import codecs
# ...
# title is a unicode string
# ...
f = codecs.open("go.txt", "w", "utf-8")
f.write(title)
# ...
fileObj = codecs.open("go.txt", "r", "utf-8")
u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file
A:
It depends on whether you want to insert a Unicode UTF-8 byte order mark, of which the only way I know of is to open a normal file and write:
import codecs
f = open('go.txt', 'wb')
f.write(codecs.BOM_UTF8)
f.write(title.encode('utf-8')
f.close()
Generally though, I don't want to add a UTF-8 BOM and the following will suffice though:
import codecs
f = codecs.open('go.txt', 'w', 'utf-8')
f.write(title)
f.close()
| This is my current way of writing to a file. However, I can't do UTF-8? | f = open("go.txt", "w")
f.write(title)
f.close()
What if "title" is in japanese/utf-8? How do I modify this code to be able to write "title" without having the ascii error?
Edit: Then, how do I read this file in UTF-8?
| [
"How to use UTF-8:\nimport codecs\n\n# ...\n# title is a unicode string\n# ...\n\nf = codecs.open(\"go.txt\", \"w\", \"utf-8\")\nf.write(title)\n\n# ...\n\nfileObj = codecs.open(\"go.txt\", \"r\", \"utf-8\")\nu = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file\n\n",
"It depends on whether you want to insert a Unicode UTF-8 byte order mark, of which the only way I know of is to open a normal file and write:\nimport codecs\n\nf = open('go.txt', 'wb')\nf.write(codecs.BOM_UTF8)\nf.write(title.encode('utf-8')\nf.close()\n\nGenerally though, I don't want to add a UTF-8 BOM and the following will suffice though:\nimport codecs\n\nf = codecs.open('go.txt', 'w', 'utf-8')\nf.write(title)\nf.close()\n\n"
] | [
2,
2
] | [] | [] | [
"encoding",
"file",
"python",
"utf_8"
] | stackoverflow_0002909386_encoding_file_python_utf_8.txt |
Q:
Python adding elements from string
I have a string like this "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1".
How to add elements to each other in python ?
I've tried :
list = []
for x in str.replace(' ', ''):
list.append(x)
sum = 0
for y in list:
sum = sum + double(x)
but I'm getting errors constantly.
A:
print sum(float(x.replace(',', '.')) for x in str.split(' '))
outputs:
45.64
A:
The "python-esque" way of doing it:
sum([float(num) for num in str.replace(',', '.').split(' ')])
Makes a list by splitting the string by spaces, then turn each piece into a float and add them up.
A:
Let's not be so ethno-centric. ',' is a legitimate decimal point for many people. Don't replace it, adapt to it using the locale module:
>>> s = "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1"
>>> import locale
>>> locale.setlocale(0,"po")
'Polish_Poland.1250'
>>> sum(map(locale.atof, s.split()))
45.639999999999993
A:
Edit: If David's guess was right such that you need decimals:
>>> from math import fsum
>>> fsum(float(n) for n in input.replace(',', '.').split())
45.640000000000001
Note I'm using math.fsum() to preserve floating point loss.
A:
my_string = "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 "
"0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 "
"1 1 2 0,5 0,66 2 1 2 1 1 1 0 1"
my_string = my_string.replace(',', '.')
value = sum([float(n) for n in my_string.split()])
A:
If I understand what you want, then try this:
list = []
for x in str.replace(',', '.').split():
list.append(x)
sum = 0
for x in list:
sum = sum + float(x)
A:
Ok this worked :
sum(float(n) for n in str.replace(',','.').split())
| Python adding elements from string | I have a string like this "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1".
How to add elements to each other in python ?
I've tried :
list = []
for x in str.replace(' ', ''):
list.append(x)
sum = 0
for y in list:
sum = sum + double(x)
but I'm getting errors constantly.
| [
"print sum(float(x.replace(',', '.')) for x in str.split(' '))\n\noutputs:\n45.64\n\n",
"The \"python-esque\" way of doing it:\nsum([float(num) for num in str.replace(',', '.').split(' ')])\n\nMakes a list by splitting the string by spaces, then turn each piece into a float and add them up.\n",
"Let's not be so ethno-centric. ',' is a legitimate decimal point for many people. Don't replace it, adapt to it using the locale module:\n>>> s = \"1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1\"\n>>> import locale\n>>> locale.setlocale(0,\"po\")\n'Polish_Poland.1250'\n>>> sum(map(locale.atof, s.split()))\n45.639999999999993\n\n",
"Edit: If David's guess was right such that you need decimals:\n>>> from math import fsum\n>>> fsum(float(n) for n in input.replace(',', '.').split())\n45.640000000000001\n\nNote I'm using math.fsum() to preserve floating point loss.\n",
"my_string = \"1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 \"\n \"0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 \"\n \"1 1 2 0,5 0,66 2 1 2 1 1 1 0 1\"\n\nmy_string = my_string.replace(',', '.')\n\nvalue = sum([float(n) for n in my_string.split()])\n\n",
"If I understand what you want, then try this:\nlist = []\nfor x in str.replace(',', '.').split():\n list.append(x)\nsum = 0\nfor x in list:\n sum = sum + float(x)\n\n",
"Ok this worked :\nsum(float(n) for n in str.replace(',','.').split())\n\n"
] | [
7,
4,
4,
2,
2,
1,
1
] | [] | [] | [
"list",
"python",
"replace",
"string"
] | stackoverflow_0002909395_list_python_replace_string.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.