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:
apache + mod_wsgi + aspell-python on OS X 10.5.8
I have a website that processes user submitted documents in a variety of ways, one of which is to do a spell check on a part of each document. When I set this website up on a Mac Mini (yes, I realize that's a pretty weak piece of equipment for a website, but it's internal and no one outside the office sees it), I remember having some trouble getting aspell-python to play nice with an install of Aspell when being invoked from Apache, but foolishly forgot to write down how I got around it. I'm under the impression that it had something to do with Apache, Python, and Aspell being compiled to run under different bit modes (64 for Apache, 32 for Python and Aspell, maybe).
In any case, I'm using the stock Apache and Python installs, and have built Aspell from source as well as installed it from MacPorts. It's been happily chugging along for about a year, but...
Fast forward to today: I ran OS X's software update (now I'm up to 10.5.8) and suddenly my spell checker stopped working. Currently, the message that's being thrown up by Django is that "no suitable image was found" by aspell-python, specifically that there is "no matching architecture in the universal wrapper".
Aspell and aspell-python continue to work fine from the command line, but not through the website. Does anyone have any thoughts?
Edit: Using 10.5.8 now, also, my psycopg2 bindings have stopped working. Both aspell and psycopg2 were being used as shared objects, if that's any help.
A:
If your upgrade was only from one patch revision of 10.5 to later patch revision of 10.5, then you shouldn't have seen any change in behaviour in respect of requirement for 32 bit vs 64 bit. If it broke now, it should have broke before as it has always behave same for 10.5 and didn't change in a patch revision.
The only reason this may not be the case, is if you followed instructions as documented in:
http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX
and thinned your Apache executable so only ran as 32 bit, or updated its plist file to similarly run as 32 bit.
This is because some of the 10.5 patch revisions replace the Apache executable and possibly the plist file and so your local change would have been overridden.
That documentation does note that you may have to reapply those changes after an upgrade of operating system.
|
apache + mod_wsgi + aspell-python on OS X 10.5.8
|
I have a website that processes user submitted documents in a variety of ways, one of which is to do a spell check on a part of each document. When I set this website up on a Mac Mini (yes, I realize that's a pretty weak piece of equipment for a website, but it's internal and no one outside the office sees it), I remember having some trouble getting aspell-python to play nice with an install of Aspell when being invoked from Apache, but foolishly forgot to write down how I got around it. I'm under the impression that it had something to do with Apache, Python, and Aspell being compiled to run under different bit modes (64 for Apache, 32 for Python and Aspell, maybe).
In any case, I'm using the stock Apache and Python installs, and have built Aspell from source as well as installed it from MacPorts. It's been happily chugging along for about a year, but...
Fast forward to today: I ran OS X's software update (now I'm up to 10.5.8) and suddenly my spell checker stopped working. Currently, the message that's being thrown up by Django is that "no suitable image was found" by aspell-python, specifically that there is "no matching architecture in the universal wrapper".
Aspell and aspell-python continue to work fine from the command line, but not through the website. Does anyone have any thoughts?
Edit: Using 10.5.8 now, also, my psycopg2 bindings have stopped working. Both aspell and psycopg2 were being used as shared objects, if that's any help.
|
[
"If your upgrade was only from one patch revision of 10.5 to later patch revision of 10.5, then you shouldn't have seen any change in behaviour in respect of requirement for 32 bit vs 64 bit. If it broke now, it should have broke before as it has always behave same for 10.5 and didn't change in a patch revision.\nThe only reason this may not be the case, is if you followed instructions as documented in:\nhttp://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX\nand thinned your Apache executable so only ran as 32 bit, or updated its plist file to similarly run as 32 bit.\nThis is because some of the 10.5 patch revisions replace the Apache executable and possibly the plist file and so your local change would have been overridden.\nThat documentation does note that you may have to reapply those changes after an upgrade of operating system.\n"
] |
[
1
] |
[] |
[] |
[
"apache",
"aspell",
"django",
"mod_wsgi",
"python"
] |
stackoverflow_0001925425_apache_aspell_django_mod_wsgi_python.txt
|
Q:
How can I do python/ruby/javascript style generators in actionscript?
I want to use coroutines in actionscript to implement a state machine.
I'd like to be able to do something like the following
function stateMachine():void
{
sendBytes(0xFFFF);
var receiveBytes:ByteArray = yield()
sendBytes(receiveBytes);
}
stateMachine.send( Socket.read() )
like in this blog entry
A:
As far as I know, Actionscript doesn't have coroutines, continuations or anything that will give you the relevant behavior (call a function without pushing a stack frame). You can fake it using static variables and a switch, but that defeats the purpose of using coroutines for state machines. Also, without tail calls (still only a proposal for ECMASCRIPT, as far as I know), faked coroutines won't use constant stack space as real coroutines do.
Regarding your sample code, coroutines generally need to loop to be useful.
A:
Well, how about this?
function stateMachine(socket:Socket, target:YourReceiverClass):void
{
target.sendBytes(0xFFFF);
var receiveByte:int = socket.readByte();
target.sendBytes(receiveByte);
}
stateMachine( mySocket )
|
How can I do python/ruby/javascript style generators in actionscript?
|
I want to use coroutines in actionscript to implement a state machine.
I'd like to be able to do something like the following
function stateMachine():void
{
sendBytes(0xFFFF);
var receiveBytes:ByteArray = yield()
sendBytes(receiveBytes);
}
stateMachine.send( Socket.read() )
like in this blog entry
|
[
"As far as I know, Actionscript doesn't have coroutines, continuations or anything that will give you the relevant behavior (call a function without pushing a stack frame). You can fake it using static variables and a switch, but that defeats the purpose of using coroutines for state machines. Also, without tail calls (still only a proposal for ECMASCRIPT, as far as I know), faked coroutines won't use constant stack space as real coroutines do.\nRegarding your sample code, coroutines generally need to loop to be useful.\n",
"Well, how about this?\nfunction stateMachine(socket:Socket, target:YourReceiverClass):void\n{\n target.sendBytes(0xFFFF);\n var receiveByte:int = socket.readByte();\n target.sendBytes(receiveByte);\n}\n\nstateMachine( mySocket )\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"actionscript",
"coroutine",
"generator",
"python"
] |
stackoverflow_0001918817_actionscript_coroutine_generator_python.txt
|
Q:
Handling an exception in another thread
What is the "correct" way of detecting and handling an exception in another thread in Python, when the code in that other thread is not under your control?
For instance, say you set a function that requires 2 parameters as the target of the threading.Thread object, but at runtime attempt to pass it 3. The Thread module will throw an exception on another thread before you can even attempt to catch it.
Sample code:
def foo(p1,p2):
p1.do_something()
p2.do_something()
thread = threading.Thread(target=foo,args=(a,b,c))
thread.start()
Throws an exception on a different thread. How would you detect and handle that?
A:
I think you can only decorate your target function or subclass threading.Thread to take care of exceptions.
def safer( func ):
def safer(*args,**kwargs):
try:
return func(*args,**kwargs)
except Exception,e:
print "Couldn't call", func
# do_stuff( e )
return safer
thread = threading.Thread(target=safer(foo),args=(1,2,3))
|
Handling an exception in another thread
|
What is the "correct" way of detecting and handling an exception in another thread in Python, when the code in that other thread is not under your control?
For instance, say you set a function that requires 2 parameters as the target of the threading.Thread object, but at runtime attempt to pass it 3. The Thread module will throw an exception on another thread before you can even attempt to catch it.
Sample code:
def foo(p1,p2):
p1.do_something()
p2.do_something()
thread = threading.Thread(target=foo,args=(a,b,c))
thread.start()
Throws an exception on a different thread. How would you detect and handle that?
|
[
"I think you can only decorate your target function or subclass threading.Thread to take care of exceptions. \ndef safer( func ):\n def safer(*args,**kwargs):\n try:\n return func(*args,**kwargs)\n except Exception,e:\n print \"Couldn't call\", func\n # do_stuff( e )\n return safer\n\n\nthread = threading.Thread(target=safer(foo),args=(1,2,3))\n\n"
] |
[
3
] |
[] |
[] |
[
"exception",
"multithreading",
"python"
] |
stackoverflow_0001925635_exception_multithreading_python.txt
|
Q:
Python programming on Eclipse with Pydev
I need major help getting started! I managed to create a new project, and add python.exe as the interpreter. But when the project is created it's blank. How do I start programming? Ugh.
A:
Create PyDev project
Add "Source Folder" under the project
Add "Modules" to the "Source Folder"
Get coding :-)
A:
Open a new text file and start writing code?
A:
You need to make sure you create a Pydev project. If you don't already have a Python interpreter installed, you'll need to get one (this is mainly a problem on Windows, ActiveState is a great commercial grade distribution, python.org also has some great free builds of Python.) Once this is complete, you'll need to get into your global Pydev preferences (not the preferences for your specific project, but for all Pydev projects) and select the interpreter of your choice. Pydev will automatically scan the libraries included with your interpreter distribution and make them available for code completion. Then, you'll need to create a source file in the 'src' folder that contains code. Run it by choosing a run configuration that matches up with your interpreter choice (regular old Python in your case, not Iron python or Jpython). Most entry point python modules will have a main function like in C/C++ that looks like this: What does if __name__ == "__main__": do?
|
Python programming on Eclipse with Pydev
|
I need major help getting started! I managed to create a new project, and add python.exe as the interpreter. But when the project is created it's blank. How do I start programming? Ugh.
|
[
"\nCreate PyDev project\nAdd \"Source Folder\" under the project\nAdd \"Modules\" to the \"Source Folder\"\nGet coding :-)\n\n",
"Open a new text file and start writing code?\n",
"You need to make sure you create a Pydev project. If you don't already have a Python interpreter installed, you'll need to get one (this is mainly a problem on Windows, ActiveState is a great commercial grade distribution, python.org also has some great free builds of Python.) Once this is complete, you'll need to get into your global Pydev preferences (not the preferences for your specific project, but for all Pydev projects) and select the interpreter of your choice. Pydev will automatically scan the libraries included with your interpreter distribution and make them available for code completion. Then, you'll need to create a source file in the 'src' folder that contains code. Run it by choosing a run configuration that matches up with your interpreter choice (regular old Python in your case, not Iron python or Jpython). Most entry point python modules will have a main function like in C/C++ that looks like this: What does if __name__ == \"__main__\": do?\n"
] |
[
4,
2,
1
] |
[] |
[] |
[
"eclipse",
"ide",
"pydev",
"python"
] |
stackoverflow_0001925750_eclipse_ide_pydev_python.txt
|
Q:
Read a formatted date in Python 2.3?
I had never worked with the datetime module in Python 2.3, and I have a very silly problem. I need to read a date in the format
'10-JUL-2010'
then subtract a day (I would use timedelta), and return the string
'09-JUL-2010 00:00:00 ET'
of course, this is for hundreds of dates. While it should be trivial, I cannot find the info on how to read formatted dates in Python 2.3! Help!
Edit
I am able to retrieve the formatted date as a tuple, but it will not accept the timedelta object for subtraction! Still working on it...
** Edit **
Finally... thanks to your help I was able to solve the problem as follows:
print (datetime(*(time.strptime(date_string, format)[0:6])).strftime('%d-%b-%Y')).upper()+'00:00:00 ET'
A:
You're looking for datetime.datetime.strptime(), but the documentation is awful for that function, it's effectively the reverse operation of datetime.datetime.strftime().
The format string you're looking for is: '%d-%b-%Y'
See: http://www.python.org/doc/2.3.5/lib/node211.html and http://www.python.org/doc/2.3.5/lib/datetime-datetime.html and http://www.python.org/doc/2.3.5/lib/module-time.html
Edit: Oh snap! There is no strptime in the datetime module in python 2.3. It's in the time module, you'll have to use that one instead.
A:
Well, there is no builtin for that in 2.3, only from 2.5 on. But for that one format you can parse it by hand ...
months = { 'JAN' : 1, 'FEB' : 2, ... } # write that yourself :p
day,mon,year = thedate.split('-')
day = int(day)
mon = months[mon]
year = int(year)
parsed = datetime.datetime(day=day, month=month, year=year)
A:
If strptime() is not working out for you there is also the option of brute forcing it with a regex:
import re
import date
timestamp_regex = re.compile(r"(\d\d)-(\w\w\w)-(\d\d\d\d)")
# month_mapping: a mapping for 3 letter months to integers
d1 = datetime.date(int(match.group(3)), #year
month_mapping[match.group(2)],#month
int(match.group(1))) #day
|
Read a formatted date in Python 2.3?
|
I had never worked with the datetime module in Python 2.3, and I have a very silly problem. I need to read a date in the format
'10-JUL-2010'
then subtract a day (I would use timedelta), and return the string
'09-JUL-2010 00:00:00 ET'
of course, this is for hundreds of dates. While it should be trivial, I cannot find the info on how to read formatted dates in Python 2.3! Help!
Edit
I am able to retrieve the formatted date as a tuple, but it will not accept the timedelta object for subtraction! Still working on it...
** Edit **
Finally... thanks to your help I was able to solve the problem as follows:
print (datetime(*(time.strptime(date_string, format)[0:6])).strftime('%d-%b-%Y')).upper()+'00:00:00 ET'
|
[
"You're looking for datetime.datetime.strptime(), but the documentation is awful for that function, it's effectively the reverse operation of datetime.datetime.strftime().\nThe format string you're looking for is: '%d-%b-%Y'\nSee: http://www.python.org/doc/2.3.5/lib/node211.html and http://www.python.org/doc/2.3.5/lib/datetime-datetime.html and http://www.python.org/doc/2.3.5/lib/module-time.html\nEdit: Oh snap! There is no strptime in the datetime module in python 2.3. It's in the time module, you'll have to use that one instead.\n",
"Well, there is no builtin for that in 2.3, only from 2.5 on. But for that one format you can parse it by hand ...\nmonths = { 'JAN' : 1, 'FEB' : 2, ... } # write that yourself :p\nday,mon,year = thedate.split('-')\nday = int(day)\nmon = months[mon]\nyear = int(year)\nparsed = datetime.datetime(day=day, month=month, year=year)\n\n",
"If strptime() is not working out for you there is also the option of brute forcing it with a regex:\nimport re\nimport date\ntimestamp_regex = re.compile(r\"(\\d\\d)-(\\w\\w\\w)-(\\d\\d\\d\\d)\")\n# month_mapping: a mapping for 3 letter months to integers\nd1 = datetime.date(int(match.group(3)), #year\n month_mapping[match.group(2)],#month\n int(match.group(1))) #day\n\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0001925678_datetime_python.txt
|
Q:
Eclipse (with Pydev) keeps throwing SyntaxError
My code:
print "Hello World!"
I even tried adding a semicolon behind, but everytime I save and run (as Python run) it says:
File "E:\Software\Eclipse\Workspace\Python1\src\main.py", line 1
print "Hello World!";
SyntaxError: invalid syntax
I have no idea why.
A:
What version of Python are you using? Python 2.X has print as a keyword, but Python 3.X only has print() as a function - you'd need to use print("Hello, World!") instead.
A:
This is kind of a longshot but - if you're running python 3.0 that is invalid syntax. Try
print("Hello World!")
to see if this is the case.
A:
In Python, indentation is really important... Have you check your indentation? Also, lose the ; (don't need it).
correct:
print("hello") or print "hello" (for < 3.0)
not correct:
...print("hello") or print "hello" (for < 3.0)
where . denotes spaces.
|
Eclipse (with Pydev) keeps throwing SyntaxError
|
My code:
print "Hello World!"
I even tried adding a semicolon behind, but everytime I save and run (as Python run) it says:
File "E:\Software\Eclipse\Workspace\Python1\src\main.py", line 1
print "Hello World!";
SyntaxError: invalid syntax
I have no idea why.
|
[
"What version of Python are you using? Python 2.X has print as a keyword, but Python 3.X only has print() as a function - you'd need to use print(\"Hello, World!\") instead.\n",
"This is kind of a longshot but - if you're running python 3.0 that is invalid syntax. Try \nprint(\"Hello World!\") \n\nto see if this is the case.\n",
"In Python, indentation is really important... Have you check your indentation? Also, lose the ; (don't need it).\ncorrect:\nprint(\"hello\") or print \"hello\" (for < 3.0)\nnot correct:\n...print(\"hello\") or print \"hello\" (for < 3.0)\nwhere . denotes spaces.\n"
] |
[
35,
4,
1
] |
[] |
[] |
[
"eclipse",
"pydev",
"python",
"syntax"
] |
stackoverflow_0001925852_eclipse_pydev_python_syntax.txt
|
Q:
Specifying chars in python
I need a functions that iterates over all the lines in the file.
Here's what I have so far:
def LineFeed(file):
ret = ""
for byte in file:
ret = ret + str(byte)
if str(byte) == '\r':
yield ret
ret = ""
All the lines in the file end with \r (not \n), and I'm reading it in "rb" mode, (I have to read this file in binary).
The yield doesn't work and returns nothing. Maybe there's a problem with the comparison?
I'm just not sure how you represent a byte/char in python.
I'm getting the idea that if you for loop on a "rb" file it still tries to iterate over lines not bytes..., How can I iterate over bytes?
My problem is that I don't have standard line endings. Also my file is filled with 0x00 bytes and I would like to get rid of them all, so I think I would need a second yield function, how could I implement that, I just don't know how to represent the 0x00 byte in python or the NULL char.
A:
I think that you are confused with what "for x in file" does. Assuming you got your handle like "file = open(file_name)", byte in this case will be an entire line, not a single character. So you are only calling yield when the entire line consists of a single carriage return. Try changing "byte" to "line" and iterating over that with a second loop.
A:
Perhaps if you were to explain what this file represents, why it has lots of '\x00', why you think you need to read it in binary mode, we could help you with your underlying problem.
Otherwise, try the following code; it avoids any dependence on (or interference from) your operating system's line-ending convention.
lines = open("the_file", "rb").read().split("\r")
for line in lines:
process(line)
Edit: the ASCII NUL (not "NULL") byte is "\x00".
A:
If you're in control of how you open the file, I'd recommend opening it with universal newlines, since \r isn't recognized as a linefeed character if you just use 'rb' mode, but it is if you use 'Urb'.
This will only work if you aren't including \n as well as \r in your binary file somewhere, since the distinction between \r and \n is lost when using universal newlines.
Assuming you want your yielded lines to still be \r terminated:
NUL = '\x00'
def lines_without_nulls(path):
with open(path, 'Urb') as f:
for line in f:
yield line.replace(NUL, '').replace('\n', '\r')
A:
Edit:
string1 += string2 string concatenation is slow. Try joining a list of strings.
ddaa is right--You shouldn't need the struct package if the binary file only contains ASCII. Also, my generator returns the string after the final '\r', before EOF. With these two minor fixes, my code is suspiciously similar (practically identical) to this more recent answer.
Code snip:
def LineFeed(f):
ret = []
while True:
oneByte = f.read(1)
if not oneByte: break
# Return everything up to, but not including the carriage return
if oneByte == '\r':
yield ''.join(ret)
ret = []
else:
ret.append(oneByte)
if oneByte:
yield ''.join(ret)
if __name__ == '__main__':
lf = LineFeed( open('filename','rb') )
for something in lf:
doSomething(something)
A:
So, your problem is iterating over the lines of a file open in binary mode that use '\r' as a line separator. Since the file is in binary mode, you cannot use the universal newline feature, and it turns out that '\r' is not interpreted as a line separator in binary mode.
Reading a file char by char is a terribly inefficient thing to do in Python, but here's how you could iterate over your lines:
def cr_lines(the_file):
line = []
while True:
byte = the_file.read(1)
if not byte:
break
line.append(byte)
if byte == '\r':
yield ''.join(line)
line = []
if line:
yield ''.join(line)
To be more efficient, you would need to read bigger chunks of text and handle buffering in your iterator. Keeping in mind that you could get strange bugs if seeking while iterating. Preventing those bugs would require a subclass of file so you can purge the buffer on seek.
Note the use of the ''.join(line) idiom. Accumulating a string with += has terrible performance and is common mistake made by beginning programmers.
|
Specifying chars in python
|
I need a functions that iterates over all the lines in the file.
Here's what I have so far:
def LineFeed(file):
ret = ""
for byte in file:
ret = ret + str(byte)
if str(byte) == '\r':
yield ret
ret = ""
All the lines in the file end with \r (not \n), and I'm reading it in "rb" mode, (I have to read this file in binary).
The yield doesn't work and returns nothing. Maybe there's a problem with the comparison?
I'm just not sure how you represent a byte/char in python.
I'm getting the idea that if you for loop on a "rb" file it still tries to iterate over lines not bytes..., How can I iterate over bytes?
My problem is that I don't have standard line endings. Also my file is filled with 0x00 bytes and I would like to get rid of them all, so I think I would need a second yield function, how could I implement that, I just don't know how to represent the 0x00 byte in python or the NULL char.
|
[
"I think that you are confused with what \"for x in file\" does. Assuming you got your handle like \"file = open(file_name)\", byte in this case will be an entire line, not a single character. So you are only calling yield when the entire line consists of a single carriage return. Try changing \"byte\" to \"line\" and iterating over that with a second loop.\n",
"Perhaps if you were to explain what this file represents, why it has lots of '\\x00', why you think you need to read it in binary mode, we could help you with your underlying problem.\nOtherwise, try the following code; it avoids any dependence on (or interference from) your operating system's line-ending convention.\nlines = open(\"the_file\", \"rb\").read().split(\"\\r\")\nfor line in lines:\n process(line)\n\nEdit: the ASCII NUL (not \"NULL\") byte is \"\\x00\".\n",
"If you're in control of how you open the file, I'd recommend opening it with universal newlines, since \\r isn't recognized as a linefeed character if you just use 'rb' mode, but it is if you use 'Urb'.\nThis will only work if you aren't including \\n as well as \\r in your binary file somewhere, since the distinction between \\r and \\n is lost when using universal newlines.\nAssuming you want your yielded lines to still be \\r terminated:\nNUL = '\\x00'\ndef lines_without_nulls(path):\n with open(path, 'Urb') as f:\n for line in f:\n yield line.replace(NUL, '').replace('\\n', '\\r')\n\n",
"Edit: \n\nstring1 += string2 string concatenation is slow. Try joining a list of strings.\nddaa is right--You shouldn't need the struct package if the binary file only contains ASCII. Also, my generator returns the string after the final '\\r', before EOF. With these two minor fixes, my code is suspiciously similar (practically identical) to this more recent answer.\n\nCode snip:\ndef LineFeed(f):\n ret = []\n while True:\n oneByte = f.read(1)\n if not oneByte: break\n # Return everything up to, but not including the carriage return\n if oneByte == '\\r':\n yield ''.join(ret)\n ret = []\n else:\n ret.append(oneByte)\n if oneByte:\n yield ''.join(ret)\nif __name__ == '__main__':\n lf = LineFeed( open('filename','rb') )\n\n for something in lf:\n doSomething(something)\n\n",
"So, your problem is iterating over the lines of a file open in binary mode that use '\\r' as a line separator. Since the file is in binary mode, you cannot use the universal newline feature, and it turns out that '\\r' is not interpreted as a line separator in binary mode.\nReading a file char by char is a terribly inefficient thing to do in Python, but here's how you could iterate over your lines:\ndef cr_lines(the_file):\n line = []\n while True:\n byte = the_file.read(1)\n if not byte:\n break\n line.append(byte)\n if byte == '\\r':\n yield ''.join(line)\n line = []\n if line:\n yield ''.join(line)\n\nTo be more efficient, you would need to read bigger chunks of text and handle buffering in your iterator. Keeping in mind that you could get strange bugs if seeking while iterating. Preventing those bugs would require a subclass of file so you can purge the buffer on seek.\nNote the use of the ''.join(line) idiom. Accumulating a string with += has terrible performance and is common mistake made by beginning programmers.\n"
] |
[
2,
2,
1,
0,
0
] |
[] |
[] |
[
"binaryfiles",
"python"
] |
stackoverflow_0001925043_binaryfiles_python.txt
|
Q:
this python script can be shortened/optimized, how?
I'm not used to doing things the python way yet, but I'm almost certain the following script can be condensed. I'm not looking for speed optimization here, I'm looking for more readable code. Make it slower for all I care, but what are some ways to make this look more Python-esque.
I'm simply reading in a csv file filled with zipcodes and populating a database with 23 columns. Lots of typing. I also don't like hard coding things like the index of the row. Also, multis = '%s, '*23 followed by multis = multis[:-2] feels dirty.
Looking forward to see what some of you can come up with.
#!/usr/bin/python
import csv
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", db="test")
c = db.cursor()
f_csv = 'zip-codes-database-STANDARD.csv'
csvReader = csv.reader(open(f_csv))
ziplist = []
multis = '%s, '*23
multis = multis[:-2]
for row in csvReader:
c.execute("""INSERT INTO lock_zipcodes_complete
(`zipcode`, `city`, `state`, `county`, `areacode`,
`citytype`, `city_alias_abbreviation`,
`city_alias_name`, `latitude`, `longitude`, `timezone`,
`elevation`, `county_fips`, `dst`,
`preferred_last_line_key`, `classification_code`,
`multicounty`, `state_fips`, `city_state_key`,
`city_alias_code`, `primary_record`, `city_mixed_case`,
`city_alias_mixed_case`) VALUES(""" + multis + ')',
(row[0], row[1], row[2], row[3], row[4], row[5], row[6],
row[7], row[8], row[9], row[10], row[11], row[12],
row[13], row[14], row[15], row[16], row[17], row[18],
row[19], row[20], row[21], row[22]))
A:
This part:
multis = '%s, '*23
multis = multis[:-2]
should be
multis = ', '.join(['%s'] * 23)
ziplist is not used, so you can just remove the line that sets it.
(row[0], row[1], row[2], row[3], row[4], row[5], row[6],
row[7], row[8], row[9], row[10], row[11], row[12],
row[13], row[14], row[15], row[16], row[17], row[18],
row[19], row[20], row[21], row[22])
should be just tuple(row) (for the specific way you're using it, just row will do).
The explicit list of column names in the INSERT is unpleasant, but needed if you're unsure whether that's all columns in that DB table or whether the order is right (or, of course, if you're sure that either is not the case); but that's a SQL - vs - CSV "impedence mismatch" issue rather that a Python one;-).
The whole loop:
for row in csvReader:
c.execute(sql_statement, row)
can, optionally, further be compacted to:
c.executemany(sql_statement, csvReader)
A:
Please do not build SQL text like that. Please do not. Please.
First. The variable ziplist is not used. Delete it.
Second. Use real SQL binding.
c.execute( "INSERT...", row )
This is documented in the MySQLdb interface. http://mysql-python.sourceforge.net/MySQLdb-1.2.2/.
|
this python script can be shortened/optimized, how?
|
I'm not used to doing things the python way yet, but I'm almost certain the following script can be condensed. I'm not looking for speed optimization here, I'm looking for more readable code. Make it slower for all I care, but what are some ways to make this look more Python-esque.
I'm simply reading in a csv file filled with zipcodes and populating a database with 23 columns. Lots of typing. I also don't like hard coding things like the index of the row. Also, multis = '%s, '*23 followed by multis = multis[:-2] feels dirty.
Looking forward to see what some of you can come up with.
#!/usr/bin/python
import csv
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", db="test")
c = db.cursor()
f_csv = 'zip-codes-database-STANDARD.csv'
csvReader = csv.reader(open(f_csv))
ziplist = []
multis = '%s, '*23
multis = multis[:-2]
for row in csvReader:
c.execute("""INSERT INTO lock_zipcodes_complete
(`zipcode`, `city`, `state`, `county`, `areacode`,
`citytype`, `city_alias_abbreviation`,
`city_alias_name`, `latitude`, `longitude`, `timezone`,
`elevation`, `county_fips`, `dst`,
`preferred_last_line_key`, `classification_code`,
`multicounty`, `state_fips`, `city_state_key`,
`city_alias_code`, `primary_record`, `city_mixed_case`,
`city_alias_mixed_case`) VALUES(""" + multis + ')',
(row[0], row[1], row[2], row[3], row[4], row[5], row[6],
row[7], row[8], row[9], row[10], row[11], row[12],
row[13], row[14], row[15], row[16], row[17], row[18],
row[19], row[20], row[21], row[22]))
|
[
"This part:\nmultis = '%s, '*23\nmultis = multis[:-2]\n\nshould be\nmultis = ', '.join(['%s'] * 23)\n\nziplist is not used, so you can just remove the line that sets it.\n (row[0], row[1], row[2], row[3], row[4], row[5], row[6],\n row[7], row[8], row[9], row[10], row[11], row[12],\n row[13], row[14], row[15], row[16], row[17], row[18],\n row[19], row[20], row[21], row[22])\n\nshould be just tuple(row) (for the specific way you're using it, just row will do).\nThe explicit list of column names in the INSERT is unpleasant, but needed if you're unsure whether that's all columns in that DB table or whether the order is right (or, of course, if you're sure that either is not the case); but that's a SQL - vs - CSV \"impedence mismatch\" issue rather that a Python one;-).\nThe whole loop:\nfor row in csvReader:\n c.execute(sql_statement, row)\n\ncan, optionally, further be compacted to:\nc.executemany(sql_statement, csvReader)\n\n",
"Please do not build SQL text like that. Please do not. Please.\nFirst. The variable ziplist is not used. Delete it.\nSecond. Use real SQL binding.\nc.execute( \"INSERT...\", row )\n\nThis is documented in the MySQLdb interface. http://mysql-python.sourceforge.net/MySQLdb-1.2.2/.\n"
] |
[
7,
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001925999_python.txt
|
Q:
How to get the LAN IP that a socket is sending (linux)
I need some code to get the address of the socket i just created (to filter out packets originating from localhost on a multicast network)
this:
socket.gethostbyname(socket.gethostname())
works on mac but it returns only the localhost IP in linux... is there anyway to get the LAN address
thanks
--edit--
is it possible to get it from the socket settings itself, like, the OS has to select a LAN IP to send on... can i play on getsockopt(... IP_MULTICAST_IF...) i dont know exactly how to use this though...?
--- edit ---
SOLVED!
send_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
putting this on the send socket eliminated packet echos to the host sending them, which eliminates the need for the program to know which IP the OS has selected to send.
yay!
A:
Looks like you're looking for the getsockname method of socket objects.
A:
quick answer - socket.getpeername() (provided that socket is a socket object, not a module)
(playing around in python/ipython/idle/... interactive shell is very helpful)
.. or if I read you question carefully, maybe socket.getsockname() :)
|
How to get the LAN IP that a socket is sending (linux)
|
I need some code to get the address of the socket i just created (to filter out packets originating from localhost on a multicast network)
this:
socket.gethostbyname(socket.gethostname())
works on mac but it returns only the localhost IP in linux... is there anyway to get the LAN address
thanks
--edit--
is it possible to get it from the socket settings itself, like, the OS has to select a LAN IP to send on... can i play on getsockopt(... IP_MULTICAST_IF...) i dont know exactly how to use this though...?
--- edit ---
SOLVED!
send_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
putting this on the send socket eliminated packet echos to the host sending them, which eliminates the need for the program to know which IP the OS has selected to send.
yay!
|
[
"Looks like you're looking for the getsockname method of socket objects.\n",
"quick answer - socket.getpeername() (provided that socket is a socket object, not a module)\n(playing around in python/ipython/idle/... interactive shell is very helpful)\n.. or if I read you question carefully, maybe socket.getsockname() :)\n"
] |
[
1,
0
] |
[] |
[] |
[
"ip_address",
"python",
"sockets"
] |
stackoverflow_0001925974_ip_address_python_sockets.txt
|
Q:
Transitioning from desktop app written in C++ to a web-based app
We have a mature Windows desktop application written in C++. The application's GUI sits on top of a windows DLL that does most of the work for the GUI (it's kind of the engine). It, too, is written in C++. We are considering transitioning the Windows app to be a web-based app for various reasons.
What I would like to avoid is having to writing the CGI for this web-based app in C++. That is, I would rather have the power of a 4G language like Python or a .NET language for creating the web-based version of this app.
So, the question is: given that I need to use a C++ DLL on the backend to do the work of the app what technology stack would you recommend for sitting between the user's browser and are C++ dll? We can assume that the web server will be Windows.
Some options:
Write a COM layer on top of the windows DLL which can then be access via .NET and use ASP.NET for the UI
Access the export DLL interface directly from .NET and use ASP.NET for the UI.
Write a custom Python library that wraps the windows DLL so that the rest of the code can be written.
Write the CGI using C++ and a C++-based MVC framework like Wt
Concerns:
I would rather not use C++ for the web framework if it can be avoided - I think languages like Python and C# are simply more powerful and efficient in terms of development time.
I'm concerned that my mixing managed and unmanaged code with one of the .NET solutions I'm asking for lots of little problems that are hard to debug (purely anecdotal evidence for that)
Same is true for using a Python layer. Anything that's slightly off the beaten path like that worries me in that I don't have much evidence one way or the other if this is a viable long term solution.
A:
See also Can a huge existing
application be ported to the web?
How?
Sorry there are no good solutions, just less bad ones....
Firstly as you already develop for windows I am assuming that you are used to using the Microsoft development tools, I would not give the same answer for a desktop application that is coming from unix (or Mac).
Some random thoughts and pointers.
I would make use of Asp.net most likely Aps.net MVC.
I would try to wrap in C++ classes in some nice high level .net class, maybe using Managed C++ / CLI.
Using COM is likely to be a lot of work on the C++ side and does not make the .NET easy, so I would avoid COM in favour of managed C++ or pinvoke (However if you are allready using COM on the C++ side, this it is an option, provided you are using the subset of COM that VB6 could cope with).
.NET can't access none managed C++ object, but it can access simple C function using Pinvoke, so whatever you do some sort of bridging layer will be needed on the C++ site.
See if you can use Silverlight rather than the web, if you are able to (install issues etc) it will save you a lot of development time. (And lets you target Microsoft Phones as well)
Check that the business case for a “port to the web” is very strong and it will take a lot longer then you think!, Is hosting with terminal server etc an option for your customers?
Think about threading and multi user access, e.g. does your dll assume it is only being used by one user?
Just because you are working on a new web version, you will still get customers demanding changes to the desktop version even after you have shipped the web version. I have found in the past that current customers don’t always wish to move to a web app.
(Sorry I don’t know match about Python, however if you don’t already have skills in it I would say stick on the Microsoft stack as you already know the Microsoft debugger etc)
(I think of porting complex applications to the web as a very big pain, it is best to avoid pain when possible however sometimes you are given no option and just have to minimize the pain. If you have never worked on large applications that are in the process (normally many years work) of being ported to the web, you just don’t know what you are letting yourself in for!)
A:
3- Python is the solution.
Make a sigle entry point interface in python that takes only the name of the function and a list of params to pass to the function itself. You will have something to start experimenting straight away and see which functions of the DLL are really needed for the first functional web prototype.
A stub for a single functions module is
#include <Python.h>
#include <string.h>
int int_function(int a){
return a +=1;
}
static PyObject *
exec_lib(PyObject *self, PyObject *args)
{
char *fun_name;
PyObject *func_name = PyTuple_GetSlice(args, 0,1);
PyObject *res;
if (!PyArg_ParseTuple(func_name, "s", &fun_name))
return NULL;
Py_DECREF(func_name);
if (strncmp("int_function", fun_name, 1024) == 0)
{
int i;
PyObject *fun_args = PyTuple_GetSlice(args, 1,20);
if (!PyArg_ParseTuple(fun_args, "i", &i))
return NULL;
Py_DECREF(fun_args);
res = Py_BuildValue( "i", int_function(i));
} else {
Py_INCREF(Py_None);
res = Py_None;
}
return res;
}
PyMethodDef methods[] = {
{"exec_lib", exec_lib, METH_VARARGS, " Returns"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
initlibwrap()
{
(void) Py_InitModule("libwrap", methods);
}
can be compiled with a setup.py file
from distutils.core import setup, Extension
setup(name = "libwrap",
version = "1.0",
ext_modules = [Extension("libwrap", ["my_library_wrap.cpp"])])
and used in a simple web server like
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import libwrap
def int_function(value):
return libwrap.exec_lib("int_function", value)
print int_function(10)
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
value = 'Error'
try:
value = int_function()
except:
import traceback
traceback.print_stack()
self.wfile.write(value)
def main():
try:
ip ='localhost'
port = 8080
server = HTTPServer((ip,port), MyHandler)
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
if __name__ == '__main__':
main()
A:
I would say option 2 is the way to go. Provided that you create an interface in .Net to your DLL to make sure you correctly release your memory etc. when needed I don't see an issue. If you can reuse your business logic in your DLL and basically make a web call into your DLL then great.
My only concern would be your DLL's API. ASP.Net is obviously a multiple user multi-threaded application. Has your API been designed to take this, given that most windows forms apps will only have one user driving them (imagine if every form in your app could be opened by more than one user all at the same time).
A:
Since nobody has mentioned it, how about Wt.
If you are not looking for a explorer-based UI, there are many C++ libraries for you to extend a local app to web-based app, POCO is one of them. If you are sticking to Windows platform, WWSAPI , is really cool for C/C++ developers.
|
Transitioning from desktop app written in C++ to a web-based app
|
We have a mature Windows desktop application written in C++. The application's GUI sits on top of a windows DLL that does most of the work for the GUI (it's kind of the engine). It, too, is written in C++. We are considering transitioning the Windows app to be a web-based app for various reasons.
What I would like to avoid is having to writing the CGI for this web-based app in C++. That is, I would rather have the power of a 4G language like Python or a .NET language for creating the web-based version of this app.
So, the question is: given that I need to use a C++ DLL on the backend to do the work of the app what technology stack would you recommend for sitting between the user's browser and are C++ dll? We can assume that the web server will be Windows.
Some options:
Write a COM layer on top of the windows DLL which can then be access via .NET and use ASP.NET for the UI
Access the export DLL interface directly from .NET and use ASP.NET for the UI.
Write a custom Python library that wraps the windows DLL so that the rest of the code can be written.
Write the CGI using C++ and a C++-based MVC framework like Wt
Concerns:
I would rather not use C++ for the web framework if it can be avoided - I think languages like Python and C# are simply more powerful and efficient in terms of development time.
I'm concerned that my mixing managed and unmanaged code with one of the .NET solutions I'm asking for lots of little problems that are hard to debug (purely anecdotal evidence for that)
Same is true for using a Python layer. Anything that's slightly off the beaten path like that worries me in that I don't have much evidence one way or the other if this is a viable long term solution.
|
[
"\nSee also Can a huge existing\n application be ported to the web?\n How?\n\nSorry there are no good solutions, just less bad ones....\nFirstly as you already develop for windows I am assuming that you are used to using the Microsoft development tools, I would not give the same answer for a desktop application that is coming from unix (or Mac).\nSome random thoughts and pointers.\n\nI would make use of Asp.net most likely Aps.net MVC.\nI would try to wrap in C++ classes in some nice high level .net class, maybe using Managed C++ / CLI.\nUsing COM is likely to be a lot of work on the C++ side and does not make the .NET easy, so I would avoid COM in favour of managed C++ or pinvoke (However if you are allready using COM on the C++ side, this it is an option, provided you are using the subset of COM that VB6 could cope with).\n.NET can't access none managed C++ object, but it can access simple C function using Pinvoke, so whatever you do some sort of bridging layer will be needed on the C++ site.\nSee if you can use Silverlight rather than the web, if you are able to (install issues etc) it will save you a lot of development time. (And lets you target Microsoft Phones as well)\nCheck that the business case for a “port to the web” is very strong and it will take a lot longer then you think!, Is hosting with terminal server etc an option for your customers?\nThink about threading and multi user access, e.g. does your dll assume it is only being used by one user?\nJust because you are working on a new web version, you will still get customers demanding changes to the desktop version even after you have shipped the web version. I have found in the past that current customers don’t always wish to move to a web app.\n\n(Sorry I don’t know match about Python, however if you don’t already have skills in it I would say stick on the Microsoft stack as you already know the Microsoft debugger etc)\n\n(I think of porting complex applications to the web as a very big pain, it is best to avoid pain when possible however sometimes you are given no option and just have to minimize the pain. If you have never worked on large applications that are in the process (normally many years work) of being ported to the web, you just don’t know what you are letting yourself in for!)\n",
"3- Python is the solution.\nMake a sigle entry point interface in python that takes only the name of the function and a list of params to pass to the function itself. You will have something to start experimenting straight away and see which functions of the DLL are really needed for the first functional web prototype.\nA stub for a single functions module is\n#include <Python.h>\n#include <string.h>\n\nint int_function(int a){\n return a +=1;\n}\n\nstatic PyObject *\nexec_lib(PyObject *self, PyObject *args)\n{\n char *fun_name;\n PyObject *func_name = PyTuple_GetSlice(args, 0,1);\n PyObject *res;\n\n if (!PyArg_ParseTuple(func_name, \"s\", &fun_name))\n return NULL;\n Py_DECREF(func_name);\n if (strncmp(\"int_function\", fun_name, 1024) == 0)\n {\n int i;\n PyObject *fun_args = PyTuple_GetSlice(args, 1,20);\n if (!PyArg_ParseTuple(fun_args, \"i\", &i))\n return NULL;\n Py_DECREF(fun_args);\n res = Py_BuildValue( \"i\", int_function(i));\n } else {\n Py_INCREF(Py_None);\n res = Py_None;\n }\n\n return res;\n}\n\n\n\nPyMethodDef methods[] = {\n {\"exec_lib\", exec_lib, METH_VARARGS, \" Returns\"},\n {NULL, NULL, 0, NULL}\n};\n\nPyMODINIT_FUNC \ninitlibwrap()\n{\n (void) Py_InitModule(\"libwrap\", methods);\n}\n\ncan be compiled with a setup.py file\nfrom distutils.core import setup, Extension\n\nsetup(name = \"libwrap\",\n version = \"1.0\",\n ext_modules = [Extension(\"libwrap\", [\"my_library_wrap.cpp\"])])\n\nand used in a simple web server like\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\nimport libwrap\n\n\ndef int_function(value):\n return libwrap.exec_lib(\"int_function\", value)\n\nprint int_function(10)\n\nclass MyHandler(BaseHTTPRequestHandler):\n\n def do_GET(self):\n self.send_response(200)\n value = 'Error'\n try:\n value = int_function()\n except:\n import traceback\n traceback.print_stack()\n self.wfile.write(value)\n\ndef main():\n try:\n ip ='localhost'\n port = 8080\n server = HTTPServer((ip,port), MyHandler)\n server.serve_forever()\n except KeyboardInterrupt:\n server.socket.close()\n\nif __name__ == '__main__':\n main()\n\n",
"I would say option 2 is the way to go. Provided that you create an interface in .Net to your DLL to make sure you correctly release your memory etc. when needed I don't see an issue. If you can reuse your business logic in your DLL and basically make a web call into your DLL then great.\nMy only concern would be your DLL's API. ASP.Net is obviously a multiple user multi-threaded application. Has your API been designed to take this, given that most windows forms apps will only have one user driving them (imagine if every form in your app could be opened by more than one user all at the same time).\n",
"Since nobody has mentioned it, how about Wt. \nIf you are not looking for a explorer-based UI, there are many C++ libraries for you to extend a local app to web-based app, POCO is one of them. If you are sticking to Windows platform, WWSAPI , is really cool for C/C++ developers.\n"
] |
[
10,
4,
2,
1
] |
[] |
[] |
[
"c#",
"c++",
"dll",
"python",
"web_based"
] |
stackoverflow_0001900868_c#_c++_dll_python_web_based.txt
|
Q:
Python programming general questions
I heard that Python is easy and powerful, but I don't know if I'm on the right track to learn it. I learn from online tutorials, I know basic maths calculation and printing strings, but how long will it take to develop something useful? I don't really know the exact uses of Python, though.
A:
I'm not exactly sure what you're looking for, but I think one or more of the following may be the next step you're looking for.
Perhaps you would like to use a variety of different protocols for a networking program, you could check out Twisted.
Or perhaps if you would like to make a web application or blog you can check out Django.
Or perhaps you would like to make a GUI application, you could take a look at TkInter.
Or perhaps you would like to get into game programming, you could take a look at Pygame.
Or perhaps you would like to ... you can take a look at the Python Package Index.
How long will it take? This depends on your programming background in general. The best way is simply to jump into the topic you're interested in and start on a mini project.
A:
Python is a general purpose language. You can use it to make a lot of different things, but it's best suited at stuff that doesn't require a lot of speed, since the high level features have a performance cost.
It's hard to tell how long it will take you to develop something useful. The other day I made a script to help on a small computer administration thing. You could do that with a week or two of experience (or maybe less), depending on your previous programming knowledge and the amount of time you put into studying. However, if you want to make something bigger (maybe an audio player, an IM client, mid-sized stuff like that), you probably need some weeks or months of practice. It depends a lot on the time and energy you invest in programming.
I'd suggest to follow either the official tutorial or Dive Into Python.
In general, it depends on you. Python can be used for simple or complex stuff, and for many different applications. It depends on what you want.
A:
Have a look at Mark Pilgrim's freely available book called Dive Into Python. I think it's a better choice to start with than online tutorials. The best way to learn a language is to start to work on a project. As I read this book, I started to implement a simple image viewer. As I advanced with the book, I could refine the project progressively. Invent something that is interesting to you.
I also suggest you taking notes when you learn a programming language. When you learn something that can be useful later, make some notes with a simple example, e.g. how to read a text file line by line, convert int to str, convert str to int, basic list operations, etc. Later on you can use these building blocks in a larger project.
A:
Like every other programming language In order to learn Python you need to write a program with it.
Find a pet project and use python to code it. I also recommend Dive into python" (like anyone else that answered your question).
A few months ago I've decided to learn IronPython (.NET implementation of python), I'vve started by reading "Dive into python" and a few tutorials and then I've started coding a simple board game using IronPython (you can read about it in my blog).
In order to learn a new programming language you need to use it and then you'll know how and where to use it.
A:
The best way to learn how to do something useful is come up with something useful you want to do. Make sure it's not way out of your league, then do research to accomplish it. That's how a lot of programmers learn languages.
A:
What other programming background do you have? What programming interests do you have -- web apps, numerical / scientific computations, games, ...? Python is good at many different things, for both beginners and experienced programmers, but the most fruitful approach(es) to it do depend on what you already know, and what really interests you!-)
A:
Bram who invented bittorrent with python says python is good for writing protocols in addition to aforementioned webapps, games and general purpose. Compared to Java python solves same problem in less code and less ways in longer development and VM time where Java has more ways solve same problem in more code and faster VM and faster development time.
A:
Making a comparison between Python, and other languages would not help, as there is always somebody who would find a reason to prefer one language instead of another.
If you want a scripting language that is powerful, but that it is easier to read than perl, that doesn't have a curly bracket syntax, and that allows you to learn something about object oriented programming, then Python is the language for you.
|
Python programming general questions
|
I heard that Python is easy and powerful, but I don't know if I'm on the right track to learn it. I learn from online tutorials, I know basic maths calculation and printing strings, but how long will it take to develop something useful? I don't really know the exact uses of Python, though.
|
[
"I'm not exactly sure what you're looking for, but I think one or more of the following may be the next step you're looking for. \nPerhaps you would like to use a variety of different protocols for a networking program, you could check out Twisted. \nOr perhaps if you would like to make a web application or blog you can check out Django.\nOr perhaps you would like to make a GUI application, you could take a look at TkInter. \nOr perhaps you would like to get into game programming, you could take a look at Pygame. \nOr perhaps you would like to ... you can take a look at the Python Package Index. \n\nHow long will it take? This depends on your programming background in general. The best way is simply to jump into the topic you're interested in and start on a mini project. \n",
"Python is a general purpose language. You can use it to make a lot of different things, but it's best suited at stuff that doesn't require a lot of speed, since the high level features have a performance cost.\nIt's hard to tell how long it will take you to develop something useful. The other day I made a script to help on a small computer administration thing. You could do that with a week or two of experience (or maybe less), depending on your previous programming knowledge and the amount of time you put into studying. However, if you want to make something bigger (maybe an audio player, an IM client, mid-sized stuff like that), you probably need some weeks or months of practice. It depends a lot on the time and energy you invest in programming.\nI'd suggest to follow either the official tutorial or Dive Into Python.\nIn general, it depends on you. Python can be used for simple or complex stuff, and for many different applications. It depends on what you want.\n",
"Have a look at Mark Pilgrim's freely available book called Dive Into Python. I think it's a better choice to start with than online tutorials. The best way to learn a language is to start to work on a project. As I read this book, I started to implement a simple image viewer. As I advanced with the book, I could refine the project progressively. Invent something that is interesting to you.\nI also suggest you taking notes when you learn a programming language. When you learn something that can be useful later, make some notes with a simple example, e.g. how to read a text file line by line, convert int to str, convert str to int, basic list operations, etc. Later on you can use these building blocks in a larger project.\n",
"Like every other programming language In order to learn Python you need to write a program with it.\nFind a pet project and use python to code it. I also recommend Dive into python\" (like anyone else that answered your question).\nA few months ago I've decided to learn IronPython (.NET implementation of python), I'vve started by reading \"Dive into python\" and a few tutorials and then I've started coding a simple board game using IronPython (you can read about it in my blog).\nIn order to learn a new programming language you need to use it and then you'll know how and where to use it.\n",
"The best way to learn how to do something useful is come up with something useful you want to do. Make sure it's not way out of your league, then do research to accomplish it. That's how a lot of programmers learn languages.\n",
"What other programming background do you have? What programming interests do you have -- web apps, numerical / scientific computations, games, ...? Python is good at many different things, for both beginners and experienced programmers, but the most fruitful approach(es) to it do depend on what you already know, and what really interests you!-)\n",
"Bram who invented bittorrent with python says python is good for writing protocols in addition to aforementioned webapps, games and general purpose. Compared to Java python solves same problem in less code and less ways in longer development and VM time where Java has more ways solve same problem in more code and faster VM and faster development time.\n",
"Making a comparison between Python, and other languages would not help, as there is always somebody who would find a reason to prefer one language instead of another.\nIf you want a scripting language that is powerful, but that it is easier to read than perl, that doesn't have a curly bracket syntax, and that allows you to learn something about object oriented programming, then Python is the language for you.\n"
] |
[
8,
4,
3,
3,
2,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001926019_python.txt
|
Q:
How should I perform cleanup at the end of a repoze.bfg response?
Example code for the repoze.bfg web framework performs post-response cleanup by adding a __del__ method to an object attached to the request's environ.
Is there a better way to clean up database connections, etc. after the response has been completely sent to the client?
A:
Since you are dealing with repoze.bfg, best you use their documented way of doing things as it is going to be compatible with their framework and how they manage the request lifecycle. That said, if you want the generic WSGI way of doing it, it is documented in:
http://code.google.com/p/modwsgi/wiki/RegisteringCleanupCode
|
How should I perform cleanup at the end of a repoze.bfg response?
|
Example code for the repoze.bfg web framework performs post-response cleanup by adding a __del__ method to an object attached to the request's environ.
Is there a better way to clean up database connections, etc. after the response has been completely sent to the client?
|
[
"Since you are dealing with repoze.bfg, best you use their documented way of doing things as it is going to be compatible with their framework and how they manage the request lifecycle. That said, if you want the generic WSGI way of doing it, it is documented in:\nhttp://code.google.com/p/modwsgi/wiki/RegisteringCleanupCode\n"
] |
[
1
] |
[] |
[] |
[
"python",
"repoze.bfg",
"wsgi"
] |
stackoverflow_0001926169_python_repoze.bfg_wsgi.txt
|
Q:
python import a method that depends on a imported class
So if I have 2 files that look like this:
File 1
import class1
import method1
def method2(something):
result = method1(classname=class1)
File 2
def method1(classname):
some_result = classname.resultfinder
return some_result
Will this work?
I mean, since I am not importing class1 in the file where method1 lives, but method1 still ends up using class1.
Will method1 have access to class1 via the import made in File 1 where method 1 is imported to?
A:
What happened when you tried it?
Note that your import of method1 is wrong. Apart from that --- yes, you do not need to import everything. Do you think the standard library imports your stuff whenever you use it? ;-)
A:
I think that should be fine - imagine having to import every possible type that could be passed to a function at runtime. I don't think a "dynamic" language like that would last very long.
A:
It doesn't quite look right--you don't exactly "import class1", you more import a module (in a file) that contains class1, or a module that contains method1. So I'd expect to see more like
from file2 import method1
from file3 import class1
Also, method1 doesn't so much take a class name as a class object. Or should that be a class instance object? Sorry if I'm being picky, but hopefully it's educational to consider the distinction.
|
python import a method that depends on a imported class
|
So if I have 2 files that look like this:
File 1
import class1
import method1
def method2(something):
result = method1(classname=class1)
File 2
def method1(classname):
some_result = classname.resultfinder
return some_result
Will this work?
I mean, since I am not importing class1 in the file where method1 lives, but method1 still ends up using class1.
Will method1 have access to class1 via the import made in File 1 where method 1 is imported to?
|
[
"What happened when you tried it?\nNote that your import of method1 is wrong. Apart from that --- yes, you do not need to import everything. Do you think the standard library imports your stuff whenever you use it? ;-)\n",
"I think that should be fine - imagine having to import every possible type that could be passed to a function at runtime. I don't think a \"dynamic\" language like that would last very long.\n",
"It doesn't quite look right--you don't exactly \"import class1\", you more import a module (in a file) that contains class1, or a module that contains method1. So I'd expect to see more like\nfrom file2 import method1\nfrom file3 import class1\n\nAlso, method1 doesn't so much take a class name as a class object. Or should that be a class instance object? Sorry if I'm being picky, but hopefully it's educational to consider the distinction.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"import",
"python"
] |
stackoverflow_0001924906_import_python.txt
|
Q:
How do I parse a string representing a nested list into an actual list?
Say I have a string representing some nested lists and I want to convert it into the real thing. I could do this, I think:
exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']"
But in an environment where users might be supplying the string to execute this could/would be a bad idea. Does anybody have any ideas for a tidy parser that would accomplish the same thing?
A:
>>> import ast
>>> mylist = ast.literal_eval("['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']")
>>> mylist
['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']
ast.literal_eval:
Safely evaluate an expression node or
a string containing a Python
expression. The string or node
provided may only consist of the
following Python literal structures:
strings, numbers, tuples, lists,
dicts, booleans, and None.
This can be used for safely evaluating
strings containing Python expressions
from untrusted sources without the
need to parse the values oneself.
|
How do I parse a string representing a nested list into an actual list?
|
Say I have a string representing some nested lists and I want to convert it into the real thing. I could do this, I think:
exec "myList = ['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']"
But in an environment where users might be supplying the string to execute this could/would be a bad idea. Does anybody have any ideas for a tidy parser that would accomplish the same thing?
|
[
">>> import ast\n>>> mylist = ast.literal_eval(\"['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']\")\n>>> mylist\n['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']\n\nast.literal_eval:\n\nSafely evaluate an expression node or\n a string containing a Python\n expression. The string or node\n provided may only consist of the\n following Python literal structures:\n strings, numbers, tuples, lists,\n dicts, booleans, and None.\nThis can be used for safely evaluating\n strings containing Python expressions\n from untrusted sources without the\n need to parse the values oneself.\n\n"
] |
[
29
] |
[] |
[] |
[
"exec",
"nested_lists",
"parsing",
"python",
"string"
] |
stackoverflow_0001926741_exec_nested_lists_parsing_python_string.txt
|
Q:
Searching a file
This is in reference to a question I posted yesterday Searching a file in 3 different ways
I just require help now on two things, searching a file and and printing the line a search result is found on and all the lines after it to the end of the file.
Lastly i need help on coding were i search a file and print the line a search result is found on and a number of lines before and after the the search result. The number of lines printed before and after the search result is defined by the user and is the before/after amount of lines are the same.
A:
for the first part
for line in open("file"):
line=line.rstrip()
if "search" in line:
f=1
if f: print line
for the second part
context=3
search="myword"
f=open("file")
d={}
for n,line in enumerate(f):
d[n%context]=line.rstrip()
if search in line:
for i in range(n+1,n+1+context):
print d[i%context]
for i in range(1,context):
print f.next().rstrip()
f.close()
|
Searching a file
|
This is in reference to a question I posted yesterday Searching a file in 3 different ways
I just require help now on two things, searching a file and and printing the line a search result is found on and all the lines after it to the end of the file.
Lastly i need help on coding were i search a file and print the line a search result is found on and a number of lines before and after the the search result. The number of lines printed before and after the search result is defined by the user and is the before/after amount of lines are the same.
|
[
"for the first part\nfor line in open(\"file\"):\n line=line.rstrip()\n if \"search\" in line:\n f=1\n if f: print line\n\nfor the second part\ncontext=3\nsearch=\"myword\"\nf=open(\"file\")\nd={}\nfor n,line in enumerate(f):\n d[n%context]=line.rstrip()\n if search in line:\n for i in range(n+1,n+1+context):\n print d[i%context]\n for i in range(1,context):\n print f.next().rstrip()\nf.close()\n\n"
] |
[
2
] |
[] |
[] |
[
"file",
"python",
"search"
] |
stackoverflow_0001927276_file_python_search.txt
|
Q:
Python script running in linux
I am having trouble trying to get this script to work. When I debug this code it will not read into the class or functions. The code will not execute properly. Has anyone know the problem here, Thanks
#!/home/build/test/Python-2.6.4
import os, subprocess
class mks_function:
sandbox="new_sandbox"
def mks_create_sandbox():
try:
retcode=call("si createsandbox" + "--no --hostname=bel --port=70 --user=user --password=1234 --populate --project=e:/project.pj --lineTerminator=lf new_sandbox", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
print "sandbox retVal="+retcode
print "Creating a new sandbox called "+sandbox+" "
###############################################################
A:
Few things to check your code
call should be subprocess.call
better use full path when you call for example, /usr/bin/si createsandbox, you can check with which si in shell
instead of concatenating the commands "si createsandbox" + "--no ...", please use list ["/usr/bin/si","createsandbox --no ..."]
you didn't import sys, but using it
sandbox should be self.sandbox and def mks_create_sandbox(): should be def mks_create_sandbox(self):
Use an IDE for example Ulipad.
A:
Try put as the first line:
#!/usr/bin/env python
If you really need specific version of Python, setup your environment before running.
Possible problems:
your code is never executed (it's like you define the class only). Use it in the file (names are misleading):
if __name__ == '__main__':
myObject = mks_function()
show us how are you executing the code? Have you changed the permissions to be able to run the script?
chmod +x filename.py
or are you trying to start it as:
python filename.py
|
Python script running in linux
|
I am having trouble trying to get this script to work. When I debug this code it will not read into the class or functions. The code will not execute properly. Has anyone know the problem here, Thanks
#!/home/build/test/Python-2.6.4
import os, subprocess
class mks_function:
sandbox="new_sandbox"
def mks_create_sandbox():
try:
retcode=call("si createsandbox" + "--no --hostname=bel --port=70 --user=user --password=1234 --populate --project=e:/project.pj --lineTerminator=lf new_sandbox", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
print "sandbox retVal="+retcode
print "Creating a new sandbox called "+sandbox+" "
###############################################################
|
[
"Few things to check your code\n\ncall should be subprocess.call\nbetter use full path when you call for example, /usr/bin/si createsandbox, you can check with which si in shell\ninstead of concatenating the commands \"si createsandbox\" + \"--no ...\", please use list [\"/usr/bin/si\",\"createsandbox --no ...\"]\nyou didn't import sys, but using it\nsandbox should be self.sandbox and def mks_create_sandbox(): should be def mks_create_sandbox(self):\nUse an IDE for example Ulipad.\n\n",
"Try put as the first line:\n#!/usr/bin/env python\n\nIf you really need specific version of Python, setup your environment before running.\nPossible problems:\n\nyour code is never executed (it's like you define the class only). Use it in the file (names are misleading):\nif __name__ == '__main__':\n myObject = mks_function()\nshow us how are you executing the code? Have you changed the permissions to be able to run the script?\nchmod +x filename.py\nor are you trying to start it as:\npython filename.py\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001927375_python.txt
|
Q:
XML-RPC method parameter data typing in Python
I have built an XML-RPC interface in Python and I need to enforce some stricter typing. For example, passing string '10' instead of int 10. I can clean this up with some type casting and a little exception handling, but I am wondering if there is any other way of forcing type integrity such as something XML-RPC specific, a decorator, or something else.
A:
It's always going to be converted to a string anyway, so why do you care what's being passed in? If you use "%s" % number or even just str(number), then it doesn't matter whether number is a string or an int.
A:
XML-RPC methods (at least in xmlrpclib) are dispatched to Python functions or method, so you have to enforce type checking in them. There is a lot of recipes on doing this task with decorators: Type Enforcement (accepts/returns), typecheck module.
Note, that xmlrpclib lacks proper error handling, so you probably would like to implement your own.
A:
I always just use the re.escape function eg.:
number = re.escape(number)
This way things always gets converted to strings
|
XML-RPC method parameter data typing in Python
|
I have built an XML-RPC interface in Python and I need to enforce some stricter typing. For example, passing string '10' instead of int 10. I can clean this up with some type casting and a little exception handling, but I am wondering if there is any other way of forcing type integrity such as something XML-RPC specific, a decorator, or something else.
|
[
"It's always going to be converted to a string anyway, so why do you care what's being passed in? If you use \"%s\" % number or even just str(number), then it doesn't matter whether number is a string or an int.\n",
"XML-RPC methods (at least in xmlrpclib) are dispatched to Python functions or method, so you have to enforce type checking in them. There is a lot of recipes on doing this task with decorators: Type Enforcement (accepts/returns), typecheck module.\nNote, that xmlrpclib lacks proper error handling, so you probably would like to implement your own.\n",
"I always just use the re.escape function eg.:\nnumber = re.escape(number)\n\nThis way things always gets converted to strings\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001925487_django_python.txt
|
Q:
strategies for finding duplicate mailing addresses
I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses:
addr_1 = '# 3 FAIRMONT LINK SOUTH'
addr_2 = '3 FAIRMONT LINK S'
addr_3 = '5703 - 48TH AVE'
adrr_4 = '5703- 48 AVENUE'
I'm planning on applying some string transformation to make long words abbreviated, like NORTH -> N, remove all spaces, commas and dashes and pound symbols. Now, having this output, how can I compare addr_3 with the rest of addresses and detect similar? What percentage of similarity would be safe? Could you provide a simple python code for this?
addr_1 = '3FAIRMONTLINKS'
addr_2 = '3FAIRMONTLINKS'
addr_3 = '570348THAV'
adrr_4 = '570348AV'
Thankful,
Eduardo
A:
Removing spaces, commas and dashes will be ambiguous . It will be better to replace them with a single space.
Take for example this address
56 5th avenue
And this
5, 65th avenue
with your method both of them will be:
565THAV
What you can do is write a good address shortening algorithm and then use string comparison to detect duplicates. This should be enough to detect duplicates in the general case. A general similarity algorithm won't work. Because one number difference can mean a huge change in Addresses.
The algorithm can go like this:
replace all commas dashes with spaces. Use he translate method for that.
Build a dictionary with words and their abbreviated form
Remove the TH part if it was following a number.
A:
This should be helpful in building your dictionary of abbreviations:
https://pe.usps.com/text/pub28/28apc_002.htm
A:
First, simplify the address string by collapsing all whitespace to a single space between each word, and forcing everything to lower case (or upper case if you prefer):
adr = " ".join(adr.tolower().split())
Then, I would strip out things like "st" in "41st Street" or "nd" in "42nd Street":
adr = re.sub("1st(\b|$)", r'1', adr)
adr = re.sub("([2-9])\s?nd(\b|$)", r'\1', adr)
Note that the second sub() will work with a space between the "2" and the "nd", but I didn't set the first one to do that; because I'm not sure how you can tell the difference between "41 St Ave" and "41 St" (that second one is "41 Street" abbreviated).
Be sure to read all the help for the re module; it's powerful but cryptic.
Then, I would split what you have left into a list of words, and apply the Soundex algorithm to list items that don't look like numbers:
http://en.wikipedia.org/wiki/Soundex
http://wwwhomes.uni-bielefeld.de/gibbon/Forms/Python/SEARCH/soundex.html
adrlist = [word if word.isdigit() else soundex(word) for word in adr.split()]
Then you can work with the list or join it back to a string as you think best.
The whole idea of the Soundex thing is to handle misspelled addresses. That may not be what you want, in which case just ignore this Soundex idea.
Good luck.
A:
I regularly inspect addresses for duplication where I work, and I have to say, I find Soundex highly unsuitable. It's both too slow and too eager to match things. I have similar issues with Levenshtein distance.
What has worked best for me is to sanitize and tokenize the addresses (get rid of punctuation, split things up into words) and then just see how many tokens match up. Because addresses typically have several tokens, you can develop a level of confidence in terms of a combination of (1) how many tokens were matched, (2) how many numeric tokens were matched, and (3) how many tokens are available. For example, if all tokens in the shorter address are in the longer address, the confidence of a match is pretty high. Likewise, if you match 5 tokens including at least one that's numeric, even if the addresses each have 8, that's still a high-confidence match.
It's definitely useful to do some tweaking, like substituting some common abbreviations. The USPS lists help, though I wouldn't go gung-ho trying to implement all of them, and some of the most valuable substitutions aren't on those lists. For example, 'JFK' should be a match for 'JOHN F KENNEDY', and there are a number of common ways to shorten 'MARTIN LUTHER KING JR'.
Maybe it goes without saying but I'll say it anyway, for completeness: Don't forget to just do a straight string comparison on the whole address before messing with more complicated things! This should be a very cheap test, and thus is probably a no-brainer first pass.
Obviously, the more time you're willing and able to spend (both on programming/testing and on run time), the better you'll be able to do. Fuzzy string matching techniques (faster and less generalized kinds than Levenshtein) can be useful, as a separate pass from the token approach (I wouldn't try to fuzzy match individual tokens against each other). I find that fuzzy string matching doesn't give me enough bang for my buck on addresses (though I will use it on names).
A:
In order to do this right, you need to standardize your addresses according to USPS standards (your address examples appear to be US based). There are many direct marketing service providers that offer CASS (Coding Accuracy Support System) certification of postal addresses. The CASS process will standardize all of your addresses and append zip + 4 to them. Any undeliverable addresses will be flagged which will further reduce your postal mailing costs, if that is your intent. Once all of your addresses are standardized, eliminating duplicates will be trivial.
A:
I had to do this once. I converted everything to lowercase, computed each address's Levenshtein distance to every other address, and ordered the results. It worked very well, but it was quite time-consuming.
You'll want to use an implementation of Levenshtein in C rather than in Python if you have a large data set. Mine was a few tens of thousands and took the better part of a day to run, I think.
|
strategies for finding duplicate mailing addresses
|
I'm trying to come up with a method of finding duplicate addresses, based on a similarity score. Consider these duplicate addresses:
addr_1 = '# 3 FAIRMONT LINK SOUTH'
addr_2 = '3 FAIRMONT LINK S'
addr_3 = '5703 - 48TH AVE'
adrr_4 = '5703- 48 AVENUE'
I'm planning on applying some string transformation to make long words abbreviated, like NORTH -> N, remove all spaces, commas and dashes and pound symbols. Now, having this output, how can I compare addr_3 with the rest of addresses and detect similar? What percentage of similarity would be safe? Could you provide a simple python code for this?
addr_1 = '3FAIRMONTLINKS'
addr_2 = '3FAIRMONTLINKS'
addr_3 = '570348THAV'
adrr_4 = '570348AV'
Thankful,
Eduardo
|
[
"Removing spaces, commas and dashes will be ambiguous . It will be better to replace them with a single space.\nTake for example this address\n56 5th avenue\n\nAnd this\n5, 65th avenue\n\nwith your method both of them will be:\n565THAV\n\nWhat you can do is write a good address shortening algorithm and then use string comparison to detect duplicates. This should be enough to detect duplicates in the general case. A general similarity algorithm won't work. Because one number difference can mean a huge change in Addresses.\nThe algorithm can go like this:\n\nreplace all commas dashes with spaces. Use he translate method for that.\nBuild a dictionary with words and their abbreviated form\nRemove the TH part if it was following a number.\n\n",
"This should be helpful in building your dictionary of abbreviations:\nhttps://pe.usps.com/text/pub28/28apc_002.htm\n",
"First, simplify the address string by collapsing all whitespace to a single space between each word, and forcing everything to lower case (or upper case if you prefer):\nadr = \" \".join(adr.tolower().split())\n\nThen, I would strip out things like \"st\" in \"41st Street\" or \"nd\" in \"42nd Street\":\nadr = re.sub(\"1st(\\b|$)\", r'1', adr)\nadr = re.sub(\"([2-9])\\s?nd(\\b|$)\", r'\\1', adr)\n\nNote that the second sub() will work with a space between the \"2\" and the \"nd\", but I didn't set the first one to do that; because I'm not sure how you can tell the difference between \"41 St Ave\" and \"41 St\" (that second one is \"41 Street\" abbreviated).\nBe sure to read all the help for the re module; it's powerful but cryptic.\nThen, I would split what you have left into a list of words, and apply the Soundex algorithm to list items that don't look like numbers:\nhttp://en.wikipedia.org/wiki/Soundex\nhttp://wwwhomes.uni-bielefeld.de/gibbon/Forms/Python/SEARCH/soundex.html\nadrlist = [word if word.isdigit() else soundex(word) for word in adr.split()]\n\nThen you can work with the list or join it back to a string as you think best.\nThe whole idea of the Soundex thing is to handle misspelled addresses. That may not be what you want, in which case just ignore this Soundex idea.\nGood luck.\n",
"I regularly inspect addresses for duplication where I work, and I have to say, I find Soundex highly unsuitable. It's both too slow and too eager to match things. I have similar issues with Levenshtein distance.\nWhat has worked best for me is to sanitize and tokenize the addresses (get rid of punctuation, split things up into words) and then just see how many tokens match up. Because addresses typically have several tokens, you can develop a level of confidence in terms of a combination of (1) how many tokens were matched, (2) how many numeric tokens were matched, and (3) how many tokens are available. For example, if all tokens in the shorter address are in the longer address, the confidence of a match is pretty high. Likewise, if you match 5 tokens including at least one that's numeric, even if the addresses each have 8, that's still a high-confidence match.\nIt's definitely useful to do some tweaking, like substituting some common abbreviations. The USPS lists help, though I wouldn't go gung-ho trying to implement all of them, and some of the most valuable substitutions aren't on those lists. For example, 'JFK' should be a match for 'JOHN F KENNEDY', and there are a number of common ways to shorten 'MARTIN LUTHER KING JR'.\nMaybe it goes without saying but I'll say it anyway, for completeness: Don't forget to just do a straight string comparison on the whole address before messing with more complicated things! This should be a very cheap test, and thus is probably a no-brainer first pass.\nObviously, the more time you're willing and able to spend (both on programming/testing and on run time), the better you'll be able to do. Fuzzy string matching techniques (faster and less generalized kinds than Levenshtein) can be useful, as a separate pass from the token approach (I wouldn't try to fuzzy match individual tokens against each other). I find that fuzzy string matching doesn't give me enough bang for my buck on addresses (though I will use it on names).\n",
"In order to do this right, you need to standardize your addresses according to USPS standards (your address examples appear to be US based). There are many direct marketing service providers that offer CASS (Coding Accuracy Support System) certification of postal addresses. The CASS process will standardize all of your addresses and append zip + 4 to them. Any undeliverable addresses will be flagged which will further reduce your postal mailing costs, if that is your intent. Once all of your addresses are standardized, eliminating duplicates will be trivial. \n",
"I had to do this once. I converted everything to lowercase, computed each address's Levenshtein distance to every other address, and ordered the results. It worked very well, but it was quite time-consuming.\nYou'll want to use an implementation of Levenshtein in C rather than in Python if you have a large data set. Mine was a few tens of thousands and took the better part of a day to run, I think.\n"
] |
[
2,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"duplicates",
"mailing",
"python",
"similarity",
"street_address"
] |
stackoverflow_0001369289_duplicates_mailing_python_similarity_street_address.txt
|
Q:
Embeddable Workflow/BPM Library For Python?
Let's say you are building a Python-based web app that requires some workflow management such as that in jBPM or Windows Workflow Foundation. Is there a library that offers this in the Python world?
A:
Oh yes, tons. But most of them depend on a specific framework. DCWorkflow is integrated with Zopes CMF, for example. hurry.workflow is for Zope 3, etc. SpiffWorkflow presumes sql-alchemy, etc. This is because you need to have something to apply the workflow to, and that means you need to make some basic assumptions on the objects you use.
Hurry.workflow is probably one of the more independent ones, but it still assumes both that you use the Persistence library (and therefore in practice ZODB), and zope3's security model.
So you probably need to expand a bit on your requirements here...
A:
Have you looked at this? http://code.djangoproject.com/wiki/GoFlow
|
Embeddable Workflow/BPM Library For Python?
|
Let's say you are building a Python-based web app that requires some workflow management such as that in jBPM or Windows Workflow Foundation. Is there a library that offers this in the Python world?
|
[
"Oh yes, tons. But most of them depend on a specific framework. DCWorkflow is integrated with Zopes CMF, for example. hurry.workflow is for Zope 3, etc. SpiffWorkflow presumes sql-alchemy, etc. This is because you need to have something to apply the workflow to, and that means you need to make some basic assumptions on the objects you use.\nHurry.workflow is probably one of the more independent ones, but it still assumes both that you use the Persistence library (and therefore in practice ZODB), and zope3's security model.\nSo you probably need to expand a bit on your requirements here...\n",
"Have you looked at this? http://code.djangoproject.com/wiki/GoFlow\n"
] |
[
3,
1
] |
[] |
[] |
[
"business_process_management",
"python",
"workflow"
] |
stackoverflow_0001493550_business_process_management_python_workflow.txt
|
Q:
Python - Tkinter - Padding woes
I have a scrollbar widget that ALWAYS hides the last 15 px under the resize button, is there an option to stop this happening on mac or a padding "under" the widget option?\
thanks!
A:
No, there isn't an option. You need to adjust your padding so that the scrollbar doesn't extend all the way to the bottom of the window. Perhaps the easiest way is to add a statusbar that extends across the bottom of the window.
A:
Or, you could also try switching to the place() layout manager.
|
Python - Tkinter - Padding woes
|
I have a scrollbar widget that ALWAYS hides the last 15 px under the resize button, is there an option to stop this happening on mac or a padding "under" the widget option?\
thanks!
|
[
"No, there isn't an option. You need to adjust your padding so that the scrollbar doesn't extend all the way to the bottom of the window. Perhaps the easiest way is to add a statusbar that extends across the bottom of the window. \n",
"Or, you could also try switching to the place() layout manager.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"tkinter",
"user_interface"
] |
stackoverflow_0001927475_python_tkinter_user_interface.txt
|
Q:
Why is (python|ruby) interpreted?
What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains. So certainly I am missing something.
A:
Several reasons:
faster development loop, write-test vs write-compile-link-test
easier to arrange for dynamic behavior (reflection, metaprogramming)
makes the whole system portable (just recompile the underlying C code and you are good to go on a new platform)
Think of what would happen if the system was not interpreted. Say you used translation-to-C as the mechanism. The compiled code would periodically have to check if it had been superseded by metaprogramming. A similar situation arises with eval()-type functions. In those cases, it would have to run the compiler again, an outrageously slow process, or it would have to also have the interpreter around at run-time anyway.
The only alternative here is a JIT compiler. These systems are highly complex and sophisticated and have even bigger run-time footprints than all the other alternatives. They start up very slowly, making them impractical for scripting. Ever seen a Java script? I haven't.
So, you have two choices:
all the disadvantages of both a compiler and an interpreter
just the disadvantages of an interpreter
It's not surprising that generally the primary implementation just goes with the second choice. It's quite possible that some day we may see secondary implementations like compilers appearing. Ruby 1.9 and Python have bytecode VM's; those are ½-way there. A compiler might target just non-dynamic code, or it might have various levels of language support declarable as options. But since such a thing can't be the primary implementation, it represents a lot of work for a very marginal benefit. Ruby already has 200,000 lines of C in it...
I suppose I should add that one can always add a compiled C (or, with some effort, any other language) extension. So, say you have a slow numerical operation. If you add, say Array#newOp with a C implementation then you get the speedup, the program stays in Ruby (or whatever) and your environment gets a new instance method. Everybody wins! So this reduces the need for a problematic secondary implementation.
A:
Exactly like (in the typical implementation of) Java or C#, Python gets first compiled into some form of bytecode, depending on the implementation (CPython uses a specialized form of its own, Jython uses JVM just like a typical Java, IronPython uses CLR just like a typical C#, and so forth) -- that bytecode then gets further processed for execution by a virtual machine (AKA interpreter), which may also generate machine code "just in time" -- known as JIT -- if and when warranted (CLR and JVM implementations often do, CPython's own virtual machine typically doesn't but can be made to do so e.g. with psyco or Unladen Swallow).
JIT may pay for itself for sufficiently long-running programs (if memory's way cheaper than CPU cycles), but it may not (due to slower startup times and larger memory footprint), especially when the types also have to be inferred or specialized as part of the code generation. Generating machine code without type inference or specialization is easy if that's what you want, e.g. freeze does it for you, but it really doesn't present the advantages that "machine code fetishists" attribute to it. E.g., you get an executable binary of 1.5 to 2 MB in lieu of a tiny "hello world" .pyc -- not much point!-). That executable is stand-alone and distributable as such, but it will only work on a very specific narrow range of operating systems and CPU architectures, so the tradeoffs are quite iffy in most cases. And, the time it takes to prepare the executable is quite long indeed, so it would be a crazy choice to make that mode of operation the default one.
A:
Merely replacing an interpreter with a compiler won't give you as big a performance boost as you might think for a language like Python. When most time is actually spend doing symbolic lookups of object members in dictionaries, it doesn't really matter if the call to the function performing such lookup is interpreted, or is native machine code - the difference, while not quite negligible, will be dwarfed by lookup overhead.
To really improve performance, you need optimizing compilers. And optimization techniques here are very different from what you have with C++, or even Java JIT - an optimizing compiler for a dynamically typed / duck typed language such as Python needs to do some very creative type inference (including probabilistic - i.e. "90% chance of it being T" and then generating efficient machine code for that case with a check/branch before it) and escape analysis. This is hard.
A:
I think the biggest reason for the languages being interpreted is portability. As a programmer you can write code that will run in an interpreter not a specific OS. So your programs behave more uniformly across platforms (more so than compiled languages). Another advantage I can think of is it's easier to have a dynamic type system in an interpreted language. I think the creators of the language were thinking having a language where programmers can be more productive due to automatic memory management, dynamic type system and meta programming wins over any performance loss due to the language being interpreted. If you are concerned about performance you can always compile the language to native machine code employing a technique like JIT compilation.
A:
Today, there is no longer a strong distinction between "compiled" and "interpreted" languages. Python is in fact compiled just as much as Java is, the only differences are:
The Python compiler is much faster than the Java compiler
Python automatically compiles source code as it is executed, there is no separate "compile" step required
Python bytecode is different from JVM bytecode
Python even has a function called compile() which is an interface to the compiler.
It sounds like the distinction you are making is between "dynamically typed" and "statically typed" languages. In dynamic languages such as Python, you can write code like:
def fn(x, y):
return x.foo(y)
Notice that the types of x and y are not specified. At runtime, this function will look at x to see whether it has a member function named foo, and if so will call it with y. If not, it will throw a runtime error that indicates no such function was found. This sort of runtime lookup is much easier to represent using an intermediate representation like bytecode, where a runtime VM does the lookup instead of having to generate machine code to do the lookup itself (or, call a function to do the lookup which is what the bytecode will do anyway).
Python has projects such as Psyco, PyPy, and Unladen Swallow that take various approaches to compiling Python object code into something closer to native code. There is active research in this area but there is not (as yet) a simple answer.
A:
The effort required to create a good compiler to generate native code for a new language is staggering. Small research groups typically take 5 to 10 years (examples: SML/NJ, Haskell, Clean, Cecil, lcc, Objective Caml, MLton, and many others). And when the language in question requires type checking and other decisions to be made at run time, a compiler writer has to work much harder to get good native-code performance (for an excellent example, see work by Craig Chambers and later Urs Hoelzle on Self). The performance gains you might hope for are harder to realize than you might think. This phenomenon partly explains why so many dynamically typed languages are interpreted.
As noted, a decent interpreter is also instantly portable, while porting compilers to new machine architectures takes substantial effort (and is a problem I personally have been working on for over 20 years, with some time off for good behavior). So an interpreter is a way to reach a wide audience quickly.
Finally, although fast compilers and slow interpreters exist, it's usually easer to make the edit-translate-go cycle faster by using an interpreter. (For some nice examples of fast compilers see the aforementioned lcc as well as Ken Thompson's go compiler. For an example of a relatively slow interpreter see GHCi.
A:
Well, isn't one of the strengths of these languages that they are so easily scriptable? They wouldn't be if they were compiled. And on the other hand, dynamic languages are easier to intereprete than to compile.
A:
In a compiled language, the loop you get into when making software is
Make a change
Compile changes
Test changes
goto 1
Interpreted languages tend to be faster to make stuff in because you get to cut out step two of that process (and when you're dealing with a large system where compile times can be upwards of two minutes, step two can add a significant amount of time).
This isn't necessarily the reason python|ruby designers thought of, but keep in mind that "How efficiently does the machine run this?" is only half the software development problem.
It also seems like it would be easier to compile code in a language that's interpreted naturally than it would be to add an interpreter to a language that's compiled by default.
A:
REPL. Don't knock it 'till you've tried it. :)
A:
By design.
The authors wanted something where they can write scripts into.
Python gets compiled the first time it is executed though
A:
Compiling Ruby at least is notoriously hard. I'm working on one, and as part of that I wrote a blog post enumerating some of the issues here.
Specifically, Ruby is suffering from a very unclear (i.e. non-existent) boundary between the "read" and "execute" phase of the program that makes it hard to compile efficiently. You could just emulate what the interpreter does, but then you're not going to see much speed up, so it wouldn't be worth the effort. If you want to compile it efficiently you then face a lot of additional complications to handle the extreme level of dynamism in Ruby.
The good news is that there are techniques for overcoming this. Self, Smalltalk and Lisp/Scheme's have dealt quite successfully with most of the same issues. But it takes time to sift through it and figure out how to make it work with Ruby. It also doesn't help that Ruby has a very convoluted grammar.
A:
Raw compute performance is probably not a goal of most interpreted languages. Interpreted languages are typically more concerned about programmer productivity than raw speed. In most cases these languages are plenty fast enough for the tasks the languages were designed to tackle.
Given that, and that just about the only advantages of a compiler are type checking (difficult to do in a dynamic language) and speed, there's not much incentive to write compilers for most interpreted languages.
|
Why is (python|ruby) interpreted?
|
What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains. So certainly I am missing something.
|
[
"Several reasons:\n\nfaster development loop, write-test vs write-compile-link-test\neasier to arrange for dynamic behavior (reflection, metaprogramming)\nmakes the whole system portable (just recompile the underlying C code and you are good to go on a new platform)\n\nThink of what would happen if the system was not interpreted. Say you used translation-to-C as the mechanism. The compiled code would periodically have to check if it had been superseded by metaprogramming. A similar situation arises with eval()-type functions. In those cases, it would have to run the compiler again, an outrageously slow process, or it would have to also have the interpreter around at run-time anyway. \nThe only alternative here is a JIT compiler. These systems are highly complex and sophisticated and have even bigger run-time footprints than all the other alternatives. They start up very slowly, making them impractical for scripting. Ever seen a Java script? I haven't.\nSo, you have two choices:\n\nall the disadvantages of both a compiler and an interpreter\njust the disadvantages of an interpreter\n\nIt's not surprising that generally the primary implementation just goes with the second choice. It's quite possible that some day we may see secondary implementations like compilers appearing. Ruby 1.9 and Python have bytecode VM's; those are ½-way there. A compiler might target just non-dynamic code, or it might have various levels of language support declarable as options. But since such a thing can't be the primary implementation, it represents a lot of work for a very marginal benefit. Ruby already has 200,000 lines of C in it...\nI suppose I should add that one can always add a compiled C (or, with some effort, any other language) extension. So, say you have a slow numerical operation. If you add, say Array#newOp with a C implementation then you get the speedup, the program stays in Ruby (or whatever) and your environment gets a new instance method. Everybody wins! So this reduces the need for a problematic secondary implementation.\n",
"Exactly like (in the typical implementation of) Java or C#, Python gets first compiled into some form of bytecode, depending on the implementation (CPython uses a specialized form of its own, Jython uses JVM just like a typical Java, IronPython uses CLR just like a typical C#, and so forth) -- that bytecode then gets further processed for execution by a virtual machine (AKA interpreter), which may also generate machine code \"just in time\" -- known as JIT -- if and when warranted (CLR and JVM implementations often do, CPython's own virtual machine typically doesn't but can be made to do so e.g. with psyco or Unladen Swallow).\nJIT may pay for itself for sufficiently long-running programs (if memory's way cheaper than CPU cycles), but it may not (due to slower startup times and larger memory footprint), especially when the types also have to be inferred or specialized as part of the code generation. Generating machine code without type inference or specialization is easy if that's what you want, e.g. freeze does it for you, but it really doesn't present the advantages that \"machine code fetishists\" attribute to it. E.g., you get an executable binary of 1.5 to 2 MB in lieu of a tiny \"hello world\" .pyc -- not much point!-). That executable is stand-alone and distributable as such, but it will only work on a very specific narrow range of operating systems and CPU architectures, so the tradeoffs are quite iffy in most cases. And, the time it takes to prepare the executable is quite long indeed, so it would be a crazy choice to make that mode of operation the default one.\n",
"Merely replacing an interpreter with a compiler won't give you as big a performance boost as you might think for a language like Python. When most time is actually spend doing symbolic lookups of object members in dictionaries, it doesn't really matter if the call to the function performing such lookup is interpreted, or is native machine code - the difference, while not quite negligible, will be dwarfed by lookup overhead.\nTo really improve performance, you need optimizing compilers. And optimization techniques here are very different from what you have with C++, or even Java JIT - an optimizing compiler for a dynamically typed / duck typed language such as Python needs to do some very creative type inference (including probabilistic - i.e. \"90% chance of it being T\" and then generating efficient machine code for that case with a check/branch before it) and escape analysis. This is hard.\n",
"I think the biggest reason for the languages being interpreted is portability. As a programmer you can write code that will run in an interpreter not a specific OS. So your programs behave more uniformly across platforms (more so than compiled languages). Another advantage I can think of is it's easier to have a dynamic type system in an interpreted language. I think the creators of the language were thinking having a language where programmers can be more productive due to automatic memory management, dynamic type system and meta programming wins over any performance loss due to the language being interpreted. If you are concerned about performance you can always compile the language to native machine code employing a technique like JIT compilation.\n",
"Today, there is no longer a strong distinction between \"compiled\" and \"interpreted\" languages. Python is in fact compiled just as much as Java is, the only differences are:\n\nThe Python compiler is much faster than the Java compiler\nPython automatically compiles source code as it is executed, there is no separate \"compile\" step required\nPython bytecode is different from JVM bytecode\n\nPython even has a function called compile() which is an interface to the compiler.\nIt sounds like the distinction you are making is between \"dynamically typed\" and \"statically typed\" languages. In dynamic languages such as Python, you can write code like:\ndef fn(x, y):\n return x.foo(y)\n\nNotice that the types of x and y are not specified. At runtime, this function will look at x to see whether it has a member function named foo, and if so will call it with y. If not, it will throw a runtime error that indicates no such function was found. This sort of runtime lookup is much easier to represent using an intermediate representation like bytecode, where a runtime VM does the lookup instead of having to generate machine code to do the lookup itself (or, call a function to do the lookup which is what the bytecode will do anyway).\nPython has projects such as Psyco, PyPy, and Unladen Swallow that take various approaches to compiling Python object code into something closer to native code. There is active research in this area but there is not (as yet) a simple answer.\n",
"The effort required to create a good compiler to generate native code for a new language is staggering. Small research groups typically take 5 to 10 years (examples: SML/NJ, Haskell, Clean, Cecil, lcc, Objective Caml, MLton, and many others). And when the language in question requires type checking and other decisions to be made at run time, a compiler writer has to work much harder to get good native-code performance (for an excellent example, see work by Craig Chambers and later Urs Hoelzle on Self). The performance gains you might hope for are harder to realize than you might think. This phenomenon partly explains why so many dynamically typed languages are interpreted.\nAs noted, a decent interpreter is also instantly portable, while porting compilers to new machine architectures takes substantial effort (and is a problem I personally have been working on for over 20 years, with some time off for good behavior). So an interpreter is a way to reach a wide audience quickly.\nFinally, although fast compilers and slow interpreters exist, it's usually easer to make the edit-translate-go cycle faster by using an interpreter. (For some nice examples of fast compilers see the aforementioned lcc as well as Ken Thompson's go compiler. For an example of a relatively slow interpreter see GHCi.\n",
"Well, isn't one of the strengths of these languages that they are so easily scriptable? They wouldn't be if they were compiled. And on the other hand, dynamic languages are easier to intereprete than to compile.\n",
"In a compiled language, the loop you get into when making software is\n\nMake a change\nCompile changes\nTest changes\ngoto 1\n\nInterpreted languages tend to be faster to make stuff in because you get to cut out step two of that process (and when you're dealing with a large system where compile times can be upwards of two minutes, step two can add a significant amount of time).\nThis isn't necessarily the reason python|ruby designers thought of, but keep in mind that \"How efficiently does the machine run this?\" is only half the software development problem.\nIt also seems like it would be easier to compile code in a language that's interpreted naturally than it would be to add an interpreter to a language that's compiled by default.\n",
"REPL. Don't knock it 'till you've tried it. :)\n",
"By design. \nThe authors wanted something where they can write scripts into.\nPython gets compiled the first time it is executed though \n",
"Compiling Ruby at least is notoriously hard. I'm working on one, and as part of that I wrote a blog post enumerating some of the issues here. \nSpecifically, Ruby is suffering from a very unclear (i.e. non-existent) boundary between the \"read\" and \"execute\" phase of the program that makes it hard to compile efficiently. You could just emulate what the interpreter does, but then you're not going to see much speed up, so it wouldn't be worth the effort. If you want to compile it efficiently you then face a lot of additional complications to handle the extreme level of dynamism in Ruby.\nThe good news is that there are techniques for overcoming this. Self, Smalltalk and Lisp/Scheme's have dealt quite successfully with most of the same issues. But it takes time to sift through it and figure out how to make it work with Ruby. It also doesn't help that Ruby has a very convoluted grammar.\n",
"Raw compute performance is probably not a goal of most interpreted languages. Interpreted languages are typically more concerned about programmer productivity than raw speed. In most cases these languages are plenty fast enough for the tasks the languages were designed to tackle. \nGiven that, and that just about the only advantages of a compiler are type checking (difficult to do in a dynamic language) and speed, there's not much incentive to write compilers for most interpreted languages.\n"
] |
[
32,
16,
8,
6,
5,
5,
2,
2,
2,
1,
1,
1
] |
[] |
[] |
[
"compiler_construction",
"python",
"ruby"
] |
stackoverflow_0001805148_compiler_construction_python_ruby.txt
|
Q:
How to use python, PyLab, NumPy, etc for my Physics lab class over excel
I took a scientific programming course this semester that I really enjoyed and experimented with a lot. We used python, and all the related modules. I am taking a physics lab next semester and I just wanted to hear from some of you how python can help me in ways that excel can't or in ways that are better than excel's capabilities. I use Mathematica for symbolic stuff so I would use python for data purposes.
Off the top of my head, here are the related things I can do:
All of the things you would expect in a intro course (loops, arrays, slicing arrays, etc).
Reading data from a text file.
Plotting scatter, line, and bar graphs.
Learning how to plot linear regression but haven't totally figured it out.
I have done 7 of the problems on Project Euler (nothing to brag about, but it might give you a better idea of where I stand in skills).
Looking forward to hearing from some of you. You don't have to explain how to use the things you mention, I could look up the documentation.
A:
The paper Python all a scientist needs comes to mind. I hope you can make the needed transformations from Biology to Physics.
A:
Scipy will also be useful to you, as it includes many more advanced analysis tools. For example, Scipy includes a linear regression, and gets more interesting from there. Along with the other tools you mentioned, you'll probably find most of your needs covered.
Other notes on tool selection:
Mathematica is a great tool, if you can afford it. I've played around with the other options, like Sympy, and sadly, they don't come close to being as useful as Mathematica.
I can't imagine using Excel for any serious scientific work. If you're planning to continue forward using the tools that you learn in class, you might as well start with tools that offer you that potential.
A:
Don't reject Excel outright. It's still great for doing simple data analysis and plotting. Excel also has the considerable advantage of being installed on most engineer and scientist's computers, making it a lot easier to share your work with colleagues.
That said, I do use Python when Excel just won't cut it; times when I've had to:
color the points in a scatter plot based on a third column
plot a field of vectors
extract a few values from each of several thousand data files to do statistical process control
generate dozens of scatter plots over different dimensions of a large data set to find which variables are important
solve a nonlinear equation at several intermediate points of a calculation, not just as the final result.
accept variable length input from a user to define a problem
VBA in Excel can do a lot of those things too, but it becomes painful fast in such a primitive language. I dream that Microsoft will make IronPython a first-class scripting language in the next version of Excel. Until then, you might want to try Resolver One
A:
I can recall 2 presentations by Jan Martinek on EuroScipy 2008, he's PhD candidate and presented some fun experiments with Physics in the background. Abstracts are here and I'm sure he would't mind to share more if you contact him directly. Also, take a look at other presentation from EuroScipy, there are some more Physics-related ones.
|
How to use python, PyLab, NumPy, etc for my Physics lab class over excel
|
I took a scientific programming course this semester that I really enjoyed and experimented with a lot. We used python, and all the related modules. I am taking a physics lab next semester and I just wanted to hear from some of you how python can help me in ways that excel can't or in ways that are better than excel's capabilities. I use Mathematica for symbolic stuff so I would use python for data purposes.
Off the top of my head, here are the related things I can do:
All of the things you would expect in a intro course (loops, arrays, slicing arrays, etc).
Reading data from a text file.
Plotting scatter, line, and bar graphs.
Learning how to plot linear regression but haven't totally figured it out.
I have done 7 of the problems on Project Euler (nothing to brag about, but it might give you a better idea of where I stand in skills).
Looking forward to hearing from some of you. You don't have to explain how to use the things you mention, I could look up the documentation.
|
[
"The paper Python all a scientist needs comes to mind. I hope you can make the needed transformations from Biology to Physics.\n",
"Scipy will also be useful to you, as it includes many more advanced analysis tools. For example, Scipy includes a linear regression, and gets more interesting from there. Along with the other tools you mentioned, you'll probably find most of your needs covered.\nOther notes on tool selection:\n\nMathematica is a great tool, if you can afford it. I've played around with the other options, like Sympy, and sadly, they don't come close to being as useful as Mathematica.\nI can't imagine using Excel for any serious scientific work. If you're planning to continue forward using the tools that you learn in class, you might as well start with tools that offer you that potential.\n\n",
"Don't reject Excel outright. It's still great for doing simple data analysis and plotting. Excel also has the considerable advantage of being installed on most engineer and scientist's computers, making it a lot easier to share your work with colleagues.\nThat said, I do use Python when Excel just won't cut it; times when I've had to:\n\ncolor the points in a scatter plot based on a third column\nplot a field of vectors\nextract a few values from each of several thousand data files to do statistical process control\ngenerate dozens of scatter plots over different dimensions of a large data set to find which variables are important\nsolve a nonlinear equation at several intermediate points of a calculation, not just as the final result. \naccept variable length input from a user to define a problem \n\nVBA in Excel can do a lot of those things too, but it becomes painful fast in such a primitive language. I dream that Microsoft will make IronPython a first-class scripting language in the next version of Excel. Until then, you might want to try Resolver One\n",
"I can recall 2 presentations by Jan Martinek on EuroScipy 2008, he's PhD candidate and presented some fun experiments with Physics in the background. Abstracts are here and I'm sure he would't mind to share more if you contact him directly. Also, take a look at other presentation from EuroScipy, there are some more Physics-related ones.\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"matplotlib",
"numpy",
"python"
] |
stackoverflow_0001912743_matplotlib_numpy_python.txt
|
Q:
Calling a method on class A depending on type of parameter
class Class1(object):
...
class Class2(object):
...
class Class3(object):
...
class A(object):
def _methA(parm1, parm2)
...
def _methB(parm1, parm2)
...
def _methC(parm1, parm2)
...
def manager(parm1, method, params)
...
if parm1.__class__.__name__==Class1.__name__:
response = _methA(parm1, params)
elif parm1.__class__.__name__==Class2.__name__:
response = _methB(parm1, params)
elif io_source.__class__.__name__==Class3.__name__:
response = _methC(parm1, params)
else:
raise Exception, "Unsupported parm1"
...
I didn't like the way that if/elif block in manager() looked and refactored it to this:
def manager(parm1, method, params)
...
try:
response = {
Class1.__name__: lambda parm1, parms: _methA(parm1, parms),
Class2.__name__: lambda parm1, parms: _methB(parm1, parms),
Class3.__name__: lambda parm1, parms: _methC(parm1, parms)
}[parm1.__class__.__name__](parm1, parms)
except KeyError:
raise Exception, "Unsupported parm1"
But the fact that the code is still looking at class names bothers me - I really don't know how to explain why... Should it bother me?
Is there a better way to write code to call a method in class A that, depending on the class of one of its parameters, triggers the calling of different methods in A?
PS. Sorry for the contrived example, but posting the actual code would make the question even more convoluted. I tried to distill the issue to its essence...
A:
That's one of many wrong ways to implement polymorphism. You should never look at class names. Looking at class names should bother you because it means that you haven't delegated the responsibility correctly.
Move each method into the appropriate class.
class Class1(object):
def method( self, theA, params ):
theA.methA( params )
class Class2(object):
def method( self, theA, params ):
theA.methB( params )
class Class3(object):
def method( self, theA, params ):
theA.methC( params )
class A(object):
def methA(parm1, parm2)
...
def methB(parm1, parm2)
...
def methC(parm1, parm2)
...
def manager(parm1, method, params)
...
param1.method( self, params )
A:
You're trying to emulate what language geeks call "multiple dispatch", or "multimethods". The linked-to Wikipedia article has a good discussion, including Python examples.
A:
I would prefer
if isinstance(parm1, Class1):
_methA(parm1, params)
elif isinstance(parm1, Class2):
_methB(parm1, params)
elif isinstance(parm1, Class3):
_methC(parm1, params)
but this still smells of a design flaw. :)
Maybe your three classes ClassX should rather all have a single method meth(params), then your manager could just call parm1.meth(params).
A:
I usually do this when processing messages, so i don't have tons of ifs ... but it still uses the class names.
Kind of a poor man's polymorphism - but, as S.Lott said, Python supports real polymorphism so why not use it :p
class Handler(object):
# .. stuff
def dispatch(self, msg):
handlername = "on_%s" % type(msg)
return getattr(self, handlername, 'on_missing_handler')(msg)
def on_SomeClass(self, msg):
# msg is of SomeClass here ..
def on_SomeOtherClass(self, msg):
# msg is of SomeOtherClass here ..
def on_missing_handler(self, msg):
# there is no other handler for msg
|
Calling a method on class A depending on type of parameter
|
class Class1(object):
...
class Class2(object):
...
class Class3(object):
...
class A(object):
def _methA(parm1, parm2)
...
def _methB(parm1, parm2)
...
def _methC(parm1, parm2)
...
def manager(parm1, method, params)
...
if parm1.__class__.__name__==Class1.__name__:
response = _methA(parm1, params)
elif parm1.__class__.__name__==Class2.__name__:
response = _methB(parm1, params)
elif io_source.__class__.__name__==Class3.__name__:
response = _methC(parm1, params)
else:
raise Exception, "Unsupported parm1"
...
I didn't like the way that if/elif block in manager() looked and refactored it to this:
def manager(parm1, method, params)
...
try:
response = {
Class1.__name__: lambda parm1, parms: _methA(parm1, parms),
Class2.__name__: lambda parm1, parms: _methB(parm1, parms),
Class3.__name__: lambda parm1, parms: _methC(parm1, parms)
}[parm1.__class__.__name__](parm1, parms)
except KeyError:
raise Exception, "Unsupported parm1"
But the fact that the code is still looking at class names bothers me - I really don't know how to explain why... Should it bother me?
Is there a better way to write code to call a method in class A that, depending on the class of one of its parameters, triggers the calling of different methods in A?
PS. Sorry for the contrived example, but posting the actual code would make the question even more convoluted. I tried to distill the issue to its essence...
|
[
"That's one of many wrong ways to implement polymorphism. You should never look at class names. Looking at class names should bother you because it means that you haven't delegated the responsibility correctly.\nMove each method into the appropriate class.\nclass Class1(object):\n def method( self, theA, params ):\n theA.methA( params )\n\nclass Class2(object):\n def method( self, theA, params ):\n theA.methB( params )\n\nclass Class3(object):\n def method( self, theA, params ):\n theA.methC( params )\n\nclass A(object):\n def methA(parm1, parm2)\n ...\n\n def methB(parm1, parm2)\n ...\n\n def methC(parm1, parm2)\n ...\n\n def manager(parm1, method, params)\n ...\n param1.method( self, params )\n\n",
"You're trying to emulate what language geeks call \"multiple dispatch\", or \"multimethods\". The linked-to Wikipedia article has a good discussion, including Python examples.\n",
"I would prefer \nif isinstance(parm1, Class1):\n _methA(parm1, params)\nelif isinstance(parm1, Class2):\n _methB(parm1, params)\nelif isinstance(parm1, Class3):\n _methC(parm1, params)\n\nbut this still smells of a design flaw. :)\nMaybe your three classes ClassX should rather all have a single method meth(params), then your manager could just call parm1.meth(params).\n",
"I usually do this when processing messages, so i don't have tons of ifs ... but it still uses the class names. \nKind of a poor man's polymorphism - but, as S.Lott said, Python supports real polymorphism so why not use it :p\nclass Handler(object):\n # .. stuff\n\n def dispatch(self, msg):\n handlername = \"on_%s\" % type(msg)\n return getattr(self, handlername, 'on_missing_handler')(msg)\n\n def on_SomeClass(self, msg):\n # msg is of SomeClass here ..\n\n def on_SomeOtherClass(self, msg):\n # msg is of SomeOtherClass here ..\n\n def on_missing_handler(self, msg):\n # there is no other handler for msg\n\n"
] |
[
5,
1,
0,
0
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0001928806_oop_python.txt
|
Q:
cross platform usb module for python?
I was interested in doing some cross platform work with a usb device in python, any tips or recommendations on modules that can do this type of thing?
I've looked around SF and googlecode without a lot of luck.
thanks!
ct
A:
PyUSB is what you are looking for. it is a wrapper around libusb which works on linux and was ported on Windows.
|
cross platform usb module for python?
|
I was interested in doing some cross platform work with a usb device in python, any tips or recommendations on modules that can do this type of thing?
I've looked around SF and googlecode without a lot of luck.
thanks!
ct
|
[
"PyUSB is what you are looking for. it is a wrapper around libusb which works on linux and was ported on Windows. \n"
] |
[
5
] |
[] |
[] |
[
"python",
"usb"
] |
stackoverflow_0001928936_python_usb.txt
|
Q:
How do I plug a new templating language into repoze.bfg?
What do I need to implement to add a new templating language to repoze.bfg? Will the framework send my plugin absolute paths or package relative paths, or both depending?
A:
The package at http://svn.repoze.org/repoze.bfg.jinja2/trunk/repoze/bfg/jinja2/ provides add-on Jinja2 bindings for BFG. Basically, you do create a package like that, then allow folks to wire it into their systems.
There are two levels of integration. The first is just an import-level integration that would allow people to do something like:
from my.template.system import render_template_to_response
def aview(request):
return render_template_to_response('some/relative/path.myt')
Aping the render_template* methods in repoze.bfg.jina2, replacing them with analogues for your favored template system would give you this.
The other level of integration is to allow your templating system to be used as a "renderer". This permits, for example:
@bfg_view(renderer="some/relative/path.myt")
def aview(request):
return {'a':1}
To do this, ape the "renderer_factory" function in repoze.bfg.jinja2, and then get folks to add this renderer in their configuration via "config.add_renderer(renderer_factory, '.myt')" (imperatively) or by including the ZCML file you ship along with your package in their ZCML.
|
How do I plug a new templating language into repoze.bfg?
|
What do I need to implement to add a new templating language to repoze.bfg? Will the framework send my plugin absolute paths or package relative paths, or both depending?
|
[
"The package at http://svn.repoze.org/repoze.bfg.jinja2/trunk/repoze/bfg/jinja2/ provides add-on Jinja2 bindings for BFG. Basically, you do create a package like that, then allow folks to wire it into their systems.\nThere are two levels of integration. The first is just an import-level integration that would allow people to do something like:\nfrom my.template.system import render_template_to_response\ndef aview(request):\n return render_template_to_response('some/relative/path.myt')\nAping the render_template* methods in repoze.bfg.jina2, replacing them with analogues for your favored template system would give you this.\nThe other level of integration is to allow your templating system to be used as a \"renderer\". This permits, for example:\n@bfg_view(renderer=\"some/relative/path.myt\")\ndef aview(request):\n return {'a':1}\nTo do this, ape the \"renderer_factory\" function in repoze.bfg.jinja2, and then get folks to add this renderer in their configuration via \"config.add_renderer(renderer_factory, '.myt')\" (imperatively) or by including the ZCML file you ship along with your package in their ZCML.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"repoze.bfg"
] |
stackoverflow_0001926199_python_repoze.bfg.txt
|
Q:
Nested dot lookups in Django templates
According to The Django Book, Django's templating system supports nested dot lookups:
Dot lookups can be nested multiple levels deep. For instance, the following example uses {{ person.name.upper }}, which translates into a dictionary lookup (person['name']), then a method call (upper()): '{{ person.name.upper }} is {{ person.age }} years old.'
Are there goblins with this approach not widely covered in the documentation? I am having problems with nested dot lookups -- here's a minimal example:
views.py:
test = [{'foo': [1, 2, 3], 'bar': [4, 5, 6]}, {'baz': [7, 8, 9]}]
ndx = 'bar'
t = loader.get_template('meh.html')
c = Context({'test': test,
'ndx': ndx,})
return HttpResponse(t.render(c))
meh.html template:
<pre>
{{ test }}
{{ test.0 }}
{{ test.0.ndx }}
</pre>
Resulting HTML:
<pre>
[{'foo': [1, 2, 3], 'bar': [4, 5, 6]}, {'baz': [7, 8, 9]}]
{'foo': [1, 2, 3], 'bar': [4, 5, 6]}
</pre>
The nested lookup of a dictionary key within a list element returns nothing, when I expect [4, 5, 6].
J.J.
A:
I think the problem is that you are expecting ndx to be evaluated when that simply never happens. Have you tried this:
{{ test.0.bar }}
I think that will do what you're looking for.
Are there goblins with this approach...?
Sort of, but they aren't the ones you're talking about, and I don't think it's because of nesting, or at least, it doesn't get worse after you get one level deep. What I mean by this is that all lookup parameters are literals. There's no way to change that. So while you might be able to develop custom template tags and pass them literals or variables to evaluate, you're really out of luck if you want to directly access some member of a variable based on the evaluated value of another value. (You could possibly write a template tag for this, but it won't work in all desired situations and is possibly more complicated than it's worth.)
For whatever it's worth, this looks like a pretty intentional facet of the templating language. I invite you to consider how the accessor should know whether {{ foo.bar }} should be read as foo[bar] or foo['bar']. It doesn't seem possible to make a meaningful judgment without complicating the syntax and that's something that django's template design is adamant about avoiding.
A:
To expand on David's answer, Django's template system doesn't allow you to use the value of a context variable as a key. So, in your example
{{ test.0.ndx }}
is actually looking for the key "ndx" in the first item in the test context variable.
If you need this functionality, you need to implement it yourself, as a template filter. This ticket has more information, including the Django devs' reasoning behind the omission of this feature and an example implementation of the template filter you're looking for.
A:
David is right: ndx won't be evaluated to get a key, it will be used literally as a key. You can define a new template tag to do what you want, here's a simple one: http://www.djangosnippets.org/snippets/1412/
A:
I'd suggest either (and I agree with David's interpretation of your problem):
{{ test.0.bar }} # as david mentioned, or
ndx=test[0]['bar'] # in views
{{ ndx }} # in template
|
Nested dot lookups in Django templates
|
According to The Django Book, Django's templating system supports nested dot lookups:
Dot lookups can be nested multiple levels deep. For instance, the following example uses {{ person.name.upper }}, which translates into a dictionary lookup (person['name']), then a method call (upper()): '{{ person.name.upper }} is {{ person.age }} years old.'
Are there goblins with this approach not widely covered in the documentation? I am having problems with nested dot lookups -- here's a minimal example:
views.py:
test = [{'foo': [1, 2, 3], 'bar': [4, 5, 6]}, {'baz': [7, 8, 9]}]
ndx = 'bar'
t = loader.get_template('meh.html')
c = Context({'test': test,
'ndx': ndx,})
return HttpResponse(t.render(c))
meh.html template:
<pre>
{{ test }}
{{ test.0 }}
{{ test.0.ndx }}
</pre>
Resulting HTML:
<pre>
[{'foo': [1, 2, 3], 'bar': [4, 5, 6]}, {'baz': [7, 8, 9]}]
{'foo': [1, 2, 3], 'bar': [4, 5, 6]}
</pre>
The nested lookup of a dictionary key within a list element returns nothing, when I expect [4, 5, 6].
J.J.
|
[
"I think the problem is that you are expecting ndx to be evaluated when that simply never happens. Have you tried this:\n{{ test.0.bar }}\n\nI think that will do what you're looking for.\n\nAre there goblins with this approach...?\n\nSort of, but they aren't the ones you're talking about, and I don't think it's because of nesting, or at least, it doesn't get worse after you get one level deep. What I mean by this is that all lookup parameters are literals. There's no way to change that. So while you might be able to develop custom template tags and pass them literals or variables to evaluate, you're really out of luck if you want to directly access some member of a variable based on the evaluated value of another value. (You could possibly write a template tag for this, but it won't work in all desired situations and is possibly more complicated than it's worth.)\nFor whatever it's worth, this looks like a pretty intentional facet of the templating language. I invite you to consider how the accessor should know whether {{ foo.bar }} should be read as foo[bar] or foo['bar']. It doesn't seem possible to make a meaningful judgment without complicating the syntax and that's something that django's template design is adamant about avoiding.\n",
"To expand on David's answer, Django's template system doesn't allow you to use the value of a context variable as a key. So, in your example\n{{ test.0.ndx }}\n\nis actually looking for the key \"ndx\" in the first item in the test context variable.\nIf you need this functionality, you need to implement it yourself, as a template filter. This ticket has more information, including the Django devs' reasoning behind the omission of this feature and an example implementation of the template filter you're looking for.\n",
"David is right: ndx won't be evaluated to get a key, it will be used literally as a key. You can define a new template tag to do what you want, here's a simple one: http://www.djangosnippets.org/snippets/1412/\n",
"I'd suggest either (and I agree with David's interpretation of your problem):\n{{ test.0.bar }} # as david mentioned, or\n\nndx=test[0]['bar'] # in views\n{{ ndx }} # in template\n\n"
] |
[
9,
4,
1,
1
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0001929109_django_django_templates_python.txt
|
Q:
python-config ldflags on mac
I have a problem with python-config --ldflags on OS X 10.6.2.
Using my non-system python.org python install:
robin-mbp:~ robince$ which python
/Library/Frameworks/Python.framework/Versions/2.5/bin/python
robin-mbp:~ robince$ python-config --ldflags
-L/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config -ldl -lpython2.5
But if I build a c program embedding Python with the above LDFLAGS, it results in the system python being embedded. It seems -lpython2.5 is picking up the system python first, before the one in the -L path.
So far the only way I've got it to work is with
LDFLAGS=-F/ -framework Python
but when it comes to distributing I'd really like to be able to use python-config.
What is going on with the library search path that stops it working as expected? According to the man page -L paths should be searched before the default path.
Is there any option along the lines of 'forget the default search path and search only paths specified with -L' that I could add to python-config output to get it to work?
Or is there any way to extract the working -framework flags from whichever Python is on the path (that would work for whatever the user is using, ie system, python.org, macports or own built)?
A:
Sorry to answer my own question but I got an amazingly prompt reply on the pythonmac-sig mailing list where I also asked. It is a bug with current python: http://bugs.python.org/issue7541
Suggested workaround:
The easiest workaround is to open a
terminal window and execute the
following commands:
cd
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config
ln -s libpython2.5.a
libpython2.5.dylib
This will ensure that the OSX linker
knows that libpython is a shared
library and links to this library. By
default the OSX linker searches for a
.dylib on the entire linker path and
only then looks for .a files.
EDIT: Further update:
If you can add mac-specific flags in
your build system you could add
-Wl,-search_paths_first to LDFLAGS
on OSX, this ensures that the linker
looks for both .dylib and .a files in
a directory on the link path before
moving to the next directory.
|
python-config ldflags on mac
|
I have a problem with python-config --ldflags on OS X 10.6.2.
Using my non-system python.org python install:
robin-mbp:~ robince$ which python
/Library/Frameworks/Python.framework/Versions/2.5/bin/python
robin-mbp:~ robince$ python-config --ldflags
-L/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config -ldl -lpython2.5
But if I build a c program embedding Python with the above LDFLAGS, it results in the system python being embedded. It seems -lpython2.5 is picking up the system python first, before the one in the -L path.
So far the only way I've got it to work is with
LDFLAGS=-F/ -framework Python
but when it comes to distributing I'd really like to be able to use python-config.
What is going on with the library search path that stops it working as expected? According to the man page -L paths should be searched before the default path.
Is there any option along the lines of 'forget the default search path and search only paths specified with -L' that I could add to python-config output to get it to work?
Or is there any way to extract the working -framework flags from whichever Python is on the path (that would work for whatever the user is using, ie system, python.org, macports or own built)?
|
[
"Sorry to answer my own question but I got an amazingly prompt reply on the pythonmac-sig mailing list where I also asked. It is a bug with current python: http://bugs.python.org/issue7541\nSuggested workaround:\n\nThe easiest workaround is to open a\n terminal window and execute the\n following commands:\ncd\n /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config\n ln -s libpython2.5.a\n libpython2.5.dylib\nThis will ensure that the OSX linker\n knows that libpython is a shared\n library and links to this library. By\n default the OSX linker searches for a\n .dylib on the entire linker path and\n only then looks for .a files.\n\nEDIT: Further update:\n\nIf you can add mac-specific flags in\n your build system you could add\n -Wl,-search_paths_first to LDFLAGS\n on OSX, this ensures that the linker\n looks for both .dylib and .a files in\n a directory on the link path before\n moving to the next directory.\n\n"
] |
[
2
] |
[] |
[] |
[
"ld",
"linker",
"macos",
"python"
] |
stackoverflow_0001929180_ld_linker_macos_python.txt
|
Q:
Searching for text in a file
hi there got a couple of probs, say in my text file i have:
abase
abased
abasement
abasements
abases
This coding below is meant to find a word in a file and print all the lines to the end of the file. But it doesnt it only prints out my search term and not the rest of the file.
search_term = r'\b%s\b' % search_term
for line in open(f, 'r'):
if re.match(search_term, line):
if search_term in line:
f = 1
if f: print line,
Say i searched for abasement, i would like the output to be:
abasement
abasements
abases
My final problem is, i would like to search a file a print the lines my search term is in and a number of lines befer and after the searchterm. If i searched the text example above with 'abasement' and i defined the number of lines to print either side as 1 my output would be:
abased
abasement
abasements
numb = ' the number of lines to print either side of the search line '
search_term = 'what i search'
f=open("file")
d={}
for n,line in enumerate(f):
d[n%numb]=line.rstrip()
if search_term in line:
for i in range(n+1,n+1+numb):
print d[i%numb]
for i in range(1,numb):
print f.next().rstrip()
A:
For the first part of the question, unindent your if f: print line,. Otherwise, you're only trying to print when the regex matches.
It's not clear to me what your question is in the second part. I see what you're trying to do, and your code, but you've not indicated how it misbehaves.
A:
For the first part the algorithm goes like this (in pseudo code):
found = False
for every line in the file:
if line contains search term:
found = True
if found:
print line
|
Searching for text in a file
|
hi there got a couple of probs, say in my text file i have:
abase
abased
abasement
abasements
abases
This coding below is meant to find a word in a file and print all the lines to the end of the file. But it doesnt it only prints out my search term and not the rest of the file.
search_term = r'\b%s\b' % search_term
for line in open(f, 'r'):
if re.match(search_term, line):
if search_term in line:
f = 1
if f: print line,
Say i searched for abasement, i would like the output to be:
abasement
abasements
abases
My final problem is, i would like to search a file a print the lines my search term is in and a number of lines befer and after the searchterm. If i searched the text example above with 'abasement' and i defined the number of lines to print either side as 1 my output would be:
abased
abasement
abasements
numb = ' the number of lines to print either side of the search line '
search_term = 'what i search'
f=open("file")
d={}
for n,line in enumerate(f):
d[n%numb]=line.rstrip()
if search_term in line:
for i in range(n+1,n+1+numb):
print d[i%numb]
for i in range(1,numb):
print f.next().rstrip()
|
[
"For the first part of the question, unindent your if f: print line,. Otherwise, you're only trying to print when the regex matches.\nIt's not clear to me what your question is in the second part. I see what you're trying to do, and your code, but you've not indicated how it misbehaves.\n",
"For the first part the algorithm goes like this (in pseudo code):\nfound = False\nfor every line in the file:\n if line contains search term:\n found = True\n if found:\n print line\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"file",
"python",
"search"
] |
stackoverflow_0001929432_file_python_search.txt
|
Q:
Reading the same file multiple times in Python
I need to download a zip archive of text files, dispatch each text file in the archive to other handlers for processing, and finally write the unzipped text file to disk.
I have the following code. It uses multiple open/close on the same file, which does not seem elegant. How do I make it more elegant and efficient?
zipped = urllib.urlopen('www.abc.com/xyz.zip')
buf = cStringIO.StringIO(zipped.read())
zipped.close()
unzipped = zipfile.ZipFile(buf, 'r')
for f_info in unzipped.infolist():
logfile = unzipped.open(f_info)
handler1(logfile)
logfile.close() ## Cannot seek(0). The file like obj does not support seek()
logfile = unzipped.open(f_info)
handler2(logfile)
logfile.close()
unzipped.extract(f_info)
A:
Your answer is in your example code. Just use StringIO to buffer the logfile:
zipped = urllib.urlopen('www.abc.com/xyz.zip')
buf = cStringIO.StringIO(zipped.read())
zipped.close()
unzipped = zipfile.ZipFile(buf, 'r')
for f_info in unzipped.infolist():
logfile = unzipped.open(f_info)
# Here's where we buffer:
logbuffer = cStringIO.StringIO(logfile.read())
logfile.close()
for handler in [handler1, handler2]:
handler(logbuffer)
# StringIO objects support seek():
logbuffer.seek(0)
unzipped.extract(f_info)
A:
You could say something like:
handler_dispatch(logfile)
and
def handler_dispatch(file):
for line in file:
handler1(line)
handler2(line)
or even make it more dynamic by constructing a Handler class with multiple handlerN functions, and applying each of them inside handler_dispatch. Like
class Handler:
def __init__(self:)
self.handlers = []
def add_handler(handler):
self.handlers.append(handler)
def handler_dispatch(self, file):
for line in file:
for handler in self.handlers:
handler.handle(line)
A:
Open the zip file once, loop through all the names, extract the file for each name and process it, then write it to disk.
Like so:
for f_info in unzipped.info_list():
file = unzipped.open(f_info)
data = file.read()
# If you need a file like object, wrap it in a cStringIO
fobj = cStringIO.StringIO(data)
handler1(fobj)
handler2(fobj)
with open(filename,"w") as fp:
fp.write(data)
You get the idea
|
Reading the same file multiple times in Python
|
I need to download a zip archive of text files, dispatch each text file in the archive to other handlers for processing, and finally write the unzipped text file to disk.
I have the following code. It uses multiple open/close on the same file, which does not seem elegant. How do I make it more elegant and efficient?
zipped = urllib.urlopen('www.abc.com/xyz.zip')
buf = cStringIO.StringIO(zipped.read())
zipped.close()
unzipped = zipfile.ZipFile(buf, 'r')
for f_info in unzipped.infolist():
logfile = unzipped.open(f_info)
handler1(logfile)
logfile.close() ## Cannot seek(0). The file like obj does not support seek()
logfile = unzipped.open(f_info)
handler2(logfile)
logfile.close()
unzipped.extract(f_info)
|
[
"Your answer is in your example code. Just use StringIO to buffer the logfile:\nzipped = urllib.urlopen('www.abc.com/xyz.zip')\nbuf = cStringIO.StringIO(zipped.read())\nzipped.close()\nunzipped = zipfile.ZipFile(buf, 'r')\nfor f_info in unzipped.infolist():\n logfile = unzipped.open(f_info)\n # Here's where we buffer:\n logbuffer = cStringIO.StringIO(logfile.read())\n logfile.close()\n\n for handler in [handler1, handler2]:\n handler(logbuffer)\n # StringIO objects support seek():\n logbuffer.seek(0)\n\n unzipped.extract(f_info)\n\n",
"You could say something like:\nhandler_dispatch(logfile)\n\nand\ndef handler_dispatch(file):\n for line in file:\n handler1(line)\n handler2(line)\n\nor even make it more dynamic by constructing a Handler class with multiple handlerN functions, and applying each of them inside handler_dispatch. Like\nclass Handler:\n def __init__(self:)\n self.handlers = []\n\n def add_handler(handler):\n self.handlers.append(handler)\n\n def handler_dispatch(self, file):\n for line in file:\n for handler in self.handlers:\n handler.handle(line)\n\n",
"Open the zip file once, loop through all the names, extract the file for each name and process it, then write it to disk.\nLike so:\nfor f_info in unzipped.info_list():\n file = unzipped.open(f_info)\n data = file.read()\n # If you need a file like object, wrap it in a cStringIO\n fobj = cStringIO.StringIO(data)\n handler1(fobj)\n handler2(fobj)\n with open(filename,\"w\") as fp:\n fp.write(data)\n\nYou get the idea\n"
] |
[
5,
1,
1
] |
[] |
[] |
[
"file_io",
"python",
"unzip",
"zip"
] |
stackoverflow_0001929662_file_io_python_unzip_zip.txt
|
Q:
Serializing resultset returned from mysqldb in python
Can anyone please help me in serializing resultset returned using mysqldb in python?
I get typeerror: datetime.date(2007, 11, 15) is not JSON serializable
What is the best way to do serialize into Json object in python?
I am using json.dumps(resultset) to serialize resultset...
A:
Set the "default" function passed to json.dump:
>>> d=datetime.datetime.now()
>>> json.dumps(d,default=str)
'"2009-12-18 14:22:21.405095"'
A:
You can use rfc3339 strings instead:
json.dump(datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))
See: JSON datetime between Python and JavaScript
A:
Serializing Django objects (Django Docs)
Serializing Python Objects (Dive Into Python 3)
|
Serializing resultset returned from mysqldb in python
|
Can anyone please help me in serializing resultset returned using mysqldb in python?
I get typeerror: datetime.date(2007, 11, 15) is not JSON serializable
What is the best way to do serialize into Json object in python?
I am using json.dumps(resultset) to serialize resultset...
|
[
"Set the \"default\" function passed to json.dump:\n>>> d=datetime.datetime.now()\n>>> json.dumps(d,default=str)\n'\"2009-12-18 14:22:21.405095\"'\n\n",
"You can use rfc3339 strings instead:\n json.dump(datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))\n\nSee: JSON datetime between Python and JavaScript\n",
"Serializing Django objects (Django Docs)\nSerializing Python Objects (Dive Into Python 3)\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"django",
"json",
"mysql",
"python"
] |
stackoverflow_0001899110_django_json_mysql_python.txt
|
Q:
Best python XMPP / Jabber client library?
What are your experiences with Python Jabber / XMPP client libraries?
What do you recommend?
A:
It depends what license you can use. Some popular libraries are GPL which can cause serious issues if you need to use it for work, especially if you need to keep proprietary extensions. The LGPL libraries are a little less popular, I think, but you have more flexibility with what you can use them for.
I'd once looked at using twisted directly for some simple XMPP scripting but the documentation was literally non-existant. Like, I opened a published twisted reference manual and it didn't include xmpp or jabbber at all. Maybe they've fixed that now.
MIT libraries.
slixmpp is a friendly fork of sleekxmpp. It has removed all threads and is for python 3.7+.
sleekxmpp was pretty popular and was used for
examples in Peter Saint-Andre's XMPP
book from O'Reilly. It has been depricated in favor of slixmpp.
GPL libraries.
xmpppy was used by gajim from 2005-2014, and began as a forked jabberpy. Also lives at xmpppy.
nbxmpp forked xmpppy, and is used by gajim. It requires python 3.7+ and is actively maintained.
LPGL libraries.
aioxmpp is an asyncio-based python 3.4+ library.
pyxmpp is abandoned in favor of pyxmpp2. It uses libxml2 internally for xml parsing.
pyxmpp2 is the next version of pyxmpp, runs on python 2.7 and 3.3, and removes the libxml2 requirement. Like many, it requires dnspython.
jabberpy is the original and is thoroughly unmaintained.
Other libraries.
Wokkel, mentioned in another post. That's a new one for me, based on twisted.
A:
All of my best XMPP work has been using wokkel.
Couple examples:
twitterspy
whatsup
|
Best python XMPP / Jabber client library?
|
What are your experiences with Python Jabber / XMPP client libraries?
What do you recommend?
|
[
"It depends what license you can use. Some popular libraries are GPL which can cause serious issues if you need to use it for work, especially if you need to keep proprietary extensions. The LGPL libraries are a little less popular, I think, but you have more flexibility with what you can use them for.\nI'd once looked at using twisted directly for some simple XMPP scripting but the documentation was literally non-existant. Like, I opened a published twisted reference manual and it didn't include xmpp or jabbber at all. Maybe they've fixed that now.\nMIT libraries.\n\nslixmpp is a friendly fork of sleekxmpp. It has removed all threads and is for python 3.7+.\nsleekxmpp was pretty popular and was used for\nexamples in Peter Saint-Andre's XMPP\nbook from O'Reilly. It has been depricated in favor of slixmpp.\n\nGPL libraries.\n\nxmpppy was used by gajim from 2005-2014, and began as a forked jabberpy. Also lives at xmpppy.\nnbxmpp forked xmpppy, and is used by gajim. It requires python 3.7+ and is actively maintained.\n\nLPGL libraries.\n\naioxmpp is an asyncio-based python 3.4+ library.\npyxmpp is abandoned in favor of pyxmpp2. It uses libxml2 internally for xml parsing.\npyxmpp2 is the next version of pyxmpp, runs on python 2.7 and 3.3, and removes the libxml2 requirement. Like many, it requires dnspython.\njabberpy is the original and is thoroughly unmaintained.\n\nOther libraries.\n\nWokkel, mentioned in another post. That's a new one for me, based on twisted.\n\n",
"All of my best XMPP work has been using wokkel.\nCouple examples:\n\ntwitterspy\nwhatsup\n\n"
] |
[
76,
7
] |
[] |
[] |
[
"chat",
"google_talk",
"python",
"xmpp"
] |
stackoverflow_0001901828_chat_google_talk_python_xmpp.txt
|
Q:
Prevent RegEx Hang on Large Matches
This is a great regular expression for dates... However it hangs indefinitely on this one page I tried... I wanted to try this page ( http://pleac.sourceforge.net/pleac_python/datesandtimes.html ) for the fact that it does have lots of dates on it and I want to grab all of them. I don't understand why it is hanging when it doesn't on other pages... Why is my regexp hanging and/or how could I clean it up to make it better/efficient ?
Python Code:
monthnames = "(?:Jan\w*|Feb\w*|Mar\w*|Apr\w*|May|Jun\w?|Jul\w?|Aug\w*|Sep\w*|Oct\w*|Nov(?:ember)?|Dec\w*)"
pattern1 = re.compile(r"(\d{1,4}[\/\\\-]+\d{1,2}[\/\\\-]+\d{2,4})")
pattern4 = re.compile(r"(?:[\d]*[\,\.\ \-]+)*%s(?:[\,\.\ \-]+[\d]+[stndrh]*)+[:\d]*[\ ]?(PM)?(AM)?([\ \-\+\d]{4,7}|[UTCESTGMT\ ]{2,4})*"%monthnames, re.I)
patterns = [pattern4, pattern1]
for pattern in patterns:
print re.findall(pattern, s)
btw... when i say im trying it against this site.. I'm trying it against the webpage source.
A:
You should read Mastering Regular Expressions. The problem is:
(?:[\d]*[\,\.\ \-]+)*
which takes exponential time. Try using:
(?:[\d,. \-]*[,. \-])?
which should match the same things but take linear time. Having checked your example, this does indeed speed things up.
You also appear to have accidentally introduced capturing groups into your pattern at some point: change e.g. (AM) to (?:AM) to fix that. This gets us the following output from your example above:
[' Aug 6 20:43:20 2003', ' Mar 14 06:02:55 1973', ' March 14 06:02:55 AM 1973', ' Jun 16 20:18:03 1981']
['2003-08-06', '2003-08-07', '2003-07-23', '1973-01-18', '3/14/1973', '16/6/1981', '16/6/1981', '16/6/1981', '16/6/1981', '08/08/2003']
To get into details (which the book I reference is very good at), * and + work (in NFAs like python's re) rather like a loop. The original pattern's inner loop will match against a long string of digits, but when the subsequent pattern fails to match, it will "give them up" one at a time. The outer loop will then rerun the inner loop on the remaining pattern, and of course it will immediately grab the digits again. Each time one instance of the inner loop relinquishes a digit, a new copy will be summoned to grab it again. Eventually, once the engine has gone through every possible way of splitting that string of digits (an exponential number of possibilities), it will move the starting point forwards one character...and try again.
On another note, your pattern looks a bit bonkers ;)
A:
The Python regular expression evaluator can take a long time. Unfortunately, it runs in a worst case exponential time.
I assume your "s" contains a copy of the entire page. If so, that could cause very long backtracks in the regular expression evaluator. Perhaps you should break the page up into smaller chunks, and run them individually through your regular expression. You could use an HTML parser like beautifulsoup and run the regular expression on each text node individually. This might reduce the runtime.
A:
The way the regex is written will cause a lot of backtracking. In addition to the tip about running it on smaller chunks of text, you can also have a simpler (and thus faster) regex that filters out text that cannot match.
A:
First, you should read up on what an r"" string means: you only have to put in backslashes where you really want backslashes, so your regex should really just be:
monthnames = "(?:Jan\w*|Feb\w*|Mar\w*|Apr\w*|May|Jun\w?|Jul\w?|Aug\w*|Sep\w*|Oct\w*|Nov(?:ember)?|Dec\w*)"
pattern1 = re.compile(r"(\d{1,4}[-/]+\d{1,2}[-/]+\d{2,4})")
pattern4 = re.compile(r"(?:\d*[,. -]+)*%s(?:[,. -]+\d+[stndrh]*)+[:\d]*[ ]?(PM)?(AM)?([ -+\d]{4,7}|[UTCESTGMT ]{2,4})*"%monthnames, re.I)
As to your real problem, Python doesn't do well with a * nested inside a *. Change pattern4 to this (the first \d* becomes \d+):
pattern4 = re.compile(r"(?:\d+[,. -]+)*%s(?:[,. -]+\d+[stndrh]*)+[:\d]*[ ]?(PM)?(AM)?([ -+\d]{4,7}|[UTCESTGMT ]{2,4})*"%monthnames, re.I)
and the regex returns quickly, printing this:
[('', '', '2003'), ('', '', '1973'), ('', 'AM', ' 1973'), ('', '', '1981"')]
['2003-08-06', '2003-08-07', '2003-07-23', '1973-01-18', '3/14/1973', '16/6/1981', '16/6/1981', '16/6/1981', '16/6/1981'
, '08/08/2003']
though I don't know if that's what you wanted.
|
Prevent RegEx Hang on Large Matches
|
This is a great regular expression for dates... However it hangs indefinitely on this one page I tried... I wanted to try this page ( http://pleac.sourceforge.net/pleac_python/datesandtimes.html ) for the fact that it does have lots of dates on it and I want to grab all of them. I don't understand why it is hanging when it doesn't on other pages... Why is my regexp hanging and/or how could I clean it up to make it better/efficient ?
Python Code:
monthnames = "(?:Jan\w*|Feb\w*|Mar\w*|Apr\w*|May|Jun\w?|Jul\w?|Aug\w*|Sep\w*|Oct\w*|Nov(?:ember)?|Dec\w*)"
pattern1 = re.compile(r"(\d{1,4}[\/\\\-]+\d{1,2}[\/\\\-]+\d{2,4})")
pattern4 = re.compile(r"(?:[\d]*[\,\.\ \-]+)*%s(?:[\,\.\ \-]+[\d]+[stndrh]*)+[:\d]*[\ ]?(PM)?(AM)?([\ \-\+\d]{4,7}|[UTCESTGMT\ ]{2,4})*"%monthnames, re.I)
patterns = [pattern4, pattern1]
for pattern in patterns:
print re.findall(pattern, s)
btw... when i say im trying it against this site.. I'm trying it against the webpage source.
|
[
"You should read Mastering Regular Expressions. The problem is:\n(?:[\\d]*[\\,\\.\\ \\-]+)*\n\nwhich takes exponential time. Try using:\n(?:[\\d,. \\-]*[,. \\-])?\n\nwhich should match the same things but take linear time. Having checked your example, this does indeed speed things up.\nYou also appear to have accidentally introduced capturing groups into your pattern at some point: change e.g. (AM) to (?:AM) to fix that. This gets us the following output from your example above:\n[' Aug 6 20:43:20 2003', ' Mar 14 06:02:55 1973', ' March 14 06:02:55 AM 1973', ' Jun 16 20:18:03 1981']\n['2003-08-06', '2003-08-07', '2003-07-23', '1973-01-18', '3/14/1973', '16/6/1981', '16/6/1981', '16/6/1981', '16/6/1981', '08/08/2003']\n\nTo get into details (which the book I reference is very good at), * and + work (in NFAs like python's re) rather like a loop. The original pattern's inner loop will match against a long string of digits, but when the subsequent pattern fails to match, it will \"give them up\" one at a time. The outer loop will then rerun the inner loop on the remaining pattern, and of course it will immediately grab the digits again. Each time one instance of the inner loop relinquishes a digit, a new copy will be summoned to grab it again. Eventually, once the engine has gone through every possible way of splitting that string of digits (an exponential number of possibilities), it will move the starting point forwards one character...and try again.\nOn another note, your pattern looks a bit bonkers ;)\n",
"The Python regular expression evaluator can take a long time. Unfortunately, it runs in a worst case exponential time.\nI assume your \"s\" contains a copy of the entire page. If so, that could cause very long backtracks in the regular expression evaluator. Perhaps you should break the page up into smaller chunks, and run them individually through your regular expression. You could use an HTML parser like beautifulsoup and run the regular expression on each text node individually. This might reduce the runtime.\n",
"The way the regex is written will cause a lot of backtracking. In addition to the tip about running it on smaller chunks of text, you can also have a simpler (and thus faster) regex that filters out text that cannot match.\n",
"First, you should read up on what an r\"\" string means: you only have to put in backslashes where you really want backslashes, so your regex should really just be:\nmonthnames = \"(?:Jan\\w*|Feb\\w*|Mar\\w*|Apr\\w*|May|Jun\\w?|Jul\\w?|Aug\\w*|Sep\\w*|Oct\\w*|Nov(?:ember)?|Dec\\w*)\"\n\npattern1 = re.compile(r\"(\\d{1,4}[-/]+\\d{1,2}[-/]+\\d{2,4})\")\n\npattern4 = re.compile(r\"(?:\\d*[,. -]+)*%s(?:[,. -]+\\d+[stndrh]*)+[:\\d]*[ ]?(PM)?(AM)?([ -+\\d]{4,7}|[UTCESTGMT ]{2,4})*\"%monthnames, re.I)\n\nAs to your real problem, Python doesn't do well with a * nested inside a *. Change pattern4 to this (the first \\d* becomes \\d+):\npattern4 = re.compile(r\"(?:\\d+[,. -]+)*%s(?:[,. -]+\\d+[stndrh]*)+[:\\d]*[ ]?(PM)?(AM)?([ -+\\d]{4,7}|[UTCESTGMT ]{2,4})*\"%monthnames, re.I)\n\nand the regex returns quickly, printing this:\n[('', '', '2003'), ('', '', '1973'), ('', 'AM', ' 1973'), ('', '', '1981\"')]\n['2003-08-06', '2003-08-07', '2003-07-23', '1973-01-18', '3/14/1973', '16/6/1981', '16/6/1981', '16/6/1981', '16/6/1981'\n, '08/08/2003']\n\nthough I don't know if that's what you wanted.\n"
] |
[
5,
0,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001930135_python_regex.txt
|
Q:
PyCrypto with Py2exe
Can you use PyCrypto with py2exe? Can you use any arbitrary library for that matter with py2exe?
Thanks,
Chris
A:
I have yet to find anything that py2exe can't actually handle, though from time to time it has lagged developments in Python itself. (For example, for a while it had trouble with the new absolute imports stuff, though I believe that's been resolved. It also wasn't so good with eggs, but I don't know if that has been resolved.)
I don't see why you'd have any problem using it with PyCrypto either, as that package has nothing special in it compared to many others that work fine. It's a bunch of pure Python plus a handful of .pyd files, and certainly py2exe deals well with those. Here's an example, using code pulled from the PyCrypto site:
from Crypto.Cipher import DES
def main():
obj=DES.new('abcdefgh', DES.MODE_ECB)
plain='Thvqb ina Ebffhz vf n fcnpr nyvra.'.encode('rot13')
ciph=obj.encrypt(plain+' ' * 6)
print obj.decrypt(ciph)
if __name__ == '__main__':
import sys
if sys.argv[1:] == ['py2exe']:
from distutils.core import setup
import py2exe
setup(console=[dict(script='script.py')],
options={'py2exe': {'excludes': ['Tkinter'] }})
else:
main()
Save as script.py, build using script py2exe, and run with dist\script to see some output.
|
PyCrypto with Py2exe
|
Can you use PyCrypto with py2exe? Can you use any arbitrary library for that matter with py2exe?
Thanks,
Chris
|
[
"I have yet to find anything that py2exe can't actually handle, though from time to time it has lagged developments in Python itself. (For example, for a while it had trouble with the new absolute imports stuff, though I believe that's been resolved. It also wasn't so good with eggs, but I don't know if that has been resolved.)\nI don't see why you'd have any problem using it with PyCrypto either, as that package has nothing special in it compared to many others that work fine. It's a bunch of pure Python plus a handful of .pyd files, and certainly py2exe deals well with those. Here's an example, using code pulled from the PyCrypto site:\nfrom Crypto.Cipher import DES\n\ndef main():\n obj=DES.new('abcdefgh', DES.MODE_ECB)\n plain='Thvqb ina Ebffhz vf n fcnpr nyvra.'.encode('rot13')\n ciph=obj.encrypt(plain+' ' * 6)\n print obj.decrypt(ciph)\n\nif __name__ == '__main__':\n import sys\n if sys.argv[1:] == ['py2exe']:\n from distutils.core import setup\n import py2exe\n setup(console=[dict(script='script.py')],\n options={'py2exe': {'excludes': ['Tkinter'] }})\n\n else:\n main()\n\nSave as script.py, build using script py2exe, and run with dist\\script to see some output.\n"
] |
[
1
] |
[] |
[] |
[
"py2exe",
"python"
] |
stackoverflow_0001930539_py2exe_python.txt
|
Q:
Robocopy error code 6 ''The handle is invalid'
I have written a python script that uses subprocess to call robocopy to sync log files from a remote host.
Like so:
program = 'Robocopy'
options = ['/S']
args.append(program)
args.append(options)
args.append('\\\\%s\%s' % (hostname, source_path))
args.append(local_path)
proc = subprocess.Popen(args=args, shell=True, stdout=cmd_log, stderr=error_log)
where source_path is the path on the remote host and local_path is the path on local host (both UNC paths).
The code typically runs in a daemon process and gets kicked off every few hours. It is also possible to runs this code directly on the command prompt. It appears that sometimes when it is running in a daemon process I get an error from Robocopy:
Error code 6: 'The handle is invalid'
But when I run this on the command prompt I get no errors. From what I found in a web search this may be related to file handles that are already open on the files being transferred. Does anyone have more information on this error and ways to avoid it?
A:
Google searches for "robocopy handle is invalid" suggest you might find success by using the /b option for "backup mode".
Even if that doesn't work, I'd suggest adding code to output the filenames as they are being copied (or log it), and once you've identified the specific failing file, you may well also realize what the problem is.
|
Robocopy error code 6 ''The handle is invalid'
|
I have written a python script that uses subprocess to call robocopy to sync log files from a remote host.
Like so:
program = 'Robocopy'
options = ['/S']
args.append(program)
args.append(options)
args.append('\\\\%s\%s' % (hostname, source_path))
args.append(local_path)
proc = subprocess.Popen(args=args, shell=True, stdout=cmd_log, stderr=error_log)
where source_path is the path on the remote host and local_path is the path on local host (both UNC paths).
The code typically runs in a daemon process and gets kicked off every few hours. It is also possible to runs this code directly on the command prompt. It appears that sometimes when it is running in a daemon process I get an error from Robocopy:
Error code 6: 'The handle is invalid'
But when I run this on the command prompt I get no errors. From what I found in a web search this may be related to file handles that are already open on the files being transferred. Does anyone have more information on this error and ways to avoid it?
|
[
"Google searches for \"robocopy handle is invalid\" suggest you might find success by using the /b option for \"backup mode\".\nEven if that doesn't work, I'd suggest adding code to output the filenames as they are being copied (or log it), and once you've identified the specific failing file, you may well also realize what the problem is.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"robocopy",
"subprocess"
] |
stackoverflow_0001928855_python_robocopy_subprocess.txt
|
Q:
Some other filter
I have a problem. I've got a string which looks like "var1,var2" and table in database which contains some records looks like "var1, var3", "var3", "var2,var3" an I want to filter them by splitting first string. When any of my string-variable fits to database-variable django will display them. So, when I have string-var like this:"var1,var2" and database-variables like: "var1,var3", "var3", "var2,var3" django will display "var1,var3", "var2,var3".
How can I do that? When I straightly filter by Data.objects.filter, Django displays only that records who contains all of string-variables.
Sorry for my poor English, hope everyone understood.
Cheers.
A:
I htink that what you want is OR lookups. Try this:
var_string = 'var1,var2'
vars = var_string.split(',')
result = MyModel.objects.none()
for var in vars:
result |= MyModel.objects.filter(name__icontains=var.strip())
return result
You might want to put this in a Manager for reusability. But personally, I'd try to find out why are names stored like that on the database and fix that.
A:
Rather than this approach, you might have better luck adding a foreign key or a grouping number to your model so you can use the Database to do the splitting for you.
So instead of this:
class MyModel(models.Model):
vars = models.CharField(max_length=200)
m = MyModel(vars="var1,var2")
m.save()
m = MyModel(vars="var2,var3")
m.save()
Do this:
class MyModel(models.Model):
group = models.IntegerField()
var = models.CharField(max_length=200)
m = MyModel(group=1, var="var1")
m.save()
m = MyModel(group=1, var="var2")
m.save()
m = MyModel(group=2, var="var2")
m.save()
m = MyModel(group=2, var="var3")
m.save()
Then you can query like this:
MyModel.objects.filter(group=1)
Or like this:
MyModel.objects.filter(var="var1")
|
Some other filter
|
I have a problem. I've got a string which looks like "var1,var2" and table in database which contains some records looks like "var1, var3", "var3", "var2,var3" an I want to filter them by splitting first string. When any of my string-variable fits to database-variable django will display them. So, when I have string-var like this:"var1,var2" and database-variables like: "var1,var3", "var3", "var2,var3" django will display "var1,var3", "var2,var3".
How can I do that? When I straightly filter by Data.objects.filter, Django displays only that records who contains all of string-variables.
Sorry for my poor English, hope everyone understood.
Cheers.
|
[
"I htink that what you want is OR lookups. Try this:\nvar_string = 'var1,var2'\nvars = var_string.split(',')\n\nresult = MyModel.objects.none()\n\nfor var in vars:\n result |= MyModel.objects.filter(name__icontains=var.strip())\n\nreturn result\n\nYou might want to put this in a Manager for reusability. But personally, I'd try to find out why are names stored like that on the database and fix that.\n",
"Rather than this approach, you might have better luck adding a foreign key or a grouping number to your model so you can use the Database to do the splitting for you. \nSo instead of this: \nclass MyModel(models.Model): \n vars = models.CharField(max_length=200)\n\nm = MyModel(vars=\"var1,var2\")\nm.save()\nm = MyModel(vars=\"var2,var3\")\nm.save()\n\nDo this: \nclass MyModel(models.Model):\n group = models.IntegerField()\n var = models.CharField(max_length=200)\n\nm = MyModel(group=1, var=\"var1\")\nm.save()\nm = MyModel(group=1, var=\"var2\")\nm.save()\n\nm = MyModel(group=2, var=\"var2\")\nm.save()\nm = MyModel(group=2, var=\"var3\")\nm.save()\n\nThen you can query like this: \nMyModel.objects.filter(group=1)\n\nOr like this: \nMyModel.objects.filter(var=\"var1\")\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001930120_django_python.txt
|
Q:
In python (django) how can I stop access to a global dictionary data structure when it's being updated?
In django when updating a global dictionary data structure I want to lock access to it by different request. I am planning to have a wrapper function to update and access and synchronize it. Coming from Java background! Any pointers?
A:
Extending the LockableDict example somewhat, to make it a little more robust you can use the real Lock:
class LockableDict(dict):
def __init__(self, *args, **kwargs):
from threading import Lock
self.lock = Lock()
dict.__init__(self, *args, **kwargs)
@property
def locked(self):
return self.lock.locked()
def lock(self):
self.lock.acquire()
def unlock(self):
self.lock.release()
# and then
my_dict = LockableDict({1:2, 3:4})
my_dict.lock()
# do modifications
my_dict.unlock()
A:
One fun option is to create a Lockable DIctionary class that will lock itself based on teh exection frame of the caller. :-)
Python introspection allows this - and depending on you r needs, this might fit -
(you would have to catch the exception raised in the places you want to use the valu, though --
I don' t use Django, so I don't know if the rewquests use threads -- if so, (and not asynchronous response over a single thread for all requests), you can replace the Exception raised for a while - sleep - retry loop.
from inspect import stack
class DictLocked(Exception):
pass
class LockableDict(dict):
def __init__(self, *args, **kw):
dict.__init__(self, *args, **kw)
self.locked = False
self.locker = None
def start_update(self):
print stack()
self.locked = True
#Holds the code frame responsible for locking
self.locker = stack()[1][0]
def finish_update(self):
self.locked = False
def __getitem__(self, item):
print stack()
if self.locked:
if stack()[1][0] != self.locker:
raise DictLocked("Dictionary locked")
return dict.__getitem__(self, item)
def __setitem__(self, item, value):
if self.locked:
if stack()[1][0] != self.locker:
raise DictLocked("Dictionary locked")
return dict.__setitem__(self, item, value)
|
In python (django) how can I stop access to a global dictionary data structure when it's being updated?
|
In django when updating a global dictionary data structure I want to lock access to it by different request. I am planning to have a wrapper function to update and access and synchronize it. Coming from Java background! Any pointers?
|
[
"Extending the LockableDict example somewhat, to make it a little more robust you can use the real Lock:\nclass LockableDict(dict):\n def __init__(self, *args, **kwargs):\n from threading import Lock\n self.lock = Lock()\n dict.__init__(self, *args, **kwargs)\n\n @property\n def locked(self):\n return self.lock.locked()\n\n def lock(self):\n self.lock.acquire()\n\n def unlock(self):\n self.lock.release()\n\n# and then\nmy_dict = LockableDict({1:2, 3:4})\nmy_dict.lock()\n# do modifications\nmy_dict.unlock()\n\n",
"One fun option is to create a Lockable DIctionary class that will lock itself based on teh exection frame of the caller. :-)\nPython introspection allows this - and depending on you r needs, this might fit - \n(you would have to catch the exception raised in the places you want to use the valu, though -- \nI don' t use Django, so I don't know if the rewquests use threads -- if so, (and not asynchronous response over a single thread for all requests), you can replace the Exception raised for a while - sleep - retry loop.\nfrom inspect import stack\n\nclass DictLocked(Exception):\n pass\n\nclass LockableDict(dict):\n def __init__(self, *args, **kw):\n dict.__init__(self, *args, **kw)\n self.locked = False\n self.locker = None\n def start_update(self):\n print stack()\n self.locked = True\n #Holds the code frame responsible for locking\n self.locker = stack()[1][0]\n def finish_update(self):\n self.locked = False\n\n def __getitem__(self, item):\n print stack()\n if self.locked:\n if stack()[1][0] != self.locker:\n raise DictLocked(\"Dictionary locked\")\n return dict.__getitem__(self, item)\n\n def __setitem__(self, item, value):\n if self.locked:\n if stack()[1][0] != self.locker:\n raise DictLocked(\"Dictionary locked\")\n return dict.__setitem__(self, item, value)\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001927887_django_python.txt
|
Q:
show html with pyqt4
print "hellp world" :)
i want to ask you if exist a function or class hwo can show the html code like the browser's jobe
thx
A:
There is QtWebKit Module within Qt. It incorporates webkit rendering engine. Whereas you can get access to Qt classes using python binding, you can use Qt official manual as help. Qt designer is also included into pyqt - you can try using it to design your application's GUI (I'm almost sure you'll be able to find web browser component or similar there).
As for using html tags to decorate labels and other components showing text, you can refer to this question.
|
show html with pyqt4
|
print "hellp world" :)
i want to ask you if exist a function or class hwo can show the html code like the browser's jobe
thx
|
[
"There is QtWebKit Module within Qt. It incorporates webkit rendering engine. Whereas you can get access to Qt classes using python binding, you can use Qt official manual as help. Qt designer is also included into pyqt - you can try using it to design your application's GUI (I'm almost sure you'll be able to find web browser component or similar there).\nAs for using html tags to decorate labels and other components showing text, you can refer to this question.\n"
] |
[
1
] |
[] |
[] |
[
"pyqt4",
"python"
] |
stackoverflow_0001930866_pyqt4_python.txt
|
Q:
Python - assign lists within nest to variable
I am new to python and would appreciate a little help.
How does one do the following:
Having converted each line within a file to a nested list,
e.g. [['line 1', 'a'], ['line 2','b']] how do I flatten the list so that each line is associated with a variable. Assume that the first member in each list, i.e. i[:][0], is known.
Is it possible to associate more than one list with one variable, i.e. can x = [list1], [list2]?
Having used a for loop on a list, how those one associate aspects of that list with a variable? See example below.
Example:
for i in list_1:
if i[:][0] == 'm':
i[2] = a
i[3] = b
i[4] = c
The above returns NameError, a, b, c, not defined. How does one define variables resulting from iterations in a for loop or loops in general?
Hope I was clear and succinct as I am perplexed!
Update:
To clarify:
I have a nested list, where each list within the nest holds strings. These strings are actually numbers. I wish to convert the strings to integers in order to perform arithmetic operations.
Example:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Now, to convert each string to an integer, is abs() appropriate? How should this be implemented?
Also, to sum the third item of each list within the nest and assign the total to a variable? Should I define a function for this?
Any suggestions on how to deal with this are much appreciated!
Also, the earlier suggestions, made me realise that my thinking was creating the problem! Thanks!
A:
# Answer to question 1 - just use the built-in functionality of lists.
#
# There is no need to use variables when lists let you do so much more
# in a quick and organised fashion.
lines = []
for line in open_file:
lines.append(line)
Since Li0liQ already answered questions 2 and 3, I'd just like to add a recommendation regarding question 3. You really don't need to make a copy of the list via i[:] since you're just testing a value in the list.
A:
No. 2: I can't see how that would be possible - surely you can only assign one value to a variable?
A:
Why do you want to associate each
item in a list with a variable? You
cannot tell the number of list
entries beforehand thus you do not
know the exact number of variables
to use.
You can use tuple: x = ([list1],
[list2])
You should write assignment vice-a-versa:
for i in list_1:
if i[:][0] == 'm':
a = i[2]
b = i[3]
c = i[4]
A:
do you want:
a, b, c = i[2:5]
A:
if I understand well, you have a list of lists, which can have length 2 or 1 (when the variable name is not known)
you would probably want to use a dict to store the lines
yet to mention i[:][0] means something different you wanted, it's the same as i[0] (i[:] would be a copy of list i)
list_1 = [['line 1', 'a'], ['line 2','b'], ['line 3']]
d = {}
for i in list_1:
if len(i) != 2:
continue
key = i[1]
value = i[0]
d[key] = value
then for a, you would use d[a]
if you eventually want to convert them to variables, you can call locals().update(d)
|
Python - assign lists within nest to variable
|
I am new to python and would appreciate a little help.
How does one do the following:
Having converted each line within a file to a nested list,
e.g. [['line 1', 'a'], ['line 2','b']] how do I flatten the list so that each line is associated with a variable. Assume that the first member in each list, i.e. i[:][0], is known.
Is it possible to associate more than one list with one variable, i.e. can x = [list1], [list2]?
Having used a for loop on a list, how those one associate aspects of that list with a variable? See example below.
Example:
for i in list_1:
if i[:][0] == 'm':
i[2] = a
i[3] = b
i[4] = c
The above returns NameError, a, b, c, not defined. How does one define variables resulting from iterations in a for loop or loops in general?
Hope I was clear and succinct as I am perplexed!
Update:
To clarify:
I have a nested list, where each list within the nest holds strings. These strings are actually numbers. I wish to convert the strings to integers in order to perform arithmetic operations.
Example:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Now, to convert each string to an integer, is abs() appropriate? How should this be implemented?
Also, to sum the third item of each list within the nest and assign the total to a variable? Should I define a function for this?
Any suggestions on how to deal with this are much appreciated!
Also, the earlier suggestions, made me realise that my thinking was creating the problem! Thanks!
|
[
"# Answer to question 1 - just use the built-in functionality of lists.\n#\n# There is no need to use variables when lists let you do so much more\n# in a quick and organised fashion.\nlines = []\nfor line in open_file:\n lines.append(line)\n\nSince Li0liQ already answered questions 2 and 3, I'd just like to add a recommendation regarding question 3. You really don't need to make a copy of the list via i[:] since you're just testing a value in the list.\n",
"No. 2: I can't see how that would be possible - surely you can only assign one value to a variable?\n",
"\nWhy do you want to associate each\nitem in a list with a variable? You\ncannot tell the number of list\nentries beforehand thus you do not\nknow the exact number of variables\nto use.\nYou can use tuple: x = ([list1],\n[list2])\nYou should write assignment vice-a-versa:\nfor i in list_1:\n if i[:][0] == 'm':\n a = i[2]\n b = i[3]\n c = i[4]\n\n\n",
"do you want:\na, b, c = i[2:5]\n\n",
"if I understand well, you have a list of lists, which can have length 2 or 1 (when the variable name is not known)\nyou would probably want to use a dict to store the lines\nyet to mention i[:][0] means something different you wanted, it's the same as i[0] (i[:] would be a copy of list i)\nlist_1 = [['line 1', 'a'], ['line 2','b'], ['line 3']]\nd = {}\n\nfor i in list_1:\n if len(i) != 2:\n continue\n key = i[1]\n value = i[0]\n d[key] = value\n\nthen for a, you would use d[a]\nif you eventually want to convert them to variables, you can call locals().update(d)\n"
] |
[
2,
1,
0,
0,
0
] |
[] |
[] |
[
"list",
"loops",
"python",
"variables"
] |
stackoverflow_0001931380_list_loops_python_variables.txt
|
Q:
How to change the max_length in a django subclass?
I have the following model in django:
class Node(models.Model):
name = models.CharField(max_length=255)
And this subclass of the above model:
class Thingy(Node):
name = models.CharField(max_length=100)
otherstuff = models.CharField(max_length=255)
The problem with this setup is that while everything Just Works, a look into the database shows that syncdb has created two tables. One called appname_node with a column called name and another one called appname_thingy with two columns: name and otherstuff. When a new object is created, the name value is copied into both tables... not really cool if you dig the whole concept of normalisation :-)
Can someone explain to me how I might modify the max_length value of the "name" property in "Thingy" without re-defining it?
A:
Your implementation is totally wrong, that is not how you suppose to write parent and child class. either define name in parent class or child class, if you define it in a parent class then you can't define again in the child because new field will be created instead. so if you want to change max_length in the child, then I would recommend that you declare name in the child so that any class that inherits from node will set its own name with its own max_length.
the correct implementation is
class Node(models.Model):
#other class attributes
child class should inherit parent attributes and add its own stuff.
class Thingy(Node):
name = models.CharField(max_length=100)
otherstuff = models.CharField(max_length=255)
now when you query, you only get one name instead of the two.
|
How to change the max_length in a django subclass?
|
I have the following model in django:
class Node(models.Model):
name = models.CharField(max_length=255)
And this subclass of the above model:
class Thingy(Node):
name = models.CharField(max_length=100)
otherstuff = models.CharField(max_length=255)
The problem with this setup is that while everything Just Works, a look into the database shows that syncdb has created two tables. One called appname_node with a column called name and another one called appname_thingy with two columns: name and otherstuff. When a new object is created, the name value is copied into both tables... not really cool if you dig the whole concept of normalisation :-)
Can someone explain to me how I might modify the max_length value of the "name" property in "Thingy" without re-defining it?
|
[
"Your implementation is totally wrong, that is not how you suppose to write parent and child class. either define name in parent class or child class, if you define it in a parent class then you can't define again in the child because new field will be created instead. so if you want to change max_length in the child, then I would recommend that you declare name in the child so that any class that inherits from node will set its own name with its own max_length.\nthe correct implementation is\nclass Node(models.Model):\n #other class attributes\n\nchild class should inherit parent attributes and add its own stuff.\nclass Thingy(Node):\n name = models.CharField(max_length=100)\n otherstuff = models.CharField(max_length=255)\n\nnow when you query, you only get one name instead of the two.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001931404_django_python.txt
|
Q:
Under what circumstances do Python unittests fail to run?
I have a standalone Django app that I'm working on right now. You can see the code at Github. In one of the edits, I introduced an error that caused the source tree to be deleted. I reset to an earlier revision, and suddenly my unittests stopped working. I've tried bisecting from an earlier revision, but it turned out nothing useful.
Actually, I know for a fact that last commit that I've pushed to Github was a good one. Cloned the Github repo, and same thing: no tests are run. What could have gone wrong here?
A:
Problem solved. Turns out it was a Django-specific problem. I had a models.py file in my app that wasn't part of git repo for some strange reason. Once the source tree was removed, and code from repo restored, the models.py was no longer there, so tests wouldn't run... Silly mistake.
|
Under what circumstances do Python unittests fail to run?
|
I have a standalone Django app that I'm working on right now. You can see the code at Github. In one of the edits, I introduced an error that caused the source tree to be deleted. I reset to an earlier revision, and suddenly my unittests stopped working. I've tried bisecting from an earlier revision, but it turned out nothing useful.
Actually, I know for a fact that last commit that I've pushed to Github was a good one. Cloned the Github repo, and same thing: no tests are run. What could have gone wrong here?
|
[
"Problem solved. Turns out it was a Django-specific problem. I had a models.py file in my app that wasn't part of git repo for some strange reason. Once the source tree was removed, and code from repo restored, the models.py was no longer there, so tests wouldn't run... Silly mistake.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"unit_testing"
] |
stackoverflow_0001931567_python_unit_testing.txt
|
Q:
Accessing python httplib2 over a network share in windows 7
I am trying to run python from a network share on windows 7.
The network share is T:
>t:\python-2.6.1\python
Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import httplib2
httplib2\__init__.py:29: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import md5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "T:\python-2.6.1\lib\python2.6\site-packages\httplib2\__init__.py", line 36, in <module>
import httplib
File "T:\python-2.6.1\lib\httplib.py", line 77, in <module>
import mimetools
File "T:\python-2.6.1\lib\mimetools.py", line 6, in <module>
import tempfile
File "T:\python-2.6.1\lib\tempfile.py", line 34, in <module>
from random import Random as _Random
File "T:\python-2.6.1\lib\random.py", line 871, in <module>
_inst = Random()
File "T:\python-2.6.1\lib\random.py", line 96, in __init__
self.seed(x)
File "T:\python-2.6.1\lib\random.py", line 110, in seed
a = long(_hexlify(_urandom(16)), 16)
WindowsError: [Error 127] The specified procedure could not be found
When I copy python-2.6.1 to my local drive it works fine. It also works fine on my windows XP machine using the same network share.
A:
Peter,
When I copy python-2.6.1 from the network share to my local drive it works fine. It also works fine on my windows XP machine using the same network share.
|
Accessing python httplib2 over a network share in windows 7
|
I am trying to run python from a network share on windows 7.
The network share is T:
>t:\python-2.6.1\python
Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import httplib2
httplib2\__init__.py:29: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import md5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "T:\python-2.6.1\lib\python2.6\site-packages\httplib2\__init__.py", line 36, in <module>
import httplib
File "T:\python-2.6.1\lib\httplib.py", line 77, in <module>
import mimetools
File "T:\python-2.6.1\lib\mimetools.py", line 6, in <module>
import tempfile
File "T:\python-2.6.1\lib\tempfile.py", line 34, in <module>
from random import Random as _Random
File "T:\python-2.6.1\lib\random.py", line 871, in <module>
_inst = Random()
File "T:\python-2.6.1\lib\random.py", line 96, in __init__
self.seed(x)
File "T:\python-2.6.1\lib\random.py", line 110, in seed
a = long(_hexlify(_urandom(16)), 16)
WindowsError: [Error 127] The specified procedure could not be found
When I copy python-2.6.1 to my local drive it works fine. It also works fine on my windows XP machine using the same network share.
|
[
"Peter, \nWhen I copy python-2.6.1 from the network share to my local drive it works fine. It also works fine on my windows XP machine using the same network share.\n"
] |
[
1
] |
[] |
[] |
[
"httplib2",
"python",
"windows_7"
] |
stackoverflow_0001931353_httplib2_python_windows_7.txt
|
Q:
Python - ignore lines in a file
How does one ignore lines in a file?
Example:
If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list?
What I have so far:
fname = raw_input('Enter file name: ')
z = open(fname, 'r')
#I tried this but it converts all lines to a nested list
z_list = [i.strip().split() for i in z]
I am guessing that I need a for loop.
for line in z:
if line[0] == 'a':
pass
if line[0] == 'b':
pass
if line[-1] == 'c':
list_1 = [line.strip().split()]
The above is the general idea but I am expert at making dead code! How does one render it undead?
A:
startswith can take a tuple of strings to match, so you can do this:
[line.strip().split() for line in z if not line.startswith(('a', 'b'))]
This will work even if a and b are words or sentences not just characters.
If there can be cases where lines don't start with a or b but also don't end with c you can extend the list comprehension to this:
[
line.strip().split()
for line in z if line.endswith('c') and not line.startswith(('a', 'b'))
]
A:
One very general approach is to "filter" the file by removing some lines:
import itertools
zlist = [l.strip.split() for l in itertools.ifilter(lambda line: line[0] not in 'ab', z)]
You can use itertools.ifilter any time you want to "selectively filter" an iterable, getting another iterable which only contains those items which satisfy some predicate -- which is why I say this approach is very general. itertools has a lot of great, fast tools for dealing with iterables in a myriad way, and is well worth studying.
A similar but syntactically simpler approach, which suffices in your case (and which therefore I would recommend due to the virtue of simplicity), is to do the "filtering" with an if clause in the listcomp:
zlist = [l.strip.split() for l in z if l[0] not in 'ab']
A:
You can add if conditions to list comprehensions.
z_list = [i.strip().split() for i in z if i[-1] == 'c']
or
z_list = [i.strip().split() for i in z if (i[0] <> 'a' and i[0] <> 'b')]
A:
One way to do it is to replace 'pass' with 'continue'. This will continue to the next line in the file without doing anything. You will also need to append line to list_1
if line[-1] == 'c':
list_1.append([line.strip().split()])
A:
f=open("file")
for line in f:
li=line.strip()
if not li[0] in ["a","b"] and li[-1]=="c":
print line.rstrip()
f.close()
A:
For those interested in the solution.
And also, another question!
Example file format:
c this is a comment
p m 1468 1 267
260 32 0
8 1 0
Code:
fname = raw_input('Please enter the name of file: ')
z = open(fname, 'r')
required_list = [line.strip().split() for line in z if not line.startswith(('c', 'p'))]
print required_list
Output:
[['260', '32', '0'], ['8', '1', '0']]
Any suggestions on how to convert the strings in the lists to integers and perform arithmetic operations?
Pseudocode to illustrate:
#for the second item in each sublist
#if sum is > than first number in second line of file
#pass
#else
#abort/raise error
Cheers folks for your suggestions so far,
Seafoid.
@Nadia, my day seems a little more worthwhile now! I spent hours (days even) trying to crack this solo! Thanks!
|
Python - ignore lines in a file
|
How does one ignore lines in a file?
Example:
If you know that the first lines in a file will begin with say, a or b and the remainder of lines end with c, how does one parse the file so that lines beginning a or b are ignored and lines ending c are converted to a nested list?
What I have so far:
fname = raw_input('Enter file name: ')
z = open(fname, 'r')
#I tried this but it converts all lines to a nested list
z_list = [i.strip().split() for i in z]
I am guessing that I need a for loop.
for line in z:
if line[0] == 'a':
pass
if line[0] == 'b':
pass
if line[-1] == 'c':
list_1 = [line.strip().split()]
The above is the general idea but I am expert at making dead code! How does one render it undead?
|
[
"startswith can take a tuple of strings to match, so you can do this:\n[line.strip().split() for line in z if not line.startswith(('a', 'b'))]\n\nThis will work even if a and b are words or sentences not just characters.\nIf there can be cases where lines don't start with a or b but also don't end with c you can extend the list comprehension to this:\n[\n line.strip().split()\n for line in z if line.endswith('c') and not line.startswith(('a', 'b'))\n]\n\n",
"One very general approach is to \"filter\" the file by removing some lines:\nimport itertools\nzlist = [l.strip.split() for l in itertools.ifilter(lambda line: line[0] not in 'ab', z)]\n\nYou can use itertools.ifilter any time you want to \"selectively filter\" an iterable, getting another iterable which only contains those items which satisfy some predicate -- which is why I say this approach is very general. itertools has a lot of great, fast tools for dealing with iterables in a myriad way, and is well worth studying.\nA similar but syntactically simpler approach, which suffices in your case (and which therefore I would recommend due to the virtue of simplicity), is to do the \"filtering\" with an if clause in the listcomp:\nzlist = [l.strip.split() for l in z if l[0] not in 'ab']\n\n",
"You can add if conditions to list comprehensions.\nz_list = [i.strip().split() for i in z if i[-1] == 'c']\n\nor\nz_list = [i.strip().split() for i in z if (i[0] <> 'a' and i[0] <> 'b')]\n\n",
"One way to do it is to replace 'pass' with 'continue'. This will continue to the next line in the file without doing anything. You will also need to append line to list_1\nif line[-1] == 'c':\n list_1.append([line.strip().split()])\n\n",
"f=open(\"file\")\nfor line in f:\n li=line.strip()\n if not li[0] in [\"a\",\"b\"] and li[-1]==\"c\":\n print line.rstrip()\nf.close()\n\n",
"For those interested in the solution.\nAnd also, another question!\nExample file format:\nc this is a comment\np m 1468 1 267\n260 32 0\n8 1 0\n\nCode:\nfname = raw_input('Please enter the name of file: ')\n\nz = open(fname, 'r')\n\nrequired_list = [line.strip().split() for line in z if not line.startswith(('c', 'p'))]\n\nprint required_list\n\nOutput:\n[['260', '32', '0'], ['8', '1', '0']]\n\nAny suggestions on how to convert the strings in the lists to integers and perform arithmetic operations?\nPseudocode to illustrate:\n#for the second item in each sublist\n #if sum is > than first number in second line of file\n #pass\n #else\n #abort/raise error\n\nCheers folks for your suggestions so far,\nSeafoid.\n@Nadia, my day seems a little more worthwhile now! I spent hours (days even) trying to crack this solo! Thanks!\n"
] |
[
9,
3,
2,
1,
0,
0
] |
[] |
[] |
[
"file",
"line",
"loops",
"python"
] |
stackoverflow_0001931527_file_line_loops_python.txt
|
Q:
Django 1.1 date-based generic view problem - archive_year, archive_month, archive_day
I'm on my first Django blog and when trying to get the posts by year, month and day, using the built-in generic view from Django, but I don't get proper results. (Sorry for my non-professional first question.. if someone knows what is the appropriate question, please let me know)
Well, I think it's better to show you my configuration to make yourself a better picture:
Complete blog URLconf:
from django.conf.urls.defaults import *
from weblog.models import Entry
entry_info_dict = {
'queryset': Entry.published,
'date_field': 'pub_date',
'template_object_name': 'Entry',
}
urlpatterns = patterns('django.views.generic.date_based',
(r'^$', 'archive_index', entry_info_dict, 'weblog_entry_archive_index'),
(r'^(?P<year>\d{4})/$',
'archive_year', entry_info_dict,
'weblog_entry_archive_year'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/$',
'archive_month',
entry_info_dict,
'weblog_entry_archive_month'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$',
'archive_day',
entry_info_dict,
'weblog_entry_archive_day'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
'object_detail',
entry_info_dict,
'weblog_entry_detail'),
)
urls.py:
urlpatterns = patterns('',
(r'^blog/', include('weblog.urls.entries')),
...
)
entry_archive_year.html:
<h2>Archive for {{ year }}</h2>
<ul>
{% for month in pub_date %}
<li>
<a href="/blog/{{ year }}/{{ month|date:"b" }}/">{{ month|date:"F" }}</a>
</li>
{% endfor %}
</ul>
Supposing I have the following blog entry:
example.com/blog/2009/dec/18/test
and now request
example.com/blog/2009/
I get no objects, though when giving the full URL the post is shown.
I think Django is failing silently somewhere, though it's in DEBUG mode, and I can't figure out where.
I'd appreciate any support with this one.
A:
The month information is stored in the context variable date_list, not pub_date.
From the django docs for archive_year:
Template context:
In addition to extra_context, the
template's context will be:
date_list: A list of datetime.date objects representing all
months that have objects available in
the given year, according to queryset,
in ascending order.
The following should do the trick:
{% for month in date_list %}
<li>
<a href="/blog/{{ year }}/{{ month|date:"b" }}/">{{ month|date:"F" }}</a>
</li>
{% endfor %}
|
Django 1.1 date-based generic view problem - archive_year, archive_month, archive_day
|
I'm on my first Django blog and when trying to get the posts by year, month and day, using the built-in generic view from Django, but I don't get proper results. (Sorry for my non-professional first question.. if someone knows what is the appropriate question, please let me know)
Well, I think it's better to show you my configuration to make yourself a better picture:
Complete blog URLconf:
from django.conf.urls.defaults import *
from weblog.models import Entry
entry_info_dict = {
'queryset': Entry.published,
'date_field': 'pub_date',
'template_object_name': 'Entry',
}
urlpatterns = patterns('django.views.generic.date_based',
(r'^$', 'archive_index', entry_info_dict, 'weblog_entry_archive_index'),
(r'^(?P<year>\d{4})/$',
'archive_year', entry_info_dict,
'weblog_entry_archive_year'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/$',
'archive_month',
entry_info_dict,
'weblog_entry_archive_month'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$',
'archive_day',
entry_info_dict,
'weblog_entry_archive_day'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
'object_detail',
entry_info_dict,
'weblog_entry_detail'),
)
urls.py:
urlpatterns = patterns('',
(r'^blog/', include('weblog.urls.entries')),
...
)
entry_archive_year.html:
<h2>Archive for {{ year }}</h2>
<ul>
{% for month in pub_date %}
<li>
<a href="/blog/{{ year }}/{{ month|date:"b" }}/">{{ month|date:"F" }}</a>
</li>
{% endfor %}
</ul>
Supposing I have the following blog entry:
example.com/blog/2009/dec/18/test
and now request
example.com/blog/2009/
I get no objects, though when giving the full URL the post is shown.
I think Django is failing silently somewhere, though it's in DEBUG mode, and I can't figure out where.
I'd appreciate any support with this one.
|
[
"The month information is stored in the context variable date_list, not pub_date.\nFrom the django docs for archive_year:\n\nTemplate context:\nIn addition to extra_context, the\n template's context will be:\n\ndate_list: A list of datetime.date objects representing all\n months that have objects available in\n the given year, according to queryset,\n in ascending order.\n\n\nThe following should do the trick:\n{% for month in date_list %}\n <li>\n <a href=\"/blog/{{ year }}/{{ month|date:\"b\" }}/\">{{ month|date:\"F\" }}</a>\n </li>\n{% endfor %}\n\n"
] |
[
2
] |
[] |
[] |
[
"django",
"django_templates",
"html",
"python"
] |
stackoverflow_0001931708_django_django_templates_html_python.txt
|
Q:
What is the use of strings like "-*- Mode: Python -*-" found at the top of some python files?
Here are the top few lines (all comments) from a python application. What do the first two comment lines indicate? Are they special markers for another app?
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Istanbul - A desktop recorder
# Copyright (C) 2005 Zaheer Abbas Merali (zaheerabbas at merali dot org)
# Portions Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
A:
The first line is an emacs thing (although it may also be a vi thing). It basically tells it that it should use python-mode to read the file. You'll usually see this if the file ends in an extension other than .py.
As mentioned, the second line deals with spacings.
A:
Its define tab size 4 spaces to text editors like vi
|
What is the use of strings like "-*- Mode: Python -*-" found at the top of some python files?
|
Here are the top few lines (all comments) from a python application. What do the first two comment lines indicate? Are they special markers for another app?
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Istanbul - A desktop recorder
# Copyright (C) 2005 Zaheer Abbas Merali (zaheerabbas at merali dot org)
# Portions Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
|
[
"The first line is an emacs thing (although it may also be a vi thing). It basically tells it that it should use python-mode to read the file. You'll usually see this if the file ends in an extension other than .py.\nAs mentioned, the second line deals with spacings.\n",
"Its define tab size 4 spaces to text editors like vi\n"
] |
[
4,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001931781_python.txt
|
Q:
What's a good general way to look SQLAlchemy transactions, complete with authenticated user, etc?
I'm using SQLAlchemy's declarative extension. I'd like all changes to tables logs, including changes in many-to-many relationships (mapping tables). Each table should have a separate "log" table with a similar schema, but additional columns specifying when the change was made, who made the change, etc.
My programming model would be something like this:
row.foo = 1
row.log_version(username, change_description, ...)
Ideally, the system wouldn't allow the transaction to commit without row.log_version being called.
Thoughts?
A:
There are too many questions in one, so they that full answers to all them won't fit StackOverflow answer format. I'll try to describe hints in short, so ask separate question for them if it's not enough.
Assigning user and description to transaction
The most popular way to do so is assigning user (and other info) to some global object (threading.local() in threaded application). This is very bad way, that causes hard to discover bugs.
A better way is assigning user to the session. This is OK when session is created for each web request (in fact, it's the best design for application with authentication anyway), since there is the only user using this session. But passing description this way is not as good.
And my favorite solution is to extent Session.commit() method to accept optional user (and probably other info) parameter and assign it current transaction. This is the most flexible, and it suites well to pass description too. Note that info is bound to single transaction and is passed in obvious way when transaction is closed.
Discovering changes
There is a sqlalchemy.org.attributes.instance_state(obj) contains all information you need. The most useful for you is probably state.committed_state dictionary which contains original state for changed fields (including many-to-many relations!). There is also state.get_history() method (or sqlalchemy.org.attributes.get_history() function) returning a history object with has_changes() method and added and deleted properties for new and old value respectively. In later case use state.manager.keys() (or state.manager.attributes) to get a list of all fields.
Automatically storing changes
SQLAlchemy supports mapper extension that can provide hooks before and after update, insert and delete. You need to provide your own extension with all before hooks (you can't use after since the state of objects is changed on flush). For declarative extension it's easy to write a subclass of DeclarativeMeta that adds a mapper extension for all your models. Note that you have to flush changes twice if you use mapped objects for log, since a unit of work doesn't account objects created in hooks.
A:
We have a pretty comprehensive "versioning" recipe at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/LogVersions . It seems some other users have contributed some variants on it. The mechanics of "add a row when something changes at the ORM level" are all there.
Alternatively you can also intercept at the execution level using ConnectionProxy, search through the SQLA docs for how to use that.
edit: versioning is now an example included with SQLA: http://docs.sqlalchemy.org/en/rel_0_8/orm/examples.html#versioned-objects
|
What's a good general way to look SQLAlchemy transactions, complete with authenticated user, etc?
|
I'm using SQLAlchemy's declarative extension. I'd like all changes to tables logs, including changes in many-to-many relationships (mapping tables). Each table should have a separate "log" table with a similar schema, but additional columns specifying when the change was made, who made the change, etc.
My programming model would be something like this:
row.foo = 1
row.log_version(username, change_description, ...)
Ideally, the system wouldn't allow the transaction to commit without row.log_version being called.
Thoughts?
|
[
"There are too many questions in one, so they that full answers to all them won't fit StackOverflow answer format. I'll try to describe hints in short, so ask separate question for them if it's not enough.\nAssigning user and description to transaction\nThe most popular way to do so is assigning user (and other info) to some global object (threading.local() in threaded application). This is very bad way, that causes hard to discover bugs.\nA better way is assigning user to the session. This is OK when session is created for each web request (in fact, it's the best design for application with authentication anyway), since there is the only user using this session. But passing description this way is not as good.\nAnd my favorite solution is to extent Session.commit() method to accept optional user (and probably other info) parameter and assign it current transaction. This is the most flexible, and it suites well to pass description too. Note that info is bound to single transaction and is passed in obvious way when transaction is closed.\nDiscovering changes\nThere is a sqlalchemy.org.attributes.instance_state(obj) contains all information you need. The most useful for you is probably state.committed_state dictionary which contains original state for changed fields (including many-to-many relations!). There is also state.get_history() method (or sqlalchemy.org.attributes.get_history() function) returning a history object with has_changes() method and added and deleted properties for new and old value respectively. In later case use state.manager.keys() (or state.manager.attributes) to get a list of all fields.\nAutomatically storing changes\nSQLAlchemy supports mapper extension that can provide hooks before and after update, insert and delete. You need to provide your own extension with all before hooks (you can't use after since the state of objects is changed on flush). For declarative extension it's easy to write a subclass of DeclarativeMeta that adds a mapper extension for all your models. Note that you have to flush changes twice if you use mapped objects for log, since a unit of work doesn't account objects created in hooks.\n",
"We have a pretty comprehensive \"versioning\" recipe at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/LogVersions . It seems some other users have contributed some variants on it. The mechanics of \"add a row when something changes at the ORM level\" are all there.\nAlternatively you can also intercept at the execution level using ConnectionProxy, search through the SQLA docs for how to use that.\nedit: versioning is now an example included with SQLA: http://docs.sqlalchemy.org/en/rel_0_8/orm/examples.html#versioned-objects\n"
] |
[
6,
1
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0001862029_python_sqlalchemy.txt
|
Q:
PyTables problem - different results when iterating over subset of table
I am new to PyTables, and am looking at using it to process data generated from an agent-based modeling simulation and stored in HDF5. I'm working with a 39 MB test file, and am experiencing some strangeness. Here's the layout of the table:
/example/agt_coords (Table(2000000,)) ''
description := {
"agent": Int32Col(shape=(), dflt=0, pos=0),
"x": Float64Col(shape=(), dflt=0.0, pos=1),
"y": Float64Col(shape=(), dflt=0.0, pos=2)}
byteorder := 'little'
chunkshape := (20000,)
Here's how I'm accessing it in Python:
from tables import *
>>> h5file = openFile("alternate_hose_test.h5", "a")
h5file.root.example.agt_coords
/example/agt_coords (Table(2000000,)) ''
description := {
"agent": Int32Col(shape=(), dflt=0, pos=0),
"x": Float64Col(shape=(), dflt=0.0, pos=1),
"y": Float64Col(shape=(), dflt=0.0, pos=2)}
byteorder := 'little'
chunkshape := (20000,)
>>> coords = h5file.root.example.agt_coords
Now here's where things get weird.
[x for x in coords[1:100] if x['agent'] == 1]
[(1, 25.0, 78.0), (1, 25.0, 78.0)]
>>> [x for x in coords if x['agent'] == 1]
[(1000000, 25.0, 78.0), (1000000, 25.0, 78.0)]
>>> [x for x in coords.iterrows() if x['agent'] == 1]
[(1000000, 25.0, 78.0), (1000000, 25.0, 78.0)]
>>> [x['agent'] for x in coords[1:100] if x['agent'] == 1]
[1, 1]
>>> [x['agent'] for x in coords if x['agent'] == 1]
[1, 1]
I don't understand why the values are screwed up when I iterate over the whole table, but not when I take a small subset of the whole set of rows. I'm sure this is an error in how I'm using the library, so any help in this matter would be extremely appreciated.
A:
This is a very common point of confusion when iterating over Table object,
When you iterate over a Table the type of item you get is not the data at the item, but an accessor to the table at the current row. So with
[x for x in coords if x['agent'] == 1]
you create a list of row accessors that all point to the "current" row of the table, the last row. But when you do
[x["agent"] for x in coords if x['agent'] == 1]
you use the accessor as you build the list.
The solution to get all the data you need as you build the list, by using the accessor on each iteration. There are two options
[x[:] for x in coords if x['agent'] == 1]
or
[x.fetch_all_fields() for x in coords if x['agent'] == 1]
The former builds a list of tuples. The latter returns a NumPy void object. IIRC, the second is faster, but the former might make more sense for you purposes.
Here's a good explanation from the PyTables developer. In future releases, printing a row accessor object may not simply show the data, but state that it's a row accessor object.
|
PyTables problem - different results when iterating over subset of table
|
I am new to PyTables, and am looking at using it to process data generated from an agent-based modeling simulation and stored in HDF5. I'm working with a 39 MB test file, and am experiencing some strangeness. Here's the layout of the table:
/example/agt_coords (Table(2000000,)) ''
description := {
"agent": Int32Col(shape=(), dflt=0, pos=0),
"x": Float64Col(shape=(), dflt=0.0, pos=1),
"y": Float64Col(shape=(), dflt=0.0, pos=2)}
byteorder := 'little'
chunkshape := (20000,)
Here's how I'm accessing it in Python:
from tables import *
>>> h5file = openFile("alternate_hose_test.h5", "a")
h5file.root.example.agt_coords
/example/agt_coords (Table(2000000,)) ''
description := {
"agent": Int32Col(shape=(), dflt=0, pos=0),
"x": Float64Col(shape=(), dflt=0.0, pos=1),
"y": Float64Col(shape=(), dflt=0.0, pos=2)}
byteorder := 'little'
chunkshape := (20000,)
>>> coords = h5file.root.example.agt_coords
Now here's where things get weird.
[x for x in coords[1:100] if x['agent'] == 1]
[(1, 25.0, 78.0), (1, 25.0, 78.0)]
>>> [x for x in coords if x['agent'] == 1]
[(1000000, 25.0, 78.0), (1000000, 25.0, 78.0)]
>>> [x for x in coords.iterrows() if x['agent'] == 1]
[(1000000, 25.0, 78.0), (1000000, 25.0, 78.0)]
>>> [x['agent'] for x in coords[1:100] if x['agent'] == 1]
[1, 1]
>>> [x['agent'] for x in coords if x['agent'] == 1]
[1, 1]
I don't understand why the values are screwed up when I iterate over the whole table, but not when I take a small subset of the whole set of rows. I'm sure this is an error in how I'm using the library, so any help in this matter would be extremely appreciated.
|
[
"This is a very common point of confusion when iterating over Table object,\nWhen you iterate over a Table the type of item you get is not the data at the item, but an accessor to the table at the current row. So with\n[x for x in coords if x['agent'] == 1]\n\nyou create a list of row accessors that all point to the \"current\" row of the table, the last row. But when you do\n[x[\"agent\"] for x in coords if x['agent'] == 1]\n\nyou use the accessor as you build the list.\nThe solution to get all the data you need as you build the list, by using the accessor on each iteration. There are two options\n[x[:] for x in coords if x['agent'] == 1]\n\nor\n[x.fetch_all_fields() for x in coords if x['agent'] == 1]\n\nThe former builds a list of tuples. The latter returns a NumPy void object. IIRC, the second is faster, but the former might make more sense for you purposes.\nHere's a good explanation from the PyTables developer. In future releases, printing a row accessor object may not simply show the data, but state that it's a row accessor object.\n"
] |
[
7
] |
[] |
[] |
[
"numpy",
"pytables",
"python"
] |
stackoverflow_0001929973_numpy_pytables_python.txt
|
Q:
Python - Check Order of Lines in File
How does one check the order of lines in a file?
Example file:
a b c d e f
b c d e f g
1 2 3 4 5 0
Requirements:
All lines beginning a, must precede lines beginning b.
There is no limit on number of lines beginning a.
Lines beginning a, may or may not be present.
Lines containing integers, must follow lines beginning b.
Numeric lines must have at least two integers followed by zero.
Failure to meet conditions must raise error.
I initially thought a rather long-winded for loop, but that failed as I am unable to index lines beyond line[0]. Also, I do not know how to define location of one line relative to the others. There is no limit on the length of these files so memory may also be an issue.
Any suggestions very welcome! Simple and readable is welcome for this confused novice!
Thanks,
Seafoid.
A:
A straightforward iterative method. This defines a function to determine a linetype from 1 to 3. Then we iterate over the lines in the file. An unknown line type or a linetype less than any previous one will raise an exception.
def linetype(line):
if line.startswith("a"):
return 1
if line.startswith("b"):
return 2
try:
parts = [int(x) for x in line.split()]
if len(parts) >=3 and parts[-1] == 0:
return 3
except:
pass
raise Exception("Unknown Line Type")
maxtype = 0
for line in open("filename","r"): #iterate over each line in the file
line = line.strip() # strip any whitespace
if line == "": # if we're left with a blank line
continue # continue to the next iteration
lt = linetype(line) # get the line type of the line
# or raise an exception if unknown type
if lt >= maxtype: # as long as our type is increasing
maxtype = lt # note the current type
else: # otherwise line type decreased
raise Exception("Out of Order") # so raise exception
print "Validates" # if we made it here, we validated
A:
You can get all the lines into a list with lines = open(thefile).readlines() and then work on the list -- not maximally efficient but maximally simple, as you require.
Again simplest is to do multiple loops, one per condition (except 2, which is not a condition that can be violated, and 5 which isn't really a condition;-). "All lines beginning a, must precede lines beginning b" might be thought of as "the last line beginning with a, if any, must be before the first line beginning with b", so:
lastwitha = max((i for i, line in enumerate(lines)
if line.startswith('a')), -1)
firstwithb = next((i for i, line in enumerate(lines)
if line.startswith('b')), len(lines))
if lastwitha > firstwithb: raise Error
then similarly for "lines containing integers":
firstwithint = next((i for i, line in enumerate(lines)
if any(c in line for c in '0123456789')), len(lines))
if firstwithint < firstwithb: raise Error
This shouild really be plenty of hints for your homework -- can you now do by yourself the last remaining bit, condition 4?
Of course you can take different tacks from what I'm suggesting here (using next to get the first number of a line satisfying a condition -- this requires Python 2.6, btw -- and any and all to satisfy if any / all items in a sequence meets a condition) but I'm trying to match your request for maximum simplicity. If you find traditional for loops simpler than next, any and all, let us know and we'll show how to recode these uses of the higher abstraction forms into those lower-layer concepts!
A:
You don't need to index the lines. For every line you can chceck/set some conditions. If some condition is not met, raise an error. E.g. rule 1: you will have variable was_b initially set to False. In each iteration (besides from other checks / sets), check also, if the line starts with "b". If does, set was_b = True. Another check would be: if line starts with "a" and was_b is true, raise the error. Another check would be: if line contains integers and was_b is False, raise the error.. etc
A:
Restrictions on lines:
I. There must be no lines that begin with 'a' after we've encountered a line that begins with 'b'.
II. If we encountered a numeric line then a previous one must start with 'b'. (or your 4-th condition allows another interpretation: each 'b' line must be followed by a numeric line).
Restriction on numeric line (as a regular expression): /\d+\s+\d+\s+0\s*$/
#!/usr/bin/env python
import re
is_numeric = lambda line: re.match(r'^\s*\d+(?:\s|\d)*$', line)
valid_numeric = lambda line: re.search(r'(?:\d+\s+){2}0\s*$', line)
def error(msg):
raise SyntaxError('%s at %s:%s: "%s"' % (msg, filename, i+1, line))
seen_b, last_is_b = False, False
with open(filename) as f:
for i, line in enumerate(f):
if not seen_b:
seen_b = line.startswith('b')
if seen_b and line.startswith('a'):
error('failed I.')
if not last_is_b and is_numeric(line):
error('failed II.')
if is_numeric(line) and not valid_numeric(line):
error('not a valid numeric line')
last_is_b = line.startswith('b')
|
Python - Check Order of Lines in File
|
How does one check the order of lines in a file?
Example file:
a b c d e f
b c d e f g
1 2 3 4 5 0
Requirements:
All lines beginning a, must precede lines beginning b.
There is no limit on number of lines beginning a.
Lines beginning a, may or may not be present.
Lines containing integers, must follow lines beginning b.
Numeric lines must have at least two integers followed by zero.
Failure to meet conditions must raise error.
I initially thought a rather long-winded for loop, but that failed as I am unable to index lines beyond line[0]. Also, I do not know how to define location of one line relative to the others. There is no limit on the length of these files so memory may also be an issue.
Any suggestions very welcome! Simple and readable is welcome for this confused novice!
Thanks,
Seafoid.
|
[
"A straightforward iterative method. This defines a function to determine a linetype from 1 to 3. Then we iterate over the lines in the file. An unknown line type or a linetype less than any previous one will raise an exception.\ndef linetype(line):\n if line.startswith(\"a\"):\n return 1\n if line.startswith(\"b\"):\n return 2\n try:\n parts = [int(x) for x in line.split()]\n if len(parts) >=3 and parts[-1] == 0:\n return 3\n except:\n pass\n raise Exception(\"Unknown Line Type\")\n\nmaxtype = 0\n\nfor line in open(\"filename\",\"r\"): #iterate over each line in the file\n line = line.strip() # strip any whitespace\n if line == \"\": # if we're left with a blank line\n continue # continue to the next iteration\n\n lt = linetype(line) # get the line type of the line\n # or raise an exception if unknown type\n if lt >= maxtype: # as long as our type is increasing\n maxtype = lt # note the current type\n else: # otherwise line type decreased\n raise Exception(\"Out of Order\") # so raise exception\n\nprint \"Validates\" # if we made it here, we validated\n\n",
"You can get all the lines into a list with lines = open(thefile).readlines() and then work on the list -- not maximally efficient but maximally simple, as you require.\nAgain simplest is to do multiple loops, one per condition (except 2, which is not a condition that can be violated, and 5 which isn't really a condition;-). \"All lines beginning a, must precede lines beginning b\" might be thought of as \"the last line beginning with a, if any, must be before the first line beginning with b\", so:\nlastwitha = max((i for i, line in enumerate(lines)\n if line.startswith('a')), -1)\nfirstwithb = next((i for i, line in enumerate(lines) \n if line.startswith('b')), len(lines))\nif lastwitha > firstwithb: raise Error\n\nthen similarly for \"lines containing integers\":\nfirstwithint = next((i for i, line in enumerate(lines)\n if any(c in line for c in '0123456789')), len(lines))\nif firstwithint < firstwithb: raise Error\n\nThis shouild really be plenty of hints for your homework -- can you now do by yourself the last remaining bit, condition 4?\nOf course you can take different tacks from what I'm suggesting here (using next to get the first number of a line satisfying a condition -- this requires Python 2.6, btw -- and any and all to satisfy if any / all items in a sequence meets a condition) but I'm trying to match your request for maximum simplicity. If you find traditional for loops simpler than next, any and all, let us know and we'll show how to recode these uses of the higher abstraction forms into those lower-layer concepts!\n",
"You don't need to index the lines. For every line you can chceck/set some conditions. If some condition is not met, raise an error. E.g. rule 1: you will have variable was_b initially set to False. In each iteration (besides from other checks / sets), check also, if the line starts with \"b\". If does, set was_b = True. Another check would be: if line starts with \"a\" and was_b is true, raise the error. Another check would be: if line contains integers and was_b is False, raise the error.. etc\n",
"Restrictions on lines:\nI. There must be no lines that begin with 'a' after we've encountered a line that begins with 'b'.\nII. If we encountered a numeric line then a previous one must start with 'b'. (or your 4-th condition allows another interpretation: each 'b' line must be followed by a numeric line). \nRestriction on numeric line (as a regular expression): /\\d+\\s+\\d+\\s+0\\s*$/\n#!/usr/bin/env python\nimport re\n\nis_numeric = lambda line: re.match(r'^\\s*\\d+(?:\\s|\\d)*$', line)\nvalid_numeric = lambda line: re.search(r'(?:\\d+\\s+){2}0\\s*$', line)\n\ndef error(msg):\n raise SyntaxError('%s at %s:%s: \"%s\"' % (msg, filename, i+1, line))\n\nseen_b, last_is_b = False, False\nwith open(filename) as f:\n for i, line in enumerate(f):\n if not seen_b:\n seen_b = line.startswith('b')\n\n if seen_b and line.startswith('a'):\n error('failed I.')\n if not last_is_b and is_numeric(line):\n error('failed II.')\n if is_numeric(line) and not valid_numeric(line):\n error('not a valid numeric line')\n\n last_is_b = line.startswith('b')\n\n"
] |
[
4,
2,
0,
0
] |
[] |
[] |
[
"file",
"lines",
"python"
] |
stackoverflow_0001931802_file_lines_python.txt
|
Q:
packaging cryptography software and distributing
I'm developing a python GUI application and plan on calling external program packaged with my program to do some encryption. I noticed from sites like OpenSSL that talk about export laws regarding cryptography software.
If I can't package binary forms of the cryptography software with my application, how can I work around this to still be able to encrypt the output of my program?
A:
You need to pick your target audiences with care, especially when you are dancing around with ITAR -- the International Traffic in Arms Regulations. Identify the countries you can legally export your product to and then, at the very least, say that people from other countries can't download it. You may have to do more than that to stay legal in your country.
Legally, this is getting into the deep end of the pool and you will want to talk to a knowledgeable attorney about this. If you live in Finland, you can probably do whatever you like. If you live in the US, be careful. If you live in France, be very careful.
Update: Sometimes I feel old, other days I prove it. Without checking on the current ITAR handling of strong cryptography I responded with an answer that is at least 12 years out of date. Prior to 1997 exporting crypto of any sort, from/to any country, was a very dicey thing to do and carried severe legal penalties. This was especially true in France which, for a time, outlawed all non-governmental uses of crypto, even very weak 40-bit DES. Although France has loosened up a bit, they still seem to behind most other developed countries in understanding that a) their citizens have a valid right to privacy, and b) there's not much they can do to stop it in a world where 4096 bit RSA is available all over the net.
ITAR's stance on crypto changed in 96-97. Although matters have improved in general, there are still obstacles to exporting/importing crypto. Before you go too much further you should thoroughly familiarize yourself with the laws of your country regarding cryto -- you might be shocked/saddened by what you find. Even the U.S. still has some restrictions on what kind of crypto you can export to whom and in what form.
Some countries, notably France and the U.K., have had (and appear to still have in some form or other) laws that can require the supplier of the software to either escrow keys used by their customers and/or provide a backdoor into the system in case the government wants to see what you are talking about.
Bottom line: Good crypto makes governments nervous and the laws on what is legal/illegal are all over the map. Try to understand exactly what role encryption plays in your proposed product/project and determine if it's something that a user can opt in/out of based on their own country's stance on the subject.
A:
i have often seen people rely on an external package for the cryptographic part: you can package your software without the cryptographic package, and tell your user that they have to download and install the cryptographic part from the original publisher.
this is effectively moving the responsibility for the cryptographic part from you to your user.
|
packaging cryptography software and distributing
|
I'm developing a python GUI application and plan on calling external program packaged with my program to do some encryption. I noticed from sites like OpenSSL that talk about export laws regarding cryptography software.
If I can't package binary forms of the cryptography software with my application, how can I work around this to still be able to encrypt the output of my program?
|
[
"You need to pick your target audiences with care, especially when you are dancing around with ITAR -- the International Traffic in Arms Regulations. Identify the countries you can legally export your product to and then, at the very least, say that people from other countries can't download it. You may have to do more than that to stay legal in your country.\nLegally, this is getting into the deep end of the pool and you will want to talk to a knowledgeable attorney about this. If you live in Finland, you can probably do whatever you like. If you live in the US, be careful. If you live in France, be very careful.\nUpdate: Sometimes I feel old, other days I prove it. Without checking on the current ITAR handling of strong cryptography I responded with an answer that is at least 12 years out of date. Prior to 1997 exporting crypto of any sort, from/to any country, was a very dicey thing to do and carried severe legal penalties. This was especially true in France which, for a time, outlawed all non-governmental uses of crypto, even very weak 40-bit DES. Although France has loosened up a bit, they still seem to behind most other developed countries in understanding that a) their citizens have a valid right to privacy, and b) there's not much they can do to stop it in a world where 4096 bit RSA is available all over the net.\nITAR's stance on crypto changed in 96-97. Although matters have improved in general, there are still obstacles to exporting/importing crypto. Before you go too much further you should thoroughly familiarize yourself with the laws of your country regarding cryto -- you might be shocked/saddened by what you find. Even the U.S. still has some restrictions on what kind of crypto you can export to whom and in what form. \nSome countries, notably France and the U.K., have had (and appear to still have in some form or other) laws that can require the supplier of the software to either escrow keys used by their customers and/or provide a backdoor into the system in case the government wants to see what you are talking about.\nBottom line: Good crypto makes governments nervous and the laws on what is legal/illegal are all over the map. Try to understand exactly what role encryption plays in your proposed product/project and determine if it's something that a user can opt in/out of based on their own country's stance on the subject.\n",
"i have often seen people rely on an external package for the cryptographic part: you can package your software without the cryptographic package, and tell your user that they have to download and install the cryptographic part from the original publisher. \nthis is effectively moving the responsibility for the cryptographic part from you to your user.\n"
] |
[
5,
0
] |
[] |
[] |
[
"aes",
"cryptography",
"itar",
"python"
] |
stackoverflow_0001932200_aes_cryptography_itar_python.txt
|
Q:
Printing Lines in a File
So here's the problem I have,
I can find the Search Term in my file but at the moment I can only print out the line that the Search Term is in. (Thanks to Questions posted by people earlier =)). But I cannot print out all the lines to the end of the file after the Search Term. Here is the coding I have so far:-
search_term = r'\b%s\b' % search_term
for line in open(f, 'r'):
if re.match(search_term, line):
print line,
Thanks in advance!
A:
It can be much improved if you first compile the regex:
search_term_regex = re.compile(r'\b%s\b' % search_term)
found = False
for line in open(f):
if not found:
found = bool(search_term_regex.findall(line))
if found:
print line,
Then you're not repeating the print line.
A:
You could set a boolean flag, e.g. "found = True";
and do a check for found==True, and if so print the line.
Code below:
search_term = r'\b%s\b' % search_term
found = False;
for line in open(f, 'r'):
if found==True:
print line,
elif re.match(search_term, line):
found = True;
print line,
To explain this a bit: With the boolean flag you are adding some state to your code to modify its functionality. What you want your code to do is dependent on whether you have found a certain line of text in your file or not, so the best way to represent such a binary state (have I found the line or not found it?) is with a boolean variable like this, and then have the code do different things depending on the value of the variable.
Also, the elif is just a shortening of else if.
|
Printing Lines in a File
|
So here's the problem I have,
I can find the Search Term in my file but at the moment I can only print out the line that the Search Term is in. (Thanks to Questions posted by people earlier =)). But I cannot print out all the lines to the end of the file after the Search Term. Here is the coding I have so far:-
search_term = r'\b%s\b' % search_term
for line in open(f, 'r'):
if re.match(search_term, line):
print line,
Thanks in advance!
|
[
"It can be much improved if you first compile the regex:\nsearch_term_regex = re.compile(r'\\b%s\\b' % search_term)\n\nfound = False\nfor line in open(f):\n if not found:\n found = bool(search_term_regex.findall(line))\n if found:\n print line,\n\nThen you're not repeating the print line. \n",
"You could set a boolean flag, e.g. \"found = True\";\nand do a check for found==True, and if so print the line.\nCode below:\nsearch_term = r'\\b%s\\b' % search_term\n\nfound = False;\nfor line in open(f, 'r'):\n if found==True:\n print line,\n elif re.match(search_term, line):\n found = True;\n print line,\n\nTo explain this a bit: With the boolean flag you are adding some state to your code to modify its functionality. What you want your code to do is dependent on whether you have found a certain line of text in your file or not, so the best way to represent such a binary state (have I found the line or not found it?) is with a boolean variable like this, and then have the code do different things depending on the value of the variable.\nAlso, the elif is just a shortening of else if.\n"
] |
[
1,
0
] |
[] |
[] |
[
"printing",
"python",
"text"
] |
stackoverflow_0001932491_printing_python_text.txt
|
Q:
python post large files to django
I am trying to find the best way (most efficient way) to post large files from a python application to a Django server.
If I rely on raw_post_data on the Django side then all the content needs to be in RAM before I can read it which doesn't seem efficient at all if the file received is 100s of megs.
Is it better to use the file uploads methods Django has. This means using a multipart/form-data post.
or maybe something better ?
Laurent
A:
I think only files less than 2.5MB are stored in the memory, any file that is larger than 2.5MB is streamed or written to temporary file in temp directory..
reference:
http://simonwillison.net/2008/Jul/1/uploads/ and here http://docs.djangoproject.com/en/dev/topics/http/file-uploads/
A:
If you really want to optimize it and don't want Django to suffer whilst the bytes are being streamed and thus occupying one of the Django threads you can use the nginx upload module
(see also this blog post)
|
python post large files to django
|
I am trying to find the best way (most efficient way) to post large files from a python application to a Django server.
If I rely on raw_post_data on the Django side then all the content needs to be in RAM before I can read it which doesn't seem efficient at all if the file received is 100s of megs.
Is it better to use the file uploads methods Django has. This means using a multipart/form-data post.
or maybe something better ?
Laurent
|
[
"I think only files less than 2.5MB are stored in the memory, any file that is larger than 2.5MB is streamed or written to temporary file in temp directory..\nreference:\nhttp://simonwillison.net/2008/Jul/1/uploads/ and here http://docs.djangoproject.com/en/dev/topics/http/file-uploads/\n",
"If you really want to optimize it and don't want Django to suffer whilst the bytes are being streamed and thus occupying one of the Django threads you can use the nginx upload module\n(see also this blog post)\n"
] |
[
6,
2
] |
[] |
[] |
[
"django",
"post",
"python",
"upload"
] |
stackoverflow_0001931673_django_post_python_upload.txt
|
Q:
Offline access to MoinMoin wiki using Google Gears
How to add offline access functionality to MoinMoin wiki?
As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online.
Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome.
An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question.
Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.
A:
If you have the freedom to change the wiki software, I might suggest looking at ikiwiki. You can set it up so the pages are backed by a real VCS such as Git, in which case you can clone the whole wiki and read and even update it offline.
A:
By using Gears with the Firefox Greasemonkey plugin, you can inject Gears code into any website that you want. Don't wait for your favorite website to enable offline support -- do it yourself. http://code.google.com/apis/gears/articles/gearsmonkey.html
A:
If you're patient enough, MoinMoin release 2.0 will ship with Mercurial DVCS backend, so you won't have to switch. More info on http://moinmo.in/MoinMoin2.0
A:
if you want to do that on servers see HelpOnSynchronisation in moinmoin + DesktopEdition
if locally, use unison + DesktopEdition . be careful to ignore cache and such. this will allow 2-way synchronisation.
|
Offline access to MoinMoin wiki using Google Gears
|
How to add offline access functionality to MoinMoin wiki?
As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update wiki content while offline and push it back to the wiki when online.
Google Gears looks like a good candidate for trying to solve this, but other solutions are also welcome.
An interesting property of MoinMoin is that it keeps content in regular files instead of the database. This can make it easier to port wiki content from one location to another, but I don't know if that can play any role in answering this question.
Note: if you see a good reply please rate it up. i'd love to do that, but the site does not let me do ratings yet.
|
[
"If you have the freedom to change the wiki software, I might suggest looking at ikiwiki. You can set it up so the pages are backed by a real VCS such as Git, in which case you can clone the whole wiki and read and even update it offline.\n",
"By using Gears with the Firefox Greasemonkey plugin, you can inject Gears code into any website that you want. Don't wait for your favorite website to enable offline support -- do it yourself. http://code.google.com/apis/gears/articles/gearsmonkey.html\n",
"If you're patient enough, MoinMoin release 2.0 will ship with Mercurial DVCS backend, so you won't have to switch. More info on http://moinmo.in/MoinMoin2.0\n",
"\nif you want to do that on servers see HelpOnSynchronisation in moinmoin + DesktopEdition \nif locally, use unison + DesktopEdition . be careful to ignore cache and such. this will allow 2-way synchronisation.\n\n"
] |
[
2,
2,
1,
1
] |
[
"Have a look at MoinMoin Desktop Edition.\n"
] |
[
-1
] |
[
"google_gears",
"moinmoin",
"offline",
"python",
"wiki"
] |
stackoverflow_0000176955_google_gears_moinmoin_offline_python_wiki.txt
|
Q:
How to use InterWiki links in moinmoin?
We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to http://mybugtracker/bug1234
A:
check out the interwiki page in moinmoin, (most wikis have them) we use trac for example and you can set up different link paths to point to your different web resources. So in our Trac you can go [[SSGWiki:Some Topic]] and it will point to another internal wiki.
A:
add to the file data/intermap.txt (create if not existing, but that should not happen) a line like
wpen http://en.wikipedia.org/wiki/
so that you can write [[wpen:MoinMoin]] instead of http://en.wikipedia.org/wiki/MoinMoin
I also have
wpfr http://fr.wikipedia.org/wiki/
wpde http://de.wikipedia.org/wiki/
the data/intermap.txt gives also other examples that serve just like bookmarklets in firefox. in your case, using :
tracker http://mybugtracker/
you would issue [[tracker:bug1234]]
|
How to use InterWiki links in moinmoin?
|
We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to http://mybugtracker/bug1234
|
[
"check out the interwiki page in moinmoin, (most wikis have them) we use trac for example and you can set up different link paths to point to your different web resources. So in our Trac you can go [[SSGWiki:Some Topic]] and it will point to another internal wiki.\n",
"add to the file data/intermap.txt (create if not existing, but that should not happen) a line like\nwpen http://en.wikipedia.org/wiki/\n\nso that you can write [[wpen:MoinMoin]] instead of http://en.wikipedia.org/wiki/MoinMoin\nI also have\nwpfr http://fr.wikipedia.org/wiki/\nwpde http://de.wikipedia.org/wiki/\n\nthe data/intermap.txt gives also other examples that serve just like bookmarklets in firefox. in your case, using :\ntracker http://mybugtracker/\n\nyou would issue [[tracker:bug1234]]\n"
] |
[
3,
0
] |
[
"I finally found the solution. \n\"Add the site to data/intermap.txt\" found at:\nhttp://moinmo.in/MoinMoinQuestions#MoinMoinQuestions.2BAC8-Administration.Howtoaddnewinterwikisites.3F\n"
] |
[
-1
] |
[
"moinmoin",
"python",
"wiki"
] |
stackoverflow_0000343769_moinmoin_python_wiki.txt
|
Q:
General questions regarding Python language
I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from online tutorials or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actually teach you how to make more advanced programs.
One example is Exif-py. How do you even start programming a program like this? Do you just sit down and start writing the code, or do you have to search for APIs or anything? I went through the code briefly and it all looked alien to me.
I'm not really sure how to express my questions into words, so do check back because I'll edit my question if the right words come to me.
A:
Well, I learnt all my Python from online sources (not just tutorials, but reference documentation, blog posts and other texts). It's certainly possible, although some people prefer the "guided" way a book teaches you, particularly people new to programming (at that point I had already been programming for years).
To create a program such as Exif.py, you would first have to know what you must do in broad terms BEFORE starting to program. You would study the EXIF format, then figure out how that is put into the image files, then you would have to formulate that in terms of the language you're using (in this case, Python). This usually requires that you're already familiar with it, otherwise it'll be a fairly slow process.
I'd suggest starting with simpler programs to begin with, or maybe follow a book such as Dive Into Python (free online), seeing as you're new to programming, and need to not only learn the language, but to think like a programmer.
A:
The tutorials are there to teach you the language syntax and the standard library, not really on how to solve a particular programming problem. Think of what you learn there as your toolbox.
I think I understand what you are saying. You want to break above and beyond the simple applications and write your own stuff, right? Well, first you need to figure out what it is you want to make. Then comes the hard part; how are you going to make it? I'd suggest starting by trying to break it down into a number of small simple problems instead of tackling it as one large problem.
If you are trying to find examples of larger projects, I'd suggest looking at the Python Cheeseshop (package index) and download a few packages you've heard of to see how they did it. Also, people often post handy pieces of code on their personal blogs and that shows up on PlanetPython.
A:
If by 'newbie to programming' you mean that you just started it last week or something along the lines, then maybe you might want to give the MIT OpenCourseWare Introduction to Computer Science videos (and homework!) a bit of your time.
The opencourse covers the syntax of the Python language, some helpful hints and general do's and don'ts that apply to any programming paradigm.
Though, if by 'newbie to programming', that you already know the basic concepts you need to start writing basic programs (like adding, subtracting, multiplying, logical operations, functions etc).
If so, Project Euler is particularly good for exercising that cranial muscle in problem solving via programming, though most of the problems on the site require you at also have knowledge of mathematics (and if you don't, at least know how to google).
Just remember, if you get stuck on anything don't get put down! It's all part of learning! If you're really stuck, search SO!
A:
If stuff like recursion, modules, classes, iteration, exceptions, dictionaries, are indeed new to you, I suggest How to Think Like a Computer Scientist in Python (lovingly abbreviated as ThinkCSPy in the community ;-).
It is a bit outdated - for best results, use Python 2.6 or lower, but then again 3.0 is not that different.
EDIT: If ThinkCSPy has little to teach you, try Dive Into Python. It's advanced and pretty "real-world", but step-by-step.
A:
There are a few very good online resources:
The Python Tutorial.
Dive Into Python. Python from novice to pro.
Code Like a Pythonista: Idiomatic Python
Another list of resources: Essential Python Reading List.
Most Python books I've seen so far are "not that good" - but that depends
on your background / prior knowledge about Python and programming.
A:
You study the EXIF format, study the GIF/JPEG format, open the binary file, scan it and get the data out.
|
General questions regarding Python language
|
I'm a newbie to programming and I've decided to start with Python. Just curious though, is it enough/recommended to learn Python from online tutorials or from books? I want to go further than simple "Hello World!" programs. I'm not sure if books will actually teach you how to make more advanced programs.
One example is Exif-py. How do you even start programming a program like this? Do you just sit down and start writing the code, or do you have to search for APIs or anything? I went through the code briefly and it all looked alien to me.
I'm not really sure how to express my questions into words, so do check back because I'll edit my question if the right words come to me.
|
[
"Well, I learnt all my Python from online sources (not just tutorials, but reference documentation, blog posts and other texts). It's certainly possible, although some people prefer the \"guided\" way a book teaches you, particularly people new to programming (at that point I had already been programming for years).\nTo create a program such as Exif.py, you would first have to know what you must do in broad terms BEFORE starting to program. You would study the EXIF format, then figure out how that is put into the image files, then you would have to formulate that in terms of the language you're using (in this case, Python). This usually requires that you're already familiar with it, otherwise it'll be a fairly slow process.\nI'd suggest starting with simpler programs to begin with, or maybe follow a book such as Dive Into Python (free online), seeing as you're new to programming, and need to not only learn the language, but to think like a programmer.\n",
"The tutorials are there to teach you the language syntax and the standard library, not really on how to solve a particular programming problem. Think of what you learn there as your toolbox. \nI think I understand what you are saying. You want to break above and beyond the simple applications and write your own stuff, right? Well, first you need to figure out what it is you want to make. Then comes the hard part; how are you going to make it? I'd suggest starting by trying to break it down into a number of small simple problems instead of tackling it as one large problem.\nIf you are trying to find examples of larger projects, I'd suggest looking at the Python Cheeseshop (package index) and download a few packages you've heard of to see how they did it. Also, people often post handy pieces of code on their personal blogs and that shows up on PlanetPython.\n",
"If by 'newbie to programming' you mean that you just started it last week or something along the lines, then maybe you might want to give the MIT OpenCourseWare Introduction to Computer Science videos (and homework!) a bit of your time. \nThe opencourse covers the syntax of the Python language, some helpful hints and general do's and don'ts that apply to any programming paradigm. \nThough, if by 'newbie to programming', that you already know the basic concepts you need to start writing basic programs (like adding, subtracting, multiplying, logical operations, functions etc). \nIf so, Project Euler is particularly good for exercising that cranial muscle in problem solving via programming, though most of the problems on the site require you at also have knowledge of mathematics (and if you don't, at least know how to google).\nJust remember, if you get stuck on anything don't get put down! It's all part of learning! If you're really stuck, search SO!\n",
"If stuff like recursion, modules, classes, iteration, exceptions, dictionaries, are indeed new to you, I suggest How to Think Like a Computer Scientist in Python (lovingly abbreviated as ThinkCSPy in the community ;-).\nIt is a bit outdated - for best results, use Python 2.6 or lower, but then again 3.0 is not that different.\nEDIT: If ThinkCSPy has little to teach you, try Dive Into Python. It's advanced and pretty \"real-world\", but step-by-step.\n",
"There are a few very good online resources:\n\nThe Python Tutorial.\nDive Into Python. Python from novice to pro.\nCode Like a Pythonista: Idiomatic Python\n\nAnother list of resources: Essential Python Reading List.\nMost Python books I've seen so far are \"not that good\" - but that depends\non your background / prior knowledge about Python and programming.\n",
"You study the EXIF format, study the GIF/JPEG format, open the binary file, scan it and get the data out.\n"
] |
[
4,
2,
2,
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001932643_python.txt
|
Q:
How do I generate multi-word terms recursively?
Say I have a string of words: 'a b c d e f'. I want to generate a list of multi-word terms from this string.
Word order matters. The term 'f e d' shouldn't be generated from the above example.
Edit: Also, words should not be skipped. 'a c', or 'b d f' shouldn't be generated.
What I have right now:
doc = 'a b c d e f'
terms= []
one_before = None
two_before = None
for word in doc.split(None):
terms.append(word)
if one_before:
terms.append(' '.join([one_before, word]))
if two_before:
terms.append(' '.join([two_before, one_before, word]))
two_before = one_before
one_before = word
for term in terms:
print term
Prints:
a
b
a b
c
b c
a b c
d
c d
b c d
e
d e
c d e
f
e f
d e f
How would I make this a recursive function so that I can pass it a variable maximum number of words per term?
Application:
I'll be using this to generate multi-word terms from readable text in HTML documents. The overall goal is a latent semantic analysis of a large corpus (about two million documents). This is why keeping word order matters (Natural Language Processing and whatnot).
A:
This isn't recursive, but I think it does what you want.
doc = 'a b c d e f'
words = doc.split(None)
max = 3
for index in xrange(len(words)):
for n in xrange(max):
if index + n < len(words):
print ' '.join(words[index:index+n+1])
And here's a recursive solution:
def find_terms(words, max_words_per_term):
if len(words) == 0: return []
return [" ".join(words[:i+1]) for i in xrange(min(len(words), max_words_per_term))] + find_terms(words[1:], max_words_per_term)
doc = 'a b c d e f'
words = doc.split(None)
for term in find_terms(words, 3):
print term
Here's the recursive function again, with some explaining variables and comments.
def find_terms(words, max_words_per_term):
# If there are no words, you've reached the end. Stop.
if len(words) == 0:
return []
# What's the max term length you could generate from the remaining
# words? It's the lesser of max_words_per_term and how many words
# you have left.
max_term_len = min(len(words), max_words_per_term)
# Find all the terms that start with the first word.
initial_terms = [" ".join(words[:i+1]) for i in xrange(max_term_len)]
# Here's the recursion. Find all of the terms in the list
# of all but the first word.
other_terms = find_terms(words[1:], max_words_per_term)
# Now put the two lists of terms together to get the answer.
return initial_terms + other_terms
A:
I would suggest that you should make your function a generator and then generate required number of terms. You would need to change print to yield (and make the whole block function, obviously).
You might have a look at itertools module as well, it's fairly useful for kind of work you do.
A:
Why are you doing this? You can instead just use a for loop and itertools.combinations().
A:
What you are looking for is N-gram algorithm. That will give you [a,ab,b,bc,c,cd,...].
|
How do I generate multi-word terms recursively?
|
Say I have a string of words: 'a b c d e f'. I want to generate a list of multi-word terms from this string.
Word order matters. The term 'f e d' shouldn't be generated from the above example.
Edit: Also, words should not be skipped. 'a c', or 'b d f' shouldn't be generated.
What I have right now:
doc = 'a b c d e f'
terms= []
one_before = None
two_before = None
for word in doc.split(None):
terms.append(word)
if one_before:
terms.append(' '.join([one_before, word]))
if two_before:
terms.append(' '.join([two_before, one_before, word]))
two_before = one_before
one_before = word
for term in terms:
print term
Prints:
a
b
a b
c
b c
a b c
d
c d
b c d
e
d e
c d e
f
e f
d e f
How would I make this a recursive function so that I can pass it a variable maximum number of words per term?
Application:
I'll be using this to generate multi-word terms from readable text in HTML documents. The overall goal is a latent semantic analysis of a large corpus (about two million documents). This is why keeping word order matters (Natural Language Processing and whatnot).
|
[
"This isn't recursive, but I think it does what you want. \ndoc = 'a b c d e f'\nwords = doc.split(None)\nmax = 3 \n\n\nfor index in xrange(len(words)): \n for n in xrange(max):\n if index + n < len(words): \n print ' '.join(words[index:index+n+1]) \n\nAnd here's a recursive solution:\ndef find_terms(words, max_words_per_term): \n if len(words) == 0: return []\n return [\" \".join(words[:i+1]) for i in xrange(min(len(words), max_words_per_term))] + find_terms(words[1:], max_words_per_term)\n\n\ndoc = 'a b c d e f'\nwords = doc.split(None) \nfor term in find_terms(words, 3):\n print term\n\nHere's the recursive function again, with some explaining variables and comments.\ndef find_terms(words, max_words_per_term): \n\n # If there are no words, you've reached the end. Stop. \n if len(words) == 0:\n return [] \n\n # What's the max term length you could generate from the remaining \n # words? It's the lesser of max_words_per_term and how many words \n # you have left. \n max_term_len = min(len(words), max_words_per_term) \n\n # Find all the terms that start with the first word.\n initial_terms = [\" \".join(words[:i+1]) for i in xrange(max_term_len)]\n\n # Here's the recursion. Find all of the terms in the list \n # of all but the first word.\n other_terms = find_terms(words[1:], max_words_per_term)\n\n # Now put the two lists of terms together to get the answer.\n return initial_terms + other_terms \n\n",
"I would suggest that you should make your function a generator and then generate required number of terms. You would need to change print to yield (and make the whole block function, obviously).\nYou might have a look at itertools module as well, it's fairly useful for kind of work you do.\n",
"Why are you doing this? You can instead just use a for loop and itertools.combinations().\n",
"What you are looking for is N-gram algorithm. That will give you [a,ab,b,bc,c,cd,...].\n"
] |
[
11,
3,
3,
1
] |
[] |
[] |
[
"python",
"recursion"
] |
stackoverflow_0000702760_python_recursion.txt
|
Q:
make python replace un-encodable chars with a string by default
I want to make python ignore chars it can't encode, by simply replacing them with the string "<could not encode>".
E.g, assuming the default encoding is ascii, the command
'%s is the word'%'ébác'
would yield
'<could not encode>b<could not encode>c is the word'
Is there any way to make this the default behavior, across all my project?
A:
The str.encode function takes an optional argument defining the error handling:
str.encode([encoding[, errors]])
From the docs:
Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Codec Base Classes. For a list of possible encodings, see section Standard Encodings.
In your case, the codecs.register_error function might be of interest.
[Note about bad chars]
By the way, note when using register_error that you'll likely find yourself replacing not just individual bad characters but groups of consecutive bad characters with your string, unless you pay attention. You get one call to the error handler per run of bad chars, not per char.
A:
>>> help("".encode)
Help on built-in function encode:
encode(...)
S.encode([encoding[,errors]]) -> object
Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. **Other possible values are** 'ignore', **'replace'** and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that is able to handle UnicodeEncodeErrors.
So, for instance:
>>> x
'\xc3\xa9b\xc3\xa1c is the word'
>>> x.decode("ascii")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
>>> x.decode("ascii", "replace")
u'\ufffd\ufffdb\ufffd\ufffdc is the word'
Add your own callback to codecs.register_error to replace with the string of your choice.
|
make python replace un-encodable chars with a string by default
|
I want to make python ignore chars it can't encode, by simply replacing them with the string "<could not encode>".
E.g, assuming the default encoding is ascii, the command
'%s is the word'%'ébác'
would yield
'<could not encode>b<could not encode>c is the word'
Is there any way to make this the default behavior, across all my project?
|
[
"The str.encode function takes an optional argument defining the error handling:\nstr.encode([encoding[, errors]])\n\nFrom the docs:\n\nReturn an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(), see section Codec Base Classes. For a list of possible encodings, see section Standard Encodings.\n\nIn your case, the codecs.register_error function might be of interest.\n[Note about bad chars]\nBy the way, note when using register_error that you'll likely find yourself replacing not just individual bad characters but groups of consecutive bad characters with your string, unless you pay attention. You get one call to the error handler per run of bad chars, not per char.\n",
">>> help(\"\".encode)\nHelp on built-in function encode:\n\nencode(...)\nS.encode([encoding[,errors]]) -> object\n\nEncodes S using the codec registered for encoding. encoding defaults\nto the default encoding. errors may be given to set a different error\nhandling scheme. Default is 'strict' meaning that encoding errors raise\na UnicodeEncodeError. **Other possible values are** 'ignore', **'replace'** and\n'xmlcharrefreplace' as well as any other name registered with\ncodecs.register_error that is able to handle UnicodeEncodeErrors.\n\nSo, for instance:\n>>> x\n'\\xc3\\xa9b\\xc3\\xa1c is the word'\n>>> x.decode(\"ascii\")\nTraceback (most recent call last):\nFile \"<stdin>\", line 1, in <module>\nUnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)\n>>> x.decode(\"ascii\", \"replace\")\nu'\\ufffd\\ufffdb\\ufffd\\ufffdc is the word'\n\nAdd your own callback to codecs.register_error to replace with the string of your choice.\n"
] |
[
11,
5
] |
[] |
[] |
[
"encode",
"python",
"replace"
] |
stackoverflow_0001933184_encode_python_replace.txt
|
Q:
I want to display name in front of field instead of
..whatdoyoucallitanyway..
I have this model:
class Kaart(models.Model):
name = models.CharField(max_length=200, name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False)
url = models.CharField(max_length=200, blank=False, null=False, name="Asukoha URL", help_text="Täisasukoht (http://www.domeen.ee/kaart/)")
kirjeldus = models.TextField(max_length=500, name="Kommentaar", help_text="Informatsioon / viide tegijale (mitte kohustuslik)")
Then i have this form:
class KaartForm(ModelForm):
class Meta:
model = Kaart
And i have this code in my template:
{% for field in form %}
<p>
<label>{{ field.label }}</label>
<em>{{ field.help_text }}</em>
{{ field }}
</p>
{% endfor %}
The problem is that both field.label and field.name display name, url, kirjeldus instead of the names i have set for them - "Kaardi pealkiri" etc. How do i get to use those instead?
A:
You need to use verbose_name instead of name in your model.
name = models.CharField(max_length=200, verbose_name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False)
See the docs. There is no option called name.
A:
According to the documentation, the ModelForm's widget pulls its label value from the verbose_name attribute.
|
I want to display name in front of field instead of
|
..whatdoyoucallitanyway..
I have this model:
class Kaart(models.Model):
name = models.CharField(max_length=200, name="Kaardi peakiri", help_text="Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)", blank=False, null=False)
url = models.CharField(max_length=200, blank=False, null=False, name="Asukoha URL", help_text="Täisasukoht (http://www.domeen.ee/kaart/)")
kirjeldus = models.TextField(max_length=500, name="Kommentaar", help_text="Informatsioon / viide tegijale (mitte kohustuslik)")
Then i have this form:
class KaartForm(ModelForm):
class Meta:
model = Kaart
And i have this code in my template:
{% for field in form %}
<p>
<label>{{ field.label }}</label>
<em>{{ field.help_text }}</em>
{{ field }}
</p>
{% endfor %}
The problem is that both field.label and field.name display name, url, kirjeldus instead of the names i have set for them - "Kaardi pealkiri" etc. How do i get to use those instead?
|
[
"You need to use verbose_name instead of name in your model.\nname = models.CharField(max_length=200, verbose_name=\"Kaardi peakiri\", help_text=\"Sisesta kaardi pealkiri (maksimum tähemärkide arv on 38)\", blank=False, null=False)\n\nSee the docs. There is no option called name.\n",
"According to the documentation, the ModelForm's widget pulls its label value from the verbose_name attribute.\n"
] |
[
22,
0
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0001933299_django_django_forms_python.txt
|
Q:
Programmable transparent forward proxy
I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings.
I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in Ruby and Python that allow you to inspect each request response and log, modify, filter at will ... however these either fail to proxy everything needed or crash after 20 minutes of use.
On the other hand I suspect that Squid and Apache are quite robust and stable, however for the life of me I can't determine how I can develop dynamic behavior through scripting. Ultimately I would like to set quota's and dynamically filter on that quota. Part of me feels like mixing mod_proxy and mod_perl?? could allow interesting dynamic proxies, but its hard to know where to begin and know if its even possible.
Please advise.
A:
Squid and Apache both have mechanisms to call external scripts for allow/deny decisions per-request. This allows you to use either for their proxy engines, but call your external script per request for processing of arbitrary complexity. Your code only has to manage the business logic, not the heavy lifting.
In Apache, I've never used mod_proxy in this way, but I have used mod_rewrite. mod_rewrite also allows you to proxy requests. The RequestMap directive allows you to pass the decision to an external script:
MapType: prg, MapSource: Unix filesystem path to valid regular file
Here the source is a program, not a map file. To create it you can use a language of your choice, but the result has to be an executable program (either object-code or a script with the magic cookie trick '#!/path/to/interpreter' as the first line).
This program is started once, when the Apache server is started, and then communicates with the rewriting engine via its stdin and stdout file-handles. For each map-function lookup it will receive the key to lookup as a newline-terminated string on stdin. It then has to give back the looked-up value as a newline-terminated string on stdout or the four-character string ``NULL'' if it fails (i.e., there is no corresponding value for the given key).
With Squid, you can get similar functionality via the external_acl_type directive:
This tag defines how the external acl classes using a helper program should look up the status.
g'luck!
A:
If you looking for a Perl solution then take a look at HTTP::Proxy
Not sure of any mod_perl solutions though. CPAN does bring up Apache::Proxy and Googling brings up MyProxy. However note, both of these are a bit old so YMMV but you may find them a useful leg up.
A:
I've been working on a HTTP library in python, written with proxy servers specifically in mind as a use case. It isn't very mature at this point (certainly needs more testing, and unit tests), but it's complete enough that I find it useful. I don't know if it would meet any of your needs or not.
The library is called httpmessage, the google-code site is found here. There is an example of writing a proxy server on the examples page.
I'm happy to receive feedback and/or bug fixes.
A:
I'd use squid, which can execute other programs to change the requests on the fly.
|
Programmable transparent forward proxy
|
I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings.
I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in Ruby and Python that allow you to inspect each request response and log, modify, filter at will ... however these either fail to proxy everything needed or crash after 20 minutes of use.
On the other hand I suspect that Squid and Apache are quite robust and stable, however for the life of me I can't determine how I can develop dynamic behavior through scripting. Ultimately I would like to set quota's and dynamically filter on that quota. Part of me feels like mixing mod_proxy and mod_perl?? could allow interesting dynamic proxies, but its hard to know where to begin and know if its even possible.
Please advise.
|
[
"Squid and Apache both have mechanisms to call external scripts for allow/deny decisions per-request. This allows you to use either for their proxy engines, but call your external script per request for processing of arbitrary complexity. Your code only has to manage the business logic, not the heavy lifting.\nIn Apache, I've never used mod_proxy in this way, but I have used mod_rewrite. mod_rewrite also allows you to proxy requests. The RequestMap directive allows you to pass the decision to an external script:\n\nMapType: prg, MapSource: Unix filesystem path to valid regular file\nHere the source is a program, not a map file. To create it you can use a language of your choice, but the result has to be an executable program (either object-code or a script with the magic cookie trick '#!/path/to/interpreter' as the first line).\nThis program is started once, when the Apache server is started, and then communicates with the rewriting engine via its stdin and stdout file-handles. For each map-function lookup it will receive the key to lookup as a newline-terminated string on stdin. It then has to give back the looked-up value as a newline-terminated string on stdout or the four-character string ``NULL'' if it fails (i.e., there is no corresponding value for the given key).\n\nWith Squid, you can get similar functionality via the external_acl_type directive:\n\nThis tag defines how the external acl classes using a helper program should look up the status.\n\ng'luck!\n",
"If you looking for a Perl solution then take a look at HTTP::Proxy\nNot sure of any mod_perl solutions though. CPAN does bring up Apache::Proxy and Googling brings up MyProxy. However note, both of these are a bit old so YMMV but you may find them a useful leg up.\n",
"I've been working on a HTTP library in python, written with proxy servers specifically in mind as a use case. It isn't very mature at this point (certainly needs more testing, and unit tests), but it's complete enough that I find it useful. I don't know if it would meet any of your needs or not. \nThe library is called httpmessage, the google-code site is found here. There is an example of writing a proxy server on the examples page.\nI'm happy to receive feedback and/or bug fixes.\n",
"I'd use squid, which can execute other programs to change the requests on the fly.\n"
] |
[
3,
2,
2,
0
] |
[] |
[] |
[
"apache",
"perl",
"proxy",
"python",
"ruby"
] |
stackoverflow_0001933217_apache_perl_proxy_python_ruby.txt
|
Q:
Python - specify which function in file to use on command line
Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line?
Example:
python prog.py -x <<<filname>>>
Where -x tells python to go to a particular for loop and then execute the function called in that for loop?
Thanks,
Seafoid.
A:
The Python idiom for the main entry point:
if __name__ == '__main__':
main()
Replace main() by whatever function should go first ...
(more on if name ...: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm)
If you want to specify the function to run via command line argument, just check these arguments, either manually or via some helpers, e.g. http://docs.python.org/library/optparse.html, then branch of to the desired function.
If you don't want stuff like this:
if options.function_to_call == 'mydesiredfunction':
mydesiredfunction()
You can take advantage of getattr.
And finally, another 'generic' approach using globals (exception handling excluded):
$ cat 1933407.py
#!/usr/bin/env python
# coding: utf-8
import sys
def first():
print '1 of 9'
def second():
print '2 of 9'
def seventh():
print '7 of 9'
if __name__ == '__main__':
globals()[sys.argv[1]]()
Meanwhile at the command line ...
$ python 1933407.py second
2 of 9
A:
You want the sys module.
For example:
import sys
#Functions
def a(filename): pass
def b(filename): pass
def c(filename): pass
#Function chooser
func_arg = {"-a": a, "-b": b, "-c": c}
#Do it
if __name__ == "__main__":
func_arg[sys.argv[1]](sys.argv[2])
Which runs a(filename) if you run python file.py -a filename
A:
If you just want to use this to quickly test different functions during development and similar situations, you can use the -c command line parameter:
python -c 'import myfile; myfile.somefunc()'
A:
A very simple way is the following:
import sys
x_is_set=False
for arg in sys.argv[1:]:
if arg == '-x': x_is_set=True
if x_is_set:
print "-x is set"
A:
Yes, the built in functions 'exec()' and 'eval()' are your friends. Just add '()' to the name of the function. However, you should wonder whether this is the best solution for the actual problem. The fact that it is technically possible does not mean it is also the best solution. Using 'exec()' and 'eval()' is generally considered 'to be avoided'.
|
Python - specify which function in file to use on command line
|
Assume you have a programme with multiple functions defined. Each function is called in a separate for loop. Is it possible to specify which function should be called via the command line?
Example:
python prog.py -x <<<filname>>>
Where -x tells python to go to a particular for loop and then execute the function called in that for loop?
Thanks,
Seafoid.
|
[
"The Python idiom for the main entry point:\nif __name__ == '__main__':\n main()\n\nReplace main() by whatever function should go first ...\n(more on if name ...: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm)\nIf you want to specify the function to run via command line argument, just check these arguments, either manually or via some helpers, e.g. http://docs.python.org/library/optparse.html, then branch of to the desired function.\nIf you don't want stuff like this:\nif options.function_to_call == 'mydesiredfunction':\n mydesiredfunction()\n\nYou can take advantage of getattr. \nAnd finally, another 'generic' approach using globals (exception handling excluded):\n$ cat 1933407.py\n\n#!/usr/bin/env python\n# coding: utf-8\n\nimport sys\n\ndef first():\n print '1 of 9'\n\ndef second():\n print '2 of 9'\n\ndef seventh():\n print '7 of 9'\n\nif __name__ == '__main__':\n globals()[sys.argv[1]]()\n\nMeanwhile at the command line ...\n$ python 1933407.py second\n2 of 9\n\n",
"You want the sys module.\nFor example:\nimport sys\n\n#Functions\ndef a(filename): pass\ndef b(filename): pass\ndef c(filename): pass\n\n#Function chooser\nfunc_arg = {\"-a\": a, \"-b\": b, \"-c\": c}\n\n#Do it\nif __name__ == \"__main__\":\n func_arg[sys.argv[1]](sys.argv[2])\n\nWhich runs a(filename) if you run python file.py -a filename\n",
"If you just want to use this to quickly test different functions during development and similar situations, you can use the -c command line parameter:\npython -c 'import myfile; myfile.somefunc()'\n\n",
"A very simple way is the following:\nimport sys\n\nx_is_set=False\nfor arg in sys.argv[1:]:\n if arg == '-x': x_is_set=True\n\nif x_is_set:\n print \"-x is set\"\n\n",
"Yes, the built in functions 'exec()' and 'eval()' are your friends. Just add '()' to the name of the function. However, you should wonder whether this is the best solution for the actual problem. The fact that it is technically possible does not mean it is also the best solution. Using 'exec()' and 'eval()' is generally considered 'to be avoided'.\n"
] |
[
10,
9,
4,
1,
0
] |
[] |
[] |
[
"command_line",
"function",
"python"
] |
stackoverflow_0001933400_command_line_function_python.txt
|
Q:
Deepcopy a simple Python object
I have an object which defines a __deepcopy__ method. I would like a function that will deepcopy it not by the method given by it, but in the default way that objects of the class object are copied.
How could I do that? I think I could try to code it but there are probably many "gotchas" I won't be thinking of.
The reason I'm doing it is because I have an object class which implements a __deepcopy__ method, and that method checks for some condition, and in some cases it will deepcopy the object in a certain way, and in other cases it will deepcopy in the default object way.
A:
You basically need to override the existing __deepcopy__ method, which means temporarily setting the object's class to something different -- whether that's acceptable essentially depends on whether the "__deepcopy__ override" needs to affect only one, "top-level" object (in which case the kludge's probably OK), or if there are many objects of that class in the graph you're copying, in which case it's quite a mess. Which case obtains?
|
Deepcopy a simple Python object
|
I have an object which defines a __deepcopy__ method. I would like a function that will deepcopy it not by the method given by it, but in the default way that objects of the class object are copied.
How could I do that? I think I could try to code it but there are probably many "gotchas" I won't be thinking of.
The reason I'm doing it is because I have an object class which implements a __deepcopy__ method, and that method checks for some condition, and in some cases it will deepcopy the object in a certain way, and in other cases it will deepcopy in the default object way.
|
[
"You basically need to override the existing __deepcopy__ method, which means temporarily setting the object's class to something different -- whether that's acceptable essentially depends on whether the \"__deepcopy__ override\" needs to affect only one, \"top-level\" object (in which case the kludge's probably OK), or if there are many objects of that class in the graph you're copying, in which case it's quite a mess. Which case obtains?\n"
] |
[
4
] |
[] |
[] |
[
"deep_copy",
"python"
] |
stackoverflow_0001933621_deep_copy_python.txt
|
Q:
How to refactor this python code block to be more efficient
This code block works - it loops through a file that has a repeating number of sets of data
and extracts out each of the 5 pieces of information for each set.
But I I know that the current factoring is not as efficient as it can be since it is looping
through each key for each line found.
Wondering if some python gurus can offer better way to do this more efficiently.
def parse_params(num_of_params,lines):
for line in lines:
for p in range(1,num_of_params + 1,1):
nam = "model.paramName "+str(p)+" "
par = "model.paramValue "+str(p)+" "
opt = "model.optimizeParam "+str(p)+" "
low = "model.paramLowerBound "+str(p)+" "
upp = "model.paramUpperBound "+str(p)+" "
keys = [nam,par,opt,low,upp]
for key in keys:
if key in line:
a,val = line.split(key)
if key == nam: names.append(val.rstrip())
if key == par: params.append(val.rstrip())
if key == opt: optimize.append(val.rstrip())
if key == upp: upper.append(val.rstrip())
if key == low: lower.append(val.rstrip())
print "Names = ",names
print "Params = ",params
print "Optimize = ",optimize
print "Upper = ",upper
print "Lower = ",lower
A:
Though this doesn't answer your question (other answers are getting at that) something that has helped me a lot in doing things similar to what you're doing are List Comprehensions. They allow you to build lists in a concise and (I think) easy to read way.
For instance, the below code builds a 2-dimenstional array with the values you're trying to get at. some_funct here would be a little regex, if I were doing it, that uses the index of the last space in the key as the parameter, and looks ahead to collect the value you're trying to get in the line (the value which corresponds to the key currently being looked at) and appends it to the correct index in the seen_keys 2D array.
Wordy, yes, but if you get list-comprehension and you're able to construct the regex to do that, you've got a nice, concise solution.
keys = ["model.paramName ","model.paramValue ","model.optimizeParam ""model.paramLowerBound ","model.paramUpperBound "]
for line in lines:
seen_keys = [[],[],[],[],[]]
[seen_keys[keys.index(k)].some_funct(line.index(k) for k in keys if k in line]
A:
There is a lot of duplication there, and if you ever add another key or param, you're going to have to add it in many places, which leaves you ripe for errors. What you want to do is pare down all of the places you have repeated things and use some sort of data model, such as a dict.
Some others have provided some excellent examples, so I'll just leave my answer here to give you something to think about.
A:
It's not totally easy to see the expected format. From what I can see, the format is like:
lines = [
"model.paramName 1 foo",
"model.paramValue 2 bar",
"model.optimizeParam 3 bat",
"model.paramLowerBound 4 zip",
"model.paramUpperBound 5 ech",
"model.paramName 1 foo2",
"model.paramValue 2 bar2",
"model.optimizeParam 3 bat2",
"model.paramLowerBound 4 zip2",
"model.paramUpperBound 5 ech2",
]
I don't see the above code working if there is more than one value in each line. Which means the digit is not really significant unless I'm missing something. In that case this works very easily:
import re
def parse_params(num_of_params,lines):
key_to_collection = {
"model.paramName":names,
"model.paramValue":params,
"model.optimizeParam":optimize,
"model.paramLowerBound":upper,
"model.paramUpperBound":lower,
}
reg = re.compile(r'(.+?) (\d) (.+)')
for line in lines:
m = reg.match(line)
key, digit, value = m.group(1, 2, 3)
key_to_collection[key].append(value)
A:
It's not entirely obvious from your code, but it looks like each line can have one "hit" at most; if that's indeed the case, then something like:
import re
def parse_params(num_of_params, lines):
sn = 'Names Params Optimize Upper Lower'.split()
ks = '''paramName paramValue optimizeParam
paramLowerBound paramUpperBound'''.split()
vals = dict((k, []) for k in ks)
are = re.compile(r'model\.(%s) (\d+) (.*)' % '|'.join(ks))
for line in lines:
mo = are.search(line)
if not mo: continue
p = int(mo.group(2))
if p < 1 or p > num_of_params: continue
vals[mo.group(1)].append(mo.group(3).rstrip())
for k, s in zip(ks, sn):
print '%-8s =' % s,
print vals[k]
might work -- I exercised it with a little code as follows:
if __name__ == '__main__':
lines = '''model.paramUpperBound 1 ZAP
model.paramLowerBound 1 zap
model.paramUpperBound 5 nope'''.splitlines()
parse_params(2, lines)
and it emits
Names = []
Params = []
Optimize = []
Upper = ['zap']
Lower = ['ZAP']
which I think is what you want (if some details must differ, please indicate exactly what they are and let's see if we can fix it).
The two key ideas are: use a dict instead of lots of ifs; use a re to match "any of the following possibilities" with parenthesized groups in the re's pattern to catch the bits of interest (the keyword after model., the integer number after that, and the "value" which is the rest of the line) instead of lots of if x in y checks and string manipulation.
A:
The code given in the OP does multiple tests per line to try to match against the expected set of values, each of which is being constructed on the fly. Rather than construct paramValue1, paramValue2, etc. for each line, we can use a regular expression to try to do the matching in a cheaper (and more robust) manner.
Here's my code snippet, drawing from some ideas that have already been posted. This lets you add a new keyword to the key_to_collection dictionary and not have to change anything else.
import re
def parse_params(num_of_params, lines):
pattern = re.compile(r"""
model\.
(.+) # keyword
(\d+) # index to keyword
[ ]+ # whitespace
(.+) # value
""", re.VERBOSE)
key_to_collection = {
"paramName": names,
"paramValue": params,
"optimizeParam": optimize,
"paramLowerBound": upper,
"paramUpperBound": lower,
}
for line in lines:
match = pattern.match(line)
if not match:
print "Invalid line: " + line
elif match[1] not in key_to_collection:
print "Invalid key: " + line
# Not sure if you really care about enforcing this
elif match[2] > num_of_params:
print "Invalid param: " + line
else:
key_to_collection[match[1]].append(match[3])
Full disclosure: I have not compiled/tested this.
A:
Are you sure that parse_params is the bottle-neck? Have you profiled your app?
import re
from collections import defaultdict
names = ("paramName paramValue optimizeParam "
"paramLowerBound paramUpperBound".split())
stmt_regex = re.compile(r'model\.(%s)\s+(\d+)\s+(.*)' % '|'.join(names))
def parse_params(num_of_params, lines):
stmts = defaultdict(list)
for m in (stmt_regex.match(s) for s in lines):
if m and 1 <= int(m.group(2)) <= num_of_params:
stmts[m.group(1)].append(m.group(3).rstrip())
for k, v in stmts.iteritems():
print "%s = %s" % (k, ' '.join(v))
A:
It can certainly be made more efficient. But, to be honest, unless this function is called hundreds of times a second, or works on thousands of lines, is it necessary?
I would be more concerned about making it clear what is happening... currently, I'm far from clear on that aspect.
Just eyeballing it, the input seems to look like this:
model.paramName 1 A model.paramValue 1 B model.optimizeParam 1 C model.paramLowerBound 1 D model.paramUpperBound 1 E model.paramName 2 F model.paramValue 2 G model.optimizeParam 2 H model.paramLowerBound 2 I model.paramUpperBound 2 J
And your desired output seems to be something like:
Names = AF
Params = BG
etc...
Now, since my input certainly doesn't match yours, the output is likely off too, but I think I have the gist.
There are a few points. First, does it matter how many parameters are passed to the function? For example, if the input has two sets of parameters, do I just want to read both, or is it necessary to allow the function to only read one? For example, your code allows me to call parse_params(1,1) and have it only read parameters ending in a 1 from the same input. If that's not actually a requirement, you can skip a large chunk of the code.
Second, is it important to ONLY read the given parameters? If I, for example, have a parameter called 'paramFoo', is it bad if I read it? You can also simplify the procedure by just grabbing all parameters regardless of their name, and extracting their value.
def parse_params(input):
parameter_list = {}
param = re.compile(r"model\.([^ ]+) [0-9]+ ([^ ]+)")
each_parameter = param.finditer(input)
for match in each_parameter:
key = match[0]
value = match[1]
if not key in paramter_list:
parameter_list[key] = []
parameter_list[key].append(value)
return parameter_list
The output, in this instance, will be something like this:
{'paramName':[A, F], 'paramValue':[B, G], 'optimizeParam':[C, H], etc...}
Notes: I don't know Python well, I'm a Ruby guy, so my syntax may be off. Apologies.
|
How to refactor this python code block to be more efficient
|
This code block works - it loops through a file that has a repeating number of sets of data
and extracts out each of the 5 pieces of information for each set.
But I I know that the current factoring is not as efficient as it can be since it is looping
through each key for each line found.
Wondering if some python gurus can offer better way to do this more efficiently.
def parse_params(num_of_params,lines):
for line in lines:
for p in range(1,num_of_params + 1,1):
nam = "model.paramName "+str(p)+" "
par = "model.paramValue "+str(p)+" "
opt = "model.optimizeParam "+str(p)+" "
low = "model.paramLowerBound "+str(p)+" "
upp = "model.paramUpperBound "+str(p)+" "
keys = [nam,par,opt,low,upp]
for key in keys:
if key in line:
a,val = line.split(key)
if key == nam: names.append(val.rstrip())
if key == par: params.append(val.rstrip())
if key == opt: optimize.append(val.rstrip())
if key == upp: upper.append(val.rstrip())
if key == low: lower.append(val.rstrip())
print "Names = ",names
print "Params = ",params
print "Optimize = ",optimize
print "Upper = ",upper
print "Lower = ",lower
|
[
"Though this doesn't answer your question (other answers are getting at that) something that has helped me a lot in doing things similar to what you're doing are List Comprehensions. They allow you to build lists in a concise and (I think) easy to read way. \nFor instance, the below code builds a 2-dimenstional array with the values you're trying to get at. some_funct here would be a little regex, if I were doing it, that uses the index of the last space in the key as the parameter, and looks ahead to collect the value you're trying to get in the line (the value which corresponds to the key currently being looked at) and appends it to the correct index in the seen_keys 2D array. \nWordy, yes, but if you get list-comprehension and you're able to construct the regex to do that, you've got a nice, concise solution. \nkeys = [\"model.paramName \",\"model.paramValue \",\"model.optimizeParam \"\"model.paramLowerBound \",\"model.paramUpperBound \"]\nfor line in lines:\n seen_keys = [[],[],[],[],[]]\n [seen_keys[keys.index(k)].some_funct(line.index(k) for k in keys if k in line]\n\n",
"There is a lot of duplication there, and if you ever add another key or param, you're going to have to add it in many places, which leaves you ripe for errors. What you want to do is pare down all of the places you have repeated things and use some sort of data model, such as a dict.\nSome others have provided some excellent examples, so I'll just leave my answer here to give you something to think about.\n",
"It's not totally easy to see the expected format. From what I can see, the format is like:\nlines = [\n \"model.paramName 1 foo\",\n \"model.paramValue 2 bar\",\n \"model.optimizeParam 3 bat\",\n \"model.paramLowerBound 4 zip\",\n \"model.paramUpperBound 5 ech\",\n \"model.paramName 1 foo2\",\n \"model.paramValue 2 bar2\",\n \"model.optimizeParam 3 bat2\",\n \"model.paramLowerBound 4 zip2\",\n \"model.paramUpperBound 5 ech2\",\n]\n\nI don't see the above code working if there is more than one value in each line. Which means the digit is not really significant unless I'm missing something. In that case this works very easily:\nimport re\n\ndef parse_params(num_of_params,lines):\n key_to_collection = {\n \"model.paramName\":names,\n \"model.paramValue\":params,\n \"model.optimizeParam\":optimize,\n \"model.paramLowerBound\":upper,\n \"model.paramUpperBound\":lower,\n }\n\n reg = re.compile(r'(.+?) (\\d) (.+)')\n\n for line in lines:\n m = reg.match(line)\n key, digit, value = m.group(1, 2, 3)\n key_to_collection[key].append(value)\n\n",
"It's not entirely obvious from your code, but it looks like each line can have one \"hit\" at most; if that's indeed the case, then something like:\nimport re\n\ndef parse_params(num_of_params, lines):\n sn = 'Names Params Optimize Upper Lower'.split()\n ks = '''paramName paramValue optimizeParam\n paramLowerBound paramUpperBound'''.split()\n vals = dict((k, []) for k in ks)\n are = re.compile(r'model\\.(%s) (\\d+) (.*)' % '|'.join(ks))\n for line in lines:\n mo = are.search(line)\n if not mo: continue\n p = int(mo.group(2))\n if p < 1 or p > num_of_params: continue\n vals[mo.group(1)].append(mo.group(3).rstrip())\n for k, s in zip(ks, sn):\n print '%-8s =' % s,\n print vals[k]\n\nmight work -- I exercised it with a little code as follows:\nif __name__ == '__main__':\n lines = '''model.paramUpperBound 1 ZAP\n model.paramLowerBound 1 zap\n model.paramUpperBound 5 nope'''.splitlines()\n parse_params(2, lines)\n\nand it emits\nNames = []\nParams = []\nOptimize = []\nUpper = ['zap']\nLower = ['ZAP']\n\nwhich I think is what you want (if some details must differ, please indicate exactly what they are and let's see if we can fix it).\nThe two key ideas are: use a dict instead of lots of ifs; use a re to match \"any of the following possibilities\" with parenthesized groups in the re's pattern to catch the bits of interest (the keyword after model., the integer number after that, and the \"value\" which is the rest of the line) instead of lots of if x in y checks and string manipulation.\n",
"The code given in the OP does multiple tests per line to try to match against the expected set of values, each of which is being constructed on the fly. Rather than construct paramValue1, paramValue2, etc. for each line, we can use a regular expression to try to do the matching in a cheaper (and more robust) manner.\nHere's my code snippet, drawing from some ideas that have already been posted. This lets you add a new keyword to the key_to_collection dictionary and not have to change anything else.\nimport re\n\ndef parse_params(num_of_params, lines):\n\n pattern = re.compile(r\"\"\"\n model\\.\n (.+) # keyword\n (\\d+) # index to keyword\n [ ]+ # whitespace\n (.+) # value\n \"\"\", re.VERBOSE)\n\n key_to_collection = {\n \"paramName\": names,\n \"paramValue\": params,\n \"optimizeParam\": optimize,\n \"paramLowerBound\": upper,\n \"paramUpperBound\": lower,\n }\n\n for line in lines:\n match = pattern.match(line)\n if not match:\n print \"Invalid line: \" + line\n elif match[1] not in key_to_collection:\n print \"Invalid key: \" + line\n # Not sure if you really care about enforcing this\n elif match[2] > num_of_params:\n print \"Invalid param: \" + line\n else:\n key_to_collection[match[1]].append(match[3])\n\nFull disclosure: I have not compiled/tested this.\n",
"Are you sure that parse_params is the bottle-neck? Have you profiled your app?\nimport re\nfrom collections import defaultdict \n\nnames = (\"paramName paramValue optimizeParam \"\n \"paramLowerBound paramUpperBound\".split())\nstmt_regex = re.compile(r'model\\.(%s)\\s+(\\d+)\\s+(.*)' % '|'.join(names))\n\ndef parse_params(num_of_params, lines):\n stmts = defaultdict(list)\n for m in (stmt_regex.match(s) for s in lines):\n if m and 1 <= int(m.group(2)) <= num_of_params: \n stmts[m.group(1)].append(m.group(3).rstrip())\n\n for k, v in stmts.iteritems():\n print \"%s = %s\" % (k, ' '.join(v))\n\n",
"It can certainly be made more efficient. But, to be honest, unless this function is called hundreds of times a second, or works on thousands of lines, is it necessary?\nI would be more concerned about making it clear what is happening... currently, I'm far from clear on that aspect.\nJust eyeballing it, the input seems to look like this:\nmodel.paramName 1 A model.paramValue 1 B model.optimizeParam 1 C model.paramLowerBound 1 D model.paramUpperBound 1 E model.paramName 2 F model.paramValue 2 G model.optimizeParam 2 H model.paramLowerBound 2 I model.paramUpperBound 2 J\nAnd your desired output seems to be something like:\nNames = AF\nParams = BG\netc...\nNow, since my input certainly doesn't match yours, the output is likely off too, but I think I have the gist.\nThere are a few points. First, does it matter how many parameters are passed to the function? For example, if the input has two sets of parameters, do I just want to read both, or is it necessary to allow the function to only read one? For example, your code allows me to call parse_params(1,1) and have it only read parameters ending in a 1 from the same input. If that's not actually a requirement, you can skip a large chunk of the code.\nSecond, is it important to ONLY read the given parameters? If I, for example, have a parameter called 'paramFoo', is it bad if I read it? You can also simplify the procedure by just grabbing all parameters regardless of their name, and extracting their value.\ndef parse_params(input):\n parameter_list = {}\n param = re.compile(r\"model\\.([^ ]+) [0-9]+ ([^ ]+)\")\n each_parameter = param.finditer(input)\n for match in each_parameter:\n key = match[0]\n value = match[1]\n if not key in paramter_list:\n parameter_list[key] = []\n\n parameter_list[key].append(value)\n\n return parameter_list\nThe output, in this instance, will be something like this:\n{'paramName':[A, F], 'paramValue':[B, G], 'optimizeParam':[C, H], etc...}\nNotes: I don't know Python well, I'm a Ruby guy, so my syntax may be off. Apologies.\n"
] |
[
2,
1,
1,
1,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001933564_python.txt
|
Q:
How do you clone a class in Python?
I have a class A and i want a class B with exactly the same capabilities.
I cannot or do not want to inherit from B, such as doing class B(A):pass
Still i want B to be identical to A, yet have a different i: id(A) != id(B)
Watch out, i am not talking about instances but classes to be cloned.
A:
I'm pretty sure whatever you are trying to do can be solved in a better way, but here is something that gives you a clone of the class with a new id:
def c():
class Clone(object):
pass
return Clone
c1 = c()
c2 = c()
print id(c1)
print id(c2)
gives:
4303713312
4303831072
A:
I guess this is not what you wanted but its what the question seems to be asking for...
class Foo(object):
def bar(self):
return "BAR!"
cls = type("Bar", (object,), dict(Foo.__dict__))
print cls
x = cls()
print x.bar()
A:
maybe i misunderstood you question but what about wrapping A in B?
class A:
def foo(self):
print "A.foo"
class B:
def __init__(self):
self._i = A()
def __getattr__(self, n):
return getattr(self._i, n)
|
How do you clone a class in Python?
|
I have a class A and i want a class B with exactly the same capabilities.
I cannot or do not want to inherit from B, such as doing class B(A):pass
Still i want B to be identical to A, yet have a different i: id(A) != id(B)
Watch out, i am not talking about instances but classes to be cloned.
|
[
"I'm pretty sure whatever you are trying to do can be solved in a better way, but here is something that gives you a clone of the class with a new id:\ndef c():\n class Clone(object):\n pass\n\n return Clone\n\nc1 = c()\nc2 = c()\nprint id(c1)\nprint id(c2)\n\ngives:\n4303713312\n4303831072\n\n",
"I guess this is not what you wanted but its what the question seems to be asking for...\nclass Foo(object):\n def bar(self):\n return \"BAR!\"\n\ncls = type(\"Bar\", (object,), dict(Foo.__dict__))\n\nprint cls\n\nx = cls()\nprint x.bar()\n\n",
"maybe i misunderstood you question but what about wrapping A in B?\nclass A:\n\n def foo(self):\n print \"A.foo\"\n\nclass B:\n\n def __init__(self):\n self._i = A()\n\n def __getattr__(self, n):\n return getattr(self._i, n)\n\n"
] |
[
14,
9,
0
] |
[
"You can clone the class via inheritance. Otherwise you are just passing around a reference to the class itself (rather than a reference to an instance of the class). Why would you want to duplicate the class anyway? It's obvious why you would want to create multiple instances of the class, but I can't fathom why you would want a duplicate class. Also, you could simply copy and paste with a new class name...\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0001933784_python.txt
|
Q:
How to load remote javascript into a SpiderMonkey context?
I have a server which will be serving up javascript files, I need to grab it and execute some of it's functions using SpiderMonkey in python. How can I do this?
A:
hope the following example helps:
>>> import urllib2
>>> import spidermonkey
>>> js = spidermonkey.Runtime()
>>> js_ctx = js.new_context()
>>> script = urllib2.urlopen('http://etherhack.co.uk/hashing/whirlpool/js/whirlpool.js').read()
>>> js_ctx.eval_script(script)
>>> js_ctx.eval_script('var s = "abc"')
>>> js_ctx.eval_script('print(HexWhirlpool(s))')
4E2448A4C6F486BB16B6562C73B4020BF3043E3A731BCE721AE1B303D97E6D4C7181EEBDB6C57E277D0E34957114CBD6C797FC9D95D8B582D225292076D4EEF5
|
How to load remote javascript into a SpiderMonkey context?
|
I have a server which will be serving up javascript files, I need to grab it and execute some of it's functions using SpiderMonkey in python. How can I do this?
|
[
"hope the following example helps:\n>>> import urllib2\n>>> import spidermonkey\n>>> js = spidermonkey.Runtime()\n>>> js_ctx = js.new_context()\n>>> script = urllib2.urlopen('http://etherhack.co.uk/hashing/whirlpool/js/whirlpool.js').read()\n>>> js_ctx.eval_script(script)\n>>> js_ctx.eval_script('var s = \"abc\"')\n>>> js_ctx.eval_script('print(HexWhirlpool(s))')\n4E2448A4C6F486BB16B6562C73B4020BF3043E3A731BCE721AE1B303D97E6D4C7181EEBDB6C57E277D0E34957114CBD6C797FC9D95D8B582D225292076D4EEF5\n\n"
] |
[
1
] |
[] |
[] |
[
"http",
"javascript",
"python",
"spidermonkey"
] |
stackoverflow_0001931688_http_javascript_python_spidermonkey.txt
|
Q:
help with python urllib2 import error
In my script, I've imported urrlib2 and the script was working fine. After reboot, I get the following error:
File "demo.py", line 2, in <module>
import urllib2
File "/usr/lib/python2.6/urllib2.py", line 92, in <module>
import httplib
File "/usr/lib/python2.6/httplib.py", line 78, in <module>
import mimetools
File "/usr/lib/python2.6/mimetools.py", line 6, in <module>
import tempfile
File "/usr/lib/python2.6/tempfile.py", line 34, in <module>
from random import Random as _Random
ImportError: cannot import name Random
And when I do import random separately, it works fine. Any ideas what might be wrong?
I'm using ubuntu 9.10 (up to date). thanks
A:
The usual answer is that you've got a file called random.py in the current directory when the script is running. tempfile would be accidentally importing that random and not the stdlib random module.
A:
Check that random is the stdlib's module and not some arbitrary module with the same name from sys.path.
>>> inspect.getabsfile(random)
|
help with python urllib2 import error
|
In my script, I've imported urrlib2 and the script was working fine. After reboot, I get the following error:
File "demo.py", line 2, in <module>
import urllib2
File "/usr/lib/python2.6/urllib2.py", line 92, in <module>
import httplib
File "/usr/lib/python2.6/httplib.py", line 78, in <module>
import mimetools
File "/usr/lib/python2.6/mimetools.py", line 6, in <module>
import tempfile
File "/usr/lib/python2.6/tempfile.py", line 34, in <module>
from random import Random as _Random
ImportError: cannot import name Random
And when I do import random separately, it works fine. Any ideas what might be wrong?
I'm using ubuntu 9.10 (up to date). thanks
|
[
"The usual answer is that you've got a file called random.py in the current directory when the script is running. tempfile would be accidentally importing that random and not the stdlib random module.\n",
"Check that random is the stdlib's module and not some arbitrary module with the same name from sys.path.\n>>> inspect.getabsfile(random)\n\n"
] |
[
5,
0
] |
[] |
[] |
[
"import",
"python",
"urllib2"
] |
stackoverflow_0001933928_import_python_urllib2.txt
|
Q:
A pythonic way how to find if a value is between two values in a list
Having a sorted list and some random value, I would like to find in which range the value is.
List goes like this: [0, 5, 10, 15, 20]
And value is, say 8.
The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform binary search.
grid = [0, 5, 10, 15, 20]
value = 8
result_index = 0
while result_index < len(grid) and grid[result_index] < value:
result_index += 1
print result_index
I am wondering if there is a more pythonic approach, as this although short, looks bit of an eye sore.
Thank you for your time!
A:
>>> import bisect
>>> grid = [0, 5, 10, 15, 20]
>>> value = 8
>>> bisect.bisect(grid, value)
2
Edit:
bisect — Array bisection algorithm
A:
for min, max in zip(grid, grid[1:]): # [(0, 5), (5, 10), (10, 15), (15, 20), (20, 25)]
if max <= value < min: #previously: if value in xrange(min, max):
return min, max
raise ValueError("value out of range")
|
A pythonic way how to find if a value is between two values in a list
|
Having a sorted list and some random value, I would like to find in which range the value is.
List goes like this: [0, 5, 10, 15, 20]
And value is, say 8.
The standard way would be to either go from start until we hit value that is bigger than ours (like in the example below), or to perform binary search.
grid = [0, 5, 10, 15, 20]
value = 8
result_index = 0
while result_index < len(grid) and grid[result_index] < value:
result_index += 1
print result_index
I am wondering if there is a more pythonic approach, as this although short, looks bit of an eye sore.
Thank you for your time!
|
[
">>> import bisect\n>>> grid = [0, 5, 10, 15, 20]\n>>> value = 8\n>>> bisect.bisect(grid, value)\n2\n\nEdit:\nbisect — Array bisection algorithm\n",
"for min, max in zip(grid, grid[1:]): # [(0, 5), (5, 10), (10, 15), (15, 20), (20, 25)]\n if max <= value < min: #previously: if value in xrange(min, max):\n return min, max\nraise ValueError(\"value out of range\")\n\n"
] |
[
20,
1
] |
[] |
[] |
[
"grid",
"list",
"python",
"range",
"snapping"
] |
stackoverflow_0001933919_grid_list_python_range_snapping.txt
|
Q:
python - urrlib2 request https site - getting 400 error
using the following snip of code to access a url with a post.
i can get it using wget and the following:
wget --post-data 'p_calling_proc=bwckschd.p_disp_dyn_sched&p_term=201010' https://spectrumssb2.memphis.edu/pls/PROD/bwckgens.p_proc_term_date
for some reason, i'm having an issue with my python text, in that i get a errorcode of 400. (and of course the browser works as expected)
any thoughts/comments/etc...
the python test that i have:
//==========================================
import urllib
import urllib2
import sys, string
import time
import mechanize
Request = urllib2.Request
urlopen = urllib2.urlopen
headers ={'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
query = "p_calling_proc%3Dbwckschd.p_disp_dyn_sched%26p_term%3D201010"
url1="https://spectrumssb2.memphis.edu/pls/PROD/bwckgens.p_proc_term_date"
req = Request(url1, query, headers)
test1=0
test=0
while test==0:
print "aaaaattttt \n"
try:
res = urlopen(req)
#req = Request(url1, query, headers)
print "aaaappppp \n"
#urllib2.URLError, (e)
#print e
except urllib2.HTTPError, e:
print "ffff1111 "+str(e.code)+"\n"
if e.code:
test1=1
print "error ..sleep \n"
time.sleep(1)
else:
test1=0
except urllib2.URLError, e:
print e.reason
#print "ffff3333 "+e.code+"\n"
if e.reason:
test1=1
print "error ..sleep \n"
time.sleep(1)
else:
test1=0
#print "ddd "+e.code +"\n"
#print e
if test1==0:
test=1
print "test1 = "+str(test1)+"\n"
#res = urlopen(req)
print "gggg 000000000000\n"
s = res.read()
.
any thoughts/comments would be appreciated..
thanks
A:
Try not encoding the query string. The &'s and ='s in the POST data don't need to be urlencoded. If the web app on the remote end does not expect the %xx encoding in the query string, it won't be able to parse it.
Here's curl's HTTP request headers:
POST / HTTP/1.1
User-Agent: curl/7.19.4 (universal-apple-darwin10.0) libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3
Host: 127.0.0.1
Accept: */*
Content-Length: 188
Expect: 100-continue
bwckschd.p_disp_dyn_sched&p_term=201010
And here's the HTTP request headers from your python:
POST / HTTP/1.1
Accept-Encoding: identity
Content-Length: 60
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Connection: close
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)
p_calling_proc%3Dbwckschd.p_disp_dyn_sched%26p_term%3D201010
A:
I think your query string is not quite right. Try using the urllib.urlencode() method to generate the query, a la
urllib.urlencode([ ('param1', value1), ('param2',value2) ])
|
python - urrlib2 request https site - getting 400 error
|
using the following snip of code to access a url with a post.
i can get it using wget and the following:
wget --post-data 'p_calling_proc=bwckschd.p_disp_dyn_sched&p_term=201010' https://spectrumssb2.memphis.edu/pls/PROD/bwckgens.p_proc_term_date
for some reason, i'm having an issue with my python text, in that i get a errorcode of 400. (and of course the browser works as expected)
any thoughts/comments/etc...
the python test that i have:
//==========================================
import urllib
import urllib2
import sys, string
import time
import mechanize
Request = urllib2.Request
urlopen = urllib2.urlopen
headers ={'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
query = "p_calling_proc%3Dbwckschd.p_disp_dyn_sched%26p_term%3D201010"
url1="https://spectrumssb2.memphis.edu/pls/PROD/bwckgens.p_proc_term_date"
req = Request(url1, query, headers)
test1=0
test=0
while test==0:
print "aaaaattttt \n"
try:
res = urlopen(req)
#req = Request(url1, query, headers)
print "aaaappppp \n"
#urllib2.URLError, (e)
#print e
except urllib2.HTTPError, e:
print "ffff1111 "+str(e.code)+"\n"
if e.code:
test1=1
print "error ..sleep \n"
time.sleep(1)
else:
test1=0
except urllib2.URLError, e:
print e.reason
#print "ffff3333 "+e.code+"\n"
if e.reason:
test1=1
print "error ..sleep \n"
time.sleep(1)
else:
test1=0
#print "ddd "+e.code +"\n"
#print e
if test1==0:
test=1
print "test1 = "+str(test1)+"\n"
#res = urlopen(req)
print "gggg 000000000000\n"
s = res.read()
.
any thoughts/comments would be appreciated..
thanks
|
[
"Try not encoding the query string. The &'s and ='s in the POST data don't need to be urlencoded. If the web app on the remote end does not expect the %xx encoding in the query string, it won't be able to parse it. \nHere's curl's HTTP request headers:\nPOST / HTTP/1.1\nUser-Agent: curl/7.19.4 (universal-apple-darwin10.0) libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3\nHost: 127.0.0.1 \nAccept: */*\nContent-Length: 188\nExpect: 100-continue\n\nbwckschd.p_disp_dyn_sched&p_term=201010\n\nAnd here's the HTTP request headers from your python:\nPOST / HTTP/1.1\nAccept-Encoding: identity\nContent-Length: 60\nHost: 127.0.0.1\nContent-Type: application/x-www-form-urlencoded\nConnection: close\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)\n\np_calling_proc%3Dbwckschd.p_disp_dyn_sched%26p_term%3D201010\n\n",
"I think your query string is not quite right. Try using the urllib.urlencode() method to generate the query, a la\nurllib.urlencode([ ('param1', value1), ('param2',value2) ])\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"https",
"parsing",
"python",
"request",
"urllib2"
] |
stackoverflow_0001934284_https_parsing_python_request_urllib2.txt
|
Q:
Editing the XML texts from a XML file using Python
I have an XML file which contains some data as given.
<?xml version="1.0" encoding="UTF-8" ?>
- <ParameterData>
<CreationInfo date="10/28/2009 03:05:14 PM" user="manoj" />
- <ParameterList count="85">
- <Parameter name="Spec 2 Included" type="boolean" mode="both">
<Value>n/a</Value>
<Result>n/a</Result>
</Parameter>
- <Parameter name="Spec 2 Label" type="string" mode="both">
<Value>n/a</Value>
<Result>n/a</Result>
</Parameter>
- <Parameter name="Spec 3 Included" type="boolean" mode="both">
<Value>n/a</Value>
<Result>n/a</Result>
</Parameter>
- <Parameter name="Spec 3 Label" type="string" mode="both">
<Value>n/a</Value>
<Result>n/a</Result>
</Parameter>
</ParameterList>
</ParameterData>
I have one text file with lines as
Spec 2 Included : TRUE
Spec 2 Label: 19-Flat2-HS3
Spec 3 Included : FALSE
Spec 3 Label: 4-1-Bead1-HS3
Now I want to edit XML texts; i,e. I want to replace the field (n/a)
with the corresponding values from the text file.
Like I want the file to looks like
<?xml version="1.0" encoding="UTF-8" ?>
- <ParameterData>
<CreationInfo date="10/28/2009 03:05:14 PM" user="manoj" />
- <ParameterList count="85">
- <Parameter name="Spec 2 Included" type="boolean" mode="both">
<Value>TRUE</Value>
<Result>TRUE</Result>
</Parameter>
- <Parameter name="Spec 2 Label" type="string" mode="both">
<Value>19-Flat2-HS3</Value>
<Result>19-Flat2-HS3</Result>
</Parameter>
- <Parameter name="Spec 3 Included" type="boolean" mode="both">
<Value>FALSE</Value>
<Result>FALSE</Result>
</Parameter>
- <Parameter name="Spec 3 Label" type="string" mode="both">
<Value>4-1-Bead1-HS3</Value>
<Result>4-1-Bead1-HS3</Result>
</Parameter>
</ParameterList>
</ParameterData>
I am new to this Python-XML coding.
I dont have idea about how to edit the text fields in a XML file.
I am trying to Use elementtree.ElementTree module.
but to read the lines in XML file and extract the attributes I dont know which modules need to be imported.
Please help.
Thanks and Regards.
A:
You can convert your data text into python dictionary by regular expression
data="""Spec 2 Included : TRUE
Spec 2 Label: 19-Flat2-HS3
Spec 3 Included : FALSE
Spec 3 Label: 4-1-Bead1-HS3"""
#data=open("data.txt").read()
import re
data=dict(re.findall('(Spec \d+ (?:Included|Label))\s*:\s*(\S+)',data))
data will be as follows
{'Spec 3 Included': 'FALSE', 'Spec 2 Included': 'TRUE', 'Spec 3 Label': '4-1-Bead1-HS3', 'Spec 2 Label': '19-Flat2-HS3'}
Then you can convert it by using any of your favoriate xml parser, I will use minidom here.
from xml.dom import minidom
dom = minidom.parseString(xml_text)
params=dom.getElementsByTagName("Parameter")
for param in params:
name=param.getAttribute("name")
if name in data:
for item in param.getElementsByTagName("*"): # You may change to "Result" or "Value" only
item.firstChild.replaceWholeText(data[name])
print dom.toxml()
#write to file
open("output.xml","wb").write(dom.toxml())
Results
<?xml version="1.0" ?><ParameterData>
<CreationInfo date="10/28/2009 03:05:14 PM" user="manoj"/>
<ParameterList count="85">
<Parameter mode="both" name="Spec 2 Included" type="boolean">
<Value>TRUE</Value>
<Result>TRUE</Result>
</Parameter>
<Parameter mode="both" name="Spec 2 Label" type="string">
<Value>19-Flat2-HS3</Value>
<Result>19-Flat2-HS3</Result>
</Parameter>
<Parameter mode="both" name="Spec 3 Included" type="boolean">
<Value>FALSE</Value>
<Result>FALSE</Result>
</Parameter>
<Parameter mode="both" name="Spec 3 Label" type="string">
<Value>4-1-Bead1-HS3</Value>
<Result>4-1-Bead1-HS3</Result>
</Parameter>
</ParameterList>
</ParameterData>
A:
Well, you could start with
import xml.etree.ElementTree as ET
tree = ET.parse("blah.xml")
Find the elements you want to modify.
To replace the contents of an element, just do
element.text = "TRUE"
The import statement above works in Python 2.5 or later. If you have an older version of Python you'll need to install ElementTree as an extension, and then the import statement is different: import elementtree.ElementTree as ET.
A:
Unfortunately, the XPath supported by ElementTree isn't complete. Since Python 2.6 includes an older version, finding elements by attribute (as stated here) does not work. So Python's own documentation should be your first stop: xml.etree.ElementTree
import xml.etree.ElementTree as ET
original = ET.parse("original.xml")
parameters = original.findall(".//Parameter")
changes = {}
# read changes
with open("changes.txt", "rb") as in_file:
for change in in_file:
change = change.rstrip() # remove line endings
name, value = change.split(":")
changes[name.strip()] = value.strip() # remove whitespaces
# find paramter element and apply changes
for parameter in parameters:
parameter_name = parameter.get("name")
if changes.has_key(parameter_name):
value = parameter.find("./Value")
value.text = changes[parameter_name]
result = parameter.find("./Result")
result.text = changes[parameter_name]
original.write("new.xml")
A:
Here is how you could do it using Amara
from amara import bindery
doc = bindery.parse(XML)
def cleanup_for_dict(key, value):
return key.strip(), value.strip()
params = dict(( cleanup_for_dict(*line.split(':', 1))
for line in TEXT.splitlines()))
for param in doc.ParameterData.ParameterList.Parameter:
if param.name in params:
param.Value = params[param.name]
param.Result = params[param.name]
doc.xml_write()
|
Editing the XML texts from a XML file using Python
|
I have an XML file which contains some data as given.
<?xml version="1.0" encoding="UTF-8" ?>
- <ParameterData>
<CreationInfo date="10/28/2009 03:05:14 PM" user="manoj" />
- <ParameterList count="85">
- <Parameter name="Spec 2 Included" type="boolean" mode="both">
<Value>n/a</Value>
<Result>n/a</Result>
</Parameter>
- <Parameter name="Spec 2 Label" type="string" mode="both">
<Value>n/a</Value>
<Result>n/a</Result>
</Parameter>
- <Parameter name="Spec 3 Included" type="boolean" mode="both">
<Value>n/a</Value>
<Result>n/a</Result>
</Parameter>
- <Parameter name="Spec 3 Label" type="string" mode="both">
<Value>n/a</Value>
<Result>n/a</Result>
</Parameter>
</ParameterList>
</ParameterData>
I have one text file with lines as
Spec 2 Included : TRUE
Spec 2 Label: 19-Flat2-HS3
Spec 3 Included : FALSE
Spec 3 Label: 4-1-Bead1-HS3
Now I want to edit XML texts; i,e. I want to replace the field (n/a)
with the corresponding values from the text file.
Like I want the file to looks like
<?xml version="1.0" encoding="UTF-8" ?>
- <ParameterData>
<CreationInfo date="10/28/2009 03:05:14 PM" user="manoj" />
- <ParameterList count="85">
- <Parameter name="Spec 2 Included" type="boolean" mode="both">
<Value>TRUE</Value>
<Result>TRUE</Result>
</Parameter>
- <Parameter name="Spec 2 Label" type="string" mode="both">
<Value>19-Flat2-HS3</Value>
<Result>19-Flat2-HS3</Result>
</Parameter>
- <Parameter name="Spec 3 Included" type="boolean" mode="both">
<Value>FALSE</Value>
<Result>FALSE</Result>
</Parameter>
- <Parameter name="Spec 3 Label" type="string" mode="both">
<Value>4-1-Bead1-HS3</Value>
<Result>4-1-Bead1-HS3</Result>
</Parameter>
</ParameterList>
</ParameterData>
I am new to this Python-XML coding.
I dont have idea about how to edit the text fields in a XML file.
I am trying to Use elementtree.ElementTree module.
but to read the lines in XML file and extract the attributes I dont know which modules need to be imported.
Please help.
Thanks and Regards.
|
[
"You can convert your data text into python dictionary by regular expression\ndata=\"\"\"Spec 2 Included : TRUE\nSpec 2 Label: 19-Flat2-HS3\nSpec 3 Included : FALSE\nSpec 3 Label: 4-1-Bead1-HS3\"\"\"\n\n#data=open(\"data.txt\").read()\n\nimport re\n\ndata=dict(re.findall('(Spec \\d+ (?:Included|Label))\\s*:\\s*(\\S+)',data))\n\ndata will be as follows\n{'Spec 3 Included': 'FALSE', 'Spec 2 Included': 'TRUE', 'Spec 3 Label': '4-1-Bead1-HS3', 'Spec 2 Label': '19-Flat2-HS3'}\n\nThen you can convert it by using any of your favoriate xml parser, I will use minidom here.\nfrom xml.dom import minidom\n\ndom = minidom.parseString(xml_text)\nparams=dom.getElementsByTagName(\"Parameter\")\nfor param in params:\n name=param.getAttribute(\"name\")\n if name in data:\n for item in param.getElementsByTagName(\"*\"): # You may change to \"Result\" or \"Value\" only\n item.firstChild.replaceWholeText(data[name])\n\nprint dom.toxml()\n\n#write to file\nopen(\"output.xml\",\"wb\").write(dom.toxml())\n\nResults\n<?xml version=\"1.0\" ?><ParameterData>\n <CreationInfo date=\"10/28/2009 03:05:14 PM\" user=\"manoj\"/>\n <ParameterList count=\"85\">\n <Parameter mode=\"both\" name=\"Spec 2 Included\" type=\"boolean\">\n <Value>TRUE</Value>\n <Result>TRUE</Result>\n </Parameter>\n <Parameter mode=\"both\" name=\"Spec 2 Label\" type=\"string\">\n <Value>19-Flat2-HS3</Value>\n <Result>19-Flat2-HS3</Result>\n </Parameter>\n <Parameter mode=\"both\" name=\"Spec 3 Included\" type=\"boolean\">\n <Value>FALSE</Value>\n <Result>FALSE</Result>\n </Parameter>\n <Parameter mode=\"both\" name=\"Spec 3 Label\" type=\"string\">\n <Value>4-1-Bead1-HS3</Value>\n <Result>4-1-Bead1-HS3</Result>\n </Parameter>\n </ParameterList>\n</ParameterData>\n\n",
"Well, you could start with\nimport xml.etree.ElementTree as ET\ntree = ET.parse(\"blah.xml\")\n\nFind the elements you want to modify.\nTo replace the contents of an element, just do\nelement.text = \"TRUE\"\n\nThe import statement above works in Python 2.5 or later. If you have an older version of Python you'll need to install ElementTree as an extension, and then the import statement is different: import elementtree.ElementTree as ET.\n",
"Unfortunately, the XPath supported by ElementTree isn't complete. Since Python 2.6 includes an older version, finding elements by attribute (as stated here) does not work. So Python's own documentation should be your first stop: xml.etree.ElementTree\nimport xml.etree.ElementTree as ET\n\noriginal = ET.parse(\"original.xml\")\nparameters = original.findall(\".//Parameter\")\nchanges = {}\n\n# read changes\nwith open(\"changes.txt\", \"rb\") as in_file:\n for change in in_file:\n change = change.rstrip() # remove line endings\n name, value = change.split(\":\")\n changes[name.strip()] = value.strip() # remove whitespaces\n\n# find paramter element and apply changes\nfor parameter in parameters:\n parameter_name = parameter.get(\"name\")\n if changes.has_key(parameter_name): \n value = parameter.find(\"./Value\")\n value.text = changes[parameter_name]\n result = parameter.find(\"./Result\")\n result.text = changes[parameter_name]\n\noriginal.write(\"new.xml\")\n\n",
"Here is how you could do it using Amara\nfrom amara import bindery\n\ndoc = bindery.parse(XML)\n\ndef cleanup_for_dict(key, value):\n return key.strip(), value.strip()\n\nparams = dict(( cleanup_for_dict(*line.split(':', 1))\n for line in TEXT.splitlines()))\n\nfor param in doc.ParameterData.ParameterList.Parameter:\n if param.name in params:\n param.Value = params[param.name]\n param.Result = params[param.name]\n\ndoc.xml_write()\n\n"
] |
[
6,
5,
1,
1
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0001926512_python_xml.txt
|
Q:
Python: incorporating index from for loop as part of a list name
How does one generate a set of lists that incorporate the index from a for loop in the list name:
for j in range(10):
li"j" = []
How can the index 'j' be part of the name, so the lists are li0, li1, li2, ...
Thanks!
A:
You can make li a dictionary:
li = {}
for j in range(10):
li[j] = []
A:
If you do this simply to initialize lists to use them later, you should instead use one multi-dimensional list or even better tuple to do this:
li = tuple( [] for i in range( 10 ) )
li[0].append( 'foo' )
li[5].append( 'bar' )
A:
You can actually do this with exec, like so:
exec ("li%s = []" % 4)
But don't do this. You almost certainly do not want dynamically named variables. Greg Hewgill's approach will probably solve your problem.
|
Python: incorporating index from for loop as part of a list name
|
How does one generate a set of lists that incorporate the index from a for loop in the list name:
for j in range(10):
li"j" = []
How can the index 'j' be part of the name, so the lists are li0, li1, li2, ...
Thanks!
|
[
"You can make li a dictionary:\nli = {}\nfor j in range(10):\n li[j] = []\n\n",
"If you do this simply to initialize lists to use them later, you should instead use one multi-dimensional list or even better tuple to do this:\nli = tuple( [] for i in range( 10 ) )\nli[0].append( 'foo' )\nli[5].append( 'bar' )\n\n",
"You can actually do this with exec, like so: \nexec (\"li%s = []\" % 4)\n\nBut don't do this. You almost certainly do not want dynamically named variables. Greg Hewgill's approach will probably solve your problem.\n"
] |
[
11,
3,
0
] |
[] |
[] |
[
"for_loop",
"indexing",
"list",
"python"
] |
stackoverflow_0001934344_for_loop_indexing_list_python.txt
|
Q:
Why should exec() and eval() be avoided?
I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case.
So, hopefully, one will be presented here. Why should we (at least, generally) not use exec() and eval()?
EDIT: I see that people are assuming that this question pertains to web servers – it doesn't. I can see why an unsanitized string being passed to exec could be bad. Is it bad in non-web-applications?
A:
There are often clearer, more direct ways to get the same effect. If you build a complex string and pass it to exec, the code is difficult to follow, and difficult to test.
Example: I wrote code that read in string keys and values and set corresponding fields in an object. It looked like this:
for key, val in values:
fieldName = valueToFieldName[key]
fieldType = fieldNameToType[fieldName]
if fieldType is int:
s = 'object.%s = int(%s)' % (fieldName, fieldType)
#Many clauses like this...
exec(s)
That code isn't too terrible for simple cases, but as new types cropped up it got more and more complex. When there were bugs they always triggered on the call to exec, so stack traces didn't help me find them. Eventually I switched to a slightly longer, less clever version that set each field explicitly.
The first rule of code clarity is that each line of your code should be easy to understand by looking only at the lines near it. This is why goto and global variables are discouraged. exec and eval make it easy to break this rule badly.
A:
When you need exec and eval, yeah, you really do need them.
But, the majority of the in-the-wild usage of these functions (and the similar constructs in other scripting languages) is totally inappropriate and could be replaced with other simpler constructs that are faster, more secure and have fewer bugs.
You can, with proper escaping and filtering, use exec and eval safely. But the kind of coder who goes straight for exec/eval to solve a problem (because they don't understand the other facilities the language makes available) isn't the kind of coder that's going to be able to get that processing right; it's going to be someone who doesn't understand string processing and just blindly concatenates substrings, resulting in fragile insecure code.
It's the Lure Of Strings. Throwing string segments around looks easy and fools naïve coders into thinking they understand what they're doing. But experience shows the results are almost always wrong in some corner (or not-so-corner) case, often with potential security implications. This is why we say eval is evil. This is why we say regex-for-HTML is evil. This is why we push SQL parameterisation. Yes, you can get all these things right with manual string processing... but unless you already understand why we say those things, chances are you won't.
A:
eval() and exec() can promote lazy programming. More importantly it indicates the code being executed may not have been written at design time therefore not tested. In other words, how do you test dynamically generated code? Especially across browsers.
A:
Security aside, eval and exec are often marked as undesirable because of the complexity they induce. When you see a eval call you often don't know what's really going on behind it, because it acts on data that's usually in a variable. This makes code harder to read.
Invoking the full power of the interpreter is a heavy weapon that should be only reserved for very tricky cases. In most cases, however, it's best avoided and simpler tools should be employed.
That said, like all generalizations, be wary of this one. In some cases, exec and eval can be valuable. But you must have a very good reason to use them. See this post for one acceptable use.
A:
In contrast to what most answers are saying here, exec is actually part of the recipe for building super-complete decorators in Python, as you can duplicate everything about the decorated function exactly, producing the same signature for the purposes of documentation and such. It's key to the functionality of the widely used decorator module (http://pypi.python.org/pypi/decorator/). Other cases where exec/eval are essential is when constructing any kind of "interpreted Python" type of application, such as a Python-parsed template language (like Mako or Jinja).
So it's not like the presence of these functions are an immediate sign of an "insecure" application or library. Using them in the naive javascripty way to evaluate incoming JSON or something, yes that's very insecure. But as always, its all in the way you use it and these are very essential functions.
A:
I have used eval() in the past (and still do from time-to-time) for massaging data during quick and dirty operations. It is part of the toolkit that can be used for getting a job done, but should NEVER be used for anything you plan to use in production such as any command-line tools or scripts, because of all the reasons mentioned in the other answers.
You cannot trust your users--ever--to do the right thing. In most cases they will, but you have to expect them to do all of the things you never thought of and find all of the bugs you never expected. This is precisely where eval() goes from being a tool to a liability.
A perfect example of this would be using Django, when constructing a QuerySet. The parameters passed to a query accepts keyword arguments, that look something like this:
results = Foo.objects.filter(whatever__contains='pizza')
If you're programmatically assigning arguments, you might think to do something like this:
results = eval("Foo.objects.filter(%s__%s=%s)" % (field, matcher, value))
But there is always a better way that doesn't use eval(), which is passing a dictionary by reference:
results = Foo.objects.filter( **{'%s__%s' % (field, matcher): value} )
By doing it this way, it's not only faster performance-wise, but also safer and more Pythonic.
Moral of the story?
Use of eval() is ok for small tasks, tests, and truly temporary things, but bad for permanent usage because there is almost certainly always a better way to do it!
A:
Allowing these function in a context where they might run user input is a security issue, and sanitizers that actually work are hard to write.
A:
Same reason you shouldn't login as root: it's too easy to shoot yourself in the foot.
A:
Don't try to do the following on your computer:
s = "import shutil; shutil.rmtree('/nonexisting')"
eval(s)
Now assume somebody can control s from a web application, for example.
A:
Reason #1: One security flaw (ie. programming errors... and we can't claim those can be avoided) and you've just given the user access to the shell of the server.
A:
Try this in the interactive interpreter and see what happens:
>>> import sys
>>> eval('{"name" : %s}' % ("sys.exit(1)"))
Of course, this is a corner case, but it can be tricky to prevent things like this.
|
Why should exec() and eval() be avoided?
|
I've seen this multiple times in multiple places, but never have found a satisfying explanation as to why this should be the case.
So, hopefully, one will be presented here. Why should we (at least, generally) not use exec() and eval()?
EDIT: I see that people are assuming that this question pertains to web servers – it doesn't. I can see why an unsanitized string being passed to exec could be bad. Is it bad in non-web-applications?
|
[
"There are often clearer, more direct ways to get the same effect. If you build a complex string and pass it to exec, the code is difficult to follow, and difficult to test. \nExample: I wrote code that read in string keys and values and set corresponding fields in an object. It looked like this: \nfor key, val in values:\n fieldName = valueToFieldName[key]\n fieldType = fieldNameToType[fieldName]\n if fieldType is int:\n s = 'object.%s = int(%s)' % (fieldName, fieldType) \n #Many clauses like this...\n\nexec(s)\n\nThat code isn't too terrible for simple cases, but as new types cropped up it got more and more complex. When there were bugs they always triggered on the call to exec, so stack traces didn't help me find them. Eventually I switched to a slightly longer, less clever version that set each field explicitly. \nThe first rule of code clarity is that each line of your code should be easy to understand by looking only at the lines near it. This is why goto and global variables are discouraged. exec and eval make it easy to break this rule badly.\n",
"When you need exec and eval, yeah, you really do need them.\nBut, the majority of the in-the-wild usage of these functions (and the similar constructs in other scripting languages) is totally inappropriate and could be replaced with other simpler constructs that are faster, more secure and have fewer bugs.\nYou can, with proper escaping and filtering, use exec and eval safely. But the kind of coder who goes straight for exec/eval to solve a problem (because they don't understand the other facilities the language makes available) isn't the kind of coder that's going to be able to get that processing right; it's going to be someone who doesn't understand string processing and just blindly concatenates substrings, resulting in fragile insecure code.\nIt's the Lure Of Strings. Throwing string segments around looks easy and fools naïve coders into thinking they understand what they're doing. But experience shows the results are almost always wrong in some corner (or not-so-corner) case, often with potential security implications. This is why we say eval is evil. This is why we say regex-for-HTML is evil. This is why we push SQL parameterisation. Yes, you can get all these things right with manual string processing... but unless you already understand why we say those things, chances are you won't.\n",
"eval() and exec() can promote lazy programming. More importantly it indicates the code being executed may not have been written at design time therefore not tested. In other words, how do you test dynamically generated code? Especially across browsers.\n",
"Security aside, eval and exec are often marked as undesirable because of the complexity they induce. When you see a eval call you often don't know what's really going on behind it, because it acts on data that's usually in a variable. This makes code harder to read.\nInvoking the full power of the interpreter is a heavy weapon that should be only reserved for very tricky cases. In most cases, however, it's best avoided and simpler tools should be employed. \nThat said, like all generalizations, be wary of this one. In some cases, exec and eval can be valuable. But you must have a very good reason to use them. See this post for one acceptable use.\n",
"In contrast to what most answers are saying here, exec is actually part of the recipe for building super-complete decorators in Python, as you can duplicate everything about the decorated function exactly, producing the same signature for the purposes of documentation and such. It's key to the functionality of the widely used decorator module (http://pypi.python.org/pypi/decorator/). Other cases where exec/eval are essential is when constructing any kind of \"interpreted Python\" type of application, such as a Python-parsed template language (like Mako or Jinja).\nSo it's not like the presence of these functions are an immediate sign of an \"insecure\" application or library. Using them in the naive javascripty way to evaluate incoming JSON or something, yes that's very insecure. But as always, its all in the way you use it and these are very essential functions.\n",
"I have used eval() in the past (and still do from time-to-time) for massaging data during quick and dirty operations. It is part of the toolkit that can be used for getting a job done, but should NEVER be used for anything you plan to use in production such as any command-line tools or scripts, because of all the reasons mentioned in the other answers. \nYou cannot trust your users--ever--to do the right thing. In most cases they will, but you have to expect them to do all of the things you never thought of and find all of the bugs you never expected. This is precisely where eval() goes from being a tool to a liability.\nA perfect example of this would be using Django, when constructing a QuerySet. The parameters passed to a query accepts keyword arguments, that look something like this:\nresults = Foo.objects.filter(whatever__contains='pizza')\n\nIf you're programmatically assigning arguments, you might think to do something like this:\nresults = eval(\"Foo.objects.filter(%s__%s=%s)\" % (field, matcher, value))\n\nBut there is always a better way that doesn't use eval(), which is passing a dictionary by reference:\nresults = Foo.objects.filter( **{'%s__%s' % (field, matcher): value} ) \n\nBy doing it this way, it's not only faster performance-wise, but also safer and more Pythonic. \nMoral of the story?\nUse of eval() is ok for small tasks, tests, and truly temporary things, but bad for permanent usage because there is almost certainly always a better way to do it!\n",
"Allowing these function in a context where they might run user input is a security issue, and sanitizers that actually work are hard to write.\n",
"Same reason you shouldn't login as root: it's too easy to shoot yourself in the foot.\n",
"Don't try to do the following on your computer:\ns = \"import shutil; shutil.rmtree('/nonexisting')\"\neval(s)\n\nNow assume somebody can control s from a web application, for example.\n",
"Reason #1: One security flaw (ie. programming errors... and we can't claim those can be avoided) and you've just given the user access to the shell of the server.\n",
"Try this in the interactive interpreter and see what happens:\n>>> import sys\n>>> eval('{\"name\" : %s}' % (\"sys.exit(1)\"))\n\nOf course, this is a corner case, but it can be tricky to prevent things like this.\n"
] |
[
32,
17,
13,
12,
9,
6,
5,
5,
4,
3,
3
] |
[] |
[] |
[
"python",
"python_exec"
] |
stackoverflow_0001933451_python_python_exec.txt
|
Q:
Item assignment to bytes object?
GAHH, code not working is bad code indeed!
in RemoveRETNs
toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment
How can I fix this?
inputFile = 'original.exe'
outputFile = 'output.txt'
patchedFile = 'original_patched.exe'
def GetFileContents(filename):
f = open(filename, 'rb')
fileContents = f.read()
f.close()
return fileContents
def FindAll(fileContents, strToFind):
found = []
lastOffset = -1
while True:
lastOffset += 1
lastOffset = fileContents.find(b'\xC3\xCC\xCC\xCC\xCC', lastOffset)
if lastOffset != -1:
found.append(lastOffset)
else:
break
return found
def FixOffsets(offsetList):
for current in range(0, len(offsetList)):
offsetList[current] += 0x00400000
return offsetList
def AbsentFromList(toFind, theList):
for i in theList:
if i == toFind:
return True
return False
# Outputs the original file with all RETNs replaced with INT3s.
def RemoveRETNs(locationsOfRETNs, oldFilesContents, newFilesName):
target = open(newFilesName, 'wb')
toOutput = oldFilesContents
for currentLoc in locationsOfRETNs:
toOutput[currentLoc - 0x00400000] = b'\xCC'
target.write(toOutput)
target.close()
fileContents = GetFileContents(inputFile)
offsets = FixOffsets(FindAll(fileContents, '\xC3\xCC\xCC\xCC\xCC'))
RemoveRETNs(offsets, fileContents, patchedFile)
What am I doing wrong, and what can I do to fix it? Code sample?
A:
Change the return statement of GetFileContents into
return bytearray(fileContents)
and the rest should work. You need to use bytearray rather than bytes simply because the former is mutable (read/write), the latter (which is what you're using now) is immutable (read-only).
A:
Bytestrings (and strings in general) are immutable objects in Python. Once you create them, you can't change them. Instead, you have to create a new one that happens to have some of the old content. (For instance, with a basic string, newString = oldString[:offset] + newChar + oldString[offset+1:] or the like.)
Instead, you may want to convert the bytestring to a list of bytes first, or a bytearray, manipulate it, and then convert the bytearray/list back to a static string after all of the manipulations have been done. This avoids creating a new string for each replace operation.
|
Item assignment to bytes object?
|
GAHH, code not working is bad code indeed!
in RemoveRETNs
toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment
How can I fix this?
inputFile = 'original.exe'
outputFile = 'output.txt'
patchedFile = 'original_patched.exe'
def GetFileContents(filename):
f = open(filename, 'rb')
fileContents = f.read()
f.close()
return fileContents
def FindAll(fileContents, strToFind):
found = []
lastOffset = -1
while True:
lastOffset += 1
lastOffset = fileContents.find(b'\xC3\xCC\xCC\xCC\xCC', lastOffset)
if lastOffset != -1:
found.append(lastOffset)
else:
break
return found
def FixOffsets(offsetList):
for current in range(0, len(offsetList)):
offsetList[current] += 0x00400000
return offsetList
def AbsentFromList(toFind, theList):
for i in theList:
if i == toFind:
return True
return False
# Outputs the original file with all RETNs replaced with INT3s.
def RemoveRETNs(locationsOfRETNs, oldFilesContents, newFilesName):
target = open(newFilesName, 'wb')
toOutput = oldFilesContents
for currentLoc in locationsOfRETNs:
toOutput[currentLoc - 0x00400000] = b'\xCC'
target.write(toOutput)
target.close()
fileContents = GetFileContents(inputFile)
offsets = FixOffsets(FindAll(fileContents, '\xC3\xCC\xCC\xCC\xCC'))
RemoveRETNs(offsets, fileContents, patchedFile)
What am I doing wrong, and what can I do to fix it? Code sample?
|
[
"Change the return statement of GetFileContents into\nreturn bytearray(fileContents)\n\nand the rest should work. You need to use bytearray rather than bytes simply because the former is mutable (read/write), the latter (which is what you're using now) is immutable (read-only).\n",
"Bytestrings (and strings in general) are immutable objects in Python. Once you create them, you can't change them. Instead, you have to create a new one that happens to have some of the old content. (For instance, with a basic string, newString = oldString[:offset] + newChar + oldString[offset+1:] or the like.)\nInstead, you may want to convert the bytestring to a list of bytes first, or a bytearray, manipulate it, and then convert the bytearray/list back to a static string after all of the manipulations have been done. This avoids creating a new string for each replace operation.\n"
] |
[
43,
8
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0001934624_python_python_3.x.txt
|
Q:
Combine matrix in numpy
Suppose I have three "sheets" of matrix a,b and c, each with the same mnp dimension. And I want to combine them to get a new mnp*3 matrix whose (i,j,k) element is (a[i,j,k],b[i,j,k],c[i,j,k]). Which command should I use ? The dstack command seems not work here. Thanks.
A:
Another one liner would be:
result = numpy.array( (a,b,c) ).transpose( (1,2,3,0) )
or a more self-descriptive method:
result = empty( (m,n,p,3) )
result[:,:,:,0] = a
result[:,:,:,1] = b
result[:,:,:,2] = c
A:
I think what you want is:
np.concatenate([np.expand_dims(x, -1) for x in (a, b, c)], axis=3)
|
Combine matrix in numpy
|
Suppose I have three "sheets" of matrix a,b and c, each with the same mnp dimension. And I want to combine them to get a new mnp*3 matrix whose (i,j,k) element is (a[i,j,k],b[i,j,k],c[i,j,k]). Which command should I use ? The dstack command seems not work here. Thanks.
|
[
"Another one liner would be:\nresult = numpy.array( (a,b,c) ).transpose( (1,2,3,0) )\n\nor a more self-descriptive method:\nresult = empty( (m,n,p,3) )\nresult[:,:,:,0] = a\nresult[:,:,:,1] = b\nresult[:,:,:,2] = c\n\n",
"I think what you want is:\nnp.concatenate([np.expand_dims(x, -1) for x in (a, b, c)], axis=3)\n\n"
] |
[
4,
2
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0001934683_numpy_python.txt
|
Q:
web framework compatible with python 3.1 and py-postgresql
I have started learning Python by writing a small application using Python 3.1 and py-PostgreSQL. Now I want to turn it into a web application.
But it seems that most frameworks such as web-py, Django, zope are still based on Python 2.x. Unfortunately, py-PostgreSQL is incompatible with Python 2.x.
Do I have to rewrite all my classes and replace py-PostgreSQL with something supported by web-py etc., or is there a framework compatible with Python 3.1?
Or maybe py-PostgreSQL is compatible with 2.x but I did not figure it out?
A:
Update: this answer is out of date in 2011.
Unless you are interested in blazing a new trail while trying to learn Python at all, I'd recommend converting your project to Python 2.x. Hopefully your code doesn't use too many py-postgresql features not found in the widely supported DB-API interface.
You should look at psycopg2 for a Python 2.x DB-API compatible interface or if you want to go higher-level SQLAlchemy which in the svn release can use psycopg2 or py-postgresql interchangeably.
You might also be interested in 3to2 which automatically converts Python 3.x code to Python 2.x code when possible.
Duplicate of #373945 What web development frameworks support Python 3?
A:
I have just found out about WSGI: a WSGI compatible app can also be written in Python 3.1. The following code runs just fine in Python 3.1:
def webapp(environment, start_response):
start_response('200 OK', [('content-type', 'text/html')])
return ['Hello, World!']
if __name__ == '__main__':
from wsgiref import simple_server
simple_server.make_server('', 8080, webapp).serve_forever()
The WSGI website has lots of pointers to frameworks. The Bottle framework claims "Bottle runs with Python 2.5+ and 3.x (using 2to3)" so I will give that a try.
A:
Here's a simplified version of tornado's WSGI server implemented in python 3.
http://code.activestate.com/recipes/576906/
probably has some bugs, but can get you started
A:
Even though it's not officially released yet, I am currently 'playing around' with CherryPy 3.2.0rc1 with Python 3.1.1 and have had no problems yet. Haven't used it with py-postgresql, but I don't see why it shouldn't work.
Hope this helps,
Alan
|
web framework compatible with python 3.1 and py-postgresql
|
I have started learning Python by writing a small application using Python 3.1 and py-PostgreSQL. Now I want to turn it into a web application.
But it seems that most frameworks such as web-py, Django, zope are still based on Python 2.x. Unfortunately, py-PostgreSQL is incompatible with Python 2.x.
Do I have to rewrite all my classes and replace py-PostgreSQL with something supported by web-py etc., or is there a framework compatible with Python 3.1?
Or maybe py-PostgreSQL is compatible with 2.x but I did not figure it out?
|
[
"Update: this answer is out of date in 2011.\nUnless you are interested in blazing a new trail while trying to learn Python at all, I'd recommend converting your project to Python 2.x. Hopefully your code doesn't use too many py-postgresql features not found in the widely supported DB-API interface.\nYou should look at psycopg2 for a Python 2.x DB-API compatible interface or if you want to go higher-level SQLAlchemy which in the svn release can use psycopg2 or py-postgresql interchangeably.\nYou might also be interested in 3to2 which automatically converts Python 3.x code to Python 2.x code when possible.\nDuplicate of #373945 What web development frameworks support Python 3?\n",
"I have just found out about WSGI: a WSGI compatible app can also be written in Python 3.1. The following code runs just fine in Python 3.1:\ndef webapp(environment, start_response):\n start_response('200 OK', [('content-type', 'text/html')])\n return ['Hello, World!']\n\nif __name__ == '__main__':\n from wsgiref import simple_server\n simple_server.make_server('', 8080, webapp).serve_forever()\n\nThe WSGI website has lots of pointers to frameworks. The Bottle framework claims \"Bottle runs with Python 2.5+ and 3.x (using 2to3)\" so I will give that a try.\n",
"Here's a simplified version of tornado's WSGI server implemented in python 3.\nhttp://code.activestate.com/recipes/576906/\nprobably has some bugs, but can get you started\n",
"Even though it's not officially released yet, I am currently 'playing around' with CherryPy 3.2.0rc1 with Python 3.1.1 and have had no problems yet. Haven't used it with py-postgresql, but I don't see why it shouldn't work.\nHope this helps,\nAlan\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"python",
"python_3.x",
"web_applications",
"wsgi"
] |
stackoverflow_0001423000_python_python_3.x_web_applications_wsgi.txt
|
Q:
numpy to matlab interface with mlabwrap
I am looking for a simple way to visualize some of my data in numpy, and I discovered the mlabwrap package which looks really promising. I am trying to create a simple plot with the ability to be updated as the data changes.
Here is the matlab code that I am trying to duplicate
>> h = plot([1,2,3], [1,2,3], '-o');
>> set(h, 'XData', [0,0,0]);
>> drawnow();
to python
>> from mlabwrap import mlab
>> h = mlab.plot([1,2,3], [1,2,3], '-o')
>> mlab.set(h, 'XData', [0,0,0])
>> mlab.drawnow();
However, the second to last command fails with an error message
error: One or more output arguments not assigned during call to "set".
Any suggestions on how to fix this?
A:
Maybe mlab is mad that you're not saving matlab's return value for that set() call...
I don't have this installed, what does someval = mlab.set(h,'XData') give?
edit: you could also try using nout... mlab.set(h,'XData',[0,0,0],nout=0)
A:
Since set takes no output arguments, we need to tell mlabwrap that no output arguments should be given to it to avoid the error message above.
mlab.set(h, 'XData', [0,0,0], nout=0)
|
numpy to matlab interface with mlabwrap
|
I am looking for a simple way to visualize some of my data in numpy, and I discovered the mlabwrap package which looks really promising. I am trying to create a simple plot with the ability to be updated as the data changes.
Here is the matlab code that I am trying to duplicate
>> h = plot([1,2,3], [1,2,3], '-o');
>> set(h, 'XData', [0,0,0]);
>> drawnow();
to python
>> from mlabwrap import mlab
>> h = mlab.plot([1,2,3], [1,2,3], '-o')
>> mlab.set(h, 'XData', [0,0,0])
>> mlab.drawnow();
However, the second to last command fails with an error message
error: One or more output arguments not assigned during call to "set".
Any suggestions on how to fix this?
|
[
"Maybe mlab is mad that you're not saving matlab's return value for that set() call...\nI don't have this installed, what does someval = mlab.set(h,'XData') give?\nedit: you could also try using nout... mlab.set(h,'XData',[0,0,0],nout=0)\n",
"Since set takes no output arguments, we need to tell mlabwrap that no output arguments should be given to it to avoid the error message above.\nmlab.set(h, 'XData', [0,0,0], nout=0)\n\n"
] |
[
6,
5
] |
[] |
[] |
[
"interface",
"matlab",
"mlabwrap",
"python"
] |
stackoverflow_0001934740_interface_matlab_mlabwrap_python.txt
|
Q:
pyfacebook stream.publish not publishing all details
Trying to publish a stream to facebook using py facebook. The stream publishes a single attachment perfectly i.e media or name or href , e.t.c
But when it comes to appending all the attachments in one line it breaks down and just publishes the message.
attachment = [media,description] etc does not work.
message = "Test Message with Picture"
media = {'media':[
{'type': 'image',
'src': 'http://www.topnews.in/usa/files/megan-fox.jpg',
'href': 'http://www.topnews.in/usa/files/megan-fox.jpg'},
{'type': 'image',
'src': 'http://www.topnews.in/usa/files/megan-fox.jpg',
'href': 'http://ihasahotdog.com/upcoming/?pid=20869'}]}
name = {'name':'testing'}
href = {'href':'http://google.com'}
caption = 'caption' :'caption goes here'
description = { 'description':'Description Goes Here'}
attachment = media
The second problem is the popup box while publishing in this manner. Python does not show a popup box, it directly publishes to the stream. How can one put a pop up box?
A:
You haven't really given enough information to know what is causing the first issue (the only code you pasted doesn't include the pyfacebook call and has a syntax error from indentation).
about the second issue, python and pyfacebook can deal with facebook's server api only. If you want a popup displayed to your user then you have to do that with javascript - details are here.
|
pyfacebook stream.publish not publishing all details
|
Trying to publish a stream to facebook using py facebook. The stream publishes a single attachment perfectly i.e media or name or href , e.t.c
But when it comes to appending all the attachments in one line it breaks down and just publishes the message.
attachment = [media,description] etc does not work.
message = "Test Message with Picture"
media = {'media':[
{'type': 'image',
'src': 'http://www.topnews.in/usa/files/megan-fox.jpg',
'href': 'http://www.topnews.in/usa/files/megan-fox.jpg'},
{'type': 'image',
'src': 'http://www.topnews.in/usa/files/megan-fox.jpg',
'href': 'http://ihasahotdog.com/upcoming/?pid=20869'}]}
name = {'name':'testing'}
href = {'href':'http://google.com'}
caption = 'caption' :'caption goes here'
description = { 'description':'Description Goes Here'}
attachment = media
The second problem is the popup box while publishing in this manner. Python does not show a popup box, it directly publishes to the stream. How can one put a pop up box?
|
[
"You haven't really given enough information to know what is causing the first issue (the only code you pasted doesn't include the pyfacebook call and has a syntax error from indentation).\nabout the second issue, python and pyfacebook can deal with facebook's server api only. If you want a popup displayed to your user then you have to do that with javascript - details are here.\n"
] |
[
0
] |
[] |
[] |
[
"facebook",
"python"
] |
stackoverflow_0001929495_facebook_python.txt
|
Q:
fb:promt-permission gives me a link, I need a direct popup
I'm using Django/Python , I need to ask the user for permission to let me put feeds ( ideally oneliners which was not working so I thought to use full streams) into the user profile.
Would you like to receive email from our application?
This is giving me a hyper link which I click and it shows me the permission box. What is need for this to happen is after the end of the game it automatically prompts for it and then publishes. Which isn't really working.
Thanks :)
A:
use the javascript FB.Connect.showPermissionDialog method.
it takes an optional callback function to which it passes whether the permission was allowed or not, so you could call FB.Connect.streamPublish in that callback if the permission was granted.
|
fb:promt-permission gives me a link, I need a direct popup
|
I'm using Django/Python , I need to ask the user for permission to let me put feeds ( ideally oneliners which was not working so I thought to use full streams) into the user profile.
Would you like to receive email from our application?
This is giving me a hyper link which I click and it shows me the permission box. What is need for this to happen is after the end of the game it automatically prompts for it and then publishes. Which isn't really working.
Thanks :)
|
[
"use the javascript FB.Connect.showPermissionDialog method.\nit takes an optional callback function to which it passes whether the permission was allowed or not, so you could call FB.Connect.streamPublish in that callback if the permission was granted.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"facebook",
"python"
] |
stackoverflow_0001928098_django_facebook_python.txt
|
Q:
File searching: TypeError
Im trying to search a file where the the line containing the search term is found and printed along with a number of lines before and after the search term defined by the user. The coding i have so far is:
f = open(f, 'r')
d = {}
for n, line in enumerate(f):
d[n%numb] = line.rstrip()
if search_term in line:
for i in rang(n+1,n+1+numb):
print d[i%numb]
for i in range(1, numb):
print f.next().rstrip()
But i get a TypeError at d[%numb] = line.rstrip()
Unsupported operand type(s) for %: 'int' and 'str'
Help would be great thanks
A:
You haven't specified what numb is, but I'm guessing it's something like:
numb = sys.argv[1]
The sys.argv is an array of strings, rather than integers. Try converting the string to an integer:
numb = int(sys.argv[1])
A:
n % numb can have different meanings, depending on the type of n and numb. If they are both numbers it means "take the modulus" which I presume is what you intend. If n is a string then it means do % formatting. If n is a number and numb is a string Python does not know what to do and raises a TypeError. Did you look at the error message on the exception? It should say "unsupported operand type(s) for %: 'int' and 'str'", which will tell you everything you need to know.
Once you fix that, I don't think your program will do what you want - there are several problems with it.
1) if your search term is in the first numb lines then you will get an exception trying to read lines out of the dictionary that have not been inserted yet.
2) the last loop in your code reads the next numb lines but does not search them, so any occurrences of the search term will be missed.
3) Using modulus to maintain the buffer of lines is clever, but there is a better way. Look at the collections.deque class,
|
File searching: TypeError
|
Im trying to search a file where the the line containing the search term is found and printed along with a number of lines before and after the search term defined by the user. The coding i have so far is:
f = open(f, 'r')
d = {}
for n, line in enumerate(f):
d[n%numb] = line.rstrip()
if search_term in line:
for i in rang(n+1,n+1+numb):
print d[i%numb]
for i in range(1, numb):
print f.next().rstrip()
But i get a TypeError at d[%numb] = line.rstrip()
Unsupported operand type(s) for %: 'int' and 'str'
Help would be great thanks
|
[
"You haven't specified what numb is, but I'm guessing it's something like:\nnumb = sys.argv[1]\n\nThe sys.argv is an array of strings, rather than integers. Try converting the string to an integer:\nnumb = int(sys.argv[1])\n\n",
"n % numb can have different meanings, depending on the type of n and numb. If they are both numbers it means \"take the modulus\" which I presume is what you intend. If n is a string then it means do % formatting. If n is a number and numb is a string Python does not know what to do and raises a TypeError. Did you look at the error message on the exception? It should say \"unsupported operand type(s) for %: 'int' and 'str'\", which will tell you everything you need to know.\nOnce you fix that, I don't think your program will do what you want - there are several problems with it.\n1) if your search term is in the first numb lines then you will get an exception trying to read lines out of the dictionary that have not been inserted yet. \n2) the last loop in your code reads the next numb lines but does not search them, so any occurrences of the search term will be missed.\n3) Using modulus to maintain the buffer of lines is clever, but there is a better way. Look at the collections.deque class,\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001935465_python.txt
|
Q:
__del__ method being called in python when it is not expected
I am new to python and have been working through the examples in Swaroop CH's "A Byte of Python". I am seeing some behavior with the __del__ method that is puzzling me.
Basically, if I run the following script (in Python 2.6.2)
class Person4:
'''Represents a person'''
population = 0
def __init__(self, name):
'''Initialize the person's data'''
self.name = name
print 'Initializing %s'% self.name
#When the person is created they increase the population
Person4.population += 1
def __del__(self):
'''I am dying'''
print '%s says bye' % self.name
Person4.population -= 1
if Person4.population == 0:
print 'I am the last one'
else:
print 'There are still %d left' % Person4.population
swaroop = Person4('Swaroop')
kaleem = Person4('Kalem')
using the Python console (or the Spyder interactive console) I see the following:
execfile(u'C:\1_eric\Python\test1.py')
Initializing Swaroop
Initializing Kalem
execfile(u'C:\1_eric\Python\test1.py')
Initializing Swaroop
Swaroop says bye
I am the last one
Initializing Kalem
Kalem says bye
I am the last one
Why is the __del__ method being called immediately after the __init__ on the second run?
I am guessing that since the same instance names ('swaroop' and 'kaleem') are being used that it is releasing the original instance and garbage collecting it. But, this seems to be playing havoc with the current population count.
What is going on here?
What is a good way to avoid this sort of confusion?
Avoid the use of __del__?
Check for existing instance names before reusing them?
...
Thanks,
Eric
A:
There are a couple of things going on here. When your Person4 class is instantiated, it initialises its population class variable to 0. From your interactive console, you appear to be running your "test1.py" file multiple times. The second time you run it, the Person4 class is declared again which makes it technically different from the first one (even though it has the same name). That means it has its own independent population count.
Now, swaroop and kaleem are global variables, shared between both your instances of "test1.py". Python internally uses reference counting for most of its automatic garbage collection, so the original instance of the first Person4 class is not released until the second assignment to swaroop. Assigning to swaroop decrements the reference count for the first instance, causing __del__ to be called because the reference count is now zero. But because you're referring to Person4 by name inside __del__(), when the previous instance disappears it decrements the new Person4.population count, instead of the old Person4 population count.
Hopefully that made sense. I can see why this might be confusing to somebody learning Python. Your use of class variables at the same time as redefining the Person4 class using execfile() is further confusing matters. For what it's worth, I've written a lot of Python code and I don't think I've ever needed to use the __del__ special method.
A:
General advice: don't use __ del __ in Python. It can break garbage collection in a number of ways, esp. in the case of circular references between objects.
In your example, there're various issues related to the usage of execfile() - which is not a best practice - and the redefinition of global variables. By the way, if you really need to create a pseudo-destructor (i.e. a code that is invoked whenever the object gets garbage collected), write a so-called "finalizer" function (it's not properly a destructor) and invoke it using weakref.ref callback. It should NOT be an instance method of course, and remember that lambda actually creates a closure, hence be sure not to leak any reference to self in the callback! If you need data from the destroyed instance, use the func default argument approach, just be sure never to reference 'self' inside the lambda, otherwise it won't work.
from weakref import ref
from time import sleep
class Person4:
'''Represents a person'''
population = 0
def __init__(self, name):
'''Initialize the person's data'''
self.name = name
print 'Initializing %s'% self.name
#When the person is created they increase the population
Person4.population += 1
self._wr = ref(self, lambda wr, name=self.name: Person4_finalizer(name))
def Person4_finalizer(name):
'''I am dying'''
print '%s says bye' % name
Person4.population -= 1
if Person4.population == 0:
print 'I am the last one'
else:
print 'There are still %d left' % Person4.population
p1 = Person4("one")
p2 = Person4("two")
p3 = Person4("three")
del p2
del p3
sleep(5)
output (the sleep is there to help see what's happening):
Initializing one
Initializing two
Initializing three
two says bye
There are still 2 left
three says bye
There are still 1 left
one says bye
I am the last one
|
__del__ method being called in python when it is not expected
|
I am new to python and have been working through the examples in Swaroop CH's "A Byte of Python". I am seeing some behavior with the __del__ method that is puzzling me.
Basically, if I run the following script (in Python 2.6.2)
class Person4:
'''Represents a person'''
population = 0
def __init__(self, name):
'''Initialize the person's data'''
self.name = name
print 'Initializing %s'% self.name
#When the person is created they increase the population
Person4.population += 1
def __del__(self):
'''I am dying'''
print '%s says bye' % self.name
Person4.population -= 1
if Person4.population == 0:
print 'I am the last one'
else:
print 'There are still %d left' % Person4.population
swaroop = Person4('Swaroop')
kaleem = Person4('Kalem')
using the Python console (or the Spyder interactive console) I see the following:
execfile(u'C:\1_eric\Python\test1.py')
Initializing Swaroop
Initializing Kalem
execfile(u'C:\1_eric\Python\test1.py')
Initializing Swaroop
Swaroop says bye
I am the last one
Initializing Kalem
Kalem says bye
I am the last one
Why is the __del__ method being called immediately after the __init__ on the second run?
I am guessing that since the same instance names ('swaroop' and 'kaleem') are being used that it is releasing the original instance and garbage collecting it. But, this seems to be playing havoc with the current population count.
What is going on here?
What is a good way to avoid this sort of confusion?
Avoid the use of __del__?
Check for existing instance names before reusing them?
...
Thanks,
Eric
|
[
"There are a couple of things going on here. When your Person4 class is instantiated, it initialises its population class variable to 0. From your interactive console, you appear to be running your \"test1.py\" file multiple times. The second time you run it, the Person4 class is declared again which makes it technically different from the first one (even though it has the same name). That means it has its own independent population count.\nNow, swaroop and kaleem are global variables, shared between both your instances of \"test1.py\". Python internally uses reference counting for most of its automatic garbage collection, so the original instance of the first Person4 class is not released until the second assignment to swaroop. Assigning to swaroop decrements the reference count for the first instance, causing __del__ to be called because the reference count is now zero. But because you're referring to Person4 by name inside __del__(), when the previous instance disappears it decrements the new Person4.population count, instead of the old Person4 population count.\nHopefully that made sense. I can see why this might be confusing to somebody learning Python. Your use of class variables at the same time as redefining the Person4 class using execfile() is further confusing matters. For what it's worth, I've written a lot of Python code and I don't think I've ever needed to use the __del__ special method.\n",
"General advice: don't use __ del __ in Python. It can break garbage collection in a number of ways, esp. in the case of circular references between objects.\nIn your example, there're various issues related to the usage of execfile() - which is not a best practice - and the redefinition of global variables. By the way, if you really need to create a pseudo-destructor (i.e. a code that is invoked whenever the object gets garbage collected), write a so-called \"finalizer\" function (it's not properly a destructor) and invoke it using weakref.ref callback. It should NOT be an instance method of course, and remember that lambda actually creates a closure, hence be sure not to leak any reference to self in the callback! If you need data from the destroyed instance, use the func default argument approach, just be sure never to reference 'self' inside the lambda, otherwise it won't work.\nfrom weakref import ref\nfrom time import sleep\n\nclass Person4:\n '''Represents a person'''\n population = 0\n\n def __init__(self, name):\n '''Initialize the person's data'''\n self.name = name\n print 'Initializing %s'% self.name\n\n #When the person is created they increase the population\n Person4.population += 1\n\n self._wr = ref(self, lambda wr, name=self.name: Person4_finalizer(name))\n\ndef Person4_finalizer(name):\n '''I am dying'''\n print '%s says bye' % name\n\n Person4.population -= 1\n\n if Person4.population == 0:\n print 'I am the last one'\n else:\n print 'There are still %d left' % Person4.population\n\np1 = Person4(\"one\")\np2 = Person4(\"two\")\np3 = Person4(\"three\")\n\ndel p2\ndel p3\nsleep(5)\n\noutput (the sleep is there to help see what's happening):\nInitializing one\nInitializing two\nInitializing three\ntwo says bye\nThere are still 2 left\nthree says bye\nThere are still 1 left\none says bye\nI am the last one\n\n"
] |
[
19,
8
] |
[] |
[] |
[
"del",
"object_lifetime",
"python"
] |
stackoverflow_0001935153_del_object_lifetime_python.txt
|
Q:
pyfacebook and javascript query
I'm using pyfacebook on the backend and javascript on the client side. Now if I want to pass a variable to the javascript from pyfacebook. how would I go about doing that, any ideas?
A:
You can't pass a variable directly, as JavaScript is running on the client (browser), and Python is running on the server.
You could make a XHR (AJAX) request from JavaScript to the server which would then return your values back to JS (JSON could be used here).
Or you could put a hidden field to your markup that would have the value in it's "value" attribute. You could then read that with JavaScript.
ps: your question really isn't related to pyfacebook but Python (or any other server side technology) in general and that has been covered here many many times.
|
pyfacebook and javascript query
|
I'm using pyfacebook on the backend and javascript on the client side. Now if I want to pass a variable to the javascript from pyfacebook. how would I go about doing that, any ideas?
|
[
"You can't pass a variable directly, as JavaScript is running on the client (browser), and Python is running on the server.\nYou could make a XHR (AJAX) request from JavaScript to the server which would then return your values back to JS (JSON could be used here).\nOr you could put a hidden field to your markup that would have the value in it's \"value\" attribute. You could then read that with JavaScript.\nps: your question really isn't related to pyfacebook but Python (or any other server side technology) in general and that has been covered here many many times.\n"
] |
[
1
] |
[] |
[] |
[
"javascript",
"python"
] |
stackoverflow_0001935636_javascript_python.txt
|
Q:
Xpath builder in Python
I'm building relatively complicated xpath expressions in Python, in order to pass them to selenium. However, its pretty easy to make a mistake, so I'm looking for a library that allows me to build the expressions without messing about with strings. For example, instead of writing
locator='//ul[@class="comment-contents"][contains(., "West")]/li[contains(., "reply")]
I could write something like:
import xpathbuilder as xpb
locator = xpb.root("ul")
.filter(attr="class",value="comment-contents")
.filter(xpb.contains(".", "West")
.subclause("li")
.filter(xpb.contains (".", "reply"))
which is maybe not as readable, but is less error-prone. Does anything like this exist?
A:
though this is not exactly what you want.. you can use css selector
...
import lxml.cssselect
csssel = 'div[class="main"]'
selobj = lxml.cssselect.CSSSelector(csssel)
elements = selobj(documenttree)
generated XPath expression is in selobj.path
>>> selobj.path
u"descendant-or-self::div[@class = 'main']"
A:
You can use lxml.etree that allows to write code as the following:
from lxml.builder import ElementMaker # lxml only !
E = ElementMaker(namespace="http://my.de/fault/namespace", nsmap={'p' : "http://my.de/fault/namespace"})
DOC = E.doc
TITLE = E.title
SECTION = E.section
PAR = E.par
my_doc = DOC(
TITLE("The dog and the hog"),
SECTION(
TITLE("The dog"),
PAR("Once upon a time, ..."),
PAR("And then …")
),
SECTION(
TITLE("The hog"),
PAR("Sooner or later …")
)
)
|
Xpath builder in Python
|
I'm building relatively complicated xpath expressions in Python, in order to pass them to selenium. However, its pretty easy to make a mistake, so I'm looking for a library that allows me to build the expressions without messing about with strings. For example, instead of writing
locator='//ul[@class="comment-contents"][contains(., "West")]/li[contains(., "reply")]
I could write something like:
import xpathbuilder as xpb
locator = xpb.root("ul")
.filter(attr="class",value="comment-contents")
.filter(xpb.contains(".", "West")
.subclause("li")
.filter(xpb.contains (".", "reply"))
which is maybe not as readable, but is less error-prone. Does anything like this exist?
|
[
"though this is not exactly what you want.. you can use css selector\n...\nimport lxml.cssselect\ncsssel = 'div[class=\"main\"]'\nselobj = lxml.cssselect.CSSSelector(csssel)\nelements = selobj(documenttree)\n\ngenerated XPath expression is in selobj.path\n>>> selobj.path\nu\"descendant-or-self::div[@class = 'main']\"\n\n",
"You can use lxml.etree that allows to write code as the following:\nfrom lxml.builder import ElementMaker # lxml only !\n\nE = ElementMaker(namespace=\"http://my.de/fault/namespace\", nsmap={'p' : \"http://my.de/fault/namespace\"})\n\nDOC = E.doc\nTITLE = E.title\nSECTION = E.section\nPAR = E.par\n\nmy_doc = DOC(\n TITLE(\"The dog and the hog\"),\n SECTION(\n TITLE(\"The dog\"),\n PAR(\"Once upon a time, ...\"),\n PAR(\"And then …\")\n ),\n SECTION(\n TITLE(\"The hog\"),\n PAR(\"Sooner or later …\")\n )\n)\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"selenium",
"xml",
"xpath"
] |
stackoverflow_0001934720_python_selenium_xml_xpath.txt
|
Q:
What are the major differences between Python and PHP?
I know PHP a little. But Python is totally new for me. I only know it's something "similar", right? Or wrong? What are the differences I should know?
A:
This page on the Python wiki highlights the main
differences and the common elements between Python and PHP:
Compared as Languages
What strengths does PHP have that Python doesn't?
the 'switch' statement and 'do ... while' construct.
increment and decrement and assignment operators (assignment is a statement only in Python).
the ternary operator/statement (... ? ... : ...).
Retort: Python 2.5 has conditional expressions.
an expedient (commonly installed) environment
one array type that doubles as a list and a dictionary. Dictionary keys are iterated in their original order.
private, protected and public modifiers for both properties and methods abstract and final modifiers for both classes and methods
interfaces.
Note: as Python has multiple inheritance, there's less
need for interfaces. Also Python 2.6 has introduced Abstract Base
Classes.
variable variables
default arguments in functions
embedding in HTML (Note: mod_python has this as well).
a wide range of byte-code caches available.
What weaknesses does PHP have that Python doesn't?
(more verbose) syntax from C/C++ and Perl, with lots curly braces and dollar signs and "->"-s
confused tableau of function names. The builtin library has a wide variety of naming conventions. Functions often have prefixes to denote
their source (but often not). Functions are often placed into classes
to simulate namespaces.
a somewhat weak type system (not to be confused with dynamic types).
What does Python have that PHP doesn't?
indentation is used to mark out block structure rather than curly braces.
Retort: PHP curly braces make it work with HTML more easy.
modules
Rules that help catching typos more; reading an undefined variable is an error, it's not silently treated as if it was null.
Retort: PHP will issue E_NOTICE. This will be shown in a develop environment.
Counter-retort: It's still dangerous in production environment. As of the development, it's extra hassle to configure, watch logs,
etc., when it could just stop, as you are supposed to eliminate these
problems anyway. That PHP still has the more easy-going approach is
probably because people have utilized undefined vars a lot in existing
code base, so they couldn't fix this.
a small core (language or runtime?)
retort: it is not entirely true (substance needed)
very clear, concise, and orthogonal syntax
keyword arguments (i.e., parameters passed by name instead of by position) to functions and methods, easy support for default arguments
Retort: PHP have default arguments
Counter-retort: Defaults are much less useful without keyword arguments
true object orientation and 'first class' classes and functions
Retort: OO has been completely revamped in PHP 5
Counter-retort: But it's still painful, obviously a hack
classes are used extensively in the standard library.
Retort: PHP 5 has SPL which is fully class-based
multiple inheritance
object-oriented file handling
excellent introspection
Retort: PHP 5 Reflection
Counter-retort: We said excellent introspection
everything is a reference! (references are painful in PHP)
Retort: Not in PHP 5
Counter-retort: note that arrays are still passed around by value (unless you add an explicit &)
Retort: You won't accidentally modify it.
consistent case sensitivity (PHP functions are case insensitive, but variables are case sensitive)
a simple array slicing syntax
iterators
Retort: in PHP 5
structured exception handling
Retort: in PHP 5
Counter-retort: where are PHP 5's equivalent of else and finally?
Counter-retort 2: unfortunately most standard PHP functions don't use exceptions for reporting errors, which makes structured
exception handling much less useful
'finally' made it in PHP 5.5 operator overloading
Retort: In PHP you can use runkit extension to emulate the same feature
Counter-retort: "In PHP you have to use runkit extension to emulate the same feature"
SWIG integration
threading
Retort: Python have Global Interpreter Lock so it's not really parallel
"with ... as" statement to deal with resources that need closing reliably and concisely
an excellent profiler
Retort: XDebug, a debugging and profiling extension, that supports both PHP4 and PHP5 is extremely popular lots of high-level
data types (lists, tuples, dicts, DateTimes, NumPy arrays, etc.)
Retort: PHP had SPL Types which is included in PHP5 as a standard library
differentiation between arrays (lists) and associative arrays (dictionaries).
Retort: PHP array is more flexible. In case developer want a true array, just use FixedArray in PHP SPL
support for all major GUI frameworks
strong internationalization and UNICODE support
Retort: PHP 6 will include Unicode support. This feature is available in PHP5.2 and PHP5.3 via intl extension which can be found
at pecl.php.net
Retort: PHP have mbstring for Unicode
tends to lead to much more scalable applications -- importing modules is safer than textually including code as in PHP: global
variables are not used to exchange information.
Compared as Web Development Frameworks
Unlike PHP, which has web development features built directly into the
core language, Python's web development capabilities are provided by
add-on modules. Basic CGI capabilities are provided by the 'cgi'
module which comes in Python's standard library. There's also a wide
range of third-party modules available for Python; some are
complementary, others compete. As a result, Python provides a more
flexible base for web development.
There are some adverse side effects of this flexibility. First, the
range of choices can be bewildering. Unless you are working
experienced Python web developers, PHP is easier to get started with.
Second, support for PHP is more common with shared-hosting companies
than support for the various Python options.
Another difference is that PHP is embedded in the web server, whereas
Python web applications can either be embedded in the web server like
PHP or run in a separate process. Here's a simple classification of
Python web development platforms:
emdedded in the web server process
Apache modules (eg. mod_python) embed the Python interpreter in Apache and allow other Apache modules to be written with Python. This
is the same idea as mod_perl.
PyWX is an extension to AOLServer that serves the same purpose as the Apache modules above.
MS ASP scripts can be written using Python via Active Scripting Host.
running in a separate process
non-persistent process (a new process is spawned for each request)
custom CGI scripts
persistent process (all requests are sent from the web server to one persistent process)
custom Fast-CGI scripts
'Application Servers' (eg. Zope, Webware, SkunkWeb)
(Note: It's possible to write a long-running server in PHP, but there
are precious few examples of it.)
The vast majority of Python Web applications are run in a separate
process. This has some important implications.
Security
PHP has historically had a horrible history when it comes to security.
See the following article as an example:
http://old.lwn.net/2001/0704/a/study-in-scarlet.php3 (Note: This
article was published 10 years ago, and is no longer valid for more
than an idea of PHPs history with security).
Community Support
PHP:
huge installed user base, but the figures are probably distorted by shared hosting
low signal-to-noise ratio -- because PHP is so expedient, many of the users are not invested in the technology (or even their own code)
or the community
Python:
sizable, but not huge, installed user base
Python Software Foundation
lots of specialized interest groups
very high signal-to-noise ratio
Commercial Support
PHP
http://www.zend.com
Python
See the
CommercialServices
page for more information.
A:
PHP is a language that's made for the web. You can make GTK and CLI applications with PHP, but it's mainly used for websites. Python is used for a lot of stuff like websites, webservers, game frameworks, desktop and CLI application, IDEs and a lot more.
There's also a huge difference in the syntax. PHP has a syntax that's like C with curly braces for loops and whitespace is ignored. Python doesn't have curly braces, instead the level of indention of blocks of code are important.
Both languages are easy to learn. It just depends on what you want to do.
A:
One main difference is, that code formatting (indentation) influences your codes behaviour in Python. PHP is not interested in how you format your code.
Furthermore PHP may be able to produce applications outside of webservers and CLIs but is definitely aimed at those two environments while Python is more "all purpose".
|
What are the major differences between Python and PHP?
|
I know PHP a little. But Python is totally new for me. I only know it's something "similar", right? Or wrong? What are the differences I should know?
|
[
"This page on the Python wiki highlights the main\ndifferences and the common elements between Python and PHP:\n\nCompared as Languages\nWhat strengths does PHP have that Python doesn't?\n\nthe 'switch' statement and 'do ... while' construct.\nincrement and decrement and assignment operators (assignment is a statement only in Python).\nthe ternary operator/statement (... ? ... : ...).\n \n \nRetort: Python 2.5 has conditional expressions.\n\nan expedient (commonly installed) environment\none array type that doubles as a list and a dictionary. Dictionary keys are iterated in their original order.\nprivate, protected and public modifiers for both properties and methods abstract and final modifiers for both classes and methods\n interfaces.\n \n \nNote: as Python has multiple inheritance, there's less\n need for interfaces. Also Python 2.6 has introduced Abstract Base\n Classes.\n\nvariable variables\ndefault arguments in functions\nembedding in HTML (Note: mod_python has this as well).\na wide range of byte-code caches available.\n\nWhat weaknesses does PHP have that Python doesn't?\n\n(more verbose) syntax from C/C++ and Perl, with lots curly braces and dollar signs and \"->\"-s\nconfused tableau of function names. The builtin library has a wide variety of naming conventions. Functions often have prefixes to denote\n their source (but often not). Functions are often placed into classes\n to simulate namespaces.\na somewhat weak type system (not to be confused with dynamic types).\n\nWhat does Python have that PHP doesn't?\n\nindentation is used to mark out block structure rather than curly braces. \n \n \nRetort: PHP curly braces make it work with HTML more easy.\n\nmodules\nRules that help catching typos more; reading an undefined variable is an error, it's not silently treated as if it was null.\n \n \nRetort: PHP will issue E_NOTICE. This will be shown in a develop environment.\n \n \nCounter-retort: It's still dangerous in production environment. As of the development, it's extra hassle to configure, watch logs,\n etc., when it could just stop, as you are supposed to eliminate these\n problems anyway. That PHP still has the more easy-going approach is\n probably because people have utilized undefined vars a lot in existing\n code base, so they couldn't fix this.\n\n\na small core (language or runtime?)\n\nretort: it is not entirely true (substance needed)\n\nvery clear, concise, and orthogonal syntax\nkeyword arguments (i.e., parameters passed by name instead of by position) to functions and methods, easy support for default arguments\n\nRetort: PHP have default arguments\n\nCounter-retort: Defaults are much less useful without keyword arguments\n\n\ntrue object orientation and 'first class' classes and functions \n\nRetort: OO has been completely revamped in PHP 5\n\nCounter-retort: But it's still painful, obviously a hack\n\n\nclasses are used extensively in the standard library.\n\nRetort: PHP 5 has SPL which is fully class-based\n\nmultiple inheritance\nobject-oriented file handling\nexcellent introspection\n\nRetort: PHP 5 Reflection\nCounter-retort: We said excellent introspection\n\neverything is a reference! (references are painful in PHP)\n\nRetort: Not in PHP 5\nCounter-retort: note that arrays are still passed around by value (unless you add an explicit &)\nRetort: You won't accidentally modify it.\n\nconsistent case sensitivity (PHP functions are case insensitive, but variables are case sensitive)\na simple array slicing syntax\niterators\n\nRetort: in PHP 5\n\nstructured exception handling\n\nRetort: in PHP 5\nCounter-retort: where are PHP 5's equivalent of else and finally?\nCounter-retort 2: unfortunately most standard PHP functions don't use exceptions for reporting errors, which makes structured\n exception handling much less useful\n\n'finally' made it in PHP 5.5 operator overloading\n\nRetort: In PHP you can use runkit extension to emulate the same feature\nCounter-retort: \"In PHP you have to use runkit extension to emulate the same feature\"\n\nSWIG integration\nthreading\n\nRetort: Python have Global Interpreter Lock so it's not really parallel\n\n\"with ... as\" statement to deal with resources that need closing reliably and concisely\nan excellent profiler\n\nRetort: XDebug, a debugging and profiling extension, that supports both PHP4 and PHP5 is extremely popular lots of high-level\n data types (lists, tuples, dicts, DateTimes, NumPy arrays, etc.)\nRetort: PHP had SPL Types which is included in PHP5 as a standard library\n\ndifferentiation between arrays (lists) and associative arrays (dictionaries).\n\nRetort: PHP array is more flexible. In case developer want a true array, just use FixedArray in PHP SPL\n\nsupport for all major GUI frameworks\nstrong internationalization and UNICODE support\n\nRetort: PHP 6 will include Unicode support. This feature is available in PHP5.2 and PHP5.3 via intl extension which can be found\n at pecl.php.net\nRetort: PHP have mbstring for Unicode\n\ntends to lead to much more scalable applications -- importing modules is safer than textually including code as in PHP: global\n variables are not used to exchange information.\n\nCompared as Web Development Frameworks\nUnlike PHP, which has web development features built directly into the\n core language, Python's web development capabilities are provided by\n add-on modules. Basic CGI capabilities are provided by the 'cgi'\n module which comes in Python's standard library. There's also a wide\n range of third-party modules available for Python; some are\n complementary, others compete. As a result, Python provides a more\n flexible base for web development.\nThere are some adverse side effects of this flexibility. First, the\n range of choices can be bewildering. Unless you are working\n experienced Python web developers, PHP is easier to get started with.\n Second, support for PHP is more common with shared-hosting companies\n than support for the various Python options.\nAnother difference is that PHP is embedded in the web server, whereas\n Python web applications can either be embedded in the web server like\n PHP or run in a separate process. Here's a simple classification of\n Python web development platforms:\n\nemdedded in the web server process\n \n \nApache modules (eg. mod_python) embed the Python interpreter in Apache and allow other Apache modules to be written with Python. This\n is the same idea as mod_perl.\nPyWX is an extension to AOLServer that serves the same purpose as the Apache modules above.\nMS ASP scripts can be written using Python via Active Scripting Host.\n\nrunning in a separate process\n \n \nnon-persistent process (a new process is spawned for each request)\n \n \ncustom CGI scripts\n\npersistent process (all requests are sent from the web server to one persistent process)\n \n \ncustom Fast-CGI scripts\n'Application Servers' (eg. Zope, Webware, SkunkWeb)\n\n\n\n(Note: It's possible to write a long-running server in PHP, but there\n are precious few examples of it.)\nThe vast majority of Python Web applications are run in a separate\n process. This has some important implications.\nSecurity\nPHP has historically had a horrible history when it comes to security.\n See the following article as an example:\n http://old.lwn.net/2001/0704/a/study-in-scarlet.php3 (Note: This\n article was published 10 years ago, and is no longer valid for more\n than an idea of PHPs history with security).\nCommunity Support\nPHP:\n\nhuge installed user base, but the figures are probably distorted by shared hosting\nlow signal-to-noise ratio -- because PHP is so expedient, many of the users are not invested in the technology (or even their own code)\n or the community\n\nPython:\n\nsizable, but not huge, installed user base\nPython Software Foundation\nlots of specialized interest groups\nvery high signal-to-noise ratio\n\nCommercial Support\nPHP\nhttp://www.zend.com\nPython\nSee the\n CommercialServices\n page for more information.\n\n",
"PHP is a language that's made for the web. You can make GTK and CLI applications with PHP, but it's mainly used for websites. Python is used for a lot of stuff like websites, webservers, game frameworks, desktop and CLI application, IDEs and a lot more.\nThere's also a huge difference in the syntax. PHP has a syntax that's like C with curly braces for loops and whitespace is ignored. Python doesn't have curly braces, instead the level of indention of blocks of code are important.\nBoth languages are easy to learn. It just depends on what you want to do.\n",
"One main difference is, that code formatting (indentation) influences your codes behaviour in Python. PHP is not interested in how you format your code.\nFurthermore PHP may be able to produce applications outside of webservers and CLIs but is definitely aimed at those two environments while Python is more \"all purpose\".\n"
] |
[
18,
16,
1
] |
[] |
[] |
[
"php",
"python"
] |
stackoverflow_0001936085_php_python.txt
|
Q:
Excluding last element in 0-based indexing
Once when I was reading some python docs I came across a reference to an article that explained why programming languages with 0-based indexing should always exclude the last element during operations like slicing:
>> a = [1, 2, 3]
>> a[0:1]
[1] #and not [1,2]
Unfortunately I did not bookmark it. Does anyone know which article I am talking about?
PS: I welcome any explanations of why this is for my immediate satisfaction :-)
A:
Could it be this note from E. W. Dijkstra?
A:
No, but there are at least two good reasons:
a[m:n] gives you n-m elements, making it easy to compute how many elements you are requesting.
With inclusive end-points, it's awkward to request an empty slice (a[3:2]? yuck).
Edit: I just thought of another Python-specific reason: a[m:-n] excludes the first m and last n items. If it was inclusive, it would exclude the first m and last n-1 items, which is much harder to remember.
A:
You might be thinking of Dijkstra's short note about zero-based numbering.
A:
I don't know exactly which article you are referring to, but Googling half-open ranges should find it for you. It found this surprisingly good one that I think is a new personal favorite.
A:
As far as I know, the first extensive treatment in print was in Koenig's great book, C Traps and Pitfalls -- 20 years old and still in print (indeed, in-stock and shipped immediately from Amazon!-), quite a tribute to its nature as a classic. Unfortunately, there are no previews of it available in Google Books, and while the PDF of the internal report which formed the book is available online, it's obviously much shorter than the book and in particular it does not mention the "open-ranges" issue. There are of course pirate copies on the web, but I don't recommend downloading those.
Several years ago, I summarized Koenig's reasoning here, with a followup discussion here, but of course that's no substitute for the complete treatment as found in his book (though it may be a helpful complement, as in the second post in particular I add other observations in response to critique that was posted on that thread).
A:
Don't know any specific article, but I think the rationale is simply that this way you get the number of resulting elements via simple subtraction, 1-0=1, instead of having to add 1 there (which you would forget half of the time anyway).
|
Excluding last element in 0-based indexing
|
Once when I was reading some python docs I came across a reference to an article that explained why programming languages with 0-based indexing should always exclude the last element during operations like slicing:
>> a = [1, 2, 3]
>> a[0:1]
[1] #and not [1,2]
Unfortunately I did not bookmark it. Does anyone know which article I am talking about?
PS: I welcome any explanations of why this is for my immediate satisfaction :-)
|
[
"Could it be this note from E. W. Dijkstra?\n",
"No, but there are at least two good reasons:\n\na[m:n] gives you n-m elements, making it easy to compute how many elements you are requesting.\nWith inclusive end-points, it's awkward to request an empty slice (a[3:2]? yuck).\n\nEdit: I just thought of another Python-specific reason: a[m:-n] excludes the first m and last n items. If it was inclusive, it would exclude the first m and last n-1 items, which is much harder to remember.\n",
"You might be thinking of Dijkstra's short note about zero-based numbering.\n",
"I don't know exactly which article you are referring to, but Googling half-open ranges should find it for you. It found this surprisingly good one that I think is a new personal favorite.\n",
"As far as I know, the first extensive treatment in print was in Koenig's great book, C Traps and Pitfalls -- 20 years old and still in print (indeed, in-stock and shipped immediately from Amazon!-), quite a tribute to its nature as a classic. Unfortunately, there are no previews of it available in Google Books, and while the PDF of the internal report which formed the book is available online, it's obviously much shorter than the book and in particular it does not mention the \"open-ranges\" issue. There are of course pirate copies on the web, but I don't recommend downloading those.\nSeveral years ago, I summarized Koenig's reasoning here, with a followup discussion here, but of course that's no substitute for the complete treatment as found in his book (though it may be a helpful complement, as in the second post in particular I add other observations in response to critique that was posted on that thread).\n",
"Don't know any specific article, but I think the rationale is simply that this way you get the number of resulting elements via simple subtraction, 1-0=1, instead of having to add 1 there (which you would forget half of the time anyway).\n"
] |
[
8,
5,
3,
1,
1,
0
] |
[] |
[] |
[
"arrays",
"programming_languages",
"python"
] |
stackoverflow_0001935990_arrays_programming_languages_python.txt
|
Q:
Sub-classing float type in Python, fails to catch exception in __init__()
On Python 2.5 I need to use float numbers with a modified __str__() method. Also I need to know when the constructor fails.
Why I can't catch exceptions raised from float.__init__()?
What is the best way to consult the numeric value of my derived float object? In my code I'm using float(self).
class My_Number(float):
def __init__(self, float_string):
try:
super(My_Number, self).__init__(float_string)
except (TypeError, ValueError):
raise My_Error(float_string)
def __str__(self):
if int(float(self)) == float(self):
return str(int(float(self)))
else:
return str(round(float(self), 2))
>>> n = My_Number('0.54353')
>>> print n
0.54
>>> n = My_Number('5.0')
>>> print n
5
>>> n = My_Number('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): foo
A:
float is immutable, therefore its __init__, the initializer, is basically a no-op -- nothing substantial can happen there, because the self object cannot be altered (if it's actually an instance of float rather than of a subclass -- but of course float's own __init__ must operate on that assumption;-).
Therefore, all the action happens in __new__, the constructor proper, just like for other immutable types like int, str, tuple, and so on. It's a common mistake to believe that __init__ is a constructor: it's not, it takes an already-constructed object as its first argument, self, and "initializes" it (if feasible, i.e., if that self is mutable!-) -- the construction itself happens in __new__.
So, your float subclass should start:
class My_Number(float):
def __new__(cls, float_string):
try: return float.__new__(cls, float_string)
except (TypeError, ValueError): raise My_Error(float_string)
and you can remove the __init__, which is not needed. Now:
>>> n = My_Number('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __new__
NameError: global name 'My_Error' is not defined
(of course, it would work even better if you did have a My_Error exception class defined;-).
A:
try __new__ instead:
class F(float):
def __new__(cls, *arg, **kw):
try:
return float.__new__(cls, *arg, **kw)
except ValueError:
raise Exception("foo")
print F("3.5")
print F("asdf")
Also "self" is a float already so no need to say float(self), just "self" will do:
def __str__(self):
return "%.2f" % self
|
Sub-classing float type in Python, fails to catch exception in __init__()
|
On Python 2.5 I need to use float numbers with a modified __str__() method. Also I need to know when the constructor fails.
Why I can't catch exceptions raised from float.__init__()?
What is the best way to consult the numeric value of my derived float object? In my code I'm using float(self).
class My_Number(float):
def __init__(self, float_string):
try:
super(My_Number, self).__init__(float_string)
except (TypeError, ValueError):
raise My_Error(float_string)
def __str__(self):
if int(float(self)) == float(self):
return str(int(float(self)))
else:
return str(round(float(self), 2))
>>> n = My_Number('0.54353')
>>> print n
0.54
>>> n = My_Number('5.0')
>>> print n
5
>>> n = My_Number('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): foo
|
[
"float is immutable, therefore its __init__, the initializer, is basically a no-op -- nothing substantial can happen there, because the self object cannot be altered (if it's actually an instance of float rather than of a subclass -- but of course float's own __init__ must operate on that assumption;-).\nTherefore, all the action happens in __new__, the constructor proper, just like for other immutable types like int, str, tuple, and so on. It's a common mistake to believe that __init__ is a constructor: it's not, it takes an already-constructed object as its first argument, self, and \"initializes\" it (if feasible, i.e., if that self is mutable!-) -- the construction itself happens in __new__.\nSo, your float subclass should start:\nclass My_Number(float):\n def __new__(cls, float_string):\n try: return float.__new__(cls, float_string)\n except (TypeError, ValueError): raise My_Error(float_string)\n\nand you can remove the __init__, which is not needed. Now:\n>>> n = My_Number('foo')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 4, in __new__\nNameError: global name 'My_Error' is not defined\n\n(of course, it would work even better if you did have a My_Error exception class defined;-).\n",
"try __new__ instead:\nclass F(float):\n def __new__(cls, *arg, **kw):\n try:\n return float.__new__(cls, *arg, **kw)\n except ValueError:\n raise Exception(\"foo\")\n\nprint F(\"3.5\") \nprint F(\"asdf\")\n\nAlso \"self\" is a float already so no need to say float(self), just \"self\" will do:\ndef __str__(self):\n return \"%.2f\" % self\n\n"
] |
[
23,
8
] |
[] |
[] |
[
"exception_handling",
"python"
] |
stackoverflow_0001936457_exception_handling_python.txt
|
Q:
operator overloading in python
Possible Duplicates:
Python: defining my own operators?
Rules of thumb for when to use operator overloading in python
Is it possible to overload operators in Python? If so, can one define new operators, such as ++ and <<?
A:
As other answers have mentioned, you can indeed overload operators (by definining special methods in the class you're writing, i.e., methods whose names start and end with two underscores). All the details are here.
To complete the answers to you questions: you cannot define new operators; but << is not a new operator, it's an existing one, and it's overloaded by defining in the class the method __lshift__.
As a historical note, this is also pretty much the situation in C++ -- but the exact set of operators you can overload differs between the two languages. For example, in C++, you cannot overload attribute access, .; in Python, you can, with __getattr__ (or __getattribute__, with different semantics) and __setattr__. Vice versa, in Python = (plain assignment) is not an operator, so you cannot overload that, while in C++ it is an operator and you can overload it.
<< is an operator, and can be overloaded, in both languages -- that's how << and >>, while not losing their initial connotation of left and right shifts, also became I/O formatting operators in C++ (not in Python!-).
A:
See: http://docs.python.org/reference/datamodel.html#special-method-names.
A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.
A:
Yes, and no. I don't think you can define your own operators, but you can overload the existing ones - you can do that by overriding the operator's special method. For example,
to override >, you can override __gt__(), for != override __ne__() and so on.
|
operator overloading in python
|
Possible Duplicates:
Python: defining my own operators?
Rules of thumb for when to use operator overloading in python
Is it possible to overload operators in Python? If so, can one define new operators, such as ++ and <<?
|
[
"As other answers have mentioned, you can indeed overload operators (by definining special methods in the class you're writing, i.e., methods whose names start and end with two underscores). All the details are here.\nTo complete the answers to you questions: you cannot define new operators; but << is not a new operator, it's an existing one, and it's overloaded by defining in the class the method __lshift__.\nAs a historical note, this is also pretty much the situation in C++ -- but the exact set of operators you can overload differs between the two languages. For example, in C++, you cannot overload attribute access, .; in Python, you can, with __getattr__ (or __getattribute__, with different semantics) and __setattr__. Vice versa, in Python = (plain assignment) is not an operator, so you cannot overload that, while in C++ it is an operator and you can overload it.\n<< is an operator, and can be overloaded, in both languages -- that's how << and >>, while not losing their initial connotation of left and right shifts, also became I/O formatting operators in C++ (not in Python!-).\n",
"See: http://docs.python.org/reference/datamodel.html#special-method-names.\n\nA class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators. \n\n",
"Yes, and no. I don't think you can define your own operators, but you can overload the existing ones - you can do that by overriding the operator's special method. For example, \nto override >, you can override __gt__(), for != override __ne__() and so on. \n"
] |
[
72,
6,
4
] |
[] |
[] |
[
"operator_overloading",
"python"
] |
stackoverflow_0001936135_operator_overloading_python.txt
|
Q:
How do you listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter)
Looking for help/tutorials/sample code of using python to listen to distributed notifications from applications on a mac. I know the py-objc lib is the bridge between python and mac/cocoa classes, and the Foundation library can be used to add observers, but looking for examples or tutorials on how to use this to monitor iTunes.
A:
If anyone comes by to this question, i figured out how to listen, the code below works. However accessing attributes do not seem to work like standard python attribute access.
Update: you do not access attributes as you would in python i.e (.x), the code has been updated below, it now generates a dict called song_details.
Update3: Update to the code, now subclassing NSObject, removed adding the addObserver from the class. Will keep the code updated on github, no more updates here.
import Foundation
from AppKit import *
from PyObjCTools import AppHelper
class GetSongs(NSObject):
def getMySongs_(self, song):
song_details = {}
ui = song.userInfo()
for x in ui:
song_details[x] = ui.objectForKey_(x)
print song_details
nc = Foundation.NSDistributedNotificationCenter.defaultCenter()
GetSongs = GetSongs.new()
nc.addObserver_selector_name_object_(GetSongs, 'getMySongs:', 'com.apple.iTunes.playerInfo',None)
NSLog("Listening for new tunes....")
AppHelper.runConsoleEventLoop()
A:
The source code for GrowlTunes might give you some clues here. You'd have to translate from Objective-C to PyObjC, but eh, whatever. :)
GrowlTurnesController.m
(Or grab the whole growl source tree and navigate to GrowlTunes so you can see it all in action.: here's a link to the directions on how to get the source
|
How do you listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter)
|
Looking for help/tutorials/sample code of using python to listen to distributed notifications from applications on a mac. I know the py-objc lib is the bridge between python and mac/cocoa classes, and the Foundation library can be used to add observers, but looking for examples or tutorials on how to use this to monitor iTunes.
|
[
"If anyone comes by to this question, i figured out how to listen, the code below works. However accessing attributes do not seem to work like standard python attribute access. \nUpdate: you do not access attributes as you would in python i.e (.x), the code has been updated below, it now generates a dict called song_details. \nUpdate3: Update to the code, now subclassing NSObject, removed adding the addObserver from the class. Will keep the code updated on github, no more updates here. \nimport Foundation\nfrom AppKit import *\nfrom PyObjCTools import AppHelper\n\nclass GetSongs(NSObject):\n def getMySongs_(self, song):\n song_details = {}\n ui = song.userInfo()\n for x in ui:\n song_details[x] = ui.objectForKey_(x)\n print song_details\n\nnc = Foundation.NSDistributedNotificationCenter.defaultCenter()\nGetSongs = GetSongs.new()\nnc.addObserver_selector_name_object_(GetSongs, 'getMySongs:', 'com.apple.iTunes.playerInfo',None)\n\nNSLog(\"Listening for new tunes....\")\nAppHelper.runConsoleEventLoop()\n\n",
"The source code for GrowlTunes might give you some clues here. You'd have to translate from Objective-C to PyObjC, but eh, whatever. :)\nGrowlTurnesController.m\n(Or grab the whole growl source tree and navigate to GrowlTunes so you can see it all in action.: here's a link to the directions on how to get the source\n"
] |
[
11,
4
] |
[] |
[] |
[
"macos",
"notifications",
"pyobjc",
"python"
] |
stackoverflow_0001933107_macos_notifications_pyobjc_python.txt
|
Q:
wxPython - DatePickerCtrl seems to ignore SetValue()
I'm trying to pre-populate a wxPython DatePicker with a value using the following code:
month, day, year = runData[2][0:8].split('/')
displayDate = wx.DateTimeFromDMY(int(day), int(month) - 1, int(year))
self.datePicker.SetValue(displayDate)
Here are the printed values:
runData[2] = 12/16/09 00:00
month, day, year = 12 16 09
displayDate = 12/16/09 00:00:00
But, datePicker always shows today's date instead.
Any ideas?
I'm using Python 2.6.4 with wxPython 2.8.10.1 on Windows 7.
Thanks.
Update 20/12/09 16:30:
When I try and process the information from the DatePickerCtrl with the problem, I get the following error:
Traceback (most recent call last):
File "test.py", line 1120, in onOk
dateLong = self.datePicker.GetValue()
File "c:\python26\lib\site-packages\wx-2.8-msw-unicode\wx\_controls.py", line
6465, in GetValue
return _controls_.DatePickerCtrlBase_GetValue(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "m_date.IsValid() == dt.IsValid() && (!
dt.IsValid() || dt == m_date)" failed at ..\..\src\msw\datectrl.cpp(278) in wxDa
tePickerCtrl::GetValue(): bug in wxDatePickerCtrl: m_date not in sync
Am I missing something?
A:
Have you tried making year 2009 instead of 9?
|
wxPython - DatePickerCtrl seems to ignore SetValue()
|
I'm trying to pre-populate a wxPython DatePicker with a value using the following code:
month, day, year = runData[2][0:8].split('/')
displayDate = wx.DateTimeFromDMY(int(day), int(month) - 1, int(year))
self.datePicker.SetValue(displayDate)
Here are the printed values:
runData[2] = 12/16/09 00:00
month, day, year = 12 16 09
displayDate = 12/16/09 00:00:00
But, datePicker always shows today's date instead.
Any ideas?
I'm using Python 2.6.4 with wxPython 2.8.10.1 on Windows 7.
Thanks.
Update 20/12/09 16:30:
When I try and process the information from the DatePickerCtrl with the problem, I get the following error:
Traceback (most recent call last):
File "test.py", line 1120, in onOk
dateLong = self.datePicker.GetValue()
File "c:\python26\lib\site-packages\wx-2.8-msw-unicode\wx\_controls.py", line
6465, in GetValue
return _controls_.DatePickerCtrlBase_GetValue(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "m_date.IsValid() == dt.IsValid() && (!
dt.IsValid() || dt == m_date)" failed at ..\..\src\msw\datectrl.cpp(278) in wxDa
tePickerCtrl::GetValue(): bug in wxDatePickerCtrl: m_date not in sync
Am I missing something?
|
[
"Have you tried making year 2009 instead of 9?\n"
] |
[
2
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0001936074_python_wxpython.txt
|
Q:
Setting an alias to a Django "plug-in" app
is there some pythonic way to load a django app trough an alias name? This I think would be one way to make an app more "pluggable-friendly".
there is a pattern used in settings.py:
INSTALLED_APPS = ('... ','...', )
where INSTALLED_APPS is a tuple containing names of apps.
That's fine, but I don't want to put in certain apps explicitly this way.
I would like to have an app handle named say external_login_app mapping to drupal_login or mediawiki_login (to be supplied by the end user or a third party), where name of the actual custom module/app is provided by a string variable in settings.py
The pluggable part (e.g. mediawiki_login) must be a full-fledged app with it's own views, models, forms, etc, while external_login_app must be accessible anywhere in the rest of the code.
The goal here is to decouple distributed code from plugins like that.
edit 1: here is what I'm trying:
in settings.py
EXTERNAL_LOGIN = __import__(EXTERNAL_LOGIN_APP)
#setting name must be upper case according to
#django docs
but my custom login app depends on the settings file too, so looks like I have a circular import problem with errors like module external_login does not have attribute views.
This problem seems to be very insidious, as I am unable to use even simple things like render_to_response shortcut in views imported with __import__ statement in settings.py.
edit 2: after trying a while I found that using __import__() in settings.py call won't work because of almost inevitable circular dependencies
The best working method I found so far is to place __import__() calls into other .py files of the app providing the generic "consumer" interface - the one that calls the plugin functions:
in settings.py: as Michał suggests in his answer
EXTERNAL_LOGIN_APP = 'drupal_login'
INSTALLED_APPS = (
'...',
EXTERNAL_LOGIN_APP,
)
e.g. in app/views.py:
from django.conf import settings
EXTERNAL_LOGIN = __import__(settings.EXTERNAL_LOGIN_APP, \
[], [], ['api','forms'])
def login_view(request, external=False):
if external:
form = EXTERNAL_LOGIN.forms.LoginForm(request.POST)
if form.is_valid():
login = form.cleaned_data['login']
password = form.cleand_data['password']
if EXTERNAL_LOGIN.api.check_password(login, password):
#maybe create local account,
#do local authentication
#set session cookies for the
#external site to synchronize logins, etc.
A:
Set
LOGIN_APP_NAME = 'drupal_login' # or 'mediawiki_login', or whatever
early enough in settings.py, then put LOGIN_APP_NAME (without any quotes around it!) in your INSTALLED_APPS instead of the name of the actual app.
If you need more complex functionality involved in determining what app to use, how about putting something like external_login_app() (a function call -- put no quotes around it!) in INSTALLED_APPS and having the external_login_app function return whatever it is that it should return based on a setting in settings.py, or maybe the contents of a config file somewhere or whatever? (EDIT: Tobu's answer shows what such a function might need to return and how it might go about achieving that with __import__.)
Anyway, I'm not sure that much is achieved in this way in terms of decoupling parts of the site -- if the user still needs to modify settings.py, why not have him / her put in the name of the appropriate app in the right place? (EDIT: OK, so now I sort of see what could be gained with the right solution here... I guess the discussion continues as to how best to do what is required.)
EDIT: I posted this prior to the Original Poster amending the question with any edits, and now edit 2 includes the idea of moving the name of the login app to a separate variable in settings.py and including the variable in INSTALLED_APPS. Now that the two edits to the original question are in place, I guess I can sort of see the problem clearer, although that just makes me think that what the situation calls for is an abstract_login app with backends to support the '*_login' modules dealing with drupal, mediawiki etc. login schemes. Well, I can't say I can provide that sort of thing right now... Hope somebody else can. Will edit again should I believe I have a bright idea simplifying the whole thing beyond the OP's edits.
A:
Defining the app name in settings(as Michał and your edit do) works well:
EXTERNAL_LOGIN_APP = 'drupal_login'
INSTALLED_APPS = (
'...',
EXTERNAL_LOGIN_APP,
)
Also in settings, or in a common module, you could then factor in importing the app:
def external_login_app():
return __import__(EXTERNAL_LOGIN_APP, …)
And use it after your imports:
external_login_app = settings.external_login_app()
|
Setting an alias to a Django "plug-in" app
|
is there some pythonic way to load a django app trough an alias name? This I think would be one way to make an app more "pluggable-friendly".
there is a pattern used in settings.py:
INSTALLED_APPS = ('... ','...', )
where INSTALLED_APPS is a tuple containing names of apps.
That's fine, but I don't want to put in certain apps explicitly this way.
I would like to have an app handle named say external_login_app mapping to drupal_login or mediawiki_login (to be supplied by the end user or a third party), where name of the actual custom module/app is provided by a string variable in settings.py
The pluggable part (e.g. mediawiki_login) must be a full-fledged app with it's own views, models, forms, etc, while external_login_app must be accessible anywhere in the rest of the code.
The goal here is to decouple distributed code from plugins like that.
edit 1: here is what I'm trying:
in settings.py
EXTERNAL_LOGIN = __import__(EXTERNAL_LOGIN_APP)
#setting name must be upper case according to
#django docs
but my custom login app depends on the settings file too, so looks like I have a circular import problem with errors like module external_login does not have attribute views.
This problem seems to be very insidious, as I am unable to use even simple things like render_to_response shortcut in views imported with __import__ statement in settings.py.
edit 2: after trying a while I found that using __import__() in settings.py call won't work because of almost inevitable circular dependencies
The best working method I found so far is to place __import__() calls into other .py files of the app providing the generic "consumer" interface - the one that calls the plugin functions:
in settings.py: as Michał suggests in his answer
EXTERNAL_LOGIN_APP = 'drupal_login'
INSTALLED_APPS = (
'...',
EXTERNAL_LOGIN_APP,
)
e.g. in app/views.py:
from django.conf import settings
EXTERNAL_LOGIN = __import__(settings.EXTERNAL_LOGIN_APP, \
[], [], ['api','forms'])
def login_view(request, external=False):
if external:
form = EXTERNAL_LOGIN.forms.LoginForm(request.POST)
if form.is_valid():
login = form.cleaned_data['login']
password = form.cleand_data['password']
if EXTERNAL_LOGIN.api.check_password(login, password):
#maybe create local account,
#do local authentication
#set session cookies for the
#external site to synchronize logins, etc.
|
[
"Set\nLOGIN_APP_NAME = 'drupal_login' # or 'mediawiki_login', or whatever\n\nearly enough in settings.py, then put LOGIN_APP_NAME (without any quotes around it!) in your INSTALLED_APPS instead of the name of the actual app.\nIf you need more complex functionality involved in determining what app to use, how about putting something like external_login_app() (a function call -- put no quotes around it!) in INSTALLED_APPS and having the external_login_app function return whatever it is that it should return based on a setting in settings.py, or maybe the contents of a config file somewhere or whatever? (EDIT: Tobu's answer shows what such a function might need to return and how it might go about achieving that with __import__.) \nAnyway, I'm not sure that much is achieved in this way in terms of decoupling parts of the site -- if the user still needs to modify settings.py, why not have him / her put in the name of the appropriate app in the right place? (EDIT: OK, so now I sort of see what could be gained with the right solution here... I guess the discussion continues as to how best to do what is required.)\nEDIT: I posted this prior to the Original Poster amending the question with any edits, and now edit 2 includes the idea of moving the name of the login app to a separate variable in settings.py and including the variable in INSTALLED_APPS. Now that the two edits to the original question are in place, I guess I can sort of see the problem clearer, although that just makes me think that what the situation calls for is an abstract_login app with backends to support the '*_login' modules dealing with drupal, mediawiki etc. login schemes. Well, I can't say I can provide that sort of thing right now... Hope somebody else can. Will edit again should I believe I have a bright idea simplifying the whole thing beyond the OP's edits.\n",
"Defining the app name in settings(as Michał and your edit do) works well:\nEXTERNAL_LOGIN_APP = 'drupal_login'\nINSTALLED_APPS = (\n '...',\n EXTERNAL_LOGIN_APP,\n )\n\nAlso in settings, or in a common module, you could then factor in importing the app:\ndef external_login_app():\n return __import__(EXTERNAL_LOGIN_APP, …)\n\nAnd use it after your imports:\nexternal_login_app = settings.external_login_app()\n\n"
] |
[
4,
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001934188_django_python.txt
|
Q:
How can I run all unit tests of Jinja2?
I want to run the unittests of Jinja2 whenever I change something to make sure I'm not breaking something.
There's a package full of unit tests. Basically it's a folder full of Python files with the name "test_xxxxxx.py"
How do I run all of these tests in one command?
A:
It looks like Jinja uses the py.test testing tool. If so you can run all tests by just running py.test from within the tests subdirectory.
A:
You could also take a look at nose too. It's supposed to be a py.test evolution.
A:
Watch out for "test.py" in the Jinja2 package! -- Those are not unit tests! That is a set of utility functions for checking attributes, etc. My testing package is assuming that they are unit tests because of the name "test" -- and returning strange messages.
|
How can I run all unit tests of Jinja2?
|
I want to run the unittests of Jinja2 whenever I change something to make sure I'm not breaking something.
There's a package full of unit tests. Basically it's a folder full of Python files with the name "test_xxxxxx.py"
How do I run all of these tests in one command?
|
[
"It looks like Jinja uses the py.test testing tool. If so you can run all tests by just running py.test from within the tests subdirectory.\n",
"You could also take a look at nose too. It's supposed to be a py.test evolution.\n",
"Watch out for \"test.py\" in the Jinja2 package! -- Those are not unit tests! That is a set of utility functions for checking attributes, etc. My testing package is assuming that they are unit tests because of the name \"test\" -- and returning strange messages.\n"
] |
[
1,
0,
0
] |
[
"Try to 'walk' through the directories and import all from files like \"test_xxxxxx.py\", then call unittest.main()\n"
] |
[
-1
] |
[
"jinja2",
"python",
"unit_testing"
] |
stackoverflow_0000665093_jinja2_python_unit_testing.txt
|
Q:
How to run installed python script?
I used distutils to install my python package, with this setup.py :
import distutils.core
args = {
'name' : 'plugh',
'version' : '1.0',
'scripts' : [ "scripts/plugh" ],
'packages': [ "plugh" ],
}
d = distutils.core.setup(
**args
)
On linux/mac, it works as expected:
% plugh
hello world
%
On windows, the script "plugh" does not run:
C:\Python25\Scripts>plugh
'plugh' is not recognized as an internal or external command,
operable program or batch file.
C:\Python25\Scripts>
I found the bug report at http://bugs.python.org/issue7231 that the \Scripts directory is not added to PATH when you install python, so I applied the workaround described in that ticket (i.e. add C:\Python25\Scripts to PATH)
C:\Python25\Scripts>path
PATH=c:\Python25\Scripts;C:\Program Files\Legato\nsr\bin;C:\WINDOWS\system32;C:\
WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\QuickTime\QTSystem\;c:\python2
5;c:\local;C:\WINDOWS\system32\WindowsPowerShell\v1.0
Is this something that just doesn't work on Windows? And if so, how exactly are you supposed to use python scripts on a windows machine?
I suppose that I could detect Windows, and add an additional script to the list, called "plugh.bat" containing something like:
@echo off
c:\python25\python.exec c:\python25\scripts\plugh %1 %2 %3 %4 %5 %6 %7 %8 %9
but is that really the right answer here? I would have thought that with all the customizations that distutils contains for windows, there would be a better answer than that.
A:
windows uses the extension of the file to determine how it will run.
Name your file plugh.py and use plugh.py on the prompt to call it.
A:
If you use ActivePython, it will already add the C:\PythonXY\Scripts directory to your %PATH% (ActivePython 2.6 additionally adds PEP 370's %APPDATA%\Python\Scripts to %PATH%) during the installation.
For deploying scripts on Windows machine, better use Distribute which will take care of installing .exe wrappers for your scripts and invoking the actual Python with which your package was installed (to avoid conflict with multiple Python installations -- so naming your script to end .py is just not enough). For more on this topic, read about entry points in Distribute documentation.
|
How to run installed python script?
|
I used distutils to install my python package, with this setup.py :
import distutils.core
args = {
'name' : 'plugh',
'version' : '1.0',
'scripts' : [ "scripts/plugh" ],
'packages': [ "plugh" ],
}
d = distutils.core.setup(
**args
)
On linux/mac, it works as expected:
% plugh
hello world
%
On windows, the script "plugh" does not run:
C:\Python25\Scripts>plugh
'plugh' is not recognized as an internal or external command,
operable program or batch file.
C:\Python25\Scripts>
I found the bug report at http://bugs.python.org/issue7231 that the \Scripts directory is not added to PATH when you install python, so I applied the workaround described in that ticket (i.e. add C:\Python25\Scripts to PATH)
C:\Python25\Scripts>path
PATH=c:\Python25\Scripts;C:\Program Files\Legato\nsr\bin;C:\WINDOWS\system32;C:\
WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\QuickTime\QTSystem\;c:\python2
5;c:\local;C:\WINDOWS\system32\WindowsPowerShell\v1.0
Is this something that just doesn't work on Windows? And if so, how exactly are you supposed to use python scripts on a windows machine?
I suppose that I could detect Windows, and add an additional script to the list, called "plugh.bat" containing something like:
@echo off
c:\python25\python.exec c:\python25\scripts\plugh %1 %2 %3 %4 %5 %6 %7 %8 %9
but is that really the right answer here? I would have thought that with all the customizations that distutils contains for windows, there would be a better answer than that.
|
[
"windows uses the extension of the file to determine how it will run.\nName your file plugh.py and use plugh.py on the prompt to call it.\n",
"\nIf you use ActivePython, it will already add the C:\\PythonXY\\Scripts directory to your %PATH% (ActivePython 2.6 additionally adds PEP 370's %APPDATA%\\Python\\Scripts to %PATH%) during the installation.\nFor deploying scripts on Windows machine, better use Distribute which will take care of installing .exe wrappers for your scripts and invoking the actual Python with which your package was installed (to avoid conflict with multiple Python installations -- so naming your script to end .py is just not enough). For more on this topic, read about entry points in Distribute documentation.\n\n"
] |
[
6,
5
] |
[] |
[] |
[
"distutils",
"packaging",
"python",
"windows"
] |
stackoverflow_0001829524_distutils_packaging_python_windows.txt
|
Q:
Python send cmd on socket
I have a simple question about Python:
I have another Python script listening on a port on a Linux machine.
I have made it so I can send a request to it, and it will inform another system that it is alive and listening.
My problem is that I don't know how to send this request from another python script running on the same machine (blush)
I have a script running every minute, and I would like to expand it to also send this request. I dont expect to get a response back, my listening-script postes to a database.
In Internet Explorer, I write like this: http://192.168.1.46:8193/?Ping
I would like to know how to do this from Python, and preferably just send and not hang if the other script is not running.
thanks
Michael
A:
It looks like you are doing an HTTP request, rather than an ICMP ping.
urllib2, built-in to Python, can help you do that.
You'll need to override the timeout so you aren't hanging too long. Straight from that article, above, here is some example code for you to tweak with your desired time-out and URL.
import socket
import urllib2
# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)
# this call to urllib2.urlopen now uses the default timeout
# we have set in the socket module
req = urllib2.Request('http://www.voidspace.org.uk')
response = urllib2.urlopen(req)
A:
import urllib2
try:
response = urllib2.urlopen('http://192.168.1.46:8193/?Ping', timeout=2)
print 'response headers: "%s"' % response.info()
except IOError, e:
if hasattr(e, 'code'): # HTTPError
print 'http error code: ', e.code
elif hasattr(e, 'reason'): # URLError
print "can't connect, reason: ", e.reason
else:
raise # don't know what it is
A:
This is a bit outside my knowledge, but maybe this question might help?
Ping a site in Python?
A:
Considered Twisted? What you're trying to achieve could be taken straight out of their examples. It might be overkill, but if you'll eventually want to start adding authentication, authorization, SSL, etc. you might as well start in that direction.
|
Python send cmd on socket
|
I have a simple question about Python:
I have another Python script listening on a port on a Linux machine.
I have made it so I can send a request to it, and it will inform another system that it is alive and listening.
My problem is that I don't know how to send this request from another python script running on the same machine (blush)
I have a script running every minute, and I would like to expand it to also send this request. I dont expect to get a response back, my listening-script postes to a database.
In Internet Explorer, I write like this: http://192.168.1.46:8193/?Ping
I would like to know how to do this from Python, and preferably just send and not hang if the other script is not running.
thanks
Michael
|
[
"It looks like you are doing an HTTP request, rather than an ICMP ping.\nurllib2, built-in to Python, can help you do that.\nYou'll need to override the timeout so you aren't hanging too long. Straight from that article, above, here is some example code for you to tweak with your desired time-out and URL.\nimport socket\nimport urllib2\n\n# timeout in seconds\ntimeout = 10\nsocket.setdefaulttimeout(timeout)\n\n# this call to urllib2.urlopen now uses the default timeout\n# we have set in the socket module\nreq = urllib2.Request('http://www.voidspace.org.uk')\nresponse = urllib2.urlopen(req)\n\n",
"import urllib2\n\ntry:\n response = urllib2.urlopen('http://192.168.1.46:8193/?Ping', timeout=2) \n print 'response headers: \"%s\"' % response.info()\nexcept IOError, e:\n if hasattr(e, 'code'): # HTTPError\n print 'http error code: ', e.code\n elif hasattr(e, 'reason'): # URLError\n print \"can't connect, reason: \", e.reason\n else:\n raise # don't know what it is\n\n",
"This is a bit outside my knowledge, but maybe this question might help?\nPing a site in Python?\n",
"Considered Twisted? What you're trying to achieve could be taken straight out of their examples. It might be overkill, but if you'll eventually want to start adding authentication, authorization, SSL, etc. you might as well start in that direction.\n"
] |
[
4,
2,
0,
0
] |
[] |
[] |
[
"python",
"sockets"
] |
stackoverflow_0001935939_python_sockets.txt
|
Q:
Sprox form with Turbogears, using Mako, only displays plain text
I'm generating a Sprox form with Turbogears 2.1 and trying to display it in a Mako template. Here is my code:
To define the form:
class NewUserForm(AddRecordForm):
__model__ = User
newuserform = NewUserForm(DBSession)
The controller definition that assigns the form and calls the template:
@expose('limelight.modules.users.templates.register')
def register(self, **kw):
tmpl_context.register_form = newuserform
return dict(value=kw)
And the relevant template code:
${tmpl_context.register_form(value=value)}
The problem is the HTML code is displayed as plain text on the page, not rendered HTML.
A:
Figured it out. I have to pass the variable through the the 'n' mako filter to remove any automatic filters mako applies to the html generated. So:
${tmpl_context.register_form(value=value) | n}
|
Sprox form with Turbogears, using Mako, only displays plain text
|
I'm generating a Sprox form with Turbogears 2.1 and trying to display it in a Mako template. Here is my code:
To define the form:
class NewUserForm(AddRecordForm):
__model__ = User
newuserform = NewUserForm(DBSession)
The controller definition that assigns the form and calls the template:
@expose('limelight.modules.users.templates.register')
def register(self, **kw):
tmpl_context.register_form = newuserform
return dict(value=kw)
And the relevant template code:
${tmpl_context.register_form(value=value)}
The problem is the HTML code is displayed as plain text on the page, not rendered HTML.
|
[
"Figured it out. I have to pass the variable through the the 'n' mako filter to remove any automatic filters mako applies to the html generated. So:\n${tmpl_context.register_form(value=value) | n}\n"
] |
[
3
] |
[] |
[] |
[
"forms",
"mako",
"python",
"sprox",
"turbogears"
] |
stackoverflow_0001919833_forms_mako_python_sprox_turbogears.txt
|
Q:
Interactive Python script output stored in some file
How do I perform logging of all activities that are done by a Python script and all scripts that are called from it?
I had several Bash scripts but now wrote a Python script which call all of these Bash scripts. I would like to have all output produced from these scripts stored in some file.
The script is interactive Python script, i.e contains raw_input lines, so I couldn't do like 'python script.py | tee log.txt' for overall the Python script since for some reasons questions are not seen on the screen.
Here is an excerpt from the script which calls one of the shell scripts.
cmd = "somescript.sh"
try:
retvalue = subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError:
print ("script command has been failed")
sys.exit("exit from script")
What do you think could be done here?
Edit
Two subquestions based on Alex's answer:
How to make the answers on the questions stored in the output file as well? For example on line ok = raw_input(prompt) the user will be asked for the question and I would like to the answer logged as well.
I read about Popen and communicate and didn't use since it buffers the data in memory. Here the amount of output is big and I need to care about standard-error with standard-output as well. Do you know if this is possible to handle with Popen and communicate method as well?
A:
Making Python's own prints go to both the terminal and a file is not hard:
>>> import sys
>>> class tee(object):
... def __init__(self, fn='/tmp/foo.txt'):
... self.o = sys.stdout
... self.f = open(fn, 'w')
... def write(self, s):
... self.o.write(s)
... self.f.write(s)
...
>>> sys.stdout = tee()
>>> print('hello world!')
hello world!
>>>
$ cat /tmp/foo.txt
hello world!
This should work both in Python 2 and Python 3.
To similarly direct the output from subcommands, don't use
retvalue = subprocess.check_call(cmd, shell=True)
which lets cmd's output go to its regular "standard output", but rather grab and re-emit it yourself, as follows:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
so, se = p.communicate()
print(so)
retvalue = p.returncode
assuming you don't care about standard-error (only standard-output) and the amount of output from cmd is reasonably small (since .communicate buffers that data in memory) -- it's easy to tweak if either assumption doesn't correspond to what you exactly want.
Edit: the OP has now clarified the specs in a long comment to this answer:
How to make the answers on the
questions stored in the output file
as well? For example on line ok =
raw_input(prompt) the user will be
asked for the question and I would
like to the answer logged as well.
Use a function such as:
def echoed_input(prompt):
response = raw_input(prompt)
sys.stdout.f.write(response)
return response
instead of just raw_input in your application code (of course, this is written specifically to cooperate with the tee class I showed above).
I read about Popen and communicate
and didn't use since it buffers the
data in memory. Here amount of output
is big and I need to care about
standard-error with standard-output
as well. Do you know if this is
possible to handle with Popen and
communicate method as well?
communicate is fine as long as you don't get more output (and standard-error) than comfortably fits in memory, say a few gigabytes at most depending on the kind of machine you're using.
If this hypothesis is met, just recode the above as, instead:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
so, se = p.communicate()
print(so)
retvalue = p.returncode
i.e., just redirect the subcommand's stderr to get mixed into its stdout.
If you DO have to worry about gigabytes (or whatever) coming at you, then
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
for line in p.stdout:
sys.stdout.write(p)
p.wait()
retvalue = p.returncode
(which gets and emits one line at a time) may be preferable (this depends on cmd not expecting anything from its standard input, of course... because, if it is expecting anything, it's not going to get it, and the problem starts to become challenging;-).
A:
Python has a tracing module: trace. Usage: python -m trace --trace file.py
A:
If you want to capture the output of any script, then on a *nix-y system you can redirect stdout and stderr to a file:
./script.py >> /tmp/outputs.txt 2>> /tmp/outputs.txt
If you want everything done by the scripts, not just what they print, then the python trace module won't trace things done by external scripts that your python executes. The only thing that can trace every action done by a program would be something like DTrace, if you are lucky enough to have a system that supports it. (OS X Instruments are based on DTrace)
|
Interactive Python script output stored in some file
|
How do I perform logging of all activities that are done by a Python script and all scripts that are called from it?
I had several Bash scripts but now wrote a Python script which call all of these Bash scripts. I would like to have all output produced from these scripts stored in some file.
The script is interactive Python script, i.e contains raw_input lines, so I couldn't do like 'python script.py | tee log.txt' for overall the Python script since for some reasons questions are not seen on the screen.
Here is an excerpt from the script which calls one of the shell scripts.
cmd = "somescript.sh"
try:
retvalue = subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError:
print ("script command has been failed")
sys.exit("exit from script")
What do you think could be done here?
Edit
Two subquestions based on Alex's answer:
How to make the answers on the questions stored in the output file as well? For example on line ok = raw_input(prompt) the user will be asked for the question and I would like to the answer logged as well.
I read about Popen and communicate and didn't use since it buffers the data in memory. Here the amount of output is big and I need to care about standard-error with standard-output as well. Do you know if this is possible to handle with Popen and communicate method as well?
|
[
"Making Python's own prints go to both the terminal and a file is not hard:\n>>> import sys\n>>> class tee(object):\n... def __init__(self, fn='/tmp/foo.txt'):\n... self.o = sys.stdout\n... self.f = open(fn, 'w')\n... def write(self, s):\n... self.o.write(s)\n... self.f.write(s)\n... \n>>> sys.stdout = tee()\n>>> print('hello world!')\nhello world!\n>>> \n$ cat /tmp/foo.txt\nhello world!\n\nThis should work both in Python 2 and Python 3.\nTo similarly direct the output from subcommands, don't use \nretvalue = subprocess.check_call(cmd, shell=True)\n\nwhich lets cmd's output go to its regular \"standard output\", but rather grab and re-emit it yourself, as follows:\np = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\nso, se = p.communicate()\nprint(so)\nretvalue = p.returncode\n\nassuming you don't care about standard-error (only standard-output) and the amount of output from cmd is reasonably small (since .communicate buffers that data in memory) -- it's easy to tweak if either assumption doesn't correspond to what you exactly want.\nEdit: the OP has now clarified the specs in a long comment to this answer:\n\nHow to make the answers on the\nquestions stored in the output file\nas well? For example on line ok =\nraw_input(prompt) the user will be\nasked for the question and I would\nlike to the answer logged as well.\n\nUse a function such as:\ndef echoed_input(prompt):\n response = raw_input(prompt)\n sys.stdout.f.write(response)\n return response\n\ninstead of just raw_input in your application code (of course, this is written specifically to cooperate with the tee class I showed above).\n\nI read about Popen and communicate\nand didn't use since it buffers the\ndata in memory. Here amount of output\nis big and I need to care about\nstandard-error with standard-output\nas well. Do you know if this is\npossible to handle with Popen and\ncommunicate method as well?\n\ncommunicate is fine as long as you don't get more output (and standard-error) than comfortably fits in memory, say a few gigabytes at most depending on the kind of machine you're using.\nIf this hypothesis is met, just recode the above as, instead:\np = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, \n stderr=subprocess.STDOUT)\nso, se = p.communicate()\nprint(so)\nretvalue = p.returncode\n\ni.e., just redirect the subcommand's stderr to get mixed into its stdout.\nIf you DO have to worry about gigabytes (or whatever) coming at you, then\np = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, \n stderr=subprocess.STDOUT)\nfor line in p.stdout:\n sys.stdout.write(p)\np.wait()\nretvalue = p.returncode\n\n(which gets and emits one line at a time) may be preferable (this depends on cmd not expecting anything from its standard input, of course... because, if it is expecting anything, it's not going to get it, and the problem starts to become challenging;-).\n",
"Python has a tracing module: trace. Usage: python -m trace --trace file.py\n",
"If you want to capture the output of any script, then on a *nix-y system you can redirect stdout and stderr to a file:\n./script.py >> /tmp/outputs.txt 2>> /tmp/outputs.txt\n\nIf you want everything done by the scripts, not just what they print, then the python trace module won't trace things done by external scripts that your python executes. The only thing that can trace every action done by a program would be something like DTrace, if you are lucky enough to have a system that supports it. (OS X Instruments are based on DTrace)\n"
] |
[
7,
1,
1
] |
[] |
[] |
[
"logging",
"python"
] |
stackoverflow_0001936996_logging_python.txt
|
Q:
Why does this code behave differently in Python3.1 than in Python2.6?
I'm very new to programming so I apologize in advance if my question is too silly.
#!/usr/bin/python2.6
import subprocess, time
p=subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for i in 'abcd':
p.stdin.write(str.encode(i+'\n'))
output=p.stdout.readline()
print(output)
time.sleep(1)
Executing this code in Python 2.6 prints letters a, b, c, d , each line of output appears after a second. This is expected behavior.
But in Python 3.1 execution is blocked at line output=p.stdout.readline().
How to correct this for Python 3.1?
A:
Appears to be a difference in buffering. Adding a p.stdin.flush() call solved the problem. (See the comments above).
Community wiki as I deserve no credits for this answer, but some answer needs to be marked accepted.
[@Geo Pop: Please "accept" this question, as it apparently is correct.]
|
Why does this code behave differently in Python3.1 than in Python2.6?
|
I'm very new to programming so I apologize in advance if my question is too silly.
#!/usr/bin/python2.6
import subprocess, time
p=subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for i in 'abcd':
p.stdin.write(str.encode(i+'\n'))
output=p.stdout.readline()
print(output)
time.sleep(1)
Executing this code in Python 2.6 prints letters a, b, c, d , each line of output appears after a second. This is expected behavior.
But in Python 3.1 execution is blocked at line output=p.stdout.readline().
How to correct this for Python 3.1?
|
[
"Appears to be a difference in buffering. Adding a p.stdin.flush() call solved the problem. (See the comments above).\nCommunity wiki as I deserve no credits for this answer, but some answer needs to be marked accepted.\n[@Geo Pop: Please \"accept\" this question, as it apparently is correct.]\n"
] |
[
3
] |
[] |
[] |
[
"popen",
"python",
"stdin",
"stdout",
"subprocess"
] |
stackoverflow_0001936725_popen_python_stdin_stdout_subprocess.txt
|
Q:
Python Service File Caching Apache Race Condition
I am writing a python service (pyamf) through which a user can access images. All images are stored on a central server. The python services will be running on satellite machines which have network access to server. The service should work as follows:
check locally to see if the file exists, if so, use it.
check locally to see if file is currently being transferred from server ( file.part exists and size is changing ). If so, wait for download to finish, then use file.
if file does not exist and file is not being downloaded, download the file via urlretrieve.
The problem is with Apache's multiple threads. Threads are reaching the file presence check at the same time and therefore they all think the file needs to be downloaded. Needless to say, this is not good.
What is the right way to handle this race condition?
Thanks!
A:
I'm guessing its either a threaded or a forked apache, but the effect would be the same since they are accessing a remote resource.
This problem is sometimes called the "dog pile" problem and its one of the issues addressed by the Beaker caching library (http://beaker.groovie.org). It provides a system bywhich you can create a callable that "creates" a new cached value, in this case a URL corresponding to some image that is fetched, if a value doesn't already exist. Locking is used such that concurrent threads or processes wait for the single process elected as the "creator" to finish what its doing. Beaker will use lockfiles if configured on a unix-like multi-process oriented system or mutexes if on a windows system.
I'm the original author of Beaker's guts along with Ben Bangert who packaged it up for usage with Pylons.
|
Python Service File Caching Apache Race Condition
|
I am writing a python service (pyamf) through which a user can access images. All images are stored on a central server. The python services will be running on satellite machines which have network access to server. The service should work as follows:
check locally to see if the file exists, if so, use it.
check locally to see if file is currently being transferred from server ( file.part exists and size is changing ). If so, wait for download to finish, then use file.
if file does not exist and file is not being downloaded, download the file via urlretrieve.
The problem is with Apache's multiple threads. Threads are reaching the file presence check at the same time and therefore they all think the file needs to be downloaded. Needless to say, this is not good.
What is the right way to handle this race condition?
Thanks!
|
[
"I'm guessing its either a threaded or a forked apache, but the effect would be the same since they are accessing a remote resource.\nThis problem is sometimes called the \"dog pile\" problem and its one of the issues addressed by the Beaker caching library (http://beaker.groovie.org). It provides a system bywhich you can create a callable that \"creates\" a new cached value, in this case a URL corresponding to some image that is fetched, if a value doesn't already exist. Locking is used such that concurrent threads or processes wait for the single process elected as the \"creator\" to finish what its doing. Beaker will use lockfiles if configured on a unix-like multi-process oriented system or mutexes if on a windows system.\nI'm the original author of Beaker's guts along with Ben Bangert who packaged it up for usage with Pylons. \n"
] |
[
1
] |
[] |
[] |
[
"apache",
"python",
"race_condition",
"service"
] |
stackoverflow_0001937018_apache_python_race_condition_service.txt
|
Q:
Word game server in Python, design pros and cons?
I'd like to get busy with a winter programming project and am contemplating writing an online word game (with a server load of up to, say, 500 users simultaneously). I would prefer it to be platform independent. I intend to use Python, which I have some experience with. For user data storage, after previous experience with MySQL, a flat database design would be preferable but not essential. Okay, now the questions:
Is it worth starting with Python 3, or is it still too poorly supported with ports of modules from previous versions?
Are there any great advantages in using Python 3 for my particular project? Would I be better off looking at using other languages instead, such as Erlang?
Is there any great advantage in using a relational database within a game server?
Are there any open source game servers' source code out there that are worthy of study before starting?
A:
I would go for Python + Django. It makes web application developments pretty easy.
A:
Is it worth starting with Python 3, or is it still too poorly supported with ports of modules from previous versions?
depends on which modules do you want to use. twisted is a "swiss knife" for the network programming and could be a choice for your project but unfortunately it does not support python3 yet.
Are there any great advantages in using Python 3 for my particular project? Would I be better off looking at using other languages instead, such as Erlang?
only you can answer your question because only you know your knowledge. Using python3 instead of python2 you get all the advantages of new features the python3 brings with him and the disadvantage that non all libraries support python3 at the moment.
note that python2.6 should implements most (if not all) of the features of python3 while it should be compatible with python2.5 but i did not investigated a lot in this way.
both python and erlang are candidates for your needs, use what you know best and what you like most.
Is there any great advantage in using a relational database within a game server?
you get all the advantages and disadvantage of having a ACID storage system.
A:
Related to your database choice, I'd seriously look at using Postgres instead of MySQL. In my experiance with the two Postgres has shown to be faster on most write operations while MySQL is slightly faster on the reads.
However, MySQL also has many issues some of which are:
Live backups are difficult at best, and impossible at worse, mostly you have to take the db offline or let it lock during the backups.
In the event of having to kill the server forcefully, either by kill -9, or due to power outage, postgres generally has better resilience to table corruption.
Full support for ACID compliance, and other relational db features that support for, again imho and experiance, are weak or lacking in MySQL.
You can use a library such as SQLAlchemy to abstract away the db access though. This would let you test against both to see which you prefer dealing with.
As far as the language choice.
If you go with Python:
More librarys support Python 2.x rather than Python 3.x at this time, so I'd likely stick to 2.x.
Beware multi-threading gotchas with Python's GIL. Utilizing Twisted can get around this.
If you go with Erlang:
Erlang's syntax and idioms can be very foreign to someone who's never used it.
If well written it not only scales, it SCALES.
Erlang has it's own highly concurrent web server named Yaws.
Erlang also has it's own highly scalable DBMS named Mnesia (Note it's not relational).
So I guess your choices could be really boiled down to how much you're willing to learn to do this project.
A:
A project of this kind could be a great way of investigating a new language. I'd say that Erlang is one of the more interesting languages out there, (1) being functional, (2) offering a superb concurrency / (distributed) parallelism paradigm, (2) seeing use in the industry (most notably & traditionally telecommunications), (3) actually entering the desktop space (CouchDB). If you don't know it yet, go for it! :-)
As for open source game servers... Well, there's plenty. Google around for MUD engines etc. For starters, check out the Wikipedia entry on MOOs and look at LambdaMOO.
A:
If you're already fairly familiar with Python, then I'd investigate the Twisted library if I were you. Twisted is an asynchronous comms library that was originally developed to support a large text-based game.
The current level of support for Python 3 by commonly used libraries is not high - so you probably want to stick with something like Python 2.6 at this point in time.
|
Word game server in Python, design pros and cons?
|
I'd like to get busy with a winter programming project and am contemplating writing an online word game (with a server load of up to, say, 500 users simultaneously). I would prefer it to be platform independent. I intend to use Python, which I have some experience with. For user data storage, after previous experience with MySQL, a flat database design would be preferable but not essential. Okay, now the questions:
Is it worth starting with Python 3, or is it still too poorly supported with ports of modules from previous versions?
Are there any great advantages in using Python 3 for my particular project? Would I be better off looking at using other languages instead, such as Erlang?
Is there any great advantage in using a relational database within a game server?
Are there any open source game servers' source code out there that are worthy of study before starting?
|
[
"I would go for Python + Django. It makes web application developments pretty easy.\n",
"\nIs it worth starting with Python 3, or is it still too poorly supported with ports of modules from previous versions?\n\ndepends on which modules do you want to use. twisted is a \"swiss knife\" for the network programming and could be a choice for your project but unfortunately it does not support python3 yet.\n\nAre there any great advantages in using Python 3 for my particular project? Would I be better off looking at using other languages instead, such as Erlang?\n\nonly you can answer your question because only you know your knowledge. Using python3 instead of python2 you get all the advantages of new features the python3 brings with him and the disadvantage that non all libraries support python3 at the moment.\nnote that python2.6 should implements most (if not all) of the features of python3 while it should be compatible with python2.5 but i did not investigated a lot in this way.\nboth python and erlang are candidates for your needs, use what you know best and what you like most.\n\nIs there any great advantage in using a relational database within a game server?\n\nyou get all the advantages and disadvantage of having a ACID storage system.\n",
"Related to your database choice, I'd seriously look at using Postgres instead of MySQL. In my experiance with the two Postgres has shown to be faster on most write operations while MySQL is slightly faster on the reads. \nHowever, MySQL also has many issues some of which are:\n\nLive backups are difficult at best, and impossible at worse, mostly you have to take the db offline or let it lock during the backups.\nIn the event of having to kill the server forcefully, either by kill -9, or due to power outage, postgres generally has better resilience to table corruption. \nFull support for ACID compliance, and other relational db features that support for, again imho and experiance, are weak or lacking in MySQL.\n\nYou can use a library such as SQLAlchemy to abstract away the db access though. This would let you test against both to see which you prefer dealing with.\nAs far as the language choice. \nIf you go with Python:\n\nMore librarys support Python 2.x rather than Python 3.x at this time, so I'd likely stick to 2.x. \nBeware multi-threading gotchas with Python's GIL. Utilizing Twisted can get around this. \n\nIf you go with Erlang:\n\nErlang's syntax and idioms can be very foreign to someone who's never used it.\nIf well written it not only scales, it SCALES. \nErlang has it's own highly concurrent web server named Yaws.\nErlang also has it's own highly scalable DBMS named Mnesia (Note it's not relational).\n\nSo I guess your choices could be really boiled down to how much you're willing to learn to do this project. \n",
"A project of this kind could be a great way of investigating a new language. I'd say that Erlang is one of the more interesting languages out there, (1) being functional, (2) offering a superb concurrency / (distributed) parallelism paradigm, (2) seeing use in the industry (most notably & traditionally telecommunications), (3) actually entering the desktop space (CouchDB). If you don't know it yet, go for it! :-)\nAs for open source game servers... Well, there's plenty. Google around for MUD engines etc. For starters, check out the Wikipedia entry on MOOs and look at LambdaMOO.\n",
"If you're already fairly familiar with Python, then I'd investigate the Twisted library if I were you. Twisted is an asynchronous comms library that was originally developed to support a large text-based game.\nThe current level of support for Python 3 by commonly used libraries is not high - so you probably want to stick with something like Python 2.6 at this point in time.\n"
] |
[
2,
2,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001937286_python.txt
|
Q:
Is there a better way to serve the results of an expensive, blocking python process over HTTP?
We have a web service which serves small, arbitrary segments of a fixed inventory of larger MP3 files. The MP3 files are generated on-the-fly by a python application. The model is, make a GET request to a URL specifying which segments you want, get an audio/mpeg stream in response. This is an expensive process.
We're using Nginx as the front-end request handler. Nginx takes care of caching responses for common requests.
We initially tried using Tornado on the back-end to handle requests from Nginx. As you would expect, the blocking MP3 operation kept Tornado from doing its thing (asynchronous I/O). So, we went multithreaded, which solved the blocking problem, and performed quite well. However, it introduced a subtle race condition (under real world load) that we haven't been able to diagnose or reproduce yet. The race condition corrupts our MP3 output.
So we decided to set our application up as a simple WSGI handler behind Apache/mod_wsgi (still w/ Nginx up front). This eliminates the blocking issue and the race condition, but creates a cascading load (i.e. Apache creates too many processses) on the server under real world conditions. We're working on tuning Apache/mod_wsgi right now, but still at a trial-and-error phase. (Update: we've switched back to Tornado. See below.)
Finally, the question: are we missing anything? Is there a better way to serve CPU-expensive resources over HTTP?
Update: Thanks to Graham's informed article, I'm pretty sure this is an Apache tuning problem. In the mean-time, we've gone back to using Tornado and are trying to resolve the data-corruption issue.
For those who were so quick to throw more iron at the problem, Tornado and a bit of multi-threading (despite the data integrity problem introduced by threading) handles the load acceptably on a small (single core) Amazon EC2 instance.
A:
Have you tried Spawning? It is a WSGI server with a flexible assortment of threading modes.
A:
You might consider a queuing system with AJAX notification methods.
Whenever there is a request for your expensive resource, and that resource needs to be generated, add that request to the queue (if it's not already there). That queuing operation should return an ID of an object that you can query to get its status.
Next you have to write a background service that spins up worker threads. These workers simply dequeue the request, generate the data, then saves the data's location in the request object.
The webpage can make AJAX calls to your server to find out the progress of the generation and to give a link to the file once it's available.
This is how LARGE media sites work - those that have to deal with video in particular. It might be overkill for your MP3 work however.
Alternatively, look into running a couple machines to distribute the load. Your threads on Apache will still block, but atleast you won't consume resources on the web server.
A:
Are you making the mistake of using embedded mode of Apache/mod_wsgi? Read:
http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html
Ensure you use daemon mode if using Apache/mod_wsgi.
A:
Please define "cascading load", as it has no common meaning.
Your most likely problem is going to be if you're running too many Apache processes.
For a load like this, make sure you're using the prefork mpm, and make sure you're limiting yourself to an appropriate number of processes (no less than one per CPU, no more than two).
A:
It looks like you are doing things right -- just lacking CPU power: can you determine what is the CPU loading in the process of generating these MP3?
I think the next thing you have to do there is to add more hardware to render the MP3's on other machines. Or that or find a way to deliver pre-rendered MP3 (maybe you can cahce some of your media?)
BTW, scaling for the web was the theme of a Keynote lecture by Jacob Kaplan-Moss on PyCon Brasil this year, and it is far from being a closed problem. The stack of technologies one needs to handle is quite impressible - (I could not find an online copy o f the presentation, though - -sorry for that)
|
Is there a better way to serve the results of an expensive, blocking python process over HTTP?
|
We have a web service which serves small, arbitrary segments of a fixed inventory of larger MP3 files. The MP3 files are generated on-the-fly by a python application. The model is, make a GET request to a URL specifying which segments you want, get an audio/mpeg stream in response. This is an expensive process.
We're using Nginx as the front-end request handler. Nginx takes care of caching responses for common requests.
We initially tried using Tornado on the back-end to handle requests from Nginx. As you would expect, the blocking MP3 operation kept Tornado from doing its thing (asynchronous I/O). So, we went multithreaded, which solved the blocking problem, and performed quite well. However, it introduced a subtle race condition (under real world load) that we haven't been able to diagnose or reproduce yet. The race condition corrupts our MP3 output.
So we decided to set our application up as a simple WSGI handler behind Apache/mod_wsgi (still w/ Nginx up front). This eliminates the blocking issue and the race condition, but creates a cascading load (i.e. Apache creates too many processses) on the server under real world conditions. We're working on tuning Apache/mod_wsgi right now, but still at a trial-and-error phase. (Update: we've switched back to Tornado. See below.)
Finally, the question: are we missing anything? Is there a better way to serve CPU-expensive resources over HTTP?
Update: Thanks to Graham's informed article, I'm pretty sure this is an Apache tuning problem. In the mean-time, we've gone back to using Tornado and are trying to resolve the data-corruption issue.
For those who were so quick to throw more iron at the problem, Tornado and a bit of multi-threading (despite the data integrity problem introduced by threading) handles the load acceptably on a small (single core) Amazon EC2 instance.
|
[
"Have you tried Spawning? It is a WSGI server with a flexible assortment of threading modes.\n",
"You might consider a queuing system with AJAX notification methods.\nWhenever there is a request for your expensive resource, and that resource needs to be generated, add that request to the queue (if it's not already there). That queuing operation should return an ID of an object that you can query to get its status.\nNext you have to write a background service that spins up worker threads. These workers simply dequeue the request, generate the data, then saves the data's location in the request object.\nThe webpage can make AJAX calls to your server to find out the progress of the generation and to give a link to the file once it's available.\nThis is how LARGE media sites work - those that have to deal with video in particular. It might be overkill for your MP3 work however.\nAlternatively, look into running a couple machines to distribute the load. Your threads on Apache will still block, but atleast you won't consume resources on the web server.\n",
"Are you making the mistake of using embedded mode of Apache/mod_wsgi? Read:\nhttp://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html\nEnsure you use daemon mode if using Apache/mod_wsgi.\n",
"Please define \"cascading load\", as it has no common meaning.\nYour most likely problem is going to be if you're running too many Apache processes.\nFor a load like this, make sure you're using the prefork mpm, and make sure you're limiting yourself to an appropriate number of processes (no less than one per CPU, no more than two).\n",
"It looks like you are doing things right -- just lacking CPU power: can you determine what is the CPU loading in the process of generating these MP3?\nI think the next thing you have to do there is to add more hardware to render the MP3's on other machines. Or that or find a way to deliver pre-rendered MP3 (maybe you can cahce some of your media?)\nBTW, scaling for the web was the theme of a Keynote lecture by Jacob Kaplan-Moss on PyCon Brasil this year, and it is far from being a closed problem. The stack of technologies one needs to handle is quite impressible - (I could not find an online copy o f the presentation, though - -sorry for that)\n"
] |
[
2,
1,
1,
1,
0
] |
[] |
[] |
[
"http",
"mod_wsgi",
"python",
"tornado"
] |
stackoverflow_0001929681_http_mod_wsgi_python_tornado.txt
|
Q:
How does one add default (hidden) values to form templates in Django?
Given a Django.db models class:
class P(models.Model):
type = models.ForeignKey(Type) # Type is another models.Model class
name = models.CharField()
where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso:
http://x.y/P/new?type=3
So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)).
Secondarily, how does one (& is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz.
urlpatterns = ('django.generic.views.create_update',
url(r'^/new$', 'create_object', { 'model': P }, name='new_P'),
)
I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!
A:
The widget django.forms.widgets.HiddenInput will render your field as hidden.
In most cases, I think you'll find that any hidden form value could also be specified as a url parameter instead. In other words:
<form action="new/{{your_hidden_value}}" method="post">
....
</form>
and in urls.py:
^/new/(?P<hidden_value>\w+)/
I prefer this technique myself because I only really find myself needing hidden form fields when I need to track the primary key of a model instance - in which case an "edit/pkey" url serves the purposes of both initiating the edit/returning the form, and receiving the POST on save.
A:
To have a default Foreign Key in a model:
mydefault = Type.objects.get(pk=3)
class P(models.Model):
type = models.ForeignKey(Type, default=mydefault) # Type is another models.Model class
name = models.CharField()
Note that using pk=x is pretty ugly, as ideally you shouldn't care what the primary key is equal to. Try to get to the object you want by some other attribute.
Here's how you put defaults in your urls:
# URLconf
urlpatterns = patterns('',
(r'^blog/$', 'blog.views.page'),
(r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
)
# View (in blog/views.py)
def page(request, num="1"):
# Output the appropriate page of blog entries, according to num.
In the above example, both URL patterns point to the same view -- blog.views.page -- but the first pattern doesn't capture anything from the URL. If the first pattern matches, the page() function will use its default argument for num, "1". If the second pattern matches, page() will use whatever num value was captured by the regex.
A:
If you go with Andrew's approach of including the hidden value in the url and still want to use one of Django's built in form templates, there are ways for you to exclude the hidden field.
http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form
|
How does one add default (hidden) values to form templates in Django?
|
Given a Django.db models class:
class P(models.Model):
type = models.ForeignKey(Type) # Type is another models.Model class
name = models.CharField()
where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso:
http://x.y/P/new?type=3
So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)).
Secondarily, how does one (& is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz.
urlpatterns = ('django.generic.views.create_update',
url(r'^/new$', 'create_object', { 'model': P }, name='new_P'),
)
I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!
|
[
"The widget django.forms.widgets.HiddenInput will render your field as hidden.\nIn most cases, I think you'll find that any hidden form value could also be specified as a url parameter instead. In other words:\n<form action=\"new/{{your_hidden_value}}\" method=\"post\">\n....\n</form>\n\nand in urls.py:\n^/new/(?P<hidden_value>\\w+)/\n\nI prefer this technique myself because I only really find myself needing hidden form fields when I need to track the primary key of a model instance - in which case an \"edit/pkey\" url serves the purposes of both initiating the edit/returning the form, and receiving the POST on save.\n",
"To have a default Foreign Key in a model:\nmydefault = Type.objects.get(pk=3)\n\nclass P(models.Model):\n type = models.ForeignKey(Type, default=mydefault) # Type is another models.Model class\n name = models.CharField()\n\nNote that using pk=x is pretty ugly, as ideally you shouldn't care what the primary key is equal to. Try to get to the object you want by some other attribute.\nHere's how you put defaults in your urls:\n# URLconf\nurlpatterns = patterns('',\n (r'^blog/$', 'blog.views.page'),\n (r'^blog/page(?P<num>\\d+)/$', 'blog.views.page'),\n)\n\n# View (in blog/views.py)\ndef page(request, num=\"1\"):\n # Output the appropriate page of blog entries, according to num.\n\n\nIn the above example, both URL patterns point to the same view -- blog.views.page -- but the first pattern doesn't capture anything from the URL. If the first pattern matches, the page() function will use its default argument for num, \"1\". If the second pattern matches, page() will use whatever num value was captured by the regex.\n\n",
"If you go with Andrew's approach of including the hidden value in the url and still want to use one of Django's built in form templates, there are ways for you to exclude the hidden field.\nhttp://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form\n"
] |
[
8,
5,
2
] |
[] |
[] |
[
"django",
"django_templates",
"django_urls",
"python"
] |
stackoverflow_0000271244_django_django_templates_django_urls_python.txt
|
Q:
Importing Excel sheets, including formulae, into Django
I have an Excel spreadsheet with calculations I would like to use in a Django web application. I do not need to present the spreadsheet as it appears in Excel. I only want to use the formulae embedded in it. What is the best way to do this?
A:
You can control Excel with Python via COM. See this thread: Driving Excel from Python in Windows
It might be a challenge to get this to work reliably as part of a Django app.
A:
In addition to the COM solution, xlrd is cross-platform. That might be more suitable, since I believe Linux is still the most common deployment environment for django. It's also a lighter-weight solution than pyUno.
A:
I think the only thing you can do is use some python/excel mechanism (the only one I could find was this: http://www.python-excel.org/; the tutorial makes me think it might be doable) to read and write from an excel spreadsheet.
You would write to certain cells that would be used by the spreadsheet formulas and then read the results from the formulas from other cells.
Django per-se has nothing to help you with this.
I'll retag your question to include python so that, maybe, someone with Python-excel experience can comment...
A:
You need to use Excel to calculate the results? I mean, maybe you could run the Excel sheet from OpenOffice and use a pyUNO macro, which is somehow "native" python.
A different approach will be to create a macro to generate some more friendly code to python, if you want Excel to perform the calculation is easy you end up with a very slow process.
|
Importing Excel sheets, including formulae, into Django
|
I have an Excel spreadsheet with calculations I would like to use in a Django web application. I do not need to present the spreadsheet as it appears in Excel. I only want to use the formulae embedded in it. What is the best way to do this?
|
[
"You can control Excel with Python via COM. See this thread: Driving Excel from Python in Windows\nIt might be a challenge to get this to work reliably as part of a Django app.\n",
"In addition to the COM solution, xlrd is cross-platform. That might be more suitable, since I believe Linux is still the most common deployment environment for django. It's also a lighter-weight solution than pyUno.\n",
"I think the only thing you can do is use some python/excel mechanism (the only one I could find was this: http://www.python-excel.org/; the tutorial makes me think it might be doable) to read and write from an excel spreadsheet.\nYou would write to certain cells that would be used by the spreadsheet formulas and then read the results from the formulas from other cells.\nDjango per-se has nothing to help you with this.\nI'll retag your question to include python so that, maybe, someone with Python-excel experience can comment...\n",
"You need to use Excel to calculate the results? I mean, maybe you could run the Excel sheet from OpenOffice and use a pyUNO macro, which is somehow \"native\" python. \nA different approach will be to create a macro to generate some more friendly code to python, if you want Excel to perform the calculation is easy you end up with a very slow process. \n"
] |
[
4,
1,
0,
0
] |
[] |
[] |
[
"django",
"excel",
"python"
] |
stackoverflow_0001883098_django_excel_python.txt
|
Q:
How to iterate over a string using a buffer (python)
I'm trying to find some code that, given a string, will allow me to iterate over each line using the for loop construct, but with the added requirement that separate for loop constructs will not reset the iteration back to the beginning.
At the moment I have
sList = [line for line in theString.split(os.linesep)]
for line in SList
... do stuff
But successive for loops will reset the iteration back to the beginning.
Does something in python exist for this, or will I have to write one from scratch?
A:
Just use a generator expression (genexp) instead of the list comprehension (listcomp) you're now using - i.e.:
sList = (line for line in theString.split(os.linesep))
that's all -- if you're otherwise happy with your code (splitting by os.linesep, even though normal text I/O in Python will already have translated those into \n...), all you need to do is to use parentheses (the round kind) instead of brackets (the square kind), and you'll get a generator instead of a list.
Now, each time you do a for line in sList:, it will start again from where the previous one had stopped (presumably because of a break) -- that's what you're asking for, right?
A:
Use another iterator:
aList = range(10)
anIterator = iter(aList)
for item in anIterator:
print item
if item > 4: break
for item in anIterator:
print item
A:
Try using a combination of slices and enumerate():
sList = theString.split(os.linesep)
for i, line in enumerate(sList):
if foo:
break
for j, line in enumerate(sList[i:]):
# do more stuff
A:
Hack at an iterator?
def iterOverList(someList):
for i in someList:
# Do some stuff
yield
Then just call iterOverList() within a loop a few times, it'll retain state?
|
How to iterate over a string using a buffer (python)
|
I'm trying to find some code that, given a string, will allow me to iterate over each line using the for loop construct, but with the added requirement that separate for loop constructs will not reset the iteration back to the beginning.
At the moment I have
sList = [line for line in theString.split(os.linesep)]
for line in SList
... do stuff
But successive for loops will reset the iteration back to the beginning.
Does something in python exist for this, or will I have to write one from scratch?
|
[
"Just use a generator expression (genexp) instead of the list comprehension (listcomp) you're now using - i.e.:\nsList = (line for line in theString.split(os.linesep))\n\nthat's all -- if you're otherwise happy with your code (splitting by os.linesep, even though normal text I/O in Python will already have translated those into \\n...), all you need to do is to use parentheses (the round kind) instead of brackets (the square kind), and you'll get a generator instead of a list.\nNow, each time you do a for line in sList:, it will start again from where the previous one had stopped (presumably because of a break) -- that's what you're asking for, right?\n",
"Use another iterator:\naList = range(10)\nanIterator = iter(aList)\n\nfor item in anIterator:\n print item\n if item > 4: break\n\nfor item in anIterator:\n print item\n\n",
"Try using a combination of slices and enumerate(): \nsList = theString.split(os.linesep)\nfor i, line in enumerate(sList):\n if foo: \n break\n\nfor j, line in enumerate(sList[i:]):\n # do more stuff\n\n",
"Hack at an iterator?\ndef iterOverList(someList):\n for i in someList:\n # Do some stuff\n yield\n\nThen just call iterOverList() within a loop a few times, it'll retain state?\n"
] |
[
13,
2,
0,
0
] |
[] |
[] |
[
"buffer",
"iteration",
"python",
"string"
] |
stackoverflow_0001937519_buffer_iteration_python_string.txt
|
Q:
Regular Expression to split on specific character ONLY if that character is not in a pair
After finding the fastest string replace algorithm in this thread, I've been trying to modify one of them to suit my needs, particularly this one by gnibbler.
I will explain the problem again here, and what issue I am having.
Say I have a string that looks like this:
str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"
You'll notice a lot of locations in the string where there is an ampersand, followed by a character (such as "&y" and "&c"). I need to replace these characters with an appropriate value that I have in a dictionary, like so:
dict = {"y":"\033[0;30m",
"c":"\033[0;31m",
"b":"\033[0;32m",
"Y":"\033[0;33m",
"u":"\033[0;34m"}
Using gnibblers solution provided in my previous thread, I have this as my current solution:
myparts = tmp.split('&')
myparts[1:]=[dict.get(x[0],"&"+x[0])+x[1:] for x in myparts[1:]]
result = "".join(myparts)
This works for replacing the characters properly, and does not fail on characters that are not found. The only problem with this is that there is no simple way to actually keep an ampersand in the output. The easiest way I could think of would be to change my dictionary to contain:
dict = {"y":"\033[0;30m",
"c":"\033[0;31m",
"b":"\033[0;32m",
"Y":"\033[0;33m",
"u":"\033[0;34m",
"&":"&"}
And change my "split" call to do a regex split on ampersands that are NOT followed by other ampersands.
>>> import re
>>> tmp = "&yI &creally &blove A && W &uRootbeer."
>>> tmp.split('&')
['', 'yI ', 'creally ', 'blove A ', '', ' W ', 'uRootbeer.']
>>> re.split('MyRegex', tmp)
['', 'yI ', 'creally ', 'blove A ', '&W ', 'uRootbeer.']
Basically, I need a Regex that will split on the first ampersand of a pair, and every single ampersand, to allow me to escape it via my dictionary.
If anyone has any better solutions please feel free to let me know.
A:
You could use a negative lookbehind (assuming the regex engine in question supports it) to only match ampersands that do not follow another ampersand.
/(?<!&)&/
A:
Maybe loop while (q = str.find('&', p)) != -1, then append the left side (p + 2 to q - 1) and the replacement value.
A:
I think this does the trick:
import re
def fix(text):
dict = {"y":"\033[0;30m",
"c":"\033[0;31m",
"b":"\033[0;32m",
"Y":"\033[0;33m",
"u":"\033[0;34m",
"&":"&"}
myparts = re.split('\&(\&*)', text)
myparts[1:]=[dict.get(x[0],"&"+x[0])+x[1:] if len(x) > 0 else x for x in myparts[1:]]
result = "".join(myparts)
return result
print fix("The &yquick &cbrown &bfox &Yjumps over the &ulazy dog")
print fix("&yI &creally &blove A && W &uRootbeer.")
A:
re.sub will do what you want. It takes a regex pattern and can take a function to process the match and return the replacement. Below if the character following the & is not in the dictionary, no replacement is made. && is replaced with & to allow escaping an & that is followed by a character in the dictionary.
Also 'str' and 'dict' are bad variables names because they shadow the built-in functions of the same name.
In 's' below, '& cat' will not be affected and '&&cat' will become "&cat" suppressing &c translation.
import re
s = "The &yquick &cbrown &bfox & cat &&cat &Yjumps over the &ulazy dog"
D = {"y":"\033[0;30m",
"c":"\033[0;31m",
"b":"\033[0;32m",
"Y":"\033[0;33m",
"u":"\033[0;34m",
"&":"&"}
def func(m):
return D.get(m.group(1),m.group(0))
print repr(re.sub(r'&(.)',func,s))
OUTPUT:
'The \x1b[0;30mquick \x1b[0;31mbrown \x1b[0;32mfox & cat &cat \x1b[0;33mjumps over the \x1b[0;34mlazy dog'
-Mark
|
Regular Expression to split on specific character ONLY if that character is not in a pair
|
After finding the fastest string replace algorithm in this thread, I've been trying to modify one of them to suit my needs, particularly this one by gnibbler.
I will explain the problem again here, and what issue I am having.
Say I have a string that looks like this:
str = "The &yquick &cbrown &bfox &Yjumps over the &ulazy dog"
You'll notice a lot of locations in the string where there is an ampersand, followed by a character (such as "&y" and "&c"). I need to replace these characters with an appropriate value that I have in a dictionary, like so:
dict = {"y":"\033[0;30m",
"c":"\033[0;31m",
"b":"\033[0;32m",
"Y":"\033[0;33m",
"u":"\033[0;34m"}
Using gnibblers solution provided in my previous thread, I have this as my current solution:
myparts = tmp.split('&')
myparts[1:]=[dict.get(x[0],"&"+x[0])+x[1:] for x in myparts[1:]]
result = "".join(myparts)
This works for replacing the characters properly, and does not fail on characters that are not found. The only problem with this is that there is no simple way to actually keep an ampersand in the output. The easiest way I could think of would be to change my dictionary to contain:
dict = {"y":"\033[0;30m",
"c":"\033[0;31m",
"b":"\033[0;32m",
"Y":"\033[0;33m",
"u":"\033[0;34m",
"&":"&"}
And change my "split" call to do a regex split on ampersands that are NOT followed by other ampersands.
>>> import re
>>> tmp = "&yI &creally &blove A && W &uRootbeer."
>>> tmp.split('&')
['', 'yI ', 'creally ', 'blove A ', '', ' W ', 'uRootbeer.']
>>> re.split('MyRegex', tmp)
['', 'yI ', 'creally ', 'blove A ', '&W ', 'uRootbeer.']
Basically, I need a Regex that will split on the first ampersand of a pair, and every single ampersand, to allow me to escape it via my dictionary.
If anyone has any better solutions please feel free to let me know.
|
[
"You could use a negative lookbehind (assuming the regex engine in question supports it) to only match ampersands that do not follow another ampersand.\n/(?<!&)&/\n\n",
"Maybe loop while (q = str.find('&', p)) != -1, then append the left side (p + 2 to q - 1) and the replacement value.\n",
"I think this does the trick:\nimport re\n\ndef fix(text):\n dict = {\"y\":\"\\033[0;30m\",\n \"c\":\"\\033[0;31m\",\n \"b\":\"\\033[0;32m\",\n \"Y\":\"\\033[0;33m\",\n \"u\":\"\\033[0;34m\",\n \"&\":\"&\"}\n\n myparts = re.split('\\&(\\&*)', text)\n myparts[1:]=[dict.get(x[0],\"&\"+x[0])+x[1:] if len(x) > 0 else x for x in myparts[1:]]\n result = \"\".join(myparts)\n return result\n\n\nprint fix(\"The &yquick &cbrown &bfox &Yjumps over the &ulazy dog\")\nprint fix(\"&yI &creally &blove A && W &uRootbeer.\")\n\n",
"re.sub will do what you want. It takes a regex pattern and can take a function to process the match and return the replacement. Below if the character following the & is not in the dictionary, no replacement is made. && is replaced with & to allow escaping an & that is followed by a character in the dictionary.\nAlso 'str' and 'dict' are bad variables names because they shadow the built-in functions of the same name.\nIn 's' below, '& cat' will not be affected and '&&cat' will become \"&cat\" suppressing &c translation.\nimport re\n\ns = \"The &yquick &cbrown &bfox & cat &&cat &Yjumps over the &ulazy dog\"\n\nD = {\"y\":\"\\033[0;30m\",\n \"c\":\"\\033[0;31m\",\n \"b\":\"\\033[0;32m\",\n \"Y\":\"\\033[0;33m\",\n \"u\":\"\\033[0;34m\",\n \"&\":\"&\"}\n\ndef func(m):\n return D.get(m.group(1),m.group(0))\n\nprint repr(re.sub(r'&(.)',func,s))\n\nOUTPUT:\n'The \\x1b[0;30mquick \\x1b[0;31mbrown \\x1b[0;32mfox & cat &cat \\x1b[0;33mjumps over the \\x1b[0;34mlazy dog'\n\n-Mark\n"
] |
[
2,
0,
0,
0
] |
[] |
[] |
[
"python",
"regex",
"replace",
"string"
] |
stackoverflow_0001936837_python_regex_replace_string.txt
|
Q:
PyQt 4 UI freezes
The following programm should just count up and int and displays its value in a label.
But after a while the GUI stops working, while the loop continous.
from PyQt4 import QtGui,QtCore
import sys
class main_window(QtGui.QWidget):
def __init__(self,parent=None):
#Layout
QtGui.QWidget.__init__(self,parent)
self.bt=QtGui.QPushButton('crash')
self.lbl=QtGui.QLabel('count')
ver=QtGui.QHBoxLayout(self)
ver.addWidget(self.bt)
ver.addWidget(self.lbl)
self.cnt=0
self.running=False
self.connect(self.bt,QtCore.SIGNAL("clicked()"),self.count)
def count(self):
self.running=True
while self.running:
self.cnt+=1
print self.cnt
self.lbl.setText(str(self.cnt))
self.repaint()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mw=main_window()
mw.show()
sys.exit(app.exec_())
Any help?
A:
You're not letting Qt's event loop run, so the GUI is not responding. Also, repaint() is not needed, the QLabel.setText() will repaint the label. All it does is queue up an extra paint event, but this never gets processed.
What you need to do is replace self.repaint() with QtGui.QApplication.processEvents(). This will give the app a chance to process any pending events (including that repaint, as well as ui interaction) while you're in the loop.
A:
def count(self):
self.running=True
while self.running:
self.cnt+=1
print self.cnt
self.lbl.setText(str(self.cnt))
self.repaint()
Have you thought about any exit from this endless loop? E.g. self.running=False.
GUI may stop working because it doesn't have enough time to perform repaint. You may want to add some time.sleep in the loop to wait for the GUI to repaint.
Upd.: You should use QTimer, not a simple while loop, for the behavior you're implementing.
A:
You have to let the main event loop run, something you're not doing.
|
PyQt 4 UI freezes
|
The following programm should just count up and int and displays its value in a label.
But after a while the GUI stops working, while the loop continous.
from PyQt4 import QtGui,QtCore
import sys
class main_window(QtGui.QWidget):
def __init__(self,parent=None):
#Layout
QtGui.QWidget.__init__(self,parent)
self.bt=QtGui.QPushButton('crash')
self.lbl=QtGui.QLabel('count')
ver=QtGui.QHBoxLayout(self)
ver.addWidget(self.bt)
ver.addWidget(self.lbl)
self.cnt=0
self.running=False
self.connect(self.bt,QtCore.SIGNAL("clicked()"),self.count)
def count(self):
self.running=True
while self.running:
self.cnt+=1
print self.cnt
self.lbl.setText(str(self.cnt))
self.repaint()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mw=main_window()
mw.show()
sys.exit(app.exec_())
Any help?
|
[
"You're not letting Qt's event loop run, so the GUI is not responding. Also, repaint() is not needed, the QLabel.setText() will repaint the label. All it does is queue up an extra paint event, but this never gets processed. \nWhat you need to do is replace self.repaint() with QtGui.QApplication.processEvents(). This will give the app a chance to process any pending events (including that repaint, as well as ui interaction) while you're in the loop.\n",
"def count(self):\n self.running=True\n while self.running:\n self.cnt+=1\n print self.cnt\n self.lbl.setText(str(self.cnt))\n self.repaint()\n\nHave you thought about any exit from this endless loop? E.g. self.running=False.\nGUI may stop working because it doesn't have enough time to perform repaint. You may want to add some time.sleep in the loop to wait for the GUI to repaint.\nUpd.: You should use QTimer, not a simple while loop, for the behavior you're implementing.\n",
"You have to let the main event loop run, something you're not doing.\n"
] |
[
7,
5,
2
] |
[] |
[] |
[
"pyqt",
"pyqt4",
"python",
"qt"
] |
stackoverflow_0001936868_pyqt_pyqt4_python_qt.txt
|
Q:
python django string rendering issue
I'm trying to render a string into a javascript ( which usually works fine for me ) here's my code
HTML:
THE USER NAME IS : {{name}} has added app {{has_added_app}}
JAVA SCRIPT:
<script>
<!--
var userName = {{name}}
The html version works the javascript fails when I have tried the same rendering in javascript before and it worked.
A:
var userName = {{name}}
Comes out when you view the HTML source as:
var userName = Bob
Which is an obvious mistake: missing quotes. But, simply putting quotes around it:
var userName = '{{name}}';
isn't good enough for the general case. What if the string contains a quote character, or a backslash, or a newline? Best case, your app falls over. Worst case, cross-site-scripting security hole. What's more a & or < character in the name won't come through properly either, as Django autoescape will probably assume it's in a non-CDATA HTML context and inappropriately &-escape them.
Use the escapejs filter instead:
var userName = '{{name|escapejs}}';
Alternatively use a JSON encoder to turn any basic datatype into JavaScript literal format, not just string. There's json in the standard library from 2.6, but note this doesn't escape the < character in strings, so for injecting code into a script element you'd have to escape that manually to prevent a </script> sequence ending the CDATA element prematurely.
A:
comments for the javascript:
var userName = "{{name}}";
A:
Remember that Django templates are purely textual: they don't "know" that you're creating Javascript. You need to include the quotes that Javascript needs around a string literal:
var userName = "{{name}}";
|
python django string rendering issue
|
I'm trying to render a string into a javascript ( which usually works fine for me ) here's my code
HTML:
THE USER NAME IS : {{name}} has added app {{has_added_app}}
JAVA SCRIPT:
<script>
<!--
var userName = {{name}}
The html version works the javascript fails when I have tried the same rendering in javascript before and it worked.
|
[
"var userName = {{name}}\n\nComes out when you view the HTML source as:\nvar userName = Bob\n\nWhich is an obvious mistake: missing quotes. But, simply putting quotes around it:\nvar userName = '{{name}}';\n\nisn't good enough for the general case. What if the string contains a quote character, or a backslash, or a newline? Best case, your app falls over. Worst case, cross-site-scripting security hole. What's more a & or < character in the name won't come through properly either, as Django autoescape will probably assume it's in a non-CDATA HTML context and inappropriately &-escape them.\nUse the escapejs filter instead:\nvar userName = '{{name|escapejs}}';\n\nAlternatively use a JSON encoder to turn any basic datatype into JavaScript literal format, not just string. There's json in the standard library from 2.6, but note this doesn't escape the < character in strings, so for injecting code into a script element you'd have to escape that manually to prevent a </script> sequence ending the CDATA element prematurely.\n",
"comments for the javascript:\nvar userName = \"{{name}}\";\n\n",
"Remember that Django templates are purely textual: they don't \"know\" that you're creating Javascript. You need to include the quotes that Javascript needs around a string literal:\nvar userName = \"{{name}}\";\n\n"
] |
[
8,
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001937682_django_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.