content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to sort a list by the 2nd tuple element in python and C#
I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this:
sorted(myList, key=lambda x: x[1])
which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I know the obvious answer involving creating classes and specifying an anonymous delegate for the whole compare step but perhaps there is a linq oriented way as well. Thanks in advance for any suggestions.
A:
Another way to do it in python is this
from operator import itemgetter
sorted(myList, key=itemgetter(1))
A:
Assuming that the list of tuples has a type IEnumerable<Tuple<int, int>> (a sequence of tuples represented using Tuple<..> class from .NET 4.0), you can write the following using LINQ extension methods:
var result = myList.OrderBy(k => k.Item2);
In the code k.Item2 returns the second component of the tuple - in C#, this is a property (because accessing item by index wouldn't be type-safe in general). Otherwise, I think that the code is pretty succinct (also thanks to nice lambda function notation).
Using the LINQ query syntax, you could write it like this (although the first version is IMHO more readable and definitely more succinct):
var result = from k in myList orderby k.Item2 select k;
| How to sort a list by the 2nd tuple element in python and C# | I had a list of tuples where every tuple consists of two integers and I wanted to sort by the 2nd integer. After looking in the python help I got this:
sorted(myList, key=lambda x: x[1])
which is great. My question is, is there an equally succinct way of doing this in C# (the language I have to work in)? I know the obvious answer involving creating classes and specifying an anonymous delegate for the whole compare step but perhaps there is a linq oriented way as well. Thanks in advance for any suggestions.
| [
"Another way to do it in python is this\nfrom operator import itemgetter\nsorted(myList, key=itemgetter(1))\n\n",
"Assuming that the list of tuples has a type IEnumerable<Tuple<int, int>> (a sequence of tuples represented using Tuple<..> class from .NET 4.0), you can write the following using LINQ extension methods:\nvar result = myList.OrderBy(k => k.Item2);\n\nIn the code k.Item2 returns the second component of the tuple - in C#, this is a property (because accessing item by index wouldn't be type-safe in general). Otherwise, I think that the code is pretty succinct (also thanks to nice lambda function notation).\nUsing the LINQ query syntax, you could write it like this (although the first version is IMHO more readable and definitely more succinct):\nvar result = from k in myList orderby k.Item2 select k;\n\n"
] | [
14,
6
] | [] | [] | [
"c#",
"python",
"sorting"
] | stackoverflow_0002909652_c#_python_sorting.txt |
Q:
Is it bad practice to use python's getattr extensively?
I'm creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making use of the fact that functions are first class objects in python.
For flexibility's sake (mostly for parsing commands), I'm thinking of changing my setup such that I'm using getattr(command), to grab the method I need and then passing arguments to it at the end of my parser. Another advantage of this approach is not having to update my (currently statically implemented) command dictionary every time I add a new method/command.
My question is two fold. First, does getattr have the same problems as eval? Second, will I be taking a hit to the efficiency of my shell? Does it matter how many methods/commands I have? I'm currently looking at 30 some commands, which could eventually double.
A:
The difference between direct attribute access and using getattr() should be fairly negligible. You can tell the difference between the two versions' bytecodes by using Python's dis module to compare the two approaches:
>>> import dis
>>> dis.dis(lambda x: x.foo)
1 0 LOAD_FAST 0 (x)
3 LOAD_ATTR 0 (foo)
6 RETURN_VALUE
>>> dis.dis(lambda x: getattr(x, 'foo'))
1 0 LOAD_GLOBAL 0 (getattr)
3 LOAD_FAST 0 (x)
6 LOAD_CONST 0 ('foo')
9 CALL_FUNCTION 2
12 RETURN_VALUE
It does, however, sound like you are developing a shell that is very similar to how the Python library cmd does command line shells. cmd lets you create shells that executes commands by matching the command name to a function defined on a cmd.Cmd object like so:
import cmd
class EchoCmd(cmd.Cmd):
"""Simple command processor example."""
def do_echo(self, line):
print line
def do_EOF(self, line):
return True
if __name__ == '__main__':
EchoCmd().cmdloop()
You can read more about the module at either the documentation, or at http://www.doughellmann.com/PyMOTW/cmd/index.html
A:
does getattr have the same problems as eval?
No -- code using eval() is terribly annoying to maintain, and can have serious security problems. Calling getattr(x, "foo") is just another way to write x.foo.
will I be taking a hit to the efficiency of my shell
It will be imperceptibly slower if the command isn't found, but not enough to matter. You'd only notice it if doing benchmarks, with tens of thousands of entries.
| Is it bad practice to use python's getattr extensively? | I'm creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making use of the fact that functions are first class objects in python.
For flexibility's sake (mostly for parsing commands), I'm thinking of changing my setup such that I'm using getattr(command), to grab the method I need and then passing arguments to it at the end of my parser. Another advantage of this approach is not having to update my (currently statically implemented) command dictionary every time I add a new method/command.
My question is two fold. First, does getattr have the same problems as eval? Second, will I be taking a hit to the efficiency of my shell? Does it matter how many methods/commands I have? I'm currently looking at 30 some commands, which could eventually double.
| [
"The difference between direct attribute access and using getattr() should be fairly negligible. You can tell the difference between the two versions' bytecodes by using Python's dis module to compare the two approaches:\n>>> import dis\n>>> dis.dis(lambda x: x.foo)\n 1 0 LOAD_FAST 0 (x)\n 3 LOAD_ATTR 0 (foo)\n 6 RETURN_VALUE \n>>> dis.dis(lambda x: getattr(x, 'foo'))\n 1 0 LOAD_GLOBAL 0 (getattr)\n 3 LOAD_FAST 0 (x)\n 6 LOAD_CONST 0 ('foo')\n 9 CALL_FUNCTION 2\n 12 RETURN_VALUE \n\nIt does, however, sound like you are developing a shell that is very similar to how the Python library cmd does command line shells. cmd lets you create shells that executes commands by matching the command name to a function defined on a cmd.Cmd object like so:\nimport cmd\n\nclass EchoCmd(cmd.Cmd):\n \"\"\"Simple command processor example.\"\"\"\n\n def do_echo(self, line):\n print line\n\n def do_EOF(self, line):\n return True\n\nif __name__ == '__main__':\n EchoCmd().cmdloop()\n\nYou can read more about the module at either the documentation, or at http://www.doughellmann.com/PyMOTW/cmd/index.html\n",
"\ndoes getattr have the same problems as eval? \n\nNo -- code using eval() is terribly annoying to maintain, and can have serious security problems. Calling getattr(x, \"foo\") is just another way to write x.foo.\n\nwill I be taking a hit to the efficiency of my shell\n\nIt will be imperceptibly slower if the command isn't found, but not enough to matter. You'd only notice it if doing benchmarks, with tens of thousands of entries.\n"
] | [
27,
10
] | [] | [] | [
"getattr",
"performance",
"python",
"shell"
] | stackoverflow_0002909423_getattr_performance_python_shell.txt |
Q:
Python: Why Does a Method Behave Differently with an Added Parameter?
I have a method in a Pygame Sprite subclass, defined as such:
def walk(self):
"""move across screen"""
displacement = self.rect.move((self.move, 0))
if self.rect.left < self.area.left or self.rect.right > self.area.right:
self.move = -self.move
displacement = self.rect.move((self.move, 0))
self.rect = displacement
I modified it, adding a parameter speed_x, and now the program is broken.
def walk(self, speed_x):
"""move across screen"""
displacement = self.rect.move((speed_x, 0))
if self.rect.left < self.area.left or self.rect.right > self.area.right:
speed_x = -speed_x
displacement = self.rect.move((speed_x, 0))
self.rect = displacement
Before I called the method like this:
def update(self):
self.walk()
Now I do:
def update(self):
self.walk(self.move)
Why doesn't this work?
A:
You don't explain how it's "broken", but the main difference is that
speed_x = -speed_x
which you have in your second version, is only changing the local variable (arguments are local variables!) speed_x, so that changed value does not persist.
In the first version,
self.move = -self.move
does alter self (specifically one of its attriubtes) and the alteration "persists" in future method calls on the object which is here accessed as self.
Just one of the many key differences between bare names (like speed_x) and qualified names (line self.move), and, I suspect, what's biting you here (hard as you may make it to guess by not saying how the second version is failing your expectations).
A:
You are no storing the offset back in to self.move.
A:
If you want to use the second version of your code, try adding this line:
self.move = speed_x
At the bottom of your function.
A:
As mentioned by others, you are not changing the value of self.move in your new code. I assume the reason you modified this function was so you could reuse this function for values other than self.move.
If you want to be able to pass different arguments into your function and modify them as well, you could pass the modified value of speed_x back as a return value:
def walk(self, speed_x):
"""move across screen"""
displacement = self.rect.move((speed_x, 0))
if self.rect.left < self.area.left or self.rect.right > self.area.right:
speed_x = -speed_x
displacement = self.rect.move((speed_x, 0))
self.rect = displacement
return speed_x
And call the function like this as:
def update(self):
self.move = self.walk(self.move)
Note: This answer assumes that self.move should not always be updated when calling walk. If this assumption is false and self.move should in fact be updated every time walk is run, then you should instead use Xavier Ho's answer.
| Python: Why Does a Method Behave Differently with an Added Parameter? | I have a method in a Pygame Sprite subclass, defined as such:
def walk(self):
"""move across screen"""
displacement = self.rect.move((self.move, 0))
if self.rect.left < self.area.left or self.rect.right > self.area.right:
self.move = -self.move
displacement = self.rect.move((self.move, 0))
self.rect = displacement
I modified it, adding a parameter speed_x, and now the program is broken.
def walk(self, speed_x):
"""move across screen"""
displacement = self.rect.move((speed_x, 0))
if self.rect.left < self.area.left or self.rect.right > self.area.right:
speed_x = -speed_x
displacement = self.rect.move((speed_x, 0))
self.rect = displacement
Before I called the method like this:
def update(self):
self.walk()
Now I do:
def update(self):
self.walk(self.move)
Why doesn't this work?
| [
"You don't explain how it's \"broken\", but the main difference is that\nspeed_x = -speed_x\n\nwhich you have in your second version, is only changing the local variable (arguments are local variables!) speed_x, so that changed value does not persist.\nIn the first version,\nself.move = -self.move \n\ndoes alter self (specifically one of its attriubtes) and the alteration \"persists\" in future method calls on the object which is here accessed as self.\nJust one of the many key differences between bare names (like speed_x) and qualified names (line self.move), and, I suspect, what's biting you here (hard as you may make it to guess by not saying how the second version is failing your expectations).\n",
"You are no storing the offset back in to self.move.\n",
"If you want to use the second version of your code, try adding this line:\n self.move = speed_x\n\nAt the bottom of your function.\n",
"As mentioned by others, you are not changing the value of self.move in your new code. I assume the reason you modified this function was so you could reuse this function for values other than self.move.\nIf you want to be able to pass different arguments into your function and modify them as well, you could pass the modified value of speed_x back as a return value:\ndef walk(self, speed_x):\n \"\"\"move across screen\"\"\"\n displacement = self.rect.move((speed_x, 0))\n if self.rect.left < self.area.left or self.rect.right > self.area.right:\n speed_x = -speed_x\n displacement = self.rect.move((speed_x, 0))\n self.rect = displacement\n return speed_x\n\nAnd call the function like this as:\ndef update(self):\n self.move = self.walk(self.move)\n\nNote: This answer assumes that self.move should not always be updated when calling walk. If this assumption is false and self.move should in fact be updated every time walk is run, then you should instead use Xavier Ho's answer.\n"
] | [
3,
1,
1,
1
] | [] | [] | [
"oop",
"pygame",
"python"
] | stackoverflow_0002909948_oop_pygame_python.txt |
Q:
python grep reverse matching
I would like to build a small python script that basicaly does the reverse of grep.
I want to match the files in a directory/subdirectory that doesn't have a "searched_string".
So far i've done that:
import os
filefilter = ['java','.jsp']
path= "/home/patate/code/project"
for path, subdirs, files in os.walk(path):
for name in files:
if name[-4:] in filefilter :
print os.path.join(path, name)
This small script will be listing everyfiles with "java" or "jsp" extension inside each subdirectory, and will output them full path.
I'm now wondering how to do the rest, for example i would like to be able if I forgot a session management entry in one file (allowing anyone a direct file access), to search for :
"if (!user.hasPermission" and list the file which does not contain this string.
Any help would be greatly appreciated !
Thanks
A:
To check if a file with a path bound to variable f contains a string bound to name s, simplest (and acceptable for most reasonably-sized files) is something like
with open(f) as fp:
if s in fp.read():
print '%s has the string' % f
else:
print '%s doesn't have the string' % f
In your os.walk loop, you have the root path and filename separately, so
f = os.path.join(path, name)
(what you're unconditionally printing) is the path you want to open and check.
A:
Instead of printing file name call function that will check if file content do not match texts you want to have in source files. In such cases I use check_file() that looks like this:
WARNING_RX = (
(re.compile(r'if\s+\(!\s+user.hasPermission'), 'user.hasPermission'),
(re.compile(r'other regexp you want to have'), 'very important'),
)
def check_file(fn):
f = open(fn, 'r')
content = f.read()
f.close()
for rx, rx_desc in WARNING_RX:
if not rx.search(content):
print('%s: not found: %s' % (fn, rx_desc))
| python grep reverse matching | I would like to build a small python script that basicaly does the reverse of grep.
I want to match the files in a directory/subdirectory that doesn't have a "searched_string".
So far i've done that:
import os
filefilter = ['java','.jsp']
path= "/home/patate/code/project"
for path, subdirs, files in os.walk(path):
for name in files:
if name[-4:] in filefilter :
print os.path.join(path, name)
This small script will be listing everyfiles with "java" or "jsp" extension inside each subdirectory, and will output them full path.
I'm now wondering how to do the rest, for example i would like to be able if I forgot a session management entry in one file (allowing anyone a direct file access), to search for :
"if (!user.hasPermission" and list the file which does not contain this string.
Any help would be greatly appreciated !
Thanks
| [
"To check if a file with a path bound to variable f contains a string bound to name s, simplest (and acceptable for most reasonably-sized files) is something like\nwith open(f) as fp:\n if s in fp.read():\n print '%s has the string' % f\n else:\n print '%s doesn't have the string' % f\n\nIn your os.walk loop, you have the root path and filename separately, so\nf = os.path.join(path, name)\n\n(what you're unconditionally printing) is the path you want to open and check.\n",
"Instead of printing file name call function that will check if file content do not match texts you want to have in source files. In such cases I use check_file() that looks like this:\nWARNING_RX = (\n (re.compile(r'if\\s+\\(!\\s+user.hasPermission'), 'user.hasPermission'),\n (re.compile(r'other regexp you want to have'), 'very important'),\n )\n\ndef check_file(fn):\n f = open(fn, 'r')\n content = f.read()\n f.close()\n for rx, rx_desc in WARNING_RX:\n if not rx.search(content):\n print('%s: not found: %s' % (fn, rx_desc))\n\n"
] | [
1,
0
] | [] | [] | [
"pattern_matching",
"python"
] | stackoverflow_0002910106_pattern_matching_python.txt |
Q:
NZEC Run time Error Occured
import math
def gen_caller(a):
for z in a:
x,y=z
if x==1:
x=2
if y>=x and y-x<=100000:
for i in range(x,y+1):
flag=0
for j in range(2,(long(math.sqrt(i))+1)):
if(i%j==0):
flag=1
break
if flag==0:
print i
print ""
n=(int(raw_input()))
gen_caller([[(long(raw_input())) for j in range(0,2)] for i in range(0,n) if n<=10])
A:
Try using Python 3.1. Just change "long" to "int", "raw_input" to "input" and put brackets around what you want to print. I didn't get an error, probably because of better support of very large numbers in Python 3.
| NZEC Run time Error Occured | import math
def gen_caller(a):
for z in a:
x,y=z
if x==1:
x=2
if y>=x and y-x<=100000:
for i in range(x,y+1):
flag=0
for j in range(2,(long(math.sqrt(i))+1)):
if(i%j==0):
flag=1
break
if flag==0:
print i
print ""
n=(int(raw_input()))
gen_caller([[(long(raw_input())) for j in range(0,2)] for i in range(0,n) if n<=10])
| [
"Try using Python 3.1. Just change \"long\" to \"int\", \"raw_input\" to \"input\" and put brackets around what you want to print. I didn't get an error, probably because of better support of very large numbers in Python 3.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002772199_python.txt |
Q:
Running an allocation simulation repeatedly breaks after the first run
Background
I have a bunch of students, their desired projects and the supervisors for the respective projects. I'm running a battery of simulations to see which projects the students end up with, which will allow me to get some useful statistics required for feedback. So, this is essentially a Monte-Carlo simulation where I'm randomising the list of students and then iterating through it, allocating projects until I hit the end of the list. Then the process is repeated again.
Note that, within a single session, after each successful allocation of a project the following take place:
+ the project is set to allocated and cannot be given to another student
+ the supervisor has a fixed quota of students he can supervise. This is decremented by 1
+ Once the quota hits 0, all the projects from that supervisor become blocked and this has the same effect as a project being allocated
Code
def resetData():
for student in students.itervalues():
student.allocated_project = None
for supervisor in supervisors.itervalues():
supervisor.quota = 0
for project in projects.itervalues():
project.allocated = False
project.blocked = False
The role of resetData() is to "reset" certain bits of the data. For example, when a project is successfully allocated, project.allocated for that project is flipped to True. While that's useful for a single run, for the next run I need to be deallocated.
Above I'm iterating through thee three dictionaries - one each for students, projects and supervisors - where the information is stored.
The next bit is the "Monte-Carlo" simulation for the allocation algorithm.
sesh_id = 1
for trial in range(50):
for id in randomiseStudents(1):
stud_id = id
student = students[id]
if not student.preferences:
# Ignoring the students who've not entered any preferences
for rank in ranks:
temp_proj = random.choice(list(student.preferences[rank]))
if not (temp_proj.allocated or temp_proj.blocked):
alloc_proj = student.allocated_proj_ref = temp_proj.proj_id
alloc_proj_rank = student.allocated_rank = rank
successActions(temp_proj)
temp_alloc = Allocated(sesh_id, stud_id, alloc_proj, alloc_proj_rank)
print temp_alloc # Explained
break
sesh_id += 1
resetData() # Refer to def resetData() above
All randomiseStudents(1) does is randomise the order of students.
Allocated is a class defined as such:
class Allocated(object):
def __init__(self, sesh_id, stud_id, alloc_proj, alloc_proj_rank):
self.sesh_id = sesh_id
self.stud_id = stud_id
self.alloc_proj = alloc_proj
self.alloc_proj_rank = alloc_proj_rank
def __repr__(self):
return str(self)
def __str__(self):
return "%s - Student: %s (Project: %s - Rank: %s)" %(self.sesh_id, self.stud_id, self.alloc_proj, self.alloc_proj_rank)
Output and problem
Now if I run this I get an output such as this (truncated):
1 - Student: 7720 (Project: 1100241 - Rank: 1)
1 - Student: 7832 (Project: 1100339 - Rank: 1)
1 - Student: 7743 (Project: 1100359 - Rank: 1)
1 - Student: 7820 (Project: 1100261 - Rank: 2)
1 - Student: 7829 (Project: 1100270 - Rank: 1)
.
.
.
1 - Student: 7822 (Project: 1100280 - Rank: 1)
1 - Student: 7792 (Project: 1100141 - Rank: 7)
2 - Student: 7739 (Project: 1100267 - Rank: 1)
3 - Student: 7806 (Project: 1100272 - Rank: 1)
.
.
.
45 - Student: 7806 (Project: 1100272 - Rank: 1)
46 - Student: 7714 (Project: 1100317 - Rank: 1)
47 - Student: 7930 (Project: 1100343 - Rank: 1)
48 - Student: 7757 (Project: 1100358 - Rank: 1)
49 - Student: 7759 (Project: 1100269 - Rank: 1)
50 - Student: 7778 (Project: 1100301 - Rank: 1)
Basically, it works perfectly for the first run, but on subsequent runs leading upto the nth run, in this case 50, only a single student-project allocation pair is returned.
Thus, the main issue I'm having trouble with is figuring out what is causing this anomalous behaviour especially since the first run works smoothly.
Thanks in advance,
Az
A:
Do you really intend to set the supervisor's quota to 0 in resetData()? Doesn't that mean all their projects are now blocked?
Quoth the raven:
The supervisor has a fixed quota of students he can supervise. This is decremented by 1. Once the quota hits 0, all the projects from that supervisor become blocked and this has the same effect as a project being allocated.
If that's not it, you should check the output of randomiseStudents() to ensure it's returning a full list. It is, after all, the controlling item for that inner loop.
Update based on comments:
It appears the problem was that you were setting the supervisor's quota to 0 thus rendering all their projects blocked.
This is pure guesswork on my part but you probably got one student out in each iteration because the checking of all supervisors happened after an allocation. In that case, the one just allocated would have a quota of -1 and all the other quotas would be 0, effectively stopping all allocations after that one.
Ideally, you'd want to set the supervisor's quota back to their original value in resetData(). If it were a fixed quota (same for each supervisor), you could simply use:
for supervisor in supervisors.itervalues():
supervisor.quota = 7 # for example
If each supervisor had a different quota, you would need to store that along with the other information (during initialisation but not resetting) as, for, example supervisor.start_quota. Then you could use:
for supervisor in supervisors.itervalues():
supervisor.quota = supervisor.start_quota
| Running an allocation simulation repeatedly breaks after the first run | Background
I have a bunch of students, their desired projects and the supervisors for the respective projects. I'm running a battery of simulations to see which projects the students end up with, which will allow me to get some useful statistics required for feedback. So, this is essentially a Monte-Carlo simulation where I'm randomising the list of students and then iterating through it, allocating projects until I hit the end of the list. Then the process is repeated again.
Note that, within a single session, after each successful allocation of a project the following take place:
+ the project is set to allocated and cannot be given to another student
+ the supervisor has a fixed quota of students he can supervise. This is decremented by 1
+ Once the quota hits 0, all the projects from that supervisor become blocked and this has the same effect as a project being allocated
Code
def resetData():
for student in students.itervalues():
student.allocated_project = None
for supervisor in supervisors.itervalues():
supervisor.quota = 0
for project in projects.itervalues():
project.allocated = False
project.blocked = False
The role of resetData() is to "reset" certain bits of the data. For example, when a project is successfully allocated, project.allocated for that project is flipped to True. While that's useful for a single run, for the next run I need to be deallocated.
Above I'm iterating through thee three dictionaries - one each for students, projects and supervisors - where the information is stored.
The next bit is the "Monte-Carlo" simulation for the allocation algorithm.
sesh_id = 1
for trial in range(50):
for id in randomiseStudents(1):
stud_id = id
student = students[id]
if not student.preferences:
# Ignoring the students who've not entered any preferences
for rank in ranks:
temp_proj = random.choice(list(student.preferences[rank]))
if not (temp_proj.allocated or temp_proj.blocked):
alloc_proj = student.allocated_proj_ref = temp_proj.proj_id
alloc_proj_rank = student.allocated_rank = rank
successActions(temp_proj)
temp_alloc = Allocated(sesh_id, stud_id, alloc_proj, alloc_proj_rank)
print temp_alloc # Explained
break
sesh_id += 1
resetData() # Refer to def resetData() above
All randomiseStudents(1) does is randomise the order of students.
Allocated is a class defined as such:
class Allocated(object):
def __init__(self, sesh_id, stud_id, alloc_proj, alloc_proj_rank):
self.sesh_id = sesh_id
self.stud_id = stud_id
self.alloc_proj = alloc_proj
self.alloc_proj_rank = alloc_proj_rank
def __repr__(self):
return str(self)
def __str__(self):
return "%s - Student: %s (Project: %s - Rank: %s)" %(self.sesh_id, self.stud_id, self.alloc_proj, self.alloc_proj_rank)
Output and problem
Now if I run this I get an output such as this (truncated):
1 - Student: 7720 (Project: 1100241 - Rank: 1)
1 - Student: 7832 (Project: 1100339 - Rank: 1)
1 - Student: 7743 (Project: 1100359 - Rank: 1)
1 - Student: 7820 (Project: 1100261 - Rank: 2)
1 - Student: 7829 (Project: 1100270 - Rank: 1)
.
.
.
1 - Student: 7822 (Project: 1100280 - Rank: 1)
1 - Student: 7792 (Project: 1100141 - Rank: 7)
2 - Student: 7739 (Project: 1100267 - Rank: 1)
3 - Student: 7806 (Project: 1100272 - Rank: 1)
.
.
.
45 - Student: 7806 (Project: 1100272 - Rank: 1)
46 - Student: 7714 (Project: 1100317 - Rank: 1)
47 - Student: 7930 (Project: 1100343 - Rank: 1)
48 - Student: 7757 (Project: 1100358 - Rank: 1)
49 - Student: 7759 (Project: 1100269 - Rank: 1)
50 - Student: 7778 (Project: 1100301 - Rank: 1)
Basically, it works perfectly for the first run, but on subsequent runs leading upto the nth run, in this case 50, only a single student-project allocation pair is returned.
Thus, the main issue I'm having trouble with is figuring out what is causing this anomalous behaviour especially since the first run works smoothly.
Thanks in advance,
Az
| [
"Do you really intend to set the supervisor's quota to 0 in resetData()? Doesn't that mean all their projects are now blocked?\nQuoth the raven:\n\nThe supervisor has a fixed quota of students he can supervise. This is decremented by 1. Once the quota hits 0, all the projects from that supervisor become blocked and this has the same effect as a project being allocated.\n\nIf that's not it, you should check the output of randomiseStudents() to ensure it's returning a full list. It is, after all, the controlling item for that inner loop.\n\nUpdate based on comments:\nIt appears the problem was that you were setting the supervisor's quota to 0 thus rendering all their projects blocked.\nThis is pure guesswork on my part but you probably got one student out in each iteration because the checking of all supervisors happened after an allocation. In that case, the one just allocated would have a quota of -1 and all the other quotas would be 0, effectively stopping all allocations after that one.\nIdeally, you'd want to set the supervisor's quota back to their original value in resetData(). If it were a fixed quota (same for each supervisor), you could simply use:\nfor supervisor in supervisors.itervalues():\n supervisor.quota = 7 # for example\n\nIf each supervisor had a different quota, you would need to store that along with the other information (during initialisation but not resetting) as, for, example supervisor.start_quota. Then you could use:\nfor supervisor in supervisors.itervalues():\n supervisor.quota = supervisor.start_quota\n\n"
] | [
0
] | [] | [] | [
"montecarlo",
"python"
] | stackoverflow_0002910240_montecarlo_python.txt |
Q:
Requesting information from the user inside a GTK main loop
I am learning Python by building a simple PyGTK application that fetches data from some SVN repositories, using pysvn. The pysvn Client has a callback you can specify that it calls when Subversion needs authentication information for a repository. When that happens, I would like to open a dialog to ask the user for the credentials.
The problem is, it seems the callback is called inside the GTK main loop, so it's basically called on every tick. Is there a way to prevent this? Perhaps by opening the dialog in a new thread? But then how do I return the tuple with the user data to the callback so it can return it to the pysvn.Client?
A:
This is the way we do it in RabbitVCS. Essentially, the main application creates the dialog and runs it using the PyGTK gtk.Dialog run() method.
Breaking it down, from the main app we have (see action.py):
def get_login(self, realm, username, may_save):
# ...other code omitted...
gtk.gdk.threads_enter()
dialog = rabbitvcs.ui.dialog.Authentication(
realm,
may_save
)
result = dialog.run()
gtk.gdk.threads_leave()
return result
This "get_login" function is the one that is given as the callback to the PySVN client instance.
Note the threads_enter() and threads_leave() methods! These allow GTK to use Python threads, but note that the GIL may be locked by other extensions.
What this does is create a dialog (already laid out using Glade), and the run() method on that class is a wrapper for the PyGTK method (see dialog.py):
def run(self):
returner = None
self.dialog = self.get_widget("Authentication")
result = self.dialog.run()
login = self.get_widget("auth_login").get_text()
password = self.get_widget("auth_password").get_text()
save = self.get_widget("auth_save").get_active()
self.dialog.destroy()
if result == gtk.RESPONSE_OK:
return (True, login, password, save)
else:
return (False, "", "", False)
The RabbitVCS UI code is probably far more convoluted that you would need, but it might help to poke around. Those "get_widget" calls are convenience methods to get the widget from the Glade tree. If you are not using Glade, you will have references to the widgets directly.
I hope it helps :)
| Requesting information from the user inside a GTK main loop | I am learning Python by building a simple PyGTK application that fetches data from some SVN repositories, using pysvn. The pysvn Client has a callback you can specify that it calls when Subversion needs authentication information for a repository. When that happens, I would like to open a dialog to ask the user for the credentials.
The problem is, it seems the callback is called inside the GTK main loop, so it's basically called on every tick. Is there a way to prevent this? Perhaps by opening the dialog in a new thread? But then how do I return the tuple with the user data to the callback so it can return it to the pysvn.Client?
| [
"This is the way we do it in RabbitVCS. Essentially, the main application creates the dialog and runs it using the PyGTK gtk.Dialog run() method.\nBreaking it down, from the main app we have (see action.py):\ndef get_login(self, realm, username, may_save):\n\n # ...other code omitted...\n\n gtk.gdk.threads_enter()\n dialog = rabbitvcs.ui.dialog.Authentication(\n realm,\n may_save\n )\n result = dialog.run()\n gtk.gdk.threads_leave()\n\n return result\n\nThis \"get_login\" function is the one that is given as the callback to the PySVN client instance.\nNote the threads_enter() and threads_leave() methods! These allow GTK to use Python threads, but note that the GIL may be locked by other extensions.\nWhat this does is create a dialog (already laid out using Glade), and the run() method on that class is a wrapper for the PyGTK method (see dialog.py):\ndef run(self):\n returner = None\n self.dialog = self.get_widget(\"Authentication\")\n result = self.dialog.run()\n\n login = self.get_widget(\"auth_login\").get_text()\n password = self.get_widget(\"auth_password\").get_text()\n save = self.get_widget(\"auth_save\").get_active()\n self.dialog.destroy()\n\n if result == gtk.RESPONSE_OK:\n return (True, login, password, save)\n else:\n return (False, \"\", \"\", False)\n\nThe RabbitVCS UI code is probably far more convoluted that you would need, but it might help to poke around. Those \"get_widget\" calls are convenience methods to get the widget from the Glade tree. If you are not using Glade, you will have references to the widgets directly.\nI hope it helps :)\n"
] | [
1
] | [] | [] | [
"multithreading",
"pygtk",
"pysvn",
"python"
] | stackoverflow_0002865438_multithreading_pygtk_pysvn_python.txt |
Q:
Log flexlm licence usage from remote machine
We have several software packages (SolidWorks, Pro/ENGINEER, OrCAD, Minitab... ) that use FlexLM to manage network licences.
I have written a python program to poll the FlexLM daemons every few mintues using lmutil lmstat -a.
However, this requires lmutil to be installed on the same machine as the python program.
Our FlexLM licence daemons are on several servers so does anyone know how to connect to a FlexLM server over its port to ask for its licence usage state?
A:
It seems the only way to get licence usage over a network is to poll the flexlm daemon using:
lmutil lmstat -a -c <port-number@license-server>
I've not marked orenhg's repsonse as an answer as it is advertising his product rather than answering the question.
| Log flexlm licence usage from remote machine | We have several software packages (SolidWorks, Pro/ENGINEER, OrCAD, Minitab... ) that use FlexLM to manage network licences.
I have written a python program to poll the FlexLM daemons every few mintues using lmutil lmstat -a.
However, this requires lmutil to be installed on the same machine as the python program.
Our FlexLM licence daemons are on several servers so does anyone know how to connect to a FlexLM server over its port to ask for its licence usage state?
| [
"It seems the only way to get licence usage over a network is to poll the flexlm daemon using:\nlmutil lmstat -a -c <port-number@license-server>\n\nI've not marked orenhg's repsonse as an answer as it is advertising his product rather than answering the question.\n"
] | [
4
] | [] | [] | [
"flexlm",
"python"
] | stackoverflow_0002789540_flexlm_python.txt |
Q:
python processs complete list files matched
I'm trying to get simple code working, unfortunately I'm a python beginner.
My script should return a list of files that doesn't match a pattern, more information here :
python grep reverse matching
My code is running but doesn't process the complete list of files found as it should :
import sys,os
filefilter = ['.xml','java','.jsp','lass']
path= "/home/patate/code/project"
s = "helloworld"
for path, subdirs, files in os.walk(path):
for name in files:
if name[-4:] in filefilter :
f = str(os.path.join(path, name))
with open(f) as fp:
if s in fp.read():
print "%s has the string" % f
else:
print "%s doesn't have the string" % f
This code returns :
/home/patate/code/project/blabla/blabla/build.xml doesn't have the string
None
If I change f = str(os.path.join(path, name)) for print str(os.path.join(path, name))
I can see the whole list being printed.
How can I process the whole list as I wish to ?
A:
Try using os.path.splitext to check for a matching file extension.
for path, subdirs, files in os.walk(path):
for name in files:
if os.path.splitext(name)[1] in filefilter:
f = str(os.path.join(path, name))
with open(f) as fp:
if s in fp.read():
print "%s has the string" % f
else:
print "%s doesn't have the string" % f
The rest looks fine.
| python processs complete list files matched | I'm trying to get simple code working, unfortunately I'm a python beginner.
My script should return a list of files that doesn't match a pattern, more information here :
python grep reverse matching
My code is running but doesn't process the complete list of files found as it should :
import sys,os
filefilter = ['.xml','java','.jsp','lass']
path= "/home/patate/code/project"
s = "helloworld"
for path, subdirs, files in os.walk(path):
for name in files:
if name[-4:] in filefilter :
f = str(os.path.join(path, name))
with open(f) as fp:
if s in fp.read():
print "%s has the string" % f
else:
print "%s doesn't have the string" % f
This code returns :
/home/patate/code/project/blabla/blabla/build.xml doesn't have the string
None
If I change f = str(os.path.join(path, name)) for print str(os.path.join(path, name))
I can see the whole list being printed.
How can I process the whole list as I wish to ?
| [
"Try using os.path.splitext to check for a matching file extension. \nfor path, subdirs, files in os.walk(path):\n for name in files:\n if os.path.splitext(name)[1] in filefilter:\n f = str(os.path.join(path, name))\n with open(f) as fp:\n if s in fp.read():\n print \"%s has the string\" % f\n else:\n print \"%s doesn't have the string\" % f\n\nThe rest looks fine.\n"
] | [
0
] | [] | [] | [
"os.walk",
"python"
] | stackoverflow_0002910605_os.walk_python.txt |
Q:
Including a Django app's url.py is resulting in a 404
I have the following code in the urls.py in mysite project.
/mysite/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^gallery/$', include('mysite.gallery.urls')),
)
This results in a 404 page when I try to access a url set in gallery/urls.py.
/mysite/gallery/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^gallery/browse/$', 'mysite.gallery.views.browse'),
(r'^gallery/photo/$', 'mysite.gallery.views.photo'),
)
404 error
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^gallery/$
The current URL, gallery/browse/, didn't match any of these.
Also, the site is hosted on a media temple (dv) server and using mod_wsgi
A:
Remove the $ from the regex of main urls.py
urlpatterns = patterns('',
(r'^gallery/', include('mysite.gallery.urls')),
)
You don't need gallery in the included Urlconf.
urlpatterns = patterns('',
(r'^browse/$', 'mysite.gallery.views.browse'),
(r'^photo/$', 'mysite.gallery.views.photo'),
)
Read the django docs for more information
Note that the regular expressions in this example don't have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
| Including a Django app's url.py is resulting in a 404 | I have the following code in the urls.py in mysite project.
/mysite/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^gallery/$', include('mysite.gallery.urls')),
)
This results in a 404 page when I try to access a url set in gallery/urls.py.
/mysite/gallery/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^gallery/browse/$', 'mysite.gallery.views.browse'),
(r'^gallery/photo/$', 'mysite.gallery.views.photo'),
)
404 error
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^gallery/$
The current URL, gallery/browse/, didn't match any of these.
Also, the site is hosted on a media temple (dv) server and using mod_wsgi
| [
"Remove the $ from the regex of main urls.py\nurlpatterns = patterns('',\n (r'^gallery/', include('mysite.gallery.urls')),\n)\n\nYou don't need gallery in the included Urlconf.\nurlpatterns = patterns('', \n (r'^browse/$', 'mysite.gallery.views.browse'),\n (r'^photo/$', 'mysite.gallery.views.photo'),\n)\n\nRead the django docs for more information\n\nNote that the regular expressions in this example don't have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.\n\n"
] | [
17
] | [] | [] | [
"django",
"django_urls",
"http_status_code_404",
"python",
"url_routing"
] | stackoverflow_0002910714_django_django_urls_http_status_code_404_python_url_routing.txt |
Q:
One single page to create a Parent object and its associated child objects
This is my very first post on this awesome site, from which I have been finding answers to a handful of challenging questions. Kudos to the community!
I am new to the Django world, so am hoping to find help from some Django experts here. Thanks in advance.
Item model:
class Item(models.Model):
name = models.CharField(max_length=50)
ItemImage model:
class ItemImage(models.Model):
image = models.ImageField(upload_to=get_unique_filename)
item = models.ForeignKey(Item, related_name='images')
As you can tell from the model definitions above, every Item object can have many ItemImage objects.
My requirements are as followings:
A single web page that allows users
to create a new Item while uploading
the images associated with the Item. The Item and the ItemImages objects should be created in the database all together, when the "Save" button on the page is clicked.
I have created a variable in a custom config file, called NUMBER_OF_IMAGES_PER_ITEM. It is based on this variable that the system generates the number of image fields per item.
Questions:
What should the forms and the template be like? Can ModelForm be used to achieve the requirements?
For the view function, what do I need to watch out other than making sure to save Item before ItemImage objects?
A:
Considering that you are using file upload fields, I'm not sure that it's a right approach for web application. What if Item name validation fails? If you re-display the form again all file upload fields become empty and user has to fill them again.
Re technical side - ModelForm will do for the Item model but you should also use model formset for ItemImage's. See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view for details.
| One single page to create a Parent object and its associated child objects | This is my very first post on this awesome site, from which I have been finding answers to a handful of challenging questions. Kudos to the community!
I am new to the Django world, so am hoping to find help from some Django experts here. Thanks in advance.
Item model:
class Item(models.Model):
name = models.CharField(max_length=50)
ItemImage model:
class ItemImage(models.Model):
image = models.ImageField(upload_to=get_unique_filename)
item = models.ForeignKey(Item, related_name='images')
As you can tell from the model definitions above, every Item object can have many ItemImage objects.
My requirements are as followings:
A single web page that allows users
to create a new Item while uploading
the images associated with the Item. The Item and the ItemImages objects should be created in the database all together, when the "Save" button on the page is clicked.
I have created a variable in a custom config file, called NUMBER_OF_IMAGES_PER_ITEM. It is based on this variable that the system generates the number of image fields per item.
Questions:
What should the forms and the template be like? Can ModelForm be used to achieve the requirements?
For the view function, what do I need to watch out other than making sure to save Item before ItemImage objects?
| [
"Considering that you are using file upload fields, I'm not sure that it's a right approach for web application. What if Item name validation fails? If you re-display the form again all file upload fields become empty and user has to fill them again.\nRe technical side - ModelForm will do for the Item model but you should also use model formset for ItemImage's. See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view for details.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002910708_django_python.txt |
Q:
Python 2.6 -> Python 3 (ProxyHandler)
I wrote a script that works with a proxy (py2.6x):
proxy_support = urllib2.ProxyHandler({'http' : 'http://127.0.0.1:80'})
But in py3.11x there is no urllib2 just a urllib... and that doesn't support the ProxyHandler
How can I use a proxy with urllib? Isn't Python 3 newer then Python 2? Why did they remove urllib2 in a newer version?
A:
In Python 3, urllib2.ProxyHandler is now urllib.request.ProxyHandler.
import urllib.request
proxy_support = urllib.request.ProxyHandler({'http' : 'http://127.0.0.1:80'})
Many of the old url*libs have been merged with theurllib package.
Here is a great explanation.
A:
It became urllib.request.ProxyHandler.
2to3 can do this for you.
| Python 2.6 -> Python 3 (ProxyHandler) | I wrote a script that works with a proxy (py2.6x):
proxy_support = urllib2.ProxyHandler({'http' : 'http://127.0.0.1:80'})
But in py3.11x there is no urllib2 just a urllib... and that doesn't support the ProxyHandler
How can I use a proxy with urllib? Isn't Python 3 newer then Python 2? Why did they remove urllib2 in a newer version?
| [
"In Python 3, urllib2.ProxyHandler is now urllib.request.ProxyHandler.\nimport urllib.request\nproxy_support = urllib.request.ProxyHandler({'http' : 'http://127.0.0.1:80'})\n\nMany of the old url*libs have been merged with theurllib package.\nHere is a great explanation.\n",
"It became urllib.request.ProxyHandler.\n2to3 can do this for you.\n"
] | [
10,
3
] | [] | [] | [
"python",
"python_3.x",
"urllib",
"urllib2"
] | stackoverflow_0002911042_python_python_3.x_urllib_urllib2.txt |
Q:
create a gtk.window under a gtk.widget
I wanna show a gtk.Window under a gtk.widget.
But I don't know how to retrieve the gtk.widget's coordinates for my gtk.window.
Anyone knows ?
Thanks.
A:
You can use the "window" attribute of the gtk.Widget to get the gtk.gdk.Window associated with it. Then look at the get_origin() method to get the screen coordinates.
These coordinates are for the top-level window, I believe (I could be wrong about that, but my code below seems to support that). You can use the get_allocation() method to get the coordinates of a widget relative to its parent.
I got the idea from here. Be warned though: some window managers ignore any initial settings for window position. You might want to look at this post for more info, but I haven't personally checked it out.
Were you intending to create another top-level window? Or a popup window?
#!/usr/bin/env python
import sys
import pygtk
import gtk
class Base:
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.on_destroy)
self.box = gtk.VButtonBox()
self.buttons = [
gtk.Button("Test 1"),
gtk.Button("Test 2"),
gtk.Button("Test 3")
]
for button in self.buttons:
self.box.add(button)
button.connect("clicked", self.show_coords)
button.show()
self.window.add(self.box)
self.box.show()
self.window.show()
def show_coords(self, widget, data=None):
print "Window coords:"
print self.window.get_window().get_origin()
print "Button coords:"
print widget.get_allocation()
def on_destroy(self, widget, data=None):
gtk.main_quit()
def main(self):
gtk.main()
if __name__ == "__main__":
base = Base()
base.main()
| create a gtk.window under a gtk.widget | I wanna show a gtk.Window under a gtk.widget.
But I don't know how to retrieve the gtk.widget's coordinates for my gtk.window.
Anyone knows ?
Thanks.
| [
"You can use the \"window\" attribute of the gtk.Widget to get the gtk.gdk.Window associated with it. Then look at the get_origin() method to get the screen coordinates.\nThese coordinates are for the top-level window, I believe (I could be wrong about that, but my code below seems to support that). You can use the get_allocation() method to get the coordinates of a widget relative to its parent.\nI got the idea from here. Be warned though: some window managers ignore any initial settings for window position. You might want to look at this post for more info, but I haven't personally checked it out.\nWere you intending to create another top-level window? Or a popup window?\n#!/usr/bin/env python\nimport sys\n\nimport pygtk\nimport gtk\n\nclass Base:\n def __init__(self):\n self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n\n self.window.connect(\"destroy\", self.on_destroy)\n\n self.box = gtk.VButtonBox()\n\n self.buttons = [\n gtk.Button(\"Test 1\"),\n gtk.Button(\"Test 2\"),\n gtk.Button(\"Test 3\")\n ]\n\n for button in self.buttons:\n self.box.add(button)\n button.connect(\"clicked\", self.show_coords)\n button.show()\n\n self.window.add(self.box)\n\n self.box.show()\n self.window.show()\n\n def show_coords(self, widget, data=None):\n print \"Window coords:\"\n print self.window.get_window().get_origin()\n print \"Button coords:\"\n print widget.get_allocation()\n\n def on_destroy(self, widget, data=None):\n gtk.main_quit()\n\n def main(self):\n gtk.main()\n\nif __name__ == \"__main__\":\n base = Base()\n base.main()\n\n"
] | [
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0002893323_pygtk_python.txt |
Q:
How to get the related_name of a many-to-many-field?
I'm trying to get the related_name of a many-to-many-field. The m2m-field is located betweeen the models "Group" and "Lection" and is defined in the group-model as following:
lections = models.ManyToManyField(Lection, blank=True)
The field looks like this:
<django.db.models.fields.related.ManyToManyField object at 0x012AD690>
The print of field.__dict__ is:
{'_choices': [],
'_m2m_column_cache': 'group_id',
'_m2m_name_cache': 'group',
'_m2m_reverse_column_cache': 'lection_id',
'_m2m_reverse_name_cache': 'lection',
'_unique': False,
'attname': 'lections',
'auto_created': False,
'blank': True,
'column': 'lections',
'creation_counter': 71,
'db_column': None,
'db_index': False,
'db_table': None,
'db_tablespace': '',
'default': <class django.db.models.fields.NOT_PROVIDED at 0x00FC8780>,
'editable': True,
'error_messages': {'blank': <django.utils.functional.__proxy__ object at 0x00FC
7B50>,
'invalid_choice': <django.utils.functional.__proxy__ object
at 0x00FC7A50>,
'null': <django.utils.functional.__proxy__ object at 0x00FC7
A70>},
'help_text': <django.utils.functional.__proxy__ object at 0x012AD6F0>,
'm2m_column_name': <function _curried at 0x012A88F0>,
'm2m_db_table': <function _curried at 0x012A8AF0>,
'm2m_field_name': <function _curried at 0x012A8970>,
'm2m_reverse_field_name': <function _curried at 0x012A89B0>,
'm2m_reverse_name': <function _curried at 0x012A8930>,
'max_length': None,
'name': 'lections',
'null': False,
'primary_key': False,
'rel': <django.db.models.fields.related.ManyToManyRel object at 0x012AD6B0>,
'related': <RelatedObject: mymodel:group related to lections>,
'related_query_name': <function _curried at 0x012A8670>,
'serialize': True,
'unique_for_date': None,
'unique_for_month': None,
'unique_for_year': None,
'validators': [],
'verbose_name': 'lections'}
Now the field should be accessed via a lection-instance. So this is done by lection.group_set
But i need to access it dynamically, so there is the need to get the related_name attribute from somewhere.
Here in the documentation, there is a note that it is possible to access ManyToManyField.related_name, but this doesn't work for my somehow..
Help would be a lot appreciated.
Thanks in advance.
Edit:
Is there a need to put a class above all my models, which specifies the related_name attribute and so, every model has a similar name? like here maybe? -> docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
A:
Try:
field.related_query_name()
A:
What you pasted is basically:
>>> f = models.ManyToManyField(...)
>>> dir(f)
(...)
What you probably need, is to get an actual model class containing that field:
class MyModel(models.Model):
my_field = models.ManyToManyField(..., related_name='some_related_name')
-- and then you can do:
>>> MyModel._meta.get_field_by_name('my_field')[0].related_query_name()
'some_related_name'
A:
I've used object.yourmanagerclass.join_table in the past, but note that this returns a quoted string
| How to get the related_name of a many-to-many-field? | I'm trying to get the related_name of a many-to-many-field. The m2m-field is located betweeen the models "Group" and "Lection" and is defined in the group-model as following:
lections = models.ManyToManyField(Lection, blank=True)
The field looks like this:
<django.db.models.fields.related.ManyToManyField object at 0x012AD690>
The print of field.__dict__ is:
{'_choices': [],
'_m2m_column_cache': 'group_id',
'_m2m_name_cache': 'group',
'_m2m_reverse_column_cache': 'lection_id',
'_m2m_reverse_name_cache': 'lection',
'_unique': False,
'attname': 'lections',
'auto_created': False,
'blank': True,
'column': 'lections',
'creation_counter': 71,
'db_column': None,
'db_index': False,
'db_table': None,
'db_tablespace': '',
'default': <class django.db.models.fields.NOT_PROVIDED at 0x00FC8780>,
'editable': True,
'error_messages': {'blank': <django.utils.functional.__proxy__ object at 0x00FC
7B50>,
'invalid_choice': <django.utils.functional.__proxy__ object
at 0x00FC7A50>,
'null': <django.utils.functional.__proxy__ object at 0x00FC7
A70>},
'help_text': <django.utils.functional.__proxy__ object at 0x012AD6F0>,
'm2m_column_name': <function _curried at 0x012A88F0>,
'm2m_db_table': <function _curried at 0x012A8AF0>,
'm2m_field_name': <function _curried at 0x012A8970>,
'm2m_reverse_field_name': <function _curried at 0x012A89B0>,
'm2m_reverse_name': <function _curried at 0x012A8930>,
'max_length': None,
'name': 'lections',
'null': False,
'primary_key': False,
'rel': <django.db.models.fields.related.ManyToManyRel object at 0x012AD6B0>,
'related': <RelatedObject: mymodel:group related to lections>,
'related_query_name': <function _curried at 0x012A8670>,
'serialize': True,
'unique_for_date': None,
'unique_for_month': None,
'unique_for_year': None,
'validators': [],
'verbose_name': 'lections'}
Now the field should be accessed via a lection-instance. So this is done by lection.group_set
But i need to access it dynamically, so there is the need to get the related_name attribute from somewhere.
Here in the documentation, there is a note that it is possible to access ManyToManyField.related_name, but this doesn't work for my somehow..
Help would be a lot appreciated.
Thanks in advance.
Edit:
Is there a need to put a class above all my models, which specifies the related_name attribute and so, every model has a similar name? like here maybe? -> docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
| [
"Try:\nfield.related_query_name()\n\n",
"What you pasted is basically:\n>>> f = models.ManyToManyField(...)\n>>> dir(f)\n(...)\n\nWhat you probably need, is to get an actual model class containing that field:\nclass MyModel(models.Model):\n my_field = models.ManyToManyField(..., related_name='some_related_name')\n\n-- and then you can do:\n>>> MyModel._meta.get_field_by_name('my_field')[0].related_query_name()\n'some_related_name'\n\n",
"I've used object.yourmanagerclass.join_table in the past, but note that this returns a quoted string\n"
] | [
6,
3,
0
] | [] | [] | [
"django",
"django_models",
"m2m",
"many_to_many",
"python"
] | stackoverflow_0002850376_django_django_models_m2m_many_to_many_python.txt |
Q:
What are some useful TextMate features?
I noticed that many people here use TextMate for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for.
So, what feature have you found most helpful for coding (mainly in Python)? Are there any third-party bundles I should know about, besides what's included?
A:
Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following...
diff file1.py file2.py | mate
...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen.
TextMate's SVN integration is great; it also seems to have bundles for some other version control systems as well.
Add GetBundle to browse the bundle repository. I found the jQuery bundle through it and it's very handy.
As others have mentioned, rolling your own bundle for frequently used snippets is very helpful. If you have some snippets that are specific to a project or framework, you might want to prefix all of them with a common letter to keep the namespace tidy.
A:
Holding down option while dragging allows you to highlight a block of text. If you type while the highlight is active, your keystrokes appear on multiple lines.
A:
Being able to write simple commands in any scripting language and bind them to a context-specific hotkey.
A:
The Navigation menu commands Go to File (Command + T) and Go to Symbol (Command + Shift + T) are both extremely helpful.
Go to File, which works when you have a project open, lets you type any part of the file name to see only files that match what you've typed.
Go to Symbol has the same type-to-filter interface, but operates on what I'd call the basic block elements of your document. For example, if you're editing a class, Go to Symbol works on the method names, but in a CSS document, you'll be searching on your selectors. It's pretty awesome.
A:
I mention some in a review on Boagworld, I find the snippets, project manager, columnar editing (hold down option while selecting stuff or push it after having selected stuff) and CSS scopes for syntax.
A:
I like the integrated HTML/XML Tidy. Cmd-shift-H is your friend.
Also, nice integration with a variety of scp/sftp clients.
A:
My favourite two features are auto-completion (bound to ⎋ [esc]), and column editing (bound to ⌥ [alt]) both of these things save me quite a lot of time, and are definitely 'robot ninjas'.
The book linked above is also a really useful into to the power of TextMate, although it doesn't specifically mention python.
A:
Don't forget "Drag commands".
They give you the ability to drag, say, an image into a blog.html document and will then upload it to the proper folder and insert the markup for you.
Here is another example of how you can expand further on drag commands if you pair TM up with QuickSilver.
(Disclaimer: I wrote the blog post I linked to there. I still think it's cool though.)
A:
It is worth noting here that there is a Windows alternative to TextMate called E Text Editor. It does pretty much everything TextMate does (apart from macros, but the author is working on this, I think), and even - shock, horror - does some things better, such as the superb bundles editor, the bundles manager, and the branching undo history. Update: and now there's Snippet Pipes.
So, not exactly a useful feature of TextMate as such, but very useful to know if you're a fan of TextMate and you have to use Windows for whatever reason.
A:
The ease of snippet creation.
It's trivial to create new snippets that can accomplish a lot using replacements, tabbing order, and regex substitutions. Quickly assigning these to the tab key for specific languages makes me more productive. And makes me worry about code bloat. :-)
A:
For me the best features are:
Projects - I know every IDE under
the sun has this but TextMate makes
this useful for all sorts of editing
and text processing tasks, and
moreover makes navigating around
these projects easy without ever
lifting your hands from the
keyboard. This is huge for Rails or
Grails projects or large programming
projects with many modules.
The excellent syntax highlighting
and 'snippets' for myriad languages
and tools
The excellent scripting language
support (Being able to evaluate
chunks of Ruby and the like with a
single key chord)
The built in Blogging bundle is
superb. I now use TextMate
exclusively for all my blog posts.
Columnar editing
The ability to use just about any
language or tool to extend TextMate,
Ruby, Perl, shell, name your poison.
An excellent mix of great Aqua GUI
support and excellent command line
support through the
mate and
commands, for
instance making it easy and pleasant
to use TextMate as your default
editor for your SCM.
A:
Using snippets to expand into large, repetitive blocks of code and then using the tab key to move through and only edit the pieces I need to without having to use the mouse or arrow keys.
A:
It's nice and lightweight and has all of the macros built-in for Ruby and let's you run Ruby code, or any other code for that matter just with a keystroke.
A:
Check out ProjectPlus, it gives some useful options for the sidebar, it has SCM status badges for svn and git (though I find the git thing a bit buggy).
I like the fact that it can change the sidebar to an embedded panel on left or right (as opposed to the drawer that's default).
A:
If, like me, you're borderline OCD when it comes to making code look neat, then Option+Cmd+] to line up all the assignments around the current line is awesome!
A:
The mate command line tool is great, you can open an individual file or my favourite use of it is to open a directory of files as a project (e.g. mate .)
A:
Checkout Zen Coding bundle . It gives you an awesome productivity boost to developing both HTML and CSS.
| What are some useful TextMate features? | I noticed that many people here use TextMate for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for.
So, what feature have you found most helpful for coding (mainly in Python)? Are there any third-party bundles I should know about, besides what's included?
| [
"Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following...\ndiff file1.py file2.py | mate\n\n...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen.\nTextMate's SVN integration is great; it also seems to have bundles for some other version control systems as well.\nAdd GetBundle to browse the bundle repository. I found the jQuery bundle through it and it's very handy.\nAs others have mentioned, rolling your own bundle for frequently used snippets is very helpful. If you have some snippets that are specific to a project or framework, you might want to prefix all of them with a common letter to keep the namespace tidy.\n",
"Holding down option while dragging allows you to highlight a block of text. If you type while the highlight is active, your keystrokes appear on multiple lines. \n",
"Being able to write simple commands in any scripting language and bind them to a context-specific hotkey.\n",
"The Navigation menu commands Go to File (Command + T) and Go to Symbol (Command + Shift + T) are both extremely helpful. \nGo to File, which works when you have a project open, lets you type any part of the file name to see only files that match what you've typed. \nGo to Symbol has the same type-to-filter interface, but operates on what I'd call the basic block elements of your document. For example, if you're editing a class, Go to Symbol works on the method names, but in a CSS document, you'll be searching on your selectors. It's pretty awesome.\n",
"I mention some in a review on Boagworld, I find the snippets, project manager, columnar editing (hold down option while selecting stuff or push it after having selected stuff) and CSS scopes for syntax.\n",
"I like the integrated HTML/XML Tidy. Cmd-shift-H is your friend.\nAlso, nice integration with a variety of scp/sftp clients.\n",
"My favourite two features are auto-completion (bound to ⎋ [esc]), and column editing (bound to ⌥ [alt]) both of these things save me quite a lot of time, and are definitely 'robot ninjas'.\nThe book linked above is also a really useful into to the power of TextMate, although it doesn't specifically mention python.\n",
"Don't forget \"Drag commands\".\nThey give you the ability to drag, say, an image into a blog.html document and will then upload it to the proper folder and insert the markup for you.\nHere is another example of how you can expand further on drag commands if you pair TM up with QuickSilver.\n(Disclaimer: I wrote the blog post I linked to there. I still think it's cool though.)\n",
"It is worth noting here that there is a Windows alternative to TextMate called E Text Editor. It does pretty much everything TextMate does (apart from macros, but the author is working on this, I think), and even - shock, horror - does some things better, such as the superb bundles editor, the bundles manager, and the branching undo history. Update: and now there's Snippet Pipes.\nSo, not exactly a useful feature of TextMate as such, but very useful to know if you're a fan of TextMate and you have to use Windows for whatever reason.\n",
"The ease of snippet creation.\nIt's trivial to create new snippets that can accomplish a lot using replacements, tabbing order, and regex substitutions. Quickly assigning these to the tab key for specific languages makes me more productive. And makes me worry about code bloat. :-)\n",
"For me the best features are:\n\nProjects - I know every IDE under\nthe sun has this but TextMate makes\nthis useful for all sorts of editing\nand text processing tasks, and\nmoreover makes navigating around\nthese projects easy without ever\nlifting your hands from the\nkeyboard. This is huge for Rails or\nGrails projects or large programming\nprojects with many modules.\nThe excellent syntax highlighting\nand 'snippets' for myriad languages\nand tools\nThe excellent scripting language\nsupport (Being able to evaluate\nchunks of Ruby and the like with a\nsingle key chord)\nThe built in Blogging bundle is\nsuperb. I now use TextMate\nexclusively for all my blog posts.\nColumnar editing\nThe ability to use just about any\nlanguage or tool to extend TextMate,\nRuby, Perl, shell, name your poison.\nAn excellent mix of great Aqua GUI\nsupport and excellent command line\nsupport through the\nmate and\n commands, for\ninstance making it easy and pleasant\nto use TextMate as your default\neditor for your SCM.\n\n",
"Using snippets to expand into large, repetitive blocks of code and then using the tab key to move through and only edit the pieces I need to without having to use the mouse or arrow keys.\n",
"It's nice and lightweight and has all of the macros built-in for Ruby and let's you run Ruby code, or any other code for that matter just with a keystroke.\n",
"Check out ProjectPlus, it gives some useful options for the sidebar, it has SCM status badges for svn and git (though I find the git thing a bit buggy).\nI like the fact that it can change the sidebar to an embedded panel on left or right (as opposed to the drawer that's default).\n",
"If, like me, you're borderline OCD when it comes to making code look neat, then Option+Cmd+] to line up all the assignments around the current line is awesome!\n",
"The mate command line tool is great, you can open an individual file or my favourite use of it is to open a directory of files as a project (e.g. mate .)\n",
"Checkout Zen Coding bundle . It gives you an awesome productivity boost to developing both HTML and CSS.\n"
] | [
29,
15,
11,
11,
7,
5,
5,
5,
4,
3,
3,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"macos",
"python",
"text_editor",
"textmate"
] | stackoverflow_0000033813_macos_python_text_editor_textmate.txt |
Q:
Best way to handle timed events in PyGame
I'm working on a Tetris-clone type game and I'm wondering what would be the best way to handle the logic that moves the blocks down every N seconds. I initially did it the easy way:
pygame.time.set_timer(USEREVENT+1, 300)
This will of course add a PyGame event to the queue every 300 milliseconds. In the main loop I can test for this event, and drop the block down when it occurs. The problem with this approach is that the player can easily flood the queue with keyboard generated events. I noticed that player can essentially keep the block at the same height indefinitely by simply rapidly pressing the up-arrow which flips it around. It doesn't seem to matter that the code testing for timer event is evaluated before the test for keyboard events. Somehow keyboard always gets higher priority than the timer. Any idea how to prevent this from happening?
And if this is unavoidable quirk of pygame.time what would be a better way to handle the timed events?
Check elapsed time on each loop iteration and advance blocks if it is greater than a certain value?
Use sched or something similar running in a separate thread and signaling back via some shared resource?
Any ideas?
A:
Here's how a typical game loop works:
repeat forever:
read all pending events
if current time > last frame + frame time:
last frame = last frame + frame time
update game
redraw screen
A timer that is supposed to fire every 300 ms but doesn't work if the user floods the game with events could be a broken timer. However, if you redraw the screen on every user event instead of redrawing the screen once you've processed all pending events, then your code is the problem.
Here's an example of a broken version of a game loop:
repeat forever:
read the next pending event
if current time > last frame + frame time:
last frame = last frame + frame time
update game
redraw screen
It's broken because it tries to redraw the screen far too often. If the player presses two keys at the same time, they'll get separated into different frames, which is unnecessary.
The above loops assume that you want to draw to the screen as often as possible. This is very common, but you might want to draw to the screen less often. Your method of using events should be fine as long as you grab all pending events before redrawing the screen.
P.S. Do NOT use multiple threads to solve this problem. That would cause a huge mess.
A:
One correction to Dietrich Epp's answer - redraw screen should actually interpolate or extrapolate between two subsequent game states. This is needed to provide smooth experience to players.
In case of interpolation, as an interpolation factor you use time fraction that is "left" from updating (because it's less than frame time) divided by frame time to get result in [0..1] range.
This is also known as a canonical game loop
| Best way to handle timed events in PyGame | I'm working on a Tetris-clone type game and I'm wondering what would be the best way to handle the logic that moves the blocks down every N seconds. I initially did it the easy way:
pygame.time.set_timer(USEREVENT+1, 300)
This will of course add a PyGame event to the queue every 300 milliseconds. In the main loop I can test for this event, and drop the block down when it occurs. The problem with this approach is that the player can easily flood the queue with keyboard generated events. I noticed that player can essentially keep the block at the same height indefinitely by simply rapidly pressing the up-arrow which flips it around. It doesn't seem to matter that the code testing for timer event is evaluated before the test for keyboard events. Somehow keyboard always gets higher priority than the timer. Any idea how to prevent this from happening?
And if this is unavoidable quirk of pygame.time what would be a better way to handle the timed events?
Check elapsed time on each loop iteration and advance blocks if it is greater than a certain value?
Use sched or something similar running in a separate thread and signaling back via some shared resource?
Any ideas?
| [
"Here's how a typical game loop works:\nrepeat forever:\n read all pending events\n if current time > last frame + frame time:\n last frame = last frame + frame time\n update game\n redraw screen\n\nA timer that is supposed to fire every 300 ms but doesn't work if the user floods the game with events could be a broken timer. However, if you redraw the screen on every user event instead of redrawing the screen once you've processed all pending events, then your code is the problem.\nHere's an example of a broken version of a game loop:\nrepeat forever:\n read the next pending event\n if current time > last frame + frame time:\n last frame = last frame + frame time\n update game\n redraw screen\n\nIt's broken because it tries to redraw the screen far too often. If the player presses two keys at the same time, they'll get separated into different frames, which is unnecessary.\nThe above loops assume that you want to draw to the screen as often as possible. This is very common, but you might want to draw to the screen less often. Your method of using events should be fine as long as you grab all pending events before redrawing the screen.\nP.S. Do NOT use multiple threads to solve this problem. That would cause a huge mess.\n",
"One correction to Dietrich Epp's answer - redraw screen should actually interpolate or extrapolate between two subsequent game states. This is needed to provide smooth experience to players. \nIn case of interpolation, as an interpolation factor you use time fraction that is \"left\" from updating (because it's less than frame time) divided by frame time to get result in [0..1] range.\nThis is also known as a canonical game loop\n"
] | [
3,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0002908397_pygame_python.txt |
Q:
wxPython formatting questions
I have an app I was working on to learn more about wxPython( I have been primarily been a scripter ). I forgot about it now I am opening it back up. It's a screen scraper, and I have it working almost the way I want it, going to build a regex parser to strip out the links in every scrape that I don't need. The questions I have are this. In it current state, if I check more than one site, it goes out and scrapes, and returns it in separate windows, the for:each section in the Clicked function. I want to put them in a frame, in the window, altogether. I also want to know if I can take the list they are read into and send it to a checklist, so someone could check off separate items, I want to build a save function and keep certain ones. In regards to a save function, I want to keep saved checks, are there calls to the widgets to save their states? I know it's a lot, but thanks for the help.
EDIT (forgot code)
import wx
import urllib2
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import Tag
import re
from pyparsing import makeHTMLTags, originalTextFor, SkipTo, Combine
import wx
import wx.html
global P
siteDict = {0:'http://www.reddit.com', 1:'http://www.boston.com', 2:'http://www.stumbleupon.com', 3:'news.google.com'}
class citPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
allSites = ['Reddit', 'Boston.com', 'StumbleUpon', 'Google News']
wx.StaticText(self, -1, "Choose the Sites you would like Charlie to Visit:", (45, 15))
self.sitList = wx.CheckListBox(self, 20, (60, 50), wx.DefaultSize, allSites)
class nextButton(wx.Button):
def __init__(self, parent, id, label, pos):
wx.Button.__init__(self, parent, id, label, pos)
class checkList(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(400, 300))
self.panel = citPanel(self, -1)
nextButton(self.panel, 30, 'Ok', (275, 50))
self.Bind(wx.EVT_BUTTON, self.Clicked)
self.Centre()
self.Show(True)
def Clicked(self, event):
checkedItems = [i for i in range(self.panel.sitList.GetCount()) if self.panel.sitList.IsChecked(i)]
print checkedItems
r = [siteDict[k] for k in checkedItems]
print r
for each in r:
pre = '<HTML><head><title>Page title</title></head>'
post = '</HTML>'
site = urllib2.urlopen(each)
html=site.read()
soup = BeautifulSoup(html)
tags = soup.findAll('a')
soup1 = BeautifulSoup(''.join(str(t) for t in tags))
for link in soup1.findAll('a'):
br= Tag(soup, 'p')
index= link.parent.contents.index(link)
link.parent.insert(index+1, br)
P = soup1.prettify()
print P
#for link2 in soup1.findAll('a'):
#p1= Tag(soup, '
frm = MyHtmlFrame(None, "Charlie", P)
frm.Show()
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title, page):
wx.Frame.__init__(self, parent, -1, title)
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
html.SetPage(page)
#app = wx.PySimpleApp()
#app.MainLoop()
#event.Skip()
#self.Destroy()
app = wx.App()
checkList(None, -1, 'Charlie')
app.MainLoop()
A:
You could create a single answer panel or frame (start with a separate frame, like you are doing now - MyHtmlFrame is fine). Don't create a new panel or frame for every result.
Create a `wx.ComboBox(self, -1, choices=['google','so']) somewhere, and bind self.Bind(wx.EVT_COMBOBOX, myHtmlFrame.setFrame).
Now you need to write MyHtmlFrame.setFrame(self,event); use choice = event.GetSelection(), then self.html.SetPage(self.results_dict[choice])
Oh, and attach a dictionary (results_dict) on MyHtmlFrame, mapping the choice ("google") to the scraper result.
Unless you want the combo-box in a separate frame, you'll have to learn how to use wx.Sizers.
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title, page, results_dict):
wx.Frame.__init__(self, parent, -1, title)
self.html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
self.html.SetStandardFonts()
self.results_dict=results_dict #here
self.html.SetPage('')
def setFrame(self,event):
self.html.SetPage(self.results_dict[choice])
| wxPython formatting questions | I have an app I was working on to learn more about wxPython( I have been primarily been a scripter ). I forgot about it now I am opening it back up. It's a screen scraper, and I have it working almost the way I want it, going to build a regex parser to strip out the links in every scrape that I don't need. The questions I have are this. In it current state, if I check more than one site, it goes out and scrapes, and returns it in separate windows, the for:each section in the Clicked function. I want to put them in a frame, in the window, altogether. I also want to know if I can take the list they are read into and send it to a checklist, so someone could check off separate items, I want to build a save function and keep certain ones. In regards to a save function, I want to keep saved checks, are there calls to the widgets to save their states? I know it's a lot, but thanks for the help.
EDIT (forgot code)
import wx
import urllib2
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import Tag
import re
from pyparsing import makeHTMLTags, originalTextFor, SkipTo, Combine
import wx
import wx.html
global P
siteDict = {0:'http://www.reddit.com', 1:'http://www.boston.com', 2:'http://www.stumbleupon.com', 3:'news.google.com'}
class citPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
allSites = ['Reddit', 'Boston.com', 'StumbleUpon', 'Google News']
wx.StaticText(self, -1, "Choose the Sites you would like Charlie to Visit:", (45, 15))
self.sitList = wx.CheckListBox(self, 20, (60, 50), wx.DefaultSize, allSites)
class nextButton(wx.Button):
def __init__(self, parent, id, label, pos):
wx.Button.__init__(self, parent, id, label, pos)
class checkList(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(400, 300))
self.panel = citPanel(self, -1)
nextButton(self.panel, 30, 'Ok', (275, 50))
self.Bind(wx.EVT_BUTTON, self.Clicked)
self.Centre()
self.Show(True)
def Clicked(self, event):
checkedItems = [i for i in range(self.panel.sitList.GetCount()) if self.panel.sitList.IsChecked(i)]
print checkedItems
r = [siteDict[k] for k in checkedItems]
print r
for each in r:
pre = '<HTML><head><title>Page title</title></head>'
post = '</HTML>'
site = urllib2.urlopen(each)
html=site.read()
soup = BeautifulSoup(html)
tags = soup.findAll('a')
soup1 = BeautifulSoup(''.join(str(t) for t in tags))
for link in soup1.findAll('a'):
br= Tag(soup, 'p')
index= link.parent.contents.index(link)
link.parent.insert(index+1, br)
P = soup1.prettify()
print P
#for link2 in soup1.findAll('a'):
#p1= Tag(soup, '
frm = MyHtmlFrame(None, "Charlie", P)
frm.Show()
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title, page):
wx.Frame.__init__(self, parent, -1, title)
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
html.SetPage(page)
#app = wx.PySimpleApp()
#app.MainLoop()
#event.Skip()
#self.Destroy()
app = wx.App()
checkList(None, -1, 'Charlie')
app.MainLoop()
| [
"You could create a single answer panel or frame (start with a separate frame, like you are doing now - MyHtmlFrame is fine). Don't create a new panel or frame for every result.\nCreate a `wx.ComboBox(self, -1, choices=['google','so']) somewhere, and bind self.Bind(wx.EVT_COMBOBOX, myHtmlFrame.setFrame).\nNow you need to write MyHtmlFrame.setFrame(self,event); use choice = event.GetSelection(), then self.html.SetPage(self.results_dict[choice])\n\nOh, and attach a dictionary (results_dict) on MyHtmlFrame, mapping the choice (\"google\") to the scraper result.\nUnless you want the combo-box in a separate frame, you'll have to learn how to use wx.Sizers.\nclass MyHtmlFrame(wx.Frame):\n def __init__(self, parent, title, page, results_dict):\n wx.Frame.__init__(self, parent, -1, title)\n self.html = wx.html.HtmlWindow(self)\n if \"gtk2\" in wx.PlatformInfo:\n self.html.SetStandardFonts()\n self.results_dict=results_dict #here\n\n self.html.SetPage('')\n\n def setFrame(self,event):\n self.html.SetPage(self.results_dict[choice])\n\n"
] | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002906561_python_wxpython.txt |
Q:
Generic unit test scheduling
I'm (re)writing a program that does generic unit test scheduling. The current program is a mono-threaded Perl program, but I'm willing to modularize it and parallelize the tests. I'm also considering rewriting it in Python.
Here is what I need to do:
I have a list of tests, with the following attributes:
uri: a URI to test (could be HTTP/HTTPS/SSH/local) ;
depends: an associative array of tests/values that this test depends on ;
join: a list of DB joints to be added when selecting items to process in this test ;
depends_db: additional conditions to add to the DB request when selecting items to process in this test.
The program builds a dependency tree, beginning with the tests that have no dependencies ;
for each test:
a list of items is selected from the database using the conditions (results of depending tests, joints and depends_db) ;
the list of items is sent to the URI (using POST or stdin) ;
the result is retrived as a YAML file listing the state and comments for the test for each tested item ;
the results are stored in the DB ;
the test returns, allowing depending tests to be performed.
the program generates reports (CSV, DB, graphviz) of the performed tests.
The primary use of this program currently is to test a fleet of machines against services such as backup, DNS, etc. The tests can then be:
- backup: hosted on the backup machine(s), called through HTTP, checks if the machines' backup went well ;
- DNS: hosted on the local machine, called via stdin, checks if the machines' fqdn have a valid DNS entry.
Does such a tool/module already exist? What would be the best implementation to achieve this (using Perl or Python)?
A:
This sort of testing is not unit testing.
If you decide not to follow rjh's advice in order to keep most of the code you've already written, then convert your tests to use the standard test toolchain.
Use Test::Class and friends to emit TAP.
Use prove's -j option or Test::Aggregate to run tests in parallel.
Use prove's -a option or App::Prove::History to record results.
Use TAP::Formatter::HTML for graphical reporting.
| Generic unit test scheduling | I'm (re)writing a program that does generic unit test scheduling. The current program is a mono-threaded Perl program, but I'm willing to modularize it and parallelize the tests. I'm also considering rewriting it in Python.
Here is what I need to do:
I have a list of tests, with the following attributes:
uri: a URI to test (could be HTTP/HTTPS/SSH/local) ;
depends: an associative array of tests/values that this test depends on ;
join: a list of DB joints to be added when selecting items to process in this test ;
depends_db: additional conditions to add to the DB request when selecting items to process in this test.
The program builds a dependency tree, beginning with the tests that have no dependencies ;
for each test:
a list of items is selected from the database using the conditions (results of depending tests, joints and depends_db) ;
the list of items is sent to the URI (using POST or stdin) ;
the result is retrived as a YAML file listing the state and comments for the test for each tested item ;
the results are stored in the DB ;
the test returns, allowing depending tests to be performed.
the program generates reports (CSV, DB, graphviz) of the performed tests.
The primary use of this program currently is to test a fleet of machines against services such as backup, DNS, etc. The tests can then be:
- backup: hosted on the backup machine(s), called through HTTP, checks if the machines' backup went well ;
- DNS: hosted on the local machine, called via stdin, checks if the machines' fqdn have a valid DNS entry.
Does such a tool/module already exist? What would be the best implementation to achieve this (using Perl or Python)?
| [
"This sort of testing is not unit testing.\nIf you decide not to follow rjh's advice in order to keep most of the code you've already written, then convert your tests to use the standard test toolchain.\n\nUse Test::Class and friends to emit TAP.\nUse prove's -j option or Test::Aggregate to run tests in parallel.\nUse prove's -a option or App::Prove::History to record results.\nUse TAP::Formatter::HTML for graphical reporting.\n\n"
] | [
4
] | [] | [] | [
"dependencies",
"perl",
"python",
"tree",
"unit_testing"
] | stackoverflow_0002911462_dependencies_perl_python_tree_unit_testing.txt |
Q:
Installing Python in Windows XP
My work PC has restrictions that stop me from adding programs to the start menu so when I try to install Python using the Python 2.6.5 Windows installer it can't complete as it tries to add a shortcut to my start menu.
Is there a way around this? I.e another way of installing without the need for a shortcut?
Edit:
I'll also need to install NumPy which I can't do on the Portable version of Python.
Ignore me, Python portable comes with NumPy installed.
A:
http://www.portablepython.com/
Or get Ubuntu.
| Installing Python in Windows XP | My work PC has restrictions that stop me from adding programs to the start menu so when I try to install Python using the Python 2.6.5 Windows installer it can't complete as it tries to add a shortcut to my start menu.
Is there a way around this? I.e another way of installing without the need for a shortcut?
Edit:
I'll also need to install NumPy which I can't do on the Portable version of Python.
Ignore me, Python portable comes with NumPy installed.
| [
"http://www.portablepython.com/\nOr get Ubuntu.\n"
] | [
2
] | [] | [] | [
"python",
"windows_installer",
"windows_xp"
] | stackoverflow_0002911946_python_windows_installer_windows_xp.txt |
Q:
How does py2exe actually -and simply explained- work? :)
I have a c++ app that calls another python one (bundled into an exe with py2exe)
So I have 2 apps.
So I was wondering: What if my c++ did what py2exe does?
i.e. embed the python app in the c++ one. This way I won't depend on py2exe and its
configurations nighmares (yes, it has some)
Hence my questions:
how does py2exe work (so I can do its job with my c++ app)
What about just embedding the whole python app with the c++? I read the python doc about embedding, did an example (a very simple one that does PyRun_SimpleString) but what about a whole python app with tons of modules? (zipimport maybe?)
I'd love to hear how you'd do that.
Thanks a lot! :)
A:
http://www.py2exe.org/index.cgi/FAQ
Basically, it packages up your python install and redistributes it. It still runs your Python as Python on a Python interpreter. The exe it creates just kicks everything off.
The Python website has some methods on integrating with C++.
| How does py2exe actually -and simply explained- work? :) | I have a c++ app that calls another python one (bundled into an exe with py2exe)
So I have 2 apps.
So I was wondering: What if my c++ did what py2exe does?
i.e. embed the python app in the c++ one. This way I won't depend on py2exe and its
configurations nighmares (yes, it has some)
Hence my questions:
how does py2exe work (so I can do its job with my c++ app)
What about just embedding the whole python app with the c++? I read the python doc about embedding, did an example (a very simple one that does PyRun_SimpleString) but what about a whole python app with tons of modules? (zipimport maybe?)
I'd love to hear how you'd do that.
Thanks a lot! :)
| [
"http://www.py2exe.org/index.cgi/FAQ\nBasically, it packages up your python install and redistributes it. It still runs your Python as Python on a Python interpreter. The exe it creates just kicks everything off.\nThe Python website has some methods on integrating with C++.\n"
] | [
3
] | [] | [] | [
"c++",
"embed",
"py2exe",
"python"
] | stackoverflow_0002912404_c++_embed_py2exe_python.txt |
Q:
traverse a binary decison tree using python?
how to traverse a binary decision tree using python language.
given a tree,i want know how can we travesre from root to required leaf
the feature of the required leaf are given in an dictionary form assume and have to traverse from root to leaf answering the questions at each node with the details given in feature list..
the decision tree node has format ((question)(left tree)(right tree))
while traversing it should answer question at each node and an choose left or right and traverse till leaf?
A:
def walk(node):
answer = ask(node.question)
if answer == left:
walk(node.left_tree)
else:
walk(node.right_tree)
def ask(question):
# get answer somehow
# depending on the answer choose which subtree to traverse
return answer
A:
@TheMachineCharmer is right: recursivity is the keyword here!
I'd add to the nice function given by @TheMachineCharmer a little return (the trivial case, where answer is neither left nor right)
def walk(node):
answer = ask(node.question)
if answer == left:
walk(node.left_tree)
else:
walk(node.right_tree)
return answer
This way if the node contains THE real answer it will return it.
| traverse a binary decison tree using python? | how to traverse a binary decision tree using python language.
given a tree,i want know how can we travesre from root to required leaf
the feature of the required leaf are given in an dictionary form assume and have to traverse from root to leaf answering the questions at each node with the details given in feature list..
the decision tree node has format ((question)(left tree)(right tree))
while traversing it should answer question at each node and an choose left or right and traverse till leaf?
| [
"def walk(node):\n answer = ask(node.question)\n if answer == left:\n walk(node.left_tree)\n else:\n walk(node.right_tree)\n\n\ndef ask(question):\n # get answer somehow\n # depending on the answer choose which subtree to traverse\n return answer\n\n",
"@TheMachineCharmer is right: recursivity is the keyword here!\nI'd add to the nice function given by @TheMachineCharmer a little return (the trivial case, where answer is neither left nor right)\ndef walk(node):\n answer = ask(node.question)\n if answer == left:\n walk(node.left_tree)\n else:\n walk(node.right_tree)\n return answer\n\nThis way if the node contains THE real answer it will return it.\n"
] | [
2,
0
] | [] | [] | [
"decision_tree",
"python",
"traversal"
] | stackoverflow_0002911706_decision_tree_python_traversal.txt |
Q:
Which Language to target on Ubuntu?
I'm a c# programmer by trade and looking to move my wares over to Ubuntu as a business concern. I have some experience of Python and like it a lot. My question is, as a developer which would be the best language to use when targeting ubuntu Mono c# or python as a commercial concern.
please note that I am not interested in the technical aspects but strictly the commercials of where Ubuntu is heading, I see that there is a lot of work done within using Python and thinking that maybe with the whole Mono issue of who "might" purchase them.
A:
Both Python and Mono are installed by default on recent Ubuntu, and will likely continue to be for the foreseeable future.
Mono is removable since it is currently only used by a few desktop apps. Python is not reasonably removable as a lot of core scripts and GNOME tools depend on it. (The same is true of Perl.)
The popularity contest shows Python to be installed somewhat more often than Mono but both are widespread:
21 python-minimal 1584305 182870 1381149 20211 75 (Matthias Klose)
577 mono-gac 1403534 25795 1323328 54159 252 (Debian Mono Group)
As for commercial potential, it's difficult to say without any idea what sector you might be working in. If you are targeting servers, especially running older versions of Ubuntu, Mono will be less widespread. If you are selling simple consumer desktop apps... well, it has yet to be demonstrated that there is really a market for this!
A:
I cannot say much about the market for Ubuntu. And since business is your primary concern, the programming language is, as you say yourself, secondary. I would say that in any business, choose the language and tools that solves the business problem most effectively. When release comes do your end users really care?
That said, if you can do it with Mono/C# I would encourage you to do so since you already have C# and .Net experience. But knowing a second language and development environment will only make you stronger.
| Which Language to target on Ubuntu? | I'm a c# programmer by trade and looking to move my wares over to Ubuntu as a business concern. I have some experience of Python and like it a lot. My question is, as a developer which would be the best language to use when targeting ubuntu Mono c# or python as a commercial concern.
please note that I am not interested in the technical aspects but strictly the commercials of where Ubuntu is heading, I see that there is a lot of work done within using Python and thinking that maybe with the whole Mono issue of who "might" purchase them.
| [
"Both Python and Mono are installed by default on recent Ubuntu, and will likely continue to be for the foreseeable future.\nMono is removable since it is currently only used by a few desktop apps. Python is not reasonably removable as a lot of core scripts and GNOME tools depend on it. (The same is true of Perl.)\nThe popularity contest shows Python to be installed somewhat more often than Mono but both are widespread:\n21 python-minimal 1584305 182870 1381149 20211 75 (Matthias Klose) \n577 mono-gac 1403534 25795 1323328 54159 252 (Debian Mono Group) \n\nAs for commercial potential, it's difficult to say without any idea what sector you might be working in. If you are targeting servers, especially running older versions of Ubuntu, Mono will be less widespread. If you are selling simple consumer desktop apps... well, it has yet to be demonstrated that there is really a market for this!\n",
"I cannot say much about the market for Ubuntu. And since business is your primary concern, the programming language is, as you say yourself, secondary. I would say that in any business, choose the language and tools that solves the business problem most effectively. When release comes do your end users really care?\nThat said, if you can do it with Mono/C# I would encourage you to do so since you already have C# and .Net experience. But knowing a second language and development environment will only make you stronger.\n"
] | [
4,
2
] | [] | [] | [
"c#",
"mono",
"python",
"ubuntu"
] | stackoverflow_0002912216_c#_mono_python_ubuntu.txt |
Q:
Login through twitter failiing as "unauthorized" in OSQA
I have installed OSQA on a site hosted on hostgator. The login functionality is working for google, yahoo and facebook, but when I click on twitter's icon it's generating an exception. I have already added the twitter consumer key and the twitter consumer secret through the admin interface. The exception I am getting is:
HTTPError at /account/twitter/signin/
HTTP Error 401: Unauthorized
Request Method: GET
Request URL: http://mydomain/account/twitter/signin/?validate_email=yes
Exception Type: HTTPError
Exception Value: HTTP Error 401: Unauthorized
Exception Location: /usr/lib/python2.4/urllib2.py in http_error_default, line 480
Python Executable: /usr/bin/python
Python Version: 2.4.3
I am unable to trace out the reason for the same.
What could be the reason for this error?
A:
I removed the earlier application created in twitter and created a new one. Added the new keys through administration panel and it resolved my issue.But i am still unable to figure out what caused problem in my earlier application?
| Login through twitter failiing as "unauthorized" in OSQA | I have installed OSQA on a site hosted on hostgator. The login functionality is working for google, yahoo and facebook, but when I click on twitter's icon it's generating an exception. I have already added the twitter consumer key and the twitter consumer secret through the admin interface. The exception I am getting is:
HTTPError at /account/twitter/signin/
HTTP Error 401: Unauthorized
Request Method: GET
Request URL: http://mydomain/account/twitter/signin/?validate_email=yes
Exception Type: HTTPError
Exception Value: HTTP Error 401: Unauthorized
Exception Location: /usr/lib/python2.4/urllib2.py in http_error_default, line 480
Python Executable: /usr/bin/python
Python Version: 2.4.3
I am unable to trace out the reason for the same.
What could be the reason for this error?
| [
"I removed the earlier application created in twitter and created a new one. Added the new keys through administration panel and it resolved my issue.But i am still unable to figure out what caused problem in my earlier application?\n"
] | [
0
] | [] | [] | [
"osqa",
"python",
"twitter"
] | stackoverflow_0002911495_osqa_python_twitter.txt |
Q:
Not getting the correct result back from inet_aton/struct.unpack
Using python 2.6.5 on Windows XP, it seems I'm getting the wrong result when using the following code:
import struct
import socket
struct.unpack('L', socket.inet_aton('192.168.1.1'))[0]
This returns 16885952 while to my knowledge it should return 3232235777.
Am I doing something wrong here? How do I fix this?
A:
You need to specify the endianess. Its interpreting the number as litle-endian, however inet_aton returns the number as big-endian.
struct.unpack('>L', socket.inet_aton('192.168.1.1'))[0]
This should work fine, and return the number you expected.
See the python documentation on "struct" for reference.
| Not getting the correct result back from inet_aton/struct.unpack | Using python 2.6.5 on Windows XP, it seems I'm getting the wrong result when using the following code:
import struct
import socket
struct.unpack('L', socket.inet_aton('192.168.1.1'))[0]
This returns 16885952 while to my knowledge it should return 3232235777.
Am I doing something wrong here? How do I fix this?
| [
"You need to specify the endianess. Its interpreting the number as litle-endian, however inet_aton returns the number as big-endian.\nstruct.unpack('>L', socket.inet_aton('192.168.1.1'))[0]\n\nThis should work fine, and return the number you expected.\nSee the python documentation on \"struct\" for reference.\n"
] | [
8
] | [] | [] | [
"python"
] | stackoverflow_0002912551_python.txt |
Q:
Important packages and modules not compatible with py2exe?
Are there major/common/important packages that py2exe cannot handle?
I am currently studying the possibility of creating a .exe from a Python program that will use Tkinter, some Excel file reading module, NumPy, SciPy and matplotlib: is it realistic to try to achieve this with py2exe?
A:
I routinely build py2exe single file executables using Scipy, matplotlib, wxpython and win32com or the Machin's xlrd/xlwt modules. Never used Tkinter but should not be a problem, probably wxpython is more picky.
I have found some problems with numpy/scipy, matplotlib and wxpython before and after building the executable but after you know what to do it works smoothy.
Some problems:
matplotlib requires to indicate where some auxiliary archives are. You need to add to your setup.py
datafiles = matplotlib.get_py2exe_datafiles()
numpy/scipy have given me some problems, due to some expresions in the modules, when executing the py2exe executable.
Numpy has some lines suchs as:
__doc__ += "something more"
that fail when __doc__ is None.
For this I had to modify manually the numpy scripts (including if's). I do not know if this has been solved in the new versions.
wxpython is generally a source of problems due to some required microsoft dlls that have to be present in the computer to work. Just you have to be carefull assuring you provide them in your package or at least preventing your users about the issue.
Some useful hints can also be found in the py2exe and wxpython wikis
A:
It's realistic to try, sure. You'll probably hit a few issues but I doubt you'll reach a blocker, especially with very common packages.
You can get a quick look at how well py2exe works with various libraries here:
http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules
For anything not listed there, fire off a quick google for py2exe <package-name>
| Important packages and modules not compatible with py2exe? | Are there major/common/important packages that py2exe cannot handle?
I am currently studying the possibility of creating a .exe from a Python program that will use Tkinter, some Excel file reading module, NumPy, SciPy and matplotlib: is it realistic to try to achieve this with py2exe?
| [
"I routinely build py2exe single file executables using Scipy, matplotlib, wxpython and win32com or the Machin's xlrd/xlwt modules. Never used Tkinter but should not be a problem, probably wxpython is more picky.\nI have found some problems with numpy/scipy, matplotlib and wxpython before and after building the executable but after you know what to do it works smoothy.\nSome problems:\nmatplotlib requires to indicate where some auxiliary archives are. You need to add to your setup.py\ndatafiles = matplotlib.get_py2exe_datafiles()\n\nnumpy/scipy have given me some problems, due to some expresions in the modules, when executing the py2exe executable.\nNumpy has some lines suchs as:\n__doc__ += \"something more\"\n\nthat fail when __doc__ is None.\nFor this I had to modify manually the numpy scripts (including if's). I do not know if this has been solved in the new versions.\nwxpython is generally a source of problems due to some required microsoft dlls that have to be present in the computer to work. Just you have to be carefull assuring you provide them in your package or at least preventing your users about the issue.\nSome useful hints can also be found in the py2exe and wxpython wikis\n",
"It's realistic to try, sure. You'll probably hit a few issues but I doubt you'll reach a blocker, especially with very common packages.\nYou can get a quick look at how well py2exe works with various libraries here:\nhttp://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules\nFor anything not listed there, fire off a quick google for py2exe <package-name>\n"
] | [
3,
2
] | [] | [] | [
"excel",
"executable",
"matplotlib",
"py2exe",
"python"
] | stackoverflow_0002912295_excel_executable_matplotlib_py2exe_python.txt |
Q:
Interesting task using random numbers only
Given any number of the random real numbers from the interval [0,1] is there exist any method to construct a floating point number with zero fractional part?
Your algorithm can use only random() function calls and no variables or constants. No constants and variables are allowed, no type casting is allowed. You can use for/while, if/else or any other programming language operands.
A:
Best I've come up with so far: generate a list of N random numbers, multiply them all together, this will go to 0 (which has a 0 fractional part) when N is large enough.
OK, I used a variable (N), but I'm not sure how to use for loops or if statements without a variable or constant.
If I had more time and the inclination I expect that I could prove that the product of N floats (or doubles) will go to 0 under IEEE arithmetic. As it is I played around with Matlab, and N == 800 seems sufficient.
EDIT: OP's insistence on avoiding all constants and variables leads me next to this solution:
random() * random() * random() * ...
I'll spare you all the other 797 calls to random. To all of you whose skulls split asunder at this mind-bogglingly ridiculous solution, may I point you to the question.
Lest you wonder or worry, I haven't a clue what random() returns in your language, here in my pseudocode it returns a floating-point number with as many bits as I wish (32, 64, 157 if I want) in the range [0,1] as required.
A:
Here's a solution in Python:
from random import random
def positiverandom():
return random() or positiverandom()
def zerofraction():
return (positiverandom() == -positiverandom()) * random()
Usage example:
>>> zerofraction()
0.0
A:
return ceil(random())
works.
If you allow only operators like +, -, *, sin you can prove that:
Every expression built using random variables from U[0,1] and arithmetic operations, using each random variable exactly once will represent an irrational number with probability 1.
Since your program must end with return expression it will be wrong (or won't halt) with probability 1.
A:
In Python:
>>> (-random() > random())*random()
0.0
But no doubt I'm going to be told that this violates some unwritten, yet-to-be-revealed condition of this bizarre problem.
A:
float random_float() {
return 1.0; /* chosen by random sphere roll, guaranteed to be random */
}
A:
Here we go!
<?php
random();
function random() {
return 1.0;
}
As long as I can tell the story that 1.0 is quite correctly one of the random numbers in the interval [0, 1].
I did not use constants! My algorithm is the call to random(), not the implementation of random(). PHP just doesn't happen to have such a function so I had to make it myself, conveniently.
A:
float random_float() {
return random(); // POSIX random returns a long.
} // I assume that's what OP means, no indication otherwise.
Considering that you didn't even specify that the returned floats are supposed to be random, much less what distribution they should have, I think this is the best we can do.
The above does contain a typecast, but there is no way to construct a floating-point number without either using a floating-point constant 0. or 1. or a value from a FP-valued function, which random is not.
To cheat a bit (this produces a different distribution and is rather unstable):
float random_float() {
if ( random() < random() ) {
return expf( float() ) + random_float();
} else return expf( float() ); // expf(float()) just a fancy name for 1
}
By the way, actual real numbers are beyond the grasp of computers. Inputting one would take infinite time.
A:
list_of_random_real_numbers = [.....]; // LoRRN
for n in LoRRN:
LoRRN[0] = LoRRN[0] * n;
while(fractional part of LoRRN[0] is not ZERO)
LoRRN[0] = LoRRN[0]* LoRRN[0]
print LoRRN[0]
Because if a,b are real numbers AND 0 < a,b < 1
then a*b < 1, a*b < a and a*b < b.
Hence, answer will always be zero. So why not just return 0.00.
PROOF:
0<a,b<1 and m,n >1
let
a = 1/m and b = 1/n
a*b = 1/(m*n)
=> 0 < a*b < a,b < 1
But as we are using floating point arithmetic after some multiplications number will be so small that computer will take it as zero.
A:
Bitwise AND the FP representations of all your real numbers together.
| Interesting task using random numbers only | Given any number of the random real numbers from the interval [0,1] is there exist any method to construct a floating point number with zero fractional part?
Your algorithm can use only random() function calls and no variables or constants. No constants and variables are allowed, no type casting is allowed. You can use for/while, if/else or any other programming language operands.
| [
"Best I've come up with so far: generate a list of N random numbers, multiply them all together, this will go to 0 (which has a 0 fractional part) when N is large enough. \nOK, I used a variable (N), but I'm not sure how to use for loops or if statements without a variable or constant.\nIf I had more time and the inclination I expect that I could prove that the product of N floats (or doubles) will go to 0 under IEEE arithmetic. As it is I played around with Matlab, and N == 800 seems sufficient.\nEDIT: OP's insistence on avoiding all constants and variables leads me next to this solution:\nrandom() * random() * random() * ...\n\nI'll spare you all the other 797 calls to random. To all of you whose skulls split asunder at this mind-bogglingly ridiculous solution, may I point you to the question. \nLest you wonder or worry, I haven't a clue what random() returns in your language, here in my pseudocode it returns a floating-point number with as many bits as I wish (32, 64, 157 if I want) in the range [0,1] as required.\n",
"Here's a solution in Python:\nfrom random import random\n\ndef positiverandom():\n return random() or positiverandom()\n\ndef zerofraction():\n return (positiverandom() == -positiverandom()) * random()\n\nUsage example:\n>>> zerofraction()\n0.0\n\n",
"return ceil(random())\n\nworks.\nIf you allow only operators like +, -, *, sin you can prove that:\n\nEvery expression built using random variables from U[0,1] and arithmetic operations, using each random variable exactly once will represent an irrational number with probability 1.\n\nSince your program must end with return expression it will be wrong (or won't halt) with probability 1.\n",
"In Python:\n>>> (-random() > random())*random()\n0.0\n\nBut no doubt I'm going to be told that this violates some unwritten, yet-to-be-revealed condition of this bizarre problem.\n",
" float random_float() {\n return 1.0; /* chosen by random sphere roll, guaranteed to be random */\n }\n\n",
"Here we go!\n<?php\n\nrandom();\n\nfunction random() {\n return 1.0;\n}\n\nAs long as I can tell the story that 1.0 is quite correctly one of the random numbers in the interval [0, 1].\nI did not use constants! My algorithm is the call to random(), not the implementation of random(). PHP just doesn't happen to have such a function so I had to make it myself, conveniently.\n",
"float random_float() {\n return random(); // POSIX random returns a long.\n} // I assume that's what OP means, no indication otherwise.\n\nConsidering that you didn't even specify that the returned floats are supposed to be random, much less what distribution they should have, I think this is the best we can do.\nThe above does contain a typecast, but there is no way to construct a floating-point number without either using a floating-point constant 0. or 1. or a value from a FP-valued function, which random is not.\nTo cheat a bit (this produces a different distribution and is rather unstable):\nfloat random_float() {\n if ( random() < random() ) {\n return expf( float() ) + random_float();\n } else return expf( float() ); // expf(float()) just a fancy name for 1\n}\n\nBy the way, actual real numbers are beyond the grasp of computers. Inputting one would take infinite time.\n",
"list_of_random_real_numbers = [.....]; // LoRRN\n\nfor n in LoRRN:\n LoRRN[0] = LoRRN[0] * n;\n\nwhile(fractional part of LoRRN[0] is not ZERO) \n LoRRN[0] = LoRRN[0]* LoRRN[0]\n\nprint LoRRN[0]\n\n\nBecause if a,b are real numbers AND 0 < a,b < 1 \nthen a*b < 1, a*b < a and a*b < b.\nHence, answer will always be zero. So why not just return 0.00.\nPROOF:\n0<a,b<1 and m,n >1\n\nlet\na = 1/m and b = 1/n \n\na*b = 1/(m*n) \n\n=> 0 < a*b < a,b < 1\n\nBut as we are using floating point arithmetic after some multiplications number will be so small that computer will take it as zero.\n",
"Bitwise AND the FP representations of all your real numbers together. \n"
] | [
4,
4,
4,
4,
2,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"c",
"math",
"python",
"random"
] | stackoverflow_0002912025_algorithm_c_math_python_random.txt |
Q:
Scipy.cluster.hierarchy.fclusterdata + distance measure
1) I am using scipy's hcluster module.
so the variable that I have control over is the threshold variable.
How do I know my performance per threshold? i.e. In Kmeans, this performance will be the sum of all the points to their centroids. Of course, this has to be adjusted since more clusters = less distance generally.
Is there an observation that I can do with hcluster for this?
2) I am realize there are tons of metrics available for fclusterdata. I am clustering of text documents based on tf-idf of key terms. The deal is, some document are longer than others, and I think that cosine is a good way to "normalize" this length issue because the longer a document are, its "direction" in a n-dimensional field SHOULD stay the same if they content is consistent. Are there any other methods someone can suggest? How can I evaluate?
Thx
A:
One can calculate average distances |x - cluster centre| for x in cluster, just as for K-means.
The following does this brute-force. (It must be a builtin
in scipy.cluster or scipy.spatial.distance but I can't find it either.)
On your question 2, pass. Any links to good tutorials on hierarchical clustering would be welcome.
#!/usr/bin/env python
""" cluster cities: pdist linkage fcluster plot
util: clusters() avdist()
"""
from __future__ import division
import sys
import numpy as np
import scipy.cluster.hierarchy as hier # $scipy/cluster/hierarchy.py
import scipy.spatial.distance as dist
import pylab as pl
from citiesin import citiesin # 1000 US cities
__date__ = "27may 2010 denis"
def clusterlists(T):
""" T = hier.fcluster( Z, t ) e.g. [a b a b a c]
-> [ [0 2 4] [1 3] [5] ] sorted by len
"""
clists = [ [] for j in range( max(T) + 1 )]
for j, c in enumerate(T):
clists[c].append( j )
clists.sort( key=len, reverse=True )
return clists[:-1] # clip the []
def avdist( X, to=None ):
""" av dist X vecs to "to", None: mean(X) """
if to is None:
to = np.mean( X, axis=0 )
return np.mean( dist.cdist( X, [to] ))
#...............................................................................
Ndata = 100
method = "average"
t = 0
crit = "maxclust"
# 'maxclust': Finds a minimum threshold `r` so that the cophenetic distance
# between any two original observations in the same flat cluster
# is no more than `r` and no more than `t` flat clusters are formed.
# but t affects cluster sizes only weakly ?
# t 25: [10, 9, 8, 7, 6
# t 20: [12, 11, 10, 9, 7
plot = 0
seed = 1
exec "\n".join( sys.argv[1:] ) # Ndata= t= ...
np.random.seed(seed)
np.set_printoptions( 2, threshold=100, edgeitems=10, suppress=True ) # .2f
me = __file__.split('/') [-1]
# biggest US cities --
cities = np.array( citiesin( n=Ndata )[0] ) # N,2
if t == 0: t = Ndata // 4
#...............................................................................
print "# %s Ndata=%d t=%d method=%s crit=%s " % (me, Ndata, t, method, crit)
Y = dist.pdist( cities ) # n*(n-1) / 2
Z = hier.linkage( Y, method ) # n-1
T = hier.fcluster( Z, t, criterion=crit ) # n
clusters = clusterlists(T)
print "cluster sizes:", map( len, clusters )
print "# average distance to centre in the biggest clusters:"
for c in clusters:
if len(c) < len(clusters[0]) // 3: break
cit = cities[c].T
print "%.2g %s" % (avdist(cit.T), cit)
if plot:
pl.plot( cit[0], cit[1] )
if plot:
pl.title( "scipy.cluster.hierarchy of %d US cities, %s t=%d" % (
Ndata, crit, t) )
pl.grid(False)
if plot >= 2:
pl.savefig( "cities-%d-%d.png" % (Ndata, t), dpi=80 )
pl.show()
| Scipy.cluster.hierarchy.fclusterdata + distance measure | 1) I am using scipy's hcluster module.
so the variable that I have control over is the threshold variable.
How do I know my performance per threshold? i.e. In Kmeans, this performance will be the sum of all the points to their centroids. Of course, this has to be adjusted since more clusters = less distance generally.
Is there an observation that I can do with hcluster for this?
2) I am realize there are tons of metrics available for fclusterdata. I am clustering of text documents based on tf-idf of key terms. The deal is, some document are longer than others, and I think that cosine is a good way to "normalize" this length issue because the longer a document are, its "direction" in a n-dimensional field SHOULD stay the same if they content is consistent. Are there any other methods someone can suggest? How can I evaluate?
Thx
| [
"One can calculate average distances |x - cluster centre| for x in cluster, just as for K-means.\nThe following does this brute-force. (It must be a builtin\nin scipy.cluster or scipy.spatial.distance but I can't find it either.)\nOn your question 2, pass. Any links to good tutorials on hierarchical clustering would be welcome.\n\n#!/usr/bin/env python\n\"\"\" cluster cities: pdist linkage fcluster plot\n util: clusters() avdist()\n\"\"\"\n\nfrom __future__ import division\nimport sys\nimport numpy as np\nimport scipy.cluster.hierarchy as hier # $scipy/cluster/hierarchy.py\nimport scipy.spatial.distance as dist\nimport pylab as pl\nfrom citiesin import citiesin # 1000 US cities\n\n__date__ = \"27may 2010 denis\"\n\ndef clusterlists(T):\n \"\"\" T = hier.fcluster( Z, t ) e.g. [a b a b a c]\n -> [ [0 2 4] [1 3] [5] ] sorted by len\n \"\"\"\n clists = [ [] for j in range( max(T) + 1 )]\n for j, c in enumerate(T):\n clists[c].append( j )\n clists.sort( key=len, reverse=True )\n return clists[:-1] # clip the []\n\ndef avdist( X, to=None ):\n \"\"\" av dist X vecs to \"to\", None: mean(X) \"\"\"\n if to is None:\n to = np.mean( X, axis=0 )\n return np.mean( dist.cdist( X, [to] ))\n\n#...............................................................................\nNdata = 100\nmethod = \"average\"\nt = 0\ncrit = \"maxclust\"\n # 'maxclust': Finds a minimum threshold `r` so that the cophenetic distance\n # between any two original observations in the same flat cluster\n # is no more than `r` and no more than `t` flat clusters are formed.\n # but t affects cluster sizes only weakly ?\n # t 25: [10, 9, 8, 7, 6\n # t 20: [12, 11, 10, 9, 7\nplot = 0\nseed = 1\n\nexec \"\\n\".join( sys.argv[1:] ) # Ndata= t= ...\nnp.random.seed(seed)\nnp.set_printoptions( 2, threshold=100, edgeitems=10, suppress=True ) # .2f\nme = __file__.split('/') [-1]\n\n # biggest US cities --\ncities = np.array( citiesin( n=Ndata )[0] ) # N,2\n\nif t == 0: t = Ndata // 4\n\n#...............................................................................\nprint \"# %s Ndata=%d t=%d method=%s crit=%s \" % (me, Ndata, t, method, crit)\n\nY = dist.pdist( cities ) # n*(n-1) / 2\nZ = hier.linkage( Y, method ) # n-1\nT = hier.fcluster( Z, t, criterion=crit ) # n\n\nclusters = clusterlists(T)\nprint \"cluster sizes:\", map( len, clusters )\nprint \"# average distance to centre in the biggest clusters:\"\nfor c in clusters:\n if len(c) < len(clusters[0]) // 3: break\n cit = cities[c].T\n print \"%.2g %s\" % (avdist(cit.T), cit)\n if plot:\n pl.plot( cit[0], cit[1] )\n\nif plot:\n pl.title( \"scipy.cluster.hierarchy of %d US cities, %s t=%d\" % (\n Ndata, crit, t) )\n pl.grid(False)\n if plot >= 2:\n pl.savefig( \"cities-%d-%d.png\" % (Ndata, t), dpi=80 )\n pl.show()\n\n"
] | [
5
] | [] | [] | [
"cluster_analysis",
"python",
"scipy"
] | stackoverflow_0002547391_cluster_analysis_python_scipy.txt |
Q:
How to iterate over function arguments
I have a Python function accepting several string arguments def foo(a, b, c): and concatenating them in a string.
I want to iterate over all function arguments to check they are not None. How it can be done?
Is there a quick way to convert None to ""?
Thanks.
A:
locals() may be your friend here if you call it first thing in your function.
Example 1:
>>> def fun(a, b, c):
... d = locals()
... e = d
... print e
... print locals()
...
>>> fun(1, 2, 3)
{'a': 1, 'c': 3, 'b': 2}
{'a': 1, 'c': 3, 'b': 2, 'e': {...}, 'd': {...}}
Example 2:
>>> def nones(a, b, c, d):
... arguments = locals()
... print 'The following arguments are not None: ', ', '.join(k for k, v in arguments.items() if v is not None)
...
>>> nones("Something", None, 'N', False)
The following arguments are not None: a, c, d
Answer:
>>> def foo(a, b, c):
... return ''.join(v for v in locals().values() if v is not None)
...
>>> foo('Cleese', 'Palin', None)
'CleesePalin'
Update:
'Example 1' highlights that we may have some extra work to do if the order of your arguments is important as the dict returned by locals() (or vars()) is unordered. The function above also doesn't deal with numbers very gracefully. So here are a couple of refinements:
>>> def foo(a, b, c):
... arguments = locals()
... return ''.join(str(arguments[k]) for k in sorted(arguments.keys()) if arguments[k] is not None)
...
>>> foo(None, 'Antioch', 3)
'Antioch3'
A:
def func(*args):
' '.join(i if i is not None else '' for i in args)
if you're joining on an empty string, you could just do ''.join(i for i in args if i is not None)
A:
You can use the inspect module and define a function like that:
import inspect
def f(a,b,c):
argspec=inspect.getargvalues(inspect.currentframe())
return argspec
f(1,2,3)
ArgInfo(args=['a', 'b', 'c'], varargs=None, keywords=None, locals={'a': 1, 'c': 3, 'b': 2})
in argspec there are all the info you need to perform any operation with argument passed.
To concatenate the string is sufficient to use the arg info received:
def f(a,b,c):
argspec=inspect.getargvalues(inspect.currentframe())
return ''.join(argspec.locals[arg] for arg in argspec.args)
For reference:
http://docs.python.org/library/inspect.html#inspect.getargvalues
A:
Is this perhaps what you'd like?
def foo(a, b, c):
"SilentGhost suggested the join"
' '.join(i if i is not None else '' for i in vars().values())
def bar(a,b,c):
"A very usefull method!"
print vars()
print vars().values()
Notice the use of vars(), which returns a dict.
| How to iterate over function arguments | I have a Python function accepting several string arguments def foo(a, b, c): and concatenating them in a string.
I want to iterate over all function arguments to check they are not None. How it can be done?
Is there a quick way to convert None to ""?
Thanks.
| [
"locals() may be your friend here if you call it first thing in your function.\nExample 1:\n>>> def fun(a, b, c):\n... d = locals()\n... e = d\n... print e\n... print locals()\n... \n>>> fun(1, 2, 3)\n{'a': 1, 'c': 3, 'b': 2}\n{'a': 1, 'c': 3, 'b': 2, 'e': {...}, 'd': {...}}\n\nExample 2:\n>>> def nones(a, b, c, d):\n... arguments = locals()\n... print 'The following arguments are not None: ', ', '.join(k for k, v in arguments.items() if v is not None)\n... \n>>> nones(\"Something\", None, 'N', False)\nThe following arguments are not None: a, c, d\n\nAnswer:\n>>> def foo(a, b, c):\n... return ''.join(v for v in locals().values() if v is not None)\n... \n>>> foo('Cleese', 'Palin', None)\n'CleesePalin'\n\nUpdate:\n'Example 1' highlights that we may have some extra work to do if the order of your arguments is important as the dict returned by locals() (or vars()) is unordered. The function above also doesn't deal with numbers very gracefully. So here are a couple of refinements:\n>>> def foo(a, b, c):\n... arguments = locals()\n... return ''.join(str(arguments[k]) for k in sorted(arguments.keys()) if arguments[k] is not None)\n... \n>>> foo(None, 'Antioch', 3)\n'Antioch3'\n\n",
"def func(*args):\n ' '.join(i if i is not None else '' for i in args)\n\nif you're joining on an empty string, you could just do ''.join(i for i in args if i is not None)\n",
"You can use the inspect module and define a function like that:\nimport inspect\ndef f(a,b,c):\n argspec=inspect.getargvalues(inspect.currentframe())\n return argspec\nf(1,2,3)\nArgInfo(args=['a', 'b', 'c'], varargs=None, keywords=None, locals={'a': 1, 'c': 3, 'b': 2})\n\nin argspec there are all the info you need to perform any operation with argument passed.\nTo concatenate the string is sufficient to use the arg info received:\ndef f(a,b,c):\n argspec=inspect.getargvalues(inspect.currentframe())\n return ''.join(argspec.locals[arg] for arg in argspec.args)\n\nFor reference:\nhttp://docs.python.org/library/inspect.html#inspect.getargvalues\n",
"Is this perhaps what you'd like?\ndef foo(a, b, c):\n \"SilentGhost suggested the join\"\n ' '.join(i if i is not None else '' for i in vars().values())\n\ndef bar(a,b,c): \n \"A very usefull method!\"\n print vars()\n print vars().values()\n\nNotice the use of vars(), which returns a dict.\n"
] | [
66,
21,
4,
2
] | [
"I would use sed s/None//g, but that's not in python, but you can probably use os.popen() to do that.\n"
] | [
-6
] | [
"arguments",
"python"
] | stackoverflow_0002912615_arguments_python.txt |
Q:
How to Return Variable for all tests to use Unittest
I have a Python script and I am trying to set a variable so that if the first test fail's the rest of then will be set to fail. The script I have so far is:
class Tests(unittest.TestCase):
def result(self):
....This function does something[ignore]......
someArg = 0
def testPass(self):
try:
self.result()
except suds.WebFault, e:
assert False
except Exception, e:
pass
finally:
if someArg == 0:
assert True
else:
global error
error = False
assert False
def testFail(self):
try:
self.result()
except suds.WebFault, e:
assert False
except Exception, e:
pass
finally:
if someArg == 0 or 'error' in globals():
assert False
else:
assert True
class Get(Tests):
def runTest(self):
self.testPass()
class GetFail(Tests):
def runTest(self):
self.errorHandle()
self.testFail()
if __name__ == '__main__':
unittest.main()
I am trying to get self.error to be set to False if the first test fail. I understand that it is being set in another test but I was hoping someone could help me find a solution to this problem using some other means.
Thanks
PS. Please ignore the strange tests. There is a problem with the error handling at the moment.
A:
I'm having a hard time understanding your code, so let's pinpoint a few bits that I do understand (as it look like you may believe things are different from how they are).
The call
self.errorHandle()
which you perform repeatedly works as a no-operation: the errorHandle method just does a return, the callers ignore the returned value, so that, net, "nothing happens" and you might as well avoid calling the method at all. What do you expect to happen when you call a method that just returns something and ignore the return value?
No idea where you're getting the someArg value -- I see it tested in two methods but never set. Is this maybe meant as pseudocode at some level...?
Not sure what the syntax of that def function(self) (i.e. result function...) is supposed to convey -- it's meant to be some kind of pseudocode, I'm sure, but what exactly?
If you can clarify these points -- most especially the first one about the errorHandle methods and the calls to it -- maybe it will be easier for us to offer assistance.
| How to Return Variable for all tests to use Unittest | I have a Python script and I am trying to set a variable so that if the first test fail's the rest of then will be set to fail. The script I have so far is:
class Tests(unittest.TestCase):
def result(self):
....This function does something[ignore]......
someArg = 0
def testPass(self):
try:
self.result()
except suds.WebFault, e:
assert False
except Exception, e:
pass
finally:
if someArg == 0:
assert True
else:
global error
error = False
assert False
def testFail(self):
try:
self.result()
except suds.WebFault, e:
assert False
except Exception, e:
pass
finally:
if someArg == 0 or 'error' in globals():
assert False
else:
assert True
class Get(Tests):
def runTest(self):
self.testPass()
class GetFail(Tests):
def runTest(self):
self.errorHandle()
self.testFail()
if __name__ == '__main__':
unittest.main()
I am trying to get self.error to be set to False if the first test fail. I understand that it is being set in another test but I was hoping someone could help me find a solution to this problem using some other means.
Thanks
PS. Please ignore the strange tests. There is a problem with the error handling at the moment.
| [
"I'm having a hard time understanding your code, so let's pinpoint a few bits that I do understand (as it look like you may believe things are different from how they are).\nThe call\nself.errorHandle() \n\nwhich you perform repeatedly works as a no-operation: the errorHandle method just does a return, the callers ignore the returned value, so that, net, \"nothing happens\" and you might as well avoid calling the method at all. What do you expect to happen when you call a method that just returns something and ignore the return value?\nNo idea where you're getting the someArg value -- I see it tested in two methods but never set. Is this maybe meant as pseudocode at some level...?\nNot sure what the syntax of that def function(self) (i.e. result function...) is supposed to convey -- it's meant to be some kind of pseudocode, I'm sure, but what exactly?\nIf you can clarify these points -- most especially the first one about the errorHandle methods and the calls to it -- maybe it will be easier for us to offer assistance.\n"
] | [
1
] | [] | [] | [
"inheritance",
"python",
"unit_testing"
] | stackoverflow_0002913053_inheritance_python_unit_testing.txt |
Q:
How should I correctly handle exceptions in Python3
I can't understand what sort of exceptions I should handle 'here and now', and what sort of exceptions I should re-raise or just don't handle here, and what to do with them later (on higher tier). For example: I wrote client/server application using python3 with ssl communication. Client is supposed to verify files on any differences on them, and if diff exists then it should send this 'updated' file to server.
class BasicConnection:
#blablabla
def sendMessage(self, sock, url, port, fileToSend, buffSize):
try:
sock.connect((url, port))
while True:
data = fileToSend.read(buffSize)
if not data: break
sock.send(data)
return True
except socket.timeout as toErr:
raise ConnectionError("TimeOutError trying to send File to remote socket: %s:%d"
% (url,port)) from toErr
except socket.error as sErr:
raise ConnectionError("Error trying to send File to remote socket: %s:%d"
% (url,port)) from sErr
except ssl.SSLError as sslErr:
raise ConnectionError("SSLError trying to send File to remote socket: %s:%d"
% (url,port)) from sslErr
finally:
sock.close()
Is it right way to use exceptions in python? The problem is: what if file.read() throws IOError? Should I handle it here, or just do nothing and catch it later? And many other possible exceptions?
Client use this class (BasicConnection) to send updated files to server:
class PClient():
def __init__(self, DATA):
'''DATA = { 'sendTo' : {'host':'','port':''},
'use_ssl' : {'use_ssl':'', 'fileKey':'', 'fileCert':'', 'fileCaCert':''},
'dirToCheck' : '',
'localStorage': '',
'timeToCheck' : '',
'buffSize' : '',
'logFile' : ''} '''
self._DATA = DATA
self._running = False
self.configureLogging()
def configureLogging(self):
#blablabla
def isRun(self):
return self._running
def initPClient(self):
try:
#blablabla
return True
except ConnectionError as conErr:
self._mainLogger.exception(conErr)
return False
except FileCheckingError as fcErr:
self._mainLogger.exception(fcErr)
return False
except IOError as ioErr:
self._mainLogger.exception(ioErr)
return False
except OSError as osErr:
self._mainLogger.exception(osErr)
return False
def startPClient(self):
try:
self._running = True
while self.isRun():
try :
self._mainLogger.debug("Checking differences")
diffFiles = FileChecker().checkDictionary(self._dict)
if len(diffFiles) != 0:
for fileName in diffFiles:
try:
self._mainLogger.info("Sending updated file: %s to remote socket: %s:%d"
% (fileName,self._DATA['sendTo']['host'],self._DATA['sendTo']['port']))
fileToSend = io.open(fileName, "rb")
result = False
result = BasicConnection().sendMessage(self._sock, self._DATA['sendTo']['host'],
self._DATA['sendTo']['port'], fileToSend, self._DATA['buffSize'])
if result:
self._mainLogger.info("Updated file: %s was successfully delivered to remote socket: %s:%d"
% (fileName,self._DATA['sendTo']['host'],self._DATA['sendTo']['port']))
except ConnectionError as conErr:
self._mainLogger.exception(conErr)
except IOError as ioErr:
self._mainLogger.exception(ioErr)
except OSError as osErr:
self._mainLogger.exception(osErr)
self._mainLogger.debug("Updating localStorage %s from %s " %(self._DATA['localStorage'], self._DATA['dirToCheck']))
FileChecker().updateLocalStorage(self._DATA['dirToCheck'],
self._DATA['localStorage'])
self._mainLogger.info("Directory %s were checked" %(self._DATA['dirToCheck']))
time.sleep(self._DATA['timeToCheck'])
except FileCheckingError as fcErr:
self._mainLogger.exception(fcErr)
except IOError as ioErr:
self._mainLogger.exception(ioErr)
except OSError as osErr:
self._mainLogger.exception(osErr)
except KeyboardInterrupt:
self._mainLogger.info("Shutting down...")
self.stopPClient()
except Exception as exc:
self._mainLogger.exception(exc)
self.stopPClient()
raise RuntimeError("Something goes wrong...") from exc
def stopPClient(self):
self._running = False
Is it correct? May be someone spend his own time and just help me to understand pythonic style of handling exceptions? I can't understand what to do with such exceptions as NameError, TypeError, KeyError, ValueError...and so on.......They could be thrown at any statement, at any time... and what to do with them, if I want to logged everything.
And what information should people usually log? If error occurs, what info about it I should log? All traceback, or just relevant message about it or something else?
I hope somebody helps me.
Thanks a lot.
A:
In general, you should "catch" the exceptions that you expect to happen (because they may be caused by user error, or other environmental problems outside of your program's control), especially if you know what your code might be able to do about them. Just giving more details in an error report is a marginal issue, though some programs' specs may require doing that (e.g. a long-running server that's not supposed to crash due to such problems, but rather log a lot of state information, give the user a summary explanation, and just keep working for future queries).
NameError, TypeError, KeyError, ValueError, SyntaxError, AttributeError, and so on, can be thought of as due to errors in the program -- bugs, not problems outside of the programmer's control. If you're releasing a library or framework, so that your code is going to be called by other code outside of your control, then such bugs may quite likely be in that other code; you should normally let the exception propagate to help the other programmer debug their own bugs. If you're releasing an application, you own the bugs, and you must pick the strategy that helps you find them.
If your bugs show up while an end-user is running the program, you should log a lot of state information, and give the user a summary explanation and apologies (perhaps with a request to send you the log info, if you can't automate that -- or, at least, ask permission before you send anything from the user's machine to yours). You may be able to save some of the user's work so far, but often (in a program that's known to be buggy) that may not work anyway.
Most bugs should show up during your own testing of course; in that case, propagating the exception is useful as you can hook it up to a debugger and explore the bug's details.
Sometimes some exceptions like these show up just because "it's easier to ask forgiveness than permission" (EAFP) -- a perfectly acceptable programming technique in Python. In that case of course you should handle them at once. For example:
try:
return mylist[theindex]
except IndexError:
return None
here you might expect that theindex is generally a valid index into mylist, but occasionally outside of mylist's bounds -- and the latter case, by the semantics of the hypothetic app in which this snippet belongs, is not an error, just a little anomaly to be fixed by considering the list to be conceptually extended on both sides with infinite numbers of Nones. It's easier to just try/except than to properly check for positive and negative values of the index (and faster, if being out of bounds is a truly rare occurrence).
Similarly appropriate cases for KeyError and AttributeError happen less frequently, thanks to the getattr builtin and get method of dicts (which let you provide a default value), collections.defaultdict, etc; but lists have no direct equivalent of those, so the try/except is seen more frequently for IndexError.
Trying to catch syntax errors, type errors, value errors, name errors, etc, is a bit rarer and more controversial -- though it would surely be appropriate if the error was diagnosed in a "plug-in", third-party code outside your control which your framework/application is trying to load and execute dynamically (indeed that's the case where you're supplying a library or the like and need to coexist peacefully with code out of your control which might well be buggy). Type and value errors may sometimes occur within an EAFP pattern -- e.g. when you try to overload a function to accept either a string or a number and behave slightly differently in each case, catching such errors may be better than trying to check types -- but the very concept of functions thus overloaded is more often than not quite dubious.
Back to "user and environmental errors", users will inevitably make mistakes when they give you input, indicate a filename that's not actually around (or that you don't have permission to read, or to write if that's what you're supposed to be doing), and so on: all such errors should of course be caught and result in a clear explanation to the user about what's gone wrong, and another chance to get the input right. Networks sometime go down, databases or other external servers may not respond as expected, and so forth -- sometimes it's worth catching such problems and retrying (maybe after a little wait -- maybe with an indication to the user about what's wrong, e.g. they may have accidentally unplugged a cable and you want to give them a chance to fix things and tell you when to try again), sometimes (especially in unattended long-running programs) there's nothing much you can do except an ordered shutdown (and detailed logging of every possibly-relevant aspect of the environment).
So, in brief, the answer to your Q's title is, "it depends";-). I hope I have been of use in listing many of the situations and aspects on which it can depend, and recommending what's generally the most useful attitude to take towards such issues.
A:
To start with, you don't need any _mainLogger.
If you want to catch any exceptions, maybe to log or send them by email or whatever, do that at the highest possible level -- certainly not inside this class.
Also, you definitely don't want to convert every Exception to a RuntimeError. Let it emerge. The stopClient() method has no purpose right now. When it has, we'll look at it..
You could basically wrap the ConnectionError, IOError and OSError together (like, re-raise as something else), but not much more than that...
| How should I correctly handle exceptions in Python3 | I can't understand what sort of exceptions I should handle 'here and now', and what sort of exceptions I should re-raise or just don't handle here, and what to do with them later (on higher tier). For example: I wrote client/server application using python3 with ssl communication. Client is supposed to verify files on any differences on them, and if diff exists then it should send this 'updated' file to server.
class BasicConnection:
#blablabla
def sendMessage(self, sock, url, port, fileToSend, buffSize):
try:
sock.connect((url, port))
while True:
data = fileToSend.read(buffSize)
if not data: break
sock.send(data)
return True
except socket.timeout as toErr:
raise ConnectionError("TimeOutError trying to send File to remote socket: %s:%d"
% (url,port)) from toErr
except socket.error as sErr:
raise ConnectionError("Error trying to send File to remote socket: %s:%d"
% (url,port)) from sErr
except ssl.SSLError as sslErr:
raise ConnectionError("SSLError trying to send File to remote socket: %s:%d"
% (url,port)) from sslErr
finally:
sock.close()
Is it right way to use exceptions in python? The problem is: what if file.read() throws IOError? Should I handle it here, or just do nothing and catch it later? And many other possible exceptions?
Client use this class (BasicConnection) to send updated files to server:
class PClient():
def __init__(self, DATA):
'''DATA = { 'sendTo' : {'host':'','port':''},
'use_ssl' : {'use_ssl':'', 'fileKey':'', 'fileCert':'', 'fileCaCert':''},
'dirToCheck' : '',
'localStorage': '',
'timeToCheck' : '',
'buffSize' : '',
'logFile' : ''} '''
self._DATA = DATA
self._running = False
self.configureLogging()
def configureLogging(self):
#blablabla
def isRun(self):
return self._running
def initPClient(self):
try:
#blablabla
return True
except ConnectionError as conErr:
self._mainLogger.exception(conErr)
return False
except FileCheckingError as fcErr:
self._mainLogger.exception(fcErr)
return False
except IOError as ioErr:
self._mainLogger.exception(ioErr)
return False
except OSError as osErr:
self._mainLogger.exception(osErr)
return False
def startPClient(self):
try:
self._running = True
while self.isRun():
try :
self._mainLogger.debug("Checking differences")
diffFiles = FileChecker().checkDictionary(self._dict)
if len(diffFiles) != 0:
for fileName in diffFiles:
try:
self._mainLogger.info("Sending updated file: %s to remote socket: %s:%d"
% (fileName,self._DATA['sendTo']['host'],self._DATA['sendTo']['port']))
fileToSend = io.open(fileName, "rb")
result = False
result = BasicConnection().sendMessage(self._sock, self._DATA['sendTo']['host'],
self._DATA['sendTo']['port'], fileToSend, self._DATA['buffSize'])
if result:
self._mainLogger.info("Updated file: %s was successfully delivered to remote socket: %s:%d"
% (fileName,self._DATA['sendTo']['host'],self._DATA['sendTo']['port']))
except ConnectionError as conErr:
self._mainLogger.exception(conErr)
except IOError as ioErr:
self._mainLogger.exception(ioErr)
except OSError as osErr:
self._mainLogger.exception(osErr)
self._mainLogger.debug("Updating localStorage %s from %s " %(self._DATA['localStorage'], self._DATA['dirToCheck']))
FileChecker().updateLocalStorage(self._DATA['dirToCheck'],
self._DATA['localStorage'])
self._mainLogger.info("Directory %s were checked" %(self._DATA['dirToCheck']))
time.sleep(self._DATA['timeToCheck'])
except FileCheckingError as fcErr:
self._mainLogger.exception(fcErr)
except IOError as ioErr:
self._mainLogger.exception(ioErr)
except OSError as osErr:
self._mainLogger.exception(osErr)
except KeyboardInterrupt:
self._mainLogger.info("Shutting down...")
self.stopPClient()
except Exception as exc:
self._mainLogger.exception(exc)
self.stopPClient()
raise RuntimeError("Something goes wrong...") from exc
def stopPClient(self):
self._running = False
Is it correct? May be someone spend his own time and just help me to understand pythonic style of handling exceptions? I can't understand what to do with such exceptions as NameError, TypeError, KeyError, ValueError...and so on.......They could be thrown at any statement, at any time... and what to do with them, if I want to logged everything.
And what information should people usually log? If error occurs, what info about it I should log? All traceback, or just relevant message about it or something else?
I hope somebody helps me.
Thanks a lot.
| [
"In general, you should \"catch\" the exceptions that you expect to happen (because they may be caused by user error, or other environmental problems outside of your program's control), especially if you know what your code might be able to do about them. Just giving more details in an error report is a marginal issue, though some programs' specs may require doing that (e.g. a long-running server that's not supposed to crash due to such problems, but rather log a lot of state information, give the user a summary explanation, and just keep working for future queries).\nNameError, TypeError, KeyError, ValueError, SyntaxError, AttributeError, and so on, can be thought of as due to errors in the program -- bugs, not problems outside of the programmer's control. If you're releasing a library or framework, so that your code is going to be called by other code outside of your control, then such bugs may quite likely be in that other code; you should normally let the exception propagate to help the other programmer debug their own bugs. If you're releasing an application, you own the bugs, and you must pick the strategy that helps you find them.\nIf your bugs show up while an end-user is running the program, you should log a lot of state information, and give the user a summary explanation and apologies (perhaps with a request to send you the log info, if you can't automate that -- or, at least, ask permission before you send anything from the user's machine to yours). You may be able to save some of the user's work so far, but often (in a program that's known to be buggy) that may not work anyway.\nMost bugs should show up during your own testing of course; in that case, propagating the exception is useful as you can hook it up to a debugger and explore the bug's details.\nSometimes some exceptions like these show up just because \"it's easier to ask forgiveness than permission\" (EAFP) -- a perfectly acceptable programming technique in Python. In that case of course you should handle them at once. For example:\ntry:\n return mylist[theindex]\nexcept IndexError:\n return None\n\nhere you might expect that theindex is generally a valid index into mylist, but occasionally outside of mylist's bounds -- and the latter case, by the semantics of the hypothetic app in which this snippet belongs, is not an error, just a little anomaly to be fixed by considering the list to be conceptually extended on both sides with infinite numbers of Nones. It's easier to just try/except than to properly check for positive and negative values of the index (and faster, if being out of bounds is a truly rare occurrence).\nSimilarly appropriate cases for KeyError and AttributeError happen less frequently, thanks to the getattr builtin and get method of dicts (which let you provide a default value), collections.defaultdict, etc; but lists have no direct equivalent of those, so the try/except is seen more frequently for IndexError.\nTrying to catch syntax errors, type errors, value errors, name errors, etc, is a bit rarer and more controversial -- though it would surely be appropriate if the error was diagnosed in a \"plug-in\", third-party code outside your control which your framework/application is trying to load and execute dynamically (indeed that's the case where you're supplying a library or the like and need to coexist peacefully with code out of your control which might well be buggy). Type and value errors may sometimes occur within an EAFP pattern -- e.g. when you try to overload a function to accept either a string or a number and behave slightly differently in each case, catching such errors may be better than trying to check types -- but the very concept of functions thus overloaded is more often than not quite dubious.\nBack to \"user and environmental errors\", users will inevitably make mistakes when they give you input, indicate a filename that's not actually around (or that you don't have permission to read, or to write if that's what you're supposed to be doing), and so on: all such errors should of course be caught and result in a clear explanation to the user about what's gone wrong, and another chance to get the input right. Networks sometime go down, databases or other external servers may not respond as expected, and so forth -- sometimes it's worth catching such problems and retrying (maybe after a little wait -- maybe with an indication to the user about what's wrong, e.g. they may have accidentally unplugged a cable and you want to give them a chance to fix things and tell you when to try again), sometimes (especially in unattended long-running programs) there's nothing much you can do except an ordered shutdown (and detailed logging of every possibly-relevant aspect of the environment).\nSo, in brief, the answer to your Q's title is, \"it depends\";-). I hope I have been of use in listing many of the situations and aspects on which it can depend, and recommending what's generally the most useful attitude to take towards such issues.\n",
"To start with, you don't need any _mainLogger.\nIf you want to catch any exceptions, maybe to log or send them by email or whatever, do that at the highest possible level -- certainly not inside this class.\nAlso, you definitely don't want to convert every Exception to a RuntimeError. Let it emerge. The stopClient() method has no purpose right now. When it has, we'll look at it..\nYou could basically wrap the ConnectionError, IOError and OSError together (like, re-raise as something else), but not much more than that...\n"
] | [
24,
3
] | [] | [] | [
"exception",
"logging",
"python"
] | stackoverflow_0002913819_exception_logging_python.txt |
Q:
Django's Admin - Many-to-Many field confusion
I'm teaching myself Django and creating a personal portfolio site. I've setup a model called FolioItem which makes use of a Many-To-Many relation to another model called FolioImage. The idea being each FolioItem can have numerous FolioImages.
class FolioImage(models.Model):
image = models.FileField(upload_to='portfolio_images')
def __unicode__(self):
return self.image.name
class FolioItem(models.Model):
title = models.CharField(max_length=50)
thumbnail = models.FileField(upload_to='portfolio_images')
images = models.ManyToManyField(FolioImage)
def __unicode__(self):
return self.title
In Django's admin interface I can create new FolioItem's but the images field (the many-to-many relating to a FolioImage) is showing all existing FolioImage's added previously to other FolioItems.
Really this should be blank as it is a new item and doesn't have any images associated yet. Is there any way to force this selector to be blank when creating a new item?
Also, it seems when I attempt to edit an existing entry I can't add or delete FolioImage associations (the small green + icon is not present).
Any advice would be great.
A:
Is there any way to force this
selector to be blank when creating a
new item?
I think you are slightly confused about the interface to the default select multiple widget. It is showing you all the existing images, making them available to you as choices, but there is no relationship on a brand new item. You have to actually click on an item, or do the shift (or control)-click trick to select multiple items, then save your folio item in order to make the relationship.
Also, it seems when I attempt to edit
an existing entry I can't add or
delete FolioImage associations (the
small green + icon is not present).
Again, I think you just need to click or ctrl-click to select/deselect the images you want to associate with your item.
You may also be interested in using Django's cool horizontal or vertical filter instead of the default select multiple interface. You can also use the inline interface. More details are here and here. I think the filter interface is much more intuitive.
A:
I think you are using the wrong relationship here. If you only want FolioImages to belong to a single FolioItem, then you should be using a ForeignKey from FolioImage to FolioItem. You can then configure the admin interface to show the related images for an item as inline formsets, which will allow you to add an edit only the images for that item.
| Django's Admin - Many-to-Many field confusion | I'm teaching myself Django and creating a personal portfolio site. I've setup a model called FolioItem which makes use of a Many-To-Many relation to another model called FolioImage. The idea being each FolioItem can have numerous FolioImages.
class FolioImage(models.Model):
image = models.FileField(upload_to='portfolio_images')
def __unicode__(self):
return self.image.name
class FolioItem(models.Model):
title = models.CharField(max_length=50)
thumbnail = models.FileField(upload_to='portfolio_images')
images = models.ManyToManyField(FolioImage)
def __unicode__(self):
return self.title
In Django's admin interface I can create new FolioItem's but the images field (the many-to-many relating to a FolioImage) is showing all existing FolioImage's added previously to other FolioItems.
Really this should be blank as it is a new item and doesn't have any images associated yet. Is there any way to force this selector to be blank when creating a new item?
Also, it seems when I attempt to edit an existing entry I can't add or delete FolioImage associations (the small green + icon is not present).
Any advice would be great.
| [
"\nIs there any way to force this\n selector to be blank when creating a\n new item?\n\nI think you are slightly confused about the interface to the default select multiple widget. It is showing you all the existing images, making them available to you as choices, but there is no relationship on a brand new item. You have to actually click on an item, or do the shift (or control)-click trick to select multiple items, then save your folio item in order to make the relationship.\n\nAlso, it seems when I attempt to edit\n an existing entry I can't add or\n delete FolioImage associations (the\n small green + icon is not present).\n\nAgain, I think you just need to click or ctrl-click to select/deselect the images you want to associate with your item.\nYou may also be interested in using Django's cool horizontal or vertical filter instead of the default select multiple interface. You can also use the inline interface. More details are here and here. I think the filter interface is much more intuitive.\n",
"I think you are using the wrong relationship here. If you only want FolioImages to belong to a single FolioItem, then you should be using a ForeignKey from FolioImage to FolioItem. You can then configure the admin interface to show the related images for an item as inline formsets, which will allow you to add an edit only the images for that item.\n"
] | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002913095_django_python.txt |
Q:
Injecting raw TCP packets with Python
What would be a suitable way to inject a raw TCP packet with Python? For example, I have the payload consisting of hexadecimal numbers and I want to send that sequence of hexadecimal numbers to a network daemon: so that if I choose to send 'abcdef', I see 'abcdef' on the wire too. But not '6162636566' as in the case of:
new = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new.connect(('127.0.0.1', 9999))
new.send('abcdef')
Can I use Python's SOCK_RAW for this purpose? If so, can you give me an example of sending raw TCP packets with SOCK_RAW (since I did not get it working myself)
Thanks!
Evgeniy
A:
Try scapy, a powerful interactive packet manipulation program.
Example:
%> sudo scapy
>>> packet1 = IP(dst='127.0.0.1')/TCP(dport=9999)
>>> packet1.payload = 'abcdef'
>>> send(packet1)
.
Sent 1 packets.
>>> packet1.show()
###[ IP ]###
version= 4
ihl= None
tos= 0x0
len= None
id= 1
flags=
frag= 0
ttl= 64
proto= ip
chksum= None
src= 127.0.0.1
dst= 127.0.0.1
\options\
###[ Raw ]###
load= 'abcdef'
>>>
A:
Sounds like you might be confused about python character strings. For example, try:
new.send('\x0a\x0b\x0c\x0d\x0e\x0f')
A:
Why not just converting your string to hex before sending it?
new = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new.connect(('127.0.0.1', 9999))
mydata = 'abcdef'
new.send(mydata.encode('hex'))
A:
For raw sockets, SOCK_RAW is the way to go. Remember that when you are using SOCK_RAW, you cant just send the payload. You will have to do the header formation as well. After you get this right, you could face problems with Operating System. While doing Raw Sockets on Windows XP, we faced some problems due to security issues.
| Injecting raw TCP packets with Python | What would be a suitable way to inject a raw TCP packet with Python? For example, I have the payload consisting of hexadecimal numbers and I want to send that sequence of hexadecimal numbers to a network daemon: so that if I choose to send 'abcdef', I see 'abcdef' on the wire too. But not '6162636566' as in the case of:
new = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new.connect(('127.0.0.1', 9999))
new.send('abcdef')
Can I use Python's SOCK_RAW for this purpose? If so, can you give me an example of sending raw TCP packets with SOCK_RAW (since I did not get it working myself)
Thanks!
Evgeniy
| [
"Try scapy, a powerful interactive packet manipulation program.\nExample:\n%> sudo scapy\n\n>>> packet1 = IP(dst='127.0.0.1')/TCP(dport=9999)\n>>> packet1.payload = 'abcdef'\n>>> send(packet1)\n.\nSent 1 packets.\n>>> packet1.show()\n###[ IP ]###\n version= 4\n ihl= None\n tos= 0x0\n len= None\n id= 1\n flags= \n frag= 0\n ttl= 64\n proto= ip\n chksum= None\n src= 127.0.0.1\n dst= 127.0.0.1\n \\options\\\n###[ Raw ]###\n load= 'abcdef'\n>>> \n\n",
"Sounds like you might be confused about python character strings. For example, try: \nnew.send('\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f')\n\n",
"Why not just converting your string to hex before sending it?\nnew = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nnew.connect(('127.0.0.1', 9999))\nmydata = 'abcdef'\nnew.send(mydata.encode('hex'))\n\n",
"For raw sockets, SOCK_RAW is the way to go. Remember that when you are using SOCK_RAW, you cant just send the payload. You will have to do the header formation as well. After you get this right, you could face problems with Operating System. While doing Raw Sockets on Windows XP, we faced some problems due to security issues. \n"
] | [
11,
1,
1,
1
] | [] | [] | [
"python",
"tcp"
] | stackoverflow_0002912123_python_tcp.txt |
Q:
Python : How to close a UDP socket while is waiting for data in recv?
let's consider this code in python:
import socket
import threading
import sys
import select
class UDPServer:
def __init__(self):
self.s=None
self.t=None
def start(self,port=8888):
if not self.s:
self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.s.bind(("",port))
self.t=threading.Thread(target=self.run)
self.t.start()
def stop(self):
if self.s:
self.s.close()
self.t.join()
self.t=None
def run(self):
while True:
try:
#receive data
data,addr=self.s.recvfrom(1024)
self.onPacket(addr,data)
except:
break
self.s=None
def onPacket(self,addr,data):
print addr,data
us=UDPServer()
while True:
sys.stdout.write("UDP server> ")
cmd=sys.stdin.readline()
if cmd=="start\n":
print "starting server..."
us.start(8888)
print "done"
elif cmd=="stop\n":
print "stopping server..."
us.stop()
print "done"
elif cmd=="quit\n":
print "Quitting ..."
us.stop()
break;
print "bye bye"
It runs an interactive shell with which I can start and stop an UDP server.
The server is implemented through a class which launches a thread in which there's a infinite loop of recv/onPacket callback inside a try/except block which should detect the error and the exits from the loop.
What I expect is that when I type "stop" on the shell the socket is closed and an exception is raised by the recvfrom function because of the invalidation of the file descriptor.
Instead, it seems that recvfrom still to block the thread waiting for data even after the close call.
Why this strange behavior ?
I've always used this patter to implements an UDP server in C++ and JAVA and it always worked.
I've tried also with a "select" passing a list with the socket to the xread argument, in order to get an event of file descriptor disruption from select instead that from recvfrom, but select seems to be "insensible" to the close too.
I need to have a unique code which maintain the same behavior on Linux and Windows with python 2.5 - 2.6.
Thanks.
A:
The usual solution is to have a pipe tell the worker thread when to die.
Create a pipe using os.pipe. This gives you a socket with both the reading and writing ends in the same program. It returns raw file descriptors, which you can use as-is (os.read and os.write) or turn into Python file objects using os.fdopen.
The worker thread waits on both the network socket and the read end of the pipe using select.select. When the pipe becomes readable, the worker thread cleans up and exits. Don't read the data, ignore it: its arrival is the message.
When the master thread wants to kill the worker, it writes a byte (any value) to the write end of the pipe. The master thread then joins the worker thread, then closes the pipe (remember to close both ends).
P.S. Closing an in-use socket is a bad idea in a multi-threaded program. The Linux close(2) manpage says:
It is probably unwise to close file descriptors while they may be in use by system calls in other threads in the same process. Since a file descriptor may be re-used, there are some obscure race conditions that may cause unintended side effects.
So it's lucky your first approach did not work!
A:
This is not java. Good hints:
Don't use threads. Use asynchronous IO.
Use a higher level networking framework
Here's an example using twisted:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor, stdio
from twisted.protocols.basic import LineReceiver
class UDPLogger(DatagramProtocol):
def datagramReceived(self, data, (host, port)):
print "received %r from %s:%d" % (data, host, port)
class ConsoleCommands(LineReceiver):
delimiter = '\n'
prompt_string = 'myserver> '
def connectionMade(self):
self.sendLine('My Server Admin Console!')
self.transport.write(self.prompt_string)
def lineReceived(self, line):
line = line.strip()
if line:
if line == 'quit':
reactor.stop()
elif line == 'start':
reactor.listenUDP(8888, UDPLogger())
self.sendLine('listening on udp 8888')
else:
self.sendLine('Unknown command: %r' % (line,))
self.transport.write(self.prompt_string)
stdio.StandardIO(ConsoleCommands())
reactor.run()
Example session:
My Server Admin Console!
myserver> foo
Unknown command: 'foo'
myserver> start
listening on udp 8888
myserver> quit
| Python : How to close a UDP socket while is waiting for data in recv? | let's consider this code in python:
import socket
import threading
import sys
import select
class UDPServer:
def __init__(self):
self.s=None
self.t=None
def start(self,port=8888):
if not self.s:
self.s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.s.bind(("",port))
self.t=threading.Thread(target=self.run)
self.t.start()
def stop(self):
if self.s:
self.s.close()
self.t.join()
self.t=None
def run(self):
while True:
try:
#receive data
data,addr=self.s.recvfrom(1024)
self.onPacket(addr,data)
except:
break
self.s=None
def onPacket(self,addr,data):
print addr,data
us=UDPServer()
while True:
sys.stdout.write("UDP server> ")
cmd=sys.stdin.readline()
if cmd=="start\n":
print "starting server..."
us.start(8888)
print "done"
elif cmd=="stop\n":
print "stopping server..."
us.stop()
print "done"
elif cmd=="quit\n":
print "Quitting ..."
us.stop()
break;
print "bye bye"
It runs an interactive shell with which I can start and stop an UDP server.
The server is implemented through a class which launches a thread in which there's a infinite loop of recv/onPacket callback inside a try/except block which should detect the error and the exits from the loop.
What I expect is that when I type "stop" on the shell the socket is closed and an exception is raised by the recvfrom function because of the invalidation of the file descriptor.
Instead, it seems that recvfrom still to block the thread waiting for data even after the close call.
Why this strange behavior ?
I've always used this patter to implements an UDP server in C++ and JAVA and it always worked.
I've tried also with a "select" passing a list with the socket to the xread argument, in order to get an event of file descriptor disruption from select instead that from recvfrom, but select seems to be "insensible" to the close too.
I need to have a unique code which maintain the same behavior on Linux and Windows with python 2.5 - 2.6.
Thanks.
| [
"The usual solution is to have a pipe tell the worker thread when to die.\n\nCreate a pipe using os.pipe. This gives you a socket with both the reading and writing ends in the same program. It returns raw file descriptors, which you can use as-is (os.read and os.write) or turn into Python file objects using os.fdopen.\nThe worker thread waits on both the network socket and the read end of the pipe using select.select. When the pipe becomes readable, the worker thread cleans up and exits. Don't read the data, ignore it: its arrival is the message.\nWhen the master thread wants to kill the worker, it writes a byte (any value) to the write end of the pipe. The master thread then joins the worker thread, then closes the pipe (remember to close both ends).\n\nP.S. Closing an in-use socket is a bad idea in a multi-threaded program. The Linux close(2) manpage says:\n\nIt is probably unwise to close file descriptors while they may be in use by system calls in other threads in the same process. Since a file descriptor may be re-used, there are some obscure race conditions that may cause unintended side effects.\n\nSo it's lucky your first approach did not work!\n",
"This is not java. Good hints:\n\nDon't use threads. Use asynchronous IO.\nUse a higher level networking framework\n\nHere's an example using twisted:\nfrom twisted.internet.protocol import DatagramProtocol\nfrom twisted.internet import reactor, stdio\nfrom twisted.protocols.basic import LineReceiver\n\nclass UDPLogger(DatagramProtocol): \n def datagramReceived(self, data, (host, port)):\n print \"received %r from %s:%d\" % (data, host, port)\n\n\nclass ConsoleCommands(LineReceiver):\n delimiter = '\\n'\n prompt_string = 'myserver> '\n\n def connectionMade(self):\n self.sendLine('My Server Admin Console!')\n self.transport.write(self.prompt_string)\n\n def lineReceived(self, line):\n line = line.strip()\n if line:\n if line == 'quit':\n reactor.stop()\n elif line == 'start':\n reactor.listenUDP(8888, UDPLogger())\n self.sendLine('listening on udp 8888')\n else:\n self.sendLine('Unknown command: %r' % (line,))\n self.transport.write(self.prompt_string)\n\nstdio.StandardIO(ConsoleCommands())\nreactor.run()\n\nExample session:\nMy Server Admin Console!\nmyserver> foo \nUnknown command: 'foo'\nmyserver> start\nlistening on udp 8888\nmyserver> quit\n\n"
] | [
4,
1
] | [] | [] | [
"multithreading",
"python",
"recv",
"sockets"
] | stackoverflow_0002912245_multithreading_python_recv_sockets.txt |
Q:
ctypes DLL with optional dependencies
Disclaimer: I'm new to windows programming so some of my assumptions may be wrong. Please correct me if so.
I am developing a python wrapper for a C API using ctypes. The API ships with both 64 and 32 DLLs/LIBs. I can succesfully load the DLL using ctypes.WinDLL('TheLibName') and call functions etc etc.
However some functions were not doing what they should. Upon further investigation it appears that the 32bit DLL is being used, which is what is causing the unexpected behaviour.
I have tried using ctypes.WinDLL('TheLibName64') but the module is not found. I have tried registering the DLL with regsrv32, but it reports there is no entry point (it also reports no entry point when I try and register TheLibName, which is found by WinDLL().
The DLL came with a sample project in Visual Studio (I have 0 experience with VS so again please correct me here) which builds both 32 and 64 bit versions of the sample project. In the .vcsproj file the configurations for the 64 bit version include:
AdditionalDependencies="TheLibName64.lib"
in the VCLinkerTool section.
In windows/system32 there are both TheLibName.dll/.lib, and TheLibName64.dll/.lib.
So it seems to me that my problem is now to make the python ctypes DLL loader load these optional dependencies when the DLL is loaded. However I can't find any information on this (perhaps because, as a doze noob, I do not know the correct terminology) in the ctypes documentation.
Is there a way to do this in ctypes? Am I going about this in completely the wrong way? Any help or general information about optional DLL dependencies and how they are loaded in windows would be much appreciated.
Thanks
A:
I can load LibName64 when I use the 64 bit version of python. Should have tried that earlier!
| ctypes DLL with optional dependencies | Disclaimer: I'm new to windows programming so some of my assumptions may be wrong. Please correct me if so.
I am developing a python wrapper for a C API using ctypes. The API ships with both 64 and 32 DLLs/LIBs. I can succesfully load the DLL using ctypes.WinDLL('TheLibName') and call functions etc etc.
However some functions were not doing what they should. Upon further investigation it appears that the 32bit DLL is being used, which is what is causing the unexpected behaviour.
I have tried using ctypes.WinDLL('TheLibName64') but the module is not found. I have tried registering the DLL with regsrv32, but it reports there is no entry point (it also reports no entry point when I try and register TheLibName, which is found by WinDLL().
The DLL came with a sample project in Visual Studio (I have 0 experience with VS so again please correct me here) which builds both 32 and 64 bit versions of the sample project. In the .vcsproj file the configurations for the 64 bit version include:
AdditionalDependencies="TheLibName64.lib"
in the VCLinkerTool section.
In windows/system32 there are both TheLibName.dll/.lib, and TheLibName64.dll/.lib.
So it seems to me that my problem is now to make the python ctypes DLL loader load these optional dependencies when the DLL is loaded. However I can't find any information on this (perhaps because, as a doze noob, I do not know the correct terminology) in the ctypes documentation.
Is there a way to do this in ctypes? Am I going about this in completely the wrong way? Any help or general information about optional DLL dependencies and how they are loaded in windows would be much appreciated.
Thanks
| [
"I can load LibName64 when I use the 64 bit version of python. Should have tried that earlier!\n"
] | [
0
] | [] | [] | [
"ctypes",
"dll",
"python",
"visual_studio",
"windows"
] | stackoverflow_0002914585_ctypes_dll_python_visual_studio_windows.txt |
Q:
How can I share data (which is updated every minute) accoss modules in Python?
I have read in many posts that global variables are bad, but I need them!
My situation:
I have few variables defined in a dedicated module which are updated every minute and are used by other modules in the application. (Implemented after reading this), Do you think its a good approach or needs any improvement or any better idea?
Thanks
A:
This sounds like a good place for the pub/sub technique, where you have objects watch for changes. This is useful in things like GUIs, when you need to update some widget whenever the value it displays changes.
Something very simple:
>>> class Widget(object):
def __init__(self, name, val):
self.name = name
self.val = val
def update(self, val):
self.val = val
print self.name, "changed to", self.val
>>> def update(updateables, val):
for u in updateables:
u(val)
>>> w1, w2 = Widget("Alpha", 5), Widget("Beta", 6)
>>> updateables = [w1.update, w2.update]
>>> update(updateables, 17)
Alpha changed to 17
Beta changed to 17
The idea is that "observers" of the value register a callback, which gets invoked whenever that value changes.
A:
I think that's fine. You're not actually using globals (as in, using the 'global' keyword). You're importing a module and then accessing that module from other modules. Seems like a fine solution to me.
How much data are you moving around? Because you could use a datastore, like SQLite and each module could read and write to the datastore as needed. But with updates every minute you probably don't need persistance or relations, making your existing solution the simpler one.
[edited much later]
Come to think of it, an in-memory SQLite database might hit your sweet spot here:
http://www.sqlite.org/inmemorydb.html
| How can I share data (which is updated every minute) accoss modules in Python? | I have read in many posts that global variables are bad, but I need them!
My situation:
I have few variables defined in a dedicated module which are updated every minute and are used by other modules in the application. (Implemented after reading this), Do you think its a good approach or needs any improvement or any better idea?
Thanks
| [
"This sounds like a good place for the pub/sub technique, where you have objects watch for changes. This is useful in things like GUIs, when you need to update some widget whenever the value it displays changes.\nSomething very simple:\n>>> class Widget(object):\n def __init__(self, name, val):\n self.name = name\n self.val = val\n def update(self, val):\n self.val = val\n print self.name, \"changed to\", self.val\n\n\n>>> def update(updateables, val):\n for u in updateables:\n u(val)\n\n\n>>> w1, w2 = Widget(\"Alpha\", 5), Widget(\"Beta\", 6)\n>>> updateables = [w1.update, w2.update]\n>>> update(updateables, 17)\nAlpha changed to 17\nBeta changed to 17\n\nThe idea is that \"observers\" of the value register a callback, which gets invoked whenever that value changes.\n",
"I think that's fine. You're not actually using globals (as in, using the 'global' keyword). You're importing a module and then accessing that module from other modules. Seems like a fine solution to me.\nHow much data are you moving around? Because you could use a datastore, like SQLite and each module could read and write to the datastore as needed. But with updates every minute you probably don't need persistance or relations, making your existing solution the simpler one.\n[edited much later]\nCome to think of it, an in-memory SQLite database might hit your sweet spot here:\nhttp://www.sqlite.org/inmemorydb.html\n"
] | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0002914823_python.txt |
Q:
Saving a Django form to a csv file
I have a Django form that is working fine. I'd like to save the data it submits to a CSV file. Is there a "best practice" way to do this?
I need to include blank fields in the CSV file where the user has not filled in a "required=False" field
A:
You can find the document CSV File Reading and Writing very helpful for your problem.
| Saving a Django form to a csv file | I have a Django form that is working fine. I'd like to save the data it submits to a CSV file. Is there a "best practice" way to do this?
I need to include blank fields in the CSV file where the user has not filled in a "required=False" field
| [
"You can find the document CSV File Reading and Writing very helpful for your problem.\n"
] | [
1
] | [] | [] | [
"django",
"django_forms",
"forms",
"python"
] | stackoverflow_0002915045_django_django_forms_forms_python.txt |
Q:
How to optimize this Python code?
def maxVote(nLabels):
count = {}
maxList = []
maxCount = 0
for nLabel in nLabels:
if nLabel in count:
count[nLabel] += 1
else:
count[nLabel] = 1
#Check if the count is max
if count[nLabel] > maxCount:
maxCount = count[nLabel]
maxList = [nLabel,]
elif count[nLabel]==maxCount:
maxList.append(nLabel)
return random.choice(maxList)
nLabels contains a list of integers.
The above function returns the integer with highest frequency, if more than one have same frequency then a randomly selected integer from them is returned.
E.g. maxVote([1,3,4,5,5,5,3,12,11]) is 5
A:
import random
import collections
def maxvote(nlabels):
cnt = collections.defaultdict(int)
for i in nlabels:
cnt[i] += 1
maxv = max(cnt.itervalues())
return random.choice([k for k,v in cnt.iteritems() if v == maxv])
print maxvote([1,3,4,5,5,5,3,3,11])
A:
In Python 3.1 or future 2.7 you'd be able to use Counter:
>>> from collections import Counter
>>> Counter([1,3,4,5,5,5,3,12,11]).most_common(1)
[(5, 3)]
If you don't have access to those versions of Python you could do:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in nLabels:
d[i] += 1
>>> max(d, key=lambda x: d[x])
5
A:
It appears to run in O(n) time. However there may be a bottleneck in checking if nLabel in count since this operation could also potentially run O(n) time as well, making the total efficiency O(n^2).
Using a dictionary instead of a list in this case is the only major efficiency boost I can spot.
A:
I'm not sure what exactly you want to optimize, but this should work:
from collections import defaultdict
def maxVote(nLabels):
count = defaultdict(int)
for nLabel in nLabels:
count[nLabel] += 1
maxCount = max(count.itervalues())
maxList = [k for k in count if count[k] == maxCount]
return random.choice(maxList)
A:
Idea 1
Does the return really need to be random, or can you just return a maximum? If you just need to nondeterministically return a max frequency, you could just store a single label and remove the list logic, including
elif count[nLabel]==maxCount:
maxList.append(nLabel)
Idea 2
If this method is called frequently, would it be possible to only work on new data, as opposed to the entire data set? You could cache your count map and then only process new data. Assuming your data set is large and the calculations are done online, this could net huge improvements.
A:
Complete example:
#!/usr/bin/env python
def max_vote(l):
"""
Return the element with the (or a) maximum frequency in ``l``.
"""
unsorted = [(a, l.count(a)) for a in set(l)]
return sorted(unsorted, key=lambda x: x[1]).pop()[0]
if __name__ == '__main__':
votes = [1, 3, 4, 5, 5, 5, 3, 12, 11]
print max_vote(votes)
# => 5
Benchmarks:
#!/usr/bin/env python
import random
import collections
def max_vote_2(l):
"""
Return the element with the (or a) maximum frequency in ``l``.
"""
unsorted = [(a, l.count(a)) for a in set(l)]
return sorted(unsorted, key=lambda x: x[1]).pop()[0]
def max_vote_1(nlabels):
cnt = collections.defaultdict(int)
for i in nlabels:
cnt[i] += 1
maxv = max(cnt.itervalues())
return random.choice([k for k,v in cnt.iteritems() if v == maxv])
if __name__ == '__main__':
from timeit import Timer
votes = [1, 3, 4, 5, 5, 5, 3, 12, 11]
print max_vote_1(votes)
print max_vote_2(votes)
t = Timer("votes = [1, 3, 4, 5, 5, 5, 3, 12, 11]; max_vote_2(votes)", \
"from __main__ import max_vote_2")
print 'max_vote_2', t.timeit(number=100000)
t = Timer("votes = [1, 3, 4, 5, 5, 5, 3, 12, 11]; max_vote_1(votes)", \
"from __main__ import max_vote_1")
print 'max_vote_1', t.timeit(number=100000)
Yields:
5
5
max_vote_2 1.79455208778
max_vote_1 2.31705093384
| How to optimize this Python code? | def maxVote(nLabels):
count = {}
maxList = []
maxCount = 0
for nLabel in nLabels:
if nLabel in count:
count[nLabel] += 1
else:
count[nLabel] = 1
#Check if the count is max
if count[nLabel] > maxCount:
maxCount = count[nLabel]
maxList = [nLabel,]
elif count[nLabel]==maxCount:
maxList.append(nLabel)
return random.choice(maxList)
nLabels contains a list of integers.
The above function returns the integer with highest frequency, if more than one have same frequency then a randomly selected integer from them is returned.
E.g. maxVote([1,3,4,5,5,5,3,12,11]) is 5
| [
"import random\nimport collections\n\ndef maxvote(nlabels):\n cnt = collections.defaultdict(int)\n for i in nlabels:\n cnt[i] += 1\n maxv = max(cnt.itervalues())\n return random.choice([k for k,v in cnt.iteritems() if v == maxv])\n\nprint maxvote([1,3,4,5,5,5,3,3,11])\n\n",
"In Python 3.1 or future 2.7 you'd be able to use Counter:\n>>> from collections import Counter\n>>> Counter([1,3,4,5,5,5,3,12,11]).most_common(1)\n[(5, 3)]\n\nIf you don't have access to those versions of Python you could do:\n>>> from collections import defaultdict\n>>> d = defaultdict(int)\n>>> for i in nLabels:\n d[i] += 1\n\n\n>>> max(d, key=lambda x: d[x])\n5\n\n",
"It appears to run in O(n) time. However there may be a bottleneck in checking if nLabel in count since this operation could also potentially run O(n) time as well, making the total efficiency O(n^2). \nUsing a dictionary instead of a list in this case is the only major efficiency boost I can spot.\n",
"I'm not sure what exactly you want to optimize, but this should work:\nfrom collections import defaultdict\n\ndef maxVote(nLabels):\n count = defaultdict(int)\n for nLabel in nLabels:\n count[nLabel] += 1\n maxCount = max(count.itervalues())\n maxList = [k for k in count if count[k] == maxCount]\n return random.choice(maxList)\n\n",
"Idea 1\nDoes the return really need to be random, or can you just return a maximum? If you just need to nondeterministically return a max frequency, you could just store a single label and remove the list logic, including\n elif count[nLabel]==maxCount:\n maxList.append(nLabel)\n\nIdea 2\nIf this method is called frequently, would it be possible to only work on new data, as opposed to the entire data set? You could cache your count map and then only process new data. Assuming your data set is large and the calculations are done online, this could net huge improvements.\n",
"Complete example:\n#!/usr/bin/env python\n\ndef max_vote(l):\n \"\"\"\n Return the element with the (or a) maximum frequency in ``l``.\n \"\"\"\n unsorted = [(a, l.count(a)) for a in set(l)]\n return sorted(unsorted, key=lambda x: x[1]).pop()[0]\n\nif __name__ == '__main__':\n votes = [1, 3, 4, 5, 5, 5, 3, 12, 11]\n print max_vote(votes)\n # => 5\n\n\nBenchmarks:\n#!/usr/bin/env python\n\nimport random\nimport collections\n\ndef max_vote_2(l):\n \"\"\"\n Return the element with the (or a) maximum frequency in ``l``.\n \"\"\"\n unsorted = [(a, l.count(a)) for a in set(l)]\n return sorted(unsorted, key=lambda x: x[1]).pop()[0]\n\ndef max_vote_1(nlabels):\n cnt = collections.defaultdict(int)\n for i in nlabels:\n cnt[i] += 1\n maxv = max(cnt.itervalues())\n return random.choice([k for k,v in cnt.iteritems() if v == maxv])\n\nif __name__ == '__main__':\n from timeit import Timer\n votes = [1, 3, 4, 5, 5, 5, 3, 12, 11]\n print max_vote_1(votes)\n print max_vote_2(votes)\n\n t = Timer(\"votes = [1, 3, 4, 5, 5, 5, 3, 12, 11]; max_vote_2(votes)\", \\\n \"from __main__ import max_vote_2\")\n print 'max_vote_2', t.timeit(number=100000)\n\n t = Timer(\"votes = [1, 3, 4, 5, 5, 5, 3, 12, 11]; max_vote_1(votes)\", \\\n \"from __main__ import max_vote_1\")\n print 'max_vote_1', t.timeit(number=100000)\n\nYields:\n5\n5\nmax_vote_2 1.79455208778\nmax_vote_1 2.31705093384\n\n"
] | [
6,
5,
2,
1,
0,
0
] | [] | [] | [
"algorithm",
"data_structures",
"python"
] | stackoverflow_0002915095_algorithm_data_structures_python.txt |
Q:
jEdit+JythonInterpreter: how to import java class?
I'm running jEdit with the JythonInterprete and I have a .jar file called JavaTest.jar.
JavaTest has a class called SampleJavaClass which has a method printerCount.
From my .py file, I want to do:
from javatest import SampleJavaClass
class SampleClass(SampleJavaClass):
def pymain(self):
SampleJavaClass.printerCount(4)
Java code:
package javatest;
public class SampleJavaClass {
public static void printerCount(int i){
for(int j=0; j< i; j++){
System.out.println("hello world");
}
}
(etc...)
In the JythonInterpreter, I have already tried clicking "Edit Jython Path" and adding the .jar file then running the interpreter again, but it still gives me ImportError: cannot import name SampleJavaClass
A:
You need to add the JavaTest.jar to the Java classpath used by jEdit. The Jython path is used to tell Jython where the Python modules are, the Java classpath is used to tell the JVM where the Java jars are. In order to access javatest.SampleJavaClass in Jython the JVM must first be able to find it. It will then make it available to the Jython interpreter and your code should run.
I'm not that familiar with how to set the JVM classpath in jEdit but I did find this wiki page which may hold the answer.
| jEdit+JythonInterpreter: how to import java class? | I'm running jEdit with the JythonInterprete and I have a .jar file called JavaTest.jar.
JavaTest has a class called SampleJavaClass which has a method printerCount.
From my .py file, I want to do:
from javatest import SampleJavaClass
class SampleClass(SampleJavaClass):
def pymain(self):
SampleJavaClass.printerCount(4)
Java code:
package javatest;
public class SampleJavaClass {
public static void printerCount(int i){
for(int j=0; j< i; j++){
System.out.println("hello world");
}
}
(etc...)
In the JythonInterpreter, I have already tried clicking "Edit Jython Path" and adding the .jar file then running the interpreter again, but it still gives me ImportError: cannot import name SampleJavaClass
| [
"You need to add the JavaTest.jar to the Java classpath used by jEdit. The Jython path is used to tell Jython where the Python modules are, the Java classpath is used to tell the JVM where the Java jars are. In order to access javatest.SampleJavaClass in Jython the JVM must first be able to find it. It will then make it available to the Jython interpreter and your code should run.\nI'm not that familiar with how to set the JVM classpath in jEdit but I did find this wiki page which may hold the answer.\n"
] | [
2
] | [] | [] | [
"java",
"jedit",
"jython",
"python"
] | stackoverflow_0002906074_java_jedit_jython_python.txt |
Q:
Python FTP grabbing and saving images issue
EDIT: I got it working it just won't download anything...
So here is my code simplified now:
notions_ftp = ftplib.FTP(ftp_host, ftp_user, ftp_passwd)
folder = "Leisure Arts - Images"
notions_ftp.cwd(folder)
image = open("015693PR-com.jpg","wb")
notions_ftp.retrlines("RETR 015693PR-com.jpg", image.write)
send_image = open("015693PR-com.jpg", 'r')
And Here is my output:
'250 "/Leisure Arts - Images": is current directory.'
'226 Transfer complete. 0 bytes in 0.00 sec. (0.000 Kb/s)'
Original Post:
OK So I have been messing with this all day long. I am fairly new to Python FTP. So I have searched through here and came up w/ this:
images = notions_ftp.nlst()
for image_name in image_names:
if found_url == False:
try:
for image in images:
ftp_image_name = "./%s" % image_name
if ftp_image_name == image:
found_url = True
image_name_we_want = image_name
except:
pass
# We failed to find an image for this product, it will have to be done manually
if found_url == False:
log.info("Image ain't there baby -- SKU: %s" % sku)
return False
# Hey we found something! Open the image....
notions_ftp.retrlines("RETR %s" % image_name_we_want, open(image_name_we_want, "rb"))
1/0
So I have narrowed the error down to the line before I divide by zero. Here is the error:
Traceback (most recent call last):
File "<console>", line 6, in <module>
File "<console>", line 39, in insert_image
IOError: [Errno 2] No such file or directory: '411483CC-IT,IM.jpg'
So if you follow the code you will see that the image IS in the directory because image_name_we_want is set if found in that directory listing on the first line of my code. And I KNOW it's there because I am looking at the FTP site myself and ...it's freakin there. So at some point during all of this I got the image to save locally, which is most desired, but I have long since forgot what I used to make it do that. Either way, why does it think that the image isn't there when it clearly finds it in the listing.
OK so I took the suggestion and now I get:
14:01:18,057 ERROR [pylons-admin] Image to big or corrupt! Skipping Image for product sku: 411483
14:01:18,057 ERROR [pylons-admin] Image to big or corrupt! Skipping Image for product sku: 411483
Traceback (most recent call last):
File "<console>", line 6, in <module>
File "<console>", line 40, in insert_image
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ftplib.py", line 418, in retrlines
callback(line)
TypeError: 'file' object is not callable
>>> 14:01:24,694 INFO [pylons-admin] Script Done! Updated 0 Products w/ Images
So it got the first image, which I think really is corrupt, but then when it goes on to the next one to be processed it throws that error on the file object. So here is how I changed it and the rest of the code not put here in the first place:
# Hey we found something! Open the image....
f = open(image_name_we_want, "wb")
notions_ftp.retrlines("RETR %s" % image_name_we_want, f)
send_image = open(image_name_we_want, 'r')
# ...and send it for processing
try:
image_id = product_obj.set_image(send_image, 5, 1)
except IOError, error:
log.error("Image to big or corrupt! Skipping Image for product sku: %s" % sku)
image_id = False
else:
if image_id == False:
log.error("Could not Insert the image for product sku: %s" % sku)
f.close()
return False
else:
f.close()
os.remove(image_name_we_want)
return True
A:
You're reading the file instead of writing it.
So instead of open(image_name_we_want, "rb") use open(image_name_we_want, "wb")
[edit]
If you're simply fetching from an ftp server than you could also try this:
import urllib2
fh = urllib2.urlopen('ftp://server/path/file.png')
file('file.png', 'wb').write(fh.read())
Also, for a fully working example read this: http://docs.python.org/library/ftplib.html
You're also missing the write after the open()
| Python FTP grabbing and saving images issue | EDIT: I got it working it just won't download anything...
So here is my code simplified now:
notions_ftp = ftplib.FTP(ftp_host, ftp_user, ftp_passwd)
folder = "Leisure Arts - Images"
notions_ftp.cwd(folder)
image = open("015693PR-com.jpg","wb")
notions_ftp.retrlines("RETR 015693PR-com.jpg", image.write)
send_image = open("015693PR-com.jpg", 'r')
And Here is my output:
'250 "/Leisure Arts - Images": is current directory.'
'226 Transfer complete. 0 bytes in 0.00 sec. (0.000 Kb/s)'
Original Post:
OK So I have been messing with this all day long. I am fairly new to Python FTP. So I have searched through here and came up w/ this:
images = notions_ftp.nlst()
for image_name in image_names:
if found_url == False:
try:
for image in images:
ftp_image_name = "./%s" % image_name
if ftp_image_name == image:
found_url = True
image_name_we_want = image_name
except:
pass
# We failed to find an image for this product, it will have to be done manually
if found_url == False:
log.info("Image ain't there baby -- SKU: %s" % sku)
return False
# Hey we found something! Open the image....
notions_ftp.retrlines("RETR %s" % image_name_we_want, open(image_name_we_want, "rb"))
1/0
So I have narrowed the error down to the line before I divide by zero. Here is the error:
Traceback (most recent call last):
File "<console>", line 6, in <module>
File "<console>", line 39, in insert_image
IOError: [Errno 2] No such file or directory: '411483CC-IT,IM.jpg'
So if you follow the code you will see that the image IS in the directory because image_name_we_want is set if found in that directory listing on the first line of my code. And I KNOW it's there because I am looking at the FTP site myself and ...it's freakin there. So at some point during all of this I got the image to save locally, which is most desired, but I have long since forgot what I used to make it do that. Either way, why does it think that the image isn't there when it clearly finds it in the listing.
OK so I took the suggestion and now I get:
14:01:18,057 ERROR [pylons-admin] Image to big or corrupt! Skipping Image for product sku: 411483
14:01:18,057 ERROR [pylons-admin] Image to big or corrupt! Skipping Image for product sku: 411483
Traceback (most recent call last):
File "<console>", line 6, in <module>
File "<console>", line 40, in insert_image
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ftplib.py", line 418, in retrlines
callback(line)
TypeError: 'file' object is not callable
>>> 14:01:24,694 INFO [pylons-admin] Script Done! Updated 0 Products w/ Images
So it got the first image, which I think really is corrupt, but then when it goes on to the next one to be processed it throws that error on the file object. So here is how I changed it and the rest of the code not put here in the first place:
# Hey we found something! Open the image....
f = open(image_name_we_want, "wb")
notions_ftp.retrlines("RETR %s" % image_name_we_want, f)
send_image = open(image_name_we_want, 'r')
# ...and send it for processing
try:
image_id = product_obj.set_image(send_image, 5, 1)
except IOError, error:
log.error("Image to big or corrupt! Skipping Image for product sku: %s" % sku)
image_id = False
else:
if image_id == False:
log.error("Could not Insert the image for product sku: %s" % sku)
f.close()
return False
else:
f.close()
os.remove(image_name_we_want)
return True
| [
"You're reading the file instead of writing it.\nSo instead of open(image_name_we_want, \"rb\") use open(image_name_we_want, \"wb\")\n[edit]\nIf you're simply fetching from an ftp server than you could also try this:\nimport urllib2\nfh = urllib2.urlopen('ftp://server/path/file.png')\nfile('file.png', 'wb').write(fh.read())\n\nAlso, for a fully working example read this: http://docs.python.org/library/ftplib.html\nYou're also missing the write after the open()\n"
] | [
1
] | [] | [] | [
"ftp",
"image",
"python"
] | stackoverflow_0002915597_ftp_image_python.txt |
Q:
Getting Unit Tests to work with Komodo IDE for Python
I've tried to run the following code on Komodo IDE (for python):
import unittest
class MathLibraryTests(unittest.TestCase):
def test1Plus1Equals2(self):
self.assertEqual(1+1, 2)
Then, I created a new test plan, pointing to this project(file) directory and tried to run it the test plan. It seems to run but it doesn't seem to find any tests.
If I try to run the following code with the "regular" run command (F7)
class MathLibraryTests(unittest.TestCase):
def testPlus1Equals2(self):
self.assertEqual(1+1, 2)
if __name__ == "__main__":
unittest.main()
it works. I get the following output:
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
What might I be doing wrong?
A:
For the test file to be picked up the filename must start with test_. I tried using just test.py which failed, however test_.py works like a dream.
All you need to do is rename your file. This is not made very clear in the documentation - I worked it out via a bug report on Komodo's web site.
It would be nice if Komodo gave at least a clue to the problem!
| Getting Unit Tests to work with Komodo IDE for Python | I've tried to run the following code on Komodo IDE (for python):
import unittest
class MathLibraryTests(unittest.TestCase):
def test1Plus1Equals2(self):
self.assertEqual(1+1, 2)
Then, I created a new test plan, pointing to this project(file) directory and tried to run it the test plan. It seems to run but it doesn't seem to find any tests.
If I try to run the following code with the "regular" run command (F7)
class MathLibraryTests(unittest.TestCase):
def testPlus1Equals2(self):
self.assertEqual(1+1, 2)
if __name__ == "__main__":
unittest.main()
it works. I get the following output:
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
What might I be doing wrong?
| [
"For the test file to be picked up the filename must start with test_. I tried using just test.py which failed, however test_.py works like a dream.\nAll you need to do is rename your file. This is not made very clear in the documentation - I worked it out via a bug report on Komodo's web site.\nIt would be nice if Komodo gave at least a clue to the problem!\n"
] | [
6
] | [] | [] | [
"ide",
"komodo",
"python",
"unit_testing"
] | stackoverflow_0002870319_ide_komodo_python_unit_testing.txt |
Q:
Convert GeoTIFF to JPEG and Extract GeoTIFF Headers in Python
I am making a Python script which will read in a GeoTIFF file, and will do both: convert the GeoTIFF into a static JPEG (that is much smaller in size), and create a separate text file which contains the GeoTIFF headers.
Using the Python GDAL API, I am able to get the script to open a GeoTIFF file, and print details, such as the RasterXSize, RasterYSize, RasterCount, etc.
The problem is with saving a JPEG. I have researched the driver.CreateCopy() method, however, all it does is create a very large JPEG file that is blank and can't be opened.
Also, which method retrieves all of the GeoTIFF Headers that I can save to a file?
I'm neither an expert on GeoTIFFs nor GDAL, and I greatly appreciate the assistance!
A:
I figured it out myself with some Googling.
To save the .jpg file with varying level of quality, you need to use the following code:
# Assume this retrieves the dataset from a GeoTIFF file.
dataset = getDataSet(tiffFileLocation)
saveOptions = []
saveOptions.append("QUALITY=75")
# Obtains a JPEG GDAL driver
jpegDriver = gdal.GetDriverByName("JPEG")
# Create the .JPG file
jpegDriver.CreateCopy("imageFile.jpg", dataset, 0, saveOptions)
The parameters I need are stored in both the theDataset.GetGeoTransform(), and the theDataset.GetProjection() methods.
Special thanks to this site: http://adventuresindevelopment.blogspot.com/2008/12/python-gdal-set-jpeg-quality-values-and.html
| Convert GeoTIFF to JPEG and Extract GeoTIFF Headers in Python | I am making a Python script which will read in a GeoTIFF file, and will do both: convert the GeoTIFF into a static JPEG (that is much smaller in size), and create a separate text file which contains the GeoTIFF headers.
Using the Python GDAL API, I am able to get the script to open a GeoTIFF file, and print details, such as the RasterXSize, RasterYSize, RasterCount, etc.
The problem is with saving a JPEG. I have researched the driver.CreateCopy() method, however, all it does is create a very large JPEG file that is blank and can't be opened.
Also, which method retrieves all of the GeoTIFF Headers that I can save to a file?
I'm neither an expert on GeoTIFFs nor GDAL, and I greatly appreciate the assistance!
| [
"I figured it out myself with some Googling.\nTo save the .jpg file with varying level of quality, you need to use the following code:\n# Assume this retrieves the dataset from a GeoTIFF file.\ndataset = getDataSet(tiffFileLocation) \n\nsaveOptions = []\nsaveOptions.append(\"QUALITY=75\")\n\n# Obtains a JPEG GDAL driver\njpegDriver = gdal.GetDriverByName(\"JPEG\") \n\n# Create the .JPG file\njpegDriver.CreateCopy(\"imageFile.jpg\", dataset, 0, saveOptions) \n\nThe parameters I need are stored in both the theDataset.GetGeoTransform(), and the theDataset.GetProjection() methods.\nSpecial thanks to this site: http://adventuresindevelopment.blogspot.com/2008/12/python-gdal-set-jpeg-quality-values-and.html\n"
] | [
8
] | [] | [] | [
"gdal",
"geospatial",
"jpeg",
"python",
"tiff"
] | stackoverflow_0002913208_gdal_geospatial_jpeg_python_tiff.txt |
Q:
Reliable and fast way to convert a zillion ODT files in PDF?
I need to pre-produce a million or two PDF files from a simple template (a few pages and tables) with embedded fonts. Usually, I would stay low level in a case like this, and compose everything with a library like ReportLab, but I joined late in the project.
Currently, I have a template.odt and use markers in the content.xml files to fill with data from a DB. I can smoothly create the ODT files, they always look rigth.
For the ODT to PDF conversion, I'm using openoffice in server mode (and PyODConverter w/ named pipe), but it's not very reliable: in a batch of documents, there is eventually a point after which all the processed files are converted into garbage (wrong fonts and letters sprawled all over the page).
Problem is not predictably reproducible (does not depend on the data), happens
in OOo 2.3 and 3.2, in Ubuntu, XP, Server 2003 and Windows 7. My Heisenbug detector is ticking.
I tried to reduce the size of batches and restarting OOo after each one; still, a small percentage of the documents
are messed up.
Of course I'll write about this on the Ooo mailing lists, but in the meanwhile, I have a delivery and lost too much time already.
Where do I go?
Completely avoid the ODT format and go for another template system.
Suggestions? Anything that takes a few seconds to run is way too slow. OOo takes around a second and it sums to 15 days of processing time. I had to write a program for clustering the jobs over several clients.
Keep the format but go for another tool/program for the conversion.
Which one? There are many apps in the shareware or commercial repositories for windows, but trying each one is a daunting task.
Some are too slow, some cannot be run in batch without buying it first, some cannot work from command line, etc.
Open source tools tend not to reinvent the wheel and often depend on openoffice.
Converting to an intermediate .DOC format could help to avoid the OOo bug, but it would double the processing time and complicate a task that is already too hairy.
Try to produce the PDFs twice and compare them, discarding the whole batch if there's something wrong.
Although the documents look equal, I know of no way to compare the binary content.
Restart OOo after processing each document.
it would take a lot more time to produce them
it would lower the percentage of the wrong files, and make it very hard to identify them.
Go for ReportLab and recreate the pages programmatically. This is the approach I'm going to try in a few minutes.
Learn to properly format bulleted lists
Thanks a lot.
Edit: it seems like I cannot use ReportLab at all, it won't let me embed the font.
My font comes in TrueType and OpenType versions.
The TrueType one says "TTFError: Font does not allow subsetting/embedding (0100) ".
The OpenType version says "TTFError[...] postscript outlines are not supported".
Very very funny.
A:
For creating such large amount of PDF files OpenOffice seems me the wrong product. You should use a real reporting solution which is optimized for creating large amount of PDF files. There many different tools. I would recommended i-net Clear Reports (used to be called i-net Crystal-Clear).
I would expect that one PDF file is faster created as with OpenOfice.
Creating 2 PDF files and comparing it will cost a lot of speed.
It can embedded True Type Fonts.
With the API you can work in a loop.
With a trial license you can work for 90 days on your batch
The disadvantages is that you must restart your development.
A:
I would probably end up finding some way to determine when the batch processing goes haywire, then reprocess everything from shortly before it failed. How to determine when it goes haywire? That will require analyzing some correct PDFs and some failed ones, to look for similarities among them:
generated files aren't the right size compared to their source
the files don't contain some string (like the name of your font)
some bit of data is not in the expected place
when converted back to text, they don't contain expected data from the template
when converted to a bitmap, text isn't in the right place
I suspect that converting them back to text and looking for expected strings is going to be the most accurate solution, but also slow. If it's too slow to run on every file, run it on every 1/100th or so, and just reconvert every file after the last known good one.
A:
For your scenario it seems that Reportlab PLUS is a good fit, including templates and phone support to get you going fast.
A:
Very interesting problem. Since you have already written it to cluster across several machines why not use the double production approach and spread it on EC2 nodes. It will cost a bit extra but you can compare stuff using md5 or sha hashes and if 2 versions are the same you can move on.
A:
For comparing 2 pdf files I would recommended i-net PDF content comparer. It can compare 2 directories of PDF files very good. We are use it in our regression test system.
| Reliable and fast way to convert a zillion ODT files in PDF? | I need to pre-produce a million or two PDF files from a simple template (a few pages and tables) with embedded fonts. Usually, I would stay low level in a case like this, and compose everything with a library like ReportLab, but I joined late in the project.
Currently, I have a template.odt and use markers in the content.xml files to fill with data from a DB. I can smoothly create the ODT files, they always look rigth.
For the ODT to PDF conversion, I'm using openoffice in server mode (and PyODConverter w/ named pipe), but it's not very reliable: in a batch of documents, there is eventually a point after which all the processed files are converted into garbage (wrong fonts and letters sprawled all over the page).
Problem is not predictably reproducible (does not depend on the data), happens
in OOo 2.3 and 3.2, in Ubuntu, XP, Server 2003 and Windows 7. My Heisenbug detector is ticking.
I tried to reduce the size of batches and restarting OOo after each one; still, a small percentage of the documents
are messed up.
Of course I'll write about this on the Ooo mailing lists, but in the meanwhile, I have a delivery and lost too much time already.
Where do I go?
Completely avoid the ODT format and go for another template system.
Suggestions? Anything that takes a few seconds to run is way too slow. OOo takes around a second and it sums to 15 days of processing time. I had to write a program for clustering the jobs over several clients.
Keep the format but go for another tool/program for the conversion.
Which one? There are many apps in the shareware or commercial repositories for windows, but trying each one is a daunting task.
Some are too slow, some cannot be run in batch without buying it first, some cannot work from command line, etc.
Open source tools tend not to reinvent the wheel and often depend on openoffice.
Converting to an intermediate .DOC format could help to avoid the OOo bug, but it would double the processing time and complicate a task that is already too hairy.
Try to produce the PDFs twice and compare them, discarding the whole batch if there's something wrong.
Although the documents look equal, I know of no way to compare the binary content.
Restart OOo after processing each document.
it would take a lot more time to produce them
it would lower the percentage of the wrong files, and make it very hard to identify them.
Go for ReportLab and recreate the pages programmatically. This is the approach I'm going to try in a few minutes.
Learn to properly format bulleted lists
Thanks a lot.
Edit: it seems like I cannot use ReportLab at all, it won't let me embed the font.
My font comes in TrueType and OpenType versions.
The TrueType one says "TTFError: Font does not allow subsetting/embedding (0100) ".
The OpenType version says "TTFError[...] postscript outlines are not supported".
Very very funny.
| [
"For creating such large amount of PDF files OpenOffice seems me the wrong product. You should use a real reporting solution which is optimized for creating large amount of PDF files. There many different tools. I would recommended i-net Clear Reports (used to be called i-net Crystal-Clear).\n\nI would expect that one PDF file is faster created as with OpenOfice.\nCreating 2 PDF files and comparing it will cost a lot of speed.\nIt can embedded True Type Fonts.\nWith the API you can work in a loop.\nWith a trial license you can work for 90 days on your batch\n\nThe disadvantages is that you must restart your development.\n",
"I would probably end up finding some way to determine when the batch processing goes haywire, then reprocess everything from shortly before it failed. How to determine when it goes haywire? That will require analyzing some correct PDFs and some failed ones, to look for similarities among them:\n\ngenerated files aren't the right size compared to their source\nthe files don't contain some string (like the name of your font)\nsome bit of data is not in the expected place\nwhen converted back to text, they don't contain expected data from the template\nwhen converted to a bitmap, text isn't in the right place\n\nI suspect that converting them back to text and looking for expected strings is going to be the most accurate solution, but also slow. If it's too slow to run on every file, run it on every 1/100th or so, and just reconvert every file after the last known good one.\n",
"For your scenario it seems that Reportlab PLUS is a good fit, including templates and phone support to get you going fast. \n",
"Very interesting problem. Since you have already written it to cluster across several machines why not use the double production approach and spread it on EC2 nodes. It will cost a bit extra but you can compare stuff using md5 or sha hashes and if 2 versions are the same you can move on.\n",
"For comparing 2 pdf files I would recommended i-net PDF content comparer. It can compare 2 directories of PDF files very good. We are use it in our regression test system.\n"
] | [
3,
2,
0,
0,
0
] | [] | [] | [
"openoffice.org",
"pdf",
"python",
"reporting"
] | stackoverflow_0002903774_openoffice.org_pdf_python_reporting.txt |
Q:
Python - drag file into .exe to run script
I have a Python script that takes the directory path of a text file and converts it into an excel file. Currently I have it running as a console application (compiled with py2exe) and prompts the user for the directory path through raw_input().
How do i make it such that I can drag & drop my text file directly into the .exe of the python script?
A:
The dropped file will be available as an element of sys.argv.
| Python - drag file into .exe to run script | I have a Python script that takes the directory path of a text file and converts it into an excel file. Currently I have it running as a console application (compiled with py2exe) and prompts the user for the directory path through raw_input().
How do i make it such that I can drag & drop my text file directly into the .exe of the python script?
| [
"The dropped file will be available as an element of sys.argv.\n"
] | [
4
] | [] | [] | [
"drag_and_drop",
"executable",
"python"
] | stackoverflow_0002915945_drag_and_drop_executable_python.txt |
Q:
Loading a wave from waveid
I'm working on a small wave thingy where i need to load a wave based on an outside event. So i don't have a context to work with.
I've been looking at the python api for a while but i can't figure out the correct way to get a wave object (that i can then call CreateBlip() on) when i just have the waveid.
Is there something i've just overlooked? or do I have to make a 'raw' json request instead of using the api ?
A:
At Google I/O, the Wave Data API was announced which allows for pulling waves which haven't previously gotten a context as long as they're accessible to a @googlewave.com user authenticated through OAuth. However, this can not call CreateBlip()
A:
At the moment the answer is that i can't be done. Hopefully in a future version of the Api.
| Loading a wave from waveid | I'm working on a small wave thingy where i need to load a wave based on an outside event. So i don't have a context to work with.
I've been looking at the python api for a while but i can't figure out the correct way to get a wave object (that i can then call CreateBlip() on) when i just have the waveid.
Is there something i've just overlooked? or do I have to make a 'raw' json request instead of using the api ?
| [
"At Google I/O, the Wave Data API was announced which allows for pulling waves which haven't previously gotten a context as long as they're accessible to a @googlewave.com user authenticated through OAuth. However, this can not call CreateBlip()\n",
"At the moment the answer is that i can't be done. Hopefully in a future version of the Api. \n"
] | [
1,
0
] | [] | [] | [
"google_wave",
"python"
] | stackoverflow_0001876908_google_wave_python.txt |
Q:
What is the Pythonic way to implement a simple FSM?
Yesterday I had to parse a very simple binary data file - the rule is, look for two bytes in a row that are both 0xAA, then the next byte will be a length byte, then skip 9 bytes and output the given amount of data from there. Repeat to the end of the file.
My solution did work, and was very quick to put together (even though I am a C programmer at heart, I still think it was quicker for me to write this in Python than it would have been in C) - BUT, it is clearly not at all Pythonic and it reads like a C program (and not a very good one at that!)
What would be a better / more Pythonic approach to this? Is a simple FSM like this even still the right choice in Python?
My solution:
#! /usr/bin/python
import sys
f = open(sys.argv[1], "rb")
state = 0
if f:
for byte in f.read():
a = ord(byte)
if state == 0:
if a == 0xAA:
state = 1
elif state == 1:
if a == 0xAA:
state = 2
else:
state = 0
elif state == 2:
count = a;
skip = 9
state = 3
elif state == 3:
skip = skip -1
if skip == 0:
state = 4
elif state == 4:
print "%02x" %a
count = count -1
if count == 0:
state = 0
print "\r\n"
A:
The coolest way I've seen to implement FSMs in Python has to be via generators and coroutines. See this Charming Python post for an example. Eli Bendersky also has an excellent treatment of the subject.
If coroutines aren't familiar territory, David Beazley's A Curious Course on Coroutines and Concurrency is a stellar introduction.
A:
You could give your states constant names instead of using 0, 1, 2, etc. for improved readability.
You could use a dictionary to map (current_state, input) -> (next_state), but that doesn't really let you do any additional processing during the transitions. Unless you include some "transition function" too to do extra processing.
Or you could do a non-FSM approach. I think this will work as long as 0xAA 0xAA only appears when it indicates a "start" (doesn't appear in data).
with open(sys.argv[1], 'rb') as f:
contents = f.read()
for chunk in contents.split('\xaa\xaa')[1:]:
length = ord(chunk[0])
data = chunk[10:10+length]
print data
If it does appear in data, you can instead use string.find('\xaa\xaa', start) to scan through the string, setting the start argument to begin looking where the last data block ended. Repeat until it returns -1.
A:
I am a little apprehensive about telling anyone what's Pythonic, but here goes. First, keep in mind that in python functions are just objects. Transitions can be defined with a dictionary that has the (input, current_state) as the key and the tuple (next_state, action) as the value. Action is just a function that does whatever is necessary to transition from the current state to the next state.
There's a nice looking example of doing this at http://code.activestate.com/recipes/146262-finite-state-machine-fsm. I haven't used it, but from a quick read it seems like it covers everything.
A similar question was asked/answered here a couple of months ago: Python state-machine design. You might find looking at those responses useful as well.
A:
I think your solution looks fine, except you should replace count = count - 1 with count -= 1.
This is one of those times where fancy code-show-offs will come up ways of have dicts mapping states to callables, with a small driver function, but it isn't better, just fancier, and using more obscure language features.
A:
I suggest checking out chapter 4 of Text Processing in Python by David Mertz. He implements a state machine class in Python that is very elegant.
A:
I think the most pythonic way would by like what FogleBird suggested, but mapping from (current state, input) to a function which would handle the processing and transition.
A:
You can use regexps. Something like this code will find the first block of data. Then it's just a case of starting the next search from after the previous match.
find_header = re.compile('\xaa\xaa(.).{9}', re.DOTALL)
m = find_header.search(input_text)
if m:
length = chr(find_header.group(1))
data = input_text[m.end():m.end() + length]
| What is the Pythonic way to implement a simple FSM? | Yesterday I had to parse a very simple binary data file - the rule is, look for two bytes in a row that are both 0xAA, then the next byte will be a length byte, then skip 9 bytes and output the given amount of data from there. Repeat to the end of the file.
My solution did work, and was very quick to put together (even though I am a C programmer at heart, I still think it was quicker for me to write this in Python than it would have been in C) - BUT, it is clearly not at all Pythonic and it reads like a C program (and not a very good one at that!)
What would be a better / more Pythonic approach to this? Is a simple FSM like this even still the right choice in Python?
My solution:
#! /usr/bin/python
import sys
f = open(sys.argv[1], "rb")
state = 0
if f:
for byte in f.read():
a = ord(byte)
if state == 0:
if a == 0xAA:
state = 1
elif state == 1:
if a == 0xAA:
state = 2
else:
state = 0
elif state == 2:
count = a;
skip = 9
state = 3
elif state == 3:
skip = skip -1
if skip == 0:
state = 4
elif state == 4:
print "%02x" %a
count = count -1
if count == 0:
state = 0
print "\r\n"
| [
"The coolest way I've seen to implement FSMs in Python has to be via generators and coroutines. See this Charming Python post for an example. Eli Bendersky also has an excellent treatment of the subject.\nIf coroutines aren't familiar territory, David Beazley's A Curious Course on Coroutines and Concurrency is a stellar introduction.\n",
"You could give your states constant names instead of using 0, 1, 2, etc. for improved readability.\nYou could use a dictionary to map (current_state, input) -> (next_state), but that doesn't really let you do any additional processing during the transitions. Unless you include some \"transition function\" too to do extra processing.\nOr you could do a non-FSM approach. I think this will work as long as 0xAA 0xAA only appears when it indicates a \"start\" (doesn't appear in data).\nwith open(sys.argv[1], 'rb') as f:\n contents = f.read()\n for chunk in contents.split('\\xaa\\xaa')[1:]:\n length = ord(chunk[0])\n data = chunk[10:10+length]\n print data\n\nIf it does appear in data, you can instead use string.find('\\xaa\\xaa', start) to scan through the string, setting the start argument to begin looking where the last data block ended. Repeat until it returns -1.\n",
"I am a little apprehensive about telling anyone what's Pythonic, but here goes. First, keep in mind that in python functions are just objects. Transitions can be defined with a dictionary that has the (input, current_state) as the key and the tuple (next_state, action) as the value. Action is just a function that does whatever is necessary to transition from the current state to the next state. \nThere's a nice looking example of doing this at http://code.activestate.com/recipes/146262-finite-state-machine-fsm. I haven't used it, but from a quick read it seems like it covers everything.\nA similar question was asked/answered here a couple of months ago: Python state-machine design. You might find looking at those responses useful as well.\n",
"I think your solution looks fine, except you should replace count = count - 1 with count -= 1.\nThis is one of those times where fancy code-show-offs will come up ways of have dicts mapping states to callables, with a small driver function, but it isn't better, just fancier, and using more obscure language features.\n",
"I suggest checking out chapter 4 of Text Processing in Python by David Mertz. He implements a state machine class in Python that is very elegant.\n",
"I think the most pythonic way would by like what FogleBird suggested, but mapping from (current state, input) to a function which would handle the processing and transition.\n",
"You can use regexps. Something like this code will find the first block of data. Then it's just a case of starting the next search from after the previous match.\nfind_header = re.compile('\\xaa\\xaa(.).{9}', re.DOTALL)\nm = find_header.search(input_text)\nif m:\n length = chr(find_header.group(1))\n data = input_text[m.end():m.end() + length]\n\n"
] | [
8,
7,
3,
1,
1,
1,
1
] | [] | [] | [
"fsm",
"python"
] | stackoverflow_0002916181_fsm_python.txt |
Q:
Unit Testing Interfaces in Python
I am currently learning python in preperation for a class over the summer and have gotten started by implementing different types of heaps and priority based data structures.
I began to write a unit test suite for the project but ran into difficulties into creating a generic unit test that only tests the interface and is oblivious of the actual implementation.
I am wondering if it is possible to do something like this..
suite = HeapTestSuite(BinaryHeap())
suite.run()
suite = HeapTestSuite(BinomialHeap())
suite.run()
What I am currently doing just feels... wrong (multiple inheritance? ACK!)..
class TestHeap:
def reset_heap(self):
self.heap = None
def test_insert(self):
self.reset_heap()
#test that insert doesnt throw an exception...
for x in self.inseq:
self.heap.insert(x)
def test_delete(self):
#assert we get the first value we put in
self.reset_heap()
self.heap.insert(5)
self.assertEquals(5, self.heap.delete_min())
#harder test. put in sequence in and check that it comes out right
self.reset_heap()
for x in self.inseq:
self.heap.insert(x)
for x in xrange(len(self.inseq)):
val = self.heap.delete_min()
self.assertEquals(val, x)
class BinaryHeapTest(TestHeap, unittest.TestCase):
def setUp(self):
self.inseq = range(99, -1, -1)
self.heap = BinaryHeap()
def reset_heap(self):
self.heap = BinaryHeap()
class BinomialHeapTest(TestHeap, unittest.TestCase):
def setUp(self):
self.inseq = range(99, -1, -1)
self.heap = BinomialHeap()
def reset_heap(self):
self.heap = BinomialHeap()
if __name__ == '__main__':
unittest.main()
A:
I personally like nose test generation more for this sort of thing. I'd then write it like:
# They happen to all be simple callable factories, if they weren't you could put
# a function in here:
make_heaps = [BinaryHeap, BinomialHeap]
def test_heaps():
for make_heap in make_heaps:
for checker in checkers: # we'll set checkers later
yield checker, make_heap
def check_insert(make_heap):
heap = make_heap()
for x in range(99, -1, -1):
heap.insert(x)
# def check_delete_min etc.
checkers = [
value
for name, value in sorted(globals().items())
if name.startswith('check_')]
A:
Why not just use an alias for the class you want to test? You can write your test class referring to a fake HeapImpl class, and then assign a specific implementation to it before each test run:
class TestHeap(unittest.TestCase):
def setUp(self):
self.heap = HeapImpl()
#test cases go here
if __name__ == '__main__'
suite = unittest.TestLoader().loadTestsFromTestCase(TestHeap)
heaps = [BinaryHeap, BinomialHeap]
for heap in heaps:
HeapImpl = heap
unittest.TextTestRunner().run(suite)
As long as they comply with the interface you're using in the test suite, this should work fine. Also, you can easily test as many implementations as you want, just add them to the heaps list.
A:
I don't think the above pattern is terrible, but multiple inheritance is certainly not idea.
I guess the reason you can't just have TestHeap be a subclass of TestCase is because it will automatically be picked up and run as test, not knowing that it needs to be subclassed.
I've gotten around this problem two other ways:
Rather than adding test_ functions, have write methods that don't automatically get picked up, then add test() to each of your subclasses. Obviously not ideal.
Rewrote unittest to not suck, allowing the option of setting __test__ = False to the base class. (See Testify)
| Unit Testing Interfaces in Python | I am currently learning python in preperation for a class over the summer and have gotten started by implementing different types of heaps and priority based data structures.
I began to write a unit test suite for the project but ran into difficulties into creating a generic unit test that only tests the interface and is oblivious of the actual implementation.
I am wondering if it is possible to do something like this..
suite = HeapTestSuite(BinaryHeap())
suite.run()
suite = HeapTestSuite(BinomialHeap())
suite.run()
What I am currently doing just feels... wrong (multiple inheritance? ACK!)..
class TestHeap:
def reset_heap(self):
self.heap = None
def test_insert(self):
self.reset_heap()
#test that insert doesnt throw an exception...
for x in self.inseq:
self.heap.insert(x)
def test_delete(self):
#assert we get the first value we put in
self.reset_heap()
self.heap.insert(5)
self.assertEquals(5, self.heap.delete_min())
#harder test. put in sequence in and check that it comes out right
self.reset_heap()
for x in self.inseq:
self.heap.insert(x)
for x in xrange(len(self.inseq)):
val = self.heap.delete_min()
self.assertEquals(val, x)
class BinaryHeapTest(TestHeap, unittest.TestCase):
def setUp(self):
self.inseq = range(99, -1, -1)
self.heap = BinaryHeap()
def reset_heap(self):
self.heap = BinaryHeap()
class BinomialHeapTest(TestHeap, unittest.TestCase):
def setUp(self):
self.inseq = range(99, -1, -1)
self.heap = BinomialHeap()
def reset_heap(self):
self.heap = BinomialHeap()
if __name__ == '__main__':
unittest.main()
| [
"I personally like nose test generation more for this sort of thing. I'd then write it like:\n# They happen to all be simple callable factories, if they weren't you could put\n# a function in here:\nmake_heaps = [BinaryHeap, BinomialHeap]\n\ndef test_heaps():\n for make_heap in make_heaps:\n for checker in checkers: # we'll set checkers later\n yield checker, make_heap\n\ndef check_insert(make_heap):\n heap = make_heap()\n for x in range(99, -1, -1):\n heap.insert(x)\n\n# def check_delete_min etc.\n\ncheckers = [\n value\n for name, value in sorted(globals().items())\n if name.startswith('check_')]\n\n",
"Why not just use an alias for the class you want to test? You can write your test class referring to a fake HeapImpl class, and then assign a specific implementation to it before each test run:\nclass TestHeap(unittest.TestCase):\n def setUp(self):\n self.heap = HeapImpl()\n #test cases go here\n\nif __name__ == '__main__'\n suite = unittest.TestLoader().loadTestsFromTestCase(TestHeap)\n heaps = [BinaryHeap, BinomialHeap]\n for heap in heaps:\n HeapImpl = heap\n unittest.TextTestRunner().run(suite)\n\nAs long as they comply with the interface you're using in the test suite, this should work fine. Also, you can easily test as many implementations as you want, just add them to the heaps list. \n",
"I don't think the above pattern is terrible, but multiple inheritance is certainly not idea.\nI guess the reason you can't just have TestHeap be a subclass of TestCase is because it will automatically be picked up and run as test, not knowing that it needs to be subclassed.\nI've gotten around this problem two other ways:\n\nRather than adding test_ functions, have write methods that don't automatically get picked up, then add test() to each of your subclasses. Obviously not ideal.\nRewrote unittest to not suck, allowing the option of setting __test__ = False to the base class. (See Testify)\n\n"
] | [
4,
2,
1
] | [] | [] | [
"interface",
"python",
"test_suite",
"unit_testing"
] | stackoverflow_0002915286_interface_python_test_suite_unit_testing.txt |
Q:
Reinterpret a CGImageRef using PyObjC in Python
I'm doing something that's a little complicated to sum up in the title, so please bear with me.
I'm writing a Python module that provides an interface to my C++ library, which provides some specialized image manipulation functionality. It would be most convenient to be able to access image buffers as CGImageRefs from Python, so they could be manipulated further using Quartz (using PyObjC, which works well).
So I have a C++ function that provides a CGImageRef representation from my own image buffers, like this:
CGImageRef CreateCGImageRefForImageBuffer(shared_ptr<ImageBuffer> buffer);
I'm using Boost::Python to create my Python bridge. What is the easiest way for me to export this function so that I can use the CGImageRef from Python?
Problems: The CGImageRef type can't be exported directly because it is a pointer to an undefined struct. So I could make a wrapper function that wraps it in a PyCObject or something to get it to send the pointer to Python. But then how do I "cast" this object to a CGImageRef from Python? Is there a better way to go about this?
A:
I think a wrapper is your only option since it is an undefined struct and Boost::Python demands to know the interface. Here is a starting point:
http://www.boost.org/doc/libs/1_43_0/libs/python/doc/v2/faq.html#xref
I would add the necessary member functions you need into the wrapper. I am doing something somewhat similar, seems to be working decently so far :).
| Reinterpret a CGImageRef using PyObjC in Python | I'm doing something that's a little complicated to sum up in the title, so please bear with me.
I'm writing a Python module that provides an interface to my C++ library, which provides some specialized image manipulation functionality. It would be most convenient to be able to access image buffers as CGImageRefs from Python, so they could be manipulated further using Quartz (using PyObjC, which works well).
So I have a C++ function that provides a CGImageRef representation from my own image buffers, like this:
CGImageRef CreateCGImageRefForImageBuffer(shared_ptr<ImageBuffer> buffer);
I'm using Boost::Python to create my Python bridge. What is the easiest way for me to export this function so that I can use the CGImageRef from Python?
Problems: The CGImageRef type can't be exported directly because it is a pointer to an undefined struct. So I could make a wrapper function that wraps it in a PyCObject or something to get it to send the pointer to Python. But then how do I "cast" this object to a CGImageRef from Python? Is there a better way to go about this?
| [
"I think a wrapper is your only option since it is an undefined struct and Boost::Python demands to know the interface. Here is a starting point:\nhttp://www.boost.org/doc/libs/1_43_0/libs/python/doc/v2/faq.html#xref\nI would add the necessary member functions you need into the wrapper. I am doing something somewhat similar, seems to be working decently so far :).\n"
] | [
0
] | [] | [] | [
"boost_python",
"core_graphics",
"pyobjc",
"python"
] | stackoverflow_0002822887_boost_python_core_graphics_pyobjc_python.txt |
Q:
Why is sys.path showing non-existent items (which cause import problems)?
I'm seeing some additional items in sys.path which 1) don't exist and 2) cause problems with imports (specifically with Nose).
Basically, I've created a package (lets call it foo) which I use in multiple projects. The project I'm working on at the moment can import everything from foo without issue, but when I run Nose I get import errors:
E
======================================================================
ERROR: Failure: ImportError (No module named foo)
----------------------------------------------------------------------
Traceback (most recent call last):
...
File "/path/to/my-project/file.py", line 6, in <module>
from foo import *
ImportError: No module named foo
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (errors=1)
When I spit out the path I get:
["/path/to/my-project/foo",
"/path/to/my-project/foo",
...,
"/usr/virtualenvs/my-project/lib/python2.6/site-packages/foo-py2.6.egg",
...]
/path/to/my-project/foo doesn't exist. If I pop the first 2 entries off sys.path everything works fine.
Can someone explain to me why those items are showing up when, really, the only one that should be in the list is the one installed into the virtualenv?
And how do I stop this from happening in the future? Is it something to do with the setup.py in foo?
A:
Do you have anything in $PYTHONPATH? This will put entries in sys.path even within a virtualenv enviroment.
Try unset PYTHONPATH in bash (if you use bash) and then see what your sys.path contains.
A:
Look for .pth files anywhere on the path. These files (e.g., easy-install.pth) can contain additional sys.path entries (one per line).
| Why is sys.path showing non-existent items (which cause import problems)? | I'm seeing some additional items in sys.path which 1) don't exist and 2) cause problems with imports (specifically with Nose).
Basically, I've created a package (lets call it foo) which I use in multiple projects. The project I'm working on at the moment can import everything from foo without issue, but when I run Nose I get import errors:
E
======================================================================
ERROR: Failure: ImportError (No module named foo)
----------------------------------------------------------------------
Traceback (most recent call last):
...
File "/path/to/my-project/file.py", line 6, in <module>
from foo import *
ImportError: No module named foo
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (errors=1)
When I spit out the path I get:
["/path/to/my-project/foo",
"/path/to/my-project/foo",
...,
"/usr/virtualenvs/my-project/lib/python2.6/site-packages/foo-py2.6.egg",
...]
/path/to/my-project/foo doesn't exist. If I pop the first 2 entries off sys.path everything works fine.
Can someone explain to me why those items are showing up when, really, the only one that should be in the list is the one installed into the virtualenv?
And how do I stop this from happening in the future? Is it something to do with the setup.py in foo?
| [
"Do you have anything in $PYTHONPATH? This will put entries in sys.path even within a virtualenv enviroment.\nTry unset PYTHONPATH in bash (if you use bash) and then see what your sys.path contains.\n",
"Look for .pth files anywhere on the path. These files (e.g., easy-install.pth) can contain additional sys.path entries (one per line).\n"
] | [
0,
0
] | [] | [] | [
"egg",
"python"
] | stackoverflow_0002914516_egg_python.txt |
Q:
Python doctest error
Hi I recently started experimenting with python currently reading "Think like a computer scientist: Learning python v2nd edition" I have been having some trouble with doctest. I use a windows 7 machine and Eclipse IDE with pydev.
My question is when i run the script below i get the error below. Said script is below the the error message
Traceback (most recent call last):
File "C:\Users\shaytac\PythonProjects\test.py", line 21, in <module>
doctest.testmod()
File "C:\Python26\lib\doctest.py", line 1829, in testmod
for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
File "C:\Python26\lib\doctest.py", line 852, in find
self._find(tests, obj, name, module, source_lines, globs, {})
File "C:\Python26\lib\doctest.py", line 906, in _find
globs, seen)
File "C:\Python26\lib\doctest.py", line 894, in _find
test = self._get_test(obj, name, module, globs, source_lines)
File "C:\Python26\lib\doctest.py", line 978, in _get_test
filename, lineno)
File "C:\Python26\lib\doctest.py", line 597, in get_doctest
return DocTest(self.get_examples(string, name), globs,
File "C:\Python26\lib\doctest.py", line 611, in get_examples
return [x for x in self.parse(string, name)
File "C:\Python26\lib\doctest.py", line 573, in parse
self._parse_example(m, name, lineno)
File "C:\Python26\lib\doctest.py", line 631, in _parse_example
self._check_prompt_blank(source_lines, indent, name, lineno)
File "C:\Python26\lib\doctest.py", line 718, in _check_prompt_blank
line[indent:indent+3], line))
ValueError: line 2 of the docstring for __main__.compare lacks blank after >>>: '>>>compare(5, 4) '
def compare(a, b):
"""
>>>compare(5, 4)
1
>>>compare(7, 7)
0
>>>compare(2, 3)
-1
>>>compare(42, 1)
1
"""
if a > b :
return 1
if a == b :
return 0
if a < b :
return -1
if __name__ == '__main__':
import doctest
doctest.testmod()
A:
you shoud write:
>>> compare(5, 4)
as the error said: missing blank before compare
| Python doctest error | Hi I recently started experimenting with python currently reading "Think like a computer scientist: Learning python v2nd edition" I have been having some trouble with doctest. I use a windows 7 machine and Eclipse IDE with pydev.
My question is when i run the script below i get the error below. Said script is below the the error message
Traceback (most recent call last):
File "C:\Users\shaytac\PythonProjects\test.py", line 21, in <module>
doctest.testmod()
File "C:\Python26\lib\doctest.py", line 1829, in testmod
for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
File "C:\Python26\lib\doctest.py", line 852, in find
self._find(tests, obj, name, module, source_lines, globs, {})
File "C:\Python26\lib\doctest.py", line 906, in _find
globs, seen)
File "C:\Python26\lib\doctest.py", line 894, in _find
test = self._get_test(obj, name, module, globs, source_lines)
File "C:\Python26\lib\doctest.py", line 978, in _get_test
filename, lineno)
File "C:\Python26\lib\doctest.py", line 597, in get_doctest
return DocTest(self.get_examples(string, name), globs,
File "C:\Python26\lib\doctest.py", line 611, in get_examples
return [x for x in self.parse(string, name)
File "C:\Python26\lib\doctest.py", line 573, in parse
self._parse_example(m, name, lineno)
File "C:\Python26\lib\doctest.py", line 631, in _parse_example
self._check_prompt_blank(source_lines, indent, name, lineno)
File "C:\Python26\lib\doctest.py", line 718, in _check_prompt_blank
line[indent:indent+3], line))
ValueError: line 2 of the docstring for __main__.compare lacks blank after >>>: '>>>compare(5, 4) '
def compare(a, b):
"""
>>>compare(5, 4)
1
>>>compare(7, 7)
0
>>>compare(2, 3)
-1
>>>compare(42, 1)
1
"""
if a > b :
return 1
if a == b :
return 0
if a < b :
return -1
if __name__ == '__main__':
import doctest
doctest.testmod()
| [
"you shoud write:\n>>> compare(5, 4)\n\nas the error said: missing blank before compare\n"
] | [
6
] | [] | [] | [
"doctest",
"python"
] | stackoverflow_0002916351_doctest_python.txt |
Q:
How do I sort a list of python Django objects?
In Django, I have a model object in a list.
[object, object, object]
Each object has ".name" which is the title of the thing.
How do I sort alphabetically by this title?
This doesn't work:
catlist.sort(key=lambda x.name: x.name.lower())
A:
catlist.sort(key=lambda x: x.name.lower())
A:
Without the call to lower(), the following could be considered slightly cleaner than using a lambda:
import operator
catlist.sort(key=operator.attrgetter('name'))
Add that call to lower(), and you enter into a world of function-composition pain. Using Ants Aasma's compose() found in an answer to this other SO question, you too can see the light that is functional programming (I'm kidding. All programming paradigms surely have their time and place.):
>>> def compose(inner_func, *outer_funcs):
... if not outer_funcs:
... return inner_func
... outer_func = compose(*outer_funcs)
... return lambda *args, **kwargs: outer_func(inner_func(*args, **kwargs))
...
>>> class A(object):
... def __init__(self, name):
... self.name = name
...
>>> L = [A(i) for i in ['aa','a','AA','A']]
>>> name_lowered = compose(operator.attrgetter('name'),
operator.methodcaller('lower'))
>>> print [i.name for i in sorted(L, key=name_lowered)]
['a', 'A', 'aa', 'AA']
| How do I sort a list of python Django objects? | In Django, I have a model object in a list.
[object, object, object]
Each object has ".name" which is the title of the thing.
How do I sort alphabetically by this title?
This doesn't work:
catlist.sort(key=lambda x.name: x.name.lower())
| [
"catlist.sort(key=lambda x: x.name.lower())\n\n",
"Without the call to lower(), the following could be considered slightly cleaner than using a lambda:\nimport operator\ncatlist.sort(key=operator.attrgetter('name'))\n\nAdd that call to lower(), and you enter into a world of function-composition pain. Using Ants Aasma's compose() found in an answer to this other SO question, you too can see the light that is functional programming (I'm kidding. All programming paradigms surely have their time and place.):\n>>> def compose(inner_func, *outer_funcs):\n... if not outer_funcs:\n... return inner_func\n... outer_func = compose(*outer_funcs)\n... return lambda *args, **kwargs: outer_func(inner_func(*args, **kwargs))\n...\n>>> class A(object):\n... def __init__(self, name):\n... self.name = name\n...\n>>> L = [A(i) for i in ['aa','a','AA','A']]\n>>> name_lowered = compose(operator.attrgetter('name'), \n operator.methodcaller('lower'))\n>>> print [i.name for i in sorted(L, key=name_lowered)]\n['a', 'A', 'aa', 'AA']\n\n"
] | [
12,
2
] | [] | [] | [
"django",
"list",
"python",
"sorting"
] | stackoverflow_0002916558_django_list_python_sorting.txt |
Q:
Distributing a Python library (single file)
For my project I would be using the argparse library. My question is, how do I distribute it with my project. I am asking this because of the technicalities and legalities involved.
Do I just:
Put the argparse.py file along with
my project. That is, in the tar file for my project.
Create a package for it for my
distro?
Tell the user to install it himself?
A:
It would be best for the user to install it so that only one copy is present on the system and so that it can be updated if there are any issues, but including it with your project is a viable option if you abide by all requirements specified in the license.
Try to import it from the public location, and if that fails then resort to using the included module.
A:
What's your target Python version? It appears that argparse is included from version 2.7.
If you're building a small library with minimal dependencies, I would consider removing the dependency on an external module and only use facilities offered by the standard Python library. You can access command line parameters with sys.argv and parse them yourself, it's usually not that hard to do. Your users will definitely appreciate not having to install yet another third party module just to use your code.
A:
You could go with Ignacio's suggestion.
But... For what it is worth, there's another library for argument parsing built into Python, which is quite powerful. Have you tried optparse? It belongs to the base Python distribution and has been there for a while...
Good luck!
| Distributing a Python library (single file) | For my project I would be using the argparse library. My question is, how do I distribute it with my project. I am asking this because of the technicalities and legalities involved.
Do I just:
Put the argparse.py file along with
my project. That is, in the tar file for my project.
Create a package for it for my
distro?
Tell the user to install it himself?
| [
"It would be best for the user to install it so that only one copy is present on the system and so that it can be updated if there are any issues, but including it with your project is a viable option if you abide by all requirements specified in the license.\nTry to import it from the public location, and if that fails then resort to using the included module.\n",
"What's your target Python version? It appears that argparse is included from version 2.7.\nIf you're building a small library with minimal dependencies, I would consider removing the dependency on an external module and only use facilities offered by the standard Python library. You can access command line parameters with sys.argv and parse them yourself, it's usually not that hard to do. Your users will definitely appreciate not having to install yet another third party module just to use your code.\n",
"You could go with Ignacio's suggestion.\nBut... For what it is worth, there's another library for argument parsing built into Python, which is quite powerful. Have you tried optparse? It belongs to the base Python distribution and has been there for a while...\nGood luck!\n"
] | [
1,
1,
1
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0002916116_argparse_python.txt |
Q:
How to import * with __import__
What's the best approach to execute the following using __import__ so that I may dynamically specify the module?
from module import *
A:
The only way I found:
module = __import__(module, globals(), locals(), ['*'])
for k in dir(module):
locals()[k] = getattr(module, k)
A:
It's the same as a normal from-import call, you just pass it a list containing '*' for the fromlist:
moduleName = "foo"
__import__(moduleName, globals(), locals(), ['*'])
A:
__import__() never adds anything to the local scope. You will have to go through the returned module, accessing its attributes as desired.
| How to import * with __import__ | What's the best approach to execute the following using __import__ so that I may dynamically specify the module?
from module import *
| [
"The only way I found:\nmodule = __import__(module, globals(), locals(), ['*'])\nfor k in dir(module):\n locals()[k] = getattr(module, k)\n\n",
"It's the same as a normal from-import call, you just pass it a list containing '*' for the fromlist:\nmoduleName = \"foo\"\n__import__(moduleName, globals(), locals(), ['*'])\n\n",
"__import__() never adds anything to the local scope. You will have to go through the returned module, accessing its attributes as desired.\n"
] | [
17,
5,
4
] | [] | [] | [
"import",
"python"
] | stackoverflow_0002916374_import_python.txt |
Q:
Hide script extension
I have a html form that posts to a python script test.py. If someone tries to access the script directly, it redirects them to the form.
I not using a web framework, just straight python cgi programming. My website is hosted on a shared hosting provider that allows me access to a .htaccess file.
I wanted to know if there was a way to have the form post to the script and in the address bar show mydomain.com/test/ and not mydomain.com/test.py ?
Thanks.
A:
Try this:
RewriteEngine On
RewriteRule ^/test/$ /test.py
A:
Absolutely. Use mod_rewrite to rewrite the URL as desired.
| Hide script extension | I have a html form that posts to a python script test.py. If someone tries to access the script directly, it redirects them to the form.
I not using a web framework, just straight python cgi programming. My website is hosted on a shared hosting provider that allows me access to a .htaccess file.
I wanted to know if there was a way to have the form post to the script and in the address bar show mydomain.com/test/ and not mydomain.com/test.py ?
Thanks.
| [
"Try this:\nRewriteEngine On\nRewriteRule ^/test/$ /test.py \n\n",
"Absolutely. Use mod_rewrite to rewrite the URL as desired.\n"
] | [
3,
1
] | [] | [] | [
"cgi",
"python",
"web_applications"
] | stackoverflow_0002917357_cgi_python_web_applications.txt |
Q:
Help a Python newbie with a Django model inheritance problem
I'm working on my first real Django project after years of PHP programming, and I am running into a problem with my models. First, I noticed that I was copying and pasting code between the models, and being a diligent OO programmer I decided to make a parent class that the other models could inherit from:
class Common(model.Model):
name = models.CharField(max_length=255)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class Meta:
abstract=True
So far so good. Now all my other models extend "Common" and have names and dates like I want. However, I have a class for "Categories" were the name has to be unique. I assume there should be a relatively simple way for me to access the name attribute from Common and make it unique. However, the different methods I have tried to use have all failed. For example:
class Category(Common):
def __init__(self, *args, **kwargs):
self.name.unique=True
Causes the Django admin page to spit up the error "Caught an exception while rendering: 'Category' object has no attribute 'name'
Can someone point me in the right direction?
A:
No, Django doesn't allow that.
See the docs: http://docs.djangoproject.com/en/1.1/topics/db/models/#field-name-hiding-is-not-permitted
Also answered in other questions like: In Django - Model Inheritance - Does it allow you to override a parent model's attribute?
A:
You have a small mistake in your Common class
class Common(model.Model):
self.name = models.CharField(max_length=255)
should be
class Common(model.Model):
name = models.CharField(max_length=255)
A:
Note that UNIQUE constraint in fact has nothing to do with Django, so you're free to add it in your database table. You can also use post-syncdb hook for that purpose.
A:
Try using Meta.unique_together to force it into its own unique index. Failing that, it's probably easiest to create two separate abstract classes, one with the field unique and one not.
| Help a Python newbie with a Django model inheritance problem | I'm working on my first real Django project after years of PHP programming, and I am running into a problem with my models. First, I noticed that I was copying and pasting code between the models, and being a diligent OO programmer I decided to make a parent class that the other models could inherit from:
class Common(model.Model):
name = models.CharField(max_length=255)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class Meta:
abstract=True
So far so good. Now all my other models extend "Common" and have names and dates like I want. However, I have a class for "Categories" were the name has to be unique. I assume there should be a relatively simple way for me to access the name attribute from Common and make it unique. However, the different methods I have tried to use have all failed. For example:
class Category(Common):
def __init__(self, *args, **kwargs):
self.name.unique=True
Causes the Django admin page to spit up the error "Caught an exception while rendering: 'Category' object has no attribute 'name'
Can someone point me in the right direction?
| [
"No, Django doesn't allow that. \nSee the docs: http://docs.djangoproject.com/en/1.1/topics/db/models/#field-name-hiding-is-not-permitted\nAlso answered in other questions like: In Django - Model Inheritance - Does it allow you to override a parent model's attribute?\n",
"You have a small mistake in your Common class\nclass Common(model.Model):\n self.name = models.CharField(max_length=255) \n\nshould be\nclass Common(model.Model):\n name = models.CharField(max_length=255)\n\n",
"Note that UNIQUE constraint in fact has nothing to do with Django, so you're free to add it in your database table. You can also use post-syncdb hook for that purpose.\n",
"Try using Meta.unique_together to force it into its own unique index. Failing that, it's probably easiest to create two separate abstract classes, one with the field unique and one not.\n"
] | [
2,
1,
1,
0
] | [] | [] | [
"django",
"django_inheritance",
"django_models",
"python"
] | stackoverflow_0002914380_django_django_inheritance_django_models_python.txt |
Q:
Recognition source of event in PyQT
I`m starting with PyQt4 and right now I have a problem with events.
I have one main class let say MainWindow. MainWindow has a list of buttons of type ButtonX (inherence form QPushButton). I would like to achieve one of 2 solutions (depends which is easier).
1) After click one of the button from the list I would like to run a one method of MainWindow. I would like to be able to read a source of event there (recognize clicked button)
2) Second solution is to run a method defined in ButtonX class.
What I tried is:
QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0).buttonMethod())
QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0), QtCore.SLOT("incrementValue()"))
and even this line occure suspend Python interpreter
QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0), QtCore.SLOT("incrementValue"))
A:
1) After click one of the button from the list I would like to run a one method of MainWindow. I would like to be able to read a source of event there (recognize clicked button)
You can access the source of an event using QObject.sender(). But, as the instructions indicate, it's often better to use QSignalMapper or do things in a more object oriented fashion.
2) Second solution is to run a method defined in ButtonX class.
Look carefully at what you typed for the last argument of the first connect call:
self.getButton(0, 0).buttonMethod()
The above will evaluate getButton with parameters 0, 0 and then, on that object, call the buttonMethod method. So, unless buttonMethod returns a method, you are using the return value of buttonMethod as the last parameter to the connect call. If this method returns a function, then this is just fine.
Rather, I would expect to see something like the following:
self.getButton(0, 0).buttonMethod # note no parenthesis at end
Take a look at the PyQt examples directory provided with PyQt as they'll demonstrate the exact syntax and serve as good examples.
Here's one small example:
class MW(QMainWindow):
def __init__(self, *args)
QMainWindow.__init__(self, *args)
layout = QHBoxLayout(self)
self.b1 = QPushButton("Button1")
self.b2 = QPushButton("Button2")
layout.addWidget(self.b1)
layout.addWidget(self.b2)
self.connect(self.b1, SIGNAL("clicked()"), self.buttonWasPressed)
self.connect(self.b2, SIGNAL("clicked()"), self.buttonWasPressed)
def buttonWasPressed(self):
print "button %s was pressed" % self.sender()
| Recognition source of event in PyQT | I`m starting with PyQt4 and right now I have a problem with events.
I have one main class let say MainWindow. MainWindow has a list of buttons of type ButtonX (inherence form QPushButton). I would like to achieve one of 2 solutions (depends which is easier).
1) After click one of the button from the list I would like to run a one method of MainWindow. I would like to be able to read a source of event there (recognize clicked button)
2) Second solution is to run a method defined in ButtonX class.
What I tried is:
QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0).buttonMethod())
QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0), QtCore.SLOT("incrementValue()"))
and even this line occure suspend Python interpreter
QtCore.QObject.connect(self.getButton(0, 0), QtCore.SIGNAL("clicked()"), self.getButton(0, 0), QtCore.SLOT("incrementValue"))
| [
"\n1) After click one of the button from the list I would like to run a one method of MainWindow. I would like to be able to read a source of event there (recognize clicked button)\n\nYou can access the source of an event using QObject.sender(). But, as the instructions indicate, it's often better to use QSignalMapper or do things in a more object oriented fashion.\n\n2) Second solution is to run a method defined in ButtonX class.\n\nLook carefully at what you typed for the last argument of the first connect call:\nself.getButton(0, 0).buttonMethod()\n\nThe above will evaluate getButton with parameters 0, 0 and then, on that object, call the buttonMethod method. So, unless buttonMethod returns a method, you are using the return value of buttonMethod as the last parameter to the connect call. If this method returns a function, then this is just fine. \nRather, I would expect to see something like the following:\nself.getButton(0, 0).buttonMethod # note no parenthesis at end\n\nTake a look at the PyQt examples directory provided with PyQt as they'll demonstrate the exact syntax and serve as good examples.\nHere's one small example:\nclass MW(QMainWindow):\n def __init__(self, *args)\n QMainWindow.__init__(self, *args)\n layout = QHBoxLayout(self)\n self.b1 = QPushButton(\"Button1\")\n self.b2 = QPushButton(\"Button2\")\n layout.addWidget(self.b1)\n layout.addWidget(self.b2)\n self.connect(self.b1, SIGNAL(\"clicked()\"), self.buttonWasPressed)\n self.connect(self.b2, SIGNAL(\"clicked()\"), self.buttonWasPressed)\n\n def buttonWasPressed(self):\n print \"button %s was pressed\" % self.sender()\n\n"
] | [
4
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"user_interface"
] | stackoverflow_0002917292_pyqt_pyqt4_python_qt_user_interface.txt |
Q:
django multiprocess problem
I have django application, running under lighttpd via fastcgi. FCGI running script looks like:
python manage.py runfcgi socket=<path>/main.socket
method=prefork \
pidfile=<path>/server.pid \
minspare=5 maxspare=10 maxchildren=10 maxrequests=500 \
I use SQLite. So I have 10 proccess, which all work with the same DB. Next I have 2 views:
def view1(request)
...
obj = MyModel.objects.get_or_create(id=1)
obj.param1 = <some value>
obj.save ()
def view2(request)
...
obj = MyModel.objects.get_or_create(id=1)
obj.param2 = <some value>
obj.save ()
And If this views are executed in two different threads sometimes I get MyModel instance in DB with id=1 and updated either param1 or param2 (BUT not both) - it depends on which process was the first. (of course in real life id changes, but sometimes 2 processes execute these two views with same id)
The question is: What should I do to get instance with updated param1 and param2? I need something for merging changes in different processes.
One decision is create interprocess lock object but in this case I will get sequence executing views and they will not be able to be executed simultaneously, so I ask help
DUPE OF Django: How can I protect against concurrent modification of data base entries
A:
SQLite is not good choice if you need such concurrent access to database.
I suggest switching to some other rdbms, like MySQL or PostgreSQL,
and also take into account get_or_create fragility:
How do I deal with this race condition in django?
Regarding the above link, there is also second solution to that problem - using READ COMMITED isolation level, instead of REPEATABLE READ. But it's less tested (At least in MySQL), so there might be more bugs/problems with it.
| django multiprocess problem | I have django application, running under lighttpd via fastcgi. FCGI running script looks like:
python manage.py runfcgi socket=<path>/main.socket
method=prefork \
pidfile=<path>/server.pid \
minspare=5 maxspare=10 maxchildren=10 maxrequests=500 \
I use SQLite. So I have 10 proccess, which all work with the same DB. Next I have 2 views:
def view1(request)
...
obj = MyModel.objects.get_or_create(id=1)
obj.param1 = <some value>
obj.save ()
def view2(request)
...
obj = MyModel.objects.get_or_create(id=1)
obj.param2 = <some value>
obj.save ()
And If this views are executed in two different threads sometimes I get MyModel instance in DB with id=1 and updated either param1 or param2 (BUT not both) - it depends on which process was the first. (of course in real life id changes, but sometimes 2 processes execute these two views with same id)
The question is: What should I do to get instance with updated param1 and param2? I need something for merging changes in different processes.
One decision is create interprocess lock object but in this case I will get sequence executing views and they will not be able to be executed simultaneously, so I ask help
DUPE OF Django: How can I protect against concurrent modification of data base entries
| [
"SQLite is not good choice if you need such concurrent access to database.\nI suggest switching to some other rdbms, like MySQL or PostgreSQL,\nand also take into account get_or_create fragility:\nHow do I deal with this race condition in django?\nRegarding the above link, there is also second solution to that problem - using READ COMMITED isolation level, instead of REPEATABLE READ. But it's less tested (At least in MySQL), so there might be more bugs/problems with it.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"sqlite",
"transactions"
] | stackoverflow_0002915609_django_python_sqlite_transactions.txt |
Q:
memcache won't store key/value because the value is too big
cache.set(key, Biglist, 3600)
print cache.get(key)
When my "Biglist" is a huge list of lots of content, it doesn't seem to store.
But when I change it to small text like "abc", it stores.
What do I have to configure so that I can set my memcache to accept unlimited size of key/value?
A:
See What is the maximum data size you can store section in the FAQ.
What is the maximum data size you can store? (1 megabyte)
The maximum size of a value you can store in memcached is 1 megabyte. If your data is larger, consider clientside compression or splitting the value up into multiple keys.
Why are items limited to 1 megabyte in size?
Ahh, this is a popular question!
Short answer: Because of how the memory allocator's algorithm works.
| memcache won't store key/value because the value is too big | cache.set(key, Biglist, 3600)
print cache.get(key)
When my "Biglist" is a huge list of lots of content, it doesn't seem to store.
But when I change it to small text like "abc", it stores.
What do I have to configure so that I can set my memcache to accept unlimited size of key/value?
| [
"See What is the maximum data size you can store section in the FAQ.\n\nWhat is the maximum data size you can store? (1 megabyte)\nThe maximum size of a value you can store in memcached is 1 megabyte. If your data is larger, consider clientside compression or splitting the value up into multiple keys.\nWhy are items limited to 1 megabyte in size?\nAhh, this is a popular question!\nShort answer: Because of how the memory allocator's algorithm works.\n\n"
] | [
5
] | [] | [] | [
"django",
"key_value",
"memcached",
"python"
] | stackoverflow_0002917484_django_key_value_memcached_python.txt |
Q:
Describe this feature of a programming language
Is there a way to describe the feature of a programming language that allows you to do something like the following:
$foo = return_an_array()[0];
I love this feature in python, and I hate that it's missing in PHP. Is there a name for this?
A:
Array indexing on arbitrary expressions
| Describe this feature of a programming language | Is there a way to describe the feature of a programming language that allows you to do something like the following:
$foo = return_an_array()[0];
I love this feature in python, and I hate that it's missing in PHP. Is there a name for this?
| [
"Array indexing on arbitrary expressions\n"
] | [
4
] | [] | [] | [
"arrays",
"python",
"return_value"
] | stackoverflow_0002917761_arrays_python_return_value.txt |
Q:
Self-contained python installation with executable tools included (pip, orbited, etc)
I'm trying deploy a Python application on Windows as a folder that includes a full python 2.6 folder. I don't need/want a fancy solution like py2exe, I'm just trying to automate deployment of a web application.
So long as I include python26.dll and set the PYTHONHOME correctly, things seem to work if I just include the Python26 folder in its entirety. However a number of the Python26/Script files don't work. For instance, pip.exe, orbited.exe, and morbid.exe all do nothing (complete with no output) when I try to run them on a system that doesn't have a real Python26 installation.
I've run out of ideas. Suggestions?
A:
How about trying to use virtualenv?
| Self-contained python installation with executable tools included (pip, orbited, etc) | I'm trying deploy a Python application on Windows as a folder that includes a full python 2.6 folder. I don't need/want a fancy solution like py2exe, I'm just trying to automate deployment of a web application.
So long as I include python26.dll and set the PYTHONHOME correctly, things seem to work if I just include the Python26 folder in its entirety. However a number of the Python26/Script files don't work. For instance, pip.exe, orbited.exe, and morbid.exe all do nothing (complete with no output) when I try to run them on a system that doesn't have a real Python26 installation.
I've run out of ideas. Suggestions?
| [
"How about trying to use virtualenv?\n"
] | [
1
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0002916616_python_windows.txt |
Q:
I have a very long and repetitive python path, where do I look to correct this?
I know it is probably not necessary to paste the whole path, but just for the record I have done so below. Whenever I run a python command, it takes a long time to load this path I suppose. I have checked in .bash_profile and only have these two lines:
export PATH=/Users/username/bin:/opt/local/Library/Frameworks/Python.framework/Versions/2.5/bin:/opt/local/bin:/opt/local/sbin:/opt/local/apache2/bin:$PATH
export PYTHONPATH=/opt/local/lib/python2.5/site-packages/
And my python path as outputed by Django's debug is:
Python path : ['/Users/username/Sites/videocluster/eggs/ipython-0.10-py2.5.egg', '/Users/username/Sites/videocluster/eggs/South-0.6.1-py2.5.egg', '/Users/username/Sites/videocluster/eggs/django_markitup-0.5.2-py2.5.egg', '/Users/username/Sites/videocluster/eggs/DateTime-2.12.0-py2.5.egg', '/Users/username/Sites/videocluster/eggs/Markdown-2.0.3-py2.5.egg', '/Users/username/Sites/videocluster/eggs/PIL-1.1.7-py2.5-macosx-10.5-i386.egg', '/Users/username/Sites/videocluster/eggs/djangorecipe-0.20-py2.5.egg', '/Users/username/Sites/videocluster/eggs/zc.recipe.egg-1.2.3b2-py2.5.egg', '/Users/username/Sites/videocluster/eggs/zc.buildout-1.5.0b2-py2.5.egg', '/Users/username/Sites/videocluster/eggs/pytz-2010h-py2.5.egg', '/Users/username/Sites/videocluster/eggs/zope.interface-3.6.1-py2.5-macosx-10.5-i386.egg', '/Users/username/Sites/videocluster/eggs/setuptools-0.6c11-py2.5.egg', '/Users/username/Sites/videocluster/parts/django', '/Users/username/Sites/videocluster', '/Users/username/Sites/videocluster/bin', '/opt/local/lib/python2.5/site-packages/setuptools_git-0.3.3-py2.5.egg', '/opt/local/lib/python2.5/site-packages/pysqlite-2.5.5-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/CouchDB-0.5-py2.5.egg', '/opt/local/lib/python2.5/site-packages/httplib2-0.4.0-py2.5.egg', '/opt/local/lib/python2.5/site-packages/PyYAML-3.08-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/simple_db_migrate-1.2.8-py2.5.egg', '/opt/local/lib/python2.5/site-packages/PyDispatcher-2.0.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/pyOpenSSL-0.9-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/greenlet-0.2-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/Supay-0.0.2-py2.5.egg', '/opt/local/lib/python2.5/site-packages/configobj-4.6.0-py2.5.egg', '/opt/local/lib/python2.5/site-packages/Fabric-0.9b1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/fudge-0.9.3-py2.5.egg', '/opt/local/lib/python2.5/site-packages/pydelicious-0.5.3-py2.5.egg', '/opt/local/lib/python2.5/site-packages/feedparser-4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/github_cli-0.2.5.2-py2.5.egg', '/opt/local/lib/python2.5/site-packages/simplejson-2.0.9-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', ......(repeating)....... '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/harobed.paster_template.advanced_package-0.2-py2.5.egg', '/opt/local/lib/python2.5/site-packages/squash-0.5.0dev-py2.5.egg', '/opt/local/lib/python2.5/site-packages/eventlet-0.8.13-py2.5.egg', '/opt/local/lib/python2.5/site-packages/FeinCMS-1.0.2-py2.5.egg', '/opt/local/lib/python2.5/site-packages/pyenchant-1.5.3-py2.5.egg', '/opt/local/lib/python2.5/site-packages/guppy-0.1.9-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/django_scraper-0.1dev-py2.5.egg', '/opt/local/lib/python2.5/site-packages/Pympler-0.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/fabric.contrib.packagemanager-0.1dev-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/selenium-1.0.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/Scrapy-0.9_dev-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', ......(repeating)....... '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/Numeric', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PIL', '/opt/local/lib/python2.5/site-packages/PIL', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', ......(repeating)....... '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/gtk-2.0']
Someone, please tell me where I can go to correct this.
A:
There are probably some files with extension .pth presumably in site-packages that add things to sys.path. This would explain (and let you fix) everything except the repetitions, which your site.py should actually eliminate (did you perhaps change site.py? Nobody ever does or should, but ...
If site.py is unbroken, the only explanation is that some other code running after site.py is doing a sys.path.append in a too-enthusiastic loop. "grepping" might help find the culprit. Until you do, a simple bandaid on the wound is to run a simple "uniquifier" as soon as you can to remove the duplicates:
done = set()
newp = []
for p in sys.path:
if p in done: continue
newp.append(p)
done.add(p)
sys.path = newp
| I have a very long and repetitive python path, where do I look to correct this? | I know it is probably not necessary to paste the whole path, but just for the record I have done so below. Whenever I run a python command, it takes a long time to load this path I suppose. I have checked in .bash_profile and only have these two lines:
export PATH=/Users/username/bin:/opt/local/Library/Frameworks/Python.framework/Versions/2.5/bin:/opt/local/bin:/opt/local/sbin:/opt/local/apache2/bin:$PATH
export PYTHONPATH=/opt/local/lib/python2.5/site-packages/
And my python path as outputed by Django's debug is:
Python path : ['/Users/username/Sites/videocluster/eggs/ipython-0.10-py2.5.egg', '/Users/username/Sites/videocluster/eggs/South-0.6.1-py2.5.egg', '/Users/username/Sites/videocluster/eggs/django_markitup-0.5.2-py2.5.egg', '/Users/username/Sites/videocluster/eggs/DateTime-2.12.0-py2.5.egg', '/Users/username/Sites/videocluster/eggs/Markdown-2.0.3-py2.5.egg', '/Users/username/Sites/videocluster/eggs/PIL-1.1.7-py2.5-macosx-10.5-i386.egg', '/Users/username/Sites/videocluster/eggs/djangorecipe-0.20-py2.5.egg', '/Users/username/Sites/videocluster/eggs/zc.recipe.egg-1.2.3b2-py2.5.egg', '/Users/username/Sites/videocluster/eggs/zc.buildout-1.5.0b2-py2.5.egg', '/Users/username/Sites/videocluster/eggs/pytz-2010h-py2.5.egg', '/Users/username/Sites/videocluster/eggs/zope.interface-3.6.1-py2.5-macosx-10.5-i386.egg', '/Users/username/Sites/videocluster/eggs/setuptools-0.6c11-py2.5.egg', '/Users/username/Sites/videocluster/parts/django', '/Users/username/Sites/videocluster', '/Users/username/Sites/videocluster/bin', '/opt/local/lib/python2.5/site-packages/setuptools_git-0.3.3-py2.5.egg', '/opt/local/lib/python2.5/site-packages/pysqlite-2.5.5-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/CouchDB-0.5-py2.5.egg', '/opt/local/lib/python2.5/site-packages/httplib2-0.4.0-py2.5.egg', '/opt/local/lib/python2.5/site-packages/PyYAML-3.08-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/simple_db_migrate-1.2.8-py2.5.egg', '/opt/local/lib/python2.5/site-packages/PyDispatcher-2.0.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/pyOpenSSL-0.9-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/greenlet-0.2-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/Supay-0.0.2-py2.5.egg', '/opt/local/lib/python2.5/site-packages/configobj-4.6.0-py2.5.egg', '/opt/local/lib/python2.5/site-packages/Fabric-0.9b1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/fudge-0.9.3-py2.5.egg', '/opt/local/lib/python2.5/site-packages/pydelicious-0.5.3-py2.5.egg', '/opt/local/lib/python2.5/site-packages/feedparser-4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/github_cli-0.2.5.2-py2.5.egg', '/opt/local/lib/python2.5/site-packages/simplejson-2.0.9-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', ......(repeating)....... '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/harobed.paster_template.advanced_package-0.2-py2.5.egg', '/opt/local/lib/python2.5/site-packages/squash-0.5.0dev-py2.5.egg', '/opt/local/lib/python2.5/site-packages/eventlet-0.8.13-py2.5.egg', '/opt/local/lib/python2.5/site-packages/FeinCMS-1.0.2-py2.5.egg', '/opt/local/lib/python2.5/site-packages/pyenchant-1.5.3-py2.5.egg', '/opt/local/lib/python2.5/site-packages/guppy-0.1.9-py2.5-macosx-10.5-i386.egg', '/opt/local/lib/python2.5/site-packages/django_scraper-0.1dev-py2.5.egg', '/opt/local/lib/python2.5/site-packages/Pympler-0.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/fabric.contrib.packagemanager-0.1dev-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/selenium-1.0.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/Scrapy-0.9_dev-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', ......(repeating)....... '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/zc.buildout-1.4.1-py2.5.egg', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '/opt/local/lib/python2.5/site-packages', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/Numeric', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PIL', '/opt/local/lib/python2.5/site-packages/PIL', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', ......(repeating)....... '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/lib/python2.5/site-packages/gtk-2.0', '/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/gtk-2.0']
Someone, please tell me where I can go to correct this.
| [
"There are probably some files with extension .pth presumably in site-packages that add things to sys.path. This would explain (and let you fix) everything except the repetitions, which your site.py should actually eliminate (did you perhaps change site.py? Nobody ever does or should, but ...\nIf site.py is unbroken, the only explanation is that some other code running after site.py is doing a sys.path.append in a too-enthusiastic loop. \"grepping\" might help find the culprit. Until you do, a simple bandaid on the wound is to run a simple \"uniquifier\" as soon as you can to remove the duplicates:\n done = set()\n newp = []\n for p in sys.path:\n if p in done: continue\n newp.append(p)\n done.add(p)\n sys.path = newp\n\n"
] | [
1
] | [] | [] | [
"development_environment",
"path",
"python",
"pythonpath",
"shell"
] | stackoverflow_0002917790_development_environment_path_python_pythonpath_shell.txt |
Q:
What is the hard recursion limit for Linux, Mac and Windows?
Python's sys module provides a function setrecursionlimit that lets you change Python's maximum recursion limit. The docs say:
The highest possible limit is platform-dependent.
My question is: What is the highest possible limits for various platforms, under CPython? I would like to know the values for Linux, Mac and Windows.
UPDATE: Can we please avoid "You're doing it wrong" answers? I know that trying to do very deep recursion is usually a bad idea. I've considered the pros and cons in my specific situation and decided that I want to do it.
A:
On Windows (at least), sys.setrecursionlimit isn't the full story. The hard limit is on a per-thread basis and you need to call threading.stack_size and create a new thread once you reach a certain limit. (I think 1MB, but not sure) I've used this approach to increase it to a 64MB stack.
import sys
import threading
threading.stack_size(67108864) # 64MB stack
sys.setrecursionlimit(2 ** 20) # something real big
# you actually hit the 64MB limit first
# going by other answers, could just use 2**32-1
# only new threads get the redefined stack size
thread = threading.Thread(target=main)
thread.start()
I haven't tried to see what limits there might be on threading.stack_size, but feel free to try... that's where you need to look.
In summary, sys.setrecursionlimit is just a limit enforced by the interpreter itself. threading.stack_size lets you manipulate the actual limit imposed by the OS. If you hit the latter limit first, Python will just crash completely.
A:
You shouldn't overuse recursive calls in CPython. It has not tail optimization, the function calls use a lot of memory and processing time. Those limits might not apply to other implementations, it's not in the blueprints.
In CPython, recursion is fine for traversing data structures (where a limit of 1000 should be enough for everybody) but not for algorithms. If I were to implement, say, graph related algorithms and hit the recursion limit, I would either implement my own stack and use iterations, or look for libraries implemented in C/C++/whatever before raising the limit by hand.
| What is the hard recursion limit for Linux, Mac and Windows? | Python's sys module provides a function setrecursionlimit that lets you change Python's maximum recursion limit. The docs say:
The highest possible limit is platform-dependent.
My question is: What is the highest possible limits for various platforms, under CPython? I would like to know the values for Linux, Mac and Windows.
UPDATE: Can we please avoid "You're doing it wrong" answers? I know that trying to do very deep recursion is usually a bad idea. I've considered the pros and cons in my specific situation and decided that I want to do it.
| [
"On Windows (at least), sys.setrecursionlimit isn't the full story. The hard limit is on a per-thread basis and you need to call threading.stack_size and create a new thread once you reach a certain limit. (I think 1MB, but not sure) I've used this approach to increase it to a 64MB stack.\nimport sys\nimport threading\n\nthreading.stack_size(67108864) # 64MB stack\nsys.setrecursionlimit(2 ** 20) # something real big\n # you actually hit the 64MB limit first\n # going by other answers, could just use 2**32-1\n\n# only new threads get the redefined stack size\nthread = threading.Thread(target=main)\nthread.start()\n\nI haven't tried to see what limits there might be on threading.stack_size, but feel free to try... that's where you need to look.\nIn summary, sys.setrecursionlimit is just a limit enforced by the interpreter itself. threading.stack_size lets you manipulate the actual limit imposed by the OS. If you hit the latter limit first, Python will just crash completely.\n",
"You shouldn't overuse recursive calls in CPython. It has not tail optimization, the function calls use a lot of memory and processing time. Those limits might not apply to other implementations, it's not in the blueprints.\nIn CPython, recursion is fine for traversing data structures (where a limit of 1000 should be enough for everybody) but not for algorithms. If I were to implement, say, graph related algorithms and hit the recursion limit, I would either implement my own stack and use iterations, or look for libraries implemented in C/C++/whatever before raising the limit by hand.\n"
] | [
36,
3
] | [] | [] | [
"platform",
"python",
"recursion"
] | stackoverflow_0002917210_platform_python_recursion.txt |
Q:
Python alternative to Adobe Real Time Messaging Protocol
Is there a way to stream audio and video over the internet using Python Web Programming and not Flash?
A:
Python is a server-side language, Flash is a client-side language. They do completely different things.
If you want to look at video streaming that doesn't require Flash, take a look at the HTML5 video element, which is a portion of the HTML5 standard being developed and is handled client-side by the browser.
| Python alternative to Adobe Real Time Messaging Protocol | Is there a way to stream audio and video over the internet using Python Web Programming and not Flash?
| [
"Python is a server-side language, Flash is a client-side language. They do completely different things.\nIf you want to look at video streaming that doesn't require Flash, take a look at the HTML5 video element, which is a portion of the HTML5 standard being developed and is handled client-side by the browser.\n"
] | [
0
] | [] | [] | [
"audio_streaming",
"python",
"streaming",
"video_streaming"
] | stackoverflow_0002918199_audio_streaming_python_streaming_video_streaming.txt |
Q:
Python encoding ISO to UTF8
I am trying to read my emails using a Python script (Python 2.5 and PyPy)
Some of my results are not in ASCII and i get strings like this:
=?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?='
Is there any way to decode it and convert to utf-8 so that i can process it?
I tried .decode('ISO-8859-7') but i got the same string
A:
import email.header as eh
unicode_data= u''.join(
str_data.decode(codec or 'ascii')
for str_data, codec
in eh.decode_header('=?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?='))
# unicode_data now is u'Πεζοπορία στον Κιθαιρώνα'
You should work with unicode_data here. However, if you (think you) need UTF-8 encoded string, you can:
utf8data= unicode_data.encode('utf-8')
Update: I changed the .decode call to cater for cases where the codec is None (e.g. eh.decode_header('plain text'))
A:
Read up on MIME encoding and Base64 encoding. The base64 module will be useful.
| Python encoding ISO to UTF8 | I am trying to read my emails using a Python script (Python 2.5 and PyPy)
Some of my results are not in ASCII and i get strings like this:
=?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?='
Is there any way to decode it and convert to utf-8 so that i can process it?
I tried .decode('ISO-8859-7') but i got the same string
| [
"import email.header as eh\n\nunicode_data= u''.join(\n str_data.decode(codec or 'ascii')\n for str_data, codec\n in eh.decode_header('=?ISO-8859-7?B?0OXm7/Dv8d/hIPP07+0gyuno4enx/u3h?='))\n# unicode_data now is u'Πεζοπορία στον Κιθαιρώνα'\n\nYou should work with unicode_data here. However, if you (think you) need UTF-8 encoded string, you can:\nutf8data= unicode_data.encode('utf-8')\n\nUpdate: I changed the .decode call to cater for cases where the codec is None (e.g. eh.decode_header('plain text'))\n",
"Read up on MIME encoding and Base64 encoding. The base64 module will be useful.\n"
] | [
5,
1
] | [] | [] | [
"encoding",
"internationalization",
"python"
] | stackoverflow_0002723212_encoding_internationalization_python.txt |
Q:
index error:list out of range
from string import Template
from string import Formatter
import pickle
f=open("C:/begpython/text2.txt",'r')
p='C:/begpython/text2.txt'
f1=open("C:/begpython/text3.txt",'w')
m=[]
i=0
k='a'
while k is not '':
k=f.readline()
mi=k.split(' ')
m=m+[mi]
i=i+1
print m[1]
f1.write(str(m[3]))
f1.write(str(m[4]))
x=[]
j=0
while j<i:
k=j-1
l=j+1
if j==0 or j==i:
j=j+1
else:
xj=[]
xj=xj+[j]
xj=xj+[m[j][2]]
xj=xj+[m[k][2]]
xj=xj+[m[l][2]]
xj=xj+[p]
x=x+[xj]
j=j+1
f1.write(','.join(x))
f.close()
f1.close()
It say line 33,xj=xj+m[l][2]
has index error,list out of range
please help
thanks in advance
A:
Suppose i is 10 then on the last run of the while loop j is 9, now you have l = j + 1 so l will be 10 but your 10 lines in m are indexed 0..9 so m[l][2] will give an index error.
Also, you code would look a lot better if you just added the elements to your list in one go i.e:
x = x + [j, m[j][2], m[k][2], m[l][2], p]
Spaces are an eyes best friend!
A:
The IndexError exception (list index out of range) means that you have attempted to access an array using an index that is beyond the bounds of the array. You can see this in action using a simple example like this:
>>> a = [1, 2, 3]
>>> a[2]
3
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
I can't exactly follow your code, but what that error means is that either:
l exceeds the bounds of m, or
2 exceeds the bounds of m[l]
| index error:list out of range | from string import Template
from string import Formatter
import pickle
f=open("C:/begpython/text2.txt",'r')
p='C:/begpython/text2.txt'
f1=open("C:/begpython/text3.txt",'w')
m=[]
i=0
k='a'
while k is not '':
k=f.readline()
mi=k.split(' ')
m=m+[mi]
i=i+1
print m[1]
f1.write(str(m[3]))
f1.write(str(m[4]))
x=[]
j=0
while j<i:
k=j-1
l=j+1
if j==0 or j==i:
j=j+1
else:
xj=[]
xj=xj+[j]
xj=xj+[m[j][2]]
xj=xj+[m[k][2]]
xj=xj+[m[l][2]]
xj=xj+[p]
x=x+[xj]
j=j+1
f1.write(','.join(x))
f.close()
f1.close()
It say line 33,xj=xj+m[l][2]
has index error,list out of range
please help
thanks in advance
| [
"Suppose i is 10 then on the last run of the while loop j is 9, now you have l = j + 1 so l will be 10 but your 10 lines in m are indexed 0..9 so m[l][2] will give an index error.\nAlso, you code would look a lot better if you just added the elements to your list in one go i.e:\nx = x + [j, m[j][2], m[k][2], m[l][2], p]\nSpaces are an eyes best friend!\n",
"The IndexError exception (list index out of range) means that you have attempted to access an array using an index that is beyond the bounds of the array. You can see this in action using a simple example like this:\n>>> a = [1, 2, 3]\n>>> a[2]\n3\n>>> a[3]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nIndexError: list index out of range\n\nI can't exactly follow your code, but what that error means is that either:\n\nl exceeds the bounds of m, or\n2 exceeds the bounds of m[l]\n\n"
] | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002918243_python.txt |
Q:
Emailing smtp with Python error
I can't figure out why this isn't working. I'm trying to send an email from my school email address with this code I got online. The same code works for sending from my GMail address. Does anyone know what this error means? The error occurs after waiting for about one and a half minutes.
import smtplib
FROMADDR = "FROM_EMAIL"
LOGIN = "USERNAME"
PASSWORD = "PASSWORD"
TOADDRS = ["TO_EMAIL"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"
server = smtplib.SMTP('OUTGOING_SMTP', 465)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
And here's the error I get:
Traceback (most recent call last):
File "emailer.py", line 13, in
server = smtplib.SMTP('OUTGOING_SMTP', 465)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in init
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 60] Operation timed out
A:
It's likely that your school's SMTP server does not permit outside access to port 587. Gmail does, and requires authentication to ensure that you are who you say you are (and so that spammers can't send email appearing to be from you unless they know your password). Your school may have chosen to set up their mail server so that only connections from within the school can send mail in this way.
| Emailing smtp with Python error | I can't figure out why this isn't working. I'm trying to send an email from my school email address with this code I got online. The same code works for sending from my GMail address. Does anyone know what this error means? The error occurs after waiting for about one and a half minutes.
import smtplib
FROMADDR = "FROM_EMAIL"
LOGIN = "USERNAME"
PASSWORD = "PASSWORD"
TOADDRS = ["TO_EMAIL"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"
server = smtplib.SMTP('OUTGOING_SMTP', 465)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
And here's the error I get:
Traceback (most recent call last):
File "emailer.py", line 13, in
server = smtplib.SMTP('OUTGOING_SMTP', 465)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 239, in init
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/socket.py", line 514, in create_connection
raise error, msg
socket.error: [Errno 60] Operation timed out
| [
"It's likely that your school's SMTP server does not permit outside access to port 587. Gmail does, and requires authentication to ensure that you are who you say you are (and so that spammers can't send email appearing to be from you unless they know your password). Your school may have chosen to set up their mail server so that only connections from within the school can send mail in this way.\n"
] | [
3
] | [] | [] | [
"email",
"python",
"smtp"
] | stackoverflow_0002918282_email_python_smtp.txt |
Q:
XML - python prints extra lines
from xml import xpath
from xml.dom import minidom
xmldata = minidom.parse('model.xml').documentElement
for maks in xpath.Evaluate('/cacti/results/maks/text()', xmldata):
print maks.nodeValue
And I get result:
85603399.14
398673062.66
95785523.81
But I needed to be:
85603399.14
NO SPACE
398673062.66
NO SPACE
95785523.81
Can somebody help me? I am new at programming
A:
Use:
print maks.nodeValue,
The comma at the end doesn't insert the extra newline.
| XML - python prints extra lines | from xml import xpath
from xml.dom import minidom
xmldata = minidom.parse('model.xml').documentElement
for maks in xpath.Evaluate('/cacti/results/maks/text()', xmldata):
print maks.nodeValue
And I get result:
85603399.14
398673062.66
95785523.81
But I needed to be:
85603399.14
NO SPACE
398673062.66
NO SPACE
95785523.81
Can somebody help me? I am new at programming
| [
"Use:\nprint maks.nodeValue,\n\nThe comma at the end doesn't insert the extra newline.\n"
] | [
3
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0002918316_minidom_python_xml.txt |
Q:
Reason for socket.error
I am a complete newbie when it comes to python, and programming in general. I've been working on a little webapp for the past few weeks trying to improve my coding chops. A few days ago my laptop was stolen so I went out and got a new MacBook Pro. Thank God I had everything under subversion control. The problem is now that I am on my new machine a script that I was running has stopped working and I have no idea why.
This is really the only part of what I have been writing that I borrowed heavily for existing scripts. It is from the widely available whois.py script and I have only slightly modified it as follows (see below). It was running fine on my old system (running ubuntu), but now the socket.error is being raised. I'm completely lost on this, and would really appreciate any help. Thanks!
def is_available(domainname, whoisserver="whois.verisign-grs.com", cache=0):
if whoisserver is None:
whoisserver = "whois.networksolutions.com"
s = None
while s == None:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
try:
s.connect((whoisserver, 43))
except socket.error, (ecode, reason):
if ecode in (115, 150): pass
else:
raise socket.error, (ecode, reason)
ret = select.select([s], [s], [], 30)
if len(ret[1])== 0 and len(ret[0]) == 0:
s.close()
raise TimedOut, "on connect "
s.setblocking(1)
except socket.error, (ecode, reason):
print ecode, reason
time.sleep(1)
s = None
s.send("%s \n\n" % domainname)
page = ""
while 1:
data = s.recv(8196)
if not data: break
page = page + data
s.close()
A:
Works fine for me, though it doesn't ever return anything. (Linux 2.6.32)
| Reason for socket.error | I am a complete newbie when it comes to python, and programming in general. I've been working on a little webapp for the past few weeks trying to improve my coding chops. A few days ago my laptop was stolen so I went out and got a new MacBook Pro. Thank God I had everything under subversion control. The problem is now that I am on my new machine a script that I was running has stopped working and I have no idea why.
This is really the only part of what I have been writing that I borrowed heavily for existing scripts. It is from the widely available whois.py script and I have only slightly modified it as follows (see below). It was running fine on my old system (running ubuntu), but now the socket.error is being raised. I'm completely lost on this, and would really appreciate any help. Thanks!
def is_available(domainname, whoisserver="whois.verisign-grs.com", cache=0):
if whoisserver is None:
whoisserver = "whois.networksolutions.com"
s = None
while s == None:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
try:
s.connect((whoisserver, 43))
except socket.error, (ecode, reason):
if ecode in (115, 150): pass
else:
raise socket.error, (ecode, reason)
ret = select.select([s], [s], [], 30)
if len(ret[1])== 0 and len(ret[0]) == 0:
s.close()
raise TimedOut, "on connect "
s.setblocking(1)
except socket.error, (ecode, reason):
print ecode, reason
time.sleep(1)
s = None
s.send("%s \n\n" % domainname)
page = ""
while 1:
data = s.recv(8196)
if not data: break
page = page + data
s.close()
| [
"Works fine for me, though it doesn't ever return anything. (Linux 2.6.32)\n"
] | [
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0002916910_python_sockets.txt |
Q:
how do simple SQLAlchemy relationships work?
I'm no database expert -- I just know the basics, really. I've picked up SQLAlchemy for a small project, and I'm using the declarative base configuration rather than the "normal" way. This way seems a lot simpler.
However, while setting up my database schema, I realized I don't understand some database relationship concepts.
If I had a many-to-one relationship before, for example, articles by authors (where each article could be written by only a single author), I would put an author_id field in my articles column. But SQLAlchemy has this ForeignKey object, and a relationship function with a backref kwarg, and I have no idea what any of it MEANS.
I'm scared to find out what a many-to-many relationship with an intermediate table looks like (when I need additional data about each relationship).
Can someone demystify this for me? Right now I'm setting up to allow openID auth for my application. So I've got this:
from __init__ import Base
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
class Users(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String, unique=True)
email = Column(String)
password = Column(String)
salt = Column(String)
class OpenID(Base):
__tablename__ = 'openid'
url = Column(String, primary_key=True)
user_id = #?
I think the ? should be replaced by Column(Integer, ForeignKey('users.id')), but I'm not sure -- and do I need to put openids = relationship("OpenID", backref="users") in the Users class? Why? What does it do? What is a backref?
A:
Yes, you need user_id = Column(Integer, ForeignKey('users.id')) or user_id = Column(Integer, ForeignKey('users.id'), nullable=False) if it's mandatory. This is directly translated to FOREIGN KEY in underlying database schema, no magic.
The simple way to declare relationship is user = relationship(Users) in OpenID class. You may also use users = relationship('OpenID') in Users class. backref parameter allows you to declare both relationships with single declaration: it means to automatically install backward relationship in related class. I personally prefer using backref-s for self-referring relationships only. The reason is that I like self-documented code: when you look through it's definition you see all defined properties, while with backref you need to look through other classes (probably defined in other modules).
| how do simple SQLAlchemy relationships work? | I'm no database expert -- I just know the basics, really. I've picked up SQLAlchemy for a small project, and I'm using the declarative base configuration rather than the "normal" way. This way seems a lot simpler.
However, while setting up my database schema, I realized I don't understand some database relationship concepts.
If I had a many-to-one relationship before, for example, articles by authors (where each article could be written by only a single author), I would put an author_id field in my articles column. But SQLAlchemy has this ForeignKey object, and a relationship function with a backref kwarg, and I have no idea what any of it MEANS.
I'm scared to find out what a many-to-many relationship with an intermediate table looks like (when I need additional data about each relationship).
Can someone demystify this for me? Right now I'm setting up to allow openID auth for my application. So I've got this:
from __init__ import Base
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
class Users(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String, unique=True)
email = Column(String)
password = Column(String)
salt = Column(String)
class OpenID(Base):
__tablename__ = 'openid'
url = Column(String, primary_key=True)
user_id = #?
I think the ? should be replaced by Column(Integer, ForeignKey('users.id')), but I'm not sure -- and do I need to put openids = relationship("OpenID", backref="users") in the Users class? Why? What does it do? What is a backref?
| [
"Yes, you need user_id = Column(Integer, ForeignKey('users.id')) or user_id = Column(Integer, ForeignKey('users.id'), nullable=False) if it's mandatory. This is directly translated to FOREIGN KEY in underlying database schema, no magic.\nThe simple way to declare relationship is user = relationship(Users) in OpenID class. You may also use users = relationship('OpenID') in Users class. backref parameter allows you to declare both relationships with single declaration: it means to automatically install backward relationship in related class. I personally prefer using backref-s for self-referring relationships only. The reason is that I like self-documented code: when you look through it's definition you see all defined properties, while with backref you need to look through other classes (probably defined in other modules).\n"
] | [
46
] | [] | [] | [
"database_design",
"python",
"sqlalchemy"
] | stackoverflow_0002917866_database_design_python_sqlalchemy.txt |
Q:
Making GUI applications on Linux/Windows. What languages/tools to use?
My student group and I are trying to continue working on a project we worked on this semester over the summer to become a professional, deployable app. We originally did it in Adobe AIR but it seems now that the computers this program will be running on will be very slow, maybe 600mhz and 128-256mb ram so flash just isn't going to cut it. It is basically a health diagnosis application that we will be shipping out to impoverished countries.
Now comes the real question. We are wondering what language to rebuild our application in. It has to have a good gui builder associated with it, like adobe flex/air gui builder or visual studio's gui builder but the application should run on linux primarily, and if it can run on windows thats just a plus. We are all students too without really any outside help so whatever we decide to do this in there must be ample documentation available when we hit problems.
Some things we have considered so far are using python and glade or c# and monodevelop, but again we really are not experts on any of this which is why I am asking for help as I would rather spend the time now choosing the right tools instead of wasting time down the line when we hit a roadblock.
Thanks in advance!
A:
I see answers pushing wx and gtk, so I can't avoid pushing Qt, my favorite!-) With a major corporation standing behind it (Nokia), two excellent sets of Python bindings (PyQt and PySide), support for Python 3, the superb Qt Designer, great Mac and mobile support too... it's seriously hard to beat...!-)
A:
The closest thing is probably going to be gtk# with monodevelop. It has a slick, Visual Studio-like ide, and the resulting programs will run on Linux and Windows. The language would be C#. I think this would be the best balance of performance and ease of use.
Alternatively, PyGtk is nice, and you can use Glade for the GUI designer, but it isn't quite as integrated as Monodevelop.
A:
For such low-end hardware I suggest wxWidgets or wxPython, using wxFormBuilder to create dialogs. You can use MS Visual Studio, Eclipse or CodeBlocks as development IDE. The latter two work on Linux well. Alternatively, you can use some simpler programmer's editor like Geany or Kate.
A:
To access really low end computers, and if you have no real graphics requirements, you could consider a text mode interface - curses/ncurses for one.
| Making GUI applications on Linux/Windows. What languages/tools to use? | My student group and I are trying to continue working on a project we worked on this semester over the summer to become a professional, deployable app. We originally did it in Adobe AIR but it seems now that the computers this program will be running on will be very slow, maybe 600mhz and 128-256mb ram so flash just isn't going to cut it. It is basically a health diagnosis application that we will be shipping out to impoverished countries.
Now comes the real question. We are wondering what language to rebuild our application in. It has to have a good gui builder associated with it, like adobe flex/air gui builder or visual studio's gui builder but the application should run on linux primarily, and if it can run on windows thats just a plus. We are all students too without really any outside help so whatever we decide to do this in there must be ample documentation available when we hit problems.
Some things we have considered so far are using python and glade or c# and monodevelop, but again we really are not experts on any of this which is why I am asking for help as I would rather spend the time now choosing the right tools instead of wasting time down the line when we hit a roadblock.
Thanks in advance!
| [
"I see answers pushing wx and gtk, so I can't avoid pushing Qt, my favorite!-) With a major corporation standing behind it (Nokia), two excellent sets of Python bindings (PyQt and PySide), support for Python 3, the superb Qt Designer, great Mac and mobile support too... it's seriously hard to beat...!-)\n",
"The closest thing is probably going to be gtk# with monodevelop. It has a slick, Visual Studio-like ide, and the resulting programs will run on Linux and Windows. The language would be C#. I think this would be the best balance of performance and ease of use.\nAlternatively, PyGtk is nice, and you can use Glade for the GUI designer, but it isn't quite as integrated as Monodevelop.\n",
"For such low-end hardware I suggest wxWidgets or wxPython, using wxFormBuilder to create dialogs. You can use MS Visual Studio, Eclipse or CodeBlocks as development IDE. The latter two work on Linux well. Alternatively, you can use some simpler programmer's editor like Geany or Kate.\n",
"To access really low end computers, and if you have no real graphics requirements, you could consider a text mode interface - curses/ncurses for one. \n"
] | [
4,
3,
1,
1
] | [] | [] | [
"glade",
"monodevelop",
"open_source",
"python",
"user_interface"
] | stackoverflow_0002918445_glade_monodevelop_open_source_python_user_interface.txt |
Q:
problem with f.readline()?
I am reading one line at a time from a file, but at the end of each line it adds a '\n'.
Example:
The file has: 094 234 hii
but my input is: 094 234 hii\n
I want to read line by line but I don't need to keep the newlines...
My goal is to read a list from every line: I need ['094','234','hii'], not ['094','234','hii\n'].
Any advice?
A:
It's not that it adds a '\n' so much as that there's really one there. Use line = line.rstrip() to get the line sans newline (or something similar to it depending on exactly what you need).
Don't use the readline method for reading a file line by line. Just use for line in f:. Files already iterate over their lines.
A:
The \n is not added, it's part of the line that's being read. And when you do line.split() the traiing \n goes away anyway, so why are you worrying about it?!
A:
for line in f:
words = line.split()
| problem with f.readline()? | I am reading one line at a time from a file, but at the end of each line it adds a '\n'.
Example:
The file has: 094 234 hii
but my input is: 094 234 hii\n
I want to read line by line but I don't need to keep the newlines...
My goal is to read a list from every line: I need ['094','234','hii'], not ['094','234','hii\n'].
Any advice?
| [
"\nIt's not that it adds a '\\n' so much as that there's really one there. Use line = line.rstrip() to get the line sans newline (or something similar to it depending on exactly what you need).\nDon't use the readline method for reading a file line by line. Just use for line in f:. Files already iterate over their lines.\n\n",
"The \\n is not added, it's part of the line that's being read. And when you do line.split() the traiing \\n goes away anyway, so why are you worrying about it?!\n",
"for line in f:\n words = line.split()\n\n"
] | [
7,
5,
4
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0002918572_file_io_python.txt |
Q:
Use a foreign key mapping to get data from the other table using Python and SQLAlchemy
Hmm, the title was harder to formulate than I thought.
Basically, I've got these simple classes mapped to tables, using SQLAlchemy. I know they're missing a few items but those aren't essential for highlighting the problem.
class Customer(object):
def __init__(self, uid, name, email):
self.uid = uid
self.name = name
self.email = email
def __repr__(self):
return str(self)
def __str__(self):
return "Cust: %s, Name: %s (Email: %s)" %(self.uid, self.name, self.email)
The above is basically a simple customer with an id, name and an email address.
class Order(object):
def __init__(self, item_id, item_name, customer):
self.item_id = item_id
self.item_name = item_name
self.customer = None
def __repr__(self):
return str(self)
def __str__(self):
return "Item ID %s: %s, has been ordered by customer no. %s" %(self.item_id, self.item_name, self.customer)
This is the Orders class that just holds the order information: an id, a name and a reference to a customer. It's initialised to None to indicate that this item doesn't have a customer yet. The code's job will assign the item a customer.
The following code maps these classes to respective database tables.
# SQLAlchemy database transmutation
engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()
customers_table = Table('customers', metadata,
Column('uid', Integer, primary_key=True),
Column('name', String),
Column('email', String)
)
orders_table = Table('orders', metadata,
Column('item_id', Integer, primary_key=True),
Column('item_name', String),
Column('customer', Integer, ForeignKey('customers.uid'))
)
metadata.create_all(engine)
mapper(Customer, customers_table)
mapper(Order, orders_table)
Now if I do something like:
for order in session.query(Order):
print order
I can get a list of orders in this form:
Item ID 1001: MX4000 Laser Mouse, has been ordered by customer no. 12
What I want to do is find out customer 12's name and email address (which is why I used the ForeignKey into the Customer table). How would I go about it?
Updated based on my comment
I know this seems a little useless, but just for the sake of knowing: what would I have to do to keep the relationship uni-directional?
Also, if I had another foreign key into another table? How would I update the mapper?
A:
First of all, if you do pass customer to the Order constructur, then at least use it.
I suggest, use a default value, but still allow assigning to a customer on creation as below:
class Order(object):
def __init__(self, item_id, item_name, customer=None):
self.item_id = item_id
self.item_name = item_name
self.customer = customer # self.customer = None
#...
In order for your relationship to work, you have to initialize relationship
between objects, FK is not enough. I suggest you change your code as following (extracts):
orders_table = Table('orders', metadata,
Column('item_id', Integer, primary_key=True),
Column('item_name', String),
Column('customer_id', Integer, ForeignKey('customers.uid')) # changed
)
# for bi-directional relationship use:
mapper(Customer, customers_table, properties={
'orders': relationship(Orders, backref='customer')
})
mapper(Orders, orders_table)
# for uni-directional relationship use:
mapper(Customer, customers_table)
mapper(Orders, orders_table, properties={
'customer': relationship(Customer)
})
#...
Then you can navigate from order to customer, and back:
print mycustomer.orders # in case of bi-directional
print order.customer
| Use a foreign key mapping to get data from the other table using Python and SQLAlchemy | Hmm, the title was harder to formulate than I thought.
Basically, I've got these simple classes mapped to tables, using SQLAlchemy. I know they're missing a few items but those aren't essential for highlighting the problem.
class Customer(object):
def __init__(self, uid, name, email):
self.uid = uid
self.name = name
self.email = email
def __repr__(self):
return str(self)
def __str__(self):
return "Cust: %s, Name: %s (Email: %s)" %(self.uid, self.name, self.email)
The above is basically a simple customer with an id, name and an email address.
class Order(object):
def __init__(self, item_id, item_name, customer):
self.item_id = item_id
self.item_name = item_name
self.customer = None
def __repr__(self):
return str(self)
def __str__(self):
return "Item ID %s: %s, has been ordered by customer no. %s" %(self.item_id, self.item_name, self.customer)
This is the Orders class that just holds the order information: an id, a name and a reference to a customer. It's initialised to None to indicate that this item doesn't have a customer yet. The code's job will assign the item a customer.
The following code maps these classes to respective database tables.
# SQLAlchemy database transmutation
engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()
customers_table = Table('customers', metadata,
Column('uid', Integer, primary_key=True),
Column('name', String),
Column('email', String)
)
orders_table = Table('orders', metadata,
Column('item_id', Integer, primary_key=True),
Column('item_name', String),
Column('customer', Integer, ForeignKey('customers.uid'))
)
metadata.create_all(engine)
mapper(Customer, customers_table)
mapper(Order, orders_table)
Now if I do something like:
for order in session.query(Order):
print order
I can get a list of orders in this form:
Item ID 1001: MX4000 Laser Mouse, has been ordered by customer no. 12
What I want to do is find out customer 12's name and email address (which is why I used the ForeignKey into the Customer table). How would I go about it?
Updated based on my comment
I know this seems a little useless, but just for the sake of knowing: what would I have to do to keep the relationship uni-directional?
Also, if I had another foreign key into another table? How would I update the mapper?
| [
"First of all, if you do pass customer to the Order constructur, then at least use it.\nI suggest, use a default value, but still allow assigning to a customer on creation as below:\nclass Order(object):\n def __init__(self, item_id, item_name, customer=None):\n self.item_id = item_id\n self.item_name = item_name\n self.customer = customer # self.customer = None\n #...\n\nIn order for your relationship to work, you have to initialize relationship\nbetween objects, FK is not enough. I suggest you change your code as following (extracts):\norders_table = Table('orders', metadata,\n Column('item_id', Integer, primary_key=True),\n Column('item_name', String),\n Column('customer_id', Integer, ForeignKey('customers.uid')) # changed\n)\n\n# for bi-directional relationship use:\nmapper(Customer, customers_table, properties={\n 'orders': relationship(Orders, backref='customer')\n})\nmapper(Orders, orders_table)\n# for uni-directional relationship use:\nmapper(Customer, customers_table)\nmapper(Orders, orders_table, properties={\n 'customer': relationship(Customer)\n})\n#...\n\nThen you can navigate from order to customer, and back:\nprint mycustomer.orders # in case of bi-directional\nprint order.customer\n\n"
] | [
5
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002918454_python_sqlalchemy.txt |
Q:
What host do I have to bind a listening socket to?
I used python's socket module and tried to open a listening socket using
import socket
import sys
def getServerSocket(host, port):
for r in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = r
try:
s = socket.socket(af, socktype, proto)
except socket.error, msg:
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error, msg:
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
sys.exit(1)
return s
Where host was None and port was 15000.
The program would then accept connections, but only from connections on the same machine. What do I have to do to accept connections from the internet?
A:
Try 0.0.0.0. That's what's mostly used.
A:
The first problem is that your except blocks are swallowing errors with no reports being made. The second problem is that you are trying to bind to a specific interface, rather than INADDR_ANY. You are probably binding to "localhost" which will only accept connections from the local machine.
INADDR_ANY is also known as the constant 0x00000000, but the macro is more meaningful.
Assuming you are using IPv4 (that is, "regular internet" these days), copy the socket/bind code from the first example on the socket module page.
A:
You'll need to bind to your public IP address, or "all" addresses (usually denoted by "0.0.0.0").
If you're trying to access it across a network you also might need to take into account firewalls etc.
| What host do I have to bind a listening socket to? | I used python's socket module and tried to open a listening socket using
import socket
import sys
def getServerSocket(host, port):
for r in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = r
try:
s = socket.socket(af, socktype, proto)
except socket.error, msg:
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error, msg:
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
sys.exit(1)
return s
Where host was None and port was 15000.
The program would then accept connections, but only from connections on the same machine. What do I have to do to accept connections from the internet?
| [
"Try 0.0.0.0. That's what's mostly used.\n",
"The first problem is that your except blocks are swallowing errors with no reports being made. The second problem is that you are trying to bind to a specific interface, rather than INADDR_ANY. You are probably binding to \"localhost\" which will only accept connections from the local machine.\nINADDR_ANY is also known as the constant 0x00000000, but the macro is more meaningful.\nAssuming you are using IPv4 (that is, \"regular internet\" these days), copy the socket/bind code from the first example on the socket module page.\n",
"You'll need to bind to your public IP address, or \"all\" addresses (usually denoted by \"0.0.0.0\").\nIf you're trying to access it across a network you also might need to take into account firewalls etc.\n"
] | [
8,
5,
2
] | [] | [] | [
"network_programming",
"networking",
"python",
"sockets"
] | stackoverflow_0002919068_network_programming_networking_python_sockets.txt |
Q:
stumped by WSGI module import errors
I'm writing a bare bones Python wsgi application and am getting stumped by module import errors. I have a .py file in the current directory which initially failed to import. By adding
sys.path.insert(0, '/Users/guhar/Sites/acom')
the import of the module worked. But I now try and import a module that I had installed via easy_install and it fails to import. I tried setting
sys.path.insert(0, '/Library/Python/2.5/site-packages/')
which contains the egg file, but to no avail. I would've thought that all packages under "/Library/Python/2.5/site-packages/" would be available to a WSGI application.
Does anybody have any pointers?
A:
Read:
http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
You cant simply add Python module directories containing .pth files into sys.path. You must use site.addsitedir() or use other options of mod_wsgi to have it use the virtual environment.
I think though perhaps, given that it looks like you are using MacOS X, that you have installed a second installation of Python and whatever mod_wsgi is using is not the version you have installed your packages into. That or your second Python installation is broken which often can be the case on MacOS X.
BTW, I am assuming that when you say WSGI you actually mean mod_wsgi given the tag you used. If you do, please do not use WSGI to refer to mod_wsgi. WSGI is a specification only, mod_wsgi is a specific hosting implementation. You should not be using the terms interchangeably.
A:
If you're running under Apache mod_wsgi, specify all necessary python paths in your virtual host configuration like this:
WSGIDaemonProcess ... python-path=/srv/lala/www:/srv/lala/lib/python2.6/site-packages:/Library/Python/2.5/site-packages
| stumped by WSGI module import errors | I'm writing a bare bones Python wsgi application and am getting stumped by module import errors. I have a .py file in the current directory which initially failed to import. By adding
sys.path.insert(0, '/Users/guhar/Sites/acom')
the import of the module worked. But I now try and import a module that I had installed via easy_install and it fails to import. I tried setting
sys.path.insert(0, '/Library/Python/2.5/site-packages/')
which contains the egg file, but to no avail. I would've thought that all packages under "/Library/Python/2.5/site-packages/" would be available to a WSGI application.
Does anybody have any pointers?
| [
"Read:\nhttp://code.google.com/p/modwsgi/wiki/VirtualEnvironments\nYou cant simply add Python module directories containing .pth files into sys.path. You must use site.addsitedir() or use other options of mod_wsgi to have it use the virtual environment.\nI think though perhaps, given that it looks like you are using MacOS X, that you have installed a second installation of Python and whatever mod_wsgi is using is not the version you have installed your packages into. That or your second Python installation is broken which often can be the case on MacOS X.\nBTW, I am assuming that when you say WSGI you actually mean mod_wsgi given the tag you used. If you do, please do not use WSGI to refer to mod_wsgi. WSGI is a specification only, mod_wsgi is a specific hosting implementation. You should not be using the terms interchangeably.\n",
"If you're running under Apache mod_wsgi, specify all necessary python paths in your virtual host configuration like this:\nWSGIDaemonProcess ... python-path=/srv/lala/www:/srv/lala/lib/python2.6/site-packages:/Library/Python/2.5/site-packages\n\n"
] | [
5,
1
] | [] | [] | [
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0002917972_mod_wsgi_python_wsgi.txt |
Q:
Load image from string
Given a string containing jpeg image data, is it possible to load this directly in pygame?
I've tried using StringIO but failed and I don't completely understand the 'file-like' object concept.
Currently, as a workaround, I'm saving to disk and then loading an image the standard way:
# imagestring contains a jpeg
f=open('test.jpg','wb')
f.write(imagestring)
f.close()
image=pygame.image.load('test.jpg')
Any suggestions on improving this so that we avoid creating a temp file?
A:
fstr = cStringIO.StringIO(simage)
pygame.image.load(fstr, namehint="somethinguseful")
| Load image from string | Given a string containing jpeg image data, is it possible to load this directly in pygame?
I've tried using StringIO but failed and I don't completely understand the 'file-like' object concept.
Currently, as a workaround, I'm saving to disk and then loading an image the standard way:
# imagestring contains a jpeg
f=open('test.jpg','wb')
f.write(imagestring)
f.close()
image=pygame.image.load('test.jpg')
Any suggestions on improving this so that we avoid creating a temp file?
| [
"fstr = cStringIO.StringIO(simage)\npygame.image.load(fstr, namehint=\"somethinguseful\")\n\n"
] | [
2
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0002919236_pygame_python.txt |
Q:
Get client ip with python
I'm a newbie in python.
I want to write a simple web that prints the client ip on screen
my http.conf Handler:
AddHandler mod_python .py
PythonHandler mod_python.publisher
PythonDebug On
The cgi.escape(os.environ["REMOTE_ADDR"]) return this error: KeyError: 'REMOTE_ADDR'
and I just get lost with the BaseHTTPRequestHandler
so what is the simple way to get the client ip?
thank you.
A:
In case you're concerned about scalability, this might be a bit faster:
from mod_python import apache
req.get_remote_host(apache.REMOTE_NOLOOKUP)
A:
OK, I found the answer:
from mod_python import apache
def client_ip(req):
req.add_common_vars()
return req.subprocess_env['REMOTE_ADDR']
It's working!
| Get client ip with python | I'm a newbie in python.
I want to write a simple web that prints the client ip on screen
my http.conf Handler:
AddHandler mod_python .py
PythonHandler mod_python.publisher
PythonDebug On
The cgi.escape(os.environ["REMOTE_ADDR"]) return this error: KeyError: 'REMOTE_ADDR'
and I just get lost with the BaseHTTPRequestHandler
so what is the simple way to get the client ip?
thank you.
| [
"In case you're concerned about scalability, this might be a bit faster:\nfrom mod_python import apache\nreq.get_remote_host(apache.REMOTE_NOLOOKUP)\n\n",
"OK, I found the answer:\nfrom mod_python import apache\ndef client_ip(req):\n req.add_common_vars()\n return req.subprocess_env['REMOTE_ADDR']\n\nIt's working!\n"
] | [
7,
0
] | [] | [] | [
"apache",
"mod_python",
"python",
"webserver"
] | stackoverflow_0002919329_apache_mod_python_python_webserver.txt |
Q:
Writing a post search algorithm
I'm trying to write a free text search algorithm for finding specific posts on a wall (similar kind of wall as Facebook uses). A user is suppose to be able to write some words in a search field and get hits on posts that contain the words; with the best match on top and then other posts in decreasing order according to match score.
I'm using the edit distance (Levenshtein) "e(x, y) = e" to calculate the score for each post when compared to the query word "x" and post word "y" according to: score(x, y) = 2^(2 - e)(1 - min(e, |x|) / |x|), where "|x|" is the number of letters in the query word.
Each word in a post contributes to the total score for that specific post. This approach seems to work well when the posts are of roughly the same size, but sometime certain large posts manages to rack up score solely on having a lot of words in them while in practice not being relevant to the query.
Am I approaching this problem in the wrong way or is there some way to normalize the score that I haven't thought of?
A:
Yes. There are many normalization methods you could use. This is a well-researched field!
Take a look at the vector space model . TDF/IDF could be relevant to what you're doing. It's not strictly related to the method you're using but could give you some normalization leads.
Also note that comparing each post will be O(N) and could get very slow. Instead of string-distance, you may have better results with stemmming. You can then put that into a VSM inverted index.
Many databases (including MySQL and Postgres) have full-text search. That's probably more practical than doing it yourself.
| Writing a post search algorithm | I'm trying to write a free text search algorithm for finding specific posts on a wall (similar kind of wall as Facebook uses). A user is suppose to be able to write some words in a search field and get hits on posts that contain the words; with the best match on top and then other posts in decreasing order according to match score.
I'm using the edit distance (Levenshtein) "e(x, y) = e" to calculate the score for each post when compared to the query word "x" and post word "y" according to: score(x, y) = 2^(2 - e)(1 - min(e, |x|) / |x|), where "|x|" is the number of letters in the query word.
Each word in a post contributes to the total score for that specific post. This approach seems to work well when the posts are of roughly the same size, but sometime certain large posts manages to rack up score solely on having a lot of words in them while in practice not being relevant to the query.
Am I approaching this problem in the wrong way or is there some way to normalize the score that I haven't thought of?
| [
"Yes. There are many normalization methods you could use. This is a well-researched field!\nTake a look at the vector space model . TDF/IDF could be relevant to what you're doing. It's not strictly related to the method you're using but could give you some normalization leads.\nAlso note that comparing each post will be O(N) and could get very slow. Instead of string-distance, you may have better results with stemmming. You can then put that into a VSM inverted index.\nMany databases (including MySQL and Postgres) have full-text search. That's probably more practical than doing it yourself.\n"
] | [
1
] | [] | [] | [
"full_text_search",
"levenshtein_distance",
"python"
] | stackoverflow_0002919528_full_text_search_levenshtein_distance_python.txt |
Q:
GWT on Python App Engine
I have a python app engine code (matured backend) - and we are now planning to have a front end for that code.
I was wondering whether it is possible to implement GWT as the front end.
Even though Alex Martelli in this post [1] mentions it is not possible, a comment to that post suggests that it is indeed possible using rpc over json for GWT.
I was unable to understand how this is possible. In app.yaml file, we have to specify the language to be python, right? In that case, how can it compile GWT based on JAVA? Are there any examples on anyone doing that?
Can someone help me out? It would be extremely helpful.
[1]: Choosing Java vs Python on Google App Engine link
A:
I use GWT with Python quite a bit - the JSON interface works perfectly well. Your GWT front-end is still written in a java-like syntax, and you still need the Java toolchain to actually compile it down to HTML/Javascript, but it doesn't care what language the backend is written in.
As for how this is accomplished - the GWT toolchain is completely independent of GAE, there's no executable Java on the AppEngine side. You design and write your frontend in GWT on your own system, and then compile it to HTML/JS, which is what you upload to GAE.
| GWT on Python App Engine | I have a python app engine code (matured backend) - and we are now planning to have a front end for that code.
I was wondering whether it is possible to implement GWT as the front end.
Even though Alex Martelli in this post [1] mentions it is not possible, a comment to that post suggests that it is indeed possible using rpc over json for GWT.
I was unable to understand how this is possible. In app.yaml file, we have to specify the language to be python, right? In that case, how can it compile GWT based on JAVA? Are there any examples on anyone doing that?
Can someone help me out? It would be extremely helpful.
[1]: Choosing Java vs Python on Google App Engine link
| [
"I use GWT with Python quite a bit - the JSON interface works perfectly well. Your GWT front-end is still written in a java-like syntax, and you still need the Java toolchain to actually compile it down to HTML/Javascript, but it doesn't care what language the backend is written in.\nAs for how this is accomplished - the GWT toolchain is completely independent of GAE, there's no executable Java on the AppEngine side. You design and write your frontend in GWT on your own system, and then compile it to HTML/JS, which is what you upload to GAE.\n"
] | [
7
] | [] | [] | [
"google_app_engine",
"gwt",
"json",
"python",
"rpc"
] | stackoverflow_0002919608_google_app_engine_gwt_json_python_rpc.txt |
Q:
Sending file over socket
I'm have a problem sending data as a file from one end of a socket to the other. What's happening is that both the server and client are trying to read the file so the file never gets sent. I was wondering how to have the client block until the server's completed reading the file sent from the client.
I have this working with raw packets using send and recv, but figured this was a cleaner solution...
Client:
connects to server creating socket connection
creates a file on socket and sends data
waits for file from server
Server:
waits for file from client
Complete interraction:
client sends data to server
server sends data to client
Edit
The code I'm actually looking at was posted in this question, but I think the Eventlet stuff scared people...
https://stackoverflow.com/questions/2909358/eventlet-client-server
Underneath its just using Python sockets so I figured I'd simplify the question and ask about just the core socket issue...
A:
It sounds like you have the client sending the file and then waiting for the server response, but if you don't give the server an indication that it has completely read the file, recv() on the server side will hang waiting for more data. You can call shutdown(SHUT_WR) on the client-side once the client is done sending. This informs the server that once it has read all the data sent that there is no more.
A very basic example (sending one data blob to server and receiving one data blob in response):
server
>>> from socket import *
>>> s=socket()
>>> s.bind(('',8000))
>>> s.listen(1)
>>> c,a = s.accept() # will hang here until a client connects
>>> recvd=''
>>> while True:
... data = c.recv(1024)
... if not data: break # recv() will return '' only if the client calls shutdown(SHUT_WR) or close()
... recvd += data
...
>>> recvd
'a message'
>>> c.sendall('a response')
>>> c.close() # done with client, could loop back to accept here
>>> s.close() # done with server
client
>>> from socket import *
>>> s=socket()
>>> s.connect(('localhost',8000))
>>> s.sendall('a message')
>>> s.shutdown(SHUT_WR) # tells server you're done sending, so recv won't wait for more
>>> recvd=''
>>> while True:
... data = s.recv(1024)
... if not data: break
... recvd += data
...
>>> recvd
'a response'
>>> s.close()
A:
I'm not sure the question is clear, are you asking:
How to send an entire file's worth of data across a socket?
How to get a writer to block after writing some data?
Something else altogether??
If the question is #1, you need to open the file and parse it into a stream of bytes and then pass the entire collection of bytes in a single 'write' call.
If the question is #2, meaning you want the writer to wait until the reader has completely read the bytes (and processed them??) before moving on, then you need the reader and writer to coordinate. You can do this by having the writer call 'read' (read is a blocking call) after writing. Then after the reader is done reading (and processing the bytes) have it write something to the writer to wake it up.
If the question is #3, maybe you can provide some more details.
A:
I'm not exactly clear on what you're asking, but perhaps you are looking for select?
http://docs.python.org/library/select.html
| Sending file over socket | I'm have a problem sending data as a file from one end of a socket to the other. What's happening is that both the server and client are trying to read the file so the file never gets sent. I was wondering how to have the client block until the server's completed reading the file sent from the client.
I have this working with raw packets using send and recv, but figured this was a cleaner solution...
Client:
connects to server creating socket connection
creates a file on socket and sends data
waits for file from server
Server:
waits for file from client
Complete interraction:
client sends data to server
server sends data to client
Edit
The code I'm actually looking at was posted in this question, but I think the Eventlet stuff scared people...
https://stackoverflow.com/questions/2909358/eventlet-client-server
Underneath its just using Python sockets so I figured I'd simplify the question and ask about just the core socket issue...
| [
"It sounds like you have the client sending the file and then waiting for the server response, but if you don't give the server an indication that it has completely read the file, recv() on the server side will hang waiting for more data. You can call shutdown(SHUT_WR) on the client-side once the client is done sending. This informs the server that once it has read all the data sent that there is no more.\nA very basic example (sending one data blob to server and receiving one data blob in response):\nserver\n>>> from socket import *\n>>> s=socket()\n>>> s.bind(('',8000))\n>>> s.listen(1)\n>>> c,a = s.accept() # will hang here until a client connects\n>>> recvd=''\n>>> while True:\n... data = c.recv(1024)\n... if not data: break # recv() will return '' only if the client calls shutdown(SHUT_WR) or close()\n... recvd += data\n...\n>>> recvd\n'a message'\n>>> c.sendall('a response')\n>>> c.close() # done with client, could loop back to accept here\n>>> s.close() # done with server\n\nclient\n>>> from socket import *\n>>> s=socket()\n>>> s.connect(('localhost',8000))\n>>> s.sendall('a message')\n>>> s.shutdown(SHUT_WR) # tells server you're done sending, so recv won't wait for more\n>>> recvd=''\n>>> while True:\n... data = s.recv(1024)\n... if not data: break\n... recvd += data\n...\n>>> recvd\n'a response'\n>>> s.close()\n\n",
"I'm not sure the question is clear, are you asking:\n\nHow to send an entire file's worth of data across a socket?\nHow to get a writer to block after writing some data?\nSomething else altogether??\n\nIf the question is #1, you need to open the file and parse it into a stream of bytes and then pass the entire collection of bytes in a single 'write' call.\nIf the question is #2, meaning you want the writer to wait until the reader has completely read the bytes (and processed them??) before moving on, then you need the reader and writer to coordinate. You can do this by having the writer call 'read' (read is a blocking call) after writing. Then after the reader is done reading (and processing the bytes) have it write something to the writer to wake it up.\nIf the question is #3, maybe you can provide some more details.\n",
"I'm not exactly clear on what you're asking, but perhaps you are looking for select?\nhttp://docs.python.org/library/select.html\n"
] | [
3,
1,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0002915030_python_sockets.txt |
Q:
Calling a non python program from python?
I am currently struggling to call a non python program from a python script.
I have a ~1000 files that when passed through this C++ program will generate ~1000 outputs. Each output file must have a distinct name.
The command I wish to run is of the form:
program_name -input -output -o1 -o2 -o3
To date I have tried:
import os
cwd = os.getcwd()
files = os.listdir(cwd)
required_files = []
for i in file:
if i.endswith('.ttp'):
required_files.append(i)
So, I have an array of the neccesary files. My problem - how do I iterate over the array and for each entry, pass it to the above command (program_name) as an argument and specify a unique output id for each file?
A:
You can use subprocess for that purpose:
import os
import subprocess
cwd = os.getcwd()
for i in os.listdir(cwd):
if i.endswith('.ttp'):
o = i + "-out"
p = subprocess.call(["program_name", "-input", i, "-output", o])
| Calling a non python program from python? | I am currently struggling to call a non python program from a python script.
I have a ~1000 files that when passed through this C++ program will generate ~1000 outputs. Each output file must have a distinct name.
The command I wish to run is of the form:
program_name -input -output -o1 -o2 -o3
To date I have tried:
import os
cwd = os.getcwd()
files = os.listdir(cwd)
required_files = []
for i in file:
if i.endswith('.ttp'):
required_files.append(i)
So, I have an array of the neccesary files. My problem - how do I iterate over the array and for each entry, pass it to the above command (program_name) as an argument and specify a unique output id for each file?
| [
"You can use subprocess for that purpose:\nimport os\nimport subprocess\n\ncwd = os.getcwd()\n\nfor i in os.listdir(cwd):\n if i.endswith('.ttp'):\n o = i + \"-out\"\n p = subprocess.call([\"program_name\", \"-input\", i, \"-output\", o])\n\n"
] | [
11
] | [] | [] | [
"python",
"system_calls"
] | stackoverflow_0002919783_python_system_calls.txt |
Q:
problem with lists?
j=0
x=[]
for j in range(9):
x=x+ [j]
this will output
[1,2,3,4,5,6,7,8,9]
i wanted it as
['1','2','3'...
how can I get it?
A:
convert to string:
>>> [str(i) for i in range(9)]
['0', '1', '2', '3', '4', '5', '6', '7', '8']
if you want your list to start with 1 just change your range function:
>>> [str(i) for i in range(1, 9)]
['1', '2', '3', '4', '5', '6', '7', '8']
Also, you don't need to initialise loop variable (j=0 is not required).
A:
Python 2
>>> map(str, range(1, 9))
['1', '2', '3', '4', '5', '6', '7', '8']
Python 3
>>> list(map(str, range(1, 9)))
['1', '2', '3', '4', '5', '6', '7', '8']
Documentation for range:
http://docs.python.org/library/functions.html#range
A:
Ok, the "good" python ways are already posted, but I want to show you how you would modify your example to make it work the way you want it:
j=0
x=[]
for j in range(9):
x = x + [str(j)]
A:
j=0
x=[]
for j in range(9):
x=x+[str(j)]
| problem with lists? | j=0
x=[]
for j in range(9):
x=x+ [j]
this will output
[1,2,3,4,5,6,7,8,9]
i wanted it as
['1','2','3'...
how can I get it?
| [
"convert to string:\n>>> [str(i) for i in range(9)]\n['0', '1', '2', '3', '4', '5', '6', '7', '8']\n\nif you want your list to start with 1 just change your range function:\n>>> [str(i) for i in range(1, 9)]\n['1', '2', '3', '4', '5', '6', '7', '8']\n\nAlso, you don't need to initialise loop variable (j=0 is not required).\n",
"Python 2\n>>> map(str, range(1, 9))\n['1', '2', '3', '4', '5', '6', '7', '8']\n\nPython 3\n>>> list(map(str, range(1, 9)))\n['1', '2', '3', '4', '5', '6', '7', '8']\n\nDocumentation for range:\n\nhttp://docs.python.org/library/functions.html#range\n\n",
"Ok, the \"good\" python ways are already posted, but I want to show you how you would modify your example to make it work the way you want it:\nj=0 \nx=[] \nfor j in range(9): \n x = x + [str(j)] \n\n",
"j=0\nx=[]\nfor j in range(9):\n x=x+[str(j)]\n\n"
] | [
12,
4,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0002919757_python.txt |
Q:
RW - Primary/Secondary DNS Address In Python
I want to read the primary and secondary dns addresses from the system and want to change it to any user given address.
Is this possible through some library.
An alternative approach is that I read the /etc/resolv.conf and do the changes, which is what I've done.
BTW the current solution I have is for Ubuntu OS, and for now if I get if for the same OS also it would be fine.
A:
/etc/resolv.conf IS the authoritative source of DNS servers, so you better check there.
A bit off-topic, but note that it's being overriden by DHCP, so if you need to add own DNS server, you have to edit /etc/dhcp3/dhclient.conf and add there something like:
append domain-name-servers <DNS-ip>;
or
prepend domain-name-servers <DNS-ip>;
Also note that Ubuntu (at least 9.04 I'm using) supports only up to 3 DNS servers.
| RW - Primary/Secondary DNS Address In Python | I want to read the primary and secondary dns addresses from the system and want to change it to any user given address.
Is this possible through some library.
An alternative approach is that I read the /etc/resolv.conf and do the changes, which is what I've done.
BTW the current solution I have is for Ubuntu OS, and for now if I get if for the same OS also it would be fine.
| [
"/etc/resolv.conf IS the authoritative source of DNS servers, so you better check there. \nA bit off-topic, but note that it's being overriden by DHCP, so if you need to add own DNS server, you have to edit /etc/dhcp3/dhclient.conf and add there something like:\nappend domain-name-servers <DNS-ip>;\n\nor\nprepend domain-name-servers <DNS-ip>;\n\nAlso note that Ubuntu (at least 9.04 I'm using) supports only up to 3 DNS servers.\n"
] | [
1
] | [] | [] | [
"dns",
"python",
"ubuntu"
] | stackoverflow_0002919794_dns_python_ubuntu.txt |
Q:
Python urllib2 multiple try statement on urlopen()
So, simply I want to be able to run a for across a list of URLs, if one fails then I want to continue on to try the next.
I've tried using the following but sadly it throws and exception if the first URL doesn't work.
servers = ('http://www.google.com', 'http://www.stackoverflow.com')
for server in servers:
try:
u = urllib2.urlopen(server)
except urllib2.URLError:
continue
else:
break
else:
raise
Any ideas?
Thanks in advance.
A:
servers = ('http://www.google.com', 'http://www.stackoverflow.com')
for server in servers:
try:
u = urllib2.urlopen(server)
except urllib2.URLError:
continue
else:
break
else:
raise
This code breaks out of the loop if the url connection doesn't raise an error (else: break part).
Do you want the 2nd one used only if the first fails?
edit: I thought that the else: following the for loop should raise because of the break, but in my quick test that didn't work ... because my understanding of for/else was wrong
A:
So the problem turned out to be user error. I was trying stupid domains like "wegwegwe.com" but I never actually had a usable domain in the list, so eventually it did just raise the exception.
User error.
| Python urllib2 multiple try statement on urlopen() | So, simply I want to be able to run a for across a list of URLs, if one fails then I want to continue on to try the next.
I've tried using the following but sadly it throws and exception if the first URL doesn't work.
servers = ('http://www.google.com', 'http://www.stackoverflow.com')
for server in servers:
try:
u = urllib2.urlopen(server)
except urllib2.URLError:
continue
else:
break
else:
raise
Any ideas?
Thanks in advance.
| [
"servers = ('http://www.google.com', 'http://www.stackoverflow.com')\nfor server in servers:\n try:\n u = urllib2.urlopen(server)\n except urllib2.URLError:\n continue\n else:\n break\nelse:\n raise\n\nThis code breaks out of the loop if the url connection doesn't raise an error (else: break part).\nDo you want the 2nd one used only if the first fails?\nedit: I thought that the else: following the for loop should raise because of the break, but in my quick test that didn't work ... because my understanding of for/else was wrong \n",
"So the problem turned out to be user error. I was trying stupid domains like \"wegwegwe.com\" but I never actually had a usable domain in the list, so eventually it did just raise the exception.\nUser error.\n"
] | [
0,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0002917127_python_urllib2.txt |
Q:
Strange (atleast for me) behavior in Django template
The following code snippet in a Django template (v 1.1) doesn't work.
{{ item.vendors.all.0 }} ==> returns "Test"
but the following code snippet, doesn't hide the paragraph!
{% ifnotequal item.vendors.all.0 "Test" %}
<p class="view_vendor">Vendor(s): {{item.vendors.all.0}} </p><br />
{% endifnotequal %}
Any tips on what's wrong?
Thanks.
A:
item.vendors.all.0 doesn't return "Test": It returns a vendor object, which gives "Test" when converted to a string. If you just compare the object with "Test", it will never be equal.
Try converting the object to a string before comparing:
{% ifnotequal item.vendors.all.0|stringformat:"s" "Test" %}
| Strange (atleast for me) behavior in Django template | The following code snippet in a Django template (v 1.1) doesn't work.
{{ item.vendors.all.0 }} ==> returns "Test"
but the following code snippet, doesn't hide the paragraph!
{% ifnotequal item.vendors.all.0 "Test" %}
<p class="view_vendor">Vendor(s): {{item.vendors.all.0}} </p><br />
{% endifnotequal %}
Any tips on what's wrong?
Thanks.
| [
"item.vendors.all.0 doesn't return \"Test\": It returns a vendor object, which gives \"Test\" when converted to a string. If you just compare the object with \"Test\", it will never be equal.\nTry converting the object to a string before comparing:\n{% ifnotequal item.vendors.all.0|stringformat:\"s\" \"Test\" %}\n\n"
] | [
6
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002920469_django_django_templates_python.txt |
Q:
Django, how to create form for add/edit object with m2m links?
Good afternoon! There are three essences. Product, Option and ProductOption. Product has link many to many to Option through ProductOption. Prompt how to create please for Product'a the form of addition/editing with these options (not on administration page)?
If simply to output {{product.options}} - will be SelectBox with a plural choice. And it is necessary for me that it there were forms. Each option has description and the map. That it was possible to enter them.
Appearance to myself I represent as:
The check boxing with the option name in a label, more low the option description. And so lines 10.
Having read materials on the Internet has understood that in this case it is necessary to use formsets. But here there is one more problem:
At the moment of product editing it is necessary to show all possible options, and not just those that with it have once been saved. I.e. saved (and filled) plus yet not anchored to this model. Prompt where to dig please.
Thanks.
A:
This is my models.py.
class Section(models.Model):
title = models.CharField(max_length=250)
def __unicode__(self):
return self.title
class Meta:
pass
class Option(models.Model):
title = models.CharField(blank=True, null=True, max_length=250)
section = models.ManyToManyField(Section)
def __unicode__(self):
return self.title
class Meta:
pass
class Card(models.Model):
title = models.CharField(max_length=250)
section = models.ForeignKey(Section)
options = models.ManyToManyField(Option, through='CardOption')
def __unicode__(self):
return self.title
class Meta:
pass
class CardOption(models.Model):
card = models.ForeignKey(Card)
option = models.ForeignKey(Option)
description = models.TextField(blank=True, null=True, max_length = 300)
class Meta:
pass
| Django, how to create form for add/edit object with m2m links? | Good afternoon! There are three essences. Product, Option and ProductOption. Product has link many to many to Option through ProductOption. Prompt how to create please for Product'a the form of addition/editing with these options (not on administration page)?
If simply to output {{product.options}} - will be SelectBox with a plural choice. And it is necessary for me that it there were forms. Each option has description and the map. That it was possible to enter them.
Appearance to myself I represent as:
The check boxing with the option name in a label, more low the option description. And so lines 10.
Having read materials on the Internet has understood that in this case it is necessary to use formsets. But here there is one more problem:
At the moment of product editing it is necessary to show all possible options, and not just those that with it have once been saved. I.e. saved (and filled) plus yet not anchored to this model. Prompt where to dig please.
Thanks.
| [
"This is my models.py.\nclass Section(models.Model):\n title = models.CharField(max_length=250)\n\n def __unicode__(self):\n return self.title\n\n class Meta:\n pass\n\n\nclass Option(models.Model):\n title = models.CharField(blank=True, null=True, max_length=250)\n section = models.ManyToManyField(Section)\n\n def __unicode__(self):\n return self.title\n\n class Meta:\n pass\n\n\nclass Card(models.Model):\n title = models.CharField(max_length=250)\n section = models.ForeignKey(Section)\n options = models.ManyToManyField(Option, through='CardOption')\n\n def __unicode__(self):\n return self.title\n\n class Meta:\n pass\n\n\nclass CardOption(models.Model):\n card = models.ForeignKey(Card)\n option = models.ForeignKey(Option)\n description = models.TextField(blank=True, null=True, max_length = 300)\n\n class Meta:\n pass\n\n"
] | [
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0002911886_django_django_forms_django_templates_python.txt |
Q:
How do I slice a python string programmatically?
Very simple question, hopefully. So, in Python you can split up strings using indices as follows:
>>> a="abcdefg"
>>> print a[2:4]
cd
but how do you do this if the indices are based on variables? E.g.
>>> j=2
>>> h=4
>>> print a[j,h]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: string indices must be integers
A:
It works you just have a typo in there, use a[j:h] instead of a[j,h] :
>>> a="abcdefg"
>>> print a[2:4]
cd
>>> j=2
>>> h=4
>>> print a[j:h]
cd
>>>
A:
In addition to Bakkal's answer, here is how to manipulate slices programmatically, which is sometimes convenient:
a = 'abcdefg'
j=2;h=4
my_slice = slice(j,h) # you can pass this object around if you wish
a[my_slice] # -> cd
| How do I slice a python string programmatically? | Very simple question, hopefully. So, in Python you can split up strings using indices as follows:
>>> a="abcdefg"
>>> print a[2:4]
cd
but how do you do this if the indices are based on variables? E.g.
>>> j=2
>>> h=4
>>> print a[j,h]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: string indices must be integers
| [
"It works you just have a typo in there, use a[j:h] instead of a[j,h] :\n>>> a=\"abcdefg\"\n>>> print a[2:4]\ncd\n>>> j=2\n>>> h=4\n>>> print a[j:h]\ncd\n>>> \n\n",
"In addition to Bakkal's answer, here is how to manipulate slices programmatically, which is sometimes convenient:\na = 'abcdefg'\nj=2;h=4\nmy_slice = slice(j,h) # you can pass this object around if you wish\n\na[my_slice] # -> cd\n\n"
] | [
12,
5
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002920551_python_string.txt |
Q:
related to list and file handling?
I have file with contents in list form such as
[1,'ab','fgf','ssd']
[2,'eb','ghf','hhsd']
[3,'ag','rtf','ssfdd']
I want to read that file line by line using f.readline and assign each line to a list.
I tried doing this:
k=[ ]
k=f.readline()
print k[1]
I expected a result to show 2nd element in the list in first line, but it showed the first bit and gave o/p as '1'.
How to get the expected output?
A:
If all you want is to take the input format shown and store it as a list attempting to execute the input file (with eval()) is not a good idea. This leaves your program open to all sorts of accidentally and intentionally harmful input. You are better advised to just parse the input file:
s=f.readline()[1:-1]
k = s.split(',')
print k[1]
A:
readline just returns strings. You need to cast it to what you want. eval does the job, be warned that however it does execute everything inside the string, so this is only an option if you trust the input (i.e. you've saved it yourself).
If you need to save data from your program to a file, you might want to use pickle.
A:
if the sample posted is actual content of your file (which I highly doubt), here is what you could do starting with Python 2.6, docs:
>>> for line in open(fname):
print(ast.literal_eval(line)[1])
ab
eb
ag
A:
You could use eval on each line; this would evaluate the the expression in the line and should yield your expected list, if the formatting is correct.
A safer solution would be a simple CSV parser. For that your input could look something like this (comma-separated):
123,321,12,123,321,'asd',ewr,'afdg','et al',213
Maybe this is feasible.
A:
Maybe You can use eval as suggested, but I'm just curious: Is there any reason not to use JSON as file format?
A:
You can use the json module:
import json
with open('lists.txt', 'r') as f:
lines = f.readlines()
for line in lines:
line = line.replace("'", '"')
l = json.loads(line)
print l[1]
Outputs:
ab
eb
ag
| related to list and file handling? | I have file with contents in list form such as
[1,'ab','fgf','ssd']
[2,'eb','ghf','hhsd']
[3,'ag','rtf','ssfdd']
I want to read that file line by line using f.readline and assign each line to a list.
I tried doing this:
k=[ ]
k=f.readline()
print k[1]
I expected a result to show 2nd element in the list in first line, but it showed the first bit and gave o/p as '1'.
How to get the expected output?
| [
"If all you want is to take the input format shown and store it as a list attempting to execute the input file (with eval()) is not a good idea. This leaves your program open to all sorts of accidentally and intentionally harmful input. You are better advised to just parse the input file:\ns=f.readline()[1:-1]\nk = s.split(',')\nprint k[1]\n\n",
"readline just returns strings. You need to cast it to what you want. eval does the job, be warned that however it does execute everything inside the string, so this is only an option if you trust the input (i.e. you've saved it yourself).\nIf you need to save data from your program to a file, you might want to use pickle.\n",
"if the sample posted is actual content of your file (which I highly doubt), here is what you could do starting with Python 2.6, docs:\n>>> for line in open(fname):\n print(ast.literal_eval(line)[1])\n\n\nab\neb\nag\n\n",
"You could use eval on each line; this would evaluate the the expression in the line and should yield your expected list, if the formatting is correct.\nA safer solution would be a simple CSV parser. For that your input could look something like this (comma-separated):\n123,321,12,123,321,'asd',ewr,'afdg','et al',213\n\nMaybe this is feasible.\n",
"Maybe You can use eval as suggested, but I'm just curious: Is there any reason not to use JSON as file format?\n",
"You can use the json module:\nimport json\n\nwith open('lists.txt', 'r') as f:\n lines = f.readlines()\n for line in lines:\n line = line.replace(\"'\", '\"')\n l = json.loads(line)\n print l[1]\n\nOutputs:\nab\neb\nag\n\n"
] | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002919865_python.txt |
Q:
Converting human readable date into integer values
I am looking to do something really simple. Merely convert a string, such as 'december' into something I can use with MySQL (such as '12').
At the moment I use a dict,
month_map = {
'december': '12',
'november': '11',
'october': '10',
'september': '09',
'august': '08',
'july': '07',
'june': '06',
'may': '05',
'april': '04',
'march': '03',
'february': '02',
'january': '01'
}
and then month_map.get('december').
Does any function already exist within the standard python modules that can achieve this? Apologies if this has already been asked.. the questions I have found using search seem a little different.
A:
It's locale-dependent, but you can accomplish this with strptime:
>>> import datetime
>>> datetime.datetime.strptime('december', '%B').month
12
>>> datetime.datetime.strptime('january', '%B').month
1
A:
Python dateutil
A:
One thing you could do is:
>>> datetime.datetime.strptime('december', '%B').month
12
'%B' would match full locale name of the month.
A:
In a database you usually have lookup tables mapping the strings to their key values (usually ints, sometimes GUIDs). For months this might not be a big deal because everyone knows what month 5 is, but if you start doing translation in the client side for more odd things, like, say, mapping states to ints then you're doing something wrong.
To be strictly correct, the DB should have this map in a lookup table, and then you should use that to do the translations.
| Converting human readable date into integer values | I am looking to do something really simple. Merely convert a string, such as 'december' into something I can use with MySQL (such as '12').
At the moment I use a dict,
month_map = {
'december': '12',
'november': '11',
'october': '10',
'september': '09',
'august': '08',
'july': '07',
'june': '06',
'may': '05',
'april': '04',
'march': '03',
'february': '02',
'january': '01'
}
and then month_map.get('december').
Does any function already exist within the standard python modules that can achieve this? Apologies if this has already been asked.. the questions I have found using search seem a little different.
| [
"It's locale-dependent, but you can accomplish this with strptime:\n>>> import datetime\n>>> datetime.datetime.strptime('december', '%B').month\n12\n>>> datetime.datetime.strptime('january', '%B').month\n1\n\n",
"Python dateutil\n",
"One thing you could do is:\n>>> datetime.datetime.strptime('december', '%B').month\n12\n\n'%B' would match full locale name of the month.\n",
"In a database you usually have lookup tables mapping the strings to their key values (usually ints, sometimes GUIDs). For months this might not be a big deal because everyone knows what month 5 is, but if you start doing translation in the client side for more odd things, like, say, mapping states to ints then you're doing something wrong. \nTo be strictly correct, the DB should have this map in a lookup table, and then you should use that to do the translations.\n"
] | [
2,
1,
1,
1
] | [] | [] | [
"datetime",
"mysql",
"python"
] | stackoverflow_0002920888_datetime_mysql_python.txt |
Q:
summer experiment: GWT & python for a trading game- arch question
As a summer learning experiment, I'm thinking of coding up a web front end for a trading game i wrote in python, that generates share prices and random snippets of text.
I am sort of struggling with how this should work on the back-end though. I'd rather have my GWT client page interact with the python share price generator, than to try and re-code it in java. I suppose i could use an sqlite db, and then use jdbc to pick up the prices, but i was wondering if there is a better way, for me to be able to poll some python script either from my client page, or from the serverside java code ?
I found this python wrapper, but i'm not sure how i could use it though:
http://code.google.com/apis/visualization/documentation/dev/gviz_api_lib.html
Thanks.
A:
Make no mistake, GWT is a Java technology. You could perhaps interoperate by using Jython to compile your Python code but your UI will basically need to be written in Java (wrappers are second class citizens here). The reason is that the RPC protocol is proprietary and even though GWT is open I believe the compiler that takes the Java source and creates the Javascript (including the RPC calls) isn't.
With Python you might be better off using an RIA Javascript framework like Yahoo UI (YUI), ExtJS, etc. Uki also looks interesting. To give you an example of Uki, here is google Wave layout in 100 lines of Javascript.
A:
I second @cletus' recommendation to go for real javascript plus a JS framework (though as the framework I'd suggest any of jquery, dojo, or google closure -- sorted in order from low to high "formality" -- but I guess that's a question of taste).
If you want a Python-based GWT-like approach, try pyjamas -- but it's not as rich and mature as GWT, so, unless your browser-side needs are really very modest, JS + framework is just a better approach.
A:
Yes you can. Using JSON, you can basically use whatever back-end language you want with GWT. See this page for more detail.
GWT is a powerful tool but nonetheless a complicated one. If you take the time to learn how to use it efficiently, you'll be rocking your way through building you front-end code. You'll also find the Google plugin for Eclipse to be quite a joy.
| summer experiment: GWT & python for a trading game- arch question | As a summer learning experiment, I'm thinking of coding up a web front end for a trading game i wrote in python, that generates share prices and random snippets of text.
I am sort of struggling with how this should work on the back-end though. I'd rather have my GWT client page interact with the python share price generator, than to try and re-code it in java. I suppose i could use an sqlite db, and then use jdbc to pick up the prices, but i was wondering if there is a better way, for me to be able to poll some python script either from my client page, or from the serverside java code ?
I found this python wrapper, but i'm not sure how i could use it though:
http://code.google.com/apis/visualization/documentation/dev/gviz_api_lib.html
Thanks.
| [
"Make no mistake, GWT is a Java technology. You could perhaps interoperate by using Jython to compile your Python code but your UI will basically need to be written in Java (wrappers are second class citizens here). The reason is that the RPC protocol is proprietary and even though GWT is open I believe the compiler that takes the Java source and creates the Javascript (including the RPC calls) isn't.\nWith Python you might be better off using an RIA Javascript framework like Yahoo UI (YUI), ExtJS, etc. Uki also looks interesting. To give you an example of Uki, here is google Wave layout in 100 lines of Javascript.\n",
"I second @cletus' recommendation to go for real javascript plus a JS framework (though as the framework I'd suggest any of jquery, dojo, or google closure -- sorted in order from low to high \"formality\" -- but I guess that's a question of taste).\nIf you want a Python-based GWT-like approach, try pyjamas -- but it's not as rich and mature as GWT, so, unless your browser-side needs are really very modest, JS + framework is just a better approach.\n",
"Yes you can. Using JSON, you can basically use whatever back-end language you want with GWT. See this page for more detail.\nGWT is a powerful tool but nonetheless a complicated one. If you take the time to learn how to use it efficiently, you'll be rocking your way through building you front-end code. You'll also find the Google plugin for Eclipse to be quite a joy.\n"
] | [
0,
0,
0
] | [] | [] | [
"gwt",
"java",
"python"
] | stackoverflow_0002917735_gwt_java_python.txt |
Q:
Python: Copying files with special characters in path
Is there a way in Python 2.5 to copy files which have special chars (Japanese chars, cyrillic letters) in their path?
shutil.copy cannot handle this.
here is some example code:
import copy, os,shutil,sys
fname=os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt"
print fname
print "type of fname: "+str(type(fname))
fname0 = unicode(fname,'mbcs')
print fname0
print "type of fname0: "+str(type(fname0))
fname1 = unicodedata.normalize('NFKD', fname0).encode('cp1251','replace')
print fname1
print "type of fname1: "+str(type(fname1))
fname2 = unicode(fname,'mbcs').encode(sys.stdout.encoding)
print fname2
print "type of fname2: "+str(type(fname2))
shutil.copy(fname2,'C:\\')
the output on a Russian Windows XP
C:\Documents and Settings\└фьшэшёЄЁрЄюЁ\Desktop\testfile.txt
type of fname: <type 'str'>
C:\Documents and Settings\Администратор\Desktop\testfile.txt
type of fname0: <type 'unicode'>
C:\Documents and Settings\└фьшэшёЄЁрЄюЁ\Desktop\testfile.txt
type of fname1: <type 'str'>
C:\Documents and Settings\Администратор\Desktop\testfile.txt
type of fname2: <type 'str'>
Traceback (most recent call last):
File "C:\Test\getuserdir.py", line 23, in <module>
shutil.copy(fname2,'C:\\')
File "C:\Python25\lib\shutil.py", line 80, in copy
copyfile(src, dst)
File "C:\Python25\lib\shutil.py", line 46, in copyfile
fsrc = open(src, 'rb')
IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\\x80\
xa4\xac\xa8\xad\xa8\xe1\xe2\xe0\xa0\xe2\xae\xe0\\Desktop\\testfile.txt'
A:
Try passing unicode arguments to shutil.copy(). That is, shutil.copy( fname0, u'c:\\')
http://docs.python.org/howto/unicode.html#unicode-filenames
http://www.amk.ca/python/howto/unicode#unicode-filenames
http://www.python.org/dev/peps/pep-0277/
A:
As a workaround, you could os.chdir to the unicode-named directory so that shutil does not have to have Unicode arguments: (obviously that won't help you if you have non-ASCII in filenames.)
os.chdir(os.getenv("USERPROFILE")+"\\Desktop\\")
shutil.copy("testfile.txt",'C:\\')
Alternatively, you could copy files the good ole fashioned way.
in_file = open(os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt", "rb")
out_file = open("C:\testfile.txt", "wb")
out_file.write(in_file.read())
in_file.close()
out_file.close()
A third workaround I can think of is using Python 3 instead :)
A:
Solved the problem
The Desktop path in Windows XP is not "C:\Documents and Settings\Администратор\Desktop". It is "C:\Documents and Settings\Администратор\Рабочий стол". And there is now mapping between both.
Since Windows Vista you can call this path with C:\users\Администратор\Desktop however it is called "C:\Пользователь\Администратор\Рабочий стол" in Explorer.
| Python: Copying files with special characters in path | Is there a way in Python 2.5 to copy files which have special chars (Japanese chars, cyrillic letters) in their path?
shutil.copy cannot handle this.
here is some example code:
import copy, os,shutil,sys
fname=os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt"
print fname
print "type of fname: "+str(type(fname))
fname0 = unicode(fname,'mbcs')
print fname0
print "type of fname0: "+str(type(fname0))
fname1 = unicodedata.normalize('NFKD', fname0).encode('cp1251','replace')
print fname1
print "type of fname1: "+str(type(fname1))
fname2 = unicode(fname,'mbcs').encode(sys.stdout.encoding)
print fname2
print "type of fname2: "+str(type(fname2))
shutil.copy(fname2,'C:\\')
the output on a Russian Windows XP
C:\Documents and Settings\└фьшэшёЄЁрЄюЁ\Desktop\testfile.txt
type of fname: <type 'str'>
C:\Documents and Settings\Администратор\Desktop\testfile.txt
type of fname0: <type 'unicode'>
C:\Documents and Settings\└фьшэшёЄЁрЄюЁ\Desktop\testfile.txt
type of fname1: <type 'str'>
C:\Documents and Settings\Администратор\Desktop\testfile.txt
type of fname2: <type 'str'>
Traceback (most recent call last):
File "C:\Test\getuserdir.py", line 23, in <module>
shutil.copy(fname2,'C:\\')
File "C:\Python25\lib\shutil.py", line 80, in copy
copyfile(src, dst)
File "C:\Python25\lib\shutil.py", line 46, in copyfile
fsrc = open(src, 'rb')
IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\\x80\
xa4\xac\xa8\xad\xa8\xe1\xe2\xe0\xa0\xe2\xae\xe0\\Desktop\\testfile.txt'
| [
"Try passing unicode arguments to shutil.copy(). That is, shutil.copy( fname0, u'c:\\\\')\nhttp://docs.python.org/howto/unicode.html#unicode-filenames\nhttp://www.amk.ca/python/howto/unicode#unicode-filenames\nhttp://www.python.org/dev/peps/pep-0277/\n",
"As a workaround, you could os.chdir to the unicode-named directory so that shutil does not have to have Unicode arguments: (obviously that won't help you if you have non-ASCII in filenames.)\nos.chdir(os.getenv(\"USERPROFILE\")+\"\\\\Desktop\\\\\")\nshutil.copy(\"testfile.txt\",'C:\\\\')\n\nAlternatively, you could copy files the good ole fashioned way.\nin_file = open(os.getenv(\"USERPROFILE\")+\"\\\\Desktop\\\\testfile.txt\", \"rb\")\nout_file = open(\"C:\\testfile.txt\", \"wb\")\nout_file.write(in_file.read())\nin_file.close()\nout_file.close()\n\nA third workaround I can think of is using Python 3 instead :)\n",
"Solved the problem\nThe Desktop path in Windows XP is not \"C:\\Documents and Settings\\Администратор\\Desktop\". It is \"C:\\Documents and Settings\\Администратор\\Рабочий стол\". And there is now mapping between both.\nSince Windows Vista you can call this path with C:\\users\\Администратор\\Desktop however it is called \"C:\\Пользователь\\Администратор\\Рабочий стол\" in Explorer.\n"
] | [
2,
0,
0
] | [] | [] | [
"copy",
"file",
"python",
"shutil"
] | stackoverflow_0002919205_copy_file_python_shutil.txt |
Q:
Django context processor gets AnonymousUser
instead of User.
def myview(request):
return render_to_response('tmpl.html', {'user': User.objects.get(id=1})
works fine and passes User to template.
But
def myview(request):
return render_to_response('tmpl.html', {}, context_instance=RequestContext(request))
with a context processor
def user(request):
from django.contrib.auth.models import User
return {'user': User.objects.get(id=1)}
passes AnonymousUser, so I can't get the variables I need :(
What's wrong?
A:
Are you sure that your context processor is enabled in TEMPLATE_CONTEXT_PROCESSORS in settings.py?
More to the point, does it come before or after the built-in django.contrib.auth.context_processors.auth? If it's before, it will be overridden by that processor, which will redefine user as the actual logged-in user, or AnonymousUser if none.
| Django context processor gets AnonymousUser | instead of User.
def myview(request):
return render_to_response('tmpl.html', {'user': User.objects.get(id=1})
works fine and passes User to template.
But
def myview(request):
return render_to_response('tmpl.html', {}, context_instance=RequestContext(request))
with a context processor
def user(request):
from django.contrib.auth.models import User
return {'user': User.objects.get(id=1)}
passes AnonymousUser, so I can't get the variables I need :(
What's wrong?
| [
"Are you sure that your context processor is enabled in TEMPLATE_CONTEXT_PROCESSORS in settings.py?\nMore to the point, does it come before or after the built-in django.contrib.auth.context_processors.auth? If it's before, it will be overridden by that processor, which will redefine user as the actual logged-in user, or AnonymousUser if none.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002921386_django_python.txt |
Q:
Difference between list, sequence and slice in Python?
What are the differences between these built-in Python data types: list, sequence and slice? As I see it, all three essentially represent what C++ and Java call array.
A:
You're mixing very different things in your question, so I'll just answer a different question
You are now asking about one of the most important interface in Python: iterable - it's basically anything you can use like for elem in iterable.
iterable has three descendants: sequence, generator and mapping.
A sequence is a iterable with random access. You can ask for any item of the sequence without having to consume the items before it. With this property you can build slices, which give you more than one element at once. A slice can give you a subsequence: seq[from:until] and every nth item: seq[from:until:nth]. list, tuple and str all are sequences.
If the access is done via keys instead of integer positions, you have a mapping. dict is the basic mapping.
The most basic iterable is a generator. It supports no random access and therefore no slicing. You have to consume all items in the order they are given. Generator typically only create their items when you iterate over them. The common way to create generators are generator expressions. They look exactly like list comprehension, except with round brackets, for example (f(x) for x in y). Calling a function that uses the yield keyword returns a generator too.
The common adapter to all iterables is the iterator. iterators have the same interface as the most basic type they support, a generator. They are created explicitly by calling iter on a iterable and are used implicitly in all kinds of looping constructs.
A:
list are more than plain arrays. You can initialize them without giving the number of items. You can append/push to them, you can remove/pop/del items from them, you can have lists of different types of objects (e.g., [1,'e', [3]]), you can have recursive lists... and you can slice lists, which means getting a new list with only a few of the items.
slice are an object type used "behind the scenes" to handle extended slicing in the a[start:stop:step] form, as help(slice) reveals.
"Sequence" is not an object, more like an informal interface some objects like list implement.
A:
lists are a sequence type, similar to an array
sequence types describe a functional superset:
There are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects.
slices are a notation for subarrays (or substrings, also)
Read more ... http://docs.python.org/glossary.html
A:
A list is a sequence but a sequence is not necessarily a list. A sequence is any type that supports the sequence interface ("protocol"). This is done by duck-typing rather than through a strict inheritance hierarchy. Note that sequences are containers, but containers are not necessarily sequences. (sequences are, well, sequential!)
See http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange
Slice objects are generally created implicitly via syntactic sugar (foo[2:5]) and provided to the container type special methods (such as __getitem__) which you can override. You will generally not have to deal with slices unless if you create your own sequences/containers.
See http://docs.python.org/reference/datamodel.html#specialnames
Lists are comparable to arrays. I'm not certain, but I think it's implemented in cPython as a dynamically expanding array. However, the interface makes it so that it's more like a C++ STL Vector than just a plain old array.
A:
Strictly speaking, a slice is a type which represents a range of indices, e.g. a start, stop, and a step. A slice isn't a container type at all. You can use a slice to index an list, resulting in a new list which is a copy of a sublist of the original list.
Lists differ from C++ arrays in that they're heterogenous; the elements are not required to be of the same type. And as MYYN has already pointed out, "sequence" isn't a Python type at all but rather a description of a variety of built-in types.
| Difference between list, sequence and slice in Python? | What are the differences between these built-in Python data types: list, sequence and slice? As I see it, all three essentially represent what C++ and Java call array.
| [
"You're mixing very different things in your question, so I'll just answer a different question\nYou are now asking about one of the most important interface in Python: iterable - it's basically anything you can use like for elem in iterable.\niterable has three descendants: sequence, generator and mapping.\n\nA sequence is a iterable with random access. You can ask for any item of the sequence without having to consume the items before it. With this property you can build slices, which give you more than one element at once. A slice can give you a subsequence: seq[from:until] and every nth item: seq[from:until:nth]. list, tuple and str all are sequences.\n\nIf the access is done via keys instead of integer positions, you have a mapping. dict is the basic mapping.\n\nThe most basic iterable is a generator. It supports no random access and therefore no slicing. You have to consume all items in the order they are given. Generator typically only create their items when you iterate over them. The common way to create generators are generator expressions. They look exactly like list comprehension, except with round brackets, for example (f(x) for x in y). Calling a function that uses the yield keyword returns a generator too.\n\n\nThe common adapter to all iterables is the iterator. iterators have the same interface as the most basic type they support, a generator. They are created explicitly by calling iter on a iterable and are used implicitly in all kinds of looping constructs.\n",
"\nlist are more than plain arrays. You can initialize them without giving the number of items. You can append/push to them, you can remove/pop/del items from them, you can have lists of different types of objects (e.g., [1,'e', [3]]), you can have recursive lists... and you can slice lists, which means getting a new list with only a few of the items.\nslice are an object type used \"behind the scenes\" to handle extended slicing in the a[start:stop:step] form, as help(slice) reveals.\n\n\"Sequence\" is not an object, more like an informal interface some objects like list implement.\n",
"\nlists are a sequence type, similar to an array\nsequence types describe a functional superset: \n\n\nThere are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects.\n\n\nslices are a notation for subarrays (or substrings, also)\n\n\nRead more ... http://docs.python.org/glossary.html\n",
"A list is a sequence but a sequence is not necessarily a list. A sequence is any type that supports the sequence interface (\"protocol\"). This is done by duck-typing rather than through a strict inheritance hierarchy. Note that sequences are containers, but containers are not necessarily sequences. (sequences are, well, sequential!)\nSee http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange\nSlice objects are generally created implicitly via syntactic sugar (foo[2:5]) and provided to the container type special methods (such as __getitem__) which you can override. You will generally not have to deal with slices unless if you create your own sequences/containers.\nSee http://docs.python.org/reference/datamodel.html#specialnames\nLists are comparable to arrays. I'm not certain, but I think it's implemented in cPython as a dynamically expanding array. However, the interface makes it so that it's more like a C++ STL Vector than just a plain old array.\n",
"Strictly speaking, a slice is a type which represents a range of indices, e.g. a start, stop, and a step. A slice isn't a container type at all. You can use a slice to index an list, resulting in a new list which is a copy of a sublist of the original list.\nLists differ from C++ arrays in that they're heterogenous; the elements are not required to be of the same type. And as MYYN has already pointed out, \"sequence\" isn't a Python type at all but rather a description of a variety of built-in types.\n"
] | [
81,
17,
9,
9,
2
] | [] | [] | [
"definition",
"list",
"python",
"sequence",
"slice"
] | stackoverflow_0002920619_definition_list_python_sequence_slice.txt |
Q:
Fast matrix transposition in Python
Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).?
Say, if I have an array
X=[ [1,2,3],
[4,5,6] ]
I need an array Y which should be a transposed version of X, so
Y=[ [1,4],
[2,5],
[3,6] ]
A:
Simple: Y=zip(*X)
>>> X=[[1,2,3], [4,5,6]]
>>> Y=zip(*X)
>>> Y
[(1, 4), (2, 5), (3, 6)]
EDIT: to answer questions in the comments about what does zip(*X) mean, here is an example from python manual:
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
So, when X is [[1,2,3], [4,5,6]], zip(*X) is zip([1,2,3], [4,5,6])
A:
>>> X = [1,2,3], [4,5,6]]
>>> zip(*X)
[(1,4), (2,5), (3,6)]
>>> [list(tup) for tup in zip(*X)]
[[1,4], [2,5], [3,6]]
If the inner pairs absolutely need to be lists, go with the second.
A:
If you're working with matrices, you should almost certainly be using numpy. This will perform numerical operations easier and more efficiently than pure Python code.
>>> x = [[1,2,3], [4,5,6]]
>>> x = numpy.array(x)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> x.T
array([[1, 4],
[2, 5],
[3, 6]])
"non-involving any library import" is a silly, non-productive requirement.
| Fast matrix transposition in Python | Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).?
Say, if I have an array
X=[ [1,2,3],
[4,5,6] ]
I need an array Y which should be a transposed version of X, so
Y=[ [1,4],
[2,5],
[3,6] ]
| [
"Simple: Y=zip(*X)\n>>> X=[[1,2,3], [4,5,6]]\n>>> Y=zip(*X)\n>>> Y\n[(1, 4), (2, 5), (3, 6)]\n\nEDIT: to answer questions in the comments about what does zip(*X) mean, here is an example from python manual:\n>>> range(3, 6) # normal call with separate arguments\n[3, 4, 5]\n>>> args = [3, 6]\n>>> range(*args) # call with arguments unpacked from a list\n[3, 4, 5]\n\nSo, when X is [[1,2,3], [4,5,6]], zip(*X) is zip([1,2,3], [4,5,6])\n",
">>> X = [1,2,3], [4,5,6]]\n>>> zip(*X)\n[(1,4), (2,5), (3,6)]\n>>> [list(tup) for tup in zip(*X)]\n[[1,4], [2,5], [3,6]]\n\nIf the inner pairs absolutely need to be lists, go with the second.\n",
"If you're working with matrices, you should almost certainly be using numpy. This will perform numerical operations easier and more efficiently than pure Python code. \n>>> x = [[1,2,3], [4,5,6]]\n>>> x = numpy.array(x)\n>>> x\narray([[1, 2, 3],\n [4, 5, 6]])\n>>> x.T\narray([[1, 4],\n [2, 5],\n [3, 6]])\n\n\"non-involving any library import\" is a silly, non-productive requirement.\n"
] | [
20,
6,
5
] | [] | [] | [
"algorithm",
"matrix",
"python"
] | stackoverflow_0002921681_algorithm_matrix_python.txt |
Q:
What is faster when looking in lists of strings? "In" or "index"?
I have a bunch of lists of strings and I need to know if an string is in any of them so I have to look for the string in the first list, if not found, in the second, if not found, in the third... and so on.
My question is: What is faster?
if (string in stringList1):
return True
else:
if (string in stringList2):
return True
# ... #
and so on or using the index() function inside a try / except block?
try:
return stringList1.index(string) >= 0
except:
try:
return stringList2.index(string) >= 0
except:
# ... #
I know the "in" is linear and that usually the python recommendations are "better say sorry than ask for permission" (meaning the second approach would be better) but I'd like to know the opinion of someone more qualified :)
Thank you!
A:
in is the correct way to determine whether something is or is not in a container. Don't worry about speed microoptimization until you have tested your app, found it to be slow, profiled, and found what's causing it. At that point, optimize by testing (the timeit module can be good for this), not by taking the words of internet weirdos.
If you are doing lots of containment checks you probably want to use a set instead of a sequence; sets have O(1) lookup. If this is not suitable to your problem, you might want to use a list and the bisect module, which still offers algorithmic performance benefits over the O(n) sequence operations.
There's a chance what you really mean if any(string in s for s in iterable_of_string_lists) or if string in string_list_1 or string in string_list_2. Nesting ifs is not quite the nicest way to do an operation like you show.
Never ever ever use a bare except:. Always catch a specific exception, in this case except ValueError. Using except: will catch and ignore all kinds of exceptions you don't intend, like a KeyboardInterrupt if the user tries to exit your app or a NameError if you have a typo.
| What is faster when looking in lists of strings? "In" or "index"? | I have a bunch of lists of strings and I need to know if an string is in any of them so I have to look for the string in the first list, if not found, in the second, if not found, in the third... and so on.
My question is: What is faster?
if (string in stringList1):
return True
else:
if (string in stringList2):
return True
# ... #
and so on or using the index() function inside a try / except block?
try:
return stringList1.index(string) >= 0
except:
try:
return stringList2.index(string) >= 0
except:
# ... #
I know the "in" is linear and that usually the python recommendations are "better say sorry than ask for permission" (meaning the second approach would be better) but I'd like to know the opinion of someone more qualified :)
Thank you!
| [
"\nin is the correct way to determine whether something is or is not in a container. Don't worry about speed microoptimization until you have tested your app, found it to be slow, profiled, and found what's causing it. At that point, optimize by testing (the timeit module can be good for this), not by taking the words of internet weirdos.\nIf you are doing lots of containment checks you probably want to use a set instead of a sequence; sets have O(1) lookup. If this is not suitable to your problem, you might want to use a list and the bisect module, which still offers algorithmic performance benefits over the O(n) sequence operations.\nThere's a chance what you really mean if any(string in s for s in iterable_of_string_lists) or if string in string_list_1 or string in string_list_2. Nesting ifs is not quite the nicest way to do an operation like you show.\nNever ever ever use a bare except:. Always catch a specific exception, in this case except ValueError. Using except: will catch and ignore all kinds of exceptions you don't intend, like a KeyboardInterrupt if the user tries to exit your app or a NameError if you have a typo.\n\n"
] | [
12
] | [] | [] | [
"list",
"performance",
"python",
"search",
"string"
] | stackoverflow_0002922072_list_performance_python_search_string.txt |
Q:
Simple numpy question
I can't get this snippet to work:
#base code
A = array([ [ 1, 2, 10 ],
[ 1, 3, 20 ],
[ 1, 4, 30 ],
[ 2, 1, 15 ],
[ 2, 3, 25 ],
[ 2, 4, 35 ],
[ 3, 1, 17 ],
[ 3, 2, 27 ],
[ 3, 4, 37 ],
[ 4, 1, 13 ],
[ 4, 2, 23 ],
[ 4, 3, 33 ] ])
# Number of zones
zones = unique1d(A[:,0])
for origin in zones:
for destination in zones:
if origin != destination:
A_ik = A[(A[:,0] == origin & A[:,1] == destination), 2]
A:
I'm practicing my Psychic debugging...
Your are missing parentheses in the last line:
A_ik = A[(A[:,0] == origin) & (A[:,1] == destination), 2]
should work.
A:
Try replacing the logical AND operator & (which is a bitwise AND) by &&?
| Simple numpy question | I can't get this snippet to work:
#base code
A = array([ [ 1, 2, 10 ],
[ 1, 3, 20 ],
[ 1, 4, 30 ],
[ 2, 1, 15 ],
[ 2, 3, 25 ],
[ 2, 4, 35 ],
[ 3, 1, 17 ],
[ 3, 2, 27 ],
[ 3, 4, 37 ],
[ 4, 1, 13 ],
[ 4, 2, 23 ],
[ 4, 3, 33 ] ])
# Number of zones
zones = unique1d(A[:,0])
for origin in zones:
for destination in zones:
if origin != destination:
A_ik = A[(A[:,0] == origin & A[:,1] == destination), 2]
| [
"I'm practicing my Psychic debugging...\nYour are missing parentheses in the last line:\nA_ik = A[(A[:,0] == origin) & (A[:,1] == destination), 2]\n\nshould work.\n",
"Try replacing the logical AND operator & (which is a bitwise AND) by &&?\n"
] | [
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002922123_numpy_python.txt |
Q:
Program structure in long running data processing python script
For my current job I am writing some long-running (think hours to days) scripts that do CPU intensive data-processing. The program flow is very simple - it proceeds into the main loop, completes the main loop, saves output and terminates: The basic structure of my programs tends to be like so:
<import statements>
<constant declarations>
<misc function declarations>
def main():
for blah in blahs():
<lots of local variables>
<lots of tightly coupled computation>
for something in somethings():
<lots more local variables>
<lots more computation>
<etc., etc.>
<save results>
if __name__ == "__main__":
main()
This gets unmanageable quickly, so I want to refactor it into something more manageable. I want to make this more maintainable, without sacrificing execution speed.
Each chuck of code relies on a large number of variables however, so refactoring parts of the computation out to functions would make parameters list grow out of hand very quickly. Should I put this sort of code into a python class, and change the local variables into class variables? It doesn't make a great deal of sense tp me conceptually to turn the program into a class, as the class would never be reused, and only one instance would ever be created per instance.
What is the best practice structure for this kind of program? I am using python but the question is relatively language-agnostic, assuming a modern object-oriented language features.
A:
First off, if your program is going to be running for hours/days then the overhead of switching to using classes/methods instead of putting everything in a giant main is pretty much non-existent.
Additionally, refactoring (even if it does involve passing a lot of variables) should help you improve speed in the long run. Profiling an application which is designed well is much easier because you can pin-point the slow parts and optimize there. Maybe a new library comes along that's highly optimized for your calculations... a well designed program will let you plug it in and test right away. Or perhaps you decide to write a C Module extension to improve the speed of a subset of your calculations, a well designed application will make that easy too.
It's hard to give concrete advice without seeing <lots of tightly coupled computation> and <lots more computation>. But, I would start with making every for block it's own method and go from there.
A:
Not too clean, but works well in little projects...
You can start using modules as if they were singleton instances, and create real classes only when you feel the complexity of the module or the computation justifies them.
If you do that, you would want to use "import module" and not "from module import stuff" -- it's cleaner and will work better if "stuff" can be reassigned. Besides, it's recommended in the Google guidelines.
A:
Using a class (or classes) can help you organize your code.
Simplicity of form (such as through use of class attributes and methods) is important because it helps you see your algorithm, and can help you more easily unit test the parts.
IMO, these benefits far outweigh the slight loss of speed that may come with using OOP.
| Program structure in long running data processing python script | For my current job I am writing some long-running (think hours to days) scripts that do CPU intensive data-processing. The program flow is very simple - it proceeds into the main loop, completes the main loop, saves output and terminates: The basic structure of my programs tends to be like so:
<import statements>
<constant declarations>
<misc function declarations>
def main():
for blah in blahs():
<lots of local variables>
<lots of tightly coupled computation>
for something in somethings():
<lots more local variables>
<lots more computation>
<etc., etc.>
<save results>
if __name__ == "__main__":
main()
This gets unmanageable quickly, so I want to refactor it into something more manageable. I want to make this more maintainable, without sacrificing execution speed.
Each chuck of code relies on a large number of variables however, so refactoring parts of the computation out to functions would make parameters list grow out of hand very quickly. Should I put this sort of code into a python class, and change the local variables into class variables? It doesn't make a great deal of sense tp me conceptually to turn the program into a class, as the class would never be reused, and only one instance would ever be created per instance.
What is the best practice structure for this kind of program? I am using python but the question is relatively language-agnostic, assuming a modern object-oriented language features.
| [
"First off, if your program is going to be running for hours/days then the overhead of switching to using classes/methods instead of putting everything in a giant main is pretty much non-existent. \nAdditionally, refactoring (even if it does involve passing a lot of variables) should help you improve speed in the long run. Profiling an application which is designed well is much easier because you can pin-point the slow parts and optimize there. Maybe a new library comes along that's highly optimized for your calculations... a well designed program will let you plug it in and test right away. Or perhaps you decide to write a C Module extension to improve the speed of a subset of your calculations, a well designed application will make that easy too. \nIt's hard to give concrete advice without seeing <lots of tightly coupled computation> and <lots more computation>. But, I would start with making every for block it's own method and go from there. \n",
"Not too clean, but works well in little projects...\nYou can start using modules as if they were singleton instances, and create real classes only when you feel the complexity of the module or the computation justifies them.\nIf you do that, you would want to use \"import module\" and not \"from module import stuff\" -- it's cleaner and will work better if \"stuff\" can be reassigned. Besides, it's recommended in the Google guidelines.\n",
"Using a class (or classes) can help you organize your code.\nSimplicity of form (such as through use of class attributes and methods) is important because it helps you see your algorithm, and can help you more easily unit test the parts.\nIMO, these benefits far outweigh the slight loss of speed that may come with using OOP.\n"
] | [
2,
2,
1
] | [] | [] | [
"language_agnostic",
"maintainability",
"python",
"refactoring"
] | stackoverflow_0002921368_language_agnostic_maintainability_python_refactoring.txt |
Q:
php/Symfony View Component analog in python/Django
Symfony has very useful feature - view component, this is small action code and template that you could embed anywhere inside view template:
<?php include_component('news') ?>
for example in above code mews component executes query in db and display results as block on a site page.
http://www.symfony-project.org/book/1_0/07-Inside-the-View-Layer#Components
I need something similar for Django to prepare and display login form in each view template.
We can call this a "widget" probably.
A:
I think you're looking for Django's template tags feature. Template tags can make database calls, render partial templates, or do pretty much anything else you need them to do. Your example, as a template tag, might look something like this in your templates:
{% include_component 'news' %}
| php/Symfony View Component analog in python/Django | Symfony has very useful feature - view component, this is small action code and template that you could embed anywhere inside view template:
<?php include_component('news') ?>
for example in above code mews component executes query in db and display results as block on a site page.
http://www.symfony-project.org/book/1_0/07-Inside-the-View-Layer#Components
I need something similar for Django to prepare and display login form in each view template.
We can call this a "widget" probably.
| [
"I think you're looking for Django's template tags feature. Template tags can make database calls, render partial templates, or do pretty much anything else you need them to do. Your example, as a template tag, might look something like this in your templates:\n{% include_component 'news' %}\n\n"
] | [
3
] | [] | [] | [
"django",
"python",
"symfony1"
] | stackoverflow_0002922145_django_python_symfony1.txt |
Q:
Framework Similar to Pylons for Ruby
I've been using Python for most of my web projects lately, and have come to really love the Pylons MVC framework. I like the incredible transparency (lack of magic), the built-in components they selected (sqlalchemy, formencode, routes), and the ability to easily change things up (use a different ORM or templating engine).
Moving forward, due to constraints at my company, I'm going to be trying out Ruby rather than Python. I'm wondering if people with experience in both have any recommendations for a Ruby framework that is comparable to Pylons.
Python is to Django as Ruby is to Rails
Python is to Pylons as Ruby is to ?
A:
I have no experience with pylons so its tough for me to compare, but if you are looking for a lightweight alternative to Rails, definitely check out Sinatra. However, keep in mind its not an MVC framework.
Ramaze is another alternative which is ORM and templating engine agnostic.
A:
Python is to Django as Ruby is to Rails
Python is to Pylons as Ruby is to Merb, is my best guess.
But since Merb and Rails are converging in the almost-released Rails 3.0 (at Beta 3 right now) - the lead developer for Merb now performs the same role in the united product, I'd suggest that
Python is to Pylons as Ruby is to Rails 3.0
YMMV, of course.
A:
Honestly I am not sure how it compares to Pylons, but if you appreciate simplicity and transparency, you will definitely like Sinatra. And if you decide to give it a try, I would also recommend you Monk if you're already used to an MVC framework.
| Framework Similar to Pylons for Ruby | I've been using Python for most of my web projects lately, and have come to really love the Pylons MVC framework. I like the incredible transparency (lack of magic), the built-in components they selected (sqlalchemy, formencode, routes), and the ability to easily change things up (use a different ORM or templating engine).
Moving forward, due to constraints at my company, I'm going to be trying out Ruby rather than Python. I'm wondering if people with experience in both have any recommendations for a Ruby framework that is comparable to Pylons.
Python is to Django as Ruby is to Rails
Python is to Pylons as Ruby is to ?
| [
"I have no experience with pylons so its tough for me to compare, but if you are looking for a lightweight alternative to Rails, definitely check out Sinatra. However, keep in mind its not an MVC framework.\nRamaze is another alternative which is ORM and templating engine agnostic.\n",
"Python is to Django as Ruby is to Rails\nPython is to Pylons as Ruby is to Merb, is my best guess.\nBut since Merb and Rails are converging in the almost-released Rails 3.0 (at Beta 3 right now) - the lead developer for Merb now performs the same role in the united product, I'd suggest that\nPython is to Pylons as Ruby is to Rails 3.0\nYMMV, of course.\n",
"Honestly I am not sure how it compares to Pylons, but if you appreciate simplicity and transparency, you will definitely like Sinatra. And if you decide to give it a try, I would also recommend you Monk if you're already used to an MVC framework.\n"
] | [
5,
0,
0
] | [] | [] | [
"frameworks",
"model_view_controller",
"pylons",
"python",
"ruby"
] | stackoverflow_0002916693_frameworks_model_view_controller_pylons_python_ruby.txt |
Q:
How to make form validation in Django dynamic?
I'm trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form.
Basically, when a user wants to create a new domain, this form should fail if the entered domain exists.
When a user wants to move a domain, this form should fail if the entered domain doesn't exist.
I've tried making it dynamic overload the initbut couldn't see a way to get my passed variabele to the clean function.
I've read that this dynamic validation can be accomplished using a factory method, but maybe someone can help me on my way with this?
Here's a simplified version of the form so far:
#OrderFormStep1 presents the user with a choice: create or move domain
class OrderFormStep2(forms.Form):
domain = forms.CharField()
extension = forms.CharField()
def clean(self):
cleaned_data = self.cleaned_data
domain = cleaned_data.get("domain")
extension = cleaned_data.get("extension")
if domain and extension:
code = whoislookup(domain+extension);
#Raise error based on result from OrderFormStep1
#raise forms.ValidationError('error, domain already exists')
#raise forms.ValidationError('error, domain does not exist')
return cleaned_data
A:
Overriding the __init__ is the way to go. In that method, you can simply set your value to an instance variable.
def __init__(self, *args, **kwargs):
self.myvalue = kwargs.pop('myvalue')
super(MyForm, self).__init__(*args, **kwargs)
Now self.myvalue is available in any form method.
A:
Do you have a model that stores the domains? If so, you want to use a ModelForm and set unique=True on whichever field stores the actual domain in the model. As of Django 1.2, you can even do any additional validation inside the model, rather than the form.
| How to make form validation in Django dynamic? | I'm trying to make a form that handles the checking of a domain: the form should fail based on a variable that was set earlier in another form.
Basically, when a user wants to create a new domain, this form should fail if the entered domain exists.
When a user wants to move a domain, this form should fail if the entered domain doesn't exist.
I've tried making it dynamic overload the initbut couldn't see a way to get my passed variabele to the clean function.
I've read that this dynamic validation can be accomplished using a factory method, but maybe someone can help me on my way with this?
Here's a simplified version of the form so far:
#OrderFormStep1 presents the user with a choice: create or move domain
class OrderFormStep2(forms.Form):
domain = forms.CharField()
extension = forms.CharField()
def clean(self):
cleaned_data = self.cleaned_data
domain = cleaned_data.get("domain")
extension = cleaned_data.get("extension")
if domain and extension:
code = whoislookup(domain+extension);
#Raise error based on result from OrderFormStep1
#raise forms.ValidationError('error, domain already exists')
#raise forms.ValidationError('error, domain does not exist')
return cleaned_data
| [
"Overriding the __init__ is the way to go. In that method, you can simply set your value to an instance variable.\ndef __init__(self, *args, **kwargs):\n self.myvalue = kwargs.pop('myvalue')\n super(MyForm, self).__init__(*args, **kwargs)\n\nNow self.myvalue is available in any form method.\n",
"Do you have a model that stores the domains? If so, you want to use a ModelForm and set unique=True on whichever field stores the actual domain in the model. As of Django 1.2, you can even do any additional validation inside the model, rather than the form.\n"
] | [
1,
0
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0002922230_django_forms_python.txt |
Q:
Execute a BASH command in Python-- in the same process
I need to execute the command . /home/db2v95/sqllib/db2profile before I can import ibm_db_dbi in Python 2.6.
Executing it before I enter Python works:
baldurb@gigur:~$ . /home/db2v95/sqllib/db2profile
baldurb@gigur:~$ python
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ibm_db_dbi
>>>
but executing it in Python using os.system(". /home/db2v95/sqllib/db2profile") or subprocess.Popen([". /home/db2v95/sqllib/db2profile"]) results in an error. What am I doing wrong?
Edit: this is the error I receive:
> Traceback (most recent call last):
> File "<file>.py", line 8, in
> <module>
> subprocess.Popen([". /home/db2v95/sqllib/db2profile"])
> File
> "/usr/lib/python2.6/subprocess.py",
> line 621, in __init__
> errread, errwrite) File "/usr/lib/python2.6/subprocess.py",
> line 1126, in _execute_child
> raise child_exception OSError: [Errno 2] No such file or directory
A:
You are calling a '.' shell command. This command means 'execute this shell file in current process'. You cannot execute shell file in Python process as Python is not a shell script interpreter.
The /home/b2v95/sqllib/db2profile probably sets some shell environment variables. If you read it using system() function, then the variables will be only changed in the shell executed and will not be visible in the process calling that shell (your script).
You can only load this file before starting your python script – you could make a shell wrapper script which would do . /home/b2v95/sqllib/db2profile and execute your python script.
Other way would be to see what the db2profile contains. If that are only NAME=value lines, you could parse it in your python script and update os.environ with the data obtained. If script does something more (like calling something else to obtain the values) you can reimplement whole script in Python.
Update An idea: read the script into python, pipe it (using Popen) to the shell, after the script write env command to the same shell and read the output. This way you will get all the variables defined in the shell. Now you can read the variables.
Something like this:
shell = subprocess.Popen(["sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
script = open("/home/db2v95/sqllib/db2profile", "r").read()
shell.stdin.write(script + "\n")
shell.stdin.write("env\n")
shell.stdin.close()
for line in shell.stdout:
name, value = line.strip().split("=", 1)
os.environ[name] = value
A:
Not sure what OS you are working on and what DB2 version you are using. The newer versions (at least 9.5 and above, not sure about 9.0 or 9.1) work by setting db2clp to **$$**. Since the DB2 usually is a LUW it might work under linux/unix too. However, under AIX I need to run the profile script to connect to the right DB instance. Haven't checked too much into what that script does.
| Execute a BASH command in Python-- in the same process | I need to execute the command . /home/db2v95/sqllib/db2profile before I can import ibm_db_dbi in Python 2.6.
Executing it before I enter Python works:
baldurb@gigur:~$ . /home/db2v95/sqllib/db2profile
baldurb@gigur:~$ python
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ibm_db_dbi
>>>
but executing it in Python using os.system(". /home/db2v95/sqllib/db2profile") or subprocess.Popen([". /home/db2v95/sqllib/db2profile"]) results in an error. What am I doing wrong?
Edit: this is the error I receive:
> Traceback (most recent call last):
> File "<file>.py", line 8, in
> <module>
> subprocess.Popen([". /home/db2v95/sqllib/db2profile"])
> File
> "/usr/lib/python2.6/subprocess.py",
> line 621, in __init__
> errread, errwrite) File "/usr/lib/python2.6/subprocess.py",
> line 1126, in _execute_child
> raise child_exception OSError: [Errno 2] No such file or directory
| [
"You are calling a '.' shell command. This command means 'execute this shell file in current process'. You cannot execute shell file in Python process as Python is not a shell script interpreter.\nThe /home/b2v95/sqllib/db2profile probably sets some shell environment variables. If you read it using system() function, then the variables will be only changed in the shell executed and will not be visible in the process calling that shell (your script).\nYou can only load this file before starting your python script – you could make a shell wrapper script which would do . /home/b2v95/sqllib/db2profile and execute your python script.\nOther way would be to see what the db2profile contains. If that are only NAME=value lines, you could parse it in your python script and update os.environ with the data obtained. If script does something more (like calling something else to obtain the values) you can reimplement whole script in Python.\nUpdate An idea: read the script into python, pipe it (using Popen) to the shell, after the script write env command to the same shell and read the output. This way you will get all the variables defined in the shell. Now you can read the variables.\nSomething like this:\nshell = subprocess.Popen([\"sh\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\nscript = open(\"/home/db2v95/sqllib/db2profile\", \"r\").read()\nshell.stdin.write(script + \"\\n\")\nshell.stdin.write(\"env\\n\")\nshell.stdin.close()\nfor line in shell.stdout:\n name, value = line.strip().split(\"=\", 1)\n os.environ[name] = value\n\n",
"Not sure what OS you are working on and what DB2 version you are using. The newer versions (at least 9.5 and above, not sure about 9.0 or 9.1) work by setting db2clp to **$$**. Since the DB2 usually is a LUW it might work under linux/unix too. However, under AIX I need to run the profile script to connect to the right DB instance. Haven't checked too much into what that script does.\n"
] | [
10,
0
] | [
"Maybe os.popen is what you're looking for (better yet, one of the popen[2-4] variants)? Example:\nimport os\np = os.popen(\". /home/b2v95/sqllib/db2profile\")\np.close() # this will wait for the command to finish\nimport ibm_db_dbi\n\n\nEdit: I see that your error says No such file or directory. Try running it without the dot, like so:\nos.popen(\"/home/b2v95/sqllib/db2profile\")\n\nIf this doesn't work, it might have something to do with your environment. Maybe you're running Python jailed/chrooted?\n",
"you need to do:\nsubprocess.Popen(['.', '/home/db2v95/sqllib/db2profile'], shell=True)\n\n"
] | [
-1,
-1
] | [
"bash",
"db2",
"python",
"subprocess"
] | stackoverflow_0002858920_bash_db2_python_subprocess.txt |
Q:
Python : Convert from C-Char to Int
I have a string read in from a binary file that is unpacked using struct.unpack as a string of length n.
Each byte in the string is a single integer (1-byte) representing 0-255. So for each character in the string I want to convert it to an integer.
I can't figure out how to do this. Using ord doesn't seem to be on the right track...
A:
>>> import struct
>>> a = struct.pack("ccc", "a", "b", "c")
>>> a
b'abc'
>>> b = struct.unpack("ccc", a)
>>> b
(b'a', b'b', b'c')
>>> ord(b[0])
97
>>> c = struct.pack("BBB", 1, 2, 3)
>>> c
b'\x01\x02\x03'
>>> d = struct.unpack("BBB", c)
>>> d
(1, 2, 3)
Works for me.
| Python : Convert from C-Char to Int | I have a string read in from a binary file that is unpacked using struct.unpack as a string of length n.
Each byte in the string is a single integer (1-byte) representing 0-255. So for each character in the string I want to convert it to an integer.
I can't figure out how to do this. Using ord doesn't seem to be on the right track...
| [
">>> import struct\n>>> a = struct.pack(\"ccc\", \"a\", \"b\", \"c\")\n>>> a\nb'abc'\n>>> b = struct.unpack(\"ccc\", a)\n>>> b\n(b'a', b'b', b'c')\n>>> ord(b[0])\n97\n>>> c = struct.pack(\"BBB\", 1, 2, 3)\n>>> c\nb'\\x01\\x02\\x03'\n>>> d = struct.unpack(\"BBB\", c)\n>>> d\n(1, 2, 3)\n\nWorks for me.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0002922461_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.