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:
How to get the contents of a field instead of `<bound method...` in a CSV output with Python (pytwist)
The snippet below is generating "weird" output:
for s in servers:
vo = ss.getServerVO(s)
values = []
for f in voFields:
attribValue = getattr(vo, f)
values.append(attribValue)
customValues = ss.getCustomFields(s)
for f in customFields:
values.append(customValues[f])
# Convert all values to string before writing
values = map(str, values)
csvFile.writerow( values )
For some - not all - items in the customFields dictionary, I get the following output:
<bound method ServerVO.getCreatedDate of <pytwist.com.opsware.server.ServerVO instance at 0x3da8680>>
What do I need to do to get the bound method to execute / put its results into my values dictionary?
(Specific context is in writing a PyTwist script against the HP Server Automation API)
A:
You could try calling the bound method if it is one:
for f, v in customFields.iteritems():
try:
v = v()
except TypeError:
pass
values.append(v)
The problem, of course, is with the design choice (by HP or whoever) to mix "accessors" with other kinds of values -- accessors are not a good Pythonic choice and should be replaced with properties (where this "call" gets automated for you where needed). This suggestion is about a possible way to work around that bad design choice.
Just trying to call, and checking for the TypeError that can result if the value is not callable (or not callable without arguments) is better than using callable or checking for a __call__ special method, because those checks would never tell you if "calling without argument" is OK. So, as usual in Python, "it's better to ask forgiveness by permission": try the operation, catch possible errors ("ask forgiveness") -- rather than try to check if the operation is permissible before attempting it ("ask permission").
|
How to get the contents of a field instead of `<bound method...` in a CSV output with Python (pytwist)
|
The snippet below is generating "weird" output:
for s in servers:
vo = ss.getServerVO(s)
values = []
for f in voFields:
attribValue = getattr(vo, f)
values.append(attribValue)
customValues = ss.getCustomFields(s)
for f in customFields:
values.append(customValues[f])
# Convert all values to string before writing
values = map(str, values)
csvFile.writerow( values )
For some - not all - items in the customFields dictionary, I get the following output:
<bound method ServerVO.getCreatedDate of <pytwist.com.opsware.server.ServerVO instance at 0x3da8680>>
What do I need to do to get the bound method to execute / put its results into my values dictionary?
(Specific context is in writing a PyTwist script against the HP Server Automation API)
|
[
"You could try calling the bound method if it is one:\nfor f, v in customFields.iteritems():\n try:\n v = v()\n except TypeError:\n pass\n values.append(v)\n\nThe problem, of course, is with the design choice (by HP or whoever) to mix \"accessors\" with other kinds of values -- accessors are not a good Pythonic choice and should be replaced with properties (where this \"call\" gets automated for you where needed). This suggestion is about a possible way to work around that bad design choice.\nJust trying to call, and checking for the TypeError that can result if the value is not callable (or not callable without arguments) is better than using callable or checking for a __call__ special method, because those checks would never tell you if \"calling without argument\" is OK. So, as usual in Python, \"it's better to ask forgiveness by permission\": try the operation, catch possible errors (\"ask forgiveness\") -- rather than try to check if the operation is permissible before attempting it (\"ask permission\").\n"
] |
[
1
] |
[] |
[] |
[
"csv",
"hpsa",
"python"
] |
stackoverflow_0002389025_csv_hpsa_python.txt
|
Q:
Declare which signals are subscribed to on DBus?
Is there a way to declare which signals are subscribed by a Python application over DBus?
In other words, is there a way to advertise through the "Introspectable" interface which signals are subscribed to. I use "D-Feet D-Bus debugger".
E.g. Application subscribes to signal X (using the add_signal_receiver method on a bus object).
A:
D-Bus clients call AddMatch on the bus daemon to register their interest in messages matching a particular pattern; most bindings add a match rule either for all signals on a particular service and object path, or for signals on a particular interface on that service and object path, when you create a proxy object.
Using dbus-monitor you can see match rules being added: try running dbus-monitor member=AddMatch and then running an application that uses D-Bus. Similarly, you can eavesdrop calls to RemoveMatch. However, there's currently no way to ask the daemon for the set of match rules currently in effect. Adding a way to ask that question would make more sense than adding a way for clients to re-advertise this, given that the daemon knows already.
A:
This is probably not possible since a signal is emitted on the bus and the application just picks out what is interesting. Subscribing is not happening inside dbus.
|
Declare which signals are subscribed to on DBus?
|
Is there a way to declare which signals are subscribed by a Python application over DBus?
In other words, is there a way to advertise through the "Introspectable" interface which signals are subscribed to. I use "D-Feet D-Bus debugger".
E.g. Application subscribes to signal X (using the add_signal_receiver method on a bus object).
|
[
"D-Bus clients call AddMatch on the bus daemon to register their interest in messages matching a particular pattern; most bindings add a match rule either for all signals on a particular service and object path, or for signals on a particular interface on that service and object path, when you create a proxy object.\nUsing dbus-monitor you can see match rules being added: try running dbus-monitor member=AddMatch and then running an application that uses D-Bus. Similarly, you can eavesdrop calls to RemoveMatch. However, there's currently no way to ask the daemon for the set of match rules currently in effect. Adding a way to ask that question would make more sense than adding a way for clients to re-advertise this, given that the daemon knows already.\n",
"This is probably not possible since a signal is emitted on the bus and the application just picks out what is interesting. Subscribing is not happening inside dbus.\n"
] |
[
4,
1
] |
[] |
[] |
[
"dbus",
"python"
] |
stackoverflow_0002240562_dbus_python.txt
|
Q:
Python string decoding issue
I am trying to parse a CSV file containing some data, mostly numeral but with some strings - which I do not know their encoding, but I do know they are in Hebrew.
Eventually I need to know the encoding so I can unicode the strings, print them, and perhaps throw them into a database later on.
I tried using Chardet, which claims the strings are Windows-1255 (cp1255) but trying to do print someString.decode('cp1255') yields the notorious error:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)
I tried every other encoding possible, to no avail. Also, the file is absolutely valid since I can open the CSV in Excel and I see the correct data.
Any idea how I can properly decode these strings?
EDIT: here is an example. One of the strings looks like this (first five letters of the Hebrew alphabet):
print repr(sampleString)
#prints:
'\xe0\xe1\xe2\xe3\xe4'
(using Python 2.6.2)
A:
This is what's happening:
sampleString is a byte string (cp1255 encoded)
sampleString.decode("cp1255") decodes (decode==bytes -> unicode string) the byte string to a unicode string
print sampleString.decode("cp1255") attempts to print the unicode string to stdout. Print has to encode the unicode string to do that (encode==unicode string -> bytes). The error that you're seeing means that the python print statement cannot write the given unicode string to the console's encoding. sys.stdout.encoding is the terminal's encoding.
So the problem is that your console does not support these characters. You should be able to tweak the console to use another encoding. The details on how to do that depends on your OS and terminal program.
Another approach would be to manually specify the encoding to use:
print sampleString.decode("cp1255").encode("utf-8")
See also:
http://wiki.python.org/moin/PrintFails
Setting the correct encoding when piping stdout in Python
A simple test program you can experiment with:
import sys
print sys.stdout.encoding
samplestring = '\xe0\xe1\xe2\xe3\xe4'
print samplestring.decode("cp1255").encode(sys.argv[1])
On my utf-8 terminal:
$ python2.6 test.py utf-8
UTF-8
אבגדה
$ python2.6 test.py latin1
UTF-8
Traceback (most recent call last):
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-4: ordinal not in range(256)
$ python2.6 test.py ascii
UTF-8
Traceback (most recent call last):
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
$ python2.6 test.py cp424
UTF-8
ABCDE
$ python2.6 test.py iso8859_8
UTF-8
�����
The error messages for latin-1 and ascii means that the unicode characters in the string cannot be represented in these encodings.
Notice the last two. I encode the unicode string to the cp424 and iso8859_8 encodings (two of the encodings listed on http://docs.python.org/library/codecs.html#standard-encodings that supports hebrew characters). I get no exception using these encodings, since the hebrew unicode characters have a representation in the encodings.
But my utf-8 terminal gets very confused when it receives bytes in a different encoding than utf-8.
In the first case (cp424), my UTF-8 terminal displays ABCDE, meaning that the utf-8 representation of A corresponds to the cp424 representation of ה, i.e. the byte value 65 means A in utf-8 and ה in cp424.
The encode method has an optional string argument you can use to specify what should happen when the encoding cannot represent a character (documentation). The supported strategies are strict (the default), ignore, replace, xmlcharref and backslashreplace. You can even add your own custom strategies.
Another test program (I print with quotes around the string to better show how ignore behaves):
import sys
samplestring = '\xe0\xe1\xe2\xe3\xe4'
print "'{0}'".format(samplestring.decode("cp1255").encode(sys.argv[1],
sys.argv[2]))
The results:
$ python2.6 test.py latin1 strict
Traceback (most recent call last):
File "test.py", line 4, in <module>
sys.argv[2]))
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-4: ordinal not in range(256)
[/tmp]
$ python2.6 test.py latin1 ignore
''
[/tmp]
$ python2.6 test.py latin1 replace
'?????'
[/tmp]
$ python2.6 test.py latin1 xmlcharrefreplace
'אבגדה'
[/tmp]
$ python2.6 test.py latin1 backslashreplace
'\u05d0\u05d1\u05d2\u05d3\u05d4'
A:
When you decode the string to unicode with someString.decode('cp1255'), you have an abstract representation of some Hebrew text in unicode. (This part happens successfully!) When you use print, you need a concrete, encoded representation in a specific encoding. It looks like your problem isn't with the decode, but with the print.
To print, either just print someString if your terminal understands cp1255 or "print someString.decode('cp1255').encode('the_encoding_your_terminal_does_understand')". If you don't need the resulting print to be readable as Hebrew, print repr(someString.decode('cp1255')) also gets you meaningful representation of the abstract unicode string.
A:
Is someString is maybe not a normal string, but a unicode string, like you would have us believe with your sampleString?
>>> print '\xe0\xe1\xe2\xe3\xe4'.decode('cp1255')
<hebrew characters>
>>> print u'\xe0\xe1\xe2\xe3\xe4'.decode('cp1255')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "[...]/encodings/cp1255.py", line 15, in decode
return codecs.charmap_decode(input,errors,decoding_table)
UnicodeEncodeError: 'ascii' codec can't encode characters [...]
A:
You're getting an encode error when printing, so most likely it's decoding fine, you just can't print out the result properly. Try running chcp 65001 at the command prompt before starting the Python code.
|
Python string decoding issue
|
I am trying to parse a CSV file containing some data, mostly numeral but with some strings - which I do not know their encoding, but I do know they are in Hebrew.
Eventually I need to know the encoding so I can unicode the strings, print them, and perhaps throw them into a database later on.
I tried using Chardet, which claims the strings are Windows-1255 (cp1255) but trying to do print someString.decode('cp1255') yields the notorious error:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)
I tried every other encoding possible, to no avail. Also, the file is absolutely valid since I can open the CSV in Excel and I see the correct data.
Any idea how I can properly decode these strings?
EDIT: here is an example. One of the strings looks like this (first five letters of the Hebrew alphabet):
print repr(sampleString)
#prints:
'\xe0\xe1\xe2\xe3\xe4'
(using Python 2.6.2)
|
[
"This is what's happening:\n\nsampleString is a byte string (cp1255 encoded)\nsampleString.decode(\"cp1255\") decodes (decode==bytes -> unicode string) the byte string to a unicode string\nprint sampleString.decode(\"cp1255\") attempts to print the unicode string to stdout. Print has to encode the unicode string to do that (encode==unicode string -> bytes). The error that you're seeing means that the python print statement cannot write the given unicode string to the console's encoding. sys.stdout.encoding is the terminal's encoding.\n\nSo the problem is that your console does not support these characters. You should be able to tweak the console to use another encoding. The details on how to do that depends on your OS and terminal program.\nAnother approach would be to manually specify the encoding to use:\nprint sampleString.decode(\"cp1255\").encode(\"utf-8\")\n\nSee also: \n\nhttp://wiki.python.org/moin/PrintFails\nSetting the correct encoding when piping stdout in Python\n\nA simple test program you can experiment with:\nimport sys\nprint sys.stdout.encoding\nsamplestring = '\\xe0\\xe1\\xe2\\xe3\\xe4'\nprint samplestring.decode(\"cp1255\").encode(sys.argv[1])\n\nOn my utf-8 terminal:\n$ python2.6 test.py utf-8\nUTF-8\nאבגדה\n\n$ python2.6 test.py latin1\nUTF-8\nTraceback (most recent call last):\nUnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-4: ordinal not in range(256)\n\n$ python2.6 test.py ascii\nUTF-8\nTraceback (most recent call last):\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)\n\n$ python2.6 test.py cp424\nUTF-8\nABCDE\n\n$ python2.6 test.py iso8859_8\nUTF-8\n�����\n\nThe error messages for latin-1 and ascii means that the unicode characters in the string cannot be represented in these encodings.\nNotice the last two. I encode the unicode string to the cp424 and iso8859_8 encodings (two of the encodings listed on http://docs.python.org/library/codecs.html#standard-encodings that supports hebrew characters). I get no exception using these encodings, since the hebrew unicode characters have a representation in the encodings.\nBut my utf-8 terminal gets very confused when it receives bytes in a different encoding than utf-8. \nIn the first case (cp424), my UTF-8 terminal displays ABCDE, meaning that the utf-8 representation of A corresponds to the cp424 representation of ה, i.e. the byte value 65 means A in utf-8 and ה in cp424.\nThe encode method has an optional string argument you can use to specify what should happen when the encoding cannot represent a character (documentation). The supported strategies are strict (the default), ignore, replace, xmlcharref and backslashreplace. You can even add your own custom strategies.\nAnother test program (I print with quotes around the string to better show how ignore behaves):\nimport sys\nsamplestring = '\\xe0\\xe1\\xe2\\xe3\\xe4'\nprint \"'{0}'\".format(samplestring.decode(\"cp1255\").encode(sys.argv[1], \n sys.argv[2]))\n\nThe results:\n$ python2.6 test.py latin1 strict\nTraceback (most recent call last):\n File \"test.py\", line 4, in <module>\n sys.argv[2]))\nUnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-4: ordinal not in range(256)\n[/tmp]\n$ python2.6 test.py latin1 ignore\n''\n[/tmp]\n$ python2.6 test.py latin1 replace\n'?????'\n[/tmp]\n$ python2.6 test.py latin1 xmlcharrefreplace\n'אבגדה'\n[/tmp]\n$ python2.6 test.py latin1 backslashreplace\n'\\u05d0\\u05d1\\u05d2\\u05d3\\u05d4'\n\n",
"When you decode the string to unicode with someString.decode('cp1255'), you have an abstract representation of some Hebrew text in unicode. (This part happens successfully!) When you use print, you need a concrete, encoded representation in a specific encoding. It looks like your problem isn't with the decode, but with the print.\nTo print, either just print someString if your terminal understands cp1255 or \"print someString.decode('cp1255').encode('the_encoding_your_terminal_does_understand')\". If you don't need the resulting print to be readable as Hebrew, print repr(someString.decode('cp1255')) also gets you meaningful representation of the abstract unicode string.\n",
"Is someString is maybe not a normal string, but a unicode string, like you would have us believe with your sampleString?\n>>> print '\\xe0\\xe1\\xe2\\xe3\\xe4'.decode('cp1255')\n<hebrew characters>\n\n>>> print u'\\xe0\\xe1\\xe2\\xe3\\xe4'.decode('cp1255')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"[...]/encodings/cp1255.py\", line 15, in decode\n return codecs.charmap_decode(input,errors,decoding_table)\nUnicodeEncodeError: 'ascii' codec can't encode characters [...]\n\n",
"You're getting an encode error when printing, so most likely it's decoding fine, you just can't print out the result properly. Try running chcp 65001 at the command prompt before starting the Python code.\n"
] |
[
13,
3,
0,
0
] |
[] |
[] |
[
"character_encoding",
"python",
"string",
"unicode"
] |
stackoverflow_0002389410_character_encoding_python_string_unicode.txt
|
Q:
Python list entries are overridden by last appended entry
I've got this code:
def __parse(self):
for line in self.lines:
r = Record(line)
self.records[len(self.records):] = [r]
print self.records[len(self.records)-1].getValue() # Works fine!
print self.record[0].getValue() # Gives the same as
print self.record[1].getValue() # as
# ... and so on ...
print self.record[len(self.record)-1].getValue()
Now what it should do is making records out of lines of text. But when I access those list after the for-loop has completed all records give the same results for methods I call on them. When I access a record within the for-loop right after it was appended it's the right one so the Record init can't be fault. No, it's absolutely sure that the lines I put in are different! Has anyone an idea why this happens? Help would be very appreciated!
A:
You aren't appending to self.records; you are always overwriting it.
Use:
self.records.append(r)
instead.
Edit: Never mind. See Ignacio Vasquez-Abrams's comment. I would delete this answer if not for that.
A:
Does it still happen if you replace it with the following:
self.record = [Record(l) for l in self.lines]
EDIT:
Something must be wrong in Record since the code there does work, even if it makes experienced coders weep when they read it.
A:
Ahue, you have mutable objects in the shared class namespace -- a very common misconception when starting out with python. Move the initialization of records = [] in CsvSet into its __init__ function, and move record = {} into Record __init__ function. Should look like the following:
class Record:
def __init__(self,lines):
self.record = {}
self.__parse()
class CsvSet:
def __init__(self,lines):
self.records = []
self.__parse()
When you declare a mutable variable in the class area, it is shared among all instances of those classes, not created for each instance. By moving the initialization into an instance method (__init__ in this case), you are creating new mutable stores for each instance, which is what you intended.
A:
Record class is broken. You use a class variable (Record.record) instead of an instance attribute. Class variable is one for all instances and you want different self.record for each instance.
Move the:
record = {}
line = ""
lines into the constructor (indented under def __init__(self,line):)
A:
The Record class is broken, you are always returning the same object.
Without seeing the code for Record it's impossible to guess
Perhaps you are using a list or a dict as default parameter to __init__ and returning that with getValue().
Another possibility is that getValue() is returning a class attribute rather than an instance attribute
A:
Ok, so I'll post the code for the Record class for clarification, too.
class Record:
record = {}
line = ""
def __init__(self,line):
self.line = line
self.__parse()
def __parse(self):
fieldnames = ['from','to','value','error']
fields = self.line.split(',')
c = 0
for field in fields:
self.record[fieldnames[c]] = field.strip()
c+=1
self.record['from'] = datetime.datetime.strptime(self.record['from'],"%Y-%m-%d")
self.record['to'] = datetime.datetime.strptime(self.record['to'],"%Y-%m-%d")
class CsvSet:
records = []
def __init__(self,lines):
self.__parse()
def __parse(self):
for line in self.lines:
self.records.append(Record(line))
The __parse method in CsvSet is now how it was in the beginning. I changed if for debugging reasons but the result is the same. And Ignacio you're right, I startet with Python only 2 weeks ago...
|
Python list entries are overridden by last appended entry
|
I've got this code:
def __parse(self):
for line in self.lines:
r = Record(line)
self.records[len(self.records):] = [r]
print self.records[len(self.records)-1].getValue() # Works fine!
print self.record[0].getValue() # Gives the same as
print self.record[1].getValue() # as
# ... and so on ...
print self.record[len(self.record)-1].getValue()
Now what it should do is making records out of lines of text. But when I access those list after the for-loop has completed all records give the same results for methods I call on them. When I access a record within the for-loop right after it was appended it's the right one so the Record init can't be fault. No, it's absolutely sure that the lines I put in are different! Has anyone an idea why this happens? Help would be very appreciated!
|
[
"You aren't appending to self.records; you are always overwriting it.\nUse:\nself.records.append(r) \ninstead.\nEdit: Never mind. See Ignacio Vasquez-Abrams's comment. I would delete this answer if not for that.\n",
"Does it still happen if you replace it with the following:\nself.record = [Record(l) for l in self.lines]\n\nEDIT:\nSomething must be wrong in Record since the code there does work, even if it makes experienced coders weep when they read it.\n",
"Ahue, you have mutable objects in the shared class namespace -- a very common misconception when starting out with python. Move the initialization of records = [] in CsvSet into its __init__ function, and move record = {} into Record __init__ function. Should look like the following:\nclass Record:\n def __init__(self,lines):\n self.record = {}\n self.__parse()\n\nclass CsvSet:\n def __init__(self,lines):\n self.records = []\n self.__parse()\n\nWhen you declare a mutable variable in the class area, it is shared among all instances of those classes, not created for each instance. By moving the initialization into an instance method (__init__ in this case), you are creating new mutable stores for each instance, which is what you intended.\n",
"Record class is broken. You use a class variable (Record.record) instead of an instance attribute. Class variable is one for all instances and you want different self.record for each instance.\nMove the:\nrecord = {}\nline = \"\"\n\nlines into the constructor (indented under def __init__(self,line):)\n",
"The Record class is broken, you are always returning the same object.\nWithout seeing the code for Record it's impossible to guess\nPerhaps you are using a list or a dict as default parameter to __init__ and returning that with getValue().\nAnother possibility is that getValue() is returning a class attribute rather than an instance attribute\n",
"Ok, so I'll post the code for the Record class for clarification, too.\n\nclass Record:\nrecord = {}\nline = \"\"\n\ndef __init__(self,line):\n self.line = line \n self.__parse()\n\ndef __parse(self):\n fieldnames = ['from','to','value','error']\n fields = self.line.split(',')\n\n c = 0\n for field in fields:\n self.record[fieldnames[c]] = field.strip()\n c+=1\n\n self.record['from'] = datetime.datetime.strptime(self.record['from'],\"%Y-%m-%d\")\n self.record['to'] = datetime.datetime.strptime(self.record['to'],\"%Y-%m-%d\")\n\nclass CsvSet:\nrecords = []\n\ndef __init__(self,lines):\n self.__parse()\n\ndef __parse(self): \n for line in self.lines:\n self.records.append(Record(line))\n\n\nThe __parse method in CsvSet is now how it was in the beginning. I changed if for debugging reasons but the result is the same. And Ignacio you're right, I startet with Python only 2 weeks ago...\n"
] |
[
1,
1,
1,
1,
0,
0
] |
[] |
[] |
[
"append",
"list",
"python"
] |
stackoverflow_0002389094_append_list_python.txt
|
Q:
python: inheriting or composition
Let's say that I have class, that uses some functionality of dict. I used to composite a dict object inside and provide some access from the outside, but recently thought about simply inheriting dict and adding some attributes and methods that I might require. Is it a good way to go, or should I stick to composition?
A:
Inheritance is very often abused. Unless your class is meant to be used as a generic dictionary with extra functionality, I would say composition is the way to go.
Saving forwarding calls is usually not a good enough reason for choosing inheritance.
From the Design Pattern book:
Favor object composition over class inheritance
Ideally you shouldn't have to create
new components to achieve reuse. You
should be able to get all the
functionality you need by assembling
existing components through object
composition. But this is rarely the
case, because the set of available
components is never quite rich enough
in practice. Reuse by inheritance
makes it easier to make new components
that can be composed with old ones.
Inheritance and object composition
thus work together.
Nevertheless, our experience is that
designers overuse inheritance as a
reuse technique and designs are often
made more reusable (and simpler) by
depending more on object composition."
The entire text is here:
http://blog.platinumsolutions.com/node/129
A:
Both are good, but I'd prefer inheriting, as it will mean less code (which is always good as long as it is readable).
Dive into Python has a very relevant example.
On Python 2.2 and prior, you couldn't subclass from built ins directly, so you had to use composition.
class FileInfo(dict):
"store file metadata"
def __init__(self, filename=None):
self["name"] = filename
The first difference is that you don't need to import the UserDict module, since dict is a built-in datatype and is always available. The second is that you are inheriting from dict directly, instead of from UserDict.UserDict.
The third difference is subtle but important. Because of the way UserDict works internally, it requires you to manually call its __init__ method to properly initialize its internal data structures. dict does not work like this; it is not a wrapper, and it requires no explicit initialization.
A:
You really have to weigh out the cost and scope of what you're trying to do. Inheriting from dict because you want dictionary-like behavior is quick and easy but prone to limitations such as causing objects created from your class to be unhashable.
So for example, if you are going to need to serialize (i.e. pickle) the objects, but also want dictionary-like behavior, then obviously you can't inherit directly from dict and you'll need to compose the parts of the functionality you desire to make that happen.
A:
Should isinstance(my_object, dict) return True or False? In other words, if you accidentally give one of the objects to something that wants a dict, should it blithely try to use it as a dict? Probably not, so use composition.
|
python: inheriting or composition
|
Let's say that I have class, that uses some functionality of dict. I used to composite a dict object inside and provide some access from the outside, but recently thought about simply inheriting dict and adding some attributes and methods that I might require. Is it a good way to go, or should I stick to composition?
|
[
"Inheritance is very often abused. Unless your class is meant to be used as a generic dictionary with extra functionality, I would say composition is the way to go.\nSaving forwarding calls is usually not a good enough reason for choosing inheritance.\nFrom the Design Pattern book:\n\nFavor object composition over class inheritance\nIdeally you shouldn't have to create\n new components to achieve reuse. You \n should be able to get all the\n functionality you need by assembling\n existing components through object\n composition. But this is rarely the\n case, because the set of available\n components is never quite rich enough\n in practice. Reuse by inheritance\n makes it easier to make new components\n that can be composed with old ones.\n Inheritance and object composition\n thus work together.\nNevertheless, our experience is that\n designers overuse inheritance as a\n reuse technique and designs are often\n made more reusable (and simpler) by\n depending more on object composition.\"\n\nThe entire text is here:\nhttp://blog.platinumsolutions.com/node/129\n",
"Both are good, but I'd prefer inheriting, as it will mean less code (which is always good as long as it is readable).\nDive into Python has a very relevant example.\nOn Python 2.2 and prior, you couldn't subclass from built ins directly, so you had to use composition.\n\nclass FileInfo(dict): \n \"store file metadata\"\n def __init__(self, filename=None): \n self[\"name\"] = filename\n\n\nThe first difference is that you don't need to import the UserDict module, since dict is a built-in datatype and is always available. The second is that you are inheriting from dict directly, instead of from UserDict.UserDict.\nThe third difference is subtle but important. Because of the way UserDict works internally, it requires you to manually call its __init__ method to properly initialize its internal data structures. dict does not work like this; it is not a wrapper, and it requires no explicit initialization.\n\n\n",
"You really have to weigh out the cost and scope of what you're trying to do. Inheriting from dict because you want dictionary-like behavior is quick and easy but prone to limitations such as causing objects created from your class to be unhashable.\nSo for example, if you are going to need to serialize (i.e. pickle) the objects, but also want dictionary-like behavior, then obviously you can't inherit directly from dict and you'll need to compose the parts of the functionality you desire to make that happen.\n",
"Should isinstance(my_object, dict) return True or False? In other words, if you accidentally give one of the objects to something that wants a dict, should it blithely try to use it as a dict? Probably not, so use composition.\n"
] |
[
14,
3,
3,
3
] |
[] |
[] |
[
"composition",
"dictionary",
"inheritance",
"python"
] |
stackoverflow_0002389816_composition_dictionary_inheritance_python.txt
|
Q:
Logging in worker threads spawned from a pylons application does not seem to work
I have a pylons application where, under certain cirumstances I want to spawn multiple worker threads to process items in a queue. Right now we aren't making use of a ThreadPool (would be ideal, but we'll add that in later). The main problem is that the worker threads logging does not get written to the log files.
When I run the code outside of the pylons application the logging works fine. So I think its something to do with the pylons log handler but not sure what.
Here is a basic example of the code (trimmed down):
import logging
log = logging.getLogger(__name__)
import sys
from Queue import Queue
from threading import Thread, activeCount
def run(input, worker, args = None, simulteneousWorkerLimit = None):
queue = Queue()
threads = []
if args is not None:
if len(args) > 0:
args = list(args)
args = [worker, queue] + args
args = tuple(args)
else:
args = (worker, queue)
# start threads
for i in range(4):
t = Thread(target = __thread, args = args)
t.daemon = True
t.start()
threads.append(t)
# add ThreadTermSignal
inputData = list(input)
inputData.extend([ThreadTermSignal] * 4)
# put in the queue
for data in inputData:
queue.put(data)
# block until all contents are downloaded
queue.join()
log.critical("** A log line that appears fine **")
del queue
for thread in threads:
del thread
del threads
class ThreadTermSignal(object):
pass
def __thread(worker, queue, *args):
try:
while True:
data = queue.get()
if data is ThreadTermSignal:
sys.exit()
try:
log.critical("** I don't appear when run under pylons **")
finally:
queue.task_done()
except SystemExit:
queue.task_done()
pass
Take note, that the log lin within the RUN method will show up in the log files, but the log line within the worker method (which is run in a spawned thread), does not appear. Any help would be appreciated. Thanks
** EDIT: I should mention that I tried passing in the "log" variable to the worker thread as well as redefining a new "log" variable within the thread and neither worked.
** EDIT: Adding the configuration used for the pylons application (which comes out of the INI file). So the snippet below is from the INI file.
[loggers]
keys = root
[handlers]
keys = wsgierrors
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = wsgierrors
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = WARNING
formatter = generic
[handler_wsgierrors]
class = pylons.log.WSGIErrorsHandler
args = ()
level = WARNING
format = generic
A:
One thing to note about logging is that if an exception occurs while emitting a log event (for whatever reason) the exception is typically swallowed, and not allowed to potentially bring down an application just because of a logging error. (It depends on the handlers used and the value of logging.raiseExceptions). So there are a couple of things to check:
That your formatting of log messages is dead simple, perhaps just using %(message)s until you find the problem.
Check that Pylons hasn't turned logging off or messed with the handlers for whatever reason. You haven't posted your logging initialization code so I'm not sure what handlers, etc. you're using. You can print log.getEffectiveLevel() to see if logging verbosity has been turned right down (unlikely for CRITICAL, but you never know).
If you put in print statements alongside your log statements, do they produce output how you'd expect them to?
Update: I'm aware of the restriction about mod_wsgi and printing, but that only applies to sys.stdout. You can e.g.
print >> sys.stderr, some_data
or
print >> open('/tmp/somefile', 'a'), some_data
without any problem.
Also: you should be aware that a call to logging.config.fileConfig() (which is presumably how the configuration you described is implemented) disables any existing loggers unless they are explicitly named in, or are descendants of loggers explicitly named in, the configuration file. While this might seem odd, it's because a configuration is intended to replace any existing configuration rather than augment it; and since threads might be pointing to existing loggers, they're disabled rather than deleted. You can check a logger's disabled attribute to see if fileConfig() has disabled the logger - that could be your problem.
A:
You can try to pass a log variable to the thread through the arguments(args).
|
Logging in worker threads spawned from a pylons application does not seem to work
|
I have a pylons application where, under certain cirumstances I want to spawn multiple worker threads to process items in a queue. Right now we aren't making use of a ThreadPool (would be ideal, but we'll add that in later). The main problem is that the worker threads logging does not get written to the log files.
When I run the code outside of the pylons application the logging works fine. So I think its something to do with the pylons log handler but not sure what.
Here is a basic example of the code (trimmed down):
import logging
log = logging.getLogger(__name__)
import sys
from Queue import Queue
from threading import Thread, activeCount
def run(input, worker, args = None, simulteneousWorkerLimit = None):
queue = Queue()
threads = []
if args is not None:
if len(args) > 0:
args = list(args)
args = [worker, queue] + args
args = tuple(args)
else:
args = (worker, queue)
# start threads
for i in range(4):
t = Thread(target = __thread, args = args)
t.daemon = True
t.start()
threads.append(t)
# add ThreadTermSignal
inputData = list(input)
inputData.extend([ThreadTermSignal] * 4)
# put in the queue
for data in inputData:
queue.put(data)
# block until all contents are downloaded
queue.join()
log.critical("** A log line that appears fine **")
del queue
for thread in threads:
del thread
del threads
class ThreadTermSignal(object):
pass
def __thread(worker, queue, *args):
try:
while True:
data = queue.get()
if data is ThreadTermSignal:
sys.exit()
try:
log.critical("** I don't appear when run under pylons **")
finally:
queue.task_done()
except SystemExit:
queue.task_done()
pass
Take note, that the log lin within the RUN method will show up in the log files, but the log line within the worker method (which is run in a spawned thread), does not appear. Any help would be appreciated. Thanks
** EDIT: I should mention that I tried passing in the "log" variable to the worker thread as well as redefining a new "log" variable within the thread and neither worked.
** EDIT: Adding the configuration used for the pylons application (which comes out of the INI file). So the snippet below is from the INI file.
[loggers]
keys = root
[handlers]
keys = wsgierrors
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = wsgierrors
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = WARNING
formatter = generic
[handler_wsgierrors]
class = pylons.log.WSGIErrorsHandler
args = ()
level = WARNING
format = generic
|
[
"One thing to note about logging is that if an exception occurs while emitting a log event (for whatever reason) the exception is typically swallowed, and not allowed to potentially bring down an application just because of a logging error. (It depends on the handlers used and the value of logging.raiseExceptions). So there are a couple of things to check:\n\nThat your formatting of log messages is dead simple, perhaps just using %(message)s until you find the problem.\nCheck that Pylons hasn't turned logging off or messed with the handlers for whatever reason. You haven't posted your logging initialization code so I'm not sure what handlers, etc. you're using. You can print log.getEffectiveLevel() to see if logging verbosity has been turned right down (unlikely for CRITICAL, but you never know).\n\nIf you put in print statements alongside your log statements, do they produce output how you'd expect them to?\nUpdate: I'm aware of the restriction about mod_wsgi and printing, but that only applies to sys.stdout. You can e.g.\nprint >> sys.stderr, some_data\n\nor\nprint >> open('/tmp/somefile', 'a'), some_data\n\nwithout any problem.\nAlso: you should be aware that a call to logging.config.fileConfig() (which is presumably how the configuration you described is implemented) disables any existing loggers unless they are explicitly named in, or are descendants of loggers explicitly named in, the configuration file. While this might seem odd, it's because a configuration is intended to replace any existing configuration rather than augment it; and since threads might be pointing to existing loggers, they're disabled rather than deleted. You can check a logger's disabled attribute to see if fileConfig() has disabled the logger - that could be your problem.\n",
"You can try to pass a log variable to the thread through the arguments(args).\n"
] |
[
1,
0
] |
[] |
[] |
[
"logging",
"multithreading",
"pylons",
"python"
] |
stackoverflow_0002389106_logging_multithreading_pylons_python.txt
|
Q:
PSP class import + MySQL connect
Ok so im trying to import a class i made which connects to a MySQL database the class code is shown below:
class connection
def__init__( self ):
self.cnx = MySQLdb.connect(user='xxx',host='xxx',passwd='xxx',db='xxx')
All of the parameters for the mysql connection are correct and file containg the class is in the same directory as the PSP file. The class file is called cnx_class.py
when i run my PSP file i get 'cnx' isnt defined. My psp code is below:
<psp:file>
import cnx_class
</psp:file>
<%
cur = cnx.cursor()
cur.execute('select * from protein;')
rows = cur.fetchall()
for row in rows:
req.write`(row)`
#end
%>
any help?
A:
You are horribly, horribly confused as to how modules and classes work. Please read and work through at least the modules section and the classes section of the Python tutorial.
A:
Try replacing
cur = cnx.cursor()
with
con=cnx_class.connection()
cur=con.cnx.cursor()
You can also replace
rows = cur.fetchall()
for row in rows:
with
for row in cur.fetchall():
since cursors are iterators.
|
PSP class import + MySQL connect
|
Ok so im trying to import a class i made which connects to a MySQL database the class code is shown below:
class connection
def__init__( self ):
self.cnx = MySQLdb.connect(user='xxx',host='xxx',passwd='xxx',db='xxx')
All of the parameters for the mysql connection are correct and file containg the class is in the same directory as the PSP file. The class file is called cnx_class.py
when i run my PSP file i get 'cnx' isnt defined. My psp code is below:
<psp:file>
import cnx_class
</psp:file>
<%
cur = cnx.cursor()
cur.execute('select * from protein;')
rows = cur.fetchall()
for row in rows:
req.write`(row)`
#end
%>
any help?
|
[
"You are horribly, horribly confused as to how modules and classes work. Please read and work through at least the modules section and the classes section of the Python tutorial.\n",
"Try replacing\ncur = cnx.cursor()\n\nwith\ncon=cnx_class.connection()\ncur=con.cnx.cursor()\n\nYou can also replace\nrows = cur.fetchall()\nfor row in rows:\n\nwith\nfor row in cur.fetchall():\n\nsince cursors are iterators.\n"
] |
[
0,
0
] |
[] |
[] |
[
"class",
"mysql",
"python",
"python_server_pages"
] |
stackoverflow_0002390158_class_mysql_python_python_server_pages.txt
|
Q:
only parse a specific subtree of an XML file
I have a massive XML file. However, I'm only interested in a single small subtree of this massive tree. I want to parse this subtree, but I don't want to waste time parsing the entire massive tree when I'm going to only be using a small part of it.
Ideally, I'd want to scan through the file until I find the start of this subtree, parse the subtree until I reach the end of it, and then not even bother reading the rest of the file. Maybe even describe the subtree I'm interested in with an XPath expression. Is there a way to do this using lxml? It looks like you might be able to do something like this using the iterparse() method, but based on the docs, it looks like that doesn't produce a parsed object, which I want to use. Any suggestions?
(Using lxml is not required, but I want to use Python, and ideally I'd like it to be speedy.)
A:
I get the impression that iterparse is what you want. Looking at the section "Selective tag events" at http://lxml.de/parsing.html it seems like that gives you what you desire:
context = etree.iterparse(xmlfile, tag="yourSubTree")
action, elem = context.next()
etree.iterwalk(elem, ...)...
Seems like XPath could also work but I'd guess that XPath reads in the whole tree before returning whereas I'd expect iterparse to only walk the tree until it has a match. It would be worth profiling the two approaches.
A:
Iterparse will still require parsing everything up to the subtree you want. It might be more efficient to extract the subtree before you feed it into the parser with a regular expression. You might want to try writing a sax parser. Sax is probably slower than lxml, but it won't use much memory, so in some cases it might be better.
|
only parse a specific subtree of an XML file
|
I have a massive XML file. However, I'm only interested in a single small subtree of this massive tree. I want to parse this subtree, but I don't want to waste time parsing the entire massive tree when I'm going to only be using a small part of it.
Ideally, I'd want to scan through the file until I find the start of this subtree, parse the subtree until I reach the end of it, and then not even bother reading the rest of the file. Maybe even describe the subtree I'm interested in with an XPath expression. Is there a way to do this using lxml? It looks like you might be able to do something like this using the iterparse() method, but based on the docs, it looks like that doesn't produce a parsed object, which I want to use. Any suggestions?
(Using lxml is not required, but I want to use Python, and ideally I'd like it to be speedy.)
|
[
"I get the impression that iterparse is what you want. Looking at the section \"Selective tag events\" at http://lxml.de/parsing.html it seems like that gives you what you desire:\ncontext = etree.iterparse(xmlfile, tag=\"yourSubTree\")\naction, elem = context.next()\netree.iterwalk(elem, ...)...\n\nSeems like XPath could also work but I'd guess that XPath reads in the whole tree before returning whereas I'd expect iterparse to only walk the tree until it has a match. It would be worth profiling the two approaches.\n",
"Iterparse will still require parsing everything up to the subtree you want. It might be more efficient to extract the subtree before you feed it into the parser with a regular expression. You might want to try writing a sax parser. Sax is probably slower than lxml, but it won't use much memory, so in some cases it might be better.\n"
] |
[
1,
0
] |
[] |
[] |
[
"parsing",
"python",
"subtree",
"xml"
] |
stackoverflow_0002390611_parsing_python_subtree_xml.txt
|
Q:
Regex + Python to remove specific trailing and ending characters from value in tab delimited file
It's been years (and years) since I've done any regex, so turning to experts on here since it's likely a trivial exercise :)
I have a tab delimited file and on each line I have a certain fields that have values such as:
foo
bar
b"foo's bar"
b'bar foo'
b'carbar'
(A complete line in the file might be something like:
123\t b'bar foo' \tabc\t123\r\n
I want to get rid of all the leading b', b" and trailing ", ' from that field on every line. So given the example line above, after running the regex, I'd get:
123\t bar foo \tabc\t123\r\n
Bonus points if you can give me the python blurb to run this over the file.
A:
(^|\t)b[\"']
should match the leadings, and for the trailing:
\"'
should do it
In Python, you do:
import re
r1 = re.compile("(^|\t)b[\"']")
r2 = re.compile("[\"'](\t|$)")
then just use
r1.sub("\\1", yourString)
r2.sub("\\1", yourString)
A:
for each line you can use
re.sub(r'''(?<![^\t\n])\W*b(["'])(.*)\1\W*(?![^\t\n])''', r'\2', line)
and for bonus points:
import re
pattern = re.compile(r'''(?<![^\t\n])\W*b(["'])(.*?)\1\W*?(?![^\t\n])''')
with open('outfile', 'w') as outfile:
for line in open('infile'):
outfile.write(pattern.sub(r'\2', line))
A:
>>> "b\"foo's bar\"".replace('b"',"").replace("b'","").rstrip("\"'")
"foo's bar"
>>> "b'bar foo'".replace('b"',"").replace("b'","").rstrip("\"'")
'bar foo'
>>>
|
Regex + Python to remove specific trailing and ending characters from value in tab delimited file
|
It's been years (and years) since I've done any regex, so turning to experts on here since it's likely a trivial exercise :)
I have a tab delimited file and on each line I have a certain fields that have values such as:
foo
bar
b"foo's bar"
b'bar foo'
b'carbar'
(A complete line in the file might be something like:
123\t b'bar foo' \tabc\t123\r\n
I want to get rid of all the leading b', b" and trailing ", ' from that field on every line. So given the example line above, after running the regex, I'd get:
123\t bar foo \tabc\t123\r\n
Bonus points if you can give me the python blurb to run this over the file.
|
[
"(^|\\t)b[\\\"']\nshould match the leadings, and for the trailing:\n\\\"'\nshould do it\nIn Python, you do:\nimport re\nr1 = re.compile(\"(^|\\t)b[\\\"']\")\nr2 = re.compile(\"[\\\"'](\\t|$)\")\n\nthen just use\nr1.sub(\"\\\\1\", yourString)\nr2.sub(\"\\\\1\", yourString)\n\n",
"for each line you can use\nre.sub(r'''(?<![^\\t\\n])\\W*b([\"'])(.*)\\1\\W*(?![^\\t\\n])''', r'\\2', line)\n\nand for bonus points:\nimport re\n\npattern = re.compile(r'''(?<![^\\t\\n])\\W*b([\"'])(.*?)\\1\\W*?(?![^\\t\\n])''')\nwith open('outfile', 'w') as outfile:\n for line in open('infile'):\n outfile.write(pattern.sub(r'\\2', line))\n\n",
">>> \"b\\\"foo's bar\\\"\".replace('b\"',\"\").replace(\"b'\",\"\").rstrip(\"\\\"'\")\n\"foo's bar\"\n>>> \"b'bar foo'\".replace('b\"',\"\").replace(\"b'\",\"\").rstrip(\"\\\"'\")\n'bar foo'\n>>>\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"python",
"python_3.x",
"regex"
] |
stackoverflow_0002390501_python_python_3.x_regex.txt
|
Q:
ZODB In Real Life
Writing an app in Python, and been playing with various ORM setups and straight SQL. All of which are ugly as sin.
I have been looking at ZODB as an object store, and it looks a promising alternative... would you recommend it? What are your experiences, problems, and criticism, particularly regarding developer's perspectives, scalability, integrity, long-term maintenance and alternatives? Anyone start a project with it and ditch it? Why?
Whilst the ideas behind ZODB, Pypersyst and others are interesting, there seems to be a lack of enthusiasm around for them :(
A:
I've used ZODB for more than ten years now, in Zope and outside. It's great if your data is hierarchical. The largest data store a customer operates has maybe. I don't know, 100GB in it? Something on that order of magnitude anyway.
Here is a performance comparison against Postgres.
If you're writing a WSGI web app, these packages may be useful:
repoze.tm2 (docs)
repoze.zodbconn (docs)
A:
Compared to "any key-value store", the key features for ZODB would be automatic integration of attribute changes with real ACID transactions, and clean, "arbitrary" references to other persistent objects.
The ZODB is bigger than just the FileStorage used by default in Zope:
The RelStorage backend lets you put your data in an RDBMS which can be backed up, replicated, etc. using standard tools.
ZEO allows easy scaling of appservers and off-line jobs.
The two-phase commit support allows coordinating transactions among multiple databases, including RDBMSes (assuming that they provide a TPC-aware layer).
Easy hierarchy based on object attributes or containment: you don't need to write recursive self-joins to emulate it.
Filesystem-based BLOB support makes serving large files trivial to implement.
Overall, I'm very happy using ZODB for nearly any problem where the shape of the data is not obviously "square".
A:
I would recommend it.
I really don't have any criticisms. If it's an object store your looking for, this is the one to use. I've stored 2.5 million objects in it before and didn't feel a pinch.
A:
ZODB has been used for plenty of large databases
Most ZODB usage is/was probably Zope users who migrated away if they migrate away from Zope
Performance is not so good as relatonal database+ORM especially if you have lots of writes.
Long term maintenance is not so bad, you want to pack the database from time to time, but that can be done live.
You have to use ZEO if you are going to use more than one process with your ZODB which is quite a lot slower than using ZODB directly
I have no idea how ZODB performs on flash disks.
A:
With pickling you should be able to use any key value database in a similar fashion.
|
ZODB In Real Life
|
Writing an app in Python, and been playing with various ORM setups and straight SQL. All of which are ugly as sin.
I have been looking at ZODB as an object store, and it looks a promising alternative... would you recommend it? What are your experiences, problems, and criticism, particularly regarding developer's perspectives, scalability, integrity, long-term maintenance and alternatives? Anyone start a project with it and ditch it? Why?
Whilst the ideas behind ZODB, Pypersyst and others are interesting, there seems to be a lack of enthusiasm around for them :(
|
[
"I've used ZODB for more than ten years now, in Zope and outside. It's great if your data is hierarchical. The largest data store a customer operates has maybe. I don't know, 100GB in it? Something on that order of magnitude anyway.\nHere is a performance comparison against Postgres.\nIf you're writing a WSGI web app, these packages may be useful:\n\nrepoze.tm2 (docs)\n\nrepoze.zodbconn (docs)\n\n\n",
"Compared to \"any key-value store\", the key features for ZODB would be automatic integration of attribute changes with real ACID transactions, and clean, \"arbitrary\" references to other persistent objects.\nThe ZODB is bigger than just the FileStorage used by default in Zope:\n\nThe RelStorage backend lets you put your data in an RDBMS which can be backed up, replicated, etc. using standard tools.\nZEO allows easy scaling of appservers and off-line jobs.\nThe two-phase commit support allows coordinating transactions among multiple databases, including RDBMSes (assuming that they provide a TPC-aware layer).\nEasy hierarchy based on object attributes or containment: you don't need to write recursive self-joins to emulate it.\nFilesystem-based BLOB support makes serving large files trivial to implement.\n\nOverall, I'm very happy using ZODB for nearly any problem where the shape of the data is not obviously \"square\".\n",
"I would recommend it.\nI really don't have any criticisms. If it's an object store your looking for, this is the one to use. I've stored 2.5 million objects in it before and didn't feel a pinch.\n",
"ZODB has been used for plenty of large databases\nMost ZODB usage is/was probably Zope users who migrated away if they migrate away from Zope\nPerformance is not so good as relatonal database+ORM especially if you have lots of writes.\nLong term maintenance is not so bad, you want to pack the database from time to time, but that can be done live.\nYou have to use ZEO if you are going to use more than one process with your ZODB which is quite a lot slower than using ZODB directly\nI have no idea how ZODB performs on flash disks.\n",
"With pickling you should be able to use any key value database in a similar fashion.\n"
] |
[
27,
15,
5,
2,
0
] |
[] |
[] |
[
"python",
"zodb"
] |
stackoverflow_0002388870_python_zodb.txt
|
Q:
Python XML need help with programming error
I am having the below code.
import xml.dom.minidom
def get_a_document(name):
return xml.dom.minidom.parse(name)
doc = get_a_document("sources.xml")
sources = doc.childNodes[1]
for e in sources.childNodes:
if e.nodeType == e.ELEMENT_NODE and e.localName == "source":
for source in e.childNodes:
print source.localName
print source.nodeType
if source.nodeType == source.ELEMENT_NAME and source.localName == "language":
print source.localName
country = doc.createElement("country")
e.appendChild(country)
I am trying to read the sources.xml and add an element country. But, I am getting the below error.
AttributeError: Text instance has no attribute 'ELEMENT_NAME'
Sources.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<!--sources.xml for multilingual, follows an ID range for different type of sources. Dailies sources are merged to this list-->
<sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<source>
<id>1005001</id>
<language>Afar</language>
<status>active</status>
<tags>
<tag>language</tag>
</tags>
<title>Afar</title>
</source>
</sources>
Can someone also suggest a good tutorial for minidom library. Also, if you could suggest a better python xml library, it will be great.
Thanks
Bala
A:
What's probably happening is you're running into the nodes containing the whitespace between your tags. It's not clear what you're trying to do, but it might work if you just remove the source.nodeType == source.ELEMENT_NAME part.
A:
[DOM Text node "u'\n '", DOM Element: source at 0x709f80, DOM Text node "u'\n '"]
Every new line is treated as a separate child entity when using the xml.dom.minidom library. Unfortunately, these new lines do not contain the value e.ELEMENT_NAME value. It seems that you have realized this, but the ultimate issue is that you meant for it to be e.ELEMENT_NODE not e.ELEMENT_NAME
for e in sources.childNodes:
if e.nodeType == e.ELEMENT_NODE and e.localName == "source":
for source in e.childNodes:
if source.nodeType == e.ELEMENT_NODE and source.localName == "language":
print source.localName
print source.nodeType
print source.localName
country = doc.createElement("country")
e.appendChild(country)
Cheers,
R
|
Python XML need help with programming error
|
I am having the below code.
import xml.dom.minidom
def get_a_document(name):
return xml.dom.minidom.parse(name)
doc = get_a_document("sources.xml")
sources = doc.childNodes[1]
for e in sources.childNodes:
if e.nodeType == e.ELEMENT_NODE and e.localName == "source":
for source in e.childNodes:
print source.localName
print source.nodeType
if source.nodeType == source.ELEMENT_NAME and source.localName == "language":
print source.localName
country = doc.createElement("country")
e.appendChild(country)
I am trying to read the sources.xml and add an element country. But, I am getting the below error.
AttributeError: Text instance has no attribute 'ELEMENT_NAME'
Sources.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<!--sources.xml for multilingual, follows an ID range for different type of sources. Dailies sources are merged to this list-->
<sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<source>
<id>1005001</id>
<language>Afar</language>
<status>active</status>
<tags>
<tag>language</tag>
</tags>
<title>Afar</title>
</source>
</sources>
Can someone also suggest a good tutorial for minidom library. Also, if you could suggest a better python xml library, it will be great.
Thanks
Bala
|
[
"What's probably happening is you're running into the nodes containing the whitespace between your tags. It's not clear what you're trying to do, but it might work if you just remove the source.nodeType == source.ELEMENT_NAME part.\n",
"[DOM Text node \"u'\\n '\", DOM Element: source at 0x709f80, DOM Text node \"u'\\n '\"]\nEvery new line is treated as a separate child entity when using the xml.dom.minidom library. Unfortunately, these new lines do not contain the value e.ELEMENT_NAME value. It seems that you have realized this, but the ultimate issue is that you meant for it to be e.ELEMENT_NODE not e.ELEMENT_NAME\nfor e in sources.childNodes:\n if e.nodeType == e.ELEMENT_NODE and e.localName == \"source\":\n for source in e.childNodes:\n if source.nodeType == e.ELEMENT_NODE and source.localName == \"language\":\n print source.localName\n print source.nodeType\n print source.localName\n country = doc.createElement(\"country\")\n e.appendChild(country)\n\nCheers,\nR\n"
] |
[
1,
1
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002391037_python_xml.txt
|
Q:
How to identify what function call raise an exception in Python?
i need to identify who raise an exception to handle better str error, is there a way ?
look at my example:
try:
os.mkdir('/valid_created_dir')
os.listdir('/invalid_path')
except OSError, msg:
# here i want i way to identify who raise the exception
if is_mkdir_who_raise_an_exception:
do some things
if is_listdir_who_raise_an_exception:
do other things ..
how i can handle this, in python ?
A:
If you have completely separate tasks to execute depending on which function failed, as your code seems to show, then separate try/exec blocks, as the existing answers suggest, may be better (though you may probably need to skip the second part if the first one has failed).
If you have many things that you need to do in either case, and only a little amount of work that depends on which function failed, then separating might create a lot of duplication and repetition so the form you suggested may well be preferable. The traceback module in Python's standard library can help in this case:
import os, sys, traceback
try:
os.mkdir('/valid_created_dir')
os.listdir('/invalid_path')
except OSError, msg:
tb = sys.exc_info()[-1]
stk = traceback.extract_tb(tb, 1)
fname = stk[0][2]
print 'The failing function was', fname
Of course instead of the print you'll use if checks to decide exactly what processing to do.
A:
Wrap in "try/catch" each function individually.
try:
os.mkdir('/valid_created_dir')
except Exception,e:
## doing something,
## quite probably skipping the next try statement
try:
os.listdir('/invalid_path')
except OSError, msg:
## do something
This will help readability/comprehension anyways.
A:
How about the simple solution:
try:
os.mkdir('/valid_created_dir')
except OSError, msg:
# it_is_mkdir_whow_raise_ane_xception:
do some things
try:
os.listdir('/invalid_path')
except OSError, msg:
# it_is_listdir_who_raise_ane_xception:
do other things ..
A:
Here's the clean approach: attach additional information to the exception where it happens, and then use it in a unified place:
import os, sys
def func():
try:
os.mkdir('/dir')
except OSError, e:
if e.errno != os.errno.EEXIST:
e.action = "creating directory"
raise
try:
os.listdir('/invalid_path')
except OSError, e:
e.action = "reading directory"
raise
try:
func()
except Exception, e:
if getattr(e, "action", None):
text = "Error %s: %s" % (e.action, e)
else:
text = str(e)
sys.exit(text)
In practice, you'd want to create wrappers for functions like mkdir and listdir if you want to do this, rather than scattering small try/except blocks all over your code.
Normally, I don't find this level of detail in error messages so important (the Python message is usually plenty), but this is a clean way to do it.
|
How to identify what function call raise an exception in Python?
|
i need to identify who raise an exception to handle better str error, is there a way ?
look at my example:
try:
os.mkdir('/valid_created_dir')
os.listdir('/invalid_path')
except OSError, msg:
# here i want i way to identify who raise the exception
if is_mkdir_who_raise_an_exception:
do some things
if is_listdir_who_raise_an_exception:
do other things ..
how i can handle this, in python ?
|
[
"If you have completely separate tasks to execute depending on which function failed, as your code seems to show, then separate try/exec blocks, as the existing answers suggest, may be better (though you may probably need to skip the second part if the first one has failed).\nIf you have many things that you need to do in either case, and only a little amount of work that depends on which function failed, then separating might create a lot of duplication and repetition so the form you suggested may well be preferable. The traceback module in Python's standard library can help in this case:\nimport os, sys, traceback\n\ntry:\n os.mkdir('/valid_created_dir')\n os.listdir('/invalid_path')\nexcept OSError, msg:\n tb = sys.exc_info()[-1]\n stk = traceback.extract_tb(tb, 1)\n fname = stk[0][2]\n print 'The failing function was', fname\n\nOf course instead of the print you'll use if checks to decide exactly what processing to do.\n",
"Wrap in \"try/catch\" each function individually.\ntry:\n os.mkdir('/valid_created_dir')\nexcept Exception,e:\n ## doing something,\n ## quite probably skipping the next try statement\n\ntry:\n os.listdir('/invalid_path')\nexcept OSError, msg:\n ## do something \n\nThis will help readability/comprehension anyways.\n",
"How about the simple solution:\ntry:\n os.mkdir('/valid_created_dir')\nexcept OSError, msg:\n # it_is_mkdir_whow_raise_ane_xception:\n do some things\n\ntry:\n os.listdir('/invalid_path')\nexcept OSError, msg: \n # it_is_listdir_who_raise_ane_xception:\n do other things ..\n\n",
"Here's the clean approach: attach additional information to the exception where it happens, and then use it in a unified place:\nimport os, sys\ndef func():\n try:\n os.mkdir('/dir')\n except OSError, e:\n if e.errno != os.errno.EEXIST:\n e.action = \"creating directory\"\n raise\n\n try:\n os.listdir('/invalid_path')\n except OSError, e:\n e.action = \"reading directory\"\n raise\n\ntry:\n func()\nexcept Exception, e:\n if getattr(e, \"action\", None):\n text = \"Error %s: %s\" % (e.action, e)\n else:\n text = str(e)\n sys.exit(text)\n\nIn practice, you'd want to create wrappers for functions like mkdir and listdir if you want to do this, rather than scattering small try/except blocks all over your code.\nNormally, I don't find this level of detail in error messages so important (the Python message is usually plenty), but this is a clean way to do it.\n"
] |
[
21,
8,
1,
1
] |
[] |
[] |
[
"exception",
"python"
] |
stackoverflow_0002380073_exception_python.txt
|
Q:
How to perform a signed PUT request with OAuth in Python
How is this meant to work? Where are all the oauth_* values meant to go if not in an encoded body like a POST request? In what form do you sign it?
All the Python OAuth libraries I can find only support GET and POST. Does anyone know any that support all methods?
A:
python-oauth2 supports all HTTP verbs -- as the comment I've linked to says, and I quote,
We use PUT extensively at SimpleGeo
(our python-simplegeo package uses
python-oauth2 and PUT requests).
The python-oauth2 package's client
(oauth2.Client) simply wraps httplib2,
which supports all of the verbs AFAIK.
So were did you get the weird notion that python-oauth2 doesn't support PUT?
|
How to perform a signed PUT request with OAuth in Python
|
How is this meant to work? Where are all the oauth_* values meant to go if not in an encoded body like a POST request? In what form do you sign it?
All the Python OAuth libraries I can find only support GET and POST. Does anyone know any that support all methods?
|
[
"python-oauth2 supports all HTTP verbs -- as the comment I've linked to says, and I quote,\n\nWe use PUT extensively at SimpleGeo\n (our python-simplegeo package uses\n python-oauth2 and PUT requests).\nThe python-oauth2 package's client\n (oauth2.Client) simply wraps httplib2,\n which supports all of the verbs AFAIK.\n\nSo were did you get the weird notion that python-oauth2 doesn't support PUT?\n"
] |
[
0
] |
[] |
[] |
[
"oauth",
"python"
] |
stackoverflow_0002391018_oauth_python.txt
|
Q:
web2py - my application doesn' login
i have a web2py application and am using default/user/login to login to my application but sometimes when i login the application redirect to the login page agin and sometimes the system logged fine and there is no problem i dont know why ?
so please can anyone tell me ?
Thanks in advance
A:
I have seen something like this happen with cookie based load balancing. The cookie was being set too late, so the user would switch frontends sometimes when they logged it.
If you have a load balancer over 2 frontends, you might see this happen 50% of the time.
Check the logs and make sure the hits are all going to the same frontend.
|
web2py - my application doesn' login
|
i have a web2py application and am using default/user/login to login to my application but sometimes when i login the application redirect to the login page agin and sometimes the system logged fine and there is no problem i dont know why ?
so please can anyone tell me ?
Thanks in advance
|
[
"I have seen something like this happen with cookie based load balancing. The cookie was being set too late, so the user would switch frontends sometimes when they logged it.\nIf you have a load balancer over 2 frontends, you might see this happen 50% of the time.\nCheck the logs and make sure the hits are all going to the same frontend.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"web2py"
] |
stackoverflow_0002126824_python_web2py.txt
|
Q:
telnetlib TypeError
I am modifying a python script to make changes en masse to a hand full of switches via telnet:
import getpass
import sys
import telnetlib
HOST = "192.168.1.1"
user = input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("User Name: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("?\n")
tn.write("exit\n")
When the script executes I receive a "TypeError: expected an object with the buffer interface" Any insight would be helpful.
A:
Per the docs, read_until's specs are (quoting, my emphasis):
Read until a given byte string,
expected, is encountered
You're not passing a byte string, in Python 3, with e.g.:
tn.read_until("User Name: ")
Instead, you're passing a text string, which in Python 3 means a Unicode string.
So, change this to
tn.read_until(b"User Name: ")
the b"..." form is one way to specify a literal byte string.
(Similarly for other such calls of course).
|
telnetlib TypeError
|
I am modifying a python script to make changes en masse to a hand full of switches via telnet:
import getpass
import sys
import telnetlib
HOST = "192.168.1.1"
user = input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("User Name: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("?\n")
tn.write("exit\n")
When the script executes I receive a "TypeError: expected an object with the buffer interface" Any insight would be helpful.
|
[
"Per the docs, read_until's specs are (quoting, my emphasis):\n\nRead until a given byte string,\n expected, is encountered\n\nYou're not passing a byte string, in Python 3, with e.g.:\ntn.read_until(\"User Name: \")\n\nInstead, you're passing a text string, which in Python 3 means a Unicode string.\nSo, change this to\ntn.read_until(b\"User Name: \")\n\nthe b\"...\" form is one way to specify a literal byte string.\n(Similarly for other such calls of course).\n"
] |
[
2
] |
[] |
[] |
[
"python",
"python_3.x",
"telnet"
] |
stackoverflow_0002388414_python_python_3.x_telnet.txt
|
Q:
Compressed xml on soappy
I'm developing an application that uses webservices in python, both sides (server and client) are developed in Python and uses SOAPpy for the webservices, but, you know, the xml is too verbose, I want to compress it, but as far as I have searched in google I can't find something helpful.
A:
You can add HTTP headers to SOAPpy call as shown here (this example sends cookies, but you can generalize it to add different headers) -- to request compression, add header Accept-Encoding: gzip. The web server (not the application server, like your "SOAPpy server" in Python, but the actual HTTP server it runs on top on, e.g. Apache) should provide the compression and have in the response a header Content-Encoding: gzip to confirm that (if that doesn't work properly, you'll have to subclass the transport class and insert compression there yourself -- I have no SOAPpy installation at hand to check).
The missing bit is, how to trick your SOAPpy.SOAPProxy into decompression of the payload before further processing -- and the right approach is once again to subclass HTTPTransport, just as for the add-header part; in the URL above, look at the line data = response.read() and consider checking the headers (to confirm that the content encoding is gzip as required) and decompressing as needed.
To deal with gzip compression and decompression, of course, you can use the zlib module of Python's standard library (not the gzip module, which adds to zlib the header metadata processing to make and read .gz files -- you're not dealing with .gz files but with streams compressed with the gzip algorithm, and that's zlib's job).
|
Compressed xml on soappy
|
I'm developing an application that uses webservices in python, both sides (server and client) are developed in Python and uses SOAPpy for the webservices, but, you know, the xml is too verbose, I want to compress it, but as far as I have searched in google I can't find something helpful.
|
[
"You can add HTTP headers to SOAPpy call as shown here (this example sends cookies, but you can generalize it to add different headers) -- to request compression, add header Accept-Encoding: gzip. The web server (not the application server, like your \"SOAPpy server\" in Python, but the actual HTTP server it runs on top on, e.g. Apache) should provide the compression and have in the response a header Content-Encoding: gzip to confirm that (if that doesn't work properly, you'll have to subclass the transport class and insert compression there yourself -- I have no SOAPpy installation at hand to check).\nThe missing bit is, how to trick your SOAPpy.SOAPProxy into decompression of the payload before further processing -- and the right approach is once again to subclass HTTPTransport, just as for the add-header part; in the URL above, look at the line data = response.read() and consider checking the headers (to confirm that the content encoding is gzip as required) and decompressing as needed.\nTo deal with gzip compression and decompression, of course, you can use the zlib module of Python's standard library (not the gzip module, which adds to zlib the header metadata processing to make and read .gz files -- you're not dealing with .gz files but with streams compressed with the gzip algorithm, and that's zlib's job).\n"
] |
[
2
] |
[] |
[] |
[
"compression",
"python",
"soappy",
"web_services"
] |
stackoverflow_0002390184_compression_python_soappy_web_services.txt
|
Q:
Models in database speed vs static dictionaries speed
I have a need for some kind of information that is in essence static. There is not much of this information, but alot of objects will use that information.
Since there is not a lot of that information (few dictionaries and some lists), I thought that I have 2 options - create models for holding that information in the database or write them as dictionaries/lists to some settings file. My question is - which is faster, to read that information from the database or from a settings file? In either case I need to be able to access that information in lot of places, which would mean alot of database read calls. So which would be faster?
A:
If they're truly never, ever going to change, then feel free to put them in your settings.py file as you would declare a normal Python dictionary.
However, if you want your information to be modifiable through the normal Django methods, then use the database for persistent storage, and then make the most of Django's cache framework.
Save your data to the database as normal, and then the first time it is accessed, cache them:
from django.core.cache import cache
def some_view_that_accesses_date(request):
my_data = cache.get('some_key')
if my_data is None:
my_data = MyObject.objects.all()
cache.set('some_key', my_data)
... snip ... normal view code
Make sure never to save None in a cache, as:
We advise against storing the literal
value None in the cache, because you
won't be able to distinguish between
your stored None value and a cache
miss signified by a return value of
None.
Make sure you kill the cache on object deletion or change:
from django.core.cache import cache
from django.db.models.signals import post_save
from myapp.models import MyModel
def kill_object_cache(sender, **kwargs):
cache.delete('some_key')
post_save.connect(kill_object_cache, sender=MyModel)
post_delete.connect(kill_object_cache, sender=MyModel)
I've got something similar to this in one of my apps, and it works great. Obviously you won't see any performance improvements if you then go and use the database backend, but this is a more Django-like (Djangonic?) approach than using memcached directly.
Obviously it's probably worth defining the cache key some_key somewhere, rather than littering it all over your code, the examples above are just intended to be easy to follow, rather than necessarily full-blown implementations of caching.
A:
If the data is static, there is no need to keep going back to the database. Just read it the first time it is required and cache the result.
If there is some reason you can't cache the result in your app, you can always use memcached to avoid hitting the database.
The advantage of using memcached is that if the data does change, you can simply update the value in memcached.
Pseudocode for using memcached
if 'foo' in memcached
data = memcached.get('foo')
else
data = database.get('foo')
memcached.put('foo', data)
A:
If you need fast access from multiple processes, then a database is the best option for you.
However, if you just want to keep data in memory and access it from multiple places in the same process, then Python dictionaries will be faster than accessing a DB.
|
Models in database speed vs static dictionaries speed
|
I have a need for some kind of information that is in essence static. There is not much of this information, but alot of objects will use that information.
Since there is not a lot of that information (few dictionaries and some lists), I thought that I have 2 options - create models for holding that information in the database or write them as dictionaries/lists to some settings file. My question is - which is faster, to read that information from the database or from a settings file? In either case I need to be able to access that information in lot of places, which would mean alot of database read calls. So which would be faster?
|
[
"If they're truly never, ever going to change, then feel free to put them in your settings.py file as you would declare a normal Python dictionary.\nHowever, if you want your information to be modifiable through the normal Django methods, then use the database for persistent storage, and then make the most of Django's cache framework.\nSave your data to the database as normal, and then the first time it is accessed, cache them:\nfrom django.core.cache import cache\n\ndef some_view_that_accesses_date(request):\n my_data = cache.get('some_key')\n\n if my_data is None:\n my_data = MyObject.objects.all()\n cache.set('some_key', my_data)\n\n ... snip ... normal view code\n\nMake sure never to save None in a cache, as:\n\nWe advise against storing the literal\n value None in the cache, because you\n won't be able to distinguish between\n your stored None value and a cache\n miss signified by a return value of\n None.\n\nMake sure you kill the cache on object deletion or change:\nfrom django.core.cache import cache\nfrom django.db.models.signals import post_save\nfrom myapp.models import MyModel\n\ndef kill_object_cache(sender, **kwargs):\n cache.delete('some_key')\n\npost_save.connect(kill_object_cache, sender=MyModel)\npost_delete.connect(kill_object_cache, sender=MyModel)\n\nI've got something similar to this in one of my apps, and it works great. Obviously you won't see any performance improvements if you then go and use the database backend, but this is a more Django-like (Djangonic?) approach than using memcached directly.\nObviously it's probably worth defining the cache key some_key somewhere, rather than littering it all over your code, the examples above are just intended to be easy to follow, rather than necessarily full-blown implementations of caching.\n",
"If the data is static, there is no need to keep going back to the database. Just read it the first time it is required and cache the result.\nIf there is some reason you can't cache the result in your app, you can always use memcached to avoid hitting the database.\nThe advantage of using memcached is that if the data does change, you can simply update the value in memcached.\nPseudocode for using memcached\nif 'foo' in memcached\n data = memcached.get('foo')\nelse\n data = database.get('foo')\n memcached.put('foo', data)\n\n",
"If you need fast access from multiple processes, then a database is the best option for you.\nHowever, if you just want to keep data in memory and access it from multiple places in the same process, then Python dictionaries will be faster than accessing a DB.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"dictionary",
"django",
"python"
] |
stackoverflow_0002391788_dictionary_django_python.txt
|
Q:
SQLite or flat text file?
I process a lot of text/data that I exchange between Python, R, and sometimes Matlab.
My go-to is the flat text file, but also use SQLite occasionally to store the data and access from each program (not Matlab yet though). I don't use GROUPBY, AVG, etc. in SQL as much as I do these operations in R, so I don't necessarily require the database operations.
For such applications that requires exchanging data among programs to make use of available libraries in each language, is there a good rule of thumb on which data exchange format/method to use (even XML or NetCDF or HDF5)?
I know between Python -> R there is rpy or rpy2 but I was wondering about this question in a more general sense - I use many computers which all don't have rpy2 and also use a few other pieces of scientific analysis software that require access to the data at various times (the stages of processing and analysis are also separated).
A:
If all the languages support SQLite - use it. The power of SQL might not be useful to you right now, but it probably will be at some point, and it saves you having to rewrite things later when you decide you want to be able to query your data in more complicated ways.
SQLite will also probably be substantially faster if you only want to access certain bits of data in your datastore - since doing that with a flat-text file is challenging without reading the whole file in (though it's not impossible).
A:
A flat text file (e.g. in csv format) would be the most portable solution. Almost every program/library can work with this format: R and Python have good csv support and if your data set isn't too large you can even import the csv into Excel for smaller tasks.
However, text files are unhandily for larger data sets since you need to read them completely for almost all operations (depending on the structure of your data).
SQLite allows you to filter the data very easily (even without much SQL experties) and as you already mentioned can do some computation on its own (AVG, SUM, ...). Using the Firefox Plug-in SQLiteManager you can work with the DB on every computer without any installation/configuration trouble and thus easily manage your data (import/export, filter).
So I would recommend to use SQLite for larger data sets that needs a lot of filtering to extract the data that you need. For smaller data sets or if there is no need to select subsets of your data a flat (csv) text file should be fine.
|
SQLite or flat text file?
|
I process a lot of text/data that I exchange between Python, R, and sometimes Matlab.
My go-to is the flat text file, but also use SQLite occasionally to store the data and access from each program (not Matlab yet though). I don't use GROUPBY, AVG, etc. in SQL as much as I do these operations in R, so I don't necessarily require the database operations.
For such applications that requires exchanging data among programs to make use of available libraries in each language, is there a good rule of thumb on which data exchange format/method to use (even XML or NetCDF or HDF5)?
I know between Python -> R there is rpy or rpy2 but I was wondering about this question in a more general sense - I use many computers which all don't have rpy2 and also use a few other pieces of scientific analysis software that require access to the data at various times (the stages of processing and analysis are also separated).
|
[
"If all the languages support SQLite - use it. The power of SQL might not be useful to you right now, but it probably will be at some point, and it saves you having to rewrite things later when you decide you want to be able to query your data in more complicated ways.\nSQLite will also probably be substantially faster if you only want to access certain bits of data in your datastore - since doing that with a flat-text file is challenging without reading the whole file in (though it's not impossible).\n",
"A flat text file (e.g. in csv format) would be the most portable solution. Almost every program/library can work with this format: R and Python have good csv support and if your data set isn't too large you can even import the csv into Excel for smaller tasks.\nHowever, text files are unhandily for larger data sets since you need to read them completely for almost all operations (depending on the structure of your data).\nSQLite allows you to filter the data very easily (even without much SQL experties) and as you already mentioned can do some computation on its own (AVG, SUM, ...). Using the Firefox Plug-in SQLiteManager you can work with the DB on every computer without any installation/configuration trouble and thus easily manage your data (import/export, filter). \nSo I would recommend to use SQLite for larger data sets that needs a lot of filtering to extract the data that you need. For smaller data sets or if there is no need to select subsets of your data a flat (csv) text file should be fine.\n"
] |
[
15,
5
] |
[] |
[] |
[
"database",
"file_format",
"python",
"r",
"sql"
] |
stackoverflow_0002392017_database_file_format_python_r_sql.txt
|
Q:
Calculating very large exponents in python
Currently i am simulating my cryptographic scheme to test it. I have developed the code but i am stuck at one point.
I am trying to take: g**x
where
g = 256 bit number
x = 256 bit number
Python hangs at this point, i have read alot of forums, threads etcc but only come to the conclusion that python hangs, as its hard for it to process such large numbers.
any idea how can it be done? any two line piece of code, any library, anything that can be done.
A:
It's not hanging, it's just processing. It will eventually give you the answer, provided it doesn't run out of memory first.
I haven't heard of the result of such a process being used in cryptography though; usually it's the modulus of said power that matters. If it's the same in your case then you can just use the 3-argument form of pow() instead.
A:
You shouldn't try to calculate x^y directly for huge values of y - as has already been pointed out, this is pretty difficult to do (takes lots of space and processing power). You need to look at algorithms that solve the problem for you with fewer multiplication operations. Take a look at: http://en.wikipedia.org/wiki/Exponentiation_by_squaring for starters.
Modular exponentiation is also pretty well understood: http://en.wikipedia.org/wiki/Modular_exponentiation.
You will need to use a python library for large numbers, such as http://gmpy.sourceforge.net/.
If it's any help, I did modular exponentiation in C using mpir. I'll attach that code, you'll need to convert it to python of course.
int power_modn( mpz_t c, mpz_t b, mpz_t e, mpz_t n)
{
mpz_t result;
mpz_t one;
mpz_t r;
mpz_t modulus; mpz_t exponent; mpz_t base;
mpz_init(modulus); mpz_init(exponent); mpz_init(base);
mpz_init(result); mpz_init(one); mpz_init(r);
mpz_set_ui(result, 1);
mpz_set_ui(one, 1);
mpz_set(base, b);
mpz_set(exponent, e);
mpz_set(modulus, n);
while ( mpz_cmp_ui(exponent, 0) > 0 )
{
if ( mpz_mod_ui( r, exponent, 2) == 1 )
{
mpz_mul(result, result, base);
mpz_mod(result, result, modulus);
};
mpz_mul(base, base, base);
mpz_mod(base, base, modulus);
mpz_fdiv_q_ui(exponent, exponent, 2);
}
mpz_set(c, result);
return 0;
}
A:
I'm not quite sure you appreciate the sheer magnitude of what you're asking Python to do. Raising something to a power x where x is 256 bits long, is doing the equivalent of 2**256 multiplications, or 115792089237316195423570985008687907853269984665640564039457584007913129639936 multiplications. As you can imagine, this may take some time. And space, which I guarantee you don't have enough of.
|
Calculating very large exponents in python
|
Currently i am simulating my cryptographic scheme to test it. I have developed the code but i am stuck at one point.
I am trying to take: g**x
where
g = 256 bit number
x = 256 bit number
Python hangs at this point, i have read alot of forums, threads etcc but only come to the conclusion that python hangs, as its hard for it to process such large numbers.
any idea how can it be done? any two line piece of code, any library, anything that can be done.
|
[
"It's not hanging, it's just processing. It will eventually give you the answer, provided it doesn't run out of memory first.\nI haven't heard of the result of such a process being used in cryptography though; usually it's the modulus of said power that matters. If it's the same in your case then you can just use the 3-argument form of pow() instead.\n",
"You shouldn't try to calculate x^y directly for huge values of y - as has already been pointed out, this is pretty difficult to do (takes lots of space and processing power). You need to look at algorithms that solve the problem for you with fewer multiplication operations. Take a look at: http://en.wikipedia.org/wiki/Exponentiation_by_squaring for starters.\nModular exponentiation is also pretty well understood: http://en.wikipedia.org/wiki/Modular_exponentiation.\nYou will need to use a python library for large numbers, such as http://gmpy.sourceforge.net/.\nIf it's any help, I did modular exponentiation in C using mpir. I'll attach that code, you'll need to convert it to python of course.\nint power_modn( mpz_t c, mpz_t b, mpz_t e, mpz_t n)\n{\n mpz_t result;\n mpz_t one;\n mpz_t r;\n\n mpz_t modulus; mpz_t exponent; mpz_t base;\n\n mpz_init(modulus); mpz_init(exponent); mpz_init(base);\n mpz_init(result); mpz_init(one); mpz_init(r);\n\n mpz_set_ui(result, 1);\n mpz_set_ui(one, 1);\n\n mpz_set(base, b);\n mpz_set(exponent, e); \n mpz_set(modulus, n);\n\n while ( mpz_cmp_ui(exponent, 0) > 0 )\n {\n if ( mpz_mod_ui( r, exponent, 2) == 1 )\n { \n mpz_mul(result, result, base);\n mpz_mod(result, result, modulus);\n };\n mpz_mul(base, base, base);\n mpz_mod(base, base, modulus);\n mpz_fdiv_q_ui(exponent, exponent, 2);\n }\n\n mpz_set(c, result);\n return 0;\n}\n\n",
"I'm not quite sure you appreciate the sheer magnitude of what you're asking Python to do. Raising something to a power x where x is 256 bits long, is doing the equivalent of 2**256 multiplications, or 115792089237316195423570985008687907853269984665640564039457584007913129639936 multiplications. As you can imagine, this may take some time. And space, which I guarantee you don't have enough of.\n"
] |
[
15,
12,
9
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002392235_python.txt
|
Q:
python json loads and unicode
I have the following case where I get the result of UTF-8 encoded HTTP response. I want to load the response content(JSON). However I don't know why I have to do 2 json.loads so that I get the final list:
result = urllib2.urlopen(req).read()
print result, type(result)
#=> "[{\"pk\": 66, \"model\": \"core.job\", \"fields\": {\"customer\": 1, \"created_ts\": \"2010-03-06 06:33:36\", \"log\": 66, \"process\": 1, \"ended_ts\": null, \"state\": \"PENDING\", \"started_ts\": null}}]" <type 'str'>
ret = json.loads(result)
print ret , type(ret)
#=> [{"pk": 66, "model": "core.job", "fields": {"customer": 1, "created_ts": "2010-03-06 06:33:36", "log": 66, "process": 1, "ended_ts": null, "state": "PENDING", "started_ts": null}}] <type 'unicode'>
ret = json.loads(ret)
print ret , type(ret)
#=>[{u'pk': 66, u'model': u'core.job', u'fields': {u'customer': 1, u'created_ts': u'2010-03-06 06:33:36', u'log': 66, u'process': 1, u'ended_ts': None, u'state': u'PENDING', u'started_ts': None}}] <type 'list'>
Any ideas?
A:
It looks like the repr() of the JSON string is what's being returned instead of the JSON string itself. So, something is broken on the server.
|
python json loads and unicode
|
I have the following case where I get the result of UTF-8 encoded HTTP response. I want to load the response content(JSON). However I don't know why I have to do 2 json.loads so that I get the final list:
result = urllib2.urlopen(req).read()
print result, type(result)
#=> "[{\"pk\": 66, \"model\": \"core.job\", \"fields\": {\"customer\": 1, \"created_ts\": \"2010-03-06 06:33:36\", \"log\": 66, \"process\": 1, \"ended_ts\": null, \"state\": \"PENDING\", \"started_ts\": null}}]" <type 'str'>
ret = json.loads(result)
print ret , type(ret)
#=> [{"pk": 66, "model": "core.job", "fields": {"customer": 1, "created_ts": "2010-03-06 06:33:36", "log": 66, "process": 1, "ended_ts": null, "state": "PENDING", "started_ts": null}}] <type 'unicode'>
ret = json.loads(ret)
print ret , type(ret)
#=>[{u'pk': 66, u'model': u'core.job', u'fields': {u'customer': 1, u'created_ts': u'2010-03-06 06:33:36', u'log': 66, u'process': 1, u'ended_ts': None, u'state': u'PENDING', u'started_ts': None}}] <type 'list'>
Any ideas?
|
[
"It looks like the repr() of the JSON string is what's being returned instead of the JSON string itself. So, something is broken on the server.\n"
] |
[
3
] |
[] |
[] |
[
"json",
"python",
"simplejson",
"unicode",
"utf_8"
] |
stackoverflow_0002392501_json_python_simplejson_unicode_utf_8.txt
|
Q:
Figuring out duration of an event in Python
This is a very noobish question, so I apologize in advance!
I have two time stamps for start and end of the event. They are stored in as datetime.datetime in UTC. What I need to do is figure out the duration of the event.
I tried subtracting one from the other, but receive error:
Traceback (most recent call last):
02.
File '/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py', line 509, in __call__
03.
handler.post(*groups)
04.
File '/base/data/home/apps/.../3.340324527833140591/main.py', line 441, in post
05.
call_record.Duration = call_record.CallStartTime - call_record.CallEndTime
06.
File '/base/python_lib/versions/1/google/appengine/ext/db/__init__.py', line 472, in __set__
07.
value = self.validate(value)
08.
File '/base/python_lib/versions/1/google/appengine/ext/db/__init__.py', line 2322, in validate
09.
(self.name, self.data_type.__name__))
10.
BadValueError: Property Duration must be a datetime
11.
CallStartTime, CallEndTime and Duration are all db.DateTimeProperty() types in GAE.
I had previously used django timesince to display the duration, but I need to do some additional calculations to figure out avg. duration of the events.
Any suggestions or pointers at what additional info might help are greatly appreciated!
A:
Subtracting one datetime from another will give you a timedelta. You can use that to create another datetime if you need to by adding it to or subtracting it from another datetime object.
How can you represent a duration with a single datetime object, though?
A:
The difference of two datetime.datetime objects is a datetime.timedelta object:
In [2]: t1=datetime.datetime.now()
In [3]: t1
Out[3]: datetime.datetime(2010, 3, 5, 12, 34, 6, 402507)
In [4]: t2=datetime.datetime.now()
In [5]: dt=t2-t1
In [6]: dt
Out[6]: datetime.timedelta(0, 8, 911129)
timedeltas have days, seconds and microseconds attributes.
In [7]: dt.seconds
Out[7]: 8
If the timedelta spans a duration of days, then you'll need to the days to seconds too:
In [8]: dt.days*(3600*24)+dt.seconds
Out[8]: 8
For more info a timedeltas, see http://docs.python.org/library/datetime.html#timedelta-objects
A:
For stuff like this I always use time.time() that gives back a nice float and then mostly format it something like this:
import time
t1 = time.time()
someLongTakingFunction()
print "Function took %.2f" % (time.time() - t1)
This is nice for quick and dirty checks, but supposedly there are way better ways of measuring performance. 90% of the time this works all the time for me though.
|
Figuring out duration of an event in Python
|
This is a very noobish question, so I apologize in advance!
I have two time stamps for start and end of the event. They are stored in as datetime.datetime in UTC. What I need to do is figure out the duration of the event.
I tried subtracting one from the other, but receive error:
Traceback (most recent call last):
02.
File '/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py', line 509, in __call__
03.
handler.post(*groups)
04.
File '/base/data/home/apps/.../3.340324527833140591/main.py', line 441, in post
05.
call_record.Duration = call_record.CallStartTime - call_record.CallEndTime
06.
File '/base/python_lib/versions/1/google/appengine/ext/db/__init__.py', line 472, in __set__
07.
value = self.validate(value)
08.
File '/base/python_lib/versions/1/google/appengine/ext/db/__init__.py', line 2322, in validate
09.
(self.name, self.data_type.__name__))
10.
BadValueError: Property Duration must be a datetime
11.
CallStartTime, CallEndTime and Duration are all db.DateTimeProperty() types in GAE.
I had previously used django timesince to display the duration, but I need to do some additional calculations to figure out avg. duration of the events.
Any suggestions or pointers at what additional info might help are greatly appreciated!
|
[
"Subtracting one datetime from another will give you a timedelta. You can use that to create another datetime if you need to by adding it to or subtracting it from another datetime object.\nHow can you represent a duration with a single datetime object, though?\n",
"The difference of two datetime.datetime objects is a datetime.timedelta object:\nIn [2]: t1=datetime.datetime.now()\n\nIn [3]: t1\nOut[3]: datetime.datetime(2010, 3, 5, 12, 34, 6, 402507)\n\nIn [4]: t2=datetime.datetime.now()\n\nIn [5]: dt=t2-t1\n\nIn [6]: dt\nOut[6]: datetime.timedelta(0, 8, 911129)\n\ntimedeltas have days, seconds and microseconds attributes. \nIn [7]: dt.seconds\nOut[7]: 8\n\nIf the timedelta spans a duration of days, then you'll need to the days to seconds too:\nIn [8]: dt.days*(3600*24)+dt.seconds\nOut[8]: 8\n\nFor more info a timedeltas, see http://docs.python.org/library/datetime.html#timedelta-objects\n",
"For stuff like this I always use time.time() that gives back a nice float and then mostly format it something like this:\nimport time\n\nt1 = time.time()\n\nsomeLongTakingFunction()\n\nprint \"Function took %.2f\" % (time.time() - t1)\n\nThis is nice for quick and dirty checks, but supposedly there are way better ways of measuring performance. 90% of the time this works all the time for me though.\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002388486_google_app_engine_python.txt
|
Q:
Suppose I have this loop in Django...how do I display this?
{% for p in profiles %}
<div class="result">
{{ p.first_name }}
</div>
{% endfor %}
Suppose I have 1000 of these, in a huge list.
How would I make this code appear every 15 times?
<div class="menu">abc</div>
A:
Use the forloop.counter variable with divisbleby filter.
{% if forloop.counter|divisbleby:"15" %}
<div class="menu">abc</div>
{% endif %}
A:
You can use the forloop.counter value with a divisibleby filter in an if condition. See the documentation here
|
Suppose I have this loop in Django...how do I display this?
|
{% for p in profiles %}
<div class="result">
{{ p.first_name }}
</div>
{% endfor %}
Suppose I have 1000 of these, in a huge list.
How would I make this code appear every 15 times?
<div class="menu">abc</div>
|
[
"Use the forloop.counter variable with divisbleby filter.\n{% if forloop.counter|divisbleby:\"15\" %}\n <div class=\"menu\">abc</div>\n{% endif %}\n\n",
"You can use the forloop.counter value with a divisibleby filter in an if condition. See the documentation here\n"
] |
[
2,
1
] |
[] |
[] |
[
"css",
"django",
"javascript",
"python",
"templates"
] |
stackoverflow_0002392556_css_django_javascript_python_templates.txt
|
Q:
How to detect mouse and keyboard inactivity in linux
I am developing an app on python which will check for user inactivity. Is there a way to check for key press and mouse move events in linux?
A:
You could monitor the /dev/input/* files, when a key is pressed/the mouse is moved it is written to one of those files.
Try this for example:
fh = file('/dev/input/mice')
while True:
fh.read(3)
print 'Mouse moved!'
Now that I think of it, it might be better to use something like xidle to detect inactivity.
|
How to detect mouse and keyboard inactivity in linux
|
I am developing an app on python which will check for user inactivity. Is there a way to check for key press and mouse move events in linux?
|
[
"You could monitor the /dev/input/* files, when a key is pressed/the mouse is moved it is written to one of those files.\nTry this for example:\nfh = file('/dev/input/mice')\nwhile True: \n fh.read(3)\n print 'Mouse moved!'\n\nNow that I think of it, it might be better to use something like xidle to detect inactivity.\n"
] |
[
8
] |
[] |
[] |
[
"input",
"keyboard",
"linux",
"mouse",
"python"
] |
stackoverflow_0002392076_input_keyboard_linux_mouse_python.txt
|
Q:
Python, dynamically invoke script
I want to run a python script from within another. By within I mean any state changes from the child script effect the parent's state. So if a variable is set in the child, it gets changed in the parent.
Normally you could do something like
import module
But the issue is here the child script being run is an argument to the parent script, I don't think you can use import with a variable
Something like this
$python run.py child.py
This would be what I would expect to happen
#run.py
#insert magic to run argv[1]
print a
#child.py
a = 1
$python run.py child.py
1
A:
You can use the __import__ function which allows you to import a module dynamically:
module = __import__(sys.argv[1])
(You may need to remove the trailing .py or not specify it on the command line.)
From the Python documentation:
Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.
A:
While __import__ certainly executes the specified file, it also stores it in the python modules list. If you want to reexecute the same file, you'd have to do a reload.
You can also take a look at the python exec statement that could be more suited to your needs.
From Python documentation :
This statement supports dynamic execution of Python code. The first expression should evaluate to either a string, an open file object, or a code object.
|
Python, dynamically invoke script
|
I want to run a python script from within another. By within I mean any state changes from the child script effect the parent's state. So if a variable is set in the child, it gets changed in the parent.
Normally you could do something like
import module
But the issue is here the child script being run is an argument to the parent script, I don't think you can use import with a variable
Something like this
$python run.py child.py
This would be what I would expect to happen
#run.py
#insert magic to run argv[1]
print a
#child.py
a = 1
$python run.py child.py
1
|
[
"You can use the __import__ function which allows you to import a module dynamically:\nmodule = __import__(sys.argv[1])\n\n(You may need to remove the trailing .py or not specify it on the command line.)\nFrom the Python documentation:\n\nDirect use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.\n\n",
"While __import__ certainly executes the specified file, it also stores it in the python modules list. If you want to reexecute the same file, you'd have to do a reload.\nYou can also take a look at the python exec statement that could be more suited to your needs.\nFrom Python documentation :\n\nThis statement supports dynamic execution of Python code. The first expression should evaluate to either a string, an open file object, or a code object.\n\n"
] |
[
9,
2
] |
[] |
[] |
[
"command",
"python"
] |
stackoverflow_0002391099_command_python.txt
|
Q:
Python: Simple Dictionary referencing Problem
I have a simple problem that i cannot solve. I have a dictionary:
aa = {'ALA':'A'}
test = 'ALA'
I'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed.
I'm assuming i would have to use a for loop? something like...
for i in test:
if i in aa:
print i
I understrand how to referenced a dictionary:
aa['ALA']
Its taking the value from i and using it to reference aa i am having trouble with.
Thanks
James
A:
I'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed.
Do you mean this?
print aa[test]
Its taking the value from i and using it to reference aa i am having trouble with.
I don’t exactly understand why you’re iterating over the characters in the string variable test. Is this really what you want? The rest of your question suggests that it’s not.
A:
Not sure what you are trying to do, but perhaps you mean:
aa = {'ALA':'A'}
test = ['ALA'] ### note this is now a list!
for i in test:
if i in aa:
print i, aa[i] #### note i is the key, aa[i] is the value
note that you can make three different kinds of iterators from a dictionary:
aa.iteritems() # tuples of (key, value)
# ('ALA', 'A')
aa.iterkeys() # keys only -- equivalent to just making an iterator directly from aa
# 'ALA'
aa.itervalues() # items only
# 'A'
|
Python: Simple Dictionary referencing Problem
|
I have a simple problem that i cannot solve. I have a dictionary:
aa = {'ALA':'A'}
test = 'ALA'
I'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed.
I'm assuming i would have to use a for loop? something like...
for i in test:
if i in aa:
print i
I understrand how to referenced a dictionary:
aa['ALA']
Its taking the value from i and using it to reference aa i am having trouble with.
Thanks
James
|
[
"\nI'm have trouble writing code where that value from test is taken and referenced in the dictionary aa and 'A' is printed.\n\nDo you mean this?\nprint aa[test]\n\n\nIts taking the value from i and using it to reference aa i am having trouble with.\n\nI don’t exactly understand why you’re iterating over the characters in the string variable test. Is this really what you want? The rest of your question suggests that it’s not.\n",
"Not sure what you are trying to do, but perhaps you mean:\naa = {'ALA':'A'}\ntest = ['ALA'] ### note this is now a list!\n\nfor i in test:\n if i in aa:\n print i, aa[i] #### note i is the key, aa[i] is the value\n\nnote that you can make three different kinds of iterators from a dictionary:\naa.iteritems() # tuples of (key, value)\n # ('ALA', 'A')\naa.iterkeys() # keys only -- equivalent to just making an iterator directly from aa\n # 'ALA'\naa.itervalues() # items only\n # 'A'\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0002392920_dictionary_python.txt
|
Q:
Vim: sort classes in a python source file
I have a .py file with lots of classes:
class First(Second):
#code
class Third(Fourth):
#code
Is it possible to sort the definitions by class name in vim?
A:
Suggestion for manual sorting.
With a reasonable amount of classes, manual sorting is not so tedious. I also propose it since I think it makes much more sense to group superclasses together and make sure superclasses are defined before subclasses -- otherwise your module won't even be importable.
Enable folding in Vim:
set foldmethod=indent
you can open a fold with zo, close with zc. Close all in the document with zM, open all in the document with zR.
Close all folds in the document. Now each class spans only two lines, and it's easy to delete and reinsert in its proper place.
|
Vim: sort classes in a python source file
|
I have a .py file with lots of classes:
class First(Second):
#code
class Third(Fourth):
#code
Is it possible to sort the definitions by class name in vim?
|
[
"Suggestion for manual sorting.\nWith a reasonable amount of classes, manual sorting is not so tedious. I also propose it since I think it makes much more sense to group superclasses together and make sure superclasses are defined before subclasses -- otherwise your module won't even be importable.\nEnable folding in Vim:\nset foldmethod=indent\n\nyou can open a fold with zo, close with zc. Close all in the document with zM, open all in the document with zR.\nClose all folds in the document. Now each class spans only two lines, and it's easy to delete and reinsert in its proper place.\n"
] |
[
5
] |
[] |
[] |
[
"python",
"vim"
] |
stackoverflow_0002393074_python_vim.txt
|
Q:
How do you randomly generate x amount of values and store them?
I found a suggestion on a Stack Overflow topic about problems beginners should do to learn a new language. A user posted a very nice list of problems from Beginner to advanced that should help you get to know a language. One of the problems is to create a phone book, with random phone numbers and random people on the phone book, and a user should be able to search a phone number and find the person, and vice-versa.
So how do you randomly generate x amount of values and store them, without a database, specifically focusing on Python and Ruby.
A:
You need to define some more parameters before you can tackle this problem.
Are phone numbers unique to each person?
How will you store names? First name and last name in different strings? All in one string?
Do you want to support fuzzy matching?
do you want to offer reverse lookup functionality? (I.E. look up a person based on a phone number?)
In Python, you could do all of this with sets, lists, and/or dicts, but you might also look into the sqlite3 module.
To generate a random string of letters in Python you do:
import random
import string
minLength = 5 # the minimum length of the string.
maxLength = 15 # the maximum length of the string
randstring = string.join([random.choice(string.lowercase)
for i in range(random.randrange(minlength,maxlength+1))], '')
To do the same with numbers, just replace random.lowercase with [1,2,3,4,5,6,7,8,9,0]
A:
With Python, you can use the random module for generating random numbers. For storing phone numbers, names, contact etc, you can use a database, eg SQLite
|
How do you randomly generate x amount of values and store them?
|
I found a suggestion on a Stack Overflow topic about problems beginners should do to learn a new language. A user posted a very nice list of problems from Beginner to advanced that should help you get to know a language. One of the problems is to create a phone book, with random phone numbers and random people on the phone book, and a user should be able to search a phone number and find the person, and vice-versa.
So how do you randomly generate x amount of values and store them, without a database, specifically focusing on Python and Ruby.
|
[
"You need to define some more parameters before you can tackle this problem.\n\nAre phone numbers unique to each person?\nHow will you store names? First name and last name in different strings? All in one string?\nDo you want to support fuzzy matching?\ndo you want to offer reverse lookup functionality? (I.E. look up a person based on a phone number?)\n\nIn Python, you could do all of this with sets, lists, and/or dicts, but you might also look into the sqlite3 module.\nTo generate a random string of letters in Python you do:\nimport random\nimport string\n\nminLength = 5 # the minimum length of the string.\nmaxLength = 15 # the maximum length of the string\n\nrandstring = string.join([random.choice(string.lowercase)\n for i in range(random.randrange(minlength,maxlength+1))], '')\n\nTo do the same with numbers, just replace random.lowercase with [1,2,3,4,5,6,7,8,9,0]\n",
"With Python, you can use the random module for generating random numbers. For storing phone numbers, names, contact etc, you can use a database, eg SQLite\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"random",
"ruby"
] |
stackoverflow_0002393238_python_random_ruby.txt
|
Q:
Replace multiple regex string matches in a file
I am trying to replace multiple strings in a file. But in the following code, only my last key value gets replaced. How can I replace all the key,value in the file?
fp1 = open(final,"w")
data = open(initial).read()
for key, value in mydict.items():
fp1.write(re.sub(key,value, data)
fp1.close()
A:
This is one task for which regular expressions can really help:
import re
def replacemany(adict, astring):
pat = '|'.join(re.escape(s) for s in adict)
there = re.compile(pat)
def onerepl(mo): return adict[mo.group()]
return there.sub(onerepl, astring)
if __name__ == '__main__':
d = {'k1': 'zap', 'k2': 'flup'}
print replacemany(d, 'a k1, a k2 and one more k1')
Run as the main script, this prints a zap, a flup and one more zap as desired.
This focuses on strings, not files, of course -- the replacement, per se, occurs in a string-to-string transformation. The advantage of the RE-based approach is that looping is reduced: all strings to be replaced are matched in a single pass, thanks to the regular expression engine. The re.escape calls ensure that strings containing special characters are treated just as literals (no weird meanings;-), the vertical bars mean "or" in the RE pattern language, and the sub method calls the nested onerepl function for each match, passing the match-object so the .group() call easily retrieves the specific string that was just matched and needs to be replaced.
To work at file level,
with open(final, 'w') as fin:
with open(initial, 'r') as ini:
fin.write(replacemany(mydict, ini.read()))
The with statement is recommended, to ensure proper closure of the files; if you're stuck with Python 2.5, use from __future__ import with_statement at the start of your module or script to gain use of the with statement.
A:
This should be better.
fp1 = open(final,"w")
fp2 = open(initial, 'r')
data = fp2.read()
fp2.close()
for key, value in mydict.items():
data = data.replace(key, value)
fp1.write(data)
fp1.close()
A:
fp1 = open("final","w")
fp2 = open("file", 'r')
for line in fp2:
sline=line.rstrip().split()
for n,item in enumerate(sline):
if item in d:
sline[n]=d[item]
fp1.write(' '.join(sline) +"\n")
|
Replace multiple regex string matches in a file
|
I am trying to replace multiple strings in a file. But in the following code, only my last key value gets replaced. How can I replace all the key,value in the file?
fp1 = open(final,"w")
data = open(initial).read()
for key, value in mydict.items():
fp1.write(re.sub(key,value, data)
fp1.close()
|
[
"This is one task for which regular expressions can really help:\nimport re\n\ndef replacemany(adict, astring):\n pat = '|'.join(re.escape(s) for s in adict)\n there = re.compile(pat)\n def onerepl(mo): return adict[mo.group()]\n return there.sub(onerepl, astring)\n\nif __name__ == '__main__':\n d = {'k1': 'zap', 'k2': 'flup'}\n print replacemany(d, 'a k1, a k2 and one more k1')\n\nRun as the main script, this prints a zap, a flup and one more zap as desired.\nThis focuses on strings, not files, of course -- the replacement, per se, occurs in a string-to-string transformation. The advantage of the RE-based approach is that looping is reduced: all strings to be replaced are matched in a single pass, thanks to the regular expression engine. The re.escape calls ensure that strings containing special characters are treated just as literals (no weird meanings;-), the vertical bars mean \"or\" in the RE pattern language, and the sub method calls the nested onerepl function for each match, passing the match-object so the .group() call easily retrieves the specific string that was just matched and needs to be replaced.\nTo work at file level,\nwith open(final, 'w') as fin:\n with open(initial, 'r') as ini:\n fin.write(replacemany(mydict, ini.read()))\n\nThe with statement is recommended, to ensure proper closure of the files; if you're stuck with Python 2.5, use from __future__ import with_statement at the start of your module or script to gain use of the with statement.\n",
"This should be better.\nfp1 = open(final,\"w\")\nfp2 = open(initial, 'r')\ndata = fp2.read()\nfp2.close()\nfor key, value in mydict.items():\n data = data.replace(key, value)\nfp1.write(data)\nfp1.close()\n\n",
"fp1 = open(\"final\",\"w\")\nfp2 = open(\"file\", 'r')\nfor line in fp2:\n sline=line.rstrip().split()\n for n,item in enumerate(sline):\n if item in d:\n sline[n]=d[item]\n fp1.write(' '.join(sline) +\"\\n\")\n\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002392623_python.txt
|
Q:
How do I disable history in python mechanize module?
I have a web scraping script that gets new data once every minute, but over the course of a couple of days, the script ends up using 200mb or more of memory, and I found out it's because mechanize is keeping an infinite browser history for the .back() function to use.
I have looked in the docstrings, and I found the clear_history() function of the browser class, and I invoke that each time I refresh, but I still get 2-3mb higher memory usage on each page refresh. edit: Hmm, seems as if it kept doing the same thing after I called clear_history, up until I got to about 30mb worth of memory usage, then it cleared back down to 10mb or so (which is the base amount of memory my program starts up with)...any way to force this behavior on a more regular basis?
How do I keep mechanize from storing all of this info? I don't need to keep any of it. I'd like to keep my python script below 15mb memory usage.
A:
You can pass an argument history=whatever when you instantiate the Browser; the default value is None which means the browser actually instantiates the History class (to allow back and reload). The simplest approach (will give an attribute error exception if you ever do call back or reload):
class NoHistory(object):
def add(self, *a, **k): pass
def clear(self): pass
b = mechanize.Browser(history=NoHistory())
a cleaner approach would implement other methods in NoHistory to give clearer exceptions on erroneous use of the browser's back or reload, but this simple one should suffice otherwise.
Note that this is an elegant (though not well documented;-) use of the dependency injection design pattern: in a (bleah) "monkeypatching" world, the client code would be expected to overwrite b._history after the browser is instantiated, but with dependency injection you just pass in the "history" object you want to use. I've often maintained that Dependency Injection may be the most important DP that wasn't in the "gang of 4" book!-).
|
How do I disable history in python mechanize module?
|
I have a web scraping script that gets new data once every minute, but over the course of a couple of days, the script ends up using 200mb or more of memory, and I found out it's because mechanize is keeping an infinite browser history for the .back() function to use.
I have looked in the docstrings, and I found the clear_history() function of the browser class, and I invoke that each time I refresh, but I still get 2-3mb higher memory usage on each page refresh. edit: Hmm, seems as if it kept doing the same thing after I called clear_history, up until I got to about 30mb worth of memory usage, then it cleared back down to 10mb or so (which is the base amount of memory my program starts up with)...any way to force this behavior on a more regular basis?
How do I keep mechanize from storing all of this info? I don't need to keep any of it. I'd like to keep my python script below 15mb memory usage.
|
[
"You can pass an argument history=whatever when you instantiate the Browser; the default value is None which means the browser actually instantiates the History class (to allow back and reload). The simplest approach (will give an attribute error exception if you ever do call back or reload):\nclass NoHistory(object):\n def add(self, *a, **k): pass\n def clear(self): pass\n\nb = mechanize.Browser(history=NoHistory())\n\na cleaner approach would implement other methods in NoHistory to give clearer exceptions on erroneous use of the browser's back or reload, but this simple one should suffice otherwise.\nNote that this is an elegant (though not well documented;-) use of the dependency injection design pattern: in a (bleah) \"monkeypatching\" world, the client code would be expected to overwrite b._history after the browser is instantiated, but with dependency injection you just pass in the \"history\" object you want to use. I've often maintained that Dependency Injection may be the most important DP that wasn't in the \"gang of 4\" book!-).\n"
] |
[
19
] |
[] |
[] |
[
"mechanize",
"memory",
"python"
] |
stackoverflow_0002393299_mechanize_memory_python.txt
|
Q:
Python double iteration
What is the pythonic way of iterating simultaneously over two lists?
Suppose I want to compare two files line by line (compare each ith line in one file with the ith line of the other file), I would want to do something like this:
file1 = csv.reader(open(filename1),...)
file2 = csv.reader(open(filename2),...)
for line1 in file1 and line2 in file2: #pseudo-code!
if line1 != line2:
print "files are not identical"
break
What is the pythonic way of achieving this?
Edit: I am not using a file handler but rather a CSV reader (csv.reader(open(file),...)), and zip() doesn't seem to work with it...
Final edit: like @Alex M. suggested, zip() loads the files to memory on first iteration, so on big files this is an issue. On Python 2, using itertools solves the issue.
A:
In Python 2, you should import itertools and use its izip:
with open(file1) as f1:
with open(file2) as f2:
for line1, line2 in itertools.izip(f1, f2):
if line1 != line2:
print 'files are different'
break
with the built-in zip, both files will be entirely read into memory at once at the start of the loop, which may not be what you want. In Python 3, the built-in zip works like itertools.izip does in Python 2 -- incrementally.
A:
I vote for using zip. The manual suggests "To loop over two or more sequences at the same time, the entries can be paired with the zip() function"
For example,
list_one = ['nachos', 'sandwich', 'name']
list_two = ['nachos', 'sandwich', 'the game']
for one, two in zip(list_one, list_two):
if one != two:
print "Difference found"
A:
In lockstep (for Python ≥3):
for line1, line2 in zip(file1, file2):
# etc.
As a "2D array":
for line1 in file1:
for line2 in file2:
# etc.
# you may need to rewind file2 to the beginning.
|
Python double iteration
|
What is the pythonic way of iterating simultaneously over two lists?
Suppose I want to compare two files line by line (compare each ith line in one file with the ith line of the other file), I would want to do something like this:
file1 = csv.reader(open(filename1),...)
file2 = csv.reader(open(filename2),...)
for line1 in file1 and line2 in file2: #pseudo-code!
if line1 != line2:
print "files are not identical"
break
What is the pythonic way of achieving this?
Edit: I am not using a file handler but rather a CSV reader (csv.reader(open(file),...)), and zip() doesn't seem to work with it...
Final edit: like @Alex M. suggested, zip() loads the files to memory on first iteration, so on big files this is an issue. On Python 2, using itertools solves the issue.
|
[
"In Python 2, you should import itertools and use its izip:\nwith open(file1) as f1:\n with open(file2) as f2:\n for line1, line2 in itertools.izip(f1, f2):\n if line1 != line2:\n print 'files are different'\n break\n\nwith the built-in zip, both files will be entirely read into memory at once at the start of the loop, which may not be what you want. In Python 3, the built-in zip works like itertools.izip does in Python 2 -- incrementally.\n",
"I vote for using zip. The manual suggests \"To loop over two or more sequences at the same time, the entries can be paired with the zip() function\"\nFor example,\nlist_one = ['nachos', 'sandwich', 'name']\nlist_two = ['nachos', 'sandwich', 'the game']\nfor one, two in zip(list_one, list_two):\n if one != two:\n print \"Difference found\"\n\n",
"In lockstep (for Python ≥3):\nfor line1, line2 in zip(file1, file2):\n # etc.\n\nAs a \"2D array\":\nfor line1 in file1:\n for line2 in file2:\n # etc.\n # you may need to rewind file2 to the beginning.\n\n"
] |
[
16,
10,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002393444_python.txt
|
Q:
Sending MESSAGE to a person on facebook using python
I want to make a script that can be used to send messages to our friends on facebook.
How do I proceed? Which is the best module to use?
A:
You may indeed want pyfacebook as another answer suggested, though the URL I'm giving (on github.com) is where the project (esp. its source;-) actually lives.
A simple survey of Python APIs for facebook is here, and it also points to a possibly-simpler but less complete API, if you want to run in Google App Engine, i.e., simplefacebook. pyfacebook does not limit you to App Engine specifically, though it can support it of course.
A pyfacebook tutorial is here -- it even briefly shows how to use it from an interactive interpreter (!), though the bulk of the tutorial is about doing web apps, of course.
A:
PyFacebook is a Python client library for the Facebook API.
|
Sending MESSAGE to a person on facebook using python
|
I want to make a script that can be used to send messages to our friends on facebook.
How do I proceed? Which is the best module to use?
|
[
"You may indeed want pyfacebook as another answer suggested, though the URL I'm giving (on github.com) is where the project (esp. its source;-) actually lives.\nA simple survey of Python APIs for facebook is here, and it also points to a possibly-simpler but less complete API, if you want to run in Google App Engine, i.e., simplefacebook. pyfacebook does not limit you to App Engine specifically, though it can support it of course.\nA pyfacebook tutorial is here -- it even briefly shows how to use it from an interactive interpreter (!), though the bulk of the tutorial is about doing web apps, of course.\n",
"PyFacebook is a Python client library for the Facebook API.\n"
] |
[
7,
0
] |
[] |
[] |
[
"api",
"facebook",
"python",
"scripting"
] |
stackoverflow_0002392111_api_facebook_python_scripting.txt
|
Q:
Python GUI framework for Mac OS X
I'm trying to find a good "python GUI framework" for Mac OS X, but I haven't found anything good until now, only wxWidgets which I don't like and it's also unstable.
Any suggestions?
A:
I use pyqt (pyside should be equivalent but with more relaxed license terms) and I find it pleasing and useful -- I also like the fact that (with no extra effort on my part) it gives me cross-platform apps!-)
pyobjc (comes w/your Mac, works w/Xcode, etc) may be preferable for apps you never want to be cross-platform, but I find it less easily usable than PyQt. However if you're very skilled in Objective C, Cocoa etc, I imagine pyobjc will feel perfectly natural and usable to you!-).
A:
For the most MacOSX you could use PyObjc which basically allows you to write Cocoa apps i python using Interface Builder etc.
|
Python GUI framework for Mac OS X
|
I'm trying to find a good "python GUI framework" for Mac OS X, but I haven't found anything good until now, only wxWidgets which I don't like and it's also unstable.
Any suggestions?
|
[
"I use pyqt (pyside should be equivalent but with more relaxed license terms) and I find it pleasing and useful -- I also like the fact that (with no extra effort on my part) it gives me cross-platform apps!-)\npyobjc (comes w/your Mac, works w/Xcode, etc) may be preferable for apps you never want to be cross-platform, but I find it less easily usable than PyQt. However if you're very skilled in Objective C, Cocoa etc, I imagine pyobjc will feel perfectly natural and usable to you!-).\n",
"For the most MacOSX you could use PyObjc which basically allows you to write Cocoa apps i python using Interface Builder etc.\n"
] |
[
7,
3
] |
[] |
[] |
[
"macos",
"python",
"user_interface"
] |
stackoverflow_0002393514_macos_python_user_interface.txt
|
Q:
Classname same as file/module name leads to inheritance issue
My code worked fine when it was all in one file. Now, I'm splitting up classes into different modules. The modules have been given the same name as the classes. Perhaps this is a problem, because MainPage is failing when it is loaded. Does it think that I'm trying to inherit from a module? Can module/class namespace collisions happen?
MainPage.py
import BaseHandler
from models import Item
from Utils import render
class MainPage(BaseHandler):
def body(self, CSIN=None): #@UnusedVariable
self.header('Store')
items = Item.all().order('name').fetch(10)
render('Views/table.html', self, {'items': items})
self.footer()
BaseHandler.py
from google.appengine.ext import webapp
from google.appengine.api import users
from Utils import *
# Controller
class BaseHandler(webapp.RequestHandler):
# ... continues ...
Failure traceback:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3180, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3123, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 515, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2382, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2292, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2188, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "C:\Users\odp\workspace\Store\src\Main.py", line 5, in <module>
import MainPage
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1267, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1917, in load_module
return self.FindAndLoadModule(submodule, fullname, search_path)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1267, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1819, in FindAndLoadModule
description)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1267, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1770, in LoadModuleRestricted
description)
File "C:\Users\odp\workspace\Store\src\MainPage.py", line 10, in <module>
class MainPage(BaseHandler):
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
It appears this can be solved by using
from BaseHandler import BaseHandler
Is it bad style to have the module and class name be the same?
A:
Yes, module names share the same namespace as everything else, and, yes, Python thinks you are trying to inherit from a module.
Change:
class MainPage(BaseHandler):
to:
class MainPage(BaseHandler.BaseHandler):
and you should be good to go. That way, you're saying "please inherit from the BaseHandler class in the BaseHandler module".
Alternately, you could change:
import BaseHandler
to:
from BaseHandler import BaseHandler
A:
First of all the filenames should be all lowercase. That's Python convention that helps to avoid confusion such as this, at least most of the time.
Next, your import from withing MainHandler.py is wrong. You are importing BaseHandler (the module) and referencing it as if it were a class. The class is actually BaseHandler.BaseHandler. You need to reference it as such.
Try that and it should work for you.
|
Classname same as file/module name leads to inheritance issue
|
My code worked fine when it was all in one file. Now, I'm splitting up classes into different modules. The modules have been given the same name as the classes. Perhaps this is a problem, because MainPage is failing when it is loaded. Does it think that I'm trying to inherit from a module? Can module/class namespace collisions happen?
MainPage.py
import BaseHandler
from models import Item
from Utils import render
class MainPage(BaseHandler):
def body(self, CSIN=None): #@UnusedVariable
self.header('Store')
items = Item.all().order('name').fetch(10)
render('Views/table.html', self, {'items': items})
self.footer()
BaseHandler.py
from google.appengine.ext import webapp
from google.appengine.api import users
from Utils import *
# Controller
class BaseHandler(webapp.RequestHandler):
# ... continues ...
Failure traceback:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3180, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3123, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 515, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2382, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2292, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2188, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "C:\Users\odp\workspace\Store\src\Main.py", line 5, in <module>
import MainPage
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1267, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1917, in load_module
return self.FindAndLoadModule(submodule, fullname, search_path)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1267, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1819, in FindAndLoadModule
description)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1267, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1770, in LoadModuleRestricted
description)
File "C:\Users\odp\workspace\Store\src\MainPage.py", line 10, in <module>
class MainPage(BaseHandler):
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
It appears this can be solved by using
from BaseHandler import BaseHandler
Is it bad style to have the module and class name be the same?
|
[
"Yes, module names share the same namespace as everything else, and, yes, Python thinks you are trying to inherit from a module.\nChange:\nclass MainPage(BaseHandler):\n\nto:\nclass MainPage(BaseHandler.BaseHandler):\n\nand you should be good to go. That way, you're saying \"please inherit from the BaseHandler class in the BaseHandler module\".\nAlternately, you could change:\nimport BaseHandler\n\nto:\nfrom BaseHandler import BaseHandler\n\n",
"First of all the filenames should be all lowercase. That's Python convention that helps to avoid confusion such as this, at least most of the time. \nNext, your import from withing MainHandler.py is wrong. You are importing BaseHandler (the module) and referencing it as if it were a class. The class is actually BaseHandler.BaseHandler. You need to reference it as such.\nTry that and it should work for you.\n"
] |
[
18,
18
] |
[] |
[] |
[
"class",
"import",
"module",
"python"
] |
stackoverflow_0002393544_class_import_module_python.txt
|
Q:
Python: Random sequence
I have the following code:
import string
import random
d =[random.choice(string.uppercase) for x in xrange(3355)]
s = "".join(d)
print s
At the moment it prints out a random sequence of letters from the alphabet. But, i need it to print out a sequence of letters containing only four letters for example 'A', 'C', 'U', 'G'. How would this be accomplished?
Thanks
Quinn
A:
Change the set you are asking random.choice to pick from:
import random
d =[random.choice('ACUG') for x in xrange(3355)]
s = "".join(d)
print s
Edit: As SilentGhost points out, if your ultimate goal is only to make a string, skipping the intermediate list is more memory-efficient:
s = "".join(random.choice('ACUG') for x in xrange(3355))
A:
just replace string.uppercase with the sequence (list or string, for example) containing your choices.
A:
Your question is not clear. Do you mean that you want to choose a string only 4 in length? If so then do:
d =[random.choice(string.uppercase) for x in xrange(4)]
Or if you want to choose from a list of only four choices, then do:
d =[random.choice("ACUG") for x in xrange(3355)]
A:
I think the OP is wanting to pre-select a 4-character sample from string.uppercase, then create a 3355 item string based on that:
import string
import random
num_samples = 4
char_sample = random.sample(string.uppercase, num_samples)
d =[random.choice(char_sample) for x in xrange(3355)]
s = "".join(d)
print s
print char_sample
In this case, random.sample(population, sample_count) will take care of that first requirement quite nicely.
However, I agree with the other answers/comments that this question is a bit vague.
|
Python: Random sequence
|
I have the following code:
import string
import random
d =[random.choice(string.uppercase) for x in xrange(3355)]
s = "".join(d)
print s
At the moment it prints out a random sequence of letters from the alphabet. But, i need it to print out a sequence of letters containing only four letters for example 'A', 'C', 'U', 'G'. How would this be accomplished?
Thanks
Quinn
|
[
"Change the set you are asking random.choice to pick from:\nimport random\n\nd =[random.choice('ACUG') for x in xrange(3355)]\ns = \"\".join(d)\n\nprint s\n\n\nEdit: As SilentGhost points out, if your ultimate goal is only to make a string, skipping the intermediate list is more memory-efficient:\ns = \"\".join(random.choice('ACUG') for x in xrange(3355))\n\n",
"just replace string.uppercase with the sequence (list or string, for example) containing your choices.\n",
"Your question is not clear. Do you mean that you want to choose a string only 4 in length? If so then do:\nd =[random.choice(string.uppercase) for x in xrange(4)]\n\nOr if you want to choose from a list of only four choices, then do:\nd =[random.choice(\"ACUG\") for x in xrange(3355)]\n\n",
"I think the OP is wanting to pre-select a 4-character sample from string.uppercase, then create a 3355 item string based on that:\nimport string\nimport random\n\nnum_samples = 4\nchar_sample = random.sample(string.uppercase, num_samples)\nd =[random.choice(char_sample) for x in xrange(3355)]\ns = \"\".join(d)\n\nprint s\nprint char_sample\n\nIn this case, random.sample(population, sample_count) will take care of that first requirement quite nicely.\nHowever, I agree with the other answers/comments that this question is a bit vague.\n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002393851_python.txt
|
Q:
Python: File formatting
I have a for loop which references a dictionary and prints out the value associated with the key. Code is below:
for i in data:
if i in dict:
print dict[i],
How would i format the output so a new line is created every 60 characters? and with the character count along the side for example:
0001
MRQLLLISDLDNTWVGDQQALEHLQEYLGDRRGNFYLAYATGRSYHSARELQKQVGLMEP
0061
DYWLTAVGSEIYHPEGLDQHWADYLSEHWQRDILQAIADGFEALKPQSPLEQNPWKISYH
0121 LDPQACPTVIDQLTEMLKETGIPVQVIFSSGKDVDLLPQRSNKGNATQYLQQHLAMEPSQ
A:
It's a finicky formatting problem, but I think the following code:
import sys
class EveryN(object):
def __init__(self, n, outs):
self.n = n # chars/line
self.outs = outs # output stream
self.numo = 1 # next tag to write
self.tll = 0 # tot chars on this line
def write(self, s):
while True:
if self.tll == 0: # start of line: emit tag
self.outs.write('%4.4d ' % self.numo)
self.numo += self.n
# wite up to N chars/line, no more
numw = min(len(s), self.n - self.tll)
self.outs.write(s[:numw])
self.tll += numw
if self.tll >= self.n:
self.tll = 0
self.outs.write('\n')
s = s[numw:]
if not s: break
if __name__ == '__main__':
sys.stdout = EveryN(60, sys.stdout)
for i, a in enumerate('abcdefgh'):
print a*(5+ i*5),
shows how to do it -- the output when running for demonstration purposes as the main script (five a's, ten b's, etc, with spaces in-between) is:
0001 aaaaa bbbbbbbbbb ccccccccccccccc dddddddddddddddddddd eeeeee
0061 eeeeeeeeeeeeeeeeeee ffffffffffffffffffffffffffffff ggggggggg
0121 gggggggggggggggggggggggggg hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
0181 hhhhhhh
A:
It seems like you're looking for textwrap
The textwrap module provides two convenience functions, wrap() and
fill(), as well as TextWrapper, the class that does all the work, and
a utility function dedent(). If you’re just wrapping or filling one or
two text strings, the convenience functions should be good enough;
otherwise, you should use an instance of TextWrapper for efficiency.
A:
# test data
data = range(10)
the_dict = dict((i, str(i)*200) for i in range( 10 ))
# your loops as a generator
lines = ( the_dict[i] for i in data if i in the_dict )
def format( line ):
def splitter():
k = 0
while True:
r = line[k:k+60] # take a 60 char block
if r: # if there are any chars left
yield "%04d %s" % (k+1, r) # format them
else:
break
k += 60
return '\n'.join(splitter()) # join all the numbered blocks
for line in lines:
print format(line)
A:
I haven't tested it on actual data, but I believe the code below would do the job. It first builds up the whole string, then outputs it a 60-character line at a time. It uses the three-argument version of range() to count by 60.
s = ''.join(dict[i] for i in data if i in dict)
for i in range(0, len(s), 60):
print '%04d %s' % (i+1, s[i:i+60])
|
Python: File formatting
|
I have a for loop which references a dictionary and prints out the value associated with the key. Code is below:
for i in data:
if i in dict:
print dict[i],
How would i format the output so a new line is created every 60 characters? and with the character count along the side for example:
0001
MRQLLLISDLDNTWVGDQQALEHLQEYLGDRRGNFYLAYATGRSYHSARELQKQVGLMEP
0061
DYWLTAVGSEIYHPEGLDQHWADYLSEHWQRDILQAIADGFEALKPQSPLEQNPWKISYH
0121 LDPQACPTVIDQLTEMLKETGIPVQVIFSSGKDVDLLPQRSNKGNATQYLQQHLAMEPSQ
|
[
"It's a finicky formatting problem, but I think the following code:\nimport sys\n\nclass EveryN(object):\n def __init__(self, n, outs):\n self.n = n # chars/line\n self.outs = outs # output stream\n self.numo = 1 # next tag to write\n self.tll = 0 # tot chars on this line\n def write(self, s):\n while True:\n if self.tll == 0: # start of line: emit tag\n self.outs.write('%4.4d ' % self.numo)\n self.numo += self.n\n # wite up to N chars/line, no more\n numw = min(len(s), self.n - self.tll)\n self.outs.write(s[:numw])\n self.tll += numw\n if self.tll >= self.n:\n self.tll = 0\n self.outs.write('\\n')\n s = s[numw:]\n if not s: break\n\nif __name__ == '__main__':\n sys.stdout = EveryN(60, sys.stdout)\n for i, a in enumerate('abcdefgh'):\n print a*(5+ i*5),\n\nshows how to do it -- the output when running for demonstration purposes as the main script (five a's, ten b's, etc, with spaces in-between) is:\n0001 aaaaa bbbbbbbbbb ccccccccccccccc dddddddddddddddddddd eeeeee\n0061 eeeeeeeeeeeeeeeeeee ffffffffffffffffffffffffffffff ggggggggg\n0121 gggggggggggggggggggggggggg hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\n0181 hhhhhhh\n\n",
"It seems like you're looking for textwrap\n\nThe textwrap module provides two convenience functions, wrap() and\n fill(), as well as TextWrapper, the class that does all the work, and\n a utility function dedent(). If you’re just wrapping or filling one or\n two text strings, the convenience functions should be good enough;\n otherwise, you should use an instance of TextWrapper for efficiency.\n\n",
"# test data\ndata = range(10)\nthe_dict = dict((i, str(i)*200) for i in range( 10 ))\n\n# your loops as a generator\nlines = ( the_dict[i] for i in data if i in the_dict )\n\ndef format( line ):\n def splitter():\n k = 0\n while True:\n r = line[k:k+60] # take a 60 char block\n if r: # if there are any chars left\n yield \"%04d %s\" % (k+1, r) # format them\n else:\n break\n k += 60\n return '\\n'.join(splitter()) # join all the numbered blocks\n\nfor line in lines:\n print format(line)\n\n",
"I haven't tested it on actual data, but I believe the code below would do the job. It first builds up the whole string, then outputs it a 60-character line at a time. It uses the three-argument version of range() to count by 60.\ns = ''.join(dict[i] for i in data if i in dict)\nfor i in range(0, len(s), 60):\n print '%04d %s' % (i+1, s[i:i+60])\n\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"file",
"formatting",
"python"
] |
stackoverflow_0002393120_file_formatting_python.txt
|
Q:
Can nginx forward to Pylons, ignore response, return alternate response?
One of my URLs is for a tracking cookie. In the basic configuration, the pylons controller parses the query string, does a DB query, and sets the cookie accordingly.
I want to move to nginx. I am wondering if this is possible:
nginx fetches value of cookie from memcached
nginx writes the headers and serves static file
nginx returns response
nginx passes request on to pylons for logging
nginx ignores pylons response
Is any variation of this possible? I'm trying to decouple the request from the latency of logging in the pylons controller, because the response is ultimately a static file with a specific cookie header.
Thanks!
A:
The scenario you described is hardly possible "as is". Problems:
Nginx cannot read cookie from memcached, as far as I know. It can pass response body only.
Nginx can indeed call "post_action", but this functionality is in beta and you'd better avoid it.
Frankly, I don't completely understand what cookie are you going to write into memcached before the actual requst.. probably you need to give more details.
However, Nginx does many things well very which could be of use for you, so I shall outline some of them
Nginx can return an empty GIF, it's built in:
location /tracking {
empty_gif;
}
Nginx writes log very effectively, you can easily define format and write query arguments, request and response headers to the log:
log_format tracking '$remote_addr "$request" "$http_referer" $arg_param $upstream_x_track_id';
location /tracking {
access_log /var/log/tracking.log tracking buffer=16k;
proxy_pass http://upstream;
}
Since you are going to use memcached, you probably wanted to cache responses and this is what Nginx can do for you (I shall show an example with proxy, but it's possible with FastCGI as well):
proxy_cache_path /var/cache/nginx/cache_tracking keys_zone=tracking:20m;
location /tracking {
access_log /var/log/tracking.log tracking buffer=16k;
proxy_cache tracking;
proxy_cache_valid 200 1m; # Cache responses with code 200 for 1 minute
proxy_pass http://upstream;
}
You can define your own cache key and do not pass it to a client:
location /tracking {
access_log /var/log/tracking.log tracking buffer=16k;
proxy_cache_key $upstream_x_track_id;
proxy_cache tracking;
proxy_cache_valid 200 1m; # Cache responses with code 200 for 1 minute
proxy_hide_header X-Track_Id;
proxy_pass http://upstream;
}
|
Can nginx forward to Pylons, ignore response, return alternate response?
|
One of my URLs is for a tracking cookie. In the basic configuration, the pylons controller parses the query string, does a DB query, and sets the cookie accordingly.
I want to move to nginx. I am wondering if this is possible:
nginx fetches value of cookie from memcached
nginx writes the headers and serves static file
nginx returns response
nginx passes request on to pylons for logging
nginx ignores pylons response
Is any variation of this possible? I'm trying to decouple the request from the latency of logging in the pylons controller, because the response is ultimately a static file with a specific cookie header.
Thanks!
|
[
"The scenario you described is hardly possible \"as is\". Problems:\n\nNginx cannot read cookie from memcached, as far as I know. It can pass response body only.\nNginx can indeed call \"post_action\", but this functionality is in beta and you'd better avoid it.\n\nFrankly, I don't completely understand what cookie are you going to write into memcached before the actual requst.. probably you need to give more details.\nHowever, Nginx does many things well very which could be of use for you, so I shall outline some of them\nNginx can return an empty GIF, it's built in:\nlocation /tracking {\n empty_gif;\n}\n\nNginx writes log very effectively, you can easily define format and write query arguments, request and response headers to the log:\nlog_format tracking '$remote_addr \"$request\" \"$http_referer\" $arg_param $upstream_x_track_id';\n\nlocation /tracking {\n access_log /var/log/tracking.log tracking buffer=16k;\n proxy_pass http://upstream;\n}\n\nSince you are going to use memcached, you probably wanted to cache responses and this is what Nginx can do for you (I shall show an example with proxy, but it's possible with FastCGI as well):\nproxy_cache_path /var/cache/nginx/cache_tracking keys_zone=tracking:20m;\n\nlocation /tracking {\n access_log /var/log/tracking.log tracking buffer=16k;\n proxy_cache tracking;\n proxy_cache_valid 200 1m; # Cache responses with code 200 for 1 minute\n proxy_pass http://upstream;\n}\n\nYou can define your own cache key and do not pass it to a client:\nlocation /tracking {\n access_log /var/log/tracking.log tracking buffer=16k;\n proxy_cache_key $upstream_x_track_id;\n proxy_cache tracking;\n proxy_cache_valid 200 1m; # Cache responses with code 200 for 1 minute\n proxy_hide_header X-Track_Id;\n proxy_pass http://upstream;\n}\n\n"
] |
[
2
] |
[] |
[] |
[
"nginx",
"pylons",
"python",
"web_applications"
] |
stackoverflow_0002383036_nginx_pylons_python_web_applications.txt
|
Q:
how do i stop beautiful soup from skipping rows while parsing?
while using beautifulsoup to parse a table in html every other row starts with
<tr class="row_k">
instead of a tr tag without a class
Sample HTML
<tr class="row_k">
<td><img src="some picture url" alt="Item A"></td>
<td><a href="some url"> Item A</a></td>
<td>14.8k</td>
<td><span class="drop">-555</span></td>
<td>
<img src="some picture url" alt="stuff" title="stuff">
</td>
<td>
<img src="some picture url" alt="Max llll">
</td>
</tr>
<tr>
<td><img src="some picture url" alt="Item B"></td>
<td><a href="some url"> Item B</a></td>
<td>64.9k</td>
<td><span class="rise">+165</span></td>
<td>
<img src="some picture url" alt="stuff" title="stuff">
</td>
<td>
<img src="some picture url" alt="max llll">
</td>
</tr>
<tr class="row_k">
<td><img src="some picture url" alt="Item C"></td>
<td><a href="some url"> Item C</a></td>
<td>4,000</td>
<td><span class="rise">+666</span></td>
<td>
<img src="some picture url" title="stuff">
</td>
<td>
<img src="some picture url" alt="Maximum lllle">
Text I wish to extract is 14.8k, 64.9k, and 4,000
this1 = urllib2.urlopen('my url').read()
this_1 = BeautifulSoup(this1)
this_1a = StringIO.StringIO()
for row in this_1.findAll("tr", { "class" : "row_k" }):
for col in row.findAll(re.compile('td')):
this_1a.write(col.string if col.string else '')
Item_this1 = this_1a.getvalue()
I get the feeling that this code is poorly written, Is there a more flexible tool I can use such as an XML parser? that someone could suggest.
still open to any answers that still utilize beautifulsoup.
A:
I am still learning a lot but I am going to suggest you try lxml. I am going to make a stab at this and I think it will mostly get you there but there may be some niceties I am not certain about.
assuming this1 is a string
from lxml.html import fromstring
this1_tree=fromstring(this1)
all_cells=[(item[0], item[1]) for item in enumerate(this1_tree.cssselect('td'))] # I am hoping this gives you the cells with their relative position in the document)
The only thing I am not totally certain about is whether you test the key or value or text_content for each cell to find out if it has the string that you are seeking in the anchor reference or text. That is why I wanted a sample of your html. But one of those should work
the_cell_before_numbers=[]
for cell in all_cells:
if 'Item' in cell[1].text_content():
the_cell_before_numbers.append(cell[0])
Now that you have the cell before your can then get the value you need by getting the text content of the next cell
todays_price=all_cells[the_cell_before_number+1][1].text_content()
I am sure there is a prettier way but I think this will get you there.
I tested using your html and I got what you were looking for.
|
how do i stop beautiful soup from skipping rows while parsing?
|
while using beautifulsoup to parse a table in html every other row starts with
<tr class="row_k">
instead of a tr tag without a class
Sample HTML
<tr class="row_k">
<td><img src="some picture url" alt="Item A"></td>
<td><a href="some url"> Item A</a></td>
<td>14.8k</td>
<td><span class="drop">-555</span></td>
<td>
<img src="some picture url" alt="stuff" title="stuff">
</td>
<td>
<img src="some picture url" alt="Max llll">
</td>
</tr>
<tr>
<td><img src="some picture url" alt="Item B"></td>
<td><a href="some url"> Item B</a></td>
<td>64.9k</td>
<td><span class="rise">+165</span></td>
<td>
<img src="some picture url" alt="stuff" title="stuff">
</td>
<td>
<img src="some picture url" alt="max llll">
</td>
</tr>
<tr class="row_k">
<td><img src="some picture url" alt="Item C"></td>
<td><a href="some url"> Item C</a></td>
<td>4,000</td>
<td><span class="rise">+666</span></td>
<td>
<img src="some picture url" title="stuff">
</td>
<td>
<img src="some picture url" alt="Maximum lllle">
Text I wish to extract is 14.8k, 64.9k, and 4,000
this1 = urllib2.urlopen('my url').read()
this_1 = BeautifulSoup(this1)
this_1a = StringIO.StringIO()
for row in this_1.findAll("tr", { "class" : "row_k" }):
for col in row.findAll(re.compile('td')):
this_1a.write(col.string if col.string else '')
Item_this1 = this_1a.getvalue()
I get the feeling that this code is poorly written, Is there a more flexible tool I can use such as an XML parser? that someone could suggest.
still open to any answers that still utilize beautifulsoup.
|
[
"I am still learning a lot but I am going to suggest you try lxml. I am going to make a stab at this and I think it will mostly get you there but there may be some niceties I am not certain about.\nassuming this1 is a string\nfrom lxml.html import fromstring\nthis1_tree=fromstring(this1)\nall_cells=[(item[0], item[1]) for item in enumerate(this1_tree.cssselect('td'))] # I am hoping this gives you the cells with their relative position in the document)\n\nThe only thing I am not totally certain about is whether you test the key or value or text_content for each cell to find out if it has the string that you are seeking in the anchor reference or text. That is why I wanted a sample of your html. But one of those should work \nthe_cell_before_numbers=[]\nfor cell in all_cells:\n if 'Item' in cell[1].text_content():\n the_cell_before_numbers.append(cell[0])\n\nNow that you have the cell before your can then get the value you need by getting the text content of the next cell\ntodays_price=all_cells[the_cell_before_number+1][1].text_content()\n\nI am sure there is a prettier way but I think this will get you there.\nI tested using your html and I got what you were looking for.\n"
] |
[
2
] |
[] |
[] |
[
"beautifulsoup",
"python",
"tags",
"urllib2",
"xml"
] |
stackoverflow_0002394300_beautifulsoup_python_tags_urllib2_xml.txt
|
Q:
pycurl READFUNCTION with a bytestream
Is there a way to write a callback function for pycurl's READFUNCTION that does not return a string? I am planning on sending blocks of binary data via pycurl. i tried writing a callback function that does this:
def read_callback(self, size):
for block in data:
yield block
but pycurl exits with an error that says the return type must be a string.
A:
The "read function" must return a string of bytes -- remember, libcurl is a wrapper on an underlying C library, so of course it's type-picky!-). However, it can perfectly be a binary string of bytes (in Python 2.* at least -- I don't think pycurl works with Python 3 anyway), so of course it can return "blocks of binary data" -- as long as they're encoded into strings of bytes and respect the size constraint.
What you just encoded, when called, returns a "generator function" -- obviously no good. Assuming data is a list of non-empty byte strings, you need to dice and slice it appropriately, returning each time a string of bytes, with return, definitely not yield (!).
Not sure where that mysterious data of yours comes from -- let's assume you mean self.data instead. Then you need to keep track, in other instance variables, of the current index into self.data and possibly -- if the items are longer than size -- of the "yet unsent part" of the current piece, too.
E.g., it could be:
class MySender(object):
def __init__(self, data):
self.data = data
self.i = 0
self.rest = 0
def readfunction(self, size):
if self.i >= len(self.data):
return ''
result = self.data[self.i][self.rest:self.rest+size]
self.rest += size
if self.rest >= len(self.data[self.i]):
self.i += 1
self.rest = 0
If self.data's items are other kinds of binary data (not already encoded as byte strings), you can turn them into byte strings e.g. with help from Python library modules such as struct and array.
|
pycurl READFUNCTION with a bytestream
|
Is there a way to write a callback function for pycurl's READFUNCTION that does not return a string? I am planning on sending blocks of binary data via pycurl. i tried writing a callback function that does this:
def read_callback(self, size):
for block in data:
yield block
but pycurl exits with an error that says the return type must be a string.
|
[
"The \"read function\" must return a string of bytes -- remember, libcurl is a wrapper on an underlying C library, so of course it's type-picky!-). However, it can perfectly be a binary string of bytes (in Python 2.* at least -- I don't think pycurl works with Python 3 anyway), so of course it can return \"blocks of binary data\" -- as long as they're encoded into strings of bytes and respect the size constraint.\nWhat you just encoded, when called, returns a \"generator function\" -- obviously no good. Assuming data is a list of non-empty byte strings, you need to dice and slice it appropriately, returning each time a string of bytes, with return, definitely not yield (!).\nNot sure where that mysterious data of yours comes from -- let's assume you mean self.data instead. Then you need to keep track, in other instance variables, of the current index into self.data and possibly -- if the items are longer than size -- of the \"yet unsent part\" of the current piece, too.\nE.g., it could be:\nclass MySender(object):\n def __init__(self, data):\n self.data = data\n self.i = 0\n self.rest = 0\n def readfunction(self, size):\n if self.i >= len(self.data):\n return ''\n result = self.data[self.i][self.rest:self.rest+size]\n self.rest += size\n if self.rest >= len(self.data[self.i]):\n self.i += 1\n self.rest = 0\n\nIf self.data's items are other kinds of binary data (not already encoded as byte strings), you can turn them into byte strings e.g. with help from Python library modules such as struct and array.\n"
] |
[
1
] |
[] |
[] |
[
"pycurl",
"python"
] |
stackoverflow_0002394258_pycurl_python.txt
|
Q:
Saving Django xml in a file?
I have a function in a view that renders the xml in the browser, but what I want is to save the xml content to a file, to be used in a Flash gallery.
def build_xml_menu(request):
rubros = Rubro.objects.all()
familias = Familia.objects.all()
context_data = {'rubros': rubros, 'familias': familias}
return render_to_response('menu.xml', context_data,
mimetype='application/xml')
How can the community help me do this or refer me to a guide that may aid me with this?
Thanks.
A:
You have to use render to string instead of render_to_response :)
|
Saving Django xml in a file?
|
I have a function in a view that renders the xml in the browser, but what I want is to save the xml content to a file, to be used in a Flash gallery.
def build_xml_menu(request):
rubros = Rubro.objects.all()
familias = Familia.objects.all()
context_data = {'rubros': rubros, 'familias': familias}
return render_to_response('menu.xml', context_data,
mimetype='application/xml')
How can the community help me do this or refer me to a guide that may aid me with this?
Thanks.
|
[
"You have to use render to string instead of render_to_response :)\n"
] |
[
4
] |
[] |
[] |
[
"django",
"flash",
"python",
"xml"
] |
stackoverflow_0002394437_django_flash_python_xml.txt
|
Q:
Is there a better way to parse html tables than lxml
I am working with html documents and ripping out tables to parse them if they turn out to be the correct tables. I am happy with the results - my extraction process successfully maps row labels and column headings in over 95% of the cases and in the cases it does not we can identify the problems and use other approaches.
In my scanning around the iternet I have come to understand that a browser has a very powerful 'engine' to properly display the contents of htm pages even if the underlying htm is mal-formed. The problems we have with parsing tables have to do with things like not being able to separate the header from the data rows or being able to separate the row labels from one or more of the adjacent data values and then not correctly parsing out adjacent data values. (We might have two data values that get mapped to one column heading instead of the two adjacent column headings. That is if I have a column heading labeled apple and then one labeled banana I might have the value '1125 12345' assigned to the banana (or apple) column heading in the output instead of having the value 1125 assigned to apple and 12345 assigned to banana.
As I said at the beginning- we get it right 95% of the time and we can tell in the output when there is a problem. I am starting to think we have gone as far as we can using logic and inferences from the html to clean these up so I am beginning to wonder if I need a new approach.
Is there a way to harness the 'engine' of a browser to help with this parser. Ultimately if the browser can properly display the columns and rows so they are properly displayed on the screen then there is some technology that handles even when the row and column spans are not consistent (for example).
Thanks for any observations
A:
Actually, browser engines are deliberately stupid in their parsing of HTML, assuming that what they get is only marginally correct. lxml and BeautifulSoup attempt to mimic this level of stupidity, so they are the correct tools to use.
A:
To "harness the 'engine' of a browser", your best bet at this time is no doubt SeleniumRC -- however its main advantage is in handling javascript "just like the browser would" (there are few other options for that); for a table that's simply logically broken though it may "look" OK when rendered, the browser (and therefore Selenium) may be just as helpless as lxml or BeautifulSoup. Still, may be worth your while to try.
|
Is there a better way to parse html tables than lxml
|
I am working with html documents and ripping out tables to parse them if they turn out to be the correct tables. I am happy with the results - my extraction process successfully maps row labels and column headings in over 95% of the cases and in the cases it does not we can identify the problems and use other approaches.
In my scanning around the iternet I have come to understand that a browser has a very powerful 'engine' to properly display the contents of htm pages even if the underlying htm is mal-formed. The problems we have with parsing tables have to do with things like not being able to separate the header from the data rows or being able to separate the row labels from one or more of the adjacent data values and then not correctly parsing out adjacent data values. (We might have two data values that get mapped to one column heading instead of the two adjacent column headings. That is if I have a column heading labeled apple and then one labeled banana I might have the value '1125 12345' assigned to the banana (or apple) column heading in the output instead of having the value 1125 assigned to apple and 12345 assigned to banana.
As I said at the beginning- we get it right 95% of the time and we can tell in the output when there is a problem. I am starting to think we have gone as far as we can using logic and inferences from the html to clean these up so I am beginning to wonder if I need a new approach.
Is there a way to harness the 'engine' of a browser to help with this parser. Ultimately if the browser can properly display the columns and rows so they are properly displayed on the screen then there is some technology that handles even when the row and column spans are not consistent (for example).
Thanks for any observations
|
[
"Actually, browser engines are deliberately stupid in their parsing of HTML, assuming that what they get is only marginally correct. lxml and BeautifulSoup attempt to mimic this level of stupidity, so they are the correct tools to use.\n",
"To \"harness the 'engine' of a browser\", your best bet at this time is no doubt SeleniumRC -- however its main advantage is in handling javascript \"just like the browser would\" (there are few other options for that); for a table that's simply logically broken though it may \"look\" OK when rendered, the browser (and therefore Selenium) may be just as helpless as lxml or BeautifulSoup. Still, may be worth your while to try.\n"
] |
[
2,
2
] |
[] |
[] |
[
"browser",
"lxml",
"python"
] |
stackoverflow_0002393917_browser_lxml_python.txt
|
Q:
How many items in a dictionary share the same value in Python
Is there a way to see how many items in a dictionary share the same value in Python?
Let's say that I have a dictionary like:
{"a": 600, "b": 75, "c": 75, "d": 90}
I'd like to get a resulting dictionary like:
{600: 1, 75: 2, 90: 1}
My first naive attempt would be to just use a nested-for loop and for each value then I would iterate over the dictionary again. Is there a better way to do this?
A:
You could use itertools.groupby for this.
import itertools
x = {"a": 600, "b": 75, "c": 75, "d": 90}
[(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]
A:
When Python 2.7 comes out you can use its collections.Counter class
otherwise see counter receipe
Under Python 2.7a3
from collections import Counter
items = {"a": 600, "b": 75, "c": 75, "d": 90}
c = Counter( items )
print( dict( c.items() ) )
output is
{600: 1, 90: 1, 75: 2}
A:
>>> a = {"a": 600, "b": 75, "c": 75, "d": 90}
>>> b = {}
>>> for k,v in a.iteritems():
... b[v] = b.get(v,0) + 1
...
>>> b
{600: 1, 90: 1, 75: 2}
>>>
A:
Use Counter (2.7+, see below at link for implementations for older versions) along with dict.values().
A:
>>> a = {"a": 600, "b": 75, "c": 75, "d": 90}
>>> d={}
>>> for v in a.values():
... if not v in d: d[v]=1
... else: d[v]+=1
...
>>> d
{600: 1, 90: 1, 75: 2}
|
How many items in a dictionary share the same value in Python
|
Is there a way to see how many items in a dictionary share the same value in Python?
Let's say that I have a dictionary like:
{"a": 600, "b": 75, "c": 75, "d": 90}
I'd like to get a resulting dictionary like:
{600: 1, 75: 2, 90: 1}
My first naive attempt would be to just use a nested-for loop and for each value then I would iterate over the dictionary again. Is there a better way to do this?
|
[
"You could use itertools.groupby for this.\nimport itertools\nx = {\"a\": 600, \"b\": 75, \"c\": 75, \"d\": 90}\n[(k, len(list(v))) for k, v in itertools.groupby(sorted(x.values()))]\n\n",
"When Python 2.7 comes out you can use its collections.Counter class\notherwise see counter receipe\nUnder Python 2.7a3 \nfrom collections import Counter\nitems = {\"a\": 600, \"b\": 75, \"c\": 75, \"d\": 90} \nc = Counter( items )\n\nprint( dict( c.items() ) )\n\noutput is\n\n{600: 1, 90: 1, 75: 2}\n\n",
">>> a = {\"a\": 600, \"b\": 75, \"c\": 75, \"d\": 90}\n>>> b = {}\n>>> for k,v in a.iteritems():\n... b[v] = b.get(v,0) + 1\n...\n>>> b\n{600: 1, 90: 1, 75: 2}\n>>>\n\n",
"Use Counter (2.7+, see below at link for implementations for older versions) along with dict.values().\n",
">>> a = {\"a\": 600, \"b\": 75, \"c\": 75, \"d\": 90}\n>>> d={}\n>>> for v in a.values():\n... if not v in d: d[v]=1\n... else: d[v]+=1\n...\n>>> d\n{600: 1, 90: 1, 75: 2}\n\n"
] |
[
7,
2,
1,
0,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0002393902_dictionary_python.txt
|
Q:
Best method of connection between automated python XMPP server and interface to django?
I have an XMPP server (likely — python, twisted, wokkel), which I prefer not to restart even in the development version, and I have some python module “worker” (which is interface to particular django project), which gets jid and message text and returns some response (text or XML, either way).
The question is, what would be the best way to connect them, considering that I may prefer to update the module part too often?
Another consideration is that it might be required to run multiple instances of “worker” for it all to be high-load-capable.
One possible way I see is implementing a thread in the server which checks if the module was changed and reload()s it if necessary.
The other way would be making something similar to fastcgi through sockets, although not HTTP-based.
A:
My suggestion is:
Use RabbitMQ with XMPP adaptor.
Use Python carrot for AMQP since it can be used directly under Django.
A:
I can't say that I understand all of your question, but the bit where you're asking how to connect django and twisted and multiple workers: I'd suggest using AMPQ. This gets you reliable message delivery, multiple consumers, persistence.
There's the txAMQP library for twisted.
https://launchpad.net/txamqp
A good primer to AMQP here, it's a good place to start:
http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
|
Best method of connection between automated python XMPP server and interface to django?
|
I have an XMPP server (likely — python, twisted, wokkel), which I prefer not to restart even in the development version, and I have some python module “worker” (which is interface to particular django project), which gets jid and message text and returns some response (text or XML, either way).
The question is, what would be the best way to connect them, considering that I may prefer to update the module part too often?
Another consideration is that it might be required to run multiple instances of “worker” for it all to be high-load-capable.
One possible way I see is implementing a thread in the server which checks if the module was changed and reload()s it if necessary.
The other way would be making something similar to fastcgi through sockets, although not HTTP-based.
|
[
"My suggestion is:\n\nUse RabbitMQ with XMPP adaptor.\nUse Python carrot for AMQP since it can be used directly under Django.\n\n",
"I can't say that I understand all of your question, but the bit where you're asking how to connect django and twisted and multiple workers: I'd suggest using AMPQ. This gets you reliable message delivery, multiple consumers, persistence.\nThere's the txAMQP library for twisted.\nhttps://launchpad.net/txamqp\nA good primer to AMQP here, it's a good place to start:\nhttp://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002394284_django_python.txt
|
Q:
How do you NOT automatically dereference a db.ReferenceProperty in Google App Engine?
Suppose I have
class Foo(db.Model):
bar = db.ReferenceProperty(Bar)
foo = Foo.all().get()
Is there a way for me to do foo.bar without a query being made to Datastore? The docs say that foo.bar will be an instance of Key, so I would expect to be able to do foo.bar.id() and be able to get the id of the Bar that's associated with foo, but it doesn't seem to work that way.
PS: The part of the docs I'm referring to can be found here:
http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ReferenceProperty
and it says this:
"An application can explicitly db.get() the value of a ReferenceProperty (which is a Key) to test whether the referenced entity exists."
A:
As the docs say,
The ReferenceProperty value can be
used as if it were a model instance,
and the datastore entity will be
fetched and the model instance created
when it is first used in this way.
Untouched reference properties do not
query for unneeded data.
so you're fine as long as you don't touch it, but if you do though it, e.g. with an .id() call as you show, "the datastore entity will be fetched", the docs say. More docs are here, but they don't show a way to magically get the id without fetching, either.
I have not tried, but you might be able to use the get_value_for_datastore of the property to get "the Python-native value of the property" which I believe is indeed a Key -- whose id() method should be callable without datastore fetches. Have you tried that?
|
How do you NOT automatically dereference a db.ReferenceProperty in Google App Engine?
|
Suppose I have
class Foo(db.Model):
bar = db.ReferenceProperty(Bar)
foo = Foo.all().get()
Is there a way for me to do foo.bar without a query being made to Datastore? The docs say that foo.bar will be an instance of Key, so I would expect to be able to do foo.bar.id() and be able to get the id of the Bar that's associated with foo, but it doesn't seem to work that way.
PS: The part of the docs I'm referring to can be found here:
http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ReferenceProperty
and it says this:
"An application can explicitly db.get() the value of a ReferenceProperty (which is a Key) to test whether the referenced entity exists."
|
[
"As the docs say,\n\nThe ReferenceProperty value can be\n used as if it were a model instance,\n and the datastore entity will be\n fetched and the model instance created\n when it is first used in this way.\n Untouched reference properties do not\n query for unneeded data.\n\nso you're fine as long as you don't touch it, but if you do though it, e.g. with an .id() call as you show, \"the datastore entity will be fetched\", the docs say. More docs are here, but they don't show a way to magically get the id without fetching, either.\nI have not tried, but you might be able to use the get_value_for_datastore of the property to get \"the Python-native value of the property\" which I believe is indeed a Key -- whose id() method should be callable without datastore fetches. Have you tried that?\n"
] |
[
8
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002395144_google_app_engine_google_cloud_datastore_python.txt
|
Q:
How do I set up QtDesigner for a project that has animated elements?
I'm writing a project to simulate creatures moving around a map. These can be represented by simple circles, but I need a map/grid and those circles animated on top of the map.
What elements should I use in QtDesigner to set up for this kind of GUI in my project? I've yet to do anything like this before
A:
You probably want a Graphics View to do it right, but if you don't care about performance, you might be able to get by with just setting the pos on a bunch of buttons to move them around on a widget (without a layout).
|
How do I set up QtDesigner for a project that has animated elements?
|
I'm writing a project to simulate creatures moving around a map. These can be represented by simple circles, but I need a map/grid and those circles animated on top of the map.
What elements should I use in QtDesigner to set up for this kind of GUI in my project? I've yet to do anything like this before
|
[
"You probably want a Graphics View to do it right, but if you don't care about performance, you might be able to get by with just setting the pos on a bunch of buttons to move them around on a widget (without a layout).\n"
] |
[
1
] |
[] |
[] |
[
"animation",
"pyqt",
"python",
"qt",
"user_interface"
] |
stackoverflow_0002395232_animation_pyqt_python_qt_user_interface.txt
|
Q:
Suppose I have 400 rows of people's names in a database. What's the best way to do a search for their names?
They will also search part of their name. Not only words with spaces.
If they type "Matt", I expect to retrieve "Matthew" too.
A:
SELECT *
FROM mytable
WHERE name LIKE 'matt%' OR name LIKE '[ ,-/]matt%'
Notes:
1) Fancy wildcard. The reason for not using the simpler LIKE '%xyz%' form is that depending on the xyz the database could return many non-relevant records. For example "Jeff Zermatt" in the case of the "Matt" search.
The brackets in the second wildcard key include all the delimiters which may be indicative of a break between words. An alternative wildcard pattern would be [^A-Z0-9] (Which may yield a few O'Brian when search for brian but maybe not a bad thing...)
2) Performance. Because there are so few records in this table, the front wildcard approach is quite feasible, and certainly the easiest approach. No reason to search any further!
If the records happen to be very wide (many fields some of them more than 30 chars in length), you can create an index on name. The front-end wildcard will still require a scan, but this will be on the index which is narrower, hence fits more readily in the cache etc.
Indeed if rather than a SELECT * this query targets only a few of the fields of the myTable table [and if this table's record are "wide"], you can create a index made of all these fields.
Would the number of records grow past, say, 50,000 (and, to a lesser degree, would the application "hit" the database with similar queries at a rate above say 40 per minute), you may consider introducing more efficient ways of dealing with keywords: Full Text Catalog or a "hand made" table with the individual keywords.
3) Advantages of another approach. The advantage of a solution whereby the application maintains a table with a list of the individual keywords, readily parsed, from the full name, doesn't only provide better scaling (when the table and/or usage grows), but also introduces improvements in the quality of the search.
For example, it may allow improving the effective recall by introducing common
common nicknames of first names (Bill or Will or Billy for William, Dick for Richard, Jack or Johnny for John etc.). Another possibility open by a more sophisticated approach is the introduction of a Soundex or modified Soundex encoding of the name tokens, allowing the users to locates names even when they may mispell or ignore the precise spelling (eg. Wilmson vs. Wilmsen vs. Willmsonn etc.)
A:
You can use:
SELECT *
FROM mytable
WHERE name LIKE '%matt%'
A:
You have the following options:
Full Text Search (FTS)
Regular Expressions
LIKE Using wildcards
...in that order of preference.
A:
If you are trying to search for the names through any development Language, you can use the Regular expression package in Java.
Some thing like java.util.regex.*;
|
Suppose I have 400 rows of people's names in a database. What's the best way to do a search for their names?
|
They will also search part of their name. Not only words with spaces.
If they type "Matt", I expect to retrieve "Matthew" too.
|
[
"SELECT * \nFROM mytable \nWHERE name LIKE 'matt%' OR name LIKE '[ ,-/]matt%'\n\nNotes:\n1) Fancy wildcard. The reason for not using the simpler LIKE '%xyz%' form is that depending on the xyz the database could return many non-relevant records. For example \"Jeff Zermatt\" in the case of the \"Matt\" search.\nThe brackets in the second wildcard key include all the delimiters which may be indicative of a break between words. An alternative wildcard pattern would be [^A-Z0-9] (Which may yield a few O'Brian when search for brian but maybe not a bad thing...)\n2) Performance. Because there are so few records in this table, the front wildcard approach is quite feasible, and certainly the easiest approach. No reason to search any further!\nIf the records happen to be very wide (many fields some of them more than 30 chars in length), you can create an index on name. The front-end wildcard will still require a scan, but this will be on the index which is narrower, hence fits more readily in the cache etc.\nIndeed if rather than a SELECT * this query targets only a few of the fields of the myTable table [and if this table's record are \"wide\"], you can create a index made of all these fields.\nWould the number of records grow past, say, 50,000 (and, to a lesser degree, would the application \"hit\" the database with similar queries at a rate above say 40 per minute), you may consider introducing more efficient ways of dealing with keywords: Full Text Catalog or a \"hand made\" table with the individual keywords.\n3) Advantages of another approach. The advantage of a solution whereby the application maintains a table with a list of the individual keywords, readily parsed, from the full name, doesn't only provide better scaling (when the table and/or usage grows), but also introduces improvements in the quality of the search.\nFor example, it may allow improving the effective recall by introducing common\ncommon nicknames of first names (Bill or Will or Billy for William, Dick for Richard, Jack or Johnny for John etc.). Another possibility open by a more sophisticated approach is the introduction of a Soundex or modified Soundex encoding of the name tokens, allowing the users to locates names even when they may mispell or ignore the precise spelling (eg. Wilmson vs. Wilmsen vs. Willmsonn etc.)\n",
"You can use:\nSELECT * \n FROM mytable \nWHERE name LIKE '%matt%'\n\n",
"You have the following options:\n\nFull Text Search (FTS)\nRegular Expressions\nLIKE Using wildcards\n\n...in that order of preference.\n",
"If you are trying to search for the names through any development Language, you can use the Regular expression package in Java.\nSome thing like java.util.regex.*;\n"
] |
[
12,
10,
1,
0
] |
[] |
[] |
[
"database",
"indexing",
"mysql",
"python",
"search"
] |
stackoverflow_0002394870_database_indexing_mysql_python_search.txt
|
Q:
List of evented / asynchronous languages
I'm working on a system than has to be pretty scalable from the beginning. I've started looking at / playing around with asynchronous/evented approaches to writing serverside code. I've played around with both ruby's EventMachine and node.js.
EventMachine is cool, but doesn't have asynchronous file I/O, which I need. The interface is kind of strange, too.
Node.js is awesome, but it's... uhh.. it's javascript.
Can the greater Stack Overflow community help me out by listing other languages that have strong asynchronous support? To qualify, the language would need to support both closures and have libraries for asynchronous file io, http, etc. It would be nice to have something like node.js that was written in a stronger language than javascript.
Lisp? Python has twisted, right?
A:
Erlang may be the language with the highest intrinsic scalability for server-side code (it manages multiprocessing for you, mostly by doing async, cooperative task switching "under the covers") -- if you can stomach its peculiar syntax and (often) peculiar semantics.
Python has twisted (very general purpose for all networking tasks), tornado (for server-side async specifically), and stackless (widely used in MMP online games), not to mention the old but usable asyncore that's in the standard library (and the even-older "Medusa" that sits on top of asyncore to enrich its functionality).
Go has very light "stackless" goroutines and channels for synchronization purposes when needed.
A:
I would recommend that you take another look at node.js. One of the biggest problems with using libraries to do event-based programming in an object-oriented programming language (rather than using an event-based programming language in the first place), is that usually all the other existing libraries are not event-based, and it is really awkward to mix event-based and synchronous I/O. In fact, it is pretty much impossible, or more precisely, it is possible but destroys all the benefits of using event-based I/O in the first place. (Note that pretty much any third-party library you use (and the libraries that they use, and so forth), including the standard and core libraries of the language itself, must be event-based, to actually reap the benefits. Otherwise, you'll spend most of your project's time writing asynchronous wrappers around existing libraries.)
Now, if using event-based libraries is such a bad thing, then why do I recommend node.js? Simple: ECMAScript doesn't have any synchronous I/O libraries (because of the simple fact that it doesn't have any I/O libraries at all), so the mixing problem simply doesn't arise. (Actually, it has some I/O libraries, like XmlHttpRequest or Web Sockets, but guess what: those are already all event-based.)
node.js implements all I/O libraries itself, all event-based, without backwards-compatibility or legacy requirements.
Otherwise, every language or platform has some event-based or asynchronous I/O libraries: Ruby has EventMachine and Rev, .NET has Rx, the JVM has NIO, Unix systems have kqueue/epoll, C has libev and libeio (on top of which node.js and Rev are built), Perl has AnyEvent (built on top of libev by the same author) and so on.
A:
F# has asynchronous workflows, which are a tremendous way to write async code.
A:
Since you have expressed interest in Lisp, you might want to consider Clojure - a Lisp dialect for the JVM with a strong focus on concurrency. Pretty much anything can be run asynchronously by running it in an agent. Of course, it also provides painless access to the entire Java ecosystem.
|
List of evented / asynchronous languages
|
I'm working on a system than has to be pretty scalable from the beginning. I've started looking at / playing around with asynchronous/evented approaches to writing serverside code. I've played around with both ruby's EventMachine and node.js.
EventMachine is cool, but doesn't have asynchronous file I/O, which I need. The interface is kind of strange, too.
Node.js is awesome, but it's... uhh.. it's javascript.
Can the greater Stack Overflow community help me out by listing other languages that have strong asynchronous support? To qualify, the language would need to support both closures and have libraries for asynchronous file io, http, etc. It would be nice to have something like node.js that was written in a stronger language than javascript.
Lisp? Python has twisted, right?
|
[
"Erlang may be the language with the highest intrinsic scalability for server-side code (it manages multiprocessing for you, mostly by doing async, cooperative task switching \"under the covers\") -- if you can stomach its peculiar syntax and (often) peculiar semantics.\nPython has twisted (very general purpose for all networking tasks), tornado (for server-side async specifically), and stackless (widely used in MMP online games), not to mention the old but usable asyncore that's in the standard library (and the even-older \"Medusa\" that sits on top of asyncore to enrich its functionality).\nGo has very light \"stackless\" goroutines and channels for synchronization purposes when needed.\n",
"I would recommend that you take another look at node.js. One of the biggest problems with using libraries to do event-based programming in an object-oriented programming language (rather than using an event-based programming language in the first place), is that usually all the other existing libraries are not event-based, and it is really awkward to mix event-based and synchronous I/O. In fact, it is pretty much impossible, or more precisely, it is possible but destroys all the benefits of using event-based I/O in the first place. (Note that pretty much any third-party library you use (and the libraries that they use, and so forth), including the standard and core libraries of the language itself, must be event-based, to actually reap the benefits. Otherwise, you'll spend most of your project's time writing asynchronous wrappers around existing libraries.)\nNow, if using event-based libraries is such a bad thing, then why do I recommend node.js? Simple: ECMAScript doesn't have any synchronous I/O libraries (because of the simple fact that it doesn't have any I/O libraries at all), so the mixing problem simply doesn't arise. (Actually, it has some I/O libraries, like XmlHttpRequest or Web Sockets, but guess what: those are already all event-based.)\nnode.js implements all I/O libraries itself, all event-based, without backwards-compatibility or legacy requirements.\nOtherwise, every language or platform has some event-based or asynchronous I/O libraries: Ruby has EventMachine and Rev, .NET has Rx, the JVM has NIO, Unix systems have kqueue/epoll, C has libev and libeio (on top of which node.js and Rev are built), Perl has AnyEvent (built on top of libev by the same author) and so on.\n",
"F# has asynchronous workflows, which are a tremendous way to write async code.\n",
"Since you have expressed interest in Lisp, you might want to consider Clojure - a Lisp dialect for the JVM with a strong focus on concurrency. Pretty much anything can be run asynchronously by running it in an agent. Of course, it also provides painless access to the entire Java ecosystem.\n"
] |
[
20,
16,
4,
4
] |
[] |
[] |
[
"asynchronous",
"javascript",
"lisp",
"python",
"ruby"
] |
stackoverflow_0002384314_asynchronous_javascript_lisp_python_ruby.txt
|
Q:
Detect workstation/System Screen Lock using Python(ubuntu)
Is there anyway that we can detect when the system/screen gets locked and notify some event to trigger in Ubuntu ?
A:
There is a possibility to be notified when the screen becomes locked/unlocked with DBus, this is reference on GnomeScreensaver showing the basics of it.
I am not DBus expert, but there are bindings for python, so you can listen for DBus events in python. Combinig the two, you should be able to get what you want:-).
Here is a python-dbus programming tutorial on wikibooks.
|
Detect workstation/System Screen Lock using Python(ubuntu)
|
Is there anyway that we can detect when the system/screen gets locked and notify some event to trigger in Ubuntu ?
|
[
"There is a possibility to be notified when the screen becomes locked/unlocked with DBus, this is reference on GnomeScreensaver showing the basics of it.\nI am not DBus expert, but there are bindings for python, so you can listen for DBus events in python. Combinig the two, you should be able to get what you want:-). \nHere is a python-dbus programming tutorial on wikibooks.\n"
] |
[
3
] |
[] |
[] |
[
"locking",
"python",
"system",
"ubuntu"
] |
stackoverflow_0002395579_locking_python_system_ubuntu.txt
|
Q:
Calling an executable from within Python / Django web application running on IIS
I have a Python / Django application which is supposed to call an external windows binary and get its output at some point. And it does so when tested via 'python manage.py shell'.
But when it is run from within the web browser, which is served by IIS, the external application is not executed.
Is IIS blocking something on the way? Can this be avoided?
Any help is much appreciated.
oMat
A:
Might be a permissions issue. when you run from the shell, you're using the user that run the python manage.py shell command. When serving requests from the IIS you're using its user (IUSR or something like that). Try giving execution permission on the executable file to the Everyone group just to see if it helps.
|
Calling an executable from within Python / Django web application running on IIS
|
I have a Python / Django application which is supposed to call an external windows binary and get its output at some point. And it does so when tested via 'python manage.py shell'.
But when it is run from within the web browser, which is served by IIS, the external application is not executed.
Is IIS blocking something on the way? Can this be avoided?
Any help is much appreciated.
oMat
|
[
"Might be a permissions issue. when you run from the shell, you're using the user that run the python manage.py shell command. When serving requests from the IIS you're using its user (IUSR or something like that). Try giving execution permission on the executable file to the Everyone group just to see if it helps.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"executable",
"iis",
"python",
"windows"
] |
stackoverflow_0002394054_django_executable_iis_python_windows.txt
|
Q:
algorithm to find independent sets
Folks,
I have a problem. I am a writing a script in python which consists of several modules. Some of the modules are dependent on other modules, hence they should be run only after the dependent modules are successfully run. So each modules derives from a base class module and overrides a list called DEPENDENCIES which is a list of dependecies to be met beofre this module is run. There is one module which needs to be run before all other modules.Currently I am doing something like this.
modules_to_run.append(a)
modules_to_run.append(b)
modules_to_run.append(c)
.....
.....
modules_to_run.append(z)
# Very simplistically just run the Analysis modules sequentially in
# an order that respects their dependencies
foundOne = True
while foundOne and len(modules_to_run) > 0:
foundOne = False
for module in modules_to_run:
if len(module.DEPENDENCIES) == 0:
foundOne = True
print_log("Executing module %s..." % module.__name__, log)
try:
module().execute()
modules_to_run.remove(module)
for module2 in modules_to_run:
try:
module2.DEPENDENCIES.remove(module)
except:
#module may not be in module2's DEPENDENCIES
pass
except Exception as e:
print_log("ERROR: %s did not run to completion" % module.__name__, log)
modules_to_run.remove(module)
print_log(e, log)
for module in modules_to_run:
name = module.__name__
print_log("ERROR: %s has unmet dependencies and could not be run:" % name, log)
print_log(module.DEPENDENCIES, log)
Now I am seeing that some modules are taking long time to execute and script tun time is too long. So I wanted to make it multi threaded so that independent modules can run simultaneously thus saving time. So I want a solution where after each iteration , I'll recalculate 'n' independent modules ( where 'n' is max no of threads, typically 2 to begin with) and execute them in parallel and wait for them to complete before next iteration. I dont know much about algorithms so I am stuck. Can you folks please help me to find an algorithm which finds max 'n' set of independent modules after each iteration which are no way dependent on each other.
A:
I posted a description of topological sorting recently in a question about make -j. Serendipity! From the Wikipedia article:
The canonical application of topological sorting (topological order) is in scheduling a sequence of jobs or tasks; topological sorting algorithms were first studied in the early 1960s in the context of the PERT technique for scheduling in project management (Jarnagin 1960). The jobs are represented by vertices, and there is an edge from x to y if job x must be completed before job y can be started (for example, when washing clothes, the washing machine must finish before we put the clothes to dry). Then, a topological sort gives an order in which to perform the jobs.
Rough outline:
Build a dependency graph.
Find n modules that have no dependencies. These can be executed now in parallel.
Remove those modules from the graph.
Repeat step 2 until done.
Read those links for a more detailed description.
A:
From your setting description you can also do it directly.
It looks like every modules known it's dependencies. Then adding a predicate function in every module stating if it can run is simple enough. A module can be run if and only if all of it's prerequisites dependencies are satisfied.
Top level modules have no dependencies so they can run from the start.
Basically that's a trivial implementation of a partial topological sorting (you don't have to explore all the dependency graph, just stay at top level).
Two pitfalls to be aware of:
If your dependencies contains cycles (A depends on B depending on C depending on A) it may loop forever (it means the problem has no solution). You should detect this case and report and error.
The modules you can run may be less than the number of thread. That should not be an error. Then you have found a solution either when you got n available modules to run or when you asked every modules if they can be run.
|
algorithm to find independent sets
|
Folks,
I have a problem. I am a writing a script in python which consists of several modules. Some of the modules are dependent on other modules, hence they should be run only after the dependent modules are successfully run. So each modules derives from a base class module and overrides a list called DEPENDENCIES which is a list of dependecies to be met beofre this module is run. There is one module which needs to be run before all other modules.Currently I am doing something like this.
modules_to_run.append(a)
modules_to_run.append(b)
modules_to_run.append(c)
.....
.....
modules_to_run.append(z)
# Very simplistically just run the Analysis modules sequentially in
# an order that respects their dependencies
foundOne = True
while foundOne and len(modules_to_run) > 0:
foundOne = False
for module in modules_to_run:
if len(module.DEPENDENCIES) == 0:
foundOne = True
print_log("Executing module %s..." % module.__name__, log)
try:
module().execute()
modules_to_run.remove(module)
for module2 in modules_to_run:
try:
module2.DEPENDENCIES.remove(module)
except:
#module may not be in module2's DEPENDENCIES
pass
except Exception as e:
print_log("ERROR: %s did not run to completion" % module.__name__, log)
modules_to_run.remove(module)
print_log(e, log)
for module in modules_to_run:
name = module.__name__
print_log("ERROR: %s has unmet dependencies and could not be run:" % name, log)
print_log(module.DEPENDENCIES, log)
Now I am seeing that some modules are taking long time to execute and script tun time is too long. So I wanted to make it multi threaded so that independent modules can run simultaneously thus saving time. So I want a solution where after each iteration , I'll recalculate 'n' independent modules ( where 'n' is max no of threads, typically 2 to begin with) and execute them in parallel and wait for them to complete before next iteration. I dont know much about algorithms so I am stuck. Can you folks please help me to find an algorithm which finds max 'n' set of independent modules after each iteration which are no way dependent on each other.
|
[
"I posted a description of topological sorting recently in a question about make -j. Serendipity! From the Wikipedia article:\n\nThe canonical application of topological sorting (topological order) is in scheduling a sequence of jobs or tasks; topological sorting algorithms were first studied in the early 1960s in the context of the PERT technique for scheduling in project management (Jarnagin 1960). The jobs are represented by vertices, and there is an edge from x to y if job x must be completed before job y can be started (for example, when washing clothes, the washing machine must finish before we put the clothes to dry). Then, a topological sort gives an order in which to perform the jobs.\n\nRough outline:\n\nBuild a dependency graph.\nFind n modules that have no dependencies. These can be executed now in parallel.\nRemove those modules from the graph.\nRepeat step 2 until done.\n\nRead those links for a more detailed description.\n",
"From your setting description you can also do it directly.\nIt looks like every modules known it's dependencies. Then adding a predicate function in every module stating if it can run is simple enough. A module can be run if and only if all of it's prerequisites dependencies are satisfied. \nTop level modules have no dependencies so they can run from the start.\nBasically that's a trivial implementation of a partial topological sorting (you don't have to explore all the dependency graph, just stay at top level).\nTwo pitfalls to be aware of:\nIf your dependencies contains cycles (A depends on B depending on C depending on A) it may loop forever (it means the problem has no solution). You should detect this case and report and error.\nThe modules you can run may be less than the number of thread. That should not be an error. Then you have found a solution either when you got n available modules to run or when you asked every modules if they can be run.\n"
] |
[
2,
1
] |
[] |
[] |
[
"algorithm",
"data_structures",
"python"
] |
stackoverflow_0002395525_algorithm_data_structures_python.txt
|
Q:
Python UTF-16 WAVY DASH encoding question / issue
I was doing some work today, and came across an issue where something "looked funny". I had been interpreting some string data as utf-8, and checking the encoded form. The data was coming from ldap (Specifically, Active Directory) via python-ldap. No surprises there.
So I came upon the byte sequence '\xe3\x80\xb0' a few times, which, when decoded as utf-8, is unicode codepoint 3030 (wavy dash). I need the string data in utf-16, so naturally I converted it via .encode('utf-16'). Unfortunately, it seems python doesn't like this character:
D:\> python
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> u"\u3030"
u'\u3030'
>>> u"\u3030".encode("utf-8")
'\xe3\x80\xb0'
>>> u"\u3030".encode("utf-16-le")
'00'
>>> u"\u3030".encode("utf-16-be")
'00'
>>> '\xe3\x80\xb0'.decode('utf-8')
u'\u3030'
>>> '\xe3\x80\xb0'.decode('utf-8').encode('utf-16')
'\xff\xfe00'
>>> '\xe3\x80\xb0'.decode('utf-8').encode('utf-16-le').decode('utf-8')
u'00'
It seems IronPython isn't a fan either:
D:\ipy
IronPython 2.6 Beta 2 (2.6.0.20) on .NET 2.0.50727.3053
Type "help", "copyright", "credits" or "license" for more information.
>>> u"\u3030"
u'\u3030'
>>> u"\u3030".encode('utf-8')
u'\xe3\x80\xb0'
>>> u"\u3030".encode('utf-16-le')
'00'
If somebody could tell me what, exactly, is going on here, it'd be much appreciated.
A:
This seems to be the correct behaviour. The character u'\u3030' when encoded in UTF-16 is the same as the encoding of '00' in UTF-8. It looks strange, but it's correct.
The '\xff\xfe' you can see is just a Byte Order Mark.
Are you sure you want a wavy dash, and not some other character? If you were hoping for a different character then it might be because it had already been misencoded before entering your application.
A:
But it decodes okay:
>>> u"\u3030".encode("utf-16-le")
'00'
>>> '00'.decode("utf-16-le")
u'\u3030'
It's that the UTF-16 encoding of that character happens to coincide with the ASCII code for '0'. You could also represent it with '\x30\x30':
>>> '00' == '\x30\x30'
True
A:
You are being confused by two things here (threw me off too):
utf-16 and utf-32 encodings use a BOM unless you specify which byte order to use, via utf-16-be and such. This is the \xff\xfe in the second last line.
'00' is two of the characters digit zero. It is not a null character. That'd print differently anyway:
>>> '\0\0'
'\x00\x00'
A:
There is a basic error in your sample code above. Remember, you encode Unicode to an encoded string, and you decode from an encoded string back to Unicode. So, you do:
'\xe3\x80\xb0'.decode('utf-8').encode('utf-16-le').decode('utf-8')
which translates to the following steps:
'\xe3\x80\xb0' # (some string)
.decode('utf-8') # decode above text as UTF-8 encoded text, giving u'\u3030'
.encode('utf-16-le') # encode u'\u3030' as UTF-16-LE, i.e. '00'
.decode('utf-8') # OOPS! decode using the wrong encoding here!
u'\u3030' is indeed encoded as '00' (ascii zero twice) in UTF-16LE but you somehow think that this is a null byte ('\0') or something.
Remember, you can't reach to the same character if you encode with one and decode with another encoding:
>>> import unicodedata as ud
>>> c= unichr(193)
>>> ud.name(c)
'LATIN CAPITAL LETTER A WITH ACUTE'
>>> ud.name(c.encode("cp1252").decode("cp1253"))
'GREEK CAPITAL LETTER ALPHA'
In this code, I encoded to Windows-1252 and decoded from Windows-1253. In your code, you encoded to UTF-16LE and decoded from UTF-8.
|
Python UTF-16 WAVY DASH encoding question / issue
|
I was doing some work today, and came across an issue where something "looked funny". I had been interpreting some string data as utf-8, and checking the encoded form. The data was coming from ldap (Specifically, Active Directory) via python-ldap. No surprises there.
So I came upon the byte sequence '\xe3\x80\xb0' a few times, which, when decoded as utf-8, is unicode codepoint 3030 (wavy dash). I need the string data in utf-16, so naturally I converted it via .encode('utf-16'). Unfortunately, it seems python doesn't like this character:
D:\> python
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> u"\u3030"
u'\u3030'
>>> u"\u3030".encode("utf-8")
'\xe3\x80\xb0'
>>> u"\u3030".encode("utf-16-le")
'00'
>>> u"\u3030".encode("utf-16-be")
'00'
>>> '\xe3\x80\xb0'.decode('utf-8')
u'\u3030'
>>> '\xe3\x80\xb0'.decode('utf-8').encode('utf-16')
'\xff\xfe00'
>>> '\xe3\x80\xb0'.decode('utf-8').encode('utf-16-le').decode('utf-8')
u'00'
It seems IronPython isn't a fan either:
D:\ipy
IronPython 2.6 Beta 2 (2.6.0.20) on .NET 2.0.50727.3053
Type "help", "copyright", "credits" or "license" for more information.
>>> u"\u3030"
u'\u3030'
>>> u"\u3030".encode('utf-8')
u'\xe3\x80\xb0'
>>> u"\u3030".encode('utf-16-le')
'00'
If somebody could tell me what, exactly, is going on here, it'd be much appreciated.
|
[
"This seems to be the correct behaviour. The character u'\\u3030' when encoded in UTF-16 is the same as the encoding of '00' in UTF-8. It looks strange, but it's correct.\nThe '\\xff\\xfe' you can see is just a Byte Order Mark.\nAre you sure you want a wavy dash, and not some other character? If you were hoping for a different character then it might be because it had already been misencoded before entering your application.\n",
"But it decodes okay:\n>>> u\"\\u3030\".encode(\"utf-16-le\")\n'00'\n>>> '00'.decode(\"utf-16-le\")\nu'\\u3030'\n\nIt's that the UTF-16 encoding of that character happens to coincide with the ASCII code for '0'. You could also represent it with '\\x30\\x30':\n>>> '00' == '\\x30\\x30'\nTrue\n\n",
"You are being confused by two things here (threw me off too):\n\nutf-16 and utf-32 encodings use a BOM unless you specify which byte order to use, via utf-16-be and such. This is the \\xff\\xfe in the second last line.\n'00' is two of the characters digit zero. It is not a null character. That'd print differently anyway:\n>>> '\\0\\0'\n'\\x00\\x00'\n\n\n",
"There is a basic error in your sample code above. Remember, you encode Unicode to an encoded string, and you decode from an encoded string back to Unicode. So, you do:\n'\\xe3\\x80\\xb0'.decode('utf-8').encode('utf-16-le').decode('utf-8')\n\nwhich translates to the following steps:\n'\\xe3\\x80\\xb0' # (some string)\n.decode('utf-8') # decode above text as UTF-8 encoded text, giving u'\\u3030'\n.encode('utf-16-le') # encode u'\\u3030' as UTF-16-LE, i.e. '00'\n.decode('utf-8') # OOPS! decode using the wrong encoding here!\n\nu'\\u3030' is indeed encoded as '00' (ascii zero twice) in UTF-16LE but you somehow think that this is a null byte ('\\0') or something.\nRemember, you can't reach to the same character if you encode with one and decode with another encoding:\n>>> import unicodedata as ud\n>>> c= unichr(193)\n>>> ud.name(c)\n'LATIN CAPITAL LETTER A WITH ACUTE'\n>>> ud.name(c.encode(\"cp1252\").decode(\"cp1253\"))\n'GREEK CAPITAL LETTER ALPHA'\n\nIn this code, I encoded to Windows-1252 and decoded from Windows-1253. In your code, you encoded to UTF-16LE and decoded from UTF-8.\n"
] |
[
2,
2,
1,
0
] |
[] |
[] |
[
"encoding",
"python",
"unicode",
"utf_16",
"utf_8"
] |
stackoverflow_0002269171_encoding_python_unicode_utf_16_utf_8.txt
|
Q:
Elixir create_all() not creating database and tables
I'm using Elixir 0.7.1 , Sqlalchemy 0.6beta1 , MySQLdb 1.2.2.
My Model file 'model.py' looks like this:
from elixir import *
from datetime import datetime
class Author:
first_name = Field(Unicode(64))
last_name = Field(Unicode(64))
class Article:
title = Field(Unicode(64))
class Category:
name = Field(Unicode(64))
setup_all()
metadata.bind = "mysql://user:pass@localhost/dbname"
metadata.bind.echo = True
create_all()
metadata.create_all()
after executing : python model.py , no tables are created and no errors are thrown.
Here is a list of echo'd commands that are issued to the SQL server:
2010-03-06 19:50:22,004 INFO sqlalchemy.engine.base.Engine.0x...6c4c SELECT DATABASE()
2010-03-06 19:50:22,004 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
2010-03-06 19:50:22,005 INFO sqlalchemy.engine.base.Engine.0x...6c4c SHOW VARIABLES LIKE 'character_set%%'
2010-03-06 19:50:22,005 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
2010-03-06 19:50:22,006 INFO sqlalchemy.engine.base.Engine.0x...6c4c SHOW VARIABLES LIKE 'lower_case_table_names'
2010-03-06 19:50:22,006 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
2010-03-06 19:50:22,007 INFO sqlalchemy.engine.base.Engine.0x...6c4c SHOW COLLATION
2010-03-06 19:50:22,007 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
2010-03-06 19:50:22,009 INFO sqlalchemy.engine.base.Engine.0x...6c4c SHOW VARIABLES LIKE 'sql_mode'
2010-03-06 19:50:22,010 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
I have searched for a solution and couldn't find any.
A:
Well, you have to inherit from the Entity base class (or from another base class of your choosing that use the EntityMeta metaclass).
class Author(Entity):
first_name = Field(Unicode(64))
last_name = Field(Unicode(64))
class Article(Entity):
title = Field(Unicode(64))
class Category(Entity):
name = Field(Unicode(64))
|
Elixir create_all() not creating database and tables
|
I'm using Elixir 0.7.1 , Sqlalchemy 0.6beta1 , MySQLdb 1.2.2.
My Model file 'model.py' looks like this:
from elixir import *
from datetime import datetime
class Author:
first_name = Field(Unicode(64))
last_name = Field(Unicode(64))
class Article:
title = Field(Unicode(64))
class Category:
name = Field(Unicode(64))
setup_all()
metadata.bind = "mysql://user:pass@localhost/dbname"
metadata.bind.echo = True
create_all()
metadata.create_all()
after executing : python model.py , no tables are created and no errors are thrown.
Here is a list of echo'd commands that are issued to the SQL server:
2010-03-06 19:50:22,004 INFO sqlalchemy.engine.base.Engine.0x...6c4c SELECT DATABASE()
2010-03-06 19:50:22,004 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
2010-03-06 19:50:22,005 INFO sqlalchemy.engine.base.Engine.0x...6c4c SHOW VARIABLES LIKE 'character_set%%'
2010-03-06 19:50:22,005 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
2010-03-06 19:50:22,006 INFO sqlalchemy.engine.base.Engine.0x...6c4c SHOW VARIABLES LIKE 'lower_case_table_names'
2010-03-06 19:50:22,006 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
2010-03-06 19:50:22,007 INFO sqlalchemy.engine.base.Engine.0x...6c4c SHOW COLLATION
2010-03-06 19:50:22,007 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
2010-03-06 19:50:22,009 INFO sqlalchemy.engine.base.Engine.0x...6c4c SHOW VARIABLES LIKE 'sql_mode'
2010-03-06 19:50:22,010 INFO sqlalchemy.engine.base.Engine.0x...6c4c ()
I have searched for a solution and couldn't find any.
|
[
"Well, you have to inherit from the Entity base class (or from another base class of your choosing that use the EntityMeta metaclass).\nclass Author(Entity):\n first_name = Field(Unicode(64))\n last_name = Field(Unicode(64))\n\nclass Article(Entity):\n title = Field(Unicode(64))\n\nclass Category(Entity):\n name = Field(Unicode(64))\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_elixir",
"sqlalchemy"
] |
stackoverflow_0002394743_python_python_elixir_sqlalchemy.txt
|
Q:
Aggregating across columns in Django
I'm trying to figure out if there's a way to do a somewhat-complex aggregation in Django using its ORM, or if I'm going to have to use extra() to stick in some raw SQL.
Here are my object models (stripped to show just the essentials):
class Submission(Models.model)
favorite_of = models.ManyToManyField(User, related_name="favorite_submissions")
class Response(Models.model)
submission = models.ForeignKey(Submission)
voted_up_by = models.ManyToManyField(User, related_name="voted_up_responses")
What I want to do is sum all the votes for a given submission: that is, all of the votes for any of its responses, and then also including the number of people who marked the submission as a favorite.
I have the first part working using the following code; this returns the total votes for all responses of each submission:
submission_list = Response.objects\
.values('submission')\
.annotate(votes=Count('voted_up_by'))\
.filter(votes__gt=0)\
.order_by('-votes')[:TOP_NUM]
(So after getting the vote total, I sort in descending order and return the top TOP_NUM submissions, to get a "best of" listing.)
That part works. Is there any way you can suggest to include the number of people who have favorited each submission in its votes? (I'd prefer to avoid extra() for portability, but I'm thinking it may be necessary, and I'm willing to use it.)
EDIT: I realized after reading the suggestions below that I should have been clearer in my description of the problem. The ideal solution would be one that allowed me to sort by total votes (the sum of voted_up_by and favorited) and then pick just the top few, all within the database. If that's not possible then I'm willing to load a few of the fields of each response and do the processing in Python; but since I'll be dealing with 100,000+ records, it'd be nice to avoid that overhead. (Also, to Adam and Dmitry: I'm sorry for the delay in responding!)
A:
One possibility would be to re-arrange your current query slightly. What if you tried something like the following:
submission_list = Response.objects\
.annotate(votes=Count('voted_up_by'))\
.filter(votes__gt=0)\
.order_by('-votes')[:TOP_NUM]
submission_list.query.group_by = ['submission_id']
This will return a queryset of Response objects (objects with the same Submission will be lumped together). In order to access the related submission and/or the favorite_of list/count, you have two options:
num_votes = submission_list[0].votes
submission = submission_list[0].submission
num_favorite = submission.favorite_of.count()
or...
submissions = []
for response in submission_list:
submission = response.submission
submission.votes = response.votes
submissions.append(submission)
num_votes = submissions[0].votes
submission = submissions[0]
num_favorite = submission.favorite_of.count()
Basically the first option has the benefit of still being a queryset, but you have to be sure to access the submission object in order to get any info about the submission (since each object in the queryset is technically a Response). The second option has the benefit of being a list of the submissions with both the favorite_of list as well as the votes, but it is no longer a queryset (so be sure you don't need to alter the query anymore afterwards).
A:
You can count favorites in another query like
favorite_list = Submission.objects.annotate(favorites=Count(favorite_of))
After that you add the values from two lists:
total_votes = {}
for item in submission_list:
total_votes[item.submission.id] = item.voted_by
for item in favorite_list:
has_votes = total_votes.get(item.id, 0)
total_votes[item.id] = has_votes + item.favorites
I am using ids in the dictionary because Submission objects will not be identical. If you need the Submissions themselves, you may use one more dictionary or store tuple (submission, votes) instead of just votes.
Added: this solution is better than the previous because you have only two DB requests.
|
Aggregating across columns in Django
|
I'm trying to figure out if there's a way to do a somewhat-complex aggregation in Django using its ORM, or if I'm going to have to use extra() to stick in some raw SQL.
Here are my object models (stripped to show just the essentials):
class Submission(Models.model)
favorite_of = models.ManyToManyField(User, related_name="favorite_submissions")
class Response(Models.model)
submission = models.ForeignKey(Submission)
voted_up_by = models.ManyToManyField(User, related_name="voted_up_responses")
What I want to do is sum all the votes for a given submission: that is, all of the votes for any of its responses, and then also including the number of people who marked the submission as a favorite.
I have the first part working using the following code; this returns the total votes for all responses of each submission:
submission_list = Response.objects\
.values('submission')\
.annotate(votes=Count('voted_up_by'))\
.filter(votes__gt=0)\
.order_by('-votes')[:TOP_NUM]
(So after getting the vote total, I sort in descending order and return the top TOP_NUM submissions, to get a "best of" listing.)
That part works. Is there any way you can suggest to include the number of people who have favorited each submission in its votes? (I'd prefer to avoid extra() for portability, but I'm thinking it may be necessary, and I'm willing to use it.)
EDIT: I realized after reading the suggestions below that I should have been clearer in my description of the problem. The ideal solution would be one that allowed me to sort by total votes (the sum of voted_up_by and favorited) and then pick just the top few, all within the database. If that's not possible then I'm willing to load a few of the fields of each response and do the processing in Python; but since I'll be dealing with 100,000+ records, it'd be nice to avoid that overhead. (Also, to Adam and Dmitry: I'm sorry for the delay in responding!)
|
[
"One possibility would be to re-arrange your current query slightly. What if you tried something like the following:\nsubmission_list = Response.objects\\\n .annotate(votes=Count('voted_up_by'))\\\n .filter(votes__gt=0)\\\n .order_by('-votes')[:TOP_NUM]\nsubmission_list.query.group_by = ['submission_id']\n\nThis will return a queryset of Response objects (objects with the same Submission will be lumped together). In order to access the related submission and/or the favorite_of list/count, you have two options:\nnum_votes = submission_list[0].votes\nsubmission = submission_list[0].submission\nnum_favorite = submission.favorite_of.count()\n\nor...\nsubmissions = []\nfor response in submission_list:\n submission = response.submission\n submission.votes = response.votes\n submissions.append(submission)\nnum_votes = submissions[0].votes\nsubmission = submissions[0]\nnum_favorite = submission.favorite_of.count()\n\nBasically the first option has the benefit of still being a queryset, but you have to be sure to access the submission object in order to get any info about the submission (since each object in the queryset is technically a Response). The second option has the benefit of being a list of the submissions with both the favorite_of list as well as the votes, but it is no longer a queryset (so be sure you don't need to alter the query anymore afterwards).\n",
"You can count favorites in another query like\nfavorite_list = Submission.objects.annotate(favorites=Count(favorite_of))\n\nAfter that you add the values from two lists:\ntotal_votes = {}\nfor item in submission_list:\n total_votes[item.submission.id] = item.voted_by\nfor item in favorite_list:\n has_votes = total_votes.get(item.id, 0)\n total_votes[item.id] = has_votes + item.favorites\n\nI am using ids in the dictionary because Submission objects will not be identical. If you need the Submissions themselves, you may use one more dictionary or store tuple (submission, votes) instead of just votes.\nAdded: this solution is better than the previous because you have only two DB requests.\n"
] |
[
1,
0
] |
[] |
[] |
[
"aggregate",
"django",
"orm",
"python"
] |
stackoverflow_0002394778_aggregate_django_orm_python.txt
|
Q:
Memory error due to the huge input file size
When I using the following code to read file:
lines=file("data.txt").read().split("\n")
I have the following error
MemoryError
the file size is
ls -l
-rw-r--r-- 1 charlie charlie 1258467201 Sep 26 12:57 data.txt
A:
Obviously the file is too large to be read into memory all at once.
Why not just use:
with open("data.txt") as myfile:
for line in myfile:
do_something(line.rstrip("\n"))
or, if you're not on Python 2.6 and higher:
myfile = open("data.txt")
for line in myfile:
do_something(line.rstrip("\n"))
In both cases, you'll get an iterator that can be treated much like a list of strings.
EDIT: Since your way of reading the entire file into one large string and then splitting it on newlines will remove the newlines in the process, I have added a .rstrip("\n") to my examples in order to better simulate the result.
A:
use this code to read file line by line:
for line in open('data.txt'):
# work with line
|
Memory error due to the huge input file size
|
When I using the following code to read file:
lines=file("data.txt").read().split("\n")
I have the following error
MemoryError
the file size is
ls -l
-rw-r--r-- 1 charlie charlie 1258467201 Sep 26 12:57 data.txt
|
[
"Obviously the file is too large to be read into memory all at once.\nWhy not just use:\nwith open(\"data.txt\") as myfile:\n for line in myfile:\n do_something(line.rstrip(\"\\n\"))\n\nor, if you're not on Python 2.6 and higher:\nmyfile = open(\"data.txt\")\nfor line in myfile:\n do_something(line.rstrip(\"\\n\"))\n\nIn both cases, you'll get an iterator that can be treated much like a list of strings.\nEDIT: Since your way of reading the entire file into one large string and then splitting it on newlines will remove the newlines in the process, I have added a .rstrip(\"\\n\") to my examples in order to better simulate the result.\n",
"use this code to read file line by line:\nfor line in open('data.txt'):\n # work with line\n\n"
] |
[
25,
3
] |
[] |
[] |
[
"file",
"python"
] |
stackoverflow_0002396238_file_python.txt
|
Q:
migrating from one framework to another in python
I'm having trouble deciding which python framework to use for my website. So I've decided to bite the bullet and use Django. My question is how easy (or difficult) will it be to migrate to a different framework in future if I have issues with Django ?
A:
Your database queries(and object models), url config, and templates to say the least will all be specific to django. That said - if you understand what you're doing, recreating them in another package shouldn't take too long if you really need to at some later time.
edit: this is all assuming you dont integrate third party projects such as sqlalchemy and mako. Django plays nice with the builtins it ships with so it's often more trouble than its worth to use said modules.
A:
For the template part, Jinja is pretty similar to Django, but stand-alone. It might help you to migrate your templates to another framework.
(Or use it right away, I've found Jinja similar but quite superior to Django's default template system.)
|
migrating from one framework to another in python
|
I'm having trouble deciding which python framework to use for my website. So I've decided to bite the bullet and use Django. My question is how easy (or difficult) will it be to migrate to a different framework in future if I have issues with Django ?
|
[
"Your database queries(and object models), url config, and templates to say the least will all be specific to django. That said - if you understand what you're doing, recreating them in another package shouldn't take too long if you really need to at some later time.\nedit: this is all assuming you dont integrate third party projects such as sqlalchemy and mako. Django plays nice with the builtins it ships with so it's often more trouble than its worth to use said modules.\n",
"For the template part, Jinja is pretty similar to Django, but stand-alone. It might help you to migrate your templates to another framework.\n(Or use it right away, I've found Jinja similar but quite superior to Django's default template system.)\n"
] |
[
1,
1
] |
[] |
[] |
[
"django",
"frameworks",
"migrate",
"python"
] |
stackoverflow_0002396294_django_frameworks_migrate_python.txt
|
Q:
Load huge data to memory using python
I have to load large data to the memory, and the structure is list.
How can I get another approach.
thanx
A:
process the data line by line, eg
for line in open("file"):
print "do processing of line:",line
Or if you really really want to load one whole chunk to memory, you can try memory mapping.
import mmap,os,re
bigfile = open( "file2" )
length = os.stat(bigfile.fileno()).st_size
try:
mapping = mmap.mmap(bigfile.fileno(), length, mmap.MAP_PRIVATE, mmap.PROT_READ )
except AttributeError:
mapping = mmap.mmap(bigfile.fileno(), 0, None, mmap.ACCESS_READ )
data = mapping.read(length)
# example, finding a pattern
pat =re.compile("pattern",re.M|re.DOTALL)
print pat.findall(data)
A:
If the data is too large to fit into your computer's memory you will have to read it piece by piece. If it is not too large you may still want to do this but it might suit your needs to read it into memory in its entirety. If you edit your question to explain more about your needs and what the characteristics of the data are, then you will get much more helpful answers than this one.
A:
Is there any structure to this data, like a big list of customer records, or is it just one big blob like an image, audio, or video data? If the former, you might want to restructure the data into a database. sqlite is included with Python as of Py2.5, and is sufficient for many data sorting and sifting tasks.
And how large is "large"? You would be surprised how much data Python can keep in memory at once. Give us some more details about your large list of data.
|
Load huge data to memory using python
|
I have to load large data to the memory, and the structure is list.
How can I get another approach.
thanx
|
[
"process the data line by line, eg\nfor line in open(\"file\"):\n print \"do processing of line:\",line\n\nOr if you really really want to load one whole chunk to memory, you can try memory mapping.\nimport mmap,os,re\nbigfile = open( \"file2\" )\nlength = os.stat(bigfile.fileno()).st_size\ntry:\n mapping = mmap.mmap(bigfile.fileno(), length, mmap.MAP_PRIVATE, mmap.PROT_READ )\nexcept AttributeError:\n mapping = mmap.mmap(bigfile.fileno(), 0, None, mmap.ACCESS_READ )\ndata = mapping.read(length)\n# example, finding a pattern\npat =re.compile(\"pattern\",re.M|re.DOTALL)\nprint pat.findall(data)\n\n",
"If the data is too large to fit into your computer's memory you will have to read it piece by piece. If it is not too large you may still want to do this but it might suit your needs to read it into memory in its entirety. If you edit your question to explain more about your needs and what the characteristics of the data are, then you will get much more helpful answers than this one.\n",
"Is there any structure to this data, like a big list of customer records, or is it just one big blob like an image, audio, or video data? If the former, you might want to restructure the data into a database. sqlite is included with Python as of Py2.5, and is sufficient for many data sorting and sifting tasks.\nAnd how large is \"large\"? You would be surprised how much data Python can keep in memory at once. Give us some more details about your large list of data.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002396350_python.txt
|
Q:
App Engine, Python: problem updating datastore record
I need to update a record in the datastore, but instead of updated record I get always a new record.
My model:
class PageModel(db.Model):
title = db.StringProperty()
content = db.TextProperty()
reference = db.SelfReferenceProperty()
user = db.UserProperty(auto_current_user = True)
created = db.DateTimeProperty(auto_now_add = True)
modified = db.DateTimeProperty(auto_now = True)
type = db.StringProperty()
template = db.StringProperty()
position = db.IntegerProperty()
hidden = db.BooleanProperty()
historical = db.BooleanProperty()
My handler:
class EditHandler(webapp.RequestHandler):
def post(self):
if self.request.path[6:] == '':
page_id = 8
else:
page_id = int(self.request.path[6:]) # path: /edit/35
#id = self.request.get('id')
CP = PageModel.get_by_id(int(page_id))
key = CP.key()
title = self.request.get('title')
content = self.request.get('content')
type = self.request.get('type')
hidden = self.request.get('hidden')
#position = self.request.get('type')
reference = PageModel.get_by_id(int(self.request.get('reference')))
template = self.request.get('template')
if ".htm" not in template:
template = "index.htm"
#if title == '' or content == '':
#doRender(self,'create_page.htm',{'error' : 'Please fill in all fields'} )
#return
#edited_page = PageModel(key=CP.key, title=title, content=content, type=type, reference=reference, template=template)
edited_page = PageModel()
edited_page.key = CP.key()
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()
There should be something wrong with edited_page.key = CP.key(), or what?!
A:
Why are you created a new PageModel everytime? instead edit the one you got by id i.e. CP ? e.g.
edited_page = CP
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()
|
App Engine, Python: problem updating datastore record
|
I need to update a record in the datastore, but instead of updated record I get always a new record.
My model:
class PageModel(db.Model):
title = db.StringProperty()
content = db.TextProperty()
reference = db.SelfReferenceProperty()
user = db.UserProperty(auto_current_user = True)
created = db.DateTimeProperty(auto_now_add = True)
modified = db.DateTimeProperty(auto_now = True)
type = db.StringProperty()
template = db.StringProperty()
position = db.IntegerProperty()
hidden = db.BooleanProperty()
historical = db.BooleanProperty()
My handler:
class EditHandler(webapp.RequestHandler):
def post(self):
if self.request.path[6:] == '':
page_id = 8
else:
page_id = int(self.request.path[6:]) # path: /edit/35
#id = self.request.get('id')
CP = PageModel.get_by_id(int(page_id))
key = CP.key()
title = self.request.get('title')
content = self.request.get('content')
type = self.request.get('type')
hidden = self.request.get('hidden')
#position = self.request.get('type')
reference = PageModel.get_by_id(int(self.request.get('reference')))
template = self.request.get('template')
if ".htm" not in template:
template = "index.htm"
#if title == '' or content == '':
#doRender(self,'create_page.htm',{'error' : 'Please fill in all fields'} )
#return
#edited_page = PageModel(key=CP.key, title=title, content=content, type=type, reference=reference, template=template)
edited_page = PageModel()
edited_page.key = CP.key()
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()
There should be something wrong with edited_page.key = CP.key(), or what?!
|
[
"Why are you created a new PageModel everytime? instead edit the one you got by id i.e. CP ? e.g.\nedited_page = CP \nedited_page.title = title\nedited_page.content = content\nedited_page.type = type\nedited_page.reference = reference\nedited_page.template = template\n\nedited_page.put()\n\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002396437_google_app_engine_google_cloud_datastore_python.txt
|
Q:
How to split big numbers?
I have a big number, which I need to split into smaller numbers in Python. I wrote the following code to swap between the two:
def split_number (num, part_size):
string = str(num)
string_size = len(string)
arr = []
pointer = 0
while pointer < string_size:
e = pointer + part_size
arr.append(int(string[pointer:e]))
pointer += part_size
return arr
def join_number(arr):
num = ""
for x in arr:
num += str(x)
return int(num)
But the number comes back different. It's hard to debug because the number is so large so before I go into that I thought I would post it here to see if there is a better way to do it or whether I'm missing something obvious.
Thanks a lot.
A:
Clearly, any leading 0s in the "parts" can't be preserved by this operation. Can't join_number also receive the part_size argument, so that it can reconstruct the string formats with all the leading zeros?
Without some information such as part_size that's known to both the sender and receiver, or the equivalent (such as the base number to use for a similar split and join based on arithmetic, roughly equivalent to 10**part_size given the way you're using part_size), the task becomes quite a bit harder. If the receiver is initially clueless about this, why not just place the part_size (or base, etc) as the very first int in the arr list that's being sent and received? That way, the encoding trivially becomes "self-sufficient", i.e., doesn't need any supplementary parameter known to both sender and receiver.
A:
There is no need to convert to and from strings, which can be very time consuming for really large numbers
>>> def split_number(n, part_size):
... base = 10**part_size
... L = []
... while n:
... n,part = divmod(n,base)
... L.append(part)
... return L[::-1]
...
>>> def join_number(L, part_size):
... base = 10**part_size
... n = 0
... L = L[::-1]
... while L:
... n = n*base+L.pop()
... return n
...
>>> print split_number(1000005,3)
[1, 0, 5]
>>> print join_number([1,0,5],3)
1000005
>>>
Here you can see that just converting the number to a str takes longer than my entire function!
>>> from time import time
>>> t=time();b = split_number(2**100000,3000);print time()-t
0.204252004623
>>> t=time();b = split_number(2**100000,30);print time()-t
0.486856222153
>>> t=time();b = str(2**100000);print time()-t
0.730905056
A:
You should think of the following number split into 3-sized chunks:
1000005 -> 100 000 5
You have two problems. The first is that if you put those integers back together, you'll get:
100 0 5 -> 100005
(i.e., the middle one is 0, not 000) which is not what you started with. Second problem is that you're not sure what size the last part should be.
I would ensure that you're first using a string whose length is an exact multiple of the part size so you know exactly how big each part should be:
def split_number (num, part_size):
string = str(num)
string_size = len(string)
while string_size % part_size != 0:
string = "0%s"%(string)
string_size = string_size + 1
arr = []
pointer = 0
while pointer < string_size:
e = pointer + part_size
arr.append(int(string[pointer:e]))
pointer += part_size
return arr
Secondly, make sure that you put the parts back together with the right length for each part (ensuring you don't put leading zeros on the first part of course):
def join_number(arr, part_size):
fmt_str = "%%s%%0%dd"%(part_size)
num = arr[0]
for x in arr[1:]:
num = fmt_str%(num,int(x))
return int(num)
Tying it all together, the following complete program:
#!/usr/bin/python
def split_number (num, part_size):
string = str(num)
string_size = len(string)
while string_size % part_size != 0:
string = "0%s"%(string)
string_size = string_size + 1
arr = []
pointer = 0
while pointer < string_size:
e = pointer + part_size
arr.append(int(string[pointer:e]))
pointer += part_size
return arr
def join_number(arr, part_size):
fmt_str = "%%s%%0%dd"%(part_size)
num = arr[0]
for x in arr[1:]:
num = fmt_str%(num,int(x))
return int(num)
x = 1000005
print x
y = split_number(x,3)
print y
z = join_number(y,3)
print z
produces the output:
1000005
[1, 0, 5]
1000005
which shows that it goes back together.
Just keep in mind I haven't done Python for a few years. There's almost certainly a more "Pythonic" way to do it with those new-fangled lambdas and things (or whatever Python calls them) but, since your code was of the basic form, I just answered with the minimal changes required to get it working. Oh yeah, and be wary of negative numbers :-)
A:
Here's some code for Alex Martelli's answer.
def digits(n, base):
while n:
yield n % base
n //= base
def split_number(n, part_size):
base = 10 ** part_size
return list(digits(n, base))
def join_number(digits, part_size):
base = 10 ** part_size
return sum(d * (base ** i) for i, d in enumerate(digits))
|
How to split big numbers?
|
I have a big number, which I need to split into smaller numbers in Python. I wrote the following code to swap between the two:
def split_number (num, part_size):
string = str(num)
string_size = len(string)
arr = []
pointer = 0
while pointer < string_size:
e = pointer + part_size
arr.append(int(string[pointer:e]))
pointer += part_size
return arr
def join_number(arr):
num = ""
for x in arr:
num += str(x)
return int(num)
But the number comes back different. It's hard to debug because the number is so large so before I go into that I thought I would post it here to see if there is a better way to do it or whether I'm missing something obvious.
Thanks a lot.
|
[
"Clearly, any leading 0s in the \"parts\" can't be preserved by this operation. Can't join_number also receive the part_size argument, so that it can reconstruct the string formats with all the leading zeros?\nWithout some information such as part_size that's known to both the sender and receiver, or the equivalent (such as the base number to use for a similar split and join based on arithmetic, roughly equivalent to 10**part_size given the way you're using part_size), the task becomes quite a bit harder. If the receiver is initially clueless about this, why not just place the part_size (or base, etc) as the very first int in the arr list that's being sent and received? That way, the encoding trivially becomes \"self-sufficient\", i.e., doesn't need any supplementary parameter known to both sender and receiver.\n",
"There is no need to convert to and from strings, which can be very time consuming for really large numbers\n>>> def split_number(n, part_size):\n... base = 10**part_size\n... L = []\n... while n:\n... n,part = divmod(n,base)\n... L.append(part)\n... return L[::-1]\n... \n>>> def join_number(L, part_size):\n... base = 10**part_size\n... n = 0\n... L = L[::-1]\n... while L:\n... n = n*base+L.pop()\n... return n\n... \n>>> print split_number(1000005,3)\n[1, 0, 5]\n>>> print join_number([1,0,5],3)\n1000005\n>>> \n\nHere you can see that just converting the number to a str takes longer than my entire function!\n>>> from time import time\n>>> t=time();b = split_number(2**100000,3000);print time()-t\n0.204252004623\n>>> t=time();b = split_number(2**100000,30);print time()-t\n0.486856222153 \n>>> t=time();b = str(2**100000);print time()-t\n0.730905056\n\n",
"You should think of the following number split into 3-sized chunks:\n1000005 -> 100 000 5\n\nYou have two problems. The first is that if you put those integers back together, you'll get:\n100 0 5 -> 100005\n\n(i.e., the middle one is 0, not 000) which is not what you started with. Second problem is that you're not sure what size the last part should be.\nI would ensure that you're first using a string whose length is an exact multiple of the part size so you know exactly how big each part should be:\ndef split_number (num, part_size):\n string = str(num)\n string_size = len(string)\n while string_size % part_size != 0:\n string = \"0%s\"%(string)\n string_size = string_size + 1\n\n arr = []\n pointer = 0\n while pointer < string_size:\n e = pointer + part_size\n arr.append(int(string[pointer:e]))\n pointer += part_size\n return arr\n\nSecondly, make sure that you put the parts back together with the right length for each part (ensuring you don't put leading zeros on the first part of course):\ndef join_number(arr, part_size):\n fmt_str = \"%%s%%0%dd\"%(part_size)\n num = arr[0]\n for x in arr[1:]:\n num = fmt_str%(num,int(x))\n return int(num)\n\nTying it all together, the following complete program:\n#!/usr/bin/python\n\ndef split_number (num, part_size):\n string = str(num)\n string_size = len(string)\n while string_size % part_size != 0:\n string = \"0%s\"%(string)\n string_size = string_size + 1\n\n arr = []\n pointer = 0\n while pointer < string_size:\n e = pointer + part_size\n arr.append(int(string[pointer:e]))\n pointer += part_size\n return arr\n\ndef join_number(arr, part_size):\n fmt_str = \"%%s%%0%dd\"%(part_size)\n num = arr[0]\n for x in arr[1:]:\n num = fmt_str%(num,int(x))\n return int(num)\n\nx = 1000005\nprint x\ny = split_number(x,3)\nprint y\nz = join_number(y,3)\nprint z\n\nproduces the output:\n1000005\n[1, 0, 5]\n1000005\n\nwhich shows that it goes back together.\nJust keep in mind I haven't done Python for a few years. There's almost certainly a more \"Pythonic\" way to do it with those new-fangled lambdas and things (or whatever Python calls them) but, since your code was of the basic form, I just answered with the minimal changes required to get it working. Oh yeah, and be wary of negative numbers :-)\n",
"Here's some code for Alex Martelli's answer.\ndef digits(n, base):\n while n:\n yield n % base\n n //= base\n\ndef split_number(n, part_size):\n base = 10 ** part_size\n return list(digits(n, base))\n\ndef join_number(digits, part_size):\n base = 10 ** part_size\n return sum(d * (base ** i) for i, d in enumerate(digits))\n\n"
] |
[
2,
2,
1,
0
] |
[] |
[] |
[
"numbers",
"python",
"string"
] |
stackoverflow_0002394698_numbers_python_string.txt
|
Q:
how to document a python package
I know what's the standard way to document functions, classes and modules, but how do I document packages - do I put a docstring in __init__.py, or something else?
A:
Yes, just like for a function or class comment, the first item in the __init__.py file should be a comment string:
"""
This is the xyz package.
"""
Now if you import the package, and use help(package), you will see your docstring. See more here: http://www.python.org/dev/peps/pep-0257/
A:
See PEP257
A package may be documented in the module docstring of the __ init __.py file in the package directory.
|
how to document a python package
|
I know what's the standard way to document functions, classes and modules, but how do I document packages - do I put a docstring in __init__.py, or something else?
|
[
"Yes, just like for a function or class comment, the first item in the __init__.py file should be a comment string:\n\"\"\"\nThis is the xyz package.\n\"\"\"\n\nNow if you import the package, and use help(package), you will see your docstring. See more here: http://www.python.org/dev/peps/pep-0257/\n",
"See PEP257\n\nA package may be documented in the module docstring of the __ init __.py file in the package directory.\n\n"
] |
[
18,
5
] |
[
"Documenting is a good idea, so long as you don't document something obvious in your code\nTry to understand that most people reading your source will understand python, so commenting or documenting lines like this is pointless:\na = 1 #this assigns 1 to a\n\nBut commenting or documenting a rather complicated function or class is a good idea.\nGeneral rule of thumb: Imagine the next person to work on your code is a Axe wielding maniac and they know where you live. \nThat way you will always leave \"helpful\" comments/doc's\n"
] |
[
-3
] |
[
"documentation",
"package",
"python"
] |
stackoverflow_0002396141_documentation_package_python.txt
|
Q:
GTK StatusIcon: Coordinates of left-click?
how do I get the x/y-coordinates of a left click in a Gtk StatusIcon?
This is my first GTK app and I'm stuck. Is there any way to get details about the last button event that occurred? Or is it possible to pass those details to the handler function when connect()ing the "activate" callback?
Greets,
Philip
A:
Since the status icon isn't a widget, it's a bit roundabout. You might be able to pass in some kind of widget as part of the user parameter object and get the global mouse position on activate. See here on how you might.
|
GTK StatusIcon: Coordinates of left-click?
|
how do I get the x/y-coordinates of a left click in a Gtk StatusIcon?
This is my first GTK app and I'm stuck. Is there any way to get details about the last button event that occurred? Or is it possible to pass those details to the handler function when connect()ing the "activate" callback?
Greets,
Philip
|
[
"Since the status icon isn't a widget, it's a bit roundabout. You might be able to pass in some kind of widget as part of the user parameter object and get the global mouse position on activate. See here on how you might.\n"
] |
[
1
] |
[] |
[] |
[
"gtk",
"linux",
"pygtk",
"python"
] |
stackoverflow_0002396557_gtk_linux_pygtk_python.txt
|
Q:
How to supress Powershell window when using the -File option
I'm calling Powershell like so:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -noninteractive -nologo -file "C:\Users\dummy\Documents\dev\powershell\samples\test.ps1"
I'm calling it from a python script, but the same problem can be observed if called via a shortcut. I thought the -NonInteractive flag would cause Poweshell to execute in a hidden window, but it doesn't. Is there a way of supressing the console window when calling Powershell from an external application?
Solution based on Johannes Rössel suggestion
import subprocess
st_inf = subprocess.STARTUPINFO()
st_inf.dwFlags = st_inf.dwFlags | subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(["notepad"], startupinfo=st_inf)
A:
You can pass appropriate arguments to CreateProcess or Process.Start to suppress the console window.
However, PowerShell also has a -WindowStyle parameter which you can set to hidden.
A:
I had no luck with -WindowStyle Hidden, because a console window appeared every time for a while.
That's why I use a helper exe called PsRun.exe that does exactly that. You can download source and exe file Run scheduled tasks with WinForm GUI in PowerShell. I use it for scheduled tasks.
(Note that -windowstyle parameter is available only for V2.)
A:
Use -WindowStyle Hidden. See here.
|
How to supress Powershell window when using the -File option
|
I'm calling Powershell like so:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -noninteractive -nologo -file "C:\Users\dummy\Documents\dev\powershell\samples\test.ps1"
I'm calling it from a python script, but the same problem can be observed if called via a shortcut. I thought the -NonInteractive flag would cause Poweshell to execute in a hidden window, but it doesn't. Is there a way of supressing the console window when calling Powershell from an external application?
Solution based on Johannes Rössel suggestion
import subprocess
st_inf = subprocess.STARTUPINFO()
st_inf.dwFlags = st_inf.dwFlags | subprocess.STARTF_USESHOWWINDOW
subprocess.Popen(["notepad"], startupinfo=st_inf)
|
[
"You can pass appropriate arguments to CreateProcess or Process.Start to suppress the console window.\nHowever, PowerShell also has a -WindowStyle parameter which you can set to hidden.\n",
"I had no luck with -WindowStyle Hidden, because a console window appeared every time for a while. \nThat's why I use a helper exe called PsRun.exe that does exactly that. You can download source and exe file Run scheduled tasks with WinForm GUI in PowerShell. I use it for scheduled tasks.\n(Note that -windowstyle parameter is available only for V2.)\n",
"Use -WindowStyle Hidden. See here.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"popen",
"powershell",
"python",
"windowless"
] |
stackoverflow_0002396271_popen_powershell_python_windowless.txt
|
Q:
Weak reference callback is not called because of circular references
I'm trying to write a finalizer for Python classes that have circular references. I found out that weak reference callbacks are the way to go. Unfortunately, it seems the lambda I use as a callback is never called. For example, running this code:
def del_A(name):
print('An A deleted:' + name)
class A(object):
def __init__(self, name):
print('A created')
self.name = name
self._wr = weakref.ref(self, lambda wr, n = self.name: del_A(n))
class B(object):
def __init__(self):
print('B created')
if __name__ == '__main__':
a = A('a1')
b = B()
a.other = b
b.other = a
returns:
A created
B created
Removing the circular reference makes the lambda callback works ('An A deleted: a1' is printed). Replacing the lambda by a simple function call works too, but the parameter value is fixed when initializing the weak reference, and not when calling the callback:
self._wr = weakref.ref(self, del_A(self.name))
...
a = A('a1')
a.name = 'a2'
b = B()
a.other = b
b.other = a
returns:
A created
An A deleted:a1
B created
Any idea why the lambda callback does not work with circular references?
A:
When you use
self._wr = weakref.ref(self, lambda wr, n = self.name: del_A(n))
the callback will only be called when self is about to be finalized.
The reason why the callback is not getting called is because
a = A('a1')
b = B()
a.other = b # This gives a another attribute; it does not switch `a` away from the original `a`
b.other = a
does not cause a to be finalized. The original a still exists.
The callback would be called if you changed the code to
a = A('a1')
b = B()
a = b
b = a
When you use
self._wr = weakref.ref(self, del_A(self.name))
then your callback is None. del_A(self.name) is not a reference to a function, it is a function call itself. So del_A(self.name) prints An A deleted:a1 immediately (before a1 is really finalized), and returns with the value None, which becomes the default callback for the weakref.
A:
I think I finally found the reason why the callback is not called in the presence of a weak reference:
Weak reference callbacks are not called if the "weakref object dies before the object it
references"
It seems that when circular references are deleted, the weak reference attribute of class A is deleted before the callback has a chance to be called. One solution, is to append the finalizer (i.e., the weak reference and its callback) to a list of finalizers. For example:
def del_A(name):
print('An A deleted:' + name)
class A(object):
def __init__(self, name, finalizers):
print('A created')
self.name = name
finalizers.append(weakref.ref(self, lambda wr, n = self.name: del_A(n)))
class B(object):
def __init__(self):
print('B created')
def do_work(finalizers):
a = A('a1', finalizers)
b = B()
a.other = b
b.other = a
if __name__ == '__main__':
finalizers = []
do_work(finalizers)
will print:
A created
B created
An A deleted:a1
Note that do_work() is necessary, otherwise finalizers gets deleted before the callbacks have a chance to be called. Obviously, finalizers has to be managed properly to avoid building a huge list of weak references, but this is another issue.
A:
Circular references are cleaned up automatically. There are a few exceptions, such as classes that define a __del__ method.
Usually you do not need to define a __del__ method
|
Weak reference callback is not called because of circular references
|
I'm trying to write a finalizer for Python classes that have circular references. I found out that weak reference callbacks are the way to go. Unfortunately, it seems the lambda I use as a callback is never called. For example, running this code:
def del_A(name):
print('An A deleted:' + name)
class A(object):
def __init__(self, name):
print('A created')
self.name = name
self._wr = weakref.ref(self, lambda wr, n = self.name: del_A(n))
class B(object):
def __init__(self):
print('B created')
if __name__ == '__main__':
a = A('a1')
b = B()
a.other = b
b.other = a
returns:
A created
B created
Removing the circular reference makes the lambda callback works ('An A deleted: a1' is printed). Replacing the lambda by a simple function call works too, but the parameter value is fixed when initializing the weak reference, and not when calling the callback:
self._wr = weakref.ref(self, del_A(self.name))
...
a = A('a1')
a.name = 'a2'
b = B()
a.other = b
b.other = a
returns:
A created
An A deleted:a1
B created
Any idea why the lambda callback does not work with circular references?
|
[
"When you use \n self._wr = weakref.ref(self, lambda wr, n = self.name: del_A(n)) \n\nthe callback will only be called when self is about to be finalized. \nThe reason why the callback is not getting called is because\na = A('a1')\nb = B()\na.other = b # This gives a another attribute; it does not switch `a` away from the original `a`\nb.other = a\n\ndoes not cause a to be finalized. The original a still exists.\nThe callback would be called if you changed the code to \na = A('a1')\nb = B()\na = b\nb = a\n\nWhen you use \nself._wr = weakref.ref(self, del_A(self.name))\n\nthen your callback is None. del_A(self.name) is not a reference to a function, it is a function call itself. So del_A(self.name) prints An A deleted:a1 immediately (before a1 is really finalized), and returns with the value None, which becomes the default callback for the weakref.\n",
"I think I finally found the reason why the callback is not called in the presence of a weak reference:\nWeak reference callbacks are not called if the \"weakref object dies before the object it\nreferences\"\nIt seems that when circular references are deleted, the weak reference attribute of class A is deleted before the callback has a chance to be called. One solution, is to append the finalizer (i.e., the weak reference and its callback) to a list of finalizers. For example:\ndef del_A(name):\n print('An A deleted:' + name)\n\nclass A(object):\n def __init__(self, name, finalizers):\n print('A created')\n self.name = name\n finalizers.append(weakref.ref(self, lambda wr, n = self.name: del_A(n)))\n\nclass B(object):\n def __init__(self):\n print('B created')\n\ndef do_work(finalizers):\n a = A('a1', finalizers)\n b = B()\n a.other = b\n b.other = a\n\nif __name__ == '__main__':\n finalizers = []\n do_work(finalizers)\n\nwill print:\nA created\nB created\nAn A deleted:a1\n\nNote that do_work() is necessary, otherwise finalizers gets deleted before the callbacks have a chance to be called. Obviously, finalizers has to be managed properly to avoid building a huge list of weak references, but this is another issue.\n",
"Circular references are cleaned up automatically. There are a few exceptions, such as classes that define a __del__ method. \nUsually you do not need to define a __del__ method\n"
] |
[
3,
3,
0
] |
[] |
[] |
[
"lambda",
"python",
"weak_references"
] |
stackoverflow_0002295993_lambda_python_weak_references.txt
|
Q:
Is the content between anchor tags (a) in html seen as a branch in lxml?
I am trying to get some content in html documents. Some of the documents have a table of contents that very nicely indicates where in the document the content I want to strip out is located. That is either the value or text_content of the tag are easily identifiable and point to what I need. For example I might have two anchor tags in the toc that have the following values
key=href value=#listofplaces text_content=Places we have visited
key=href value=#transport text_content=Ways we have traveled
and then in the body of the document
key=name value=listofplaces text_content=''
then there are lots of html elements, some tables, maybe some div tags, some unknown number of elements followed by the next anchor
key=name value=transport text_content=''
I was planning on using the output from a function to identify the beginning and end of the section I want to copy from the document. That is I was going to read the document and snip out the section between the anchor tags listofplaces and transport. I started thinking that LXML is so powerful that maybe the content I want is a branch of some sort that I just have not been able to figure out its identity.
A:
No, there is not a single branch between siblings. However, you can just iterate over their parent and extract (can be done in various ways, depending on how you already have handles for the anchor tags). Note the handling of text and tail to avoid losing data. Modifying example_doc to see the results may help you better understand this example code.
import lxml.etree
example_doc = """
<root>
<a name="listofplaces"/>
text
<sibling/>
<sibling/>
<a name="transport"/>
</root>
"""
root = lxml.etree.XML(example_doc)
new_root = lxml.etree.Element("root")
it = iter(root)
for e in it:
if e.tag == "a" and e.get("name") == "listofplaces":
new_root.text = e.tail
break
else:
assert False, "TODO: handle tag not found"
for e in it:
if e.tag == "a" and e.get("name") == "transport":
break
new_root.append(e)
else:
assert False, "TODO: handle tag not found"
print lxml.etree.tostring(new_root)
|
Is the content between anchor tags (a) in html seen as a branch in lxml?
|
I am trying to get some content in html documents. Some of the documents have a table of contents that very nicely indicates where in the document the content I want to strip out is located. That is either the value or text_content of the tag are easily identifiable and point to what I need. For example I might have two anchor tags in the toc that have the following values
key=href value=#listofplaces text_content=Places we have visited
key=href value=#transport text_content=Ways we have traveled
and then in the body of the document
key=name value=listofplaces text_content=''
then there are lots of html elements, some tables, maybe some div tags, some unknown number of elements followed by the next anchor
key=name value=transport text_content=''
I was planning on using the output from a function to identify the beginning and end of the section I want to copy from the document. That is I was going to read the document and snip out the section between the anchor tags listofplaces and transport. I started thinking that LXML is so powerful that maybe the content I want is a branch of some sort that I just have not been able to figure out its identity.
|
[
"No, there is not a single branch between siblings. However, you can just iterate over their parent and extract (can be done in various ways, depending on how you already have handles for the anchor tags). Note the handling of text and tail to avoid losing data. Modifying example_doc to see the results may help you better understand this example code.\nimport lxml.etree\n\nexample_doc = \"\"\"\n <root>\n <a name=\"listofplaces\"/>\n text\n <sibling/>\n <sibling/>\n <a name=\"transport\"/>\n </root>\n\"\"\"\nroot = lxml.etree.XML(example_doc)\n\nnew_root = lxml.etree.Element(\"root\")\nit = iter(root)\nfor e in it:\n if e.tag == \"a\" and e.get(\"name\") == \"listofplaces\":\n new_root.text = e.tail\n break\nelse:\n assert False, \"TODO: handle tag not found\"\nfor e in it:\n if e.tag == \"a\" and e.get(\"name\") == \"transport\":\n break\n new_root.append(e)\nelse:\n assert False, \"TODO: handle tag not found\"\n\nprint lxml.etree.tostring(new_root)\n\n"
] |
[
1
] |
[] |
[] |
[
"html",
"lxml",
"python"
] |
stackoverflow_0002397064_html_lxml_python.txt
|
Q:
Python: Connect blender with WinTracker 2
I am trying to develop a project that uses a control model in Blender by using WinTracker machine, but I don't know how to connect it with Blender Game Engine.
How can I connect it with Blender Game Engine?
A:
You must write the plug-in for blender and used the wintracker driver. It is ready for c Lagrange.
but you have "wintracker2"?
I wanted to buy it but the company said "it's not ready to seal".
|
Python: Connect blender with WinTracker 2
|
I am trying to develop a project that uses a control model in Blender by using WinTracker machine, but I don't know how to connect it with Blender Game Engine.
How can I connect it with Blender Game Engine?
|
[
"You must write the plug-in for blender and used the wintracker driver. It is ready for c Lagrange.\nbut you have \"wintracker2\"?\nI wanted to buy it but the company said \"it's not ready to seal\".\n"
] |
[
0
] |
[] |
[] |
[
"blender",
"python"
] |
stackoverflow_0001748482_blender_python.txt
|
Q:
import strategy within django applications
I would like to know what is the best import strategy within django reusable applications.
Say I have an application called usefulapp. Inside my app, I will need to access, say, the models. Should I use an explicit import as:
import usefulapp.models
or simply, since I am inside this very app, I could use:
import models
Which one is recommended?
Are there disadvantages of using the second approach?
A:
The second approach assumes that . is in sys.path before any other directories that may contain a models module. There is no requirement that . be in it at all, so importing either via relative imports or via the app is best.
A:
I personally, try to keep the convention of always importing from the app.
Don't import from the project, because project name can change; your app can be used in some other project (at least you are supposed to make apps like that).
Don't import from models directly because, as Ignacio rightly mentions, it is not necessary that . is in the python path.
But, App names are always on the python path. Django adds them to the python path (via set_environ(settings)), on the top of the list, so you can be rest assured that the right files are always picked up.
|
import strategy within django applications
|
I would like to know what is the best import strategy within django reusable applications.
Say I have an application called usefulapp. Inside my app, I will need to access, say, the models. Should I use an explicit import as:
import usefulapp.models
or simply, since I am inside this very app, I could use:
import models
Which one is recommended?
Are there disadvantages of using the second approach?
|
[
"The second approach assumes that . is in sys.path before any other directories that may contain a models module. There is no requirement that . be in it at all, so importing either via relative imports or via the app is best.\n",
"I personally, try to keep the convention of always importing from the app.\nDon't import from the project, because project name can change; your app can be used in some other project (at least you are supposed to make apps like that).\nDon't import from models directly because, as Ignacio rightly mentions, it is not necessary that . is in the python path.\nBut, App names are always on the python path. Django adds them to the python path (via set_environ(settings)), on the top of the list, so you can be rest assured that the right files are always picked up.\n"
] |
[
3,
3
] |
[] |
[] |
[
"django",
"import",
"python"
] |
stackoverflow_0002397055_django_import_python.txt
|
Q:
Python: web login script, what's the problem?
this is the script >>
import ClientForm
import urllib2
request = urllib2.Request("http://ritaj.birzeit.edu")
response = urllib2.urlopen(request)
forms = ClientForm.ParseResponse(response, backwards_compat=False)
response.close()
form = forms[0]
print form
sooform = str(raw_input("Form Name: "))
username = str(raw_input("Username: "))
password = str(raw_input("Password: "))
form[sooform] = [username, password]
request2 = form.click()
try:
response2 = urllib2.urlopen(request2)
except urllib2.HTTPError, response2:
pass
print response2.geturl()
print response2.info() # headers
print response2.read() # body
response2.close()
when start the script ,, i got this
Traceback (most recent call last):
File "C:/Python26/ritaj2.py", line 9, in <module>
form = forms[0]
IndexError: list index out of range
what is th problem,, i running on windows, python 2.6.4
Update:
I want a script that login this site, and print the response :)
A:
The only <form> tag in the HTML served at that URL (save it to a file and look for yourself!) is:
<form method="GET" action="http://www.google.com/u/ritaj">
which does a customized Google search and has nothing to do with logging in (plus, for some reason, ClientForm has some problem identifying that specific form -- but that form is no use to you anyway, so I didn't explore that issue further).
You can still get at the controls in the page by using
forms = ClientForms.ParseResponseEx(response)
which makes forms[0] an artificial one containing all controls that aren't within a form.
Specifically, this approach identifies controls with the following names, in order (again there's a bit of parsing confusion here, but hopefully not a killer for you...):
>>> f = forms[0]
>>> [c.name for c in f.controls]
['q', 'sitesearch', 'sa', 'domains', 'form:mode', 'form:id', '__confirmed_p', '__refreshing_p', 'return_url', 'time', 'token_id', 'hash', 'username', 'password', 'persistent_p', 'formbutton:ok']
so you should be able to set the username and password controls of the "non-form form" f, and proceed from there.
(A side bit: raw_input already returns a string, lose those redundant str() calls around it).
A:
the actual address seems to be using https instead of http. check the urllib2 doc to see if it handles HTTPS( i believe you need ssl)
|
Python: web login script, what's the problem?
|
this is the script >>
import ClientForm
import urllib2
request = urllib2.Request("http://ritaj.birzeit.edu")
response = urllib2.urlopen(request)
forms = ClientForm.ParseResponse(response, backwards_compat=False)
response.close()
form = forms[0]
print form
sooform = str(raw_input("Form Name: "))
username = str(raw_input("Username: "))
password = str(raw_input("Password: "))
form[sooform] = [username, password]
request2 = form.click()
try:
response2 = urllib2.urlopen(request2)
except urllib2.HTTPError, response2:
pass
print response2.geturl()
print response2.info() # headers
print response2.read() # body
response2.close()
when start the script ,, i got this
Traceback (most recent call last):
File "C:/Python26/ritaj2.py", line 9, in <module>
form = forms[0]
IndexError: list index out of range
what is th problem,, i running on windows, python 2.6.4
Update:
I want a script that login this site, and print the response :)
|
[
"The only <form> tag in the HTML served at that URL (save it to a file and look for yourself!) is:\n<form method=\"GET\" action=\"http://www.google.com/u/ritaj\">\n\nwhich does a customized Google search and has nothing to do with logging in (plus, for some reason, ClientForm has some problem identifying that specific form -- but that form is no use to you anyway, so I didn't explore that issue further).\nYou can still get at the controls in the page by using\nforms = ClientForms.ParseResponseEx(response)\n\nwhich makes forms[0] an artificial one containing all controls that aren't within a form.\nSpecifically, this approach identifies controls with the following names, in order (again there's a bit of parsing confusion here, but hopefully not a killer for you...):\n>>> f = forms[0]\n>>> [c.name for c in f.controls]\n['q', 'sitesearch', 'sa', 'domains', 'form:mode', 'form:id', '__confirmed_p', '__refreshing_p', 'return_url', 'time', 'token_id', 'hash', 'username', 'password', 'persistent_p', 'formbutton:ok']\n\nso you should be able to set the username and password controls of the \"non-form form\" f, and proceed from there.\n(A side bit: raw_input already returns a string, lose those redundant str() calls around it).\n",
"the actual address seems to be using https instead of http. check the urllib2 doc to see if it handles HTTPS( i believe you need ssl)\n"
] |
[
1,
0
] |
[] |
[] |
[
"browser",
"python"
] |
stackoverflow_0002396382_browser_python.txt
|
Q:
Coding style - keep parentheses on the same line or new line?
Suppose you are calling a function, where there's clearly a need to break down the statement into few lines, for readability's sake. However there are at least two way to do it:
Would you do this:
return render(request, template,
{
'var1' : value1,
'var2' : value2,
'var3' : value3
}
)
Or would you rather do that:
return render \
(
request, template,
{
'var1' : value1,
'var2' : value2,
'var3' : value3
}
)
Or, please suggest your own formatting. Please also list reasons why would you use a particular formatting and what's wrong with the other one.
Thanks
A:
I'd probably do:
return render(
request,
template,
{
'var1' : value1,
'var2' : value2,
'var3' : value3
}
)
I would keep the bracket on the same line, so that searches for render( work. And because I find it clearer. But I'd put all the arguments on new lines.
A:
Python's official PEP-8 suggests the first one.
A:
I would do:
vars = {
'var1' : value1,
'var2' : value2,
'var3' : value3,
}
return render(request, template, vars)
A:
The second one looks like it escaped from a C[#+]* program. Backslash line continuation is ugly, prone to trouble with trailing space, and there's no excuse to use it when you've got () or [] to use.
|
Coding style - keep parentheses on the same line or new line?
|
Suppose you are calling a function, where there's clearly a need to break down the statement into few lines, for readability's sake. However there are at least two way to do it:
Would you do this:
return render(request, template,
{
'var1' : value1,
'var2' : value2,
'var3' : value3
}
)
Or would you rather do that:
return render \
(
request, template,
{
'var1' : value1,
'var2' : value2,
'var3' : value3
}
)
Or, please suggest your own formatting. Please also list reasons why would you use a particular formatting and what's wrong with the other one.
Thanks
|
[
"I'd probably do:\nreturn render(\n request, \n template,\n {\n 'var1' : value1,\n 'var2' : value2,\n 'var3' : value3\n }\n)\n\nI would keep the bracket on the same line, so that searches for render( work. And because I find it clearer. But I'd put all the arguments on new lines.\n",
"Python's official PEP-8 suggests the first one.\n",
"I would do:\nvars = {\n 'var1' : value1,\n 'var2' : value2,\n 'var3' : value3,\n}\nreturn render(request, template, vars)\n\n",
"The second one looks like it escaped from a C[#+]* program. Backslash line continuation is ugly, prone to trouble with trailing space, and there's no excuse to use it when you've got () or [] to use.\n"
] |
[
10,
9,
9,
2
] |
[] |
[] |
[
"coding_style",
"formatting",
"python",
"readability"
] |
stackoverflow_0002395664_coding_style_formatting_python_readability.txt
|
Q:
Re-order list in Python to ensure it starts with check values
I'm reading in serial data using Pyserial, to populate a list of 17 values (1byte each) at a sampling rate of 256Hz.
The bytes I ultimately want to use are the 5th to 8th in the list. Providing no bytes are dropped, the first two values of the stream are always the same ('165','90'). I'm getting quite a few dropped values though, and my list values are shifting, so when I read the 5th-8th bytes, they aren't the correct values.
I've partially combatted this by ensuring that before the wanted segement is captured, the first few values are checked against what they should be (i.e. if mylist[0]==165 &....).
This is crude but ok since the chances of these two values appearing adjacent to each other in the list elsewhere is small.
The problem is that this means as soon as the bytes shift, I'm losing a load of values, until it eventually realigns.
My question is: what code can I use to either:
a) Force the list to realign once it has been detected that it no longer starts with 165,90. (elif....).
b) Detect where '165' & '90' are (next to each other) in the list and extract the values I want in relation to their position (next but one, onwards).
Thanks in advance
S_S
Just noticed from the related Qs that I could use
mylist.append(mylist.pop(0))
multiple times until they are in the right place. Is there a better way that anyone can suggest?
A:
In case I understood you well,
suppose you have a list like this:
l = [67, 126, 165, 90, 11, 1, 3, 5, 151, 99, 23]
you'd want to obtain:
useful = [3,5,151,99]
Then, you could do:
# obtain places where 165 is followed by 90
match = [x for x in xrange(len(l)-1) if l[x]==165 and l[x+1]==90]
# obtain range of useful values
useful = l[match[0]+4:match[0]+8]
You may have to tweak the numbers in case I misunderstood your problem.
Hope it helps,
Manuel
A:
If I understand your problem correct, you have data continuously arriving, in 17-byte chunks. Assuming that's right, how about something like this:
while True:
mylist.extend(get_more_data())
# If we're misaligned, skip bytes until we're aligned again
while mylist and mylist[0] != 165 or mylist[1] != 90:
mylist.pop(0)
# If we've skip bytes, we might not have enough data, so get more
if len(mylist) < 17:
continue
# Process one chunk of data and remove it from the list
process_data(mylist[:17])
del mylist[:17]
A:
I would use the 165 and 90 as header values, always checking the incoming byte for a match. This solution automatically re-syncs itself and it is as simple as:
def get_message():
while True: #Some timeout functionality is useful here ;-)
message = []
byte = xxx.get_byte()
if byte == 165:
byte = xxx.get_byte()
if byte == 90:
xxx.get_byte() #drop it
xxx.get_byte() #drop it
message[0] = xxx.get_byte()
message[1] = xxx.get_byte()
message[2] = xxx.get_byte()
message[3] = xxx.get_byte()
#Break out of loop. We have a message!
return message
If your designing both sides, you really should insert some kind of checksum. If your just hacking something, look in the bytes for a checksum. It's probably there already.
|
Re-order list in Python to ensure it starts with check values
|
I'm reading in serial data using Pyserial, to populate a list of 17 values (1byte each) at a sampling rate of 256Hz.
The bytes I ultimately want to use are the 5th to 8th in the list. Providing no bytes are dropped, the first two values of the stream are always the same ('165','90'). I'm getting quite a few dropped values though, and my list values are shifting, so when I read the 5th-8th bytes, they aren't the correct values.
I've partially combatted this by ensuring that before the wanted segement is captured, the first few values are checked against what they should be (i.e. if mylist[0]==165 &....).
This is crude but ok since the chances of these two values appearing adjacent to each other in the list elsewhere is small.
The problem is that this means as soon as the bytes shift, I'm losing a load of values, until it eventually realigns.
My question is: what code can I use to either:
a) Force the list to realign once it has been detected that it no longer starts with 165,90. (elif....).
b) Detect where '165' & '90' are (next to each other) in the list and extract the values I want in relation to their position (next but one, onwards).
Thanks in advance
S_S
Just noticed from the related Qs that I could use
mylist.append(mylist.pop(0))
multiple times until they are in the right place. Is there a better way that anyone can suggest?
|
[
"In case I understood you well,\nsuppose you have a list like this:\nl = [67, 126, 165, 90, 11, 1, 3, 5, 151, 99, 23]\n\nyou'd want to obtain:\n useful = [3,5,151,99]\nThen, you could do:\n# obtain places where 165 is followed by 90\nmatch = [x for x in xrange(len(l)-1) if l[x]==165 and l[x+1]==90]\n# obtain range of useful values\nuseful = l[match[0]+4:match[0]+8]\n\nYou may have to tweak the numbers in case I misunderstood your problem.\nHope it helps,\nManuel\n",
"If I understand your problem correct, you have data continuously arriving, in 17-byte chunks. Assuming that's right, how about something like this:\nwhile True: \n mylist.extend(get_more_data())\n\n # If we're misaligned, skip bytes until we're aligned again\n while mylist and mylist[0] != 165 or mylist[1] != 90:\n mylist.pop(0)\n\n # If we've skip bytes, we might not have enough data, so get more\n if len(mylist) < 17:\n continue\n\n # Process one chunk of data and remove it from the list\n process_data(mylist[:17])\n del mylist[:17]\n\n",
"I would use the 165 and 90 as header values, always checking the incoming byte for a match. This solution automatically re-syncs itself and it is as simple as:\ndef get_message():\n while True: #Some timeout functionality is useful here ;-)\n message = []\n byte = xxx.get_byte()\n if byte == 165:\n byte = xxx.get_byte()\n if byte == 90:\n xxx.get_byte() #drop it\n xxx.get_byte() #drop it\n message[0] = xxx.get_byte()\n message[1] = xxx.get_byte()\n message[2] = xxx.get_byte()\n message[3] = xxx.get_byte()\n #Break out of loop. We have a message! \n return message\n\nIf your designing both sides, you really should insert some kind of checksum. If your just hacking something, look in the bytes for a checksum. It's probably there already.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002387068_list_python.txt
|
Q:
using os.path is quite verbose is there a more concise way to manipulate paths
for example I have a script that needs to put it's parent directory on the python path, currently I'm using the following
sys.path += [os.path.dirname(os.path.dirname(os.path.realpath(__file__)))]
this seems a touch ridiculous, surely there is a simpler way?
A:
I've found Jason Orendorff's path module to be very nice. Unfortunately, it seems that his website is no longer on the internet, but you can still download the module from PyPI.
A:
You could do:
from os.path import dirname,realpath
sys.path.append(dirname(dirname(realpath(__file__))))
But to be honest, I prefer the full explicit version. It's much easier to read as a standalone statement.
A:
you can also do this
>>> from os.path import dirname as dn, realpath as rp
but its still better to explicitly define the name so you won't have variable names collision problems.
A:
Another option is to import path from os. It's not the most consise but I think it's still easy to read. Do you really want us to golf it? :)
from os import path
sys.path += [path.dirname(path.dirname(path.realpath(__file__)))]
A:
If it is a huge problem, you could wrap os.path functionality is a path class. I'm pretty sure there is a Path module floating around on the internet.
|
using os.path is quite verbose is there a more concise way to manipulate paths
|
for example I have a script that needs to put it's parent directory on the python path, currently I'm using the following
sys.path += [os.path.dirname(os.path.dirname(os.path.realpath(__file__)))]
this seems a touch ridiculous, surely there is a simpler way?
|
[
"I've found Jason Orendorff's path module to be very nice. Unfortunately, it seems that his website is no longer on the internet, but you can still download the module from PyPI.\n",
"You could do:\nfrom os.path import dirname,realpath\nsys.path.append(dirname(dirname(realpath(__file__))))\n\nBut to be honest, I prefer the full explicit version. It's much easier to read as a standalone statement.\n",
"you can also do this\n>>> from os.path import dirname as dn, realpath as rp\n\nbut its still better to explicitly define the name so you won't have variable names collision problems.\n",
"Another option is to import path from os. It's not the most consise but I think it's still easy to read. Do you really want us to golf it? :)\nfrom os import path\nsys.path += [path.dirname(path.dirname(path.realpath(__file__)))]\n\n",
"If it is a huge problem, you could wrap os.path functionality is a path class. I'm pretty sure there is a Path module floating around on the internet.\n"
] |
[
2,
1,
1,
0,
0
] |
[] |
[] |
[
"path",
"python"
] |
stackoverflow_0002395653_path_python.txt
|
Q:
Why time.clock() returns such a large value on Windows Server 2008 X64
I ran following script on different machine and got quite different results. The elapsed time.clock() is so large.
Script:
#------------------------------------------------------------------------------------
import time
start_clock = time.clock()
time.sleep(60)
end_clock = time.clock()
print "Sleep Clock = ", str(end_clock - start_clock)
start_time = time.time()
time.sleep(60)
end_time = time.time()
print "Sleep Time = ", str(end_time - start_time)
#-------------------------------------------------------------------------------------
Output:
Instance (Windows Server 2008, X64):
Sleep Clock = 938.306471633
Sleep Time = 60.0119998455
Local Machine (Windows Vista, X86):
Sleep Clock = 59.9997987873
Sleep Time = 59.996999979
Following result really confused me:
Sleep Clock = 938.306471633
P.s:
I have not tested on other X64 OSs. This Windows Server 2008 is a running Amazon Instance.
A:
Per the docs on time.clock
On Windows, this function returns
wall-clock seconds elapsed since the
first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter().
so my (blind, i.e., I've never seen Amazon's code for Windows virtualization!-) guess would be that Amazon's virtualization doesn't go quite deep enough to trick QueryPerformanceCounter (which is a very low-level, low-overhead function). Tricking time.time (in a virtualizing hypervisor) is easier (and a more common need).
Do you know what happens e.g. on Microsoft's Azure, and with other non-Microsoft virtualizers such as Parallels or VMWare? I wouldn't be surprised to see different "depth" to the amount of "trickery" (deep virtualization) performed in each case. (I don't doubt that the explanation for this observation must have to do with virtualization, although the specific guess I make above could be flawed).
It would also be interesting to try (again, on various different virtualizers) a tiny C program doing just QueryPerformanceCounter, just to confirm that Python's runtime has nothing to do with the case (I believe so, by inspection of the runtime's source, but a confirmation could not hurt -- unfortunately I don't have access to the resources needed to try it myself).
|
Why time.clock() returns such a large value on Windows Server 2008 X64
|
I ran following script on different machine and got quite different results. The elapsed time.clock() is so large.
Script:
#------------------------------------------------------------------------------------
import time
start_clock = time.clock()
time.sleep(60)
end_clock = time.clock()
print "Sleep Clock = ", str(end_clock - start_clock)
start_time = time.time()
time.sleep(60)
end_time = time.time()
print "Sleep Time = ", str(end_time - start_time)
#-------------------------------------------------------------------------------------
Output:
Instance (Windows Server 2008, X64):
Sleep Clock = 938.306471633
Sleep Time = 60.0119998455
Local Machine (Windows Vista, X86):
Sleep Clock = 59.9997987873
Sleep Time = 59.996999979
Following result really confused me:
Sleep Clock = 938.306471633
P.s:
I have not tested on other X64 OSs. This Windows Server 2008 is a running Amazon Instance.
|
[
"Per the docs on time.clock\n\nOn Windows, this function returns\n wall-clock seconds elapsed since the\n first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter().\n\nso my (blind, i.e., I've never seen Amazon's code for Windows virtualization!-) guess would be that Amazon's virtualization doesn't go quite deep enough to trick QueryPerformanceCounter (which is a very low-level, low-overhead function). Tricking time.time (in a virtualizing hypervisor) is easier (and a more common need).\nDo you know what happens e.g. on Microsoft's Azure, and with other non-Microsoft virtualizers such as Parallels or VMWare? I wouldn't be surprised to see different \"depth\" to the amount of \"trickery\" (deep virtualization) performed in each case. (I don't doubt that the explanation for this observation must have to do with virtualization, although the specific guess I make above could be flawed).\nIt would also be interesting to try (again, on various different virtualizers) a tiny C program doing just QueryPerformanceCounter, just to confirm that Python's runtime has nothing to do with the case (I believe so, by inspection of the runtime's source, but a confirmation could not hurt -- unfortunately I don't have access to the resources needed to try it myself).\n"
] |
[
2
] |
[] |
[] |
[
"python",
"time"
] |
stackoverflow_0002395677_python_time.txt
|
Q:
Django: using variables as array indices?
I am trying to create a template that will put items in a table.
Controller:
items = Item.all().order('name').fetch(10)
template_values = {'items': items,
'headers': ['Name', 'Price', 'Quantity']}
render('Views/table.html', self, template_values)
Template:
<table>
<tr>
{% for header in headers %}
<th>{{header}}</th>
{% endfor %}
</tr>
{% for item in items %}
<tr><td><a href="detail/{{item.CSIN}}">{{item.name}}</a></td><td>{{item.CSIN}}</td></tr>
{% endfor %}
</table>
Right now, the template is hard coded to look for certain attributes of item. I want to change this so it either looks for the attributes with the names that are in headers, or so that it looks for the first n attributes, where n is the length of headers.
How can I do this?
A:
You could tweak the view to do:
items = Item.all().order('name').fetch(10)
headers = ['Name', 'Price', 'Quantity']
viewitems = [[getattr(x, h) for h in headers] for x in items]
template_values = {'items': viewitems,
'headers': headers}
render('Views/table.html', self, template_values)
so all the template has to do is loop over each "item" (which will just be a list of the values to show corresponding to the headers. Basically, this would move the logic (deciding what to show) from the template (or actually split a bit each in template and view) entirely to the Python code in the view, simplifying the template and making it more general, as you desire.
A:
I'm not sure if there is an existing template tag/filter that will accomplish what you want. You could look into writing a custom template tag or filter which accepts the items list and the current header and returns the value after the look-up. Have a look at http://docs.djangoproject.com/en/dev/howto/custom-template-tags/.
|
Django: using variables as array indices?
|
I am trying to create a template that will put items in a table.
Controller:
items = Item.all().order('name').fetch(10)
template_values = {'items': items,
'headers': ['Name', 'Price', 'Quantity']}
render('Views/table.html', self, template_values)
Template:
<table>
<tr>
{% for header in headers %}
<th>{{header}}</th>
{% endfor %}
</tr>
{% for item in items %}
<tr><td><a href="detail/{{item.CSIN}}">{{item.name}}</a></td><td>{{item.CSIN}}</td></tr>
{% endfor %}
</table>
Right now, the template is hard coded to look for certain attributes of item. I want to change this so it either looks for the attributes with the names that are in headers, or so that it looks for the first n attributes, where n is the length of headers.
How can I do this?
|
[
"You could tweak the view to do:\nitems = Item.all().order('name').fetch(10)\nheaders = ['Name', 'Price', 'Quantity']\nviewitems = [[getattr(x, h) for h in headers] for x in items]\n\ntemplate_values = {'items': viewitems,\n 'headers': headers}\nrender('Views/table.html', self, template_values)\n\nso all the template has to do is loop over each \"item\" (which will just be a list of the values to show corresponding to the headers. Basically, this would move the logic (deciding what to show) from the template (or actually split a bit each in template and view) entirely to the Python code in the view, simplifying the template and making it more general, as you desire.\n",
"I'm not sure if there is an existing template tag/filter that will accomplish what you want. You could look into writing a custom template tag or filter which accepts the items list and the current header and returns the value after the look-up. Have a look at http://docs.djangoproject.com/en/dev/howto/custom-template-tags/.\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"google_app_engine",
"python",
"templating"
] |
stackoverflow_0002397324_django_google_app_engine_python_templating.txt
|
Q:
How to have multiple python programs append rows to the same file?
I've got multiple python processes (typically 1 per core) transforming large volumes of data that they are each reading from dedicated sources, and writing to a single output file that each opened in append mode.
Is this a safe way for these programs to work?
Because of the tight performance requirements and large data volumes I don't think that I can have each process repeatedly open & close the file. Another option is to have each write to a dedicated output file and a single process concatenate them together once they're all done. But I'd prefer to avoid that.
Thanks in advance for any & all answers and suggestions.
A:
Have you considered using the multiprocessing module to coordinate between the running programs in a thread-like manner? See in particular the queue interface; you can place each completed work item on a queue when completed, and have a single process reading off the queue and writing to your output file.
Alternately, you can have each subprocess maintain a separate pipe to a parent process which does a select() call from all of them, and copies data to the output file when appropriate. Of course, this can be done "by hand" (without the multiprocessing module) as well as with it.
Alternately, if the reason you're avoiding threads is to avoid the global interpreter lock, you might consider a non-CPython implementation (such as Jython or IronPython).
A:
Your procedure is "safe" in that no crashes will result, but data coming (with very unlucky timing) from different processes could get mixed up -- e.g., process 1 is appending a long string of as, process 2 a long string of b, you could end up in the file with lots of as then the bs then more as (or other combinations / mixings).
Problem is, .write is not guaranteed to be atomic for sufficiently long string arguments. If you have a tight boundary on the arguments, less than your fs/os's blocksize, you might be lucky. Otherwise, try using the logging module, which does take more precautions (but perhaps those precautions might slow you down... you'll need to benchmark) exactly because it targets "log files" that are often being appended to by multiple programs.
|
How to have multiple python programs append rows to the same file?
|
I've got multiple python processes (typically 1 per core) transforming large volumes of data that they are each reading from dedicated sources, and writing to a single output file that each opened in append mode.
Is this a safe way for these programs to work?
Because of the tight performance requirements and large data volumes I don't think that I can have each process repeatedly open & close the file. Another option is to have each write to a dedicated output file and a single process concatenate them together once they're all done. But I'd prefer to avoid that.
Thanks in advance for any & all answers and suggestions.
|
[
"Have you considered using the multiprocessing module to coordinate between the running programs in a thread-like manner? See in particular the queue interface; you can place each completed work item on a queue when completed, and have a single process reading off the queue and writing to your output file.\nAlternately, you can have each subprocess maintain a separate pipe to a parent process which does a select() call from all of them, and copies data to the output file when appropriate. Of course, this can be done \"by hand\" (without the multiprocessing module) as well as with it.\nAlternately, if the reason you're avoiding threads is to avoid the global interpreter lock, you might consider a non-CPython implementation (such as Jython or IronPython).\n",
"Your procedure is \"safe\" in that no crashes will result, but data coming (with very unlucky timing) from different processes could get mixed up -- e.g., process 1 is appending a long string of as, process 2 a long string of b, you could end up in the file with lots of as then the bs then more as (or other combinations / mixings).\nProblem is, .write is not guaranteed to be atomic for sufficiently long string arguments. If you have a tight boundary on the arguments, less than your fs/os's blocksize, you might be lucky. Otherwise, try using the logging module, which does take more precautions (but perhaps those precautions might slow you down... you'll need to benchmark) exactly because it targets \"log files\" that are often being appended to by multiple programs.\n"
] |
[
4,
4
] |
[] |
[] |
[
"concurrency",
"python"
] |
stackoverflow_0002397576_concurrency_python.txt
|
Q:
Best seed for parallel process
I need to run a MonteCarlo simulations in parallel on different machines. The code is in c++, but the program is set up and launched with a python script that set a lot of things, in particular the random seed. The function setseed thake a 4 bytes unsigned integer
Using a simple
import time
setseed(int(time.time()))
is not very good because I submit the jobs to a queue on a cluster, they remain pending for some minutes then they starts, but the start time is impredicible, it can be that two jobs start at the same time (seconds), so I switch to:
setseet(int(time.time()*100))
but I'm not happy. What is the best solution? Maybe I can combine information from: time, machine id, process id. Or maybe the best solution is to read from /dev/random (linux machines)?
How to read 4 bytes from /dev/random?
f = open("/dev/random","rb")
f.read(4)
give me a string, I want an integer!
A:
Reading from /dev/random is a good idea. Just convert the 4 byte string into an Integer:
f = open("/dev/random","rb")
rnd_str = f.read(4)
Either using struct:
import struct
rand_int = struct.unpack('I', rnd_string)[0]
Update Uppercase I is needed.
Or multiply and add:
rand_int = 0
for c in rnd_str:
rand_int <<= 8
rand_int += ord(c)
A:
You could simply copy over the four bytes into an integer, that should be the least of your worries.
But parallel pseudo-random number generation is a rather complex topic and very often not done well. Usually you generate seeds on one machine and distribute them to the others.
Take a look at SPRNG, which handles exactly your problem.
A:
If this is Linux or a similar OS, you want /dev/urandom -- it always produces data immediately.
/dev/random may stall waiting for the system to gather randomness. It does produce cryptographic-grade random numbers, but that is overkill for your problem.
A:
You can use a random number as the seed, which has the advantage of being operating-system agnostic (no /dev/random needed), with no conversion from string to int:
Why not simply use
random.randrange(-2**31, 2**31)
as the seed of each process? Slightly different starting times give wildly different seeds, this way…
You could also alternatively use the random.jumpahead method, if you know roughly how many random numbers each process is going to use (the documentation of random.WichmannHill.jumpahead is useful).
|
Best seed for parallel process
|
I need to run a MonteCarlo simulations in parallel on different machines. The code is in c++, but the program is set up and launched with a python script that set a lot of things, in particular the random seed. The function setseed thake a 4 bytes unsigned integer
Using a simple
import time
setseed(int(time.time()))
is not very good because I submit the jobs to a queue on a cluster, they remain pending for some minutes then they starts, but the start time is impredicible, it can be that two jobs start at the same time (seconds), so I switch to:
setseet(int(time.time()*100))
but I'm not happy. What is the best solution? Maybe I can combine information from: time, machine id, process id. Or maybe the best solution is to read from /dev/random (linux machines)?
How to read 4 bytes from /dev/random?
f = open("/dev/random","rb")
f.read(4)
give me a string, I want an integer!
|
[
"Reading from /dev/random is a good idea. Just convert the 4 byte string into an Integer:\nf = open(\"/dev/random\",\"rb\")\nrnd_str = f.read(4)\n\nEither using struct:\nimport struct\nrand_int = struct.unpack('I', rnd_string)[0]\n\nUpdate Uppercase I is needed.\nOr multiply and add:\nrand_int = 0\nfor c in rnd_str:\n rand_int <<= 8\n rand_int += ord(c)\n\n",
"You could simply copy over the four bytes into an integer, that should be the least of your worries.\nBut parallel pseudo-random number generation is a rather complex topic and very often not done well. Usually you generate seeds on one machine and distribute them to the others.\nTake a look at SPRNG, which handles exactly your problem.\n",
"If this is Linux or a similar OS, you want /dev/urandom -- it always produces data immediately.\n/dev/random may stall waiting for the system to gather randomness. It does produce cryptographic-grade random numbers, but that is overkill for your problem.\n",
"You can use a random number as the seed, which has the advantage of being operating-system agnostic (no /dev/random needed), with no conversion from string to int:\nWhy not simply use\nrandom.randrange(-2**31, 2**31)\n\nas the seed of each process? Slightly different starting times give wildly different seeds, this way…\nYou could also alternatively use the random.jumpahead method, if you know roughly how many random numbers each process is going to use (the documentation of random.WichmannHill.jumpahead is useful).\n"
] |
[
5,
2,
1,
0
] |
[] |
[] |
[
"montecarlo",
"parallel_processing",
"python",
"random",
"seed"
] |
stackoverflow_0002396209_montecarlo_parallel_processing_python_random_seed.txt
|
Q:
What's the easiest way to convert a list of hex byte strings to a list of hex integers?
I have a list of hex bytes strings like this
['BB', 'A7', 'F6', '9E']
(as read from a text file)
How do I convert that list to this format?
[0xBB, 0xA7, 0xF6, 0x9E]
A:
[int(x, 16) for x in L]
A:
[0xBB, 0xA7, 0xF6, 0x9E] is the same as [187, 167, 158]. So there's no special 'hex integer' form or the like.
But you can convert your hex strings to ints:
>>> [int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]
[187, 167, 246, 158]
See also Convert hex string to int in Python
A:
Depending on the format in the text file, it may be easier to convert directly
>>> b=bytearray('BBA7F69E'.decode('hex'))
or
>>> b=bytearray('BB A7 F6 9E'.replace(' ','').decode('hex'))
>>> b
bytearray(b'\xbb\xa7\xf6\x9e')
>>> b[0]
187
>>> hex(b[0])
'0xbb'
>>>
a bytearray is easily converted to a list
>>> list(b) == [0xBB, 0xA7, 0xF6, 0x9E]
True
>>> list(b)
[187, 167, 246, 158]
If you want to change the way the list is displayed you'll need to make your own list class
>>> class MyList(list):
... def __repr__(self):
... return '['+', '.join("0x%X"%x if type(x) is int else repr(x) for x in self)+']'
...
>>> MyList(b)
[0xBB, 0xA7, 0xF6, 0x9E]
>>> str(MyList(b))
'[0xBB, 0xA7, 0xF6, 0x9E]'
|
What's the easiest way to convert a list of hex byte strings to a list of hex integers?
|
I have a list of hex bytes strings like this
['BB', 'A7', 'F6', '9E']
(as read from a text file)
How do I convert that list to this format?
[0xBB, 0xA7, 0xF6, 0x9E]
|
[
"[int(x, 16) for x in L]\n\n",
"[0xBB, 0xA7, 0xF6, 0x9E] is the same as [187, 167, 158]. So there's no special 'hex integer' form or the like.\nBut you can convert your hex strings to ints:\n>>> [int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]\n[187, 167, 246, 158]\n\nSee also Convert hex string to int in Python\n",
"Depending on the format in the text file, it may be easier to convert directly\n>>> b=bytearray('BBA7F69E'.decode('hex'))\n\nor\n>>> b=bytearray('BB A7 F6 9E'.replace(' ','').decode('hex'))\n>>> b\nbytearray(b'\\xbb\\xa7\\xf6\\x9e')\n>>> b[0]\n187\n>>> hex(b[0])\n'0xbb'\n>>> \n\na bytearray is easily converted to a list\n>>> list(b) == [0xBB, 0xA7, 0xF6, 0x9E]\nTrue\n\n>>> list(b)\n[187, 167, 246, 158]\n\nIf you want to change the way the list is displayed you'll need to make your own list class\n>>> class MyList(list):\n... def __repr__(self):\n... return '['+', '.join(\"0x%X\"%x if type(x) is int else repr(x) for x in self)+']'\n... \n>>> MyList(b)\n[0xBB, 0xA7, 0xF6, 0x9E]\n>>> str(MyList(b))\n'[0xBB, 0xA7, 0xF6, 0x9E]'\n\n"
] |
[
9,
4,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002397687_python.txt
|
Q:
Test if value is Decimal
In some Python (v3) code I am creating lists of Decimals from user input, like this:
input = [] # later populated with strings by user with values like '1.45984000E+001'
decimals = [Decimal(c) for c in input]
However, sometimes the input list contains strings that cannot be parsed. How can I test if c can be represented as a decimal before calling the constructor?
A:
Catch exception
decimals = []
for s in input:
try: decimals.append(Decimal(s))
except InvalidOperation:
pass
Use helper function
from itertools import imap
def parse_decimal(s):
try: return Decimal(s)
except InvalidOperation:
return None
decimals = [d for d in imap(parse_decimal, input) if d is not None]
A:
Don't. Catch the exception thrown by the constructor. If that means turning the list comprehension into a for loop then so be it.
|
Test if value is Decimal
|
In some Python (v3) code I am creating lists of Decimals from user input, like this:
input = [] # later populated with strings by user with values like '1.45984000E+001'
decimals = [Decimal(c) for c in input]
However, sometimes the input list contains strings that cannot be parsed. How can I test if c can be represented as a decimal before calling the constructor?
|
[
"Catch exception\ndecimals = []\nfor s in input:\n try: decimals.append(Decimal(s))\n except InvalidOperation:\n pass\n\nUse helper function\nfrom itertools import imap\n\ndef parse_decimal(s):\n try: return Decimal(s)\n except InvalidOperation:\n return None\n\ndecimals = [d for d in imap(parse_decimal, input) if d is not None]\n\n",
"Don't. Catch the exception thrown by the constructor. If that means turning the list comprehension into a for loop then so be it.\n"
] |
[
3,
0
] |
[] |
[] |
[
"decimal",
"python"
] |
stackoverflow_0002398141_decimal_python.txt
|
Q:
How to check if datetime is older than 20 seconds
This is my first time here so I hope I post this question at the right place. :)
I need to build flood control for my script but I'm not good at all this datetime to time conversions with UTC and stuff. I hope you can help me out.
I'm using the Google App Engine with Python. I've got a datetimeproperty at the DataStore database which should be checked if it's older than 20 seconds, then proceed.
Could anybody help me out?
So in semi-psuedo:
q = db.GqlQuery("SELECT * FROM Kudo WHERE fromuser = :1", user)
lastplus = q.get()
if lastplus.date is older than 20 seconds:
print"Go!"
A:
You can use the datetime.timedelta datatype, like this:
import datetime
lastplus = q.get()
if lastplus.date < datetime.datetime.now()-datetime.timedelta(seconds=20):
print "Go"
Read more about it here: http://docs.python.org/library/datetime.html
Cheers,
Philip
A:
Try this:
from datetime import timedelta, datetime
if lastplus.date < datetime.utcnow() + timedelta(seconds = -20):
print "fee fie fo foo!"
|
How to check if datetime is older than 20 seconds
|
This is my first time here so I hope I post this question at the right place. :)
I need to build flood control for my script but I'm not good at all this datetime to time conversions with UTC and stuff. I hope you can help me out.
I'm using the Google App Engine with Python. I've got a datetimeproperty at the DataStore database which should be checked if it's older than 20 seconds, then proceed.
Could anybody help me out?
So in semi-psuedo:
q = db.GqlQuery("SELECT * FROM Kudo WHERE fromuser = :1", user)
lastplus = q.get()
if lastplus.date is older than 20 seconds:
print"Go!"
|
[
"You can use the datetime.timedelta datatype, like this:\nimport datetime\nlastplus = q.get()\nif lastplus.date < datetime.datetime.now()-datetime.timedelta(seconds=20):\n print \"Go\"\n\nRead more about it here: http://docs.python.org/library/datetime.html\nCheers,\nPhilip\n",
"Try this:\nfrom datetime import timedelta, datetime\nif lastplus.date < datetime.utcnow() + timedelta(seconds = -20):\n print \"fee fie fo foo!\"\n\n"
] |
[
57,
4
] |
[] |
[] |
[
"datetime",
"google_app_engine",
"python",
"time"
] |
stackoverflow_0002398205_datetime_google_app_engine_python_time.txt
|
Q:
Python - BaseHTTPServer.HTTPServer Concurrency & Threading
Is there a way to make BaseHTTPServer.HTTPServer be multi-threaded like SocketServer.ThreadingTCPServer?
A:
You can simply use the threading mixin using both of those classes to make it multithread :)
It won't help you much in performance though, but it's atleast multithreaded.
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer
class MultiThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass
|
Python - BaseHTTPServer.HTTPServer Concurrency & Threading
|
Is there a way to make BaseHTTPServer.HTTPServer be multi-threaded like SocketServer.ThreadingTCPServer?
|
[
"You can simply use the threading mixin using both of those classes to make it multithread :)\nIt won't help you much in performance though, but it's atleast multithreaded.\nfrom SocketServer import ThreadingMixIn\nfrom BaseHTTPServer import HTTPServer\n\nclass MultiThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n pass\n\n"
] |
[
19
] |
[] |
[] |
[
"basehttpserver",
"httpserver",
"multithreading",
"python",
"socketserver"
] |
stackoverflow_0002398144_basehttpserver_httpserver_multithreading_python_socketserver.txt
|
Q:
pyqt signal problem
I'm working on a plugin for Avogadro (chemistry software) that uses pyqt.
I've some problem with connecting a method to the clicked signal of a button.
I've my class:
class Controller(object):
def __init__(self):
self.ui = MyDialog() # self.ui.run is a QPushButton
self.ui.run.clicked.connect(self.on_run_click)
def on_run_click(self):
1/0
class MyDialog(QDialog,Ui_Dialog): # ui designer compiled
def __init__(self):
QDialog.__init__(self)
self.setupUi(self)
Why when I click the button the on_run_click isn't called?
A:
Unless they've considerably changed something recently, this doesn't seem like the way to connect signals in PyQt. I'm more used to:
self.connect(self.ui.run, QtCore.SIGNAL("clicked()"),
self, QtCore.SLOT("on_run_click()"))
A:
The problem is that Avogadro python wrappers don't support the new signal syntax as described in Tim's blog post:
http://timvdm.blogspot.com/2008/12/avogadro-gets-new-python-wrappers.html
|
pyqt signal problem
|
I'm working on a plugin for Avogadro (chemistry software) that uses pyqt.
I've some problem with connecting a method to the clicked signal of a button.
I've my class:
class Controller(object):
def __init__(self):
self.ui = MyDialog() # self.ui.run is a QPushButton
self.ui.run.clicked.connect(self.on_run_click)
def on_run_click(self):
1/0
class MyDialog(QDialog,Ui_Dialog): # ui designer compiled
def __init__(self):
QDialog.__init__(self)
self.setupUi(self)
Why when I click the button the on_run_click isn't called?
|
[
"Unless they've considerably changed something recently, this doesn't seem like the way to connect signals in PyQt. I'm more used to:\nself.connect(self.ui.run, QtCore.SIGNAL(\"clicked()\"),\n self, QtCore.SLOT(\"on_run_click()\"))\n\n",
"The problem is that Avogadro python wrappers don't support the new signal syntax as described in Tim's blog post:\nhttp://timvdm.blogspot.com/2008/12/avogadro-gets-new-python-wrappers.html\n"
] |
[
1,
1
] |
[] |
[] |
[
"pyqt4",
"python"
] |
stackoverflow_0002392793_pyqt4_python.txt
|
Q:
Rebuilding website from Django 0.96 to Django 1.2
I've got a website done in Django 0.96 (done in 2007), and now we are thinking about rebuilding it (not just migrating) for Django 1.2 .
Can anyone point me to the new (and worth the while) widgets, plugins and other stuff for Django 1.2 (released in april 2010).
I've heard of "South" and of a widget for debugging (can't remember the name), but I'm a little lost here.
A:
The Django API is amazingly stable so you may not have to rewrite it at all (unless you really want to).
I have a site I did in 2007 using 0.97-pre -- at least I think that's what they called it, it was trunk 6688. Anyway, I have ported the site twice, once to 1.0 and then to 1.1.1. The only "major" thing we had to deal with was Admin moving into its own file, but that was mostly cut-and-paste in the editor plus a few tweaks. You'll run into small stuff like maxlength going to max_length, etc., but that's easy stuff to deal with.
Check the lists of Backward Incompatible Changes, and here, and here to see if anything jumps out at you. Read through the ORM docs as if you've never seen them before -- a lot has changed. You may want to look at some of your model relationships and queries and see if the revised ORM makes some of them easier/more efficient to do.
I recommend using Grappelli along with Filebrowser (in fact I think the recent releases of filebrowser require grappelli). Take a look at Pinax for a whole bushel basket of apps brought together under one roof. There's a lot out there and you sort of have to poke around a little. Depending on what you're doing, GeoDjango may be of interest to you. Etc., etc. I'm sure you'll have fun with all of the new toys.
A:
You probably heard about the django-debug-toolbar
A:
Of course, there's the release notes, but the rest is just stuff you... find.
South is for schema migration, not debugging.
|
Rebuilding website from Django 0.96 to Django 1.2
|
I've got a website done in Django 0.96 (done in 2007), and now we are thinking about rebuilding it (not just migrating) for Django 1.2 .
Can anyone point me to the new (and worth the while) widgets, plugins and other stuff for Django 1.2 (released in april 2010).
I've heard of "South" and of a widget for debugging (can't remember the name), but I'm a little lost here.
|
[
"The Django API is amazingly stable so you may not have to rewrite it at all (unless you really want to).\nI have a site I did in 2007 using 0.97-pre -- at least I think that's what they called it, it was trunk 6688. Anyway, I have ported the site twice, once to 1.0 and then to 1.1.1. The only \"major\" thing we had to deal with was Admin moving into its own file, but that was mostly cut-and-paste in the editor plus a few tweaks. You'll run into small stuff like maxlength going to max_length, etc., but that's easy stuff to deal with.\nCheck the lists of Backward Incompatible Changes, and here, and here to see if anything jumps out at you. Read through the ORM docs as if you've never seen them before -- a lot has changed. You may want to look at some of your model relationships and queries and see if the revised ORM makes some of them easier/more efficient to do.\nI recommend using Grappelli along with Filebrowser (in fact I think the recent releases of filebrowser require grappelli). Take a look at Pinax for a whole bushel basket of apps brought together under one roof. There's a lot out there and you sort of have to poke around a little. Depending on what you're doing, GeoDjango may be of interest to you. Etc., etc. I'm sure you'll have fun with all of the new toys.\n",
"You probably heard about the django-debug-toolbar\n",
"Of course, there's the release notes, but the rest is just stuff you... find.\nSouth is for schema migration, not debugging.\n"
] |
[
5,
2,
0
] |
[] |
[] |
[
"django",
"python",
"web"
] |
stackoverflow_0002398299_django_python_web.txt
|
Q:
excluding fields from json serialization in python using jsonpickle
I am using jsonpickle to serialize an object to json. The object has certain fields that point to other objects. I'd like to selectively not include those in the serialization, so that the resulting json file is essentially pure human-readable text without any funny representations of objects. Is there a way to make jsonpickle ignore certain object fields when serialization? Or more generally, include only fields that are "primitive" or easily serializable fields, like dictionaries, ints, lists of dicts, etc.
thanks.
A:
I think what you might be looking for is the unpicklable argument (see this doc for details). In short, if this argument is set to False, jsonpickle will not output custom python classes to JSON. It should only output JSON native types e.g strings, ints, bools and lists.
|
excluding fields from json serialization in python using jsonpickle
|
I am using jsonpickle to serialize an object to json. The object has certain fields that point to other objects. I'd like to selectively not include those in the serialization, so that the resulting json file is essentially pure human-readable text without any funny representations of objects. Is there a way to make jsonpickle ignore certain object fields when serialization? Or more generally, include only fields that are "primitive" or easily serializable fields, like dictionaries, ints, lists of dicts, etc.
thanks.
|
[
"I think what you might be looking for is the unpicklable argument (see this doc for details). In short, if this argument is set to False, jsonpickle will not output custom python classes to JSON. It should only output JSON native types e.g strings, ints, bools and lists.\n"
] |
[
2
] |
[] |
[] |
[
"json",
"jsonpickle",
"python",
"serialization"
] |
stackoverflow_0002397757_json_jsonpickle_python_serialization.txt
|
Q:
How to encode HTML non-ASCII data to UTF-8 in Python
I tried to do that, and I found this errors:
>>> import re
>>> x = 'Ingl\xeas'
>>> x
'Ingl\xeas'
>>> print x
Ingl�s
>>> x.decode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 4-5: unexpected end of data
>>> x.decode('utf8', 'ignore')
u'Ingl'
>>> x.decode('utf8', 'replace')
u'Ingl\ufffd'
>>> print x.decode('utf8', 'replace')
Ingl�
>>> print x.decode('utf8', 'xmlcharrefreplace')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
TypeError: don't know how to handle UnicodeDecodeError in error callback
When I use the print statement, I want that:
>>> print x
u'Inglês'
Any help is welcome.
A:
You need to know how the input data is encoded before you decode it. In some of you're attempts, you're trying to decode it from UTF-8, but Python throws an exception because the input isn't valid UTF-8. It looks like it might be latin-1. This works for me:
>>> x = 'Ingl\xeas'
>>> print x.decode('latin1')
Inglês
You mention "non-ASCII HTML". If you're writing a web server script and you're getting data from an HTTP request, you should check the Content-Type header. In an ideal world, it will tell you which encoding the client is using for the data. Keep in mind that the client may be working incorrectly.
Hope that helps!
A:
Ingl\xeas
is not UTF-8 but (probably) Windows-1252- or latin1-encoded. So you first need to decode it. Only then you can encode it to UTF-8.
Therefore:
>>> x = 'Ingl\xeas'
>>> print x.decode("cp1252")
Inglês
Similarly,
>>> x.decode("cp1252").encode("UTF-8")
'Ingl\xc3\xaas'
which is the correct UTF-8 representation.
By the way, in Python 3, you can (at least in the interactive console under Windows) simply type
>>> x = 'Ingl\xeas'
>>> print (x)
Inglês
since Python 3 strings are always Unicode strings (not counting bytes objects).
A:
Some observations:
(1) latin1 will decode ANY 8-bit byte without throwing an exception. Use latin1 only when you have exhausted all other possibilities. Use chardet to help deciding what a particular file or webpage or XML stream is encoded in.
(2) Possible alternatives based on very limited evidence (ONE character):
>>> import unicodedata as ucd
>>> for codepage in range(1250, 1259):
... try:
... uc = "\xea".decode(str(codepage))
... except UnicodeDecodeError:
... pass
... if uc == u'\xea': print codepage, ucd.name(uc)
...
1252 LATIN SMALL LETTER E WITH CIRCUMFLEX
1254 LATIN SMALL LETTER E WITH CIRCUMFLEX
1256 LATIN SMALL LETTER E WITH CIRCUMFLEX
1258 LATIN SMALL LETTER E WITH CIRCUMFLEX
>>>
(3) The range U+0080 to U+009F (inclusive) is assigned to "C1 control characters" which nobody outside unicode.org knows what use they could be. No matter what encoding you are using (even UTF-8), after no-exception decoding to unicode, you are not out of the woods yet. Check for characters in that range. If you find any, your data is corrupt, or your choice of encoding is not correct.
def check_for_c1_control_characters(unicode_obj):
return any('\u0080' <= c <= '\u009F' for c in unicode_obj)
or use a regex, as in this example of how to fix one of the many ways the data can be corrupted.
|
How to encode HTML non-ASCII data to UTF-8 in Python
|
I tried to do that, and I found this errors:
>>> import re
>>> x = 'Ingl\xeas'
>>> x
'Ingl\xeas'
>>> print x
Ingl�s
>>> x.decode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 4-5: unexpected end of data
>>> x.decode('utf8', 'ignore')
u'Ingl'
>>> x.decode('utf8', 'replace')
u'Ingl\ufffd'
>>> print x.decode('utf8', 'replace')
Ingl�
>>> print x.decode('utf8', 'xmlcharrefreplace')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
TypeError: don't know how to handle UnicodeDecodeError in error callback
When I use the print statement, I want that:
>>> print x
u'Inglês'
Any help is welcome.
|
[
"You need to know how the input data is encoded before you decode it. In some of you're attempts, you're trying to decode it from UTF-8, but Python throws an exception because the input isn't valid UTF-8. It looks like it might be latin-1. This works for me:\n>>> x = 'Ingl\\xeas'\n>>> print x.decode('latin1')\nInglês\n\nYou mention \"non-ASCII HTML\". If you're writing a web server script and you're getting data from an HTTP request, you should check the Content-Type header. In an ideal world, it will tell you which encoding the client is using for the data. Keep in mind that the client may be working incorrectly.\nHope that helps!\n",
"Ingl\\xeas\n\nis not UTF-8 but (probably) Windows-1252- or latin1-encoded. So you first need to decode it. Only then you can encode it to UTF-8.\nTherefore:\n>>> x = 'Ingl\\xeas'\n>>> print x.decode(\"cp1252\")\nInglês\n\nSimilarly,\n >>> x.decode(\"cp1252\").encode(\"UTF-8\")\n 'Ingl\\xc3\\xaas'\n\nwhich is the correct UTF-8 representation.\nBy the way, in Python 3, you can (at least in the interactive console under Windows) simply type \n>>> x = 'Ingl\\xeas'\n>>> print (x)\nInglês\n\nsince Python 3 strings are always Unicode strings (not counting bytes objects).\n",
"Some observations:\n(1) latin1 will decode ANY 8-bit byte without throwing an exception. Use latin1 only when you have exhausted all other possibilities. Use chardet to help deciding what a particular file or webpage or XML stream is encoded in.\n(2) Possible alternatives based on very limited evidence (ONE character):\n>>> import unicodedata as ucd\n>>> for codepage in range(1250, 1259):\n... try:\n... uc = \"\\xea\".decode(str(codepage))\n... except UnicodeDecodeError:\n... pass\n... if uc == u'\\xea': print codepage, ucd.name(uc)\n...\n1252 LATIN SMALL LETTER E WITH CIRCUMFLEX\n1254 LATIN SMALL LETTER E WITH CIRCUMFLEX\n1256 LATIN SMALL LETTER E WITH CIRCUMFLEX\n1258 LATIN SMALL LETTER E WITH CIRCUMFLEX\n>>>\n\n(3) The range U+0080 to U+009F (inclusive) is assigned to \"C1 control characters\" which nobody outside unicode.org knows what use they could be. No matter what encoding you are using (even UTF-8), after no-exception decoding to unicode, you are not out of the woods yet. Check for characters in that range. If you find any, your data is corrupt, or your choice of encoding is not correct.\ndef check_for_c1_control_characters(unicode_obj):\n return any('\\u0080' <= c <= '\\u009F' for c in unicode_obj)\n\nor use a regex, as in this example of how to fix one of the many ways the data can be corrupted.\n"
] |
[
7,
0,
0
] |
[] |
[] |
[
"python",
"unicode",
"utf_8"
] |
stackoverflow_0002396925_python_unicode_utf_8.txt
|
Q:
Python: Can subclasses overload inherited methods?
I'm making a shopping cart app in Google App Engine. I have many classes that derive from a base handler:
class BaseHandler(webapp.RequestHandler):
def get(self, CSIN=None):
self.body(CSIN)
Does this mean that the body() method of every descendant class needs to have the same argument? This is cumbersome. Only one descendant actually uses that argument. And what about when I add new args? Do I need to go through and change every class?
class Detail(BaseHandler):
def body(self, CSIN):
class MainPage(BaseHandler):
def body(self, CSIN=None): #@UnusedVariable
class Cart(BaseHandler):
def body(self, CSIN): #@UnusedVariable
A:
Overridden methods don't have to have the same parameters as each other in principle, but they do have to have the same formal parameters they're called with. So since any handler can have body called on it by get, yes they have to be the same. For that matter, kind of the point of overriding is that the caller doesn't know the exact class of the object, and hence if they don't all have the same parameters, normally the caller wouldn't know what to pass. So overrides with different parameters would be an unusual bit of trickery, I think.
If you change the args it's called with then yes, you have to change the functions to match. This has nothing to do with inheritance, it's how Python functions work.
If you want a bit more flexibility, you could use keyword arguments, which are a fancy way of passing a dictionary as an argument:
class Detail(BaseHandler):
def body(self, **kwargs):
print kwargs['CSIN']
class MainPage(BaseHandler):
def body(self, **kwargs): # can ignore kwargs
class Cart(BaseHandler):
def body(self, **kwargs): # can ignore kwargs
class BaseHandler(webapp.RequestHandler):
def get(self, CSIN=None):
self.body(CSIN = CSIN, some_new_arg = 3)
class SomeNewHandler(BaseHandler):
def body(self, **kwargs):
print kwargs['some_new_arg']
I do slightly question the wisdom of this, though: if you're going to be adding new parameters a lot, and most implementations ignore most parameters, then maybe body isn't really a function of those arguments. Maybe actually the arguments are part of the state of the handler object, that you just happen to be passing as parameters. Obviously the difference is somewhat subjective - for functions only called once per object there's not a whole lot of practical difference between passing a dictionary, and using self as the dictionary.
A:
Python matches methods for overloading based on name only. Which means that
class Base:
def method(self, param2):
print "cheeses"
class NotBase(Base):
def method(self):
print "dill"
obj = NotBase();
obj.method()
will output dill( while obj.method("stuff") will fail ).
However, in your case this isn't the desirable behavior. If you overload the body method with fewer parameters than required by the invocation in the base get method, invoking the get method on such classes will result in an error.
|
Python: Can subclasses overload inherited methods?
|
I'm making a shopping cart app in Google App Engine. I have many classes that derive from a base handler:
class BaseHandler(webapp.RequestHandler):
def get(self, CSIN=None):
self.body(CSIN)
Does this mean that the body() method of every descendant class needs to have the same argument? This is cumbersome. Only one descendant actually uses that argument. And what about when I add new args? Do I need to go through and change every class?
class Detail(BaseHandler):
def body(self, CSIN):
class MainPage(BaseHandler):
def body(self, CSIN=None): #@UnusedVariable
class Cart(BaseHandler):
def body(self, CSIN): #@UnusedVariable
|
[
"Overridden methods don't have to have the same parameters as each other in principle, but they do have to have the same formal parameters they're called with. So since any handler can have body called on it by get, yes they have to be the same. For that matter, kind of the point of overriding is that the caller doesn't know the exact class of the object, and hence if they don't all have the same parameters, normally the caller wouldn't know what to pass. So overrides with different parameters would be an unusual bit of trickery, I think.\nIf you change the args it's called with then yes, you have to change the functions to match. This has nothing to do with inheritance, it's how Python functions work.\nIf you want a bit more flexibility, you could use keyword arguments, which are a fancy way of passing a dictionary as an argument:\nclass Detail(BaseHandler):\n def body(self, **kwargs):\n print kwargs['CSIN']\n\nclass MainPage(BaseHandler):\n def body(self, **kwargs): # can ignore kwargs\n\nclass Cart(BaseHandler):\n def body(self, **kwargs): # can ignore kwargs\n\nclass BaseHandler(webapp.RequestHandler):\n def get(self, CSIN=None):\n self.body(CSIN = CSIN, some_new_arg = 3)\n\nclass SomeNewHandler(BaseHandler):\n def body(self, **kwargs):\n print kwargs['some_new_arg']\n\nI do slightly question the wisdom of this, though: if you're going to be adding new parameters a lot, and most implementations ignore most parameters, then maybe body isn't really a function of those arguments. Maybe actually the arguments are part of the state of the handler object, that you just happen to be passing as parameters. Obviously the difference is somewhat subjective - for functions only called once per object there's not a whole lot of practical difference between passing a dictionary, and using self as the dictionary.\n",
"Python matches methods for overloading based on name only. Which means that\nclass Base:\n def method(self, param2):\n print \"cheeses\"\n\nclass NotBase(Base):\n def method(self):\n print \"dill\"\n\nobj = NotBase();\nobj.method() \n\nwill output dill( while obj.method(\"stuff\") will fail ).\nHowever, in your case this isn't the desirable behavior. If you overload the body method with fewer parameters than required by the invocation in the base get method, invoking the get method on such classes will result in an error.\n"
] |
[
7,
5
] |
[] |
[] |
[
"google_app_engine",
"oop",
"overloading",
"python",
"refactoring"
] |
stackoverflow_0002398666_google_app_engine_oop_overloading_python_refactoring.txt
|
Q:
Saving Python Complex Data Types to Amazon S3
Can Python class data be saved to S3 without marshalling? I am trying to cut down of I/O operations until necessary.
A:
Amazon S3 stores plain data files. Even if there's a library that makes it look like objects are being saved, it's going to do marshalling in the background. Might as well just pickle your objects by yourself.
|
Saving Python Complex Data Types to Amazon S3
|
Can Python class data be saved to S3 without marshalling? I am trying to cut down of I/O operations until necessary.
|
[
"Amazon S3 stores plain data files. Even if there's a library that makes it look like objects are being saved, it's going to do marshalling in the background. Might as well just pickle your objects by yourself.\n"
] |
[
1
] |
[] |
[] |
[
"amazon",
"amazon_s3",
"boto",
"python"
] |
stackoverflow_0002398735_amazon_amazon_s3_boto_python.txt
|
Q:
Python 3.1.1 Class Question
I'm a new Python programmer who is having a little trouble using 'self' in classes. For example:
class data:
def __init__(self):
self.table = []
def add(self, file):
self.table.append(file)
data.add('yes')
In this function I want to have table be a variable stored in the class data and use add to modify it. However, when I run this script it gives me the error:
Traceback (most recent call last):
File "/Projects/Python/sfdfs.py", line 7, in <module>
data.add('yes')
TypeError: add() takes exactly 2 positional arguments (1 given)
I assume that I am trying to call the function the wrong way in this instance, as this syntax is very similar to an example in the python documentation: http://docs.python.org/3.1/tutorial/classes.html
A:
You first need to make an instance of the class:
mydata = data()
then you can call the method -- on the instance, of course, not on the class:
mydata.add('yes')
A:
You need to instantiate the class before you can call methods on it:
mydata = Data()
mydata.add('yes')
A:
you are calling the add method on the class object not an instance of the class.
It looks like what you want to do is:
classInst = data() #make an instance
classInst.add("stuff") #call the method
When add is invoked on an instance object, the instance object is passed as the self argument to the method. Having the self argument differentiates class methods from instance methods.
A:
You are trying to call data.add() somewhat like you would call a static method in Java.
Try doing this instead:
d = data()
d.add('yes')
The self parameter tells the method that it operates on an object of type data.
|
Python 3.1.1 Class Question
|
I'm a new Python programmer who is having a little trouble using 'self' in classes. For example:
class data:
def __init__(self):
self.table = []
def add(self, file):
self.table.append(file)
data.add('yes')
In this function I want to have table be a variable stored in the class data and use add to modify it. However, when I run this script it gives me the error:
Traceback (most recent call last):
File "/Projects/Python/sfdfs.py", line 7, in <module>
data.add('yes')
TypeError: add() takes exactly 2 positional arguments (1 given)
I assume that I am trying to call the function the wrong way in this instance, as this syntax is very similar to an example in the python documentation: http://docs.python.org/3.1/tutorial/classes.html
|
[
"You first need to make an instance of the class:\nmydata = data()\n\nthen you can call the method -- on the instance, of course, not on the class:\nmydata.add('yes')\n\n",
"You need to instantiate the class before you can call methods on it:\nmydata = Data()\nmydata.add('yes')\n\n",
"you are calling the add method on the class object not an instance of the class.\nIt looks like what you want to do is:\nclassInst = data() #make an instance\nclassInst.add(\"stuff\") #call the method\nWhen add is invoked on an instance object, the instance object is passed as the self argument to the method. Having the self argument differentiates class methods from instance methods.\n",
"You are trying to call data.add() somewhat like you would call a static method in Java.\nTry doing this instead:\nd = data()\nd.add('yes')\n\nThe self parameter tells the method that it operates on an object of type data. \n"
] |
[
7,
1,
1,
0
] |
[] |
[] |
[
"class",
"python"
] |
stackoverflow_0002398782_class_python.txt
|
Q:
Why is my implementation of the Sieve of Atkin overlooking numbers close to the specified limit?
My implementation of Sieve of Atkin either overlooks primes near the limit or composites near the limit. while some limits work and others don't. I'm am completely confused as to what is wrong.
def AtkinSieve (limit):
results = [2,3,5]
sieve = [False]*limit
factor = int(math.sqrt(lim))
for i in range(1,factor):
for j in range(1, factor):
n = 4*i**2+j**2
if (n <= lim) and (n % 12 == 1 or n % 12 == 5):
sieve[n] = not sieve[n]
n = 3*i**2+j**2
if (n <= lim) and (n % 12 == 7):
sieve[n] = not sieve[n]
if i>j:
n = 3*i**2-j**2
if (n <= lim) and (n % 12 == 11):
sieve[n] = not sieve[n]
for index in range(5,factor):
if sieve[index]:
for jndex in range(index**2, limit, index**2):
sieve[jndex] = False
for index in range(7,limit):
if sieve[index]:
results.append(index)
return results
For example, when I generate a primes to the limit of 1000, the Atkin sieve misses the prime 997, but includes the composite 965. But if I generate up the limit of 5000, the list it returns is completely correct.
A:
Change lim to limit. Of course you must have known that.
Since sieve = [False]*limit,
the largest index allowed is limit-1.
However, on this line
if (n <= limit) and (n % 12 == 1 or n % 12 == 5):
you are checking if n<=limit. If n==limit then sieve[n] raises an IndexError.
Try your algorithm with a small value of limit (e.g. n=50). You'll see this error come up.
An easy fix is to use
sieve = [False]*(limit+1)
The easy fix is a bit wasteful since sieve[0] is never used. So you might think a better fix is to keep sieve = [False]*limit, but fix all your other code by stepping the index on sieve down by one. (E.g., change sieve[n] to sieve[n-1] everywhere, etc.) However, this will force you to do a number of extra subtractions which will not be good for speed. So the easy/wasteful solution is actually probably the better option.
According to http://en.wikipedia.org/wiki/Sieve_of_Atkin,
x should be an integer in [1,sqrt(limit)], inclusive of the endpoints.
In your code
factor = int(math.sqrt(limit))
and int takes the floor of math.sqrt(limit). Furthermore,
range(1,factor) goes from 1 to factor-1. So you are off by 1.
So you need to change this to
factor = int(math.sqrt(limit))+1
See Fastest way to list all primes below N for an alternative (and faster) implementation of the Sieve of Atkin, due to Steve Krenzel.
def AtkinSieve (limit):
results = [2,3,5]
sieve = [False]*(limit+1)
factor = int(math.sqrt(limit))+1
for i in range(1,factor):
for j in range(1, factor):
n = 4*i**2+j**2
if (n <= limit) and (n % 12 == 1 or n % 12 == 5):
sieve[n] = not sieve[n]
n = 3*i**2+j**2
if (n <= limit) and (n % 12 == 7):
sieve[n] = not sieve[n]
if i>j:
n = 3*i**2-j**2
if (n <= limit) and (n % 12 == 11):
sieve[n] = not sieve[n]
for index in range(5,factor):
if sieve[index]:
for jndex in range(index**2, limit, index**2):
sieve[jndex] = False
for index in range(7,limit):
if sieve[index]:
results.append(index)
return results
|
Why is my implementation of the Sieve of Atkin overlooking numbers close to the specified limit?
|
My implementation of Sieve of Atkin either overlooks primes near the limit or composites near the limit. while some limits work and others don't. I'm am completely confused as to what is wrong.
def AtkinSieve (limit):
results = [2,3,5]
sieve = [False]*limit
factor = int(math.sqrt(lim))
for i in range(1,factor):
for j in range(1, factor):
n = 4*i**2+j**2
if (n <= lim) and (n % 12 == 1 or n % 12 == 5):
sieve[n] = not sieve[n]
n = 3*i**2+j**2
if (n <= lim) and (n % 12 == 7):
sieve[n] = not sieve[n]
if i>j:
n = 3*i**2-j**2
if (n <= lim) and (n % 12 == 11):
sieve[n] = not sieve[n]
for index in range(5,factor):
if sieve[index]:
for jndex in range(index**2, limit, index**2):
sieve[jndex] = False
for index in range(7,limit):
if sieve[index]:
results.append(index)
return results
For example, when I generate a primes to the limit of 1000, the Atkin sieve misses the prime 997, but includes the composite 965. But if I generate up the limit of 5000, the list it returns is completely correct.
|
[
"\n Change lim to limit. Of course you must have known that.\n\nSince sieve = [False]*limit,\nthe largest index allowed is limit-1.\nHowever, on this line\nif (n <= limit) and (n % 12 == 1 or n % 12 == 5):\n\nyou are checking if n<=limit. If n==limit then sieve[n] raises an IndexError.\nTry your algorithm with a small value of limit (e.g. n=50). You'll see this error come up.\nAn easy fix is to use\nsieve = [False]*(limit+1)\n\nThe easy fix is a bit wasteful since sieve[0] is never used. So you might think a better fix is to keep sieve = [False]*limit, but fix all your other code by stepping the index on sieve down by one. (E.g., change sieve[n] to sieve[n-1] everywhere, etc.) However, this will force you to do a number of extra subtractions which will not be good for speed. So the easy/wasteful solution is actually probably the better option.\nAccording to http://en.wikipedia.org/wiki/Sieve_of_Atkin,\nx should be an integer in [1,sqrt(limit)], inclusive of the endpoints.\nIn your code\nfactor = int(math.sqrt(limit))\n\nand int takes the floor of math.sqrt(limit). Furthermore, \nrange(1,factor) goes from 1 to factor-1. So you are off by 1. \nSo you need to change this to \nfactor = int(math.sqrt(limit))+1\n\n See Fastest way to list all primes below N for an alternative (and faster) implementation of the Sieve of Atkin, due to Steve Krenzel.\n\ndef AtkinSieve (limit):\n results = [2,3,5]\n sieve = [False]*(limit+1)\n factor = int(math.sqrt(limit))+1\n for i in range(1,factor):\n for j in range(1, factor):\n n = 4*i**2+j**2\n if (n <= limit) and (n % 12 == 1 or n % 12 == 5):\n sieve[n] = not sieve[n]\n n = 3*i**2+j**2\n if (n <= limit) and (n % 12 == 7):\n sieve[n] = not sieve[n]\n if i>j:\n n = 3*i**2-j**2\n if (n <= limit) and (n % 12 == 11):\n sieve[n] = not sieve[n]\n for index in range(5,factor):\n if sieve[index]:\n for jndex in range(index**2, limit, index**2):\n sieve[jndex] = False\n for index in range(7,limit):\n if sieve[index]:\n results.append(index)\n return results\n\n"
] |
[
6
] |
[] |
[] |
[
"math",
"primes",
"python",
"sieve_of_atkin"
] |
stackoverflow_0002398894_math_primes_python_sieve_of_atkin.txt
|
Q:
How to use py2exe icon_resources in wxPython application?
I have a wxPython application I'm bundling into an exe using py2exe. I've defined an icon in the setup.py file using the following:
setup(
windows=[
{
'script': 'myapp.py',
'icon_resources': [(1, 'myicon.ico')]
},
],
)
This works, but I'd like to be able to access that icon from my wxPython application and use it as the window icon that appears in the top right. Currently I'm using the following to load the icon from the file system:
icon = wx.Icon('myicon.ico', wx.BITMAP_TYPE_ICO, 16, 16)
self.SetIcon(icon)
Which works, but requires that the icon sit beside the EXE, rather than bundled inside it.
A:
I do this inside the Frame subclass
if os.path.exists("myWxApplication.exe"):
self.SetIcon(wx.Icon("myWxApplication.exe",wx.BITMAP_TYPE_ICO))
|
How to use py2exe icon_resources in wxPython application?
|
I have a wxPython application I'm bundling into an exe using py2exe. I've defined an icon in the setup.py file using the following:
setup(
windows=[
{
'script': 'myapp.py',
'icon_resources': [(1, 'myicon.ico')]
},
],
)
This works, but I'd like to be able to access that icon from my wxPython application and use it as the window icon that appears in the top right. Currently I'm using the following to load the icon from the file system:
icon = wx.Icon('myicon.ico', wx.BITMAP_TYPE_ICO, 16, 16)
self.SetIcon(icon)
Which works, but requires that the icon sit beside the EXE, rather than bundled inside it.
|
[
"I do this inside the Frame subclass\nif os.path.exists(\"myWxApplication.exe\"):\n self.SetIcon(wx.Icon(\"myWxApplication.exe\",wx.BITMAP_TYPE_ICO))\n\n"
] |
[
4
] |
[] |
[] |
[
"bundle",
"icons",
"py2exe",
"python",
"wxpython"
] |
stackoverflow_0002399424_bundle_icons_py2exe_python_wxpython.txt
|
Q:
Python learner needs help spotting an error
This piece of code gives a syntax error at the colon of "elif process.loop(i, len(list_i) != 'repeat':" and I can't seem to figure out why.
class process:
def loop(v1, v2):
if v1 < v2 - 1:
return 'repeat'
def isel(chr_i, list_i):
for i in range(len(list_i)):
if chr_i == list_i[i]:
return list_i[i]
elif process.loop(i, len(list_i) != 'repeat':
return 'error'()
Edit: I am using 3.1.1 by the by.
A:
elif process.loop(i, len(list_i) != 'repeat':
you forgot a closed-paren, ), just before the !=; so the would-be left-hand side of the comparison opens two parentheses but closes only one -- that's the syntax error: "unbalanced parentheses", if you will.
A:
You're missing a parentheses!
Change
elif process.loop(i, len(list_i) != 'repeat':
to
elif process.loop(i, len(list_i)) != 'repeat':
|
Python learner needs help spotting an error
|
This piece of code gives a syntax error at the colon of "elif process.loop(i, len(list_i) != 'repeat':" and I can't seem to figure out why.
class process:
def loop(v1, v2):
if v1 < v2 - 1:
return 'repeat'
def isel(chr_i, list_i):
for i in range(len(list_i)):
if chr_i == list_i[i]:
return list_i[i]
elif process.loop(i, len(list_i) != 'repeat':
return 'error'()
Edit: I am using 3.1.1 by the by.
|
[
"elif process.loop(i, len(list_i) != 'repeat':\n\nyou forgot a closed-paren, ), just before the !=; so the would-be left-hand side of the comparison opens two parentheses but closes only one -- that's the syntax error: \"unbalanced parentheses\", if you will.\n",
"You're missing a parentheses!\nChange\n\nelif process.loop(i, len(list_i) != 'repeat':\n\nto\n\nelif process.loop(i, len(list_i)) != 'repeat':\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002399438_python.txt
|
Q:
Hexadecimals in python
I don't know python and I'm porting a library to C#, I've encountered the following lines of code that is used in some I/O operation but I'm not sure what it is, my guess is that it's a hexadecimal but I don't know why it's inside a string, neither what the backslashes do?
sep1 = '\x04H\xfe\x13' # record separator
sep2 = '\x00\xdd\x01\x0fT\x02\x00\x00\x01' # record separator
A:
They're escape sequences. In Python, \xNN within a (non-raw) string is treated as the character 0xNN.
A:
The backslashes are escape characters. They allow you to insert special characters (IE a quotation mark) inside a string. \xNN is hexadecimal, like you say.
It looks like they're using a string in place of an array to me. I'm not really sure why someone would do this... but oh well
I'm not familiar with C#, but in C, sep1 is similar to char[] {0x04H, 0xfe, 0x13} (with an additional 0 at the end if it's a null terminated string)
A:
The same escape sequence works in most languages. You'll just have to use the proper string quotes, in C# that's the double quote (").
A:
As others have stated it's escaped characters that can't really be represented as US ASCII characters. Why do you do this then?
The IO device needs a sequence of bytes with these special hexadecimal values for some reason.
Some languages does not support a native type for bytes, and then we have a problem. How can we write and send out a sequence of bytes when we can't have them in a variable?
The language C uses characters and strings of characters to store those bytes instead. So what you have is not really a string. Think of it as a sequence of bytes instead (stored in a string).
The "string" can be used as normal, i.e it can be sent to the I/O device just as any other character can be sent, and usually withe the same kind of functions (Write, Put, Print,...)
|
Hexadecimals in python
|
I don't know python and I'm porting a library to C#, I've encountered the following lines of code that is used in some I/O operation but I'm not sure what it is, my guess is that it's a hexadecimal but I don't know why it's inside a string, neither what the backslashes do?
sep1 = '\x04H\xfe\x13' # record separator
sep2 = '\x00\xdd\x01\x0fT\x02\x00\x00\x01' # record separator
|
[
"They're escape sequences. In Python, \\xNN within a (non-raw) string is treated as the character 0xNN.\n",
"The backslashes are escape characters. They allow you to insert special characters (IE a quotation mark) inside a string. \\xNN is hexadecimal, like you say.\nIt looks like they're using a string in place of an array to me. I'm not really sure why someone would do this... but oh well\nI'm not familiar with C#, but in C, sep1 is similar to char[] {0x04H, 0xfe, 0x13} (with an additional 0 at the end if it's a null terminated string)\n",
"The same escape sequence works in most languages. You'll just have to use the proper string quotes, in C# that's the double quote (\").\n",
"As others have stated it's escaped characters that can't really be represented as US ASCII characters. Why do you do this then? \nThe IO device needs a sequence of bytes with these special hexadecimal values for some reason. \nSome languages does not support a native type for bytes, and then we have a problem. How can we write and send out a sequence of bytes when we can't have them in a variable? \nThe language C uses characters and strings of characters to store those bytes instead. So what you have is not really a string. Think of it as a sequence of bytes instead (stored in a string). \nThe \"string\" can be used as normal, i.e it can be sent to the I/O device just as any other character can be sent, and usually withe the same kind of functions (Write, Put, Print,...)\n"
] |
[
5,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002398468_python.txt
|
Q:
Is there a static analysis tool for Python, Ruby, Sql, Cobol, Perl, and PL/SQL?
I am looking for a static analysis tool for Python, Ruby, Sql, Cobol, Perl, PL/SQL, SQL similar to find bugs and check style. I am looking for calculating the line count, identify bugs during the development, and enforcing coding standard.
A:
Perl has Perl::Critic (and perlcritic.com)
A:
I use PyChecker and pylint as Python code checkers. However it seems that they get buggy when you use some modules (e.g., socket or pygame, IIRC).
A:
For Ruby, you're probably best served looking at this previous SO question:
https://stackoverflow.com/questions/286564/can-anyone-recommend-a-ruby-source-code-analyzer-something-like-pylint
which seems pretty thorough.
A:
I use Pylint for Python which was nicely integrated into Komodo by Brandon Corfman (if ActiveState's Komodo is your thing).
A:
Sonar has a PL/SQL plugin that is based on Toad CodeXpert code analyzer.
A:
See various static analysis tools from Semantic
Designs.
These cover standard metrics for Java, C# and COBOL. There are also tools to detect duplicate code (clones) for many languages, including Python, Java, PL/SQL (from your list).
Finally, there is a style checker (coding standards checks) for COBOL (with optional Eclipse plugin) that offers refactoring support to fix some of the style errors.
|
Is there a static analysis tool for Python, Ruby, Sql, Cobol, Perl, and PL/SQL?
|
I am looking for a static analysis tool for Python, Ruby, Sql, Cobol, Perl, PL/SQL, SQL similar to find bugs and check style. I am looking for calculating the line count, identify bugs during the development, and enforcing coding standard.
|
[
"Perl has Perl::Critic (and perlcritic.com)\n",
"I use PyChecker and pylint as Python code checkers. However it seems that they get buggy when you use some modules (e.g., socket or pygame, IIRC).\n",
"For Ruby, you're probably best served looking at this previous SO question:\nhttps://stackoverflow.com/questions/286564/can-anyone-recommend-a-ruby-source-code-analyzer-something-like-pylint\nwhich seems pretty thorough.\n",
"I use Pylint for Python which was nicely integrated into Komodo by Brandon Corfman (if ActiveState's Komodo is your thing).\n",
"Sonar has a PL/SQL plugin that is based on Toad CodeXpert code analyzer.\n",
"See various static analysis tools from Semantic \nDesigns.\nThese cover standard metrics for Java, C# and COBOL. There are also tools to detect duplicate code (clones) for many languages, including Python, Java, PL/SQL (from your list).\nFinally, there is a style checker (coding standards checks) for COBOL (with optional Eclipse plugin) that offers refactoring support to fix some of the style errors.\n"
] |
[
10,
4,
2,
0,
0,
0
] |
[] |
[] |
[
"cobol",
"plsql",
"python",
"ruby",
"static_analysis"
] |
stackoverflow_0000956104_cobol_plsql_python_ruby_static_analysis.txt
|
Q:
Kiosk mode in wxpython?
Is there a way to create a 'kiosk mode' in wxpython under Windows (98 - 7) where the application disables you from breaking out of the app using Windows keys, alt-tab, alt-f4, and ctrl+alt+delete?
A:
If an application could do that it would make a great denial-of-service attack on the machine.
In particular Ctrl+Alt+Delete is the Secure Attention Sequence. Microsoft goes to great lengths to insure that when the user hits those keys, they switch to a secure desktop that they can be confident that the logon box is the real Windows logon and not a counterfeit.
What you need to look at isn't functions that your application can call, but System Administration options that allow an Administrator to configure a machine for limited use. These exist, but it's more a question for Super User than for Stack Overflow.
This should get you started
http://msdn.microsoft.com/en-us/library/aa372139(VS.85).aspx
A:
wxPython alone cannot be done with that.
You need to do Low Level Keyboard Hook with C/C++ or with equivalent ctypes, for
Windows keys, alt-tab, alt-f4,
but Ctrl-Alt-Del, I don't think so for Windows XP and above.
|
Kiosk mode in wxpython?
|
Is there a way to create a 'kiosk mode' in wxpython under Windows (98 - 7) where the application disables you from breaking out of the app using Windows keys, alt-tab, alt-f4, and ctrl+alt+delete?
|
[
"If an application could do that it would make a great denial-of-service attack on the machine.\nIn particular Ctrl+Alt+Delete is the Secure Attention Sequence. Microsoft goes to great lengths to insure that when the user hits those keys, they switch to a secure desktop that they can be confident that the logon box is the real Windows logon and not a counterfeit. \nWhat you need to look at isn't functions that your application can call, but System Administration options that allow an Administrator to configure a machine for limited use. These exist, but it's more a question for Super User than for Stack Overflow. \nThis should get you started\nhttp://msdn.microsoft.com/en-us/library/aa372139(VS.85).aspx\n",
"wxPython alone cannot be done with that. \nYou need to do Low Level Keyboard Hook with C/C++ or with equivalent ctypes, for\nWindows keys, alt-tab, alt-f4, \nbut Ctrl-Alt-Del, I don't think so for Windows XP and above.\n"
] |
[
2,
0
] |
[] |
[] |
[
"kiosk",
"mode",
"python",
"wxpython"
] |
stackoverflow_0002399812_kiosk_mode_python_wxpython.txt
|
Q:
In python, what does len(list) do?
Does len(list) calculate the length of the list every time it is called, or does it return the value of the built-in counter?I have a context where I need to check the length of a list every time through a loop, like:
listData = []
for value in ioread():
if len(listData)>=25:
processlistdata()
clearlistdata()
listData.append(value)
Should I check len(listData) on every iteration, or should I have a counter for the length of the list?
A:
You should probably be aware, if you're worried about this operation's performance, that "lists" in Python are really dynamic arrays. That is, they're not implemented as linked lists, which you generally have to "walk" to compute a length for (unless stored in a header).
Since they already need to store "bookkeeping" information to handle memory allocation, the length is stored too.
A:
Help on built-in function len in module __builtin__:
len(...)
len(object) -> integer
Return the number of items of a sequence or mapping.
so yes, len(list) returns how many items in the list. You might want to describe in more details, providing necessary input files/output to help better understand what you want to do.
A:
len(list) returns the length of a list. If you change it, you'll have to check it's length every iteration. Or use a counter.
A:
len(list) returns the length of the list. Everytime you call it, it will return the length of the list as it currently is. You could set up a counter by taking the len of list initially and then adding 1 to the variable each time something is appended to the list.
|
In python, what does len(list) do?
|
Does len(list) calculate the length of the list every time it is called, or does it return the value of the built-in counter?I have a context where I need to check the length of a list every time through a loop, like:
listData = []
for value in ioread():
if len(listData)>=25:
processlistdata()
clearlistdata()
listData.append(value)
Should I check len(listData) on every iteration, or should I have a counter for the length of the list?
|
[
"You should probably be aware, if you're worried about this operation's performance, that \"lists\" in Python are really dynamic arrays. That is, they're not implemented as linked lists, which you generally have to \"walk\" to compute a length for (unless stored in a header).\nSince they already need to store \"bookkeeping\" information to handle memory allocation, the length is stored too.\n",
"Help on built-in function len in module __builtin__:\n\nlen(...)\n len(object) -> integer\n\n Return the number of items of a sequence or mapping.\n\nso yes, len(list) returns how many items in the list. You might want to describe in more details, providing necessary input files/output to help better understand what you want to do.\n",
"len(list) returns the length of a list. If you change it, you'll have to check it's length every iteration. Or use a counter.\n",
"len(list) returns the length of the list. Everytime you call it, it will return the length of the list as it currently is. You could set up a counter by taking the len of list initially and then adding 1 to the variable each time something is appended to the list.\n"
] |
[
18,
2,
0,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002399835_list_python.txt
|
Q:
__rlshift__, __ror__ in Python
I noticed that this recipe seems to use __rlshift__, __ror__ like operators. But, they aren't in the documentation! Can anyone explain these and perhaps point to some docs?
A:
See the documentation for:
object.__rlshift__()
object.__ror__()
__rlshift__ is the swapped operands version of __lshift__, used when the right-hand operand supports the operation but the left-hand operand doesn't.
|
__rlshift__, __ror__ in Python
|
I noticed that this recipe seems to use __rlshift__, __ror__ like operators. But, they aren't in the documentation! Can anyone explain these and perhaps point to some docs?
|
[
"See the documentation for:\n\nobject.__rlshift__()\nobject.__ror__()\n\n__rlshift__ is the swapped operands version of __lshift__, used when the right-hand operand supports the operation but the left-hand operand doesn't.\n"
] |
[
10
] |
[] |
[] |
[
"operators",
"python"
] |
stackoverflow_0002400171_operators_python.txt
|
Q:
Python 3.1.1 Problem With Tuples
This piece of code is supposed to go through a list and preform some formatting to the items, such as removing quotations, and then saving it to another list.
class process:
def rchr(string_i, asciivalue):
string_o = ()
for i in range(len(string_i)):
if ord(string_i[i]) != asciivalue:
string_o += string_i[i]
return string_o
def flist(self, list_i):
cache = ()
cache_list = []
index = 0
for line in list_i:
cache = line.split('\t')
cache[0] = process.rchr(str(cache[0]), 34)
cache_list.append(cache[0])
cache_list[index] = cache
index += 1
cache_list.sort()
return cache_list
p = process()
list1a = ['cow', 'dog', 'sheep']
list1 = p.flist(list1a)
print (list1)
However; it chokes at string_o += string_i[i] and gives the following error:
Traceback (most recent call last):
File "/Projects/Python/safafa.py", line 23, in <module>
list1 = p.flist(list1a)
File "/Projects/Python/safafa.py", line 14, in flist
cacbe[0] = process.rchr(str(cache[0]), 34)
File "/Projects/Python/safafa.py", line 7, in rchr
string_o += string_i[i]
TypeError: can only concatenate tuple (not "str") to tuple
A:
I think you want string_o = "" instead of string_o = ()
Your problem is that you want string_o to be a string so you can append other strings onto it. Setting it equal to () makes it a tuple instead, which is a data type incompatible with string.
A:
In addition to the previous answer, a more pythonic way to go would be:
string_o = ''.join(c for c in string_i if ord(c) != asciivalue)
It is short and readable.
A:
To add to Olivier's answer, I think the whole code could be replaced with:
import itertools
output = [i.replace('"','') for i in list(itertools.chain(*(x.split('\t') for x in input)))]
Tested with python 2.x only.
|
Python 3.1.1 Problem With Tuples
|
This piece of code is supposed to go through a list and preform some formatting to the items, such as removing quotations, and then saving it to another list.
class process:
def rchr(string_i, asciivalue):
string_o = ()
for i in range(len(string_i)):
if ord(string_i[i]) != asciivalue:
string_o += string_i[i]
return string_o
def flist(self, list_i):
cache = ()
cache_list = []
index = 0
for line in list_i:
cache = line.split('\t')
cache[0] = process.rchr(str(cache[0]), 34)
cache_list.append(cache[0])
cache_list[index] = cache
index += 1
cache_list.sort()
return cache_list
p = process()
list1a = ['cow', 'dog', 'sheep']
list1 = p.flist(list1a)
print (list1)
However; it chokes at string_o += string_i[i] and gives the following error:
Traceback (most recent call last):
File "/Projects/Python/safafa.py", line 23, in <module>
list1 = p.flist(list1a)
File "/Projects/Python/safafa.py", line 14, in flist
cacbe[0] = process.rchr(str(cache[0]), 34)
File "/Projects/Python/safafa.py", line 7, in rchr
string_o += string_i[i]
TypeError: can only concatenate tuple (not "str") to tuple
|
[
"I think you want string_o = \"\" instead of string_o = ()\nYour problem is that you want string_o to be a string so you can append other strings onto it. Setting it equal to () makes it a tuple instead, which is a data type incompatible with string.\n",
"In addition to the previous answer, a more pythonic way to go would be:\nstring_o = ''.join(c for c in string_i if ord(c) != asciivalue)\n\nIt is short and readable.\n",
"To add to Olivier's answer, I think the whole code could be replaced with:\nimport itertools\noutput = [i.replace('\"','') for i in list(itertools.chain(*(x.split('\\t') for x in input)))]\n\nTested with python 2.x only.\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"class",
"python",
"tuples"
] |
stackoverflow_0002400188_class_python_tuples.txt
|
Q:
Is closing file descriptor and removing inotify watch really necessary?
With python inotifyx, do I have to remove watch and close opened system file descriptor if I need them until program exit? E.g. is there some possible problems if I create one (file descriptor + watch) with each run and don't close it?
A:
It's always a good idea to release resources (e.g. free memory, close file descriptors, waitpid(2) on child processes, etc) whenever you're done using them. Being lazy and letting the operating system take care of it for you when you exit is a sure way to cause bugs in the future.
A:
The kernel stores watches as full paths, so closing the watch is preferable, it also takes unnecessary work off of VFS. As for the file descriptor, that would depend on how many others you had opened.
Kind of like a phone call, its nice to tell the other party that you have stopped listening, hanging up the phone is optional, but conventional. If you need it for something, keep it.
|
Is closing file descriptor and removing inotify watch really necessary?
|
With python inotifyx, do I have to remove watch and close opened system file descriptor if I need them until program exit? E.g. is there some possible problems if I create one (file descriptor + watch) with each run and don't close it?
|
[
"It's always a good idea to release resources (e.g. free memory, close file descriptors, waitpid(2) on child processes, etc) whenever you're done using them. Being lazy and letting the operating system take care of it for you when you exit is a sure way to cause bugs in the future.\n",
"The kernel stores watches as full paths, so closing the watch is preferable, it also takes unnecessary work off of VFS. As for the file descriptor, that would depend on how many others you had opened.\nKind of like a phone call, its nice to tell the other party that you have stopped listening, hanging up the phone is optional, but conventional. If you need it for something, keep it.\n"
] |
[
1,
0
] |
[] |
[] |
[
"inotify",
"linux",
"python"
] |
stackoverflow_0002400276_inotify_linux_python.txt
|
Q:
Implementing __concat__ in Python
I tried to implement __concat__, but it didn't work
>>> class lHolder():
... def __init__(self,l):
... self.l=l
... def __concat__(self, l2):
... return self.l+l2
... def __iter__(self):
... return self.l.__iter__()
...
>>> lHolder([1])+[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'lHolder' and 'list'
How can I fix this?
A:
__concat__ is not a special method (http://docs.python.org/glossary.html#term-special-method). It is part of the operator module.
You will need to implement __add__ to get the behaviour you want.
A:
You want to implement __add__, not __concat__. There's no __concat__ special method in Python.
|
Implementing __concat__ in Python
|
I tried to implement __concat__, but it didn't work
>>> class lHolder():
... def __init__(self,l):
... self.l=l
... def __concat__(self, l2):
... return self.l+l2
... def __iter__(self):
... return self.l.__iter__()
...
>>> lHolder([1])+[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'lHolder' and 'list'
How can I fix this?
|
[
"__concat__ is not a special method (http://docs.python.org/glossary.html#term-special-method). It is part of the operator module.\nYou will need to implement __add__ to get the behaviour you want.\n",
"You want to implement __add__, not __concat__. There's no __concat__ special method in Python.\n"
] |
[
5,
2
] |
[] |
[] |
[
"operator_overloading",
"python",
"sequences"
] |
stackoverflow_0002400561_operator_overloading_python_sequences.txt
|
Q:
How can I interact with rather long python scripts?
I love the IDLE. However, sometimes I have 100-200 line scripts and I want to sort of interactively debug/play with say, functions defined in foo.py instead of just calling python foo.py. Is there a way I can trigger IDLE in the context of my foo.py?
A:
Insert this line into the script:
import pdb; pdb.set_trace()
Which will start the python debugger which lets you step through the script interactively, checking variables and such as you go.
A:
I assume you are asking about how to enable debugging in Idle?
In the Python Shell window, choose Debugger from the Debug menu, then open foo.py and use the Run Model command. A Debug Control window opens, allowing you to step through the execution of foo.py; when execution is over, the prompt is still available for you to manually call functions, interact with objects or otherwise tinker with your application (and you will be still debugging the script).
|
How can I interact with rather long python scripts?
|
I love the IDLE. However, sometimes I have 100-200 line scripts and I want to sort of interactively debug/play with say, functions defined in foo.py instead of just calling python foo.py. Is there a way I can trigger IDLE in the context of my foo.py?
|
[
"Insert this line into the script:\nimport pdb; pdb.set_trace()\n\nWhich will start the python debugger which lets you step through the script interactively, checking variables and such as you go. \n",
"I assume you are asking about how to enable debugging in Idle?\nIn the Python Shell window, choose Debugger from the Debug menu, then open foo.py and use the Run Model command. A Debug Control window opens, allowing you to step through the execution of foo.py; when execution is over, the prompt is still available for you to manually call functions, interact with objects or otherwise tinker with your application (and you will be still debugging the script).\n"
] |
[
5,
1
] |
[] |
[] |
[
"python",
"python_idle"
] |
stackoverflow_0002400619_python_python_idle.txt
|
Q:
Python urllib proxy
I'm trying to fetch some urls via urllib and mechanize through my proxy.
With mechanize I try the following:
from mechanize import Browser
import re
br = Browser()
br.set_proxies({"http": "MYUSERNAME:*******@itmalsproxy.italy.local:8080"})
br.open("http://www.example.com/")
I get the following error:
httperror_seek_wrapper: HTTP Error 407: Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy service is denied.
As the proxy, the username and the password are correct, what could be the problem?
A:
Maybe the proxy is using NTLM authentication?
If that is the case, you can try using the NTLM Authorization Proxy Server (see also this answer).
A:
you might get more info from the response headers
print br.response().info()
A:
When your web browser uses proxy server to surf the Web from within your local
network your may be required to authenticate youself to use proxy. Google ntlmaps.
|
Python urllib proxy
|
I'm trying to fetch some urls via urllib and mechanize through my proxy.
With mechanize I try the following:
from mechanize import Browser
import re
br = Browser()
br.set_proxies({"http": "MYUSERNAME:*******@itmalsproxy.italy.local:8080"})
br.open("http://www.example.com/")
I get the following error:
httperror_seek_wrapper: HTTP Error 407: Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy service is denied.
As the proxy, the username and the password are correct, what could be the problem?
|
[
"Maybe the proxy is using NTLM authentication?\nIf that is the case, you can try using the NTLM Authorization Proxy Server (see also this answer).\n",
"you might get more info from the response headers\nprint br.response().info()\n",
"When your web browser uses proxy server to surf the Web from within your local\nnetwork your may be required to authenticate youself to use proxy. Google ntlmaps.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"mechanize",
"proxy",
"python"
] |
stackoverflow_0001899901_mechanize_proxy_python.txt
|
Q:
How do I execute SQL_CALC_FOUND_ROWS in python MySQLDB
cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5")
rows = cursor.fetchall()
...
total_rows = cursor.execute("SELECT FOUND_ROWS()") #this doesn't work for some reason.
Edit: I tried SELECT FOUND_ROWS() FROM my_table...and the numbers are funky.
A:
Seems to work here by fetching the result for the second cursor:
cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5")
rows = cursor.fetchall()
cursor.execute("SELECT FOUND_ROWS()")
(total_rows,) = cursor.fetchone()
|
How do I execute SQL_CALC_FOUND_ROWS in python MySQLDB
|
cursor.execute("SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5")
rows = cursor.fetchall()
...
total_rows = cursor.execute("SELECT FOUND_ROWS()") #this doesn't work for some reason.
Edit: I tried SELECT FOUND_ROWS() FROM my_table...and the numbers are funky.
|
[
"Seems to work here by fetching the result for the second cursor:\ncursor.execute(\"SELECT SQL_CALC_FOUND_ROWS user_id FROM...limit 5\")\nrows = cursor.fetchall()\n\ncursor.execute(\"SELECT FOUND_ROWS()\")\n(total_rows,) = cursor.fetchone()\n\n"
] |
[
1
] |
[] |
[] |
[
"database",
"mysql",
"python",
"select"
] |
stackoverflow_0002400492_database_mysql_python_select.txt
|
Q:
Comprehensive guide to Operator Overloading in Python
Is there a comprehensive guide to operator overloading anywhere? Preferably online, but a book would be fine too. The description of the operator module leaves a lot out, such as including operators that can't be overloaded and missing the r operators or providing sensible defaults. (Writing these operators is good practice, but still belongs in a good reference)
A:
Python's operator overloading is done by redefining certain special methods in any class.
This is explained in the Python language reference.
For example, to overload the addition operator:
>>> class MyClass(object):
... def __add__(self, x):
... return '%s plus %s' % (self, x)
...
>>> obj = MyClass()
>>> obj + 1
'<__main__.MyClass object at 0xb77eff2c> plus 1'
The relevant section in the Python 3 documentation can be seen here.
A:
I like this reference to quickly see which operators may be overloaded:
http://rgruet.free.fr/PQR26/PQR2.6.html#SpecialMethods
Here is another resource, for completeness (and also for Python 3)
http://www.python-course.eu/python3_magic_methods.php
|
Comprehensive guide to Operator Overloading in Python
|
Is there a comprehensive guide to operator overloading anywhere? Preferably online, but a book would be fine too. The description of the operator module leaves a lot out, such as including operators that can't be overloaded and missing the r operators or providing sensible defaults. (Writing these operators is good practice, but still belongs in a good reference)
|
[
"Python's operator overloading is done by redefining certain special methods in any class.\nThis is explained in the Python language reference.\nFor example, to overload the addition operator:\n>>> class MyClass(object):\n... def __add__(self, x):\n... return '%s plus %s' % (self, x)\n... \n>>> obj = MyClass()\n>>> obj + 1\n'<__main__.MyClass object at 0xb77eff2c> plus 1'\n\nThe relevant section in the Python 3 documentation can be seen here.\n",
"I like this reference to quickly see which operators may be overloaded:\nhttp://rgruet.free.fr/PQR26/PQR2.6.html#SpecialMethods\nHere is another resource, for completeness (and also for Python 3)\nhttp://www.python-course.eu/python3_magic_methods.php\n"
] |
[
50,
24
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002400635_python.txt
|
Q:
Adding a generic image field onto a ModelForm in django
I have two models, Room and Image. Image is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.
Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong.
Update:
I've tried to clarify why I chose this design in comments to the current answers. To summarize:
I didn't simply put an ImageField on the Room model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single Image class, which seemed messy, or multiple Image classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.
Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.
# Models
class Image(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
image = models.ImageField(_('Image'),
height_field='',
width_field='',
upload_to='uploads/images',
max_length=200)
class Room(models.Model):
name = models.CharField(max_length=50)
image_set = generic.GenericRelation('Image')
# The form
class AddRoomForm(forms.ModelForm):
image_1 = forms.ImageField()
class Meta:
model = Room
# The view
def handle_uploaded_file(f):
# DRY violation, I've already specified the upload path in the image model
upload_suffix = join('uploads/images', f.name)
upload_path = join(settings.MEDIA_ROOT, upload_suffix)
destination = open(upload_path, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
return upload_suffix
def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'):
apartment = Apartment.objects.get(id=apartment_id)
if request.method == 'POST':
form = form_class(request.POST, request.FILES)
if form.is_valid():
room = form.save()
image_1 = form.cleaned_data['image_1']
# Instead of writing a special function to handle the image,
# shouldn't I just be able to pass it straight into Image.objects.create
# ...but it doesn't seem to work for some reason, wrong syntax perhaps?
upload_path = handle_uploaded_file(image_1)
image = Image.objects.create(content_object=room, image=upload_path)
return HttpResponseRedirect(room.get_absolute_url())
else:
form = form_class()
context = {'form': form, }
return direct_to_template(request, template, extra_context=context)
A:
Why don't you just use ImageField? I don't see the need for the Image class.
# model
class Room(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to="uploads/images/")
# form
from django import forms
class UploadFileForm(forms.Form):
name = forms.CharField(max_length=50)
image = forms.FileField()
Take a look at Basic file uploads and How do I use image and file fields?
A:
You don't have to use the Image class. As DZPM suggested, convert the image field to an ImageField. You also need to make some changes to the view.
Instead of using an upload handler, you can create a Image object with the uploaded data and attach the Image object to the Room object.
To save the Image object you need to do something like this in the view:
from django.core.files.base import ContentFile
if request.FILES.has_key('image_1'):
image_obj = Image()
image_obj.file.save(request.FILES['image_1'].name,\
ContentFile(request.FILES['image_1'].read()))
image_obj.save()
room_obj.image_set.create(image_obj)
room_obj.save()
Also, I think instead of the GenericRelation, you should use a ManyToManyField, in which case the syntax for adding an Image to a Room will change slightly.
A:
What about using two forms on the page: one for the room and one for the image?
You'll just have to make the generic foreign key fields of the image form not required, and fill in their values in the view after saving the room.
A:
Django does support your use case at least up to a point:
formsets display repeated forms
model formsets handle repeated model forms
inline formsets bind model formsets to related objects of an instance
generic inline formsets do the same for generic relations
Generic inline formsets were introduced in changeset [8279]. See the changes to unit tests to see how they are used.
With generic inline formsets you'll also be able to display multiple already saved images for existing rooms in your form.
Inline formsets seem to expect an existing parent instance in the instance= argument. The admin interface does let you fill in inlines before saving the parent instance, so there must be a way to achieve that. I've just never tried that myself.
A:
I found this page look for a solution to this same problem.
Here is my info -- hopefully helps some.
MODELS: Image, Review, Manufacturer, Profile
I want Review, Manufacturer, Profile to have a relationship to the Image model. But you have to beable to have multiple Images per object. (Ie, One Review can have 5 images a different Review can have 3, etc)
Originally I did a
images = ManyToManyField(Image)
in each of the other models. This works fine, but sucks for admin (combo select box). This may be a solution for you though. I dont like it for what I'm trying to do.
The other thing I'm working on now is having multiple foreign keys.
class Image(models.Model):
description = models.TextField(blank=True)
image = models.ImageField(upload_to="media/")
user_profile = models.ForeignKey(UserProfile)
mfgr = models.ForeignKey(Manufacturer)
review = models.ForeignKey(Review)
but like you said. This is pretty sloppy looking and I just dont like it.
One other thing I just found but don't have my brain completely wrapped around (and not sure how transparent it is after implementation is Generic Relationships (or Generic Foreign Keys), which may be a solution. Well once I comprehend it all. Need more caffeine.
http://www.djangoproject.com/documentation/models/generic_relations/
Let me know if you get this sorted out or any of this helps. Thanks!
Let me know if this helps or you have a different solutions.
A:
Ok I figured it out with some more reading... I feel like you want to do exactly what I have done so here it is.
I'll be using GenericForeignKeys for this.
First the imports for models.py
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
Now add the following to your Image Model
class Image(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
This lets this model be just that, a Generic Foreign Key for any number of models.
Then add the following to all the models you want to have related images
images = generic.GenericRelation(Image)
Now in admin.py you need to add the following things.
from django.contrib.contenttypes.generic import GenericTabularInline
class ImageInline(GenericTabularInline):
model = Image
extra = 3
ct_field_name = 'content_type'
id_field_name = 'object_id'
And then include it in a admin declaration
class ReviewAdmin(admin.ModelAdmin):
inlines = [ImageInline]
And thats it. Its working great over here. Hope this helps man!
.adam.
A:
Use two forms, one for the room and one for the image:
class Image(models.Model)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
image = models.ImageField(upload_to='')
class UploadImage(forms.ModelForm):
class Meta:
model = Image
fields = ('image')
class Room(models.Model):
name = models.CharField(max_length=50)
images = models.ManyToManyField(Image)
class RoomForm(forms.ModelForm):
class Meta:
model = Room
in the views
if request.method == "POST":
##2 form, una per l'annuncio ed una per la fotografia
form = RoomForm(request.POST)
image_form = UploadImage(request.POST, request.FILES)
#my_logger.debug('form.is_valid() : ' + str(form.is_valid()))
if form.is_valid() and image_form.is_valid():
##save room
room = room.save()
##save image
image = image_form.save()
##ManyToMany
room.images = [image]
room.save()
|
Adding a generic image field onto a ModelForm in django
|
I have two models, Room and Image. Image is a generic model that can tack onto any other model. I want to give users a form to upload an image when they post information about a room. I've written code that works, but I'm afraid I've done it the hard way, and specifically in a way that violates DRY.
Was hoping someone who's a little more familiar with django forms could point out where I've gone wrong.
Update:
I've tried to clarify why I chose this design in comments to the current answers. To summarize:
I didn't simply put an ImageField on the Room model because I wanted more than one image associated with the Room model. I chose a generic Image model because I wanted to add images to several different models. The alternatives I considered were were multiple foreign keys on a single Image class, which seemed messy, or multiple Image classes, which I thought would clutter my schema. I didn't make this clear in my first post, so sorry about that.
Seeing as none of the answers so far has addressed how to make this a little more DRY I did come up with my own solution which was to add the upload path as a class attribute on the image model and reference that every time it's needed.
# Models
class Image(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
image = models.ImageField(_('Image'),
height_field='',
width_field='',
upload_to='uploads/images',
max_length=200)
class Room(models.Model):
name = models.CharField(max_length=50)
image_set = generic.GenericRelation('Image')
# The form
class AddRoomForm(forms.ModelForm):
image_1 = forms.ImageField()
class Meta:
model = Room
# The view
def handle_uploaded_file(f):
# DRY violation, I've already specified the upload path in the image model
upload_suffix = join('uploads/images', f.name)
upload_path = join(settings.MEDIA_ROOT, upload_suffix)
destination = open(upload_path, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
return upload_suffix
def add_room(request, apartment_id, form_class=AddRoomForm, template='apartments/add_room.html'):
apartment = Apartment.objects.get(id=apartment_id)
if request.method == 'POST':
form = form_class(request.POST, request.FILES)
if form.is_valid():
room = form.save()
image_1 = form.cleaned_data['image_1']
# Instead of writing a special function to handle the image,
# shouldn't I just be able to pass it straight into Image.objects.create
# ...but it doesn't seem to work for some reason, wrong syntax perhaps?
upload_path = handle_uploaded_file(image_1)
image = Image.objects.create(content_object=room, image=upload_path)
return HttpResponseRedirect(room.get_absolute_url())
else:
form = form_class()
context = {'form': form, }
return direct_to_template(request, template, extra_context=context)
|
[
"Why don't you just use ImageField? I don't see the need for the Image class.\n# model\nclass Room(models.Model):\n name = models.CharField(max_length=50)\n image = models.ImageField(upload_to=\"uploads/images/\")\n\n# form\nfrom django import forms\n\nclass UploadFileForm(forms.Form):\n name = forms.CharField(max_length=50)\n image = forms.FileField()\n\nTake a look at Basic file uploads and How do I use image and file fields?\n",
"You don't have to use the Image class. As DZPM suggested, convert the image field to an ImageField. You also need to make some changes to the view.\nInstead of using an upload handler, you can create a Image object with the uploaded data and attach the Image object to the Room object.\nTo save the Image object you need to do something like this in the view:\nfrom django.core.files.base import ContentFile\n\nif request.FILES.has_key('image_1'):\n image_obj = Image()\n image_obj.file.save(request.FILES['image_1'].name,\\\n ContentFile(request.FILES['image_1'].read()))\n image_obj.save()\n room_obj.image_set.create(image_obj)\n room_obj.save()\n\nAlso, I think instead of the GenericRelation, you should use a ManyToManyField, in which case the syntax for adding an Image to a Room will change slightly.\n",
"What about using two forms on the page: one for the room and one for the image?\nYou'll just have to make the generic foreign key fields of the image form not required, and fill in their values in the view after saving the room.\n",
"Django does support your use case at least up to a point:\n\nformsets display repeated forms\nmodel formsets handle repeated model forms\ninline formsets bind model formsets to related objects of an instance\ngeneric inline formsets do the same for generic relations\n\nGeneric inline formsets were introduced in changeset [8279]. See the changes to unit tests to see how they are used.\nWith generic inline formsets you'll also be able to display multiple already saved images for existing rooms in your form.\nInline formsets seem to expect an existing parent instance in the instance= argument. The admin interface does let you fill in inlines before saving the parent instance, so there must be a way to achieve that. I've just never tried that myself.\n",
"I found this page look for a solution to this same problem.\nHere is my info -- hopefully helps some.\nMODELS: Image, Review, Manufacturer, Profile\nI want Review, Manufacturer, Profile to have a relationship to the Image model. But you have to beable to have multiple Images per object. (Ie, One Review can have 5 images a different Review can have 3, etc)\nOriginally I did a \nimages = ManyToManyField(Image)\n\nin each of the other models. This works fine, but sucks for admin (combo select box). This may be a solution for you though. I dont like it for what I'm trying to do.\nThe other thing I'm working on now is having multiple foreign keys.\nclass Image(models.Model):\n description = models.TextField(blank=True)\n image = models.ImageField(upload_to=\"media/\")\n user_profile = models.ForeignKey(UserProfile)\n mfgr = models.ForeignKey(Manufacturer)\n review = models.ForeignKey(Review)\n\nbut like you said. This is pretty sloppy looking and I just dont like it.\nOne other thing I just found but don't have my brain completely wrapped around (and not sure how transparent it is after implementation is Generic Relationships (or Generic Foreign Keys), which may be a solution. Well once I comprehend it all. Need more caffeine.\nhttp://www.djangoproject.com/documentation/models/generic_relations/\nLet me know if you get this sorted out or any of this helps. Thanks!\nLet me know if this helps or you have a different solutions.\n",
"Ok I figured it out with some more reading... I feel like you want to do exactly what I have done so here it is.\nI'll be using GenericForeignKeys for this.\nFirst the imports for models.py\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nNow add the following to your Image Model\nclass Image(models.Model):\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n content_object = generic.GenericForeignKey()\n\nThis lets this model be just that, a Generic Foreign Key for any number of models.\nThen add the following to all the models you want to have related images\nimages = generic.GenericRelation(Image)\n\nNow in admin.py you need to add the following things.\nfrom django.contrib.contenttypes.generic import GenericTabularInline\n\nclass ImageInline(GenericTabularInline):\n model = Image\n extra = 3\n ct_field_name = 'content_type'\n id_field_name = 'object_id'\n\nAnd then include it in a admin declaration\nclass ReviewAdmin(admin.ModelAdmin):\n inlines = [ImageInline]\n\nAnd thats it. Its working great over here. Hope this helps man!\n.adam.\n",
"Use two forms, one for the room and one for the image:\nclass Image(models.Model)\ncontent_type = models.ForeignKey(ContentType)\nobject_id = models.PositiveIntegerField()\ncontent_object = generic.GenericForeignKey('content_type', 'object_id')\nimage = models.ImageField(upload_to='')\n\nclass UploadImage(forms.ModelForm):\nclass Meta:\n model = Image\n fields = ('image')\n\nclass Room(models.Model):\nname = models.CharField(max_length=50)\nimages = models.ManyToManyField(Image) \n\nclass RoomForm(forms.ModelForm):\nclass Meta:\n model = Room\n\nin the views\nif request.method == \"POST\":\n ##2 form, una per l'annuncio ed una per la fotografia\n form = RoomForm(request.POST)\n image_form = UploadImage(request.POST, request.FILES)\n #my_logger.debug('form.is_valid() : ' + str(form.is_valid()))\n if form.is_valid() and image_form.is_valid():\n ##save room\n room = room.save()\n\n ##save image\n image = image_form.save()\n\n ##ManyToMany\n room.images = [image]\n room.save()\n\n"
] |
[
4,
2,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0000467985_django_django_forms_python.txt
|
Q:
Netbeans not allowing Python 2.6 as default platform (forcing Jython2.5)
I am trying to get Netbeans python to run with the default python platform set to Python 2.6.1 (my system python), so in Netbeans I do the following:
Tools -> Python Platform
Set Python 2.6.1 to 'default'
However, it seems impossible to make this stick. Whenever I restart Netbeans it's back to Jython 2.5 again.
Moreover, I can obviously autodetect and find Python 2.6.1, but whenever I make it "Default", Netbeans still runs with Jython 2.5 in that very session. (I know this because when I import sys and do a sys.path it only has Jython library dirs). And when I remove Jython I get the error:
"Selected project has broken python platform : default => bind to an existing python platform in project's properties".
I have tried this is 6.5 and 6.7. And I still get the same behavior. Furthermore, I know my system python works because I can use the python interpreter.
A:
Looks like http://netbeans.org/bugzilla/show_bug.cgi?id=180693 which provides a clumsy and non persistent workaround.
This needs heavy complaining on the netbean bug tracker imo.
A:
Might be worth logging a bug with Netbeans about the first bit of behaviour you described - I can confirm similar (although strangely not identical) symptoms on my system.
I tried this with Python 2.6.2 / Netbeans 6.5.1
NetBeans IDE 6.5.1 (Build 200903060201)
Java: 1.6.0_01; Java HotSpot(TM) Client VM 1.6.0_01-b06
System: Windows XP version 5.1 running on x86; Cp1252; en_GB (nb)
And my default Python platform also doesn't seem to stick: I restart and the default is back to "Jython 2.5b0+"
However, when I create a new Python project: the drop-down on the wizard is correctly set to 'Python 2.6.2": furthermore, when I created a new module like this:
import sys
print(sys.path)
It reports back correctly:
...'d:\\python26\\DLLs', 'd:\\python26\\lib'...
Maybe this is due to something about the slightly different Python platform versions - dunno?
|
Netbeans not allowing Python 2.6 as default platform (forcing Jython2.5)
|
I am trying to get Netbeans python to run with the default python platform set to Python 2.6.1 (my system python), so in Netbeans I do the following:
Tools -> Python Platform
Set Python 2.6.1 to 'default'
However, it seems impossible to make this stick. Whenever I restart Netbeans it's back to Jython 2.5 again.
Moreover, I can obviously autodetect and find Python 2.6.1, but whenever I make it "Default", Netbeans still runs with Jython 2.5 in that very session. (I know this because when I import sys and do a sys.path it only has Jython library dirs). And when I remove Jython I get the error:
"Selected project has broken python platform : default => bind to an existing python platform in project's properties".
I have tried this is 6.5 and 6.7. And I still get the same behavior. Furthermore, I know my system python works because I can use the python interpreter.
|
[
"Looks like http://netbeans.org/bugzilla/show_bug.cgi?id=180693 which provides a clumsy and non persistent workaround. \nThis needs heavy complaining on the netbean bug tracker imo. \n",
"Might be worth logging a bug with Netbeans about the first bit of behaviour you described - I can confirm similar (although strangely not identical) symptoms on my system.\nI tried this with Python 2.6.2 / Netbeans 6.5.1\nNetBeans IDE 6.5.1 (Build 200903060201)\nJava: 1.6.0_01; Java HotSpot(TM) Client VM 1.6.0_01-b06\nSystem: Windows XP version 5.1 running on x86; Cp1252; en_GB (nb)\n\nAnd my default Python platform also doesn't seem to stick: I restart and the default is back to \"Jython 2.5b0+\"\nHowever, when I create a new Python project: the drop-down on the wizard is correctly set to 'Python 2.6.2\": furthermore, when I created a new module like this:\nimport sys\nprint(sys.path)\n\nIt reports back correctly:\n...'d:\\\\python26\\\\DLLs', 'd:\\\\python26\\\\lib'...\n\nMaybe this is due to something about the slightly different Python platform versions - dunno?\n"
] |
[
1,
0
] |
[] |
[] |
[
"jython",
"netbeans",
"python"
] |
stackoverflow_0002200685_jython_netbeans_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.