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 would I make a simple URL extracter in Python?
How would I start on a single web page, let's say at the root of DMOZ.org and index every single url attached to it. Then store those links inside a text file. I don't want the content, just the links themselves. An example would be awesome.
A:
This, for instance, would print out links on this very related (but poorly named) question:
import urllib2
from BeautifulSoup import BeautifulSoup
q = urllib2.urlopen('https://stackoverflow.com/questions/3884419/')
soup = BeautifulSoup(q.read())
for link in soup.findAll('a'):
if link.has_key('href'):
print str(link.string) + " -> " + link['href']
elif link.has_key('id'):
print "ID: " + link['id']
else:
print "???"
Output:
Stack Exchange -> http://stackexchange.com
log in -> /users/login?returnurl=%2fquestions%2f3884419%2f
careers -> http://careers.stackoverflow.com
meta -> http://meta.stackoverflow.com
...
ID: flag-post-3884419
None -> /posts/3884419/revisions
...
A:
If you insist on reinventing the wheel, use an html parser like BeautifulSoup to grab all the tags out. This answer to a similar question is relevant.
A:
Scrapy is a Python framework for web crawling. Plenty of examples here: http://snippets.scrapy.org/popular/bookmarked/
| How would I make a simple URL extracter in Python? | How would I start on a single web page, let's say at the root of DMOZ.org and index every single url attached to it. Then store those links inside a text file. I don't want the content, just the links themselves. An example would be awesome.
| [
"This, for instance, would print out links on this very related (but poorly named) question:\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nq = urllib2.urlopen('https://stackoverflow.com/questions/3884419/')\nsoup = BeautifulSoup(q.read())\n\nfor link in soup.findAll('a'):\n if link.has_key('href'):... | [
2,
0,
0
] | [] | [] | [
"hyperlink",
"python",
"web_crawler"
] | stackoverflow_0003925585_hyperlink_python_web_crawler.txt |
Q:
Python: how can I initialize my empty objects?
how can initialize empty objects in python ?
I need to initialize my class members (for examples tk.frames, vtk visualizations etc)
thanks
A:
Access the attributes of self in your __init__() method.
class C(object):
def __init__(self, val):
self.val = val
| Python: how can I initialize my empty objects? | how can initialize empty objects in python ?
I need to initialize my class members (for examples tk.frames, vtk visualizations etc)
thanks
| [
"Access the attributes of self in your __init__() method.\nclass C(object):\n def __init__(self, val):\n self.val = val\n\n"
] | [
4
] | [] | [] | [
"initialization",
"member",
"object",
"python"
] | stackoverflow_0003931481_initialization_member_object_python.txt |
Q:
compare two windows paths, one containing tilde, in python
I'm trying to use the TMP environment variable in a program. When I ask for
tmp = os.path.expandvars("$TMP")
I get
C:\Users\STEVE~1.COO\AppData\Local\Temp
Which contains the old-school, tilde form. A function I have no control over returns paths like
C:\Users\steve.cooper\AppData\Local\Temp\file.txt
My problem is this; I'd like to check if the file is in my temp drive, but I can't find a way to compare them. How do you tell if these two Windows directories;
C:\Users\STEVE~1.COO\AppData\Local\Temp
C:\Users\steve.cooper\AppData\Local\Temp
are the same?
A:
Here is alternative solution using only ctypes from Standard Python Library.
tmp = unicode(os.path.expandvars("$TMP"))
import ctypes
GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
buffer = ctypes.create_unicode_buffer(GetLongPathName(tmp, 0, 0))
GetLongPathName(tmp, buffer, len(buffer))
print buffer.value
A:
You will need the python win32 extensions from http://sourceforge.net/projects/pywin32/ or I use python packaged by ActiveState
They include the function win32file.GetLongPathName which will transform the 8.3 version into the full path.
| compare two windows paths, one containing tilde, in python | I'm trying to use the TMP environment variable in a program. When I ask for
tmp = os.path.expandvars("$TMP")
I get
C:\Users\STEVE~1.COO\AppData\Local\Temp
Which contains the old-school, tilde form. A function I have no control over returns paths like
C:\Users\steve.cooper\AppData\Local\Temp\file.txt
My problem is this; I'd like to check if the file is in my temp drive, but I can't find a way to compare them. How do you tell if these two Windows directories;
C:\Users\STEVE~1.COO\AppData\Local\Temp
C:\Users\steve.cooper\AppData\Local\Temp
are the same?
| [
"Here is alternative solution using only ctypes from Standard Python Library.\ntmp = unicode(os.path.expandvars(\"$TMP\"))\n\nimport ctypes\nGetLongPathName = ctypes.windll.kernel32.GetLongPathNameW\nbuffer = ctypes.create_unicode_buffer(GetLongPathName(tmp, 0, 0))\nGetLongPathName(tmp, buffer, len(buffer))\nprint ... | [
8,
4
] | [] | [] | [
"directory",
"path",
"python",
"string_comparison",
"windows"
] | stackoverflow_0002738473_directory_path_python_string_comparison_windows.txt |
Q:
variable scope in python nested functions
As I am studying decorators, I noticed something strange :
def f():
... msg='aa'
... def a():
... print msg
... msg='bb'
... def b():
... print msg
... return a,b
...
>>> a,b = f()
>>> a()
bb
>>> b()
bb
>>>
Why a() returns 'bb' and not 'aa' ??
A:
Because a and b have the same outer scope, in which msg is bound to 'bb'. Put them in separate functions if you want them to have separate scopes.
A:
Both a and b have read access to the outer scope (the local scope of f). As you overwrite the value of msg, the later call to a/b will read the new value.
| variable scope in python nested functions | As I am studying decorators, I noticed something strange :
def f():
... msg='aa'
... def a():
... print msg
... msg='bb'
... def b():
... print msg
... return a,b
...
>>> a,b = f()
>>> a()
bb
>>> b()
bb
>>>
Why a() returns 'bb' and not 'aa' ??
| [
"Because a and b have the same outer scope, in which msg is bound to 'bb'. Put them in separate functions if you want them to have separate scopes.\n",
"Both a and b have read access to the outer scope (the local scope of f). As you overwrite the value of msg, the later call to a/b will read the new value.\n"
] | [
3,
1
] | [] | [] | [
"python",
"scope"
] | stackoverflow_0003931957_python_scope.txt |
Q:
win32com - Write String values in Excel sheet
I'm using win32com to write some dates that I receive from a database, and my problem is that I'm having values like '01' and in Excel is just '1' - not '01'.
Example:
b = row[1] # b has the value 01
c = "-"+b+"-" # c has value -01-
sheet.Cells(1,1).Value = b # I have in Excel '1' ; I've try with str(b), c - but is the same
How can I fix this, to have in Excel the value recognize as a String, in this case - 01?
Thanks.
A:
Thanks eumiro for the point
I've found the solution - I'm formating the cells to contain String values:
range = sheet.Range(sheet.Cells(1, 1), sheet.Cells(100, 2) )
range.NumberFormat = '@'
I'm doing this before I'm puting the values in cells and it works ok, now in Excel cells I have String values.
| win32com - Write String values in Excel sheet | I'm using win32com to write some dates that I receive from a database, and my problem is that I'm having values like '01' and in Excel is just '1' - not '01'.
Example:
b = row[1] # b has the value 01
c = "-"+b+"-" # c has value -01-
sheet.Cells(1,1).Value = b # I have in Excel '1' ; I've try with str(b), c - but is the same
How can I fix this, to have in Excel the value recognize as a String, in this case - 01?
Thanks.
| [
"Thanks eumiro for the point\nI've found the solution - I'm formating the cells to contain String values:\nrange = sheet.Range(sheet.Cells(1, 1), sheet.Cells(100, 2) )\nrange.NumberFormat = '@'\n\nI'm doing this before I'm puting the values in cells and it works ok, now in Excel cells I have String values.\n"
] | [
3
] | [] | [] | [
"excel",
"python",
"win32com"
] | stackoverflow_0003931791_excel_python_win32com.txt |
Q:
Object generator pattern
I have a class that represents a pretty complex object. The objects can be created by many ways: incremental building, by parsing text strings in different formats and by analyzing binary files. So far my strategy was as follows:
Have the constructor (__init__, in my case) initialize all the internal variables to None
Supply different member functions to populate the object
Have those functions return the new, modified object to the caller so we can do sd = SuperDuper().fromString(s)
For example:
class SuperDuper:
def __init__(self):
self.var1 = None
self.var2 = None
self.varN = None
## Generators
def fromStringFormat1(self, s):
#parse the string
return self
def fromStringFormat2(self, s):
#parse the string
return self
def fromAnotherLogic(self, *params):
#parse params
return self
## Modifiers (for incremental work)
def addThis(self, p):
pass
def addThat(self, p):
pass
def removeTheOtherOne(self, p):
pass
The problem is that the class becomes very huge. Unfotunately I am not familiar with OOP pattern designs, but I assume that there is a more ellegant solution for this problem. Is taking the generator functions out of the class (so that fromString(self, s) becomes superDuperFromString(s) a good idea?
A:
What might be a better idea in your case is dependency injection and inversion of control. The idea is to create another class that has all of the settings that you are parsing out of all of these different sources. Then subclasses can define the method to actually parse it. Then when you instantiate the class, pass an instance of the settings class to it:
class Settings(object):
var1 = None
var2 = None
var3 = None
def configure_superduper(self, superduper):
superduper.var1 = self.var1
# etc
class FromString(Settings):
def __init__(self, string):
#parse strings and set var1, etc.
class SuperDuper(object):
def __init__(self, settings): # dependency injection
settings.configure_superduper(self) # inversion of control
# other initialization stuff
sup = SuperDuper(object, FromString(some_string))
Doing it this way has the advantage of adhering more closely to the single responsibility principle which says that a class should only have one (likely to occur) reason to change. If you change the way you're storing any of these strings, then the class has to change. Here, we're isolating that into one simple, separate class for each source of data.
If on the other hand, you think that the data that's being stored is more likely to change than the way it's stored, you might want to go with class methods as Ignacio is suggesting because this is (slightly) more complicated and doesn't really buy you much in that case because when that happens you have to change two classes in this scheme. Of course it doesn't really hurt much either because you'll only have to change one more assignment.
A:
I don't believe it would be, since those all relate directly to the class regardless.
What I would do is make the constructor take arguments to initialize the fields (defaulting to None of course), then turn all the from*() methods into classmethods that construct new objects and return them.
A:
I don't think it is a bad design to have conversion/creation methods inside the class. You could always move it to a separate class and then you would have a Simple Factory which is a very light-weight design pattern.
I'd keep them in the class though :)
A:
Have those functions return the new, modified object to the caller so we can do sd = SuperDuper().fromString(s)
Rarely is this a good idea. While some Python library classes do this, it's not the best approach.
Generally, you want to do this.
class SuperDuper( object ):
def __init__(self, var1=None, var2=None, var3=None):
self.var1 = var1
self.var2 = var2
self.varN = var3
def addThis(self, p):
pass
def addThat(self, p):
pass
def removeTheOtherOne(self, p):
pass
class ParseString( object ):
def __init__( self, someString ):
pass
def superDuper( self ):
pass
class ParseString_Format1( ParseString ):
pass
class ParseString_Format2( ParseString ):
pass
def parse_format1( string ):
parser= ParseString_Format1( string )
return parser.superDuper()
def parse_format2( string ):
parser= ParseString_Format2( string )
return parser.superDuper()
def fromAnotherLogic( **kw ):
return SuperDuper( **kw )
There are two unrelated responsibilities: the object and the string representations of the object.
Do Not Conflate Objects and String Representations.
Objects and Parsing must be kept separate. After all, the compiler is not part of the code that's produced. An XML parser and the Document Object Model are generally separate objects.
| Object generator pattern | I have a class that represents a pretty complex object. The objects can be created by many ways: incremental building, by parsing text strings in different formats and by analyzing binary files. So far my strategy was as follows:
Have the constructor (__init__, in my case) initialize all the internal variables to None
Supply different member functions to populate the object
Have those functions return the new, modified object to the caller so we can do sd = SuperDuper().fromString(s)
For example:
class SuperDuper:
def __init__(self):
self.var1 = None
self.var2 = None
self.varN = None
## Generators
def fromStringFormat1(self, s):
#parse the string
return self
def fromStringFormat2(self, s):
#parse the string
return self
def fromAnotherLogic(self, *params):
#parse params
return self
## Modifiers (for incremental work)
def addThis(self, p):
pass
def addThat(self, p):
pass
def removeTheOtherOne(self, p):
pass
The problem is that the class becomes very huge. Unfotunately I am not familiar with OOP pattern designs, but I assume that there is a more ellegant solution for this problem. Is taking the generator functions out of the class (so that fromString(self, s) becomes superDuperFromString(s) a good idea?
| [
"What might be a better idea in your case is dependency injection and inversion of control. The idea is to create another class that has all of the settings that you are parsing out of all of these different sources. Then subclasses can define the method to actually parse it. Then when you instantiate the class, pa... | [
3,
2,
1,
1
] | [] | [] | [
"design_patterns",
"factory",
"factory_pattern",
"oop",
"python"
] | stackoverflow_0003931123_design_patterns_factory_factory_pattern_oop_python.txt |
Q:
What is for Python as json_encode for PHP
Possible Duplicate:
Easy JSON encoding with Python
I want to get a record from database and built it in to json. I know we can do it with json_encode when using PHP. But how can we do it in Python
A:
# Python 2.6+
import json
result = json.dumps(value)
or
# Python 2.6+
import json
json.dump(value, out_file)
Got if from google first result. http://www.php2python.com/wiki/function.json-encode/
Please do your research before asking simple, searchable questions!
A:
There are several json implementations for Python. I like simplejson because it's, well, simple.
| What is for Python as json_encode for PHP |
Possible Duplicate:
Easy JSON encoding with Python
I want to get a record from database and built it in to json. I know we can do it with json_encode when using PHP. But how can we do it in Python
| [
"# Python 2.6+\nimport json\nresult = json.dumps(value)\nor\n# Python 2.6+\nimport json\njson.dump(value, out_file)\n\nGot if from google first result. http://www.php2python.com/wiki/function.json-encode/\nPlease do your research before asking simple, searchable questions!\n",
"There are several json implementati... | [
9,
2
] | [] | [] | [
"json",
"php",
"python"
] | stackoverflow_0003932087_json_php_python.txt |
Q:
Finding permuations and combinations using Python
I have 2 variables - a and b. I need to fill up k places using these variables. So if k = 3 output should be
[a,a,a], [a,a,b] , [a,b,a], [b,a,a], [a,b,b], [b,a,b], [b,b,a] and [b,b,b]
Input - k
Output - All the combinations
How do I code this in Python? Can itertools be of any help here?
A:
>>> import itertools
>>> list(itertools.product('ab', repeat=3))
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'b', 'a'), ('b', 'b', 'b')]
A:
def genPerm(varslist, pos,resultLen, result, resultsList)
if pos>resultLen:
return;
for e in varslist:
if pos==resultLen:
resultsList.append(result + [e]);
else
genPerm(varsList, pos+1, resultLen, result + [e], resultsList);
Call with:
genPerm([a,b], 0, resLength, [], resultsList);
| Finding permuations and combinations using Python | I have 2 variables - a and b. I need to fill up k places using these variables. So if k = 3 output should be
[a,a,a], [a,a,b] , [a,b,a], [b,a,a], [a,b,b], [b,a,b], [b,b,a] and [b,b,b]
Input - k
Output - All the combinations
How do I code this in Python? Can itertools be of any help here?
| [
">>> import itertools\n>>> list(itertools.product('ab', repeat=3))\n[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'b', 'a'), ('b', 'b', 'b')]\n\n",
"def genPerm(varslist, pos,resultLen, result, resultsList)\n if pos>resultLen:\n return;\n fo... | [
6,
1
] | [] | [] | [
"permutation",
"python"
] | stackoverflow_0003932148_permutation_python.txt |
Q:
Integrating C++ code with any web technology on Linux
i am writing an program in c++ and i need an web interface to control the program and which will be efficient and best programming language ...
A:
Your application will just have to listen to messages from the network that your web application would send to it.
Any web application (whatever the language) implementation could use sockets so don't worry about the details, just make sure your application manage messages that you made a protocol for.
Now, if you want to keep it all C++, you could use CPPCMS for your web application.
A:
If it were Windows, I could advice you to register some COM component for your program. At least from ASP.NET it is easily accessible.
You could try some in-memory exchange techniques like reading/writing over a localhost socket connection. It however requires you to design some exchange protocol first.
Or data exchange via a database. You program writes/reads data from the database, the web front-end reads/writes data to the database.
A:
You could use a framework like Thrift to communicate between a PHP/Python/Ruby/whatever webapp and a C++ daemon, or you could even go the extra mile (probably harder than just using something like Thrift) and write language bindings for the scripting language of your choice.
Either of the two options gives you the ability to write web-facing code in a language more suitable for the task while keeping the "heavy lifting" in C++.
A:
Did you take a look at Wt? It's a widget-centric C++ framework for web applications, has a solid MVC system, an ORM, ...
| Integrating C++ code with any web technology on Linux | i am writing an program in c++ and i need an web interface to control the program and which will be efficient and best programming language ...
| [
"Your application will just have to listen to messages from the network that your web application would send to it.\nAny web application (whatever the language) implementation could use sockets so don't worry about the details, just make sure your application manage messages that you made a protocol for.\nNow, if y... | [
1,
0,
0,
0
] | [
"The Win32 API method.\nMSDN - Getting Started with Winsock:\nhttp://msdn.microsoft.com/en-us/library/ms738545%28v=VS.85%29.aspx\n(Since you didn't specify an OS, we're assuming Windows)\n",
"This is not as simple as it seems!\nThere is a mis-match between your C++ program (which presumibly is long running otherw... | [
-1,
-1,
-1
] | [
"c++",
"linux",
"python",
"web_technologies"
] | stackoverflow_0003733994_c++_linux_python_web_technologies.txt |
Q:
Number of matches in regex substitution
I am looking for a Pythonic way to simplify this code:
fix = re.compile(r'((?<=>\n)(\t){2}(?=<))')
fixed_output = re.sub(fix, 1*2*' ', fixed_output)
fix = re.compile(r'((?<=>\n)(\t){3}(?=<))')
fixed_output = re.sub(fix, 2*2*' ', fixed_output)
# and so on...
That is: if there are n tab characters between ">" and "<", they are replaced by *(n-1) * 2* characters. Can this be generalized to a single regular expression? In other words, is it possible to write a regular expression that uses the number of matches in order to determine the replacement string?
A:
You can use a function instead of a fixed replacement string and take the number of matched tabulator characters to generate the replacement, for example:
re.sub(r'((?<=>\n)\t{2,}(?=<))', lambda m: (len(m.group(0))-1)*2*" ", string)
Here the lambda expression lambda m: (len(m.group(0))-1)*2*" " is used to replace n tabulator character by (n-1)·2 spaces.
| Number of matches in regex substitution | I am looking for a Pythonic way to simplify this code:
fix = re.compile(r'((?<=>\n)(\t){2}(?=<))')
fixed_output = re.sub(fix, 1*2*' ', fixed_output)
fix = re.compile(r'((?<=>\n)(\t){3}(?=<))')
fixed_output = re.sub(fix, 2*2*' ', fixed_output)
# and so on...
That is: if there are n tab characters between ">" and "<", they are replaced by *(n-1) * 2* characters. Can this be generalized to a single regular expression? In other words, is it possible to write a regular expression that uses the number of matches in order to determine the replacement string?
| [
"You can use a function instead of a fixed replacement string and take the number of matched tabulator characters to generate the replacement, for example:\nre.sub(r'((?<=>\\n)\\t{2,}(?=<))', lambda m: (len(m.group(0))-1)*2*\" \", string)\n\nHere the lambda expression lambda m: (len(m.group(0))-1)*2*\" \" is used t... | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003932710_python_regex.txt |
Q:
django : unique name for object within foreign-key set
I'm trying to upload files for an article model. Since an object can have multiple images, I'm using a foreign-key from file model to my article model. However, I want all the files to have unique titles. Herez the code snippet.
class Article(models.Model):
name = models.CharField(max_length=64)
class Files(models.Model):
title = models.CharField(max_length=64)
file = models.FileField(upload_to="files/%Y/%m/%d/")
article = models.ForeignKey(Article)
Now when I upload the files, I want the file titles to be unique within the "foreign_key" set of Article, and NOT necessarily among all the objects of Files. Is there a way I can automatically set the title of Files? Preferably to some combination of related Article and incremental integers!! I intend to upload the files only from the admin interface, and Files are set Inline in Article admin form.
A:
def add_file(request, article_id):
if request.method == 'POST':
form = FileForm(request.POST, request.FILES)
if form.is_valid():
file = form.save(commit=False)
article = Article.objects.get(id=article_id)
file.article = article
file.save()
file.title = article.name + ' ' + file.id
file.save()
redirect_to = 'redirect to url'
return HttpResponseRedirect(redirect_to)
| django : unique name for object within foreign-key set | I'm trying to upload files for an article model. Since an object can have multiple images, I'm using a foreign-key from file model to my article model. However, I want all the files to have unique titles. Herez the code snippet.
class Article(models.Model):
name = models.CharField(max_length=64)
class Files(models.Model):
title = models.CharField(max_length=64)
file = models.FileField(upload_to="files/%Y/%m/%d/")
article = models.ForeignKey(Article)
Now when I upload the files, I want the file titles to be unique within the "foreign_key" set of Article, and NOT necessarily among all the objects of Files. Is there a way I can automatically set the title of Files? Preferably to some combination of related Article and incremental integers!! I intend to upload the files only from the admin interface, and Files are set Inline in Article admin form.
| [
"def add_file(request, article_id): \n if request.method == 'POST': \n form = FileForm(request.POST, request.FILES) \n if form.is_valid(): \n file = form.save(commit=False) \n article = Article.objects.get(id=article_id) \n file.article = article \n... | [
1
] | [] | [] | [
"admin",
"django",
"file_upload",
"foreign_keys",
"python"
] | stackoverflow_0003932969_admin_django_file_upload_foreign_keys_python.txt |
Q:
Calling staticmethod inside class level containers initialization
Given the following example class:
class Foo:
def aStaticMethod():
return "aStaticMethod"
aVariable = staticmethod(aStaticMethod)
aTuple = (staticmethod(aStaticMethod),)
aList = [staticmethod(aStaticMethod)]
print Foo.aVariable()
print Foo.aTuple[0]()
print Foo.aList[0]()
Why would the call to aVariable works properly but with the aTuple and aList it returns the error 'staticmethod' object is not callable?
A:
It's because a static method is a descriptor. When you attach it to a class and call it with the usual syntax, then python calls its __get__ method which returns a callable object. When you deal with it as a bare descriptor, python never calls its __get__ method and you end up attempting to call the descriptor directly which is not callable.
So if you want to call it, you have to fill in the details for yourself:
>>> Foo.aTuple[0].__get__(None, Foo)()
'aStaticMethod'
Here, None is passed to the instance parameter (the instance upon which the descriptor is being accessed) and Foo is passed to the owner parameter (the class upon which this instance of the descriptor resides). This causes it to return an actual callable function:
>>> Foo.aTuple[0].__get__(None, Foo)
<function aStaticMethod at 0xb776daac>
| Calling staticmethod inside class level containers initialization | Given the following example class:
class Foo:
def aStaticMethod():
return "aStaticMethod"
aVariable = staticmethod(aStaticMethod)
aTuple = (staticmethod(aStaticMethod),)
aList = [staticmethod(aStaticMethod)]
print Foo.aVariable()
print Foo.aTuple[0]()
print Foo.aList[0]()
Why would the call to aVariable works properly but with the aTuple and aList it returns the error 'staticmethod' object is not callable?
| [
"It's because a static method is a descriptor. When you attach it to a class and call it with the usual syntax, then python calls its __get__ method which returns a callable object. When you deal with it as a bare descriptor, python never calls its __get__ method and you end up attempting to call the descriptor dir... | [
16
] | [] | [] | [
"python",
"static_methods"
] | stackoverflow_0003932948_python_static_methods.txt |
Q:
how to insert text inside bar if bar color equal to purple
So I've this image :
What I trying to do if to leave 'H37Rv' only in the purple bar.
My code is the following:
rects = ax.bar(ind, num, width, color=colors)
for rect in rects:
height = int(rect.get_height())
if height < 5:
yloc = height + 2
clr = '#182866'
else:
yloc = height / 2.0
clr = '#182866'
p = 'H37Rv'
xloc = rect.get_x() + (rect.get_width() / 2.0)
ax.text(xloc, yloc, p, horizontalalignment='center', verticalalignment='center', color=clr, weight='bold')
I also tried this:
for rect in rects:
if color == purple:
height = int(rect.get_height())
if height < 5:
yloc = height + 2
clr = '#182866'
but I get an error saying color is not defined.
Anyone has any idea how to solve this?
Thanks a lot!
A:
If you move the last three lines of your first example in one indent level, so they are part of the "else" clause that sets the colour to purple, that should do it.
[Edit: Sorry, I misread slightly. That would also leave the text in the 2nd bar. There's no way to get the colour of a rectangle as far as I know, but you could do:
rects = ax.bar(ind, num, width, color=colors)
rect = rects[-1]
height = int(rect.get_height())
if height < 5:
yloc = height + 2
else:
yloc = height / 2.0
clr = '#182866'
p = 'H37Rv'
xloc = rect.get_x() + (rect.get_width() / 2.0)
ax.text(xloc, yloc, p, horizontalalignment='center', verticalalignment='center', color=clr, weight='bold')
That would set the text in the last bar only.
If it could be any bar that might be purple, not necessarily the last one, well, you've got the list of colours you initialised the rectangles with, so:
rects = ax.bar(ind, num, width, color=colors)
for i in range(len(colors):
if colors[i] == purple: # or however you specified "purple" in your colors list
labelled_rects.append(i)
for i in labelled_rects:
rect = rects[i]
height = int(rect.get_height())
if height < 5:
yloc = height + 2
else:
yloc = height / 2.0
clr = '#182866'
p = 'H37Rv'
xloc = rect.get_x() + (rect.get_width() / 2.0)
ax.text(xloc, yloc, p, horizontalalignment='center', verticalalignment='center', color=clr, weight='bold')
A:
You can get the color of a rectangle with rect.get_facecolor(), which allows you to place the label the way you want.
Alternatively, since you know which colors you used when drawing the bar plot, and if they are represented by a list, you can indeed easily get the list of purple rectangles.
| how to insert text inside bar if bar color equal to purple | So I've this image :
What I trying to do if to leave 'H37Rv' only in the purple bar.
My code is the following:
rects = ax.bar(ind, num, width, color=colors)
for rect in rects:
height = int(rect.get_height())
if height < 5:
yloc = height + 2
clr = '#182866'
else:
yloc = height / 2.0
clr = '#182866'
p = 'H37Rv'
xloc = rect.get_x() + (rect.get_width() / 2.0)
ax.text(xloc, yloc, p, horizontalalignment='center', verticalalignment='center', color=clr, weight='bold')
I also tried this:
for rect in rects:
if color == purple:
height = int(rect.get_height())
if height < 5:
yloc = height + 2
clr = '#182866'
but I get an error saying color is not defined.
Anyone has any idea how to solve this?
Thanks a lot!
| [
"If you move the last three lines of your first example in one indent level, so they are part of the \"else\" clause that sets the colour to purple, that should do it. \n[Edit: Sorry, I misread slightly. That would also leave the text in the 2nd bar. There's no way to get the colour of a rectangle as far as I know,... | [
2,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003932547_matplotlib_python.txt |
Q:
What is the difference between None check and var or default syntax in Python?
I noted this syntax listed as a gotchya but with no explanation as to why:
def func(x=None):
#good
if x == None:
x = []
#bad
x = x or []
In what ways can this be a gotchya?
A:
In this particular case, it’s bad because an empty list evaluates to false. If you mutate the list, then the results won’t be as expected
def func(x=None):
x = x or []
x.append('hello')
mylist = []
func(mylist)
print mylist[0] # doesn't work
Since you want to check to see if the caller passed None or not, you should just say that explicitly and not try to be clever. Objects like [], (), {}, 0, and False evaluate to false, as can any user-defined object that wants to — checking for falsehood really catches too many false positives.
(Also: Using is None instead of == None can be faster and more reliable.)
A:
x or [] will return an empty list if bool(x) is false. None is false, but zeros (ints, longs, floats, etc) and empty collections ([], {}, "", etc) are also false. So this isn't catching None, it's catching falsy object - which isn't equivalent to x == None and most likely not what you want (empty collections are perfectly valid input for many algorithms).
Oh, and while we're at it: That should be x is None - is is the semantically correct (and propably faster) choice for testing identity. == can be overwritten by x, and you can't be sure if it won't consider None equal to itself or even break on it.
A:
I think the best idiom to check for any python singleton is:
if x is None:
x = []
The reason is that some objects like ORM objects in django or sqlalchemy, for example, are lazy (they will not call the database until the latest possible time). Using the other options to check for None may trigger evaluation of an expensive operation.
| What is the difference between None check and var or default syntax in Python? | I noted this syntax listed as a gotchya but with no explanation as to why:
def func(x=None):
#good
if x == None:
x = []
#bad
x = x or []
In what ways can this be a gotchya?
| [
"In this particular case, it’s bad because an empty list evaluates to false. If you mutate the list, then the results won’t be as expected\ndef func(x=None):\n x = x or []\n x.append('hello')\n\nmylist = []\nfunc(mylist)\nprint mylist[0] # doesn't work\n\nSince you want to check to see if the caller passed No... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003933083_python.txt |
Q:
Facebook connect button
I can't seem to find how to generate the classic Facebook Connect button:
all I can find how to generate is the following:
I'm using the documentation here http://developers.facebook.com/docs/guides/web
Any ideas? :)
A:
http://developers.facebook.com/docs/reference/plugins/login
If you wanna change the image you must doing manually:
<div id='login'><a href="#" id='facebook-login' onclick='fblogin();'><img src="your image url here" /></a></div>
</a>
<script>
function fblogin(){
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
window.location.reload();
} else {
// user is logged in, but did not grant any permissions
window.location.reload();
}
} else {
// user is not logged in
window.location.reload();
}
}, {perms:'email'});
return false;
}
</script>
A:
"Connect with Facebook" is simply an earlier design of the same button. If you really want to use that, you could fetch the code for "Login with Facebook", adjust it to look like "Connect with Facebook" and put it inline, but I would recommend against it, as such a solution is fragile and will break when Facebook changes something on their side.
| Facebook connect button | I can't seem to find how to generate the classic Facebook Connect button:
all I can find how to generate is the following:
I'm using the documentation here http://developers.facebook.com/docs/guides/web
Any ideas? :)
| [
"http://developers.facebook.com/docs/reference/plugins/login\nIf you wanna change the image you must doing manually:\n<div id='login'><a href=\"#\" id='facebook-login' onclick='fblogin();'><img src=\"your image url here\" /></a></div>\n</a>\n<script>\n function fblogin(){\n FB.login(function(response) {\n... | [
3,
1
] | [] | [] | [
"django",
"django_socialauth",
"facebook",
"python"
] | stackoverflow_0003931649_django_django_socialauth_facebook_python.txt |
Q:
Why an error in nosetests and not in Eclipse?
I'm using a third-party library which needs urlfetch from google.appengine.api. It is imported into the executing tests using this line:
from google.appengine.api import urlfetch
The google_appengine directory is on my PYTHONPATH, and if I execute my unit tests directly from Eclipse, I see no errors. However, if I use nosetests, I see this:
File "/home/wraith/dev/sdks/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 54, in CreateRPC
assert stub, 'No api proxy found for service "%s"' % service
AssertionError: No api proxy found for service "urlfetch"
Someone had a similar issue, but I am using Python 2.5 and I tried to execute nosetests from the google_appengine directory using --where and providing the path to my unit test directory and I see the same result.
Why is this fine in Eclipse but fail in nosetests?
A:
Calls to App Engine APIs are handled by API proxy modules. In the dev_appserver, local, development versions of these are set up for you, but if you try and run your code directly from the command line, they're not set up.
You can set them up yourself something like this, or you can just use nosegae.
| Why an error in nosetests and not in Eclipse? | I'm using a third-party library which needs urlfetch from google.appengine.api. It is imported into the executing tests using this line:
from google.appengine.api import urlfetch
The google_appengine directory is on my PYTHONPATH, and if I execute my unit tests directly from Eclipse, I see no errors. However, if I use nosetests, I see this:
File "/home/wraith/dev/sdks/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 54, in CreateRPC
assert stub, 'No api proxy found for service "%s"' % service
AssertionError: No api proxy found for service "urlfetch"
Someone had a similar issue, but I am using Python 2.5 and I tried to execute nosetests from the google_appengine directory using --where and providing the path to my unit test directory and I see the same result.
Why is this fine in Eclipse but fail in nosetests?
| [
"Calls to App Engine APIs are handled by API proxy modules. In the dev_appserver, local, development versions of these are set up for you, but if you try and run your code directly from the command line, they're not set up.\nYou can set them up yourself something like this, or you can just use nosegae.\n"
] | [
1
] | [] | [] | [
"eclipse",
"google_app_engine",
"nosetests",
"python",
"unit_testing"
] | stackoverflow_0003929842_eclipse_google_app_engine_nosetests_python_unit_testing.txt |
Q:
Why do we need readlines() when we can iterate over the file handle itself?
In Python, after
fh = open('file.txt')
one may do the following to iterate over lines:
for l in fh:
pass
Then why do we have fh.readlines()?
A:
I would imagine that it's from before files were iterators and is maintained for backwards compatibility. Even for a one-liner, it's totally1 fairly redundant as list(fh) will do the same thing in a more intuitive way. That also gives you the freedom to do set(fh), tuple(fh), etc.
1 See John La Rooy's answer.
A:
Mostly it is there for backward compatibility. readlines was there way before file objects were iterable
Using readlines with the size argument is also one of the fastest ways to read from files because it reads a bunch of data in one hit, but doesn't need to allocate memory for the entire file all at once
A:
readlines() returns a list of lines, which you may want if you don't plan on iterating through each line.
| Why do we need readlines() when we can iterate over the file handle itself? | In Python, after
fh = open('file.txt')
one may do the following to iterate over lines:
for l in fh:
pass
Then why do we have fh.readlines()?
| [
"I would imagine that it's from before files were iterators and is maintained for backwards compatibility. Even for a one-liner, it's totally1 fairly redundant as list(fh) will do the same thing in a more intuitive way. That also gives you the freedom to do set(fh), tuple(fh), etc.\n1 See John La Rooy's answer.\n",... | [
18,
16,
1
] | [] | [] | [
"python"
] | stackoverflow_0003933223_python.txt |
Q:
How to display a sequence of widgets on the same row?
I'm new to tkinter, and I was wondering if I can display a sequence of widgets on the same row instead of placing them one below the other one in a column.
I'm currently using frames to place my components, however if I have several widgets (buttons) in a frame, I would prefer to directly place the button as I want, instead of creating additional subframes.
A:
You use geometry managers to lay out widgets within a container. Tkinter's geometry managers are grid, pack and place.
grid allows you to lay out your widgets in rows and columns. pack allows you to lay out your widgets along sides of a box (and great for making single horizontal or vertical columns). place lets you use absolute and relative positioning. In practice, place is used very infrequently.
In your case, you want to create a horizontal row of buttons which is typically done by creating a frame that represents the row, and then using pack to place the widgets side by side. Don't be afraid of using subframes for layout -- that is exactly what they are for.
For example:
import Tkinter as tk
class App:
def __init__(self):
self.root = tk.Tk()
# this will be the container for a row of buttons
# a background color has been added just to make
# it stand out.
container = tk.Frame(self.root, background="#ffd3d3")
# these are the buttons. If you want, you can make these
# children of the container and avoid the use of "in_"
# in the pack command, but I find it easier to maintain
# code by keeping my widget hierarchy shallow.
b1 = tk.Button(text="Button 1")
b2 = tk.Button(text="Button 2")
b3 = tk.Button(text="Button 3")
# pack the buttons in the container. Since the buttons
# are children of the root we need to use the in_ parameter.
b1.pack(in_=container, side="left")
b2.pack(in_=container, side="left")
b3.pack(in_=container, side="left")
# finally, pack the container in the root window
container.pack(side="top", fill="x")
self.root.mainloop()
if __name__ == "__main__":
app=App()
| How to display a sequence of widgets on the same row? | I'm new to tkinter, and I was wondering if I can display a sequence of widgets on the same row instead of placing them one below the other one in a column.
I'm currently using frames to place my components, however if I have several widgets (buttons) in a frame, I would prefer to directly place the button as I want, instead of creating additional subframes.
| [
"You use geometry managers to lay out widgets within a container. Tkinter's geometry managers are grid, pack and place. \ngrid allows you to lay out your widgets in rows and columns. pack allows you to lay out your widgets along sides of a box (and great for making single horizontal or vertical columns). place lets... | [
5
] | [] | [] | [
"layout",
"python",
"tkinter"
] | stackoverflow_0003931386_layout_python_tkinter.txt |
Q:
Best Practices for Python UnicodeDecodeError
I use Pylons framework, Mako template for a web based application. I wasn't really bother too deep into the way Python handles the unicode strings. I had tense moment when I did see my site crash when the page is rendered and later I came to know that it was related to UnicodeDecodeError.
After seeing the error, I started mesh around my Python code adding encode, decode calls for string with 'ignore' option but still I could not see the errors gone sometime.
Finally I used to decode to ascii with ignore and made the site running without any crash.
Input to my site comes through many sites. This means that I do not control the languages or language of choice. My site supports international languages and along with English. I have feed aggregation which generally not bother about unicode/ascii/utf-8. While I display the text through mako template, I display as it is.
Not being a web expert, what are the best practices to handle the strings within the Python project? Should I care only while rendering the text or all the phase of the application?
A:
If you have influence on it, this is the painless way:
know your input encoding (or decode with ignore) and decode(encoding) the data as soon as it hits your app
work internally only with unicode (u'something' is unicode), also in the database
for rendering, export etc, anytime it leaves your app, encode('utf-8') the data
A:
this might not be a viable option for you, but let me say that a big number of encoding-related errors vanish when using python 3, just because the separation between unicode strings and byte objects has been made so much clearer. when i have to use python 2, i opt for version 2.6, where you can declare from future import unicode_literals. disbelievers should actually read the link you posted, as it points out some subtleties with Python's en/decoding behavior that fortunately vanished in Python 3.
you say
I do not control the languages or
language of choice. My site supports
international languages and along with
English. I have feed aggregation which
generally not bother about
unicode/ascii/utf-8
well, whatever you choose to do, it is clear you do not want your web application to crash just because some dænish bløgger whose feeds you consume chose to encode their posts in an obscure scandinavian encoding scheme. the underlying problem is relevant for all web applications since URLs do not carry encoding information, and because you never know what byte sequences a malicious user might want to send you. in this case i do what i call 'safe chain-decoding': i try to decode as utf-8 first, and if that should fail, try again using cp1252. if that fails, i discard the request (HTTP 404) or something similar.
you mention you process feeds and ¿you? ¿the feeds? do not 'bother' about unicode and encodings. could you clarify that statement? it completely evades me how one can successfully build a site that carries text in multiple languages and not care about encodings. clearly using ascii-only will not carry you very far.
| Best Practices for Python UnicodeDecodeError | I use Pylons framework, Mako template for a web based application. I wasn't really bother too deep into the way Python handles the unicode strings. I had tense moment when I did see my site crash when the page is rendered and later I came to know that it was related to UnicodeDecodeError.
After seeing the error, I started mesh around my Python code adding encode, decode calls for string with 'ignore' option but still I could not see the errors gone sometime.
Finally I used to decode to ascii with ignore and made the site running without any crash.
Input to my site comes through many sites. This means that I do not control the languages or language of choice. My site supports international languages and along with English. I have feed aggregation which generally not bother about unicode/ascii/utf-8. While I display the text through mako template, I display as it is.
Not being a web expert, what are the best practices to handle the strings within the Python project? Should I care only while rendering the text or all the phase of the application?
| [
"If you have influence on it, this is the painless way:\n\nknow your input encoding (or decode with ignore) and decode(encoding) the data as soon as it hits your app\nwork internally only with unicode (u'something' is unicode), also in the database\nfor rendering, export etc, anytime it leaves your app, encode('utf... | [
11,
2
] | [] | [] | [
"exception_handling",
"mako",
"pylons",
"python",
"unicode"
] | stackoverflow_0003933911_exception_handling_mako_pylons_python_unicode.txt |
Q:
Sharing model between Camelot and non-Camelot apps
I would like to share my data model between different Elixir/SQLAlchemy applications, one of which would be a Camelot UI and the others stuff like web interfaces and so on. They would all connect to the same underlying database.
As far as I know, to build a Camelot app my model would do from camelot import blah and that would prevent it to run in any environment without Camelot installed.
I would like to know if there is a recommended way / best practice to do that. The idea is of course to maintain a single code base for my model and not to replicate it with subtle differences between different apps (like importing from SA/Elixir here, and from Camelot there, and so on).
My project is currently laid out with a model/ python package:
model/__init__.py
foo.py
bar.py
...
init.py looks like this:
from foo import a, b, c
from bar import d, e, f
__all__ = ('a', 'b', 'c', 'd', 'e', 'f')
and python modules foo.py, bar.py, and so on actually implement the various parts.
Every one of these modules starts like this:
from sqlalchemy import Integer, Numeric, Date, Unicode, LargeBinary
from elixir import Entity, Field, ManyToOne, OneToMany, ManyToMany
from elixir import using_options
An idea could be to do something like:
try:
from camelot import Integer, Numeric, ...
except ImportError:
from elixir import Integer, Numeric, ...
would that be actually a good idea or there's something I'm missing? Also, ideally I'd do that kind of "environment initialization" stuff in some central place, like in model/__init__.py, but how would I pass my imports to the underlying modules?
A:
I can't speak as to whether it would be a good idea, but it's easy to make the imports central because modules are 'singletons' in the Java idiom: they share state. In other words, you could do the following:
dataProxy.py
try:
from camelot import Integer, Numeric, ...
except ImportError:
from elixir import Integer, Numeric, ...
and then in a different module do
from dataProxy import Integer
and you will get the same classes everywhere (in the same interpreter session, that is). This idiom is often used for configuration files, because you can write e.g. setup code in a settings.py and then the rest of your app will have access to the results of that code.
| Sharing model between Camelot and non-Camelot apps | I would like to share my data model between different Elixir/SQLAlchemy applications, one of which would be a Camelot UI and the others stuff like web interfaces and so on. They would all connect to the same underlying database.
As far as I know, to build a Camelot app my model would do from camelot import blah and that would prevent it to run in any environment without Camelot installed.
I would like to know if there is a recommended way / best practice to do that. The idea is of course to maintain a single code base for my model and not to replicate it with subtle differences between different apps (like importing from SA/Elixir here, and from Camelot there, and so on).
My project is currently laid out with a model/ python package:
model/__init__.py
foo.py
bar.py
...
init.py looks like this:
from foo import a, b, c
from bar import d, e, f
__all__ = ('a', 'b', 'c', 'd', 'e', 'f')
and python modules foo.py, bar.py, and so on actually implement the various parts.
Every one of these modules starts like this:
from sqlalchemy import Integer, Numeric, Date, Unicode, LargeBinary
from elixir import Entity, Field, ManyToOne, OneToMany, ManyToMany
from elixir import using_options
An idea could be to do something like:
try:
from camelot import Integer, Numeric, ...
except ImportError:
from elixir import Integer, Numeric, ...
would that be actually a good idea or there's something I'm missing? Also, ideally I'd do that kind of "environment initialization" stuff in some central place, like in model/__init__.py, but how would I pass my imports to the underlying modules?
| [
"I can't speak as to whether it would be a good idea, but it's easy to make the imports central because modules are 'singletons' in the Java idiom: they share state. In other words, you could do the following:\ndataProxy.py\ntry:\n from camelot import Integer, Numeric, ...\nexcept ImportError:\n from elixir i... | [
0
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0003934351_python_python_elixir_sqlalchemy.txt |
Q:
Django admin inline form error
I have an inline formset in my admin site. I also have save_as = True in admin.py.
My models are, for example:
class Poll(models.Model):
question = models.CharField(max_length=200, unique = True)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
I chose to have an unique question.
The problem is, whenever I try to save a poll as a new poll, if I forget to change the question I get an error, as it supposed to happen. But if I then change the question and try to save I get this error: invalid literal for int() with base 10: ''
and if I check the error I see that the pool foreign key is not available and that's the cause of the error.
Anyone else has got this error?
Is it a django bug? I know that there was an error related with save_as in http://code.djangoproject.com/ticket/9651 but I can't tell if it's related with my error.
Try in the django tutorial as I did and see if the error appears.
Thanks for any reply.
A:
I've never had much luck with Save as and relationships. Although, I think I was trying to do complicated many to many stuff.
What is the url of the page that is giving that error... From the errors it looks like it would be something like.... /admin/myapp/poll// whereas it should be something more like /admin/myapp/poll/103/. So the error is caused by the admin's urls parsing trying to convert the PK of '' to an int so it can look it up in the DB.
You'll get that error whenever you have a admin url that has an ID that is not an int (and your PK field is an int). It was probably None (because it didn't save) and then the admin tried to redirect it there.
Bug in Django? Could be, but I doubt it - Django is pretty stable these days. But you never know.
A:
I just had this error with a different part of the tutorial.
Have you checked your templates for typos? I had a template that was supposed to pass choice_id and instead I was passing choice_if which was nonsense.
| Django admin inline form error | I have an inline formset in my admin site. I also have save_as = True in admin.py.
My models are, for example:
class Poll(models.Model):
question = models.CharField(max_length=200, unique = True)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
I chose to have an unique question.
The problem is, whenever I try to save a poll as a new poll, if I forget to change the question I get an error, as it supposed to happen. But if I then change the question and try to save I get this error: invalid literal for int() with base 10: ''
and if I check the error I see that the pool foreign key is not available and that's the cause of the error.
Anyone else has got this error?
Is it a django bug? I know that there was an error related with save_as in http://code.djangoproject.com/ticket/9651 but I can't tell if it's related with my error.
Try in the django tutorial as I did and see if the error appears.
Thanks for any reply.
| [
"I've never had much luck with Save as and relationships. Although, I think I was trying to do complicated many to many stuff.\nWhat is the url of the page that is giving that error... From the errors it looks like it would be something like.... /admin/myapp/poll// whereas it should be something more like /admin/m... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002221901_django_django_models_python.txt |
Q:
How do I use this information in Python? I don't know how to use this data-type
According to the NLTK book, I first apply the grammar, and parse it.
grammar = r"""
NP: {<DT|PP\$>?<JJ>*<NN>}
{<NNP>+}
"""
cp = nltk.RegexpParser(grammar)
chunked_sent = cp.parse(sentence)
When I print chunked_sent, I get this:
(S
i/PRP
use/VBP
to/TO
work/VB
with/IN
you/PRP
at/IN
(NP match/NN)
./.)
I don't want to just look at it. I want to actually pull out the "NP" noun phrases.
How can I print out "match"...which is the noun phrase?
I want to get all "NP" out of that chunked_sent.
for k in chunked_sents:
print k
(u'i', 'PRP')
(u'use', 'VBP')
(u'to', 'TO')
(u'work', 'VB')
(u'with', 'IN')
(u'you', 'PRP')
(u'at', 'IN')
(NP match/NN)
(u'.', '.')
for k in chunked_sents:
print k[0]
i
use
to
work
with
you
at
(u'match', 'NN')
See, for some reason, I lose the "NP".
Also, how do I determine if k[0] is a string or tuple (as in the case above)
A:
Well you might have already found the answer. I am posting it for the people who might face this scenario in the future.
for subtree in chunked_sent.subtrees():
if subtree.node == 'NP': print subtree
| How do I use this information in Python? I don't know how to use this data-type | According to the NLTK book, I first apply the grammar, and parse it.
grammar = r"""
NP: {<DT|PP\$>?<JJ>*<NN>}
{<NNP>+}
"""
cp = nltk.RegexpParser(grammar)
chunked_sent = cp.parse(sentence)
When I print chunked_sent, I get this:
(S
i/PRP
use/VBP
to/TO
work/VB
with/IN
you/PRP
at/IN
(NP match/NN)
./.)
I don't want to just look at it. I want to actually pull out the "NP" noun phrases.
How can I print out "match"...which is the noun phrase?
I want to get all "NP" out of that chunked_sent.
for k in chunked_sents:
print k
(u'i', 'PRP')
(u'use', 'VBP')
(u'to', 'TO')
(u'work', 'VB')
(u'with', 'IN')
(u'you', 'PRP')
(u'at', 'IN')
(NP match/NN)
(u'.', '.')
for k in chunked_sents:
print k[0]
i
use
to
work
with
you
at
(u'match', 'NN')
See, for some reason, I lose the "NP".
Also, how do I determine if k[0] is a string or tuple (as in the case above)
| [
"Well you might have already found the answer. I am posting it for the people who might face this scenario in the future.\nfor subtree in chunked_sent.subtrees():\n if subtree.node == 'NP': print subtree\n\n"
] | [
0
] | [] | [] | [
"list",
"python",
"tuples",
"types",
"variables"
] | stackoverflow_0001896260_list_python_tuples_types_variables.txt |
Q:
Non-blocking class in python (detached Thread)
I'm trying to create a kind of non-blocking class in python, but I'm not sure how.
I'd like a class to be a thread itself, detached from the main thread so other threads can interact with it.
In a little example:
#!/usr/bin/python2.4
import threading
import time
class Sample(threading.Thread):
def __init__(self):
super(Sample, self).__init__()
self.status = 1
self.stop = False
def run(self):
while not(self.stop):
pass
def getStatus(self):
return self.status
def setStatus(self, status):
self.status = status
def test(self):
while self.status != 0:
time.sleep(2)
#main
sample = Sample()
sample.start()
sample.test()
sample.setStatus(0)
sample.stop()
What I'd like is having the "sample" instance running as a separate thread (detached from the main one) so, in the example, when the main thread reaches sample.test(), sample (and only "sample") would go to sleep for 2 seconds. In the meanwhile, the main thread would continue its execution and set sample's status to 0. When after the 2 seconds "sample" wakes up it would see the status=0 and exit the while loop.
The problem is that if I do this, the line sample.setStatus(0) is never reached (creating an infinite loop). I have named the threads, and it turns out that by doing this, test() is run by the main thread.
I guess I don't get the threading in python that well...
Thank you in advance
A:
The object's run() method is what executes in a separate thread. When you call sample.test(), that executes in the main thread, so you get your infinite loop.
A:
Perhaps something like this?
import threading
import time
class Sample(threading.Thread):
def __init__(self):
super(Sample, self).__init__()
self.stop = False
def run(self):
while not(self.stop):
print('hi')
time.sleep(.1)
def test(self):
print('testing...')
time.sleep(2)
#main
sample = Sample()
sample.start() # Initiates second thread which calls sample.run()
sample.test() # Main thread calls sample.test
sample.stop=True # Main thread sets sample.stop
sample.join() # Main thread waits for second thread to finish
| Non-blocking class in python (detached Thread) | I'm trying to create a kind of non-blocking class in python, but I'm not sure how.
I'd like a class to be a thread itself, detached from the main thread so other threads can interact with it.
In a little example:
#!/usr/bin/python2.4
import threading
import time
class Sample(threading.Thread):
def __init__(self):
super(Sample, self).__init__()
self.status = 1
self.stop = False
def run(self):
while not(self.stop):
pass
def getStatus(self):
return self.status
def setStatus(self, status):
self.status = status
def test(self):
while self.status != 0:
time.sleep(2)
#main
sample = Sample()
sample.start()
sample.test()
sample.setStatus(0)
sample.stop()
What I'd like is having the "sample" instance running as a separate thread (detached from the main one) so, in the example, when the main thread reaches sample.test(), sample (and only "sample") would go to sleep for 2 seconds. In the meanwhile, the main thread would continue its execution and set sample's status to 0. When after the 2 seconds "sample" wakes up it would see the status=0 and exit the while loop.
The problem is that if I do this, the line sample.setStatus(0) is never reached (creating an infinite loop). I have named the threads, and it turns out that by doing this, test() is run by the main thread.
I guess I don't get the threading in python that well...
Thank you in advance
| [
"The object's run() method is what executes in a separate thread. When you call sample.test(), that executes in the main thread, so you get your infinite loop.\n",
"Perhaps something like this?\nimport threading\nimport time\n\nclass Sample(threading.Thread):\n def __init__(self):\n super(Sample, self).... | [
4,
2
] | [] | [] | [
"multithreading",
"nonblocking",
"python"
] | stackoverflow_0003935094_multithreading_nonblocking_python.txt |
Q:
Beautiful Soup findAll() on the results of a findall() returns TypeError
Hi I'm new to both Python and Beautiful soup. I'm trying to get the text only from a certain part of a table. But it seems the result of a findAll is not a BeautifulSoup type that I can run findAll on again.
select = soup.find('table',{'id':"tp_section_1"})
print "got the right table"
tissues = select.findAll('td',{"class":re.compile("tissue[10]")})
print "got the right cells, now I'd like to get just the text"
tissueText = tissues.findAll(text = True)
The final line errors, with a TypeError. I seem to be able to run findAll on the result of a find but not findAll on the subsequent result. Is it because I need to do this element-wise?
For reference, the contents of tissues, before the final line look like this and I'm trying to extract the text such as "Adrenal gland":
<td valign="top" height="15" class="tissue1" nowrap>
<a class="tissue_link" href="normal_unit.php?antibody_id=20769&mainannotation_id=2065466">Adrenal gland</a> </td>
A:
Yes, you need to do it element-wise. find returns a single element. findAll returns a list, even if the list only contains one item.
| Beautiful Soup findAll() on the results of a findall() returns TypeError | Hi I'm new to both Python and Beautiful soup. I'm trying to get the text only from a certain part of a table. But it seems the result of a findAll is not a BeautifulSoup type that I can run findAll on again.
select = soup.find('table',{'id':"tp_section_1"})
print "got the right table"
tissues = select.findAll('td',{"class":re.compile("tissue[10]")})
print "got the right cells, now I'd like to get just the text"
tissueText = tissues.findAll(text = True)
The final line errors, with a TypeError. I seem to be able to run findAll on the result of a find but not findAll on the subsequent result. Is it because I need to do this element-wise?
For reference, the contents of tissues, before the final line look like this and I'm trying to extract the text such as "Adrenal gland":
<td valign="top" height="15" class="tissue1" nowrap>
<a class="tissue_link" href="normal_unit.php?antibody_id=20769&mainannotation_id=2065466">Adrenal gland</a> </td>
| [
"Yes, you need to do it element-wise. find returns a single element. findAll returns a list, even if the list only contains one item.\n"
] | [
3
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003935224_beautifulsoup_python.txt |
Q:
Django's equivalent to Rails 5 min blog demo
Some how some way I'm trying to get out of Ruby because things are just working and I don't necessarily know why. I'm taking the forest for the trees approach by which I mean I'm trying to get perspective by learning a new language; Python/Django seems to be the right way to go.
The first application I built in Rails was from the 5 min blog screencast by DHH and form there I was able to get by. I'm looking for a relevant resource for learning a Django application in particular I"m looking for a simple blog application.
A:
With a little bit of google-fu I turned up this relatively recent example:
Django Tutorial: A Simple Blog, Part 1
Django Tutorial: A Simple Blog, Part 2
A:
I would check out the official "writing your first..." tutorial on djangoproject.com: http://docs.djangoproject.com/en/dev/intro/tutorial01/
It's great and gets you started in no time.
A:
The Django site provides a tutorial on how to build a poll, which can be easily modified to build a blog. James Bennett's book, Practical Django Projects, also explains in significant detail how to build a blog/cms.
| Django's equivalent to Rails 5 min blog demo | Some how some way I'm trying to get out of Ruby because things are just working and I don't necessarily know why. I'm taking the forest for the trees approach by which I mean I'm trying to get perspective by learning a new language; Python/Django seems to be the right way to go.
The first application I built in Rails was from the 5 min blog screencast by DHH and form there I was able to get by. I'm looking for a relevant resource for learning a Django application in particular I"m looking for a simple blog application.
| [
"With a little bit of google-fu I turned up this relatively recent example:\n\nDjango Tutorial: A Simple Blog, Part 1\nDjango Tutorial: A Simple Blog, Part 2\n\n",
"I would check out the official \"writing your first...\" tutorial on djangoproject.com: http://docs.djangoproject.com/en/dev/intro/tutorial01/\nIt's ... | [
3,
2,
2
] | [] | [] | [
"blogs",
"django",
"python"
] | stackoverflow_0003935454_blogs_django_python.txt |
Q:
What is the most general python type to which I can add attributes?
I have a class Foo with a method isValid. Then I have a method bar() that receives a Foo object and whose behavior depends on whether it is valid or not.
For testing this, I wanted to pass some object to bar whose isValid method returns always False. For other reasons, I cannot create an object of Foo at the time of testing, so I needed an object to fake it. What I first thought of was creating the most general object and adding the attribute isValid to it, for using it as a Foo. But that didn't quite work:
>>> foo = object()
>>> foo.isValid = lambda : False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'isValid'
I found out object doesn't have a __dict__, so you cannot add attributes to it. At this point, the workaround I am using is creating a type on the fly for this purpose and then creating an object of that type:
>>> tmptype = type('tmptype', (), {'isValid' : lambda self : False})
>>> x = tmptype()
>>> x.isValid()
False
But this seems too long a shot. There must be some readily available general type that I could use for this purpose, but which?
A:
you have the right idea but you can make it more general. Either
tmptype = type('tmptype', (object,) {})
or
class tmptype(object):
pass
Then you can just do
foo = tmptype()
foo.is_valid = lambda: False
like you wanted to do with object. This way, you can use the same class for all of your dynamic, monky-patching needs.
A:
Just so that the right answer is stated and people don't have to read all the comments: There is no such type. It has been proposed, discussed, and the idea has been rejected. Here is the link that aaronasterling posted on a comment, where more can be read: http://mail.python.org/pipermail/python-bugs-list/2007-January/036866.html
A:
why do you have to have to make it complex? i think the most simple way (and the 'standard' way) is to do
class FakeFoo(object):
def is_valid():
return False
besides, the use of lambda is not good in this context... take a look at this:
http://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html
is by the BDFL
and so on...
| What is the most general python type to which I can add attributes? | I have a class Foo with a method isValid. Then I have a method bar() that receives a Foo object and whose behavior depends on whether it is valid or not.
For testing this, I wanted to pass some object to bar whose isValid method returns always False. For other reasons, I cannot create an object of Foo at the time of testing, so I needed an object to fake it. What I first thought of was creating the most general object and adding the attribute isValid to it, for using it as a Foo. But that didn't quite work:
>>> foo = object()
>>> foo.isValid = lambda : False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'isValid'
I found out object doesn't have a __dict__, so you cannot add attributes to it. At this point, the workaround I am using is creating a type on the fly for this purpose and then creating an object of that type:
>>> tmptype = type('tmptype', (), {'isValid' : lambda self : False})
>>> x = tmptype()
>>> x.isValid()
False
But this seems too long a shot. There must be some readily available general type that I could use for this purpose, but which?
| [
"you have the right idea but you can make it more general. Either \n tmptype = type('tmptype', (object,) {})\n\nor\n class tmptype(object):\n pass\n\nThen you can just do\nfoo = tmptype()\nfoo.is_valid = lambda: False\n\nlike you wanted to do with object. This way, you can use the same class for all of your dyn... | [
7,
4,
1
] | [] | [] | [
"attributes",
"object",
"python",
"types"
] | stackoverflow_0003933904_attributes_object_python_types.txt |
Q:
build recent numpy on recent ubuntu
How do I build numpy 1.5 on ubuntu 10.10?
The instructions I found seems outdated or not clear.
Thanks
A:
One way to try, which isn't guaranteed to work, but worth a shot is to see if uupdate can sucessfully update the package. Get a tarball of numpy 1.5. run "apt-get source numpy" which should fetch and unpack the current source from ubuntu. cd into this source directory and run "uupdate ../numpytarballname". This should update the old source package using the newer tarball. then you can try building with "apt-get build-dep numpy" and "dpkg-buildpackage -rfakeroot". This will require you have the build-essential and fakeroot packages installed.
A:
I used pip to install after getting the required compiler/build tools:
sudo apt-get -y install build-essential
wget http://python-distribute.org/distribute_setup.py && sudo python ./distribute_setup.py
sudo easy_install pip
sudo pip install numpy
I used easy_install to get pip and then pip to get numpy.
| build recent numpy on recent ubuntu | How do I build numpy 1.5 on ubuntu 10.10?
The instructions I found seems outdated or not clear.
Thanks
| [
"One way to try, which isn't guaranteed to work, but worth a shot is to see if uupdate can sucessfully update the package. Get a tarball of numpy 1.5. run \"apt-get source numpy\" which should fetch and unpack the current source from ubuntu. cd into this source directory and run \"uupdate ../numpytarballname\". ... | [
2,
1
] | [] | [] | [
"numpy",
"python",
"ubuntu"
] | stackoverflow_0003933923_numpy_python_ubuntu.txt |
Q:
Find and replace in CSV files with Python
Related to a previous question, I'm trying to do replacements over a number of large CSV files.
The column order (and contents) change between files, but for each file there are about 10 columns that I want and can identify by the column header names. I also have 1-2 dictionaries for each column I want. So for the columns I want, I want to use only the correct dictionaries and want to implement them sequentially.
An example of how I've tried to solve this:
# -*- coding: utf-8 -*-
import re
# imaginary csv file. pretend that we do not know the column order.
Header = [u'col1', u'col2']
Line1 = [u'A',u'X']
Line2 = [u'B',u'Y']
fileLines = [Line1,Line2]
# dicts to translate lines
D1a = {u'A':u'a'}
D1b = {u'B':u'b'}
D2 = {u'X':u'x',u'Y':u'y'}
# dict to correspond header names with the correct dictionary.
# i would like the dictionaries to be read sequentially in col1.
refD = {u'col1':[D1a,D1b],u'col2':[D2]}
# clunky replace function
def freplace(str, dict):
rc = re.compile('|'.join(re.escape(k) for k in dict))
def trans(m):
return dict[m.group(0)]
return rc.sub(trans, str)
# get correspondence between dictionary and column
C = []
for i in range(len(Header)):
if Header[i] in refD:
C.append([refD[Header[i]],i])
# loop through lines and make replacements
for line in fileLines:
for i in range(len(line)):
for j in range(len(C)):
if C[j][1] == i:
for dict in C[j][0]:
line[i] = freplace(line[i], dict)
My problem is that this code is quite slow, and I can't figure out how to speed it up. I'm a beginner, and my guess was that my freplace function is largely what is slowing things down, because it has to compile for each column in each row. I would like to take the line rc = re.compile('|'.join(re.escape(k) for k in dict)) out of that function, but don't know how to do that and still preserve what the rest of my code is doing.
A:
There's a ton of things that you can do to speed this up:
First, use the csv module. It provides efficient and bug-free methods for reading and writing CSV files. The DictReader object in particular is what you're interested in: it will present every row it reads from the file as a dictionary keyed by its column name.
Second, compile your regexes once, not every time you use them. Save the compiled regexes in a dictionary keyed by the column that you're going to apply them to.
Third, consider that if you apply a hundred regexes to a long string, you're going to be scanning the string from start to finish a hundred times. That may not be the best approach to your problem; you might be better off investing some time in an approach that lets you read the string from start to end once.
A:
You don't need re:
# -*- coding: utf-8 -*-
# imaginary csv file. pretend that we do not know the column order.
Header = [u'col1', u'col2']
Line1 = [u'A',u'X']
Line2 = [u'B',u'Y']
fileLines = [Line1,Line2]
# dicts to translate lines
D1a = {u'A':u'a'}
D1b = {u'B':u'b'}
D2 = {u'X':u'x',u'Y':u'y'}
# dict to correspond header names with the correct dictionary
refD = {u'col1':[D1a,D1b],u'col2':[D2]}
# now let's have some fun...
for line in fileLines:
for i, (param, word) in enumerate(zip(Header, line)):
for minitranslator in refD[param]:
if word in minitranslator:
line[i] = minitranslator[word]
returns:
[[u'a', u'x'], [u'b', u'y']]
A:
So if that's the case, and all 10 columns have the same names each time, but out of order, (I'm not sure if this is what you're doing up there, but here goes) keep one array for the heading names, and one for each column split into elements (should be 10 items each line), now just offset which regex by doing a case/select combo, compare the element number of your header array, then inside the case, reference the data array at the same offset, since the name is what will get to the right case you should be able to use the same 10 regex's repeatedly, and not have to recompile a new "command" each time.
I hope that makes sense. I'm sorry i don't know the syntax to help you out, but I hope my idea is what you're looking for
EDIT:
I.E.
initialize all regexes before starting your loops.
then after you read a line (and after the header line)
select array[n]
case "column1"
regex(data[0]);
case "column2"
regex(data[1]);
.
.
.
.
end select
This should call the right regex for the right columns
| Find and replace in CSV files with Python | Related to a previous question, I'm trying to do replacements over a number of large CSV files.
The column order (and contents) change between files, but for each file there are about 10 columns that I want and can identify by the column header names. I also have 1-2 dictionaries for each column I want. So for the columns I want, I want to use only the correct dictionaries and want to implement them sequentially.
An example of how I've tried to solve this:
# -*- coding: utf-8 -*-
import re
# imaginary csv file. pretend that we do not know the column order.
Header = [u'col1', u'col2']
Line1 = [u'A',u'X']
Line2 = [u'B',u'Y']
fileLines = [Line1,Line2]
# dicts to translate lines
D1a = {u'A':u'a'}
D1b = {u'B':u'b'}
D2 = {u'X':u'x',u'Y':u'y'}
# dict to correspond header names with the correct dictionary.
# i would like the dictionaries to be read sequentially in col1.
refD = {u'col1':[D1a,D1b],u'col2':[D2]}
# clunky replace function
def freplace(str, dict):
rc = re.compile('|'.join(re.escape(k) for k in dict))
def trans(m):
return dict[m.group(0)]
return rc.sub(trans, str)
# get correspondence between dictionary and column
C = []
for i in range(len(Header)):
if Header[i] in refD:
C.append([refD[Header[i]],i])
# loop through lines and make replacements
for line in fileLines:
for i in range(len(line)):
for j in range(len(C)):
if C[j][1] == i:
for dict in C[j][0]:
line[i] = freplace(line[i], dict)
My problem is that this code is quite slow, and I can't figure out how to speed it up. I'm a beginner, and my guess was that my freplace function is largely what is slowing things down, because it has to compile for each column in each row. I would like to take the line rc = re.compile('|'.join(re.escape(k) for k in dict)) out of that function, but don't know how to do that and still preserve what the rest of my code is doing.
| [
"There's a ton of things that you can do to speed this up:\nFirst, use the csv module. It provides efficient and bug-free methods for reading and writing CSV files. The DictReader object in particular is what you're interested in: it will present every row it reads from the file as a dictionary keyed by its colu... | [
3,
1,
0
] | [] | [] | [
"csv",
"dictionary",
"function",
"performance",
"python"
] | stackoverflow_0003934133_csv_dictionary_function_performance_python.txt |
Q:
xapian-bindings python compatibility
i am able to get xapian working as expected with python on my development server but i am having issues with my web server.
i keep running into this error:
import xapian
Traceback (most recent call last):
File "", line 1, in
File "/home/x/lib/python2.6/xapian/init.py", line 28, in
_xapian = swig_import_helper()
File "/home/x/lib/python2.6/xapian/init.py", line 27, in swig_import_helper
return _mod
UnboundLocalError: local variable '_mod' referenced before assignment
i installed the latest copy of swig and reinstalled both xapian core and xapian-bindings but the error persists.
any ideas are greatly appreciated.
A:
I believe the problem here will be in the installation of the xapian-bindings package.
The xapian bindings for Python consist of two parts - a part written in python, and a compiled module. You've clearly installed the python part successfully (ie, /home/x/lib/python2.6/xapian/init.py), but when the python part attempts to load the compiled module, it fails to import it.
Unfortunately, a bug (possibly in swig) is causing another error to be thrown, so you don't see the exception from the failed import. To see the import error, remove line 27 of modern/xapian.py; ie, change it from reading:
try:
_mod = imp.load_module('_xapian', fp, pathname, description)
finally:
fp.close()
return _mod
to reading:
try:
_mod = imp.load_module('_xapian', fp, pathname, description)
finally:
fp.close()
You don't say how you've installed xapian-bindings, what platform you're on, or what version of Xapian you're using, so I can't really speculate how you've got into this state. Hopefully, the full exception will be enlightening.
| xapian-bindings python compatibility | i am able to get xapian working as expected with python on my development server but i am having issues with my web server.
i keep running into this error:
import xapian
Traceback (most recent call last):
File "", line 1, in
File "/home/x/lib/python2.6/xapian/init.py", line 28, in
_xapian = swig_import_helper()
File "/home/x/lib/python2.6/xapian/init.py", line 27, in swig_import_helper
return _mod
UnboundLocalError: local variable '_mod' referenced before assignment
i installed the latest copy of swig and reinstalled both xapian core and xapian-bindings but the error persists.
any ideas are greatly appreciated.
| [
"I believe the problem here will be in the installation of the xapian-bindings package.\nThe xapian bindings for Python consist of two parts - a part written in python, and a compiled module. You've clearly installed the python part successfully (ie, /home/x/lib/python2.6/xapian/init.py), but when the python part ... | [
3
] | [] | [] | [
"python",
"swig",
"xapian"
] | stackoverflow_0003936138_python_swig_xapian.txt |
Q:
Python "++" operator doesn't work
Possible Duplicate:
Python: Behaviour of increment and decrement operators
Hi, I've tried this.
++num
and the num doesn't change at all, always show the value when initialized
if I change ++num to num+=1 then it works.
So, my question is how that ++ operator works?
A:
There isn't a ++ operator in python. You're applying unary + twice to the variable.
A:
Answer: there is no ++ operator in Python. += 1 is the correct way to increment a number, but note that since integers and floats are immutable in Python,
>>> a = 2
>>> b = a
>>> a += 2
>>> b
2
>>> a
4
This behavior is different from that of a mutable object, where b would also be changed after the operation:
>>> a = [1]
>>> b = a
>>> a += [2]
>>> b
[1, 2]
>>> a
[1, 2]
| Python "++" operator doesn't work |
Possible Duplicate:
Python: Behaviour of increment and decrement operators
Hi, I've tried this.
++num
and the num doesn't change at all, always show the value when initialized
if I change ++num to num+=1 then it works.
So, my question is how that ++ operator works?
| [
"There isn't a ++ operator in python. You're applying unary + twice to the variable.\n",
"Answer: there is no ++ operator in Python. += 1 is the correct way to increment a number, but note that since integers and floats are immutable in Python,\n>>> a = 2\n>>> b = a\n>>> a += 2\n>>> b\n2\n>>> a\n4\n\nThis behavi... | [
27,
14
] | [] | [] | [
"operator_keyword",
"python"
] | stackoverflow_0003936691_operator_keyword_python.txt |
Q:
C / Python ctypes shared object introspection libraries/techniques
I was looking for a way to list .text section defined symbols on a C shared object loaded on a python program using the ctypes wrapper. In other words, i am trying to get a list of defined functions on a CDLL loaded object.
If there is no way to do this with ctypes or library ( or python binding ), another option is a python elf parsing library or a solution like http://halflifelibrary.com/wiki/Metamod-P.
Any way to do this ?
A:
Adding to the list of methods that you are trying to use to get the list of functions that is exported by the dll.
There is a script at : http://projects.scipy.org/numpy/wiki/MicrosoftToolchainSupport that dumps the symbol tables of the dll, parses it to get the public table and output the table into a .def file. It also says that this may not work if the dll is stripped.
I am not sure if there are good ELF parsers out there in Python. Adding some that I have found.
http://code.google.com/p/syn-code/source/browse/trunk/freezedis.py
A:
FYI there is no way to get a list of defined methods on a shared object loaded using ctypes because there is no meta information on the object structure.
If you need a platform specific object parser maybe you should take a look at http://projects.scipy.org/numpy/wiki/MicrosoftToolchainSupport using the objdump routines to get defined function references on the text section.
My option do this is to write a small parser using a ELF parser library like Hachoir or the Pydevtools in order to introspect the object.
| C / Python ctypes shared object introspection libraries/techniques | I was looking for a way to list .text section defined symbols on a C shared object loaded on a python program using the ctypes wrapper. In other words, i am trying to get a list of defined functions on a CDLL loaded object.
If there is no way to do this with ctypes or library ( or python binding ), another option is a python elf parsing library or a solution like http://halflifelibrary.com/wiki/Metamod-P.
Any way to do this ?
| [
"Adding to the list of methods that you are trying to use to get the list of functions that is exported by the dll.\nThere is a script at : http://projects.scipy.org/numpy/wiki/MicrosoftToolchainSupport that dumps the symbol tables of the dll, parses it to get the public table and output the table into a .def file.... | [
1,
0
] | [] | [] | [
"ctypes",
"object",
"python",
"shared"
] | stackoverflow_0003936190_ctypes_object_python_shared.txt |
Q:
Python lxml.html linebreaks?
Im using lxml.html.cleaner to clean html from an input text. how can i change \n to <br /> in lxml.html?
A:
Fairly easy, slightly hacky way: You could do this as part of a two step process, assuming you have used lxml.html.parse or whichever method to build DOM.
iterate through the text and tail attributes of the nodes with string replacements. Look at the iterdescendants method, which walks through everything for you.
lxml.html.clean as per normal
A more complex way would be to monkey patch the lxml.html.clean module. Unlike lots of lxml, this module is written in Python and is fairly accessible. For example, there is currently a _substitute_whitespace function.
| Python lxml.html linebreaks? | Im using lxml.html.cleaner to clean html from an input text. how can i change \n to <br /> in lxml.html?
| [
"Fairly easy, slightly hacky way: You could do this as part of a two step process, assuming you have used lxml.html.parse or whichever method to build DOM. \n\niterate through the text and tail attributes of the nodes with string replacements. Look at the iterdescendants method, which walks through everything for y... | [
1
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0003936754_lxml_python.txt |
Q:
What is the Python equivalent of Perl's backticks?
Possible Duplicate:
Equivalent of Backticks in Python
When I want to write directly to the command prompt in Perl, I can do something like this:
Perl File test.pl:
$directory = `dir`;
print $directory;
Which would output something like..
C:\Documents and
Settings\joslim\Desktop>perl test.pl
Volume in drive C has no label.
Volume Serial Number is EC37-EB31
Directory of C:\Documents and
Settings\joslim\Desktop
(and a listing of all the files..)
Can I do this in Python? I've searched around but have had no luck.
Also, can you tell me what this is called? I'm sure there's a more technical term than "writing directly to the command prompt"...
A:
What you are referring to in Perl is the backtick operator, which also behaves identically in PHP.
What you are looking to achieve is to execute a command line operation.
The equivalent in Python of the backtick operator, and how to run a command line program and retrieve the output, has been answered in: Equivalent of Backticks in Python
A:
The equivalent is commands.getoutput. So for your example:
import commands
directory = commands.getoutput("dir")
print directory
| What is the Python equivalent of Perl's backticks? |
Possible Duplicate:
Equivalent of Backticks in Python
When I want to write directly to the command prompt in Perl, I can do something like this:
Perl File test.pl:
$directory = `dir`;
print $directory;
Which would output something like..
C:\Documents and
Settings\joslim\Desktop>perl test.pl
Volume in drive C has no label.
Volume Serial Number is EC37-EB31
Directory of C:\Documents and
Settings\joslim\Desktop
(and a listing of all the files..)
Can I do this in Python? I've searched around but have had no luck.
Also, can you tell me what this is called? I'm sure there's a more technical term than "writing directly to the command prompt"...
| [
"What you are referring to in Perl is the backtick operator, which also behaves identically in PHP.\nWhat you are looking to achieve is to execute a command line operation.\nThe equivalent in Python of the backtick operator, and how to run a command line program and retrieve the output, has been answered in: Equiva... | [
6,
3
] | [] | [] | [
"cmd",
"perl",
"python",
"terminal"
] | stackoverflow_0003936982_cmd_perl_python_terminal.txt |
Q:
Add repository url to install_requires in project's setup.py
I'm developing a django app which depends on an app in a private
bitbucket repository, for example ssh:/...@bitbucket.org/username/my-django-app.
is it possible to add this url to the list of install_requires in my
setup.py? tried various possibilities, but none worked.
A:
I don't know if you can do this with setuptools, but it's possible with distribute (wich can be consider as the new setuptools). Check Dependencies that aren’t in PyPI sections in distribute documentation.
| Add repository url to install_requires in project's setup.py | I'm developing a django app which depends on an app in a private
bitbucket repository, for example ssh:/...@bitbucket.org/username/my-django-app.
is it possible to add this url to the list of install_requires in my
setup.py? tried various possibilities, but none worked.
| [
"I don't know if you can do this with setuptools, but it's possible with distribute (wich can be consider as the new setuptools). Check Dependencies that aren’t in PyPI sections in distribute documentation.\n"
] | [
5
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0003880605_python_setuptools.txt |
Q:
nltk custom tokenizer and tagger
Here is my requirement. I want to tokenize and tag a paragraph in such a way that it allows me to achieve following stuffs.
Should identify date and time in the paragraph and Tag them as DATE and TIME
Should identify known phrases in the paragraph and Tag them as CUSTOM
And rest content should be tokenized should be tokenized by the default nltk's word_tokenize and pos_tag functions?
For example, following sentense
"They all like to go there on 5th November 2010, but I am not interested."
should be tagged and tokenized as follows in case of that custom phrase is "I am not interested".
[('They', 'PRP'), ('all', 'VBP'), ('like', 'IN'), ('to', 'TO'), ('go', 'VB'),
('there', 'RB'), ('on', 'IN'), ('5th November 2010', 'DATE'), (',', ','),
('but', 'CC'), ('I am not interested', 'CUSTOM'), ('.', '.')]
Any suggestions would be useful.
A:
The proper answer is to compile a large dataset tagged in the way you want, then train a machine learned chunker on it. If that's too time-consuming, the easy way is to run the POS tagger and post-process its output using regular expressions. Getting the longest match is the hard part here:
s = "They all like to go there on 5th November 2010, but I am not interested."
DATE = re.compile(r'^[1-9][0-9]?(th|st|rd)? (January|...)( [12][0-9][0-9][0-9])?$')
def custom_tagger(sentence):
tagged = pos_tag(word_tokenize(sentence))
phrase = []
date_found = False
i = 0
while i < len(tagged):
(w,t) = tagged[i]
phrase.append(w)
in_date = DATE.match(' '.join(phrase))
date_found |= bool(in_date)
if date_found and not in_date: # end of date found
yield (' '.join(phrase[:-1]), 'DATE')
phrase = []
date_found = False
elif date_found and i == len(tagged)-1: # end of date found
yield (' '.join(phrase), 'DATE')
return
else:
i += 1
if not in_date:
yield (w,t)
phrase = []
Todo: expand the DATE re, insert code to search for CUSTOM phrases, make this more sophisticated by matching POS tags as well as tokens and decide whether 5th on its own should count as a date. (Probably not, so filter out dates of length one that only contain an ordinal number.)
A:
You should probably do chunking with the nltk.RegexpParser to achieve your objective.
Reference:
http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html#code-chunker1
| nltk custom tokenizer and tagger | Here is my requirement. I want to tokenize and tag a paragraph in such a way that it allows me to achieve following stuffs.
Should identify date and time in the paragraph and Tag them as DATE and TIME
Should identify known phrases in the paragraph and Tag them as CUSTOM
And rest content should be tokenized should be tokenized by the default nltk's word_tokenize and pos_tag functions?
For example, following sentense
"They all like to go there on 5th November 2010, but I am not interested."
should be tagged and tokenized as follows in case of that custom phrase is "I am not interested".
[('They', 'PRP'), ('all', 'VBP'), ('like', 'IN'), ('to', 'TO'), ('go', 'VB'),
('there', 'RB'), ('on', 'IN'), ('5th November 2010', 'DATE'), (',', ','),
('but', 'CC'), ('I am not interested', 'CUSTOM'), ('.', '.')]
Any suggestions would be useful.
| [
"The proper answer is to compile a large dataset tagged in the way you want, then train a machine learned chunker on it. If that's too time-consuming, the easy way is to run the POS tagger and post-process its output using regular expressions. Getting the longest match is the hard part here:\ns = \"They all like to... | [
7,
2
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0003930267_nlp_nltk_python.txt |
Q:
How do I use rstrip to remove trailing characters?
I am trying to loop through a bunch of documents I have to put each word in a list for that document. I am doing it like this. stoplist is just a list of words that I want to ignore by default.
texts = [[word for word in document.lower().split() if word not in stoplist]
for document in documents]
I am returned with a list of documents, and in each of those lists, is a list of words. Some of the words still contain the trailing punctuation or other anomalies. I thought I could do this, but it doesn't seem to be working right
texts = [[word.rstrip() for word in document.lower().split() if word not in stoplist]
for document in documents]
Or
texts = [[word.rstrip('.,:!?:') for word in document.lower().split() if word not in stoplist]
for document in documents]
My other question is this. I may see words like this where I want to keep the word, but dump the trailing numbers / special characters.
agency[15]
assignment[72],
you’ll
america’s
So to clean up most of the other noise, I was thinking I should keep removing characters from the end of a string until it's a-zA-Z or if there is more special characters than alpha chars in a string, toss it. You can see though in my last two examples, the end of the string is an alpha character. So in those cases, I should just ignore the word because of the amount of special chars (more than alpha chars). I was thinking I should just search the end of strings because I would like to keep hyphenated words intact if possible.
Basically I want to remove all trailing punctuation on each word, and possibly a subroutine that handles the cases I just described. I am not sure how to do that or if its the best way.
A:
>>> a = ['agency[15]','assignment72,','you’11','america’s']
>>> import re
>>> b = re.compile('\w+')
>>> for item in a:
... print b.search(item).group(0)
...
agency
assignment72
you
america
>>> b = re.compile('[a-z]+')
>>> for item in a:
... print b.search(item).group(0)
...
agency
assignment
you
america
>>>
Update
>>> a = "I-have-hyphens-yo!"
>>> re.findall('[a-z]+',a)
['have', 'hyphens', 'yo']
>>> re.findall('[a-z-]+',a)
['-have-hyphens-yo']
>>> re.findall('[a-zA-Z-]+',a)
['I-have-hyphens-yo']
>>> re.findall('\w+',a)
['I', 'have', 'hyphens', 'yo']
>>>
A:
Maybe try re.findall instead, with a pattern like [a-z]+:
import re
word_re = re.compile(r'[a-z]+')
texts = [[match.group(0) for match in word_re.finditer(document.lower()) if match.group(0) not in stoplist]
for document in documents]
texts = [[word for word in word_re.findall(document.lower()) if word not in stoplist]
for document in documents]
You can then easily tweak your regular expression to get the words you want. Alternate version uses re.split:
import re
word_re = re.compile(r'[^a-z]+')
texts = [[word for word in word_re.split(document.lower()) if word and word not in stoplist]
for document in documents]
| How do I use rstrip to remove trailing characters? | I am trying to loop through a bunch of documents I have to put each word in a list for that document. I am doing it like this. stoplist is just a list of words that I want to ignore by default.
texts = [[word for word in document.lower().split() if word not in stoplist]
for document in documents]
I am returned with a list of documents, and in each of those lists, is a list of words. Some of the words still contain the trailing punctuation or other anomalies. I thought I could do this, but it doesn't seem to be working right
texts = [[word.rstrip() for word in document.lower().split() if word not in stoplist]
for document in documents]
Or
texts = [[word.rstrip('.,:!?:') for word in document.lower().split() if word not in stoplist]
for document in documents]
My other question is this. I may see words like this where I want to keep the word, but dump the trailing numbers / special characters.
agency[15]
assignment[72],
you’ll
america’s
So to clean up most of the other noise, I was thinking I should keep removing characters from the end of a string until it's a-zA-Z or if there is more special characters than alpha chars in a string, toss it. You can see though in my last two examples, the end of the string is an alpha character. So in those cases, I should just ignore the word because of the amount of special chars (more than alpha chars). I was thinking I should just search the end of strings because I would like to keep hyphenated words intact if possible.
Basically I want to remove all trailing punctuation on each word, and possibly a subroutine that handles the cases I just described. I am not sure how to do that or if its the best way.
| [
">>> a = ['agency[15]','assignment72,','you’11','america’s']\n>>> import re\n>>> b = re.compile('\\w+')\n>>> for item in a:\n... print b.search(item).group(0)\n...\nagency\nassignment72\nyou\namerica\n>>> b = re.compile('[a-z]+')\n>>> for item in a:\n... print b.search(item).group(0)\n...\nagenc... | [
3,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003937273_python_regex_string.txt |
Q:
What does raise in Python raise?
Consider the following code:
try:
raise Exception("a")
except:
try:
raise Exception("b")
finally:
raise
This will raise Exception: a. I expected it to raise Exception: b (need I explain why?). Why does the final raise raise the original exception rather than (what I thought) was the last exception raised?
A:
Raise is re-raising the last exception you caught, not the last exception you raised
(reposted from comments for clarity)
A:
On python2.6
I guess, you are expecting the finally block to be tied with the "try" block where you raise the exception "B". The finally block is attached to the first "try" block.
If you added an except block in the inner try block, then the finally block will raise exception B.
try:
raise Exception("a")
except:
try:
raise Exception("b")
except:
pass
finally:
raise
Output:
Traceback (most recent call last):
File "test.py", line 5, in <module>
raise Exception("b")
Exception: b
Another variation that explains whats happening here
try:
raise Exception("a")
except:
try:
raise Exception("b")
except:
raise
Output:
Traceback (most recent call last):
File "test.py", line 7, in <module>
raise Exception("b")
Exception: b
If you see here, replacing the finally block with except does raise the exception B.
| What does raise in Python raise? | Consider the following code:
try:
raise Exception("a")
except:
try:
raise Exception("b")
finally:
raise
This will raise Exception: a. I expected it to raise Exception: b (need I explain why?). Why does the final raise raise the original exception rather than (what I thought) was the last exception raised?
| [
"\nRaise is re-raising the last exception you caught, not the last exception you raised\n\n(reposted from comments for clarity)\n",
"On python2.6\nI guess, you are expecting the finally block to be tied with the \"try\" block where you raise the exception \"B\". The finally block is attached to the first \"try\" ... | [
28,
14
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0003935603_exception_python.txt |
Q:
elegant way to match two wildcarded strings
I'm OCRing some text from two different sources. They can each make mistakes in different places, where they won't recognize a letter/group of letters. If they don't recognize something, it's replaced with a ?. For example, if the word is Roflcopter, one source might return Ro?copter, while another, Roflcop?er. I'd like a function that returns whether two matches might be equivalent, allowing for multiple ?s. Example:
match("Ro?copter", "Roflcop?er") --> True
match("Ro?copter", "Roflcopter") --> True
match("Roflcopter", "Roflcop?er") --> True
match("Ro?co?er", "Roflcop?er") --> True
So far I can match one OCR with a perfect one by using regular expressions:
>>> def match(tn1, tn2):
tn1re = tn1.replace("?", ".{0,4}")
tn2re = tn2.replace("?", ".{0,4}")
return bool(re.match(tn1re, tn2) or re.match(tn2re, tn1))
>>> match("Roflcopter", "Roflcop?er")
True
>>> match("R??lcopter", "Roflcopter")
True
But this doesn't work when they both have ?s in different places:
>>> match("R??lcopter", "Roflcop?er")
False
A:
Well, as long as one ? corresponds to one character, then I can suggest a performant and a compact enough method.
def match(str1, str2):
if len(str1) != len(str2): return False
for index, ch1 in enumerate(str1):
ch2 = str2[index]
if ch1 == '?' or ch2 == '?': continue
if ch1 != ch2: return False
return True
>>> ================================ RESTART ================================
>>>
>>> match("Roflcopter", "Roflcop?er")
True
>>> match("R??lcopter", "Roflcopter")
True
>>>
>>> match("R??lcopter", "Roflcop?er")
True
>>>
Edit: Part B), brain-fart free now.
def sets_match(set1, set2):
return any(match(str1, str2) for str1 in set1 for str2 in set2)
>>> ================================ RESTART ================================
>>>
>>> s1 = set(['a?', 'fg'])
>>> s2 = set(['?x'])
>>> sets_match(s1, s2) # a? = x?
True
>>>
A:
Thanks to Hamish Grubijan for this idea. Every ? in my ocr'd names can be anywhere from 0 to 3 letters. What I do is expand each string to a list of possible expansions:
>>> list(expQuestions("?flcopt?"))
['flcopt', 'flcopt@', 'flcopt@@', 'flcopt@@@', '@flcopt', '@flcopt@', '@flcopt@@', '@flcopt@@@', '@@flcopt', '@@flcopt@', '@@flcopt@@', '@@flcopt@@@', '@@@flcopt', '@@@flcopt@', '@@@flcopt@@', '@@@flcopt@@@']
then I expand both and use his matching function, which I called matchats:
def matchOCR(l, r):
for expl in expQuestions(l):
for expr in expQuestions(r):
if matchats(expl, expr):
return True
return False
Works as desired:
>>> matchOCR("Ro?co?er", "?flcopt?")
True
>>> matchOCR("Ro?co?er", "?flcopt?z")
False
>>> matchOCR("Ro?co?er", "?flc?pt?")
True
>>> matchOCR("Ro?co?e?", "?flc?pt?")
True
The matching function:
def matchats(l, r):
"""Match two strings with @ representing exactly 1 char"""
if len(l) != len(r): return False
for i, c1 in enumerate(l):
c2 = r[i]
if c1 == "@" or c2 == "@": continue
if c1 != c2: return False
return True
and the expanding function, where cartesian_product does just that:
def expQuestions(s):
"""For OCR w/ a questionmark in them, expand questions with
@s for all possibilities"""
numqs = s.count("?")
blah = list(s)
for expqs in cartesian_product([(0,1,2,3)]*numqs):
newblah = blah[:]
qi = 0
for i,c in enumerate(newblah):
if newblah[i] == '?':
newblah[i] = '@'*expqs[qi]
qi += 1
yield "".join(newblah)
A:
Using the Levenshtein distance may be useful. It will give a value of how similar the strings are to each other. This will work if they are different lengths, too. The linked page has some psuedocode to get you started.
You'll end up with something like this:
>>> match("Roflcopter", "Roflcop?er")
1
>>> match("R??lcopter", "Roflcopter")
2
>>> match("R?lcopter", "Roflcop?er")
3
So you could have a maximum threshold below which you say they may match.
A:
This might not be the most Pythonic of options, but if a ? is allowed to match any number of characters, then the following backtracking search does the trick:
def match(a,b):
def matcher(i,j):
if i == len(a) and j == len(b):
return True
elif i < len(a) and a[i] == '?' \
or j < len(b) and b[j] == '?':
return i < len(a) and matcher(i+1,j) \
or j < len(b) and matcher(i,j+1)
elif i == len(a) or j == len(b):
return False
else:
return a[i] == b[j] and matcher(i+1,j+1)
return matcher(0,0)
This may be adapted to be more stringent in what to match. Also, to save stack space, the final case (i+1,j+1) may be transformed into a non-recursive solution.
Edit: some more clarification in response to the reactions below. This is an adaptation of a naive matching algorithm for simplified regexes/NFAs (see Kernighan's contrib to Beautiful Code, O'Reilly 2007 or Jurafsky & Martin, Speech and Language Processing, Prentice Hall 2009).
How it works: the matcher function recursively walks through both strings/patterns, starting at (0,0). It succeeds when it reaches the end of both strings (len(a),len(b)); it fails when it encounters two unequal characters or the end of one string while there are still characters to match in the other string.
When matcher encounters a variable (?) in either string (say a), it can do two things: either skip over the variable (matching zero characters), or skip over the next character in b but keep pointing to the variable in a, allowing it to match more characters.
| elegant way to match two wildcarded strings | I'm OCRing some text from two different sources. They can each make mistakes in different places, where they won't recognize a letter/group of letters. If they don't recognize something, it's replaced with a ?. For example, if the word is Roflcopter, one source might return Ro?copter, while another, Roflcop?er. I'd like a function that returns whether two matches might be equivalent, allowing for multiple ?s. Example:
match("Ro?copter", "Roflcop?er") --> True
match("Ro?copter", "Roflcopter") --> True
match("Roflcopter", "Roflcop?er") --> True
match("Ro?co?er", "Roflcop?er") --> True
So far I can match one OCR with a perfect one by using regular expressions:
>>> def match(tn1, tn2):
tn1re = tn1.replace("?", ".{0,4}")
tn2re = tn2.replace("?", ".{0,4}")
return bool(re.match(tn1re, tn2) or re.match(tn2re, tn1))
>>> match("Roflcopter", "Roflcop?er")
True
>>> match("R??lcopter", "Roflcopter")
True
But this doesn't work when they both have ?s in different places:
>>> match("R??lcopter", "Roflcop?er")
False
| [
"Well, as long as one ? corresponds to one character, then I can suggest a performant and a compact enough method.\ndef match(str1, str2):\n if len(str1) != len(str2): return False\n for index, ch1 in enumerate(str1):\n ch2 = str2[index]\n if ch1 == '?' or ch2 == '?': continue\n if ch1 !=... | [
2,
2,
1,
1
] | [] | [] | [
"python",
"regex",
"string",
"string_matching"
] | stackoverflow_0003936566_python_regex_string_string_matching.txt |
Q:
Python Method Placement
Can someone give me a solution to this
dosomething()
def dosomething():
print 'do something'
I don't want my method defines up at the top of the file, is there a way around this?
A:
The "standard" way is to do things inside a main function at the top of your file and then call main() at the bottom. E.g.
def main():
print 'doing stuff'
foo()
bar()
def foo():
print 'inside foo'
def bar():
print 'inside bar'
if __name__ == '__main__':
main()
if if __name__ == '__main__': part ensures that main() won't be called if the file is imported into another python program, but is only called when the file is run directly.
Of course, "main" doesn't mean anything... (__main__ does, however!) It's a psuedo-convention, but you could just as well call it do_stuff, and then have if __name__ == '__main__': do_stuff() at the bottom.
Edit: You might also want to see Guido's advice on writing main's. Also, Daenyth makes an excellent point (and beat me to answering): The reason why you should do something like this isn't that is "standard" or even that it allows you to define functions below your "main" code. The reason you should do it is that it encourages you to write modular and reusable code.
A:
Aside from adding the definition of dosomething to a separate file and importing it:
from my_module import dosomething
dosomething()
I don't believe there is any other way ... but I could be wrong.
| Python Method Placement | Can someone give me a solution to this
dosomething()
def dosomething():
print 'do something'
I don't want my method defines up at the top of the file, is there a way around this?
| [
"The \"standard\" way is to do things inside a main function at the top of your file and then call main() at the bottom. E.g. \ndef main():\n print 'doing stuff'\n foo()\n bar()\n\ndef foo():\n print 'inside foo'\n\ndef bar():\n print 'inside bar'\n\nif __name__ == '__main__':\n main()\n\nif if __... | [
13,
3
] | [] | [] | [
"python"
] | stackoverflow_0003937450_python.txt |
Q:
accessing python dictionary
I am writing code that will search twitter for key words and store them in a python dictionary:
base_url = 'http://search.twitter.com/search.json?rpp=100&q=4sq.com/'
query = '7bOHRP'
url_string = base_url + query
logging.info("url string = " + url_string)
json_text = fetch(url_string)
json_response = simplejson.loads(json_text.content)
result = json_response['results']
print "Contents"
print result
The resulting dictionary is :
Contents[{
u 'iso_language_code': u 'en',
u 'text': u "I'm at Cafe en Seine (40 Dawson Street, Dublin) w/ 2 others. http://4sq.com/7bOHRP",
u 'created_at': u 'Wed, 06 Oct 2010 23:37:02 +0000',
u 'profile_image_url': u 'http://a1.twimg.com/profile_images/573130785/twitterProfilePhoto_normal.jpg',
u 'source': u '<a href="http://foursquare.com" rel="nofollow">foursquare</a>',
u 'place': {
u 'type': u 'neighborhood',
u 'id': u '898cf727ca504e96',
u 'full_name': u 'Mansion House B, Dublin'
},
u 'from_user': u 'pkerssemakers',
u 'from_user_id': 60241195,
u 'to_user_id': None,
u 'geo': None,
u 'id': 26597357992,
u 'metadata': {
u 'result_type': u 'recent'
}
}]
Status: 200 OK
Content - Type: text / html;charset = utf - 8
Cache - Control: no - cache
Expires: Fri, 01 Jan 1990 00: 00: 00 GMT
Content - Length: 0
How can I access the 'from_user' and what is the 'u' before the key and value?
A:
result[0][u'from_user']
The u prefix means that it's a unicode instead of a str.
A:
You access the item ala
print Contents['from_user']
The 'u' in front of the string indicates that the string is uni-code.
A:
note that in Python 3.x you don't need the 'u' before the string 'cause all the string are unicode object...
this can be obtained also in Python 2.x, just put at the top of your code
from __future__ import unicode_literals
A:
Since the item returned is a list containing a dictionary you would do:
print Contents[0]['from_user']
The u is for unicode and you do not need to mention that when you access the data. Python takes care of that.
Since the data returned is in a dictionary itself the final statement would be
print result['Contents'][0]['from_user']
| accessing python dictionary | I am writing code that will search twitter for key words and store them in a python dictionary:
base_url = 'http://search.twitter.com/search.json?rpp=100&q=4sq.com/'
query = '7bOHRP'
url_string = base_url + query
logging.info("url string = " + url_string)
json_text = fetch(url_string)
json_response = simplejson.loads(json_text.content)
result = json_response['results']
print "Contents"
print result
The resulting dictionary is :
Contents[{
u 'iso_language_code': u 'en',
u 'text': u "I'm at Cafe en Seine (40 Dawson Street, Dublin) w/ 2 others. http://4sq.com/7bOHRP",
u 'created_at': u 'Wed, 06 Oct 2010 23:37:02 +0000',
u 'profile_image_url': u 'http://a1.twimg.com/profile_images/573130785/twitterProfilePhoto_normal.jpg',
u 'source': u '<a href="http://foursquare.com" rel="nofollow">foursquare</a>',
u 'place': {
u 'type': u 'neighborhood',
u 'id': u '898cf727ca504e96',
u 'full_name': u 'Mansion House B, Dublin'
},
u 'from_user': u 'pkerssemakers',
u 'from_user_id': 60241195,
u 'to_user_id': None,
u 'geo': None,
u 'id': 26597357992,
u 'metadata': {
u 'result_type': u 'recent'
}
}]
Status: 200 OK
Content - Type: text / html;charset = utf - 8
Cache - Control: no - cache
Expires: Fri, 01 Jan 1990 00: 00: 00 GMT
Content - Length: 0
How can I access the 'from_user' and what is the 'u' before the key and value?
| [
"result[0][u'from_user']\n\nThe u prefix means that it's a unicode instead of a str.\n",
"You access the item ala\nprint Contents['from_user']\n\nThe 'u' in front of the string indicates that the string is uni-code.\n",
"note that in Python 3.x you don't need the 'u' before the string 'cause all the string are ... | [
11,
1,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003933478_dictionary_python.txt |
Q:
what is the concept of store in OpenID
Hi so this is what I understand how Openid works:-
the user enters his openid url on the site say"hii.com"
The app does a redirect to the openid provider and either does the login or denies it and sends the response back to the site i.e"hii.com"
If authentication was succesful then the response object provided by the openid provider can contain other data too like email etc if "hii.com" had requested for it.
I can save this data in the database.
Please correct me if I am wrong. However what I am not understanding here is the concept of stores. I see openid.store.filestore,nonce,sqlstore. Could someone please provide some clarity on it. What role does this store play here.
I have gone through python openid docs but end up feeling clueless.
Thanks
A:
upd.: my previous answer was wrong
The store you are referring to is where your app stores the data during auth.
Storing it in a shared memcached instance should be the best option (faster than db and reliable enough).
| what is the concept of store in OpenID | Hi so this is what I understand how Openid works:-
the user enters his openid url on the site say"hii.com"
The app does a redirect to the openid provider and either does the login or denies it and sends the response back to the site i.e"hii.com"
If authentication was succesful then the response object provided by the openid provider can contain other data too like email etc if "hii.com" had requested for it.
I can save this data in the database.
Please correct me if I am wrong. However what I am not understanding here is the concept of stores. I see openid.store.filestore,nonce,sqlstore. Could someone please provide some clarity on it. What role does this store play here.
I have gone through python openid docs but end up feeling clueless.
Thanks
| [
"upd.: my previous answer was wrong\nThe store you are referring to is where your app stores the data during auth.\nStoring it in a shared memcached instance should be the best option (faster than db and reliable enough).\n"
] | [
1
] | [] | [] | [
"openid",
"python",
"store"
] | stackoverflow_0003937456_openid_python_store.txt |
Q:
Difference between "if x" and "if x is not None"
It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently?
I would assume the behavior should also be identical across Python implementations - but if there are subtle differences it would be great to know.
A:
In the following cases:
test = False
test = ""
test = 0
test = 0.0
test = []
test = ()
test = {}
test = set()
the if test will differ:
if test: #False
if test is not None: #True
This is the case because is tests for identity, meaning
test is not None
is equivalent to
id(test) == id(None) #False
therefore
(test is not None) is (id(test) != id(None)) #True
A:
The former tests trueness, whereas the latter tests for identity with None. Lots of values are false, such as False, 0, '', and None, but only None is None.
A:
x = 0
if x: ... # False
if x is not None: ... # True
A:
if x checks if x is considered as True.
In Python, everything has a boolean value (True/False).
Values that are considered as False:
False, None
0, 0.0, 0j
[], (), {}
''
Other instances that signal to Python that they are empty
Other values are considered as True. For example, [False], ('hello'), 'hello' are considered as True (because they are not empty).
When using if x is not None, you are checking if x is not None, but it can be False or other instances that are considered as False.
>>> x = None
>>> if not x:print x # bool(None) is False
None
>>> if x == None:print x
None
>>> x = False
>>> if not x:print x
False
>>> if x == None:print x
Finally, note that True and False are respectively equal to 1 and 0:
>>> True + 1
2
>>> False + 1
1
>>> range(1, 5)[False]
1
A:
if x:
# Evaluates for any defined non-False value of x
if not x:
# Evaluates for any defined False value of x
if x is None:
# Evaluates for any instances of None
None is its own type, which happens to be False. "if not x" evaluates if x = None, only because None is False.
There aren't any subtle differences that I know of but there are exact methods to test for use for positivity/negativity in exact situations. Mixing them can work in some situations, but can lead to problems if they're not understood.
if x is True:
# Use for checking for literal instances of True
if x is False:
# Use for checking for literal instances of False
if x is None:
# Use for checking for literal instances of None
if x:
# Use for checking for non-negative values
if not x:
# Use for checking for negative values
# 0, "", None, False, [], (), {} are negative, all others are True
| Difference between "if x" and "if x is not None" | It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently?
I would assume the behavior should also be identical across Python implementations - but if there are subtle differences it would be great to know.
| [
"In the following cases: \ntest = False \ntest = \"\" \ntest = 0\ntest = 0.0 \ntest = []\ntest = () \ntest = {} \ntest = set()\n\nthe if test will differ:\nif test: #False\n\nif test is not None: #True \n\nThis is the case because is tests for identity, meaning\ntest is not None\n\nis equivalent to \nid(test) == id... | [
66,
37,
5,
5,
3
] | [] | [] | [
"boolean",
"python"
] | stackoverflow_0003901144_boolean_python.txt |
Q:
Convert higher order function from Python to Haskell
I have the following code:
import operator
def stagger(l, w):
if len(l)>=w:
return [tuple(l[0:w])]+stagger(l[1:], w)
return []
def pleat(f, l, w=2):
return map(lambda p: f(*p), stagger(l, w))
if __name__=="__main__":
print pleat(operator.add, range(10))
print pleat(lambda x, y, z: x*y/z, range(3, 13), 3)
print pleat(lambda x: "~%s~"%(x), range(10), 1)
print pleat(lambda a, b, x, y: a+b==x+y, [3, 2, 4, 1, 5, 0, 9, 9, 0], 4)
Important part: Pleat takes any function and any sequence and passes the first handful of elements from that sequence into the received function as parameters.
Is there a way to do this in Haskell or am I dreaming?
A:
The type signatures below are optional:
stagger :: [a] -> Int -> [[a]]
stagger l w
| length l >= w = take w l : stagger (tail l) w
| otherwise = []
pleat :: ([a] -> b) -> [a] -> Int -> [b]
pleat f l w = map f $ stagger l w
main = do
print $ pleat (\[x, y] -> x+y) [0..9] 2
print $ pleat (\[x, y, z] -> x*y/z) [3..12] 3
print $ pleat (\[x] -> "~" ++ show x ++ "~") [0..9] 1
print $ pleat (\[a, b, x, y] -> a+b == x+y) [3, 2, 4, 1, 5, 0, 9, 9, 0] 4
The idea is that the function is explicit about taking a list of unknown length as an argument, so it is not very type-safe. But it is pretty much a 1-to-1 mapping of the Python code.
| Convert higher order function from Python to Haskell | I have the following code:
import operator
def stagger(l, w):
if len(l)>=w:
return [tuple(l[0:w])]+stagger(l[1:], w)
return []
def pleat(f, l, w=2):
return map(lambda p: f(*p), stagger(l, w))
if __name__=="__main__":
print pleat(operator.add, range(10))
print pleat(lambda x, y, z: x*y/z, range(3, 13), 3)
print pleat(lambda x: "~%s~"%(x), range(10), 1)
print pleat(lambda a, b, x, y: a+b==x+y, [3, 2, 4, 1, 5, 0, 9, 9, 0], 4)
Important part: Pleat takes any function and any sequence and passes the first handful of elements from that sequence into the received function as parameters.
Is there a way to do this in Haskell or am I dreaming?
| [
"The type signatures below are optional:\n\nstagger :: [a] -> Int -> [[a]]\nstagger l w\n | length l >= w = take w l : stagger (tail l) w\n | otherwise = []\n\npleat :: ([a] -> b) -> [a] -> Int -> [b]\npleat f l w = map f $ stagger l w\n\nmain = do\n print $ pleat (\\[x, y] -> x+y) [0..9] 2\n pr... | [
6
] | [] | [] | [
"haskell",
"higher_order_functions",
"python"
] | stackoverflow_0003937683_haskell_higher_order_functions_python.txt |
Q:
splitting the bill algorithmically & fair, afterwards :)
I'm trying to solve the following real-life problem you might have encountered yourselves:
You had dinner with some friends and you all agreed to split the bill evenly. Except that when the bill finally arrives, you find out not everyone has enough cash on them (if any, cheap bastards).
So, some of you pays more than others... Afterwards you come home and try to decide "who owes who what amount?".
This, I'm trying to solve algorithmically & fair :)
it seems so easy at first, but I'm getting stuck with rounding and what not, I feel like a total loser ;)
Any ideas on how to tackle this?
EDIT: Some python code to show my confusion
>>> amounts_paid = [100, 25, 30]
>>> total = sum(amounts_paid)
>>> correct_amount = total / float(len(amounts_paid))
>>> correct_amount
51.666666666666664
>>> diffs = [amnt-correct_amount for amnt in amounts_paid]
>>> diffs
[48.333333333333336, -26.666666666666664, -21.666666666666664]
>>> sum(diffs)
7.1054273576010019e-015
Theoratically, the sum of the differences should be zero, right?
for another example it works :)
>>> amounts_paid = [100, 50, 150]
>>> total = sum(amounts_paid)
>>> correct_amount = total / float(len(amounts_paid))
>>> correct_amount
100.0
>>> diffs = [amnt-correct_amount for amnt in amounts_paid]
>>> diffs
[0.0, -50.0, 50.0]
>>> sum(diffs)
0.0
A:
http://www.billmonk.com/
Amongst others. The problem has already been solved. Many times over.
"Theoratically, the sum of the differences should be zero, right?"
Yes. Since you've used float, however, you have representation issues when the number of people is not a power of two.
Never. Use. float For. Finance.
Never
Always. Use. decimal For. Finance.
Always
A:
The trick is to treat each person as a separate account.
You can easily determine (from the original bill) how much each person should pay. Set this as a negative amount for each person. Next, record the amount that each person has paid by adding the amount paid to their account. At this point, the people who have overpaid (lenders) will have positive balances, and the people who have underpaid (borrowers) will have negative balances.
There is no one right answer to which borrower owes money to each lender, except in the obvious case where there is only one lender. Amounts paid by a borrower can go to any of the lenders. Simply add the amount to the borrower's total, and subtract amounts from the lenders who receive the payment.
When all accounts hit zero, everyone has paid up.
Edit (in response to comments):
I think my problem lies with the fact that the amount is not always evenly divisible, so coming up with an algorithm that handles this elegantly seems to trip me up again & again.
When dealing with dollars and cents, there is no 100% clean way to handle the rounding. Some people will pay one cent more than others. The only way to be fair is to assign the extra $0.01 at random (as required). This would be done only once, when the "amount owed" is being calculated by dividing up the bill. It sometimes helps to store monetary values as cents, not as dollars ($12.34 would be stored as 1234, for example). This lets you use integers instead of floats.
To distribute the extra cents, I would do the following:
total_cents = 100 * total;
base_amount = Floor(total_cents / num_people);
cents_short = total_cents - base_amount * num_people;
while (cents_short > 0)
{
// add one cent to a random person
cents_short--;
}
Note: the easiest way to assign the pennies "randomly" is to assign the first extra cent to the first person, the second to the second, etc. This only becomes a problem if you always enter the same people in the same order.
A:
I'm not a python guy, but I found it an interesting problem =) Here's my solution. Dev time ~45min. I write clean perl... should be easy to port.
~/sandbox/$ ./bistro_math.pl
Anna owes Bill 7.57
Anna owes Mike 2.16
John owes Mike 2.62
~/sandbox/$ cat bistro_math.pl
#!/usr/bin/perl
use strict;
use warnings;
### Dataset.
### Bill total: 50.00
### Paid total: 50.00
my @people = (
{ name => 'Bill', bill => 5.43, paid => 13.00 },
{ name => 'Suzy', bill => 12.00, paid => 12.00 },
{ name => 'John', bill => 10.62, paid => 8.00 },
{ name => 'Mike', bill => 9.22, paid => 14.00 },
{ name => 'Anna', bill => 12.73, paid => 3.00 },
);
### Calculate how much each person owes (or is owed: -/+)
calculate_balances(\@people);
### Tally it all up =) This algorithm is designed to have bigger lenders
### paid back by the fewest number of people possible (they have the least
### hassle, since they were the most generous!).
sub calculate_balances {
my $people = shift;
### Use two pools
my @debtors;
my @lenders;
foreach my $person (@$people) {
### Ignore people who paid exactly what they owed.
$person->{owes} = $person->{bill} - $person->{paid};
push @debtors, $person if ($person->{owes} > 0);
push @lenders, $person if ($person->{owes} < 0);
}
LENDERS: foreach my $lender (@lenders) {
next if ($lender->{owes} >= 0);
DEBTORS: foreach my $debtor (@debtors) {
next if ($debtor->{owes} <= 0);
my $payment = ($lender->{owes} + $debtor->{owes} < 0)
? abs $debtor->{owes}
: abs $lender->{owes};
$lender->{owes} += $payment;
$debtor->{owes} -= $payment;
$debtor->{pays} = [] if (not exists $debtor->{pays});
print "$debtor->{name} owes $lender->{name} $payment\n";
next LENDERS if ($lender->{owes} >= 0);
}
}
}
exit;
~/sandbox/$
A:
You know the total everyone owed, and who was short. Take that total short that everyone was and divy it out to those who paid more, starting from the highest overpayer to lowest.
A:
The "problem" you are seeing has to do with binary representation of floating-point numbers as explained here. At any rate, 7.1054273576010019e-015 is a tiny, tiny number, so if you round your results to the nearest cent, as you should, you wouldn't have any problems.
| splitting the bill algorithmically & fair, afterwards :) | I'm trying to solve the following real-life problem you might have encountered yourselves:
You had dinner with some friends and you all agreed to split the bill evenly. Except that when the bill finally arrives, you find out not everyone has enough cash on them (if any, cheap bastards).
So, some of you pays more than others... Afterwards you come home and try to decide "who owes who what amount?".
This, I'm trying to solve algorithmically & fair :)
it seems so easy at first, but I'm getting stuck with rounding and what not, I feel like a total loser ;)
Any ideas on how to tackle this?
EDIT: Some python code to show my confusion
>>> amounts_paid = [100, 25, 30]
>>> total = sum(amounts_paid)
>>> correct_amount = total / float(len(amounts_paid))
>>> correct_amount
51.666666666666664
>>> diffs = [amnt-correct_amount for amnt in amounts_paid]
>>> diffs
[48.333333333333336, -26.666666666666664, -21.666666666666664]
>>> sum(diffs)
7.1054273576010019e-015
Theoratically, the sum of the differences should be zero, right?
for another example it works :)
>>> amounts_paid = [100, 50, 150]
>>> total = sum(amounts_paid)
>>> correct_amount = total / float(len(amounts_paid))
>>> correct_amount
100.0
>>> diffs = [amnt-correct_amount for amnt in amounts_paid]
>>> diffs
[0.0, -50.0, 50.0]
>>> sum(diffs)
0.0
| [
"http://www.billmonk.com/\nAmongst others. The problem has already been solved. Many times over.\n\n\n\"Theoratically, the sum of the differences should be zero, right?\"\n\nYes. Since you've used float, however, you have representation issues when the number of people is not a power of two.\nNever. Use. float F... | [
9,
5,
2,
1,
1
] | [] | [] | [
"algorithm",
"floating_accuracy",
"math",
"python"
] | stackoverflow_0003918567_algorithm_floating_accuracy_math_python.txt |
Q:
Is it really possible to POST files with python?
So I'm struggling with this for a second day in a row and still nothing. Found few solutions on the internet but still I'm getting "Internal Server Error" when trying to send files with POST. The idea is as follows : I'm sending a file opened in python's shell to a django function on my server that will read and store the file there. I've tried urllib, urllib2 (with and without poster module), httplib and Multipart methods. Here's the whole list of what I've tried together with results :
#Variables
In [35]: url = "http://www.address"
In [36]: values = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
In [37]: dataurllib = urllib.urlencode(values)
In [39]: dataposterlib, dataheaders = multipart_encode(values)
In [40]: dataposterlib
Out[40]: <generator object yielder at 0x15a0410>
In [41]: headers
{'Content-Length': 491,
'Content-Type': 'multipart/form-data; boundary=13936c2ddba0441eab9c3f4133a4009e'}
In [43]: f = open("winter.jpg", "rb")
In [45]: filegen, fileheaders = multipart_encode({"file": f})
In [46]: filegen
Out[46]: <generator object yielder at 0xc5b3c0>
In [47]: fileheaders
Out[47]:
{'Content-Length': 39876,
'Content-Type': 'multipart/form-data; boundary=0aa7a1b68d714440be06e166080925ec'}
#Working:
1. urllib.urlopen("http://www.address", data=urllib.urlencode({"key": "value"}))
2. urllib.urlopen(url, data=urllib.urlencode({"key": "value"}))
3. urllib.urlopen(url, data=urlib.urlencode(values))
4. urllib.urlopen(url, urlib.urlencode(values))
5. urllib.urlopen(url, data=dataurllib)
6. urllib.urlopen(url, dataurllib)
7. urllib.urlopen(url, data=urllib.urlencode({"file": f})) : works, but doesnt send file
8. import cookielib
from utils.multipart import MultipartPostHandler
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies), MultipartPostHandler)
params = { "username": "bob", "password": "riviera", "file": f }
opener.open(url, params)
#Not working:
4. u = urllib.urlopen(url, "string")
5. u = urllib.urlopen(url, data="string")
7. u = urllib2.urlopen(url, data=urllib.urlencode(values)) : Error 500 but sends data
6. u = urllib2.urlopen("http://www.fandrive.yum.pl/event/upload/", data=urllib.urlencode({"key": "value"})) : Error 500 but sends data
7. u = urllib2.urlopen(url, data=urllib.urlencode({"key": "value"})) : Error 500 but sends data
8. u = urllib2.urlopen(url, data=dataurllib) : Error 500 but sends data
9. u = urllib2.urlopen(url, dataurllib) : Error 500 but sends data
10. In [31]: req = urllib2.Request(url, f, fileheaders)
urllib2.urlopen(req) : Error 500
11. req = urllib2.Request(url, filegen, fileheaders)
urllib2.urlopen(req) : Error 500, very seldomly sends data
12. req = urllib2.Request(url, dataurllib)
urllib2.urlopen(req) : Error 500, sends data
I've found somebody with the same problem so I borrowed his django function (which is based on this post :
def upload(request):
logging.debug("GO")
for key, file in request.FILES.items():
path = '/path/'+ file.name
logging.debug(path)
dest = open(path.encode('utf-8'), 'wb+')
logging.debug(dest)
if file.multiple_chunks:
loggin.debug("big")
for c in file.chunks():
dest.write(c)
else:
logging.dobug("small")
dest.write(file.read())
dest.close()
destination = path + 'test.txt'
logging.debug(destination)
file = open(destination, "a")
file.write("file \n")
file.close
return 0
I've noticed that even when my function runs, the files sent are not saved, as well as the code after destination... is skipped. Just as there would be timeout before it reached this place. Wireshark shows POST request being sent, but server always gives 500 error. How is this happening ? I've tried few combinations with my 2 servers as well as sending from local computer but still nothing. What am I missing here ? I'm using the same code as everybody else on the internet. Even built-in urllib2 module always gives error even though urllib works.
EDIT
I've changed server to another one and finally I have some solid error log (receiver side):
[Sat Oct 16 20:40:46 2010] [error] [client IP] mod_python (pid=24773, interpreter='host', phase='PythonHandler', handler='django.core.handlers.modpython'): Application error
[Sat Oct 16 20:40:46 2010] [error] [client IP] ServerName: 'xxx'
[Sat Oct 16 20:40:46 2010] [error] [client IP] DocumentRoot: 'path'
[Sat Oct 16 20:40:46 2010] [error] [client IP] URI: '/error/internalServerError.html'
[Sat Oct 16 20:40:46 2010] [error] [client IP] Location: None
[Sat Oct 16 20:40:46 2010] [error] [client IP] Directory: None
[Sat Oct 16 20:40:46 2010] [error] [client IP] Filename: 'path/error/internalServerError.html'
[Sat Oct 16 20:40:46 2010] [error] [client IP] PathInfo: ''
[Sat Oct 16 20:40:46 2010] [error] [client IP] Traceback (most recent call last):
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch\n default=default_handler, arg=req, silent=hlist.silent)
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1229, in _process_target\n result = _execute_target(config, req, object, arg)
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1128, in _execute_target\n result = object(arg)
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/django/core/handlers/modpython.py", line 228, in handler\n return ModPythonHandler()(req)
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/django/core/handlers/modpython.py", line 220, in __call__\n req.write(chunk)
[Sat Oct 16 20:40:46 2010] [error] [client IP] IOError: Write failed, client closed connection.
[Sat Oct 16 20:40:46 2010] [error] [client IP] python_handler: Dispatch() returned non-integer.
A:
MAJOR EDIT:
Im very sorry, I gave you the wrong code. The working code, which I use, is based on this:
http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/
so I won't repeat it here and claim It being mine.
Because of your comment I read RFC1867 and realised I gave you the wrong code (I use this, too, it is convenient, if you control both sides).
Your Errorlog shows IOError: Write failed, client closed connection., which I suppose means that the server either tries to write some data (the file?) somewhere it doesn't should or I where it has no file system permissions to write. You should check where this is and look for write permission for the user the server runs as.
| Is it really possible to POST files with python? | So I'm struggling with this for a second day in a row and still nothing. Found few solutions on the internet but still I'm getting "Internal Server Error" when trying to send files with POST. The idea is as follows : I'm sending a file opened in python's shell to a django function on my server that will read and store the file there. I've tried urllib, urllib2 (with and without poster module), httplib and Multipart methods. Here's the whole list of what I've tried together with results :
#Variables
In [35]: url = "http://www.address"
In [36]: values = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
In [37]: dataurllib = urllib.urlencode(values)
In [39]: dataposterlib, dataheaders = multipart_encode(values)
In [40]: dataposterlib
Out[40]: <generator object yielder at 0x15a0410>
In [41]: headers
{'Content-Length': 491,
'Content-Type': 'multipart/form-data; boundary=13936c2ddba0441eab9c3f4133a4009e'}
In [43]: f = open("winter.jpg", "rb")
In [45]: filegen, fileheaders = multipart_encode({"file": f})
In [46]: filegen
Out[46]: <generator object yielder at 0xc5b3c0>
In [47]: fileheaders
Out[47]:
{'Content-Length': 39876,
'Content-Type': 'multipart/form-data; boundary=0aa7a1b68d714440be06e166080925ec'}
#Working:
1. urllib.urlopen("http://www.address", data=urllib.urlencode({"key": "value"}))
2. urllib.urlopen(url, data=urllib.urlencode({"key": "value"}))
3. urllib.urlopen(url, data=urlib.urlencode(values))
4. urllib.urlopen(url, urlib.urlencode(values))
5. urllib.urlopen(url, data=dataurllib)
6. urllib.urlopen(url, dataurllib)
7. urllib.urlopen(url, data=urllib.urlencode({"file": f})) : works, but doesnt send file
8. import cookielib
from utils.multipart import MultipartPostHandler
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies), MultipartPostHandler)
params = { "username": "bob", "password": "riviera", "file": f }
opener.open(url, params)
#Not working:
4. u = urllib.urlopen(url, "string")
5. u = urllib.urlopen(url, data="string")
7. u = urllib2.urlopen(url, data=urllib.urlencode(values)) : Error 500 but sends data
6. u = urllib2.urlopen("http://www.fandrive.yum.pl/event/upload/", data=urllib.urlencode({"key": "value"})) : Error 500 but sends data
7. u = urllib2.urlopen(url, data=urllib.urlencode({"key": "value"})) : Error 500 but sends data
8. u = urllib2.urlopen(url, data=dataurllib) : Error 500 but sends data
9. u = urllib2.urlopen(url, dataurllib) : Error 500 but sends data
10. In [31]: req = urllib2.Request(url, f, fileheaders)
urllib2.urlopen(req) : Error 500
11. req = urllib2.Request(url, filegen, fileheaders)
urllib2.urlopen(req) : Error 500, very seldomly sends data
12. req = urllib2.Request(url, dataurllib)
urllib2.urlopen(req) : Error 500, sends data
I've found somebody with the same problem so I borrowed his django function (which is based on this post :
def upload(request):
logging.debug("GO")
for key, file in request.FILES.items():
path = '/path/'+ file.name
logging.debug(path)
dest = open(path.encode('utf-8'), 'wb+')
logging.debug(dest)
if file.multiple_chunks:
loggin.debug("big")
for c in file.chunks():
dest.write(c)
else:
logging.dobug("small")
dest.write(file.read())
dest.close()
destination = path + 'test.txt'
logging.debug(destination)
file = open(destination, "a")
file.write("file \n")
file.close
return 0
I've noticed that even when my function runs, the files sent are not saved, as well as the code after destination... is skipped. Just as there would be timeout before it reached this place. Wireshark shows POST request being sent, but server always gives 500 error. How is this happening ? I've tried few combinations with my 2 servers as well as sending from local computer but still nothing. What am I missing here ? I'm using the same code as everybody else on the internet. Even built-in urllib2 module always gives error even though urllib works.
EDIT
I've changed server to another one and finally I have some solid error log (receiver side):
[Sat Oct 16 20:40:46 2010] [error] [client IP] mod_python (pid=24773, interpreter='host', phase='PythonHandler', handler='django.core.handlers.modpython'): Application error
[Sat Oct 16 20:40:46 2010] [error] [client IP] ServerName: 'xxx'
[Sat Oct 16 20:40:46 2010] [error] [client IP] DocumentRoot: 'path'
[Sat Oct 16 20:40:46 2010] [error] [client IP] URI: '/error/internalServerError.html'
[Sat Oct 16 20:40:46 2010] [error] [client IP] Location: None
[Sat Oct 16 20:40:46 2010] [error] [client IP] Directory: None
[Sat Oct 16 20:40:46 2010] [error] [client IP] Filename: 'path/error/internalServerError.html'
[Sat Oct 16 20:40:46 2010] [error] [client IP] PathInfo: ''
[Sat Oct 16 20:40:46 2010] [error] [client IP] Traceback (most recent call last):
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch\n default=default_handler, arg=req, silent=hlist.silent)
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1229, in _process_target\n result = _execute_target(config, req, object, arg)
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1128, in _execute_target\n result = object(arg)
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/django/core/handlers/modpython.py", line 228, in handler\n return ModPythonHandler()(req)
[Sat Oct 16 20:40:46 2010] [error] [client IP] File "/usr/lib/python2.5/site-packages/django/core/handlers/modpython.py", line 220, in __call__\n req.write(chunk)
[Sat Oct 16 20:40:46 2010] [error] [client IP] IOError: Write failed, client closed connection.
[Sat Oct 16 20:40:46 2010] [error] [client IP] python_handler: Dispatch() returned non-integer.
| [
"MAJOR EDIT:\nIm very sorry, I gave you the wrong code. The working code, which I use, is based on this:\nhttp://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/\nso I won't repeat it here and claim It being mine. \nBecause of your comment I read RFC1867 and realised I gave you the ... | [
3
] | [] | [] | [
"file_upload",
"post",
"python",
"request"
] | stackoverflow_0003937877_file_upload_post_python_request.txt |
Q:
Any value in catching an exception and immediately raising it again?
Possible Duplicate:
Does a exception with just a raise have any use?
Is there any value to re-raising an exception with no other code in between?
try:
#code
except Exception:
raise
I was recently looking through some code and saw a few blocks like these with nothing extra in the except block but another raise. I assume this was a mistake and poor decision making, am I right?
A:
I am not able to come up with something useful, other than to keep it as a placeholder for later insertion to catch useful exceptions.
It kind of avoids re-indenting the code, when you want to include the "try .. except.." blocks later on.
A:
I've seen similar code before in a (set of) horrible VB.NET projects. Either the intent was to catch and log exceptions, without ever coming back to finish the logging, or they heard "you must catch exceptions", implemented this functionality, and someone else decided it should just re-raise.
There is no benefit to the above code.
A:
Example built on this question. If there's some other except's in the try block, it can be used to filter the exceptions, but alone it's pointless.
class FruitException(Exception): pass
try:
raise FruitException
except FruitException:
print "we got a bad fruit"
raise
except Exception:
print "not fruit related, irrelevant."
A:
Yes, this is usually a bad practice. The only (somewhat) correct usage I've seen of this pattern was before VB.NET had a Using construct available. Usage looked something like:
Dim myResource As DisposableService
Try
myResource = New DisposableService()
' This might throw an exception....
myResource.DoSomething()
Catch
Throw
Finally
' Perform cleanup on resource
If Not myResource Is Nothing Then
myResource.Dispose()
End If
End Try
Other than that, I really can't think of a good use case for this sort of thing.
A:
sometimes it useful let me give you a real example that i did i my work :
this was is in a decorator that wrap func : so basically what i have wanted is to re-raise the error that i catched when i called the function func so that the decorator don't change the behavior of the function func, because when func raise an exception the exception are send to the GUI so that an error message can pop up to the user,
and for the try except i use it because i want to execute the code in finally even if an exception is raised
try:
result = func(self, *args, **kws)
return result
except Exception, ex:
# If an exception is raised save it also.
logging_data['message'] = str(ex)
logging_data['type'] = 'exception'
# Raise the error catched here so that we could have
# the same behavior as the decorated method.
raise
finally:
# Save logging data in the database
....
hope this will help to understand the use of re-raise
A:
Typically in a try-catch model, any uncaught exception will automatically be thrown (raised?). Catching the exception only to re-throw it may be in the spirit Allman style coding, but serves no functional purpose.
A:
Uh, Imagine
def something(a,b):
try:
// do stuff
except SomethingSpecificToThisFunction:
//handle
except: //Everything else, should likely be handled somewhere else
raise
try:
something("a","b")
except e:
Log(e)
Then again its default behaviour anyways, so might just want to leave it out
A:
There are some approaches with such technics in multithread enviroment. For example to throw something to upper stack level.
| Any value in catching an exception and immediately raising it again? |
Possible Duplicate:
Does a exception with just a raise have any use?
Is there any value to re-raising an exception with no other code in between?
try:
#code
except Exception:
raise
I was recently looking through some code and saw a few blocks like these with nothing extra in the except block but another raise. I assume this was a mistake and poor decision making, am I right?
| [
"I am not able to come up with something useful, other than to keep it as a placeholder for later insertion to catch useful exceptions.\nIt kind of avoids re-indenting the code, when you want to include the \"try .. except..\" blocks later on.\n",
"I've seen similar code before in a (set of) horrible VB.NET proje... | [
2,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0003937597_exception_handling_python.txt |
Q:
How do I encode and decode PER-encoded data in Python?
I need to be able to decode and encode PER-encoded octet strings using Python. I found PyASN1, but it doesn't include a PER codec. Is there another solution out there? How difficult would it be to write a PER codec?
A:
If, I remember well, there is an incomplete implementation / support of PER encoding format in SNMPy .
http://sourceforge.net/projects/snmpy/
| How do I encode and decode PER-encoded data in Python? | I need to be able to decode and encode PER-encoded octet strings using Python. I found PyASN1, but it doesn't include a PER codec. Is there another solution out there? How difficult would it be to write a PER codec?
| [
"If, I remember well, there is an incomplete implementation / support of PER encoding format in SNMPy .\n\nhttp://sourceforge.net/projects/snmpy/\n\n"
] | [
0
] | [] | [] | [
"asn.1",
"python"
] | stackoverflow_0003937889_asn.1_python.txt |
Q:
When would my Python test suite file coverage not be 100%?
We are using Hudson and coverage.py to report the code coverage of our test suite. Hudson breaks down coverage into:
packages
files
classes
lines
conditionals
Coverage.py only reports coverage on files executed/imported during the tests, and so it seems is oblivious to any files not executed during the tests. Is there ever an instance where files would not report 100% coverage?
A:
Currently, coverage.py doesn't know how to find files that are never executed and report them as not covered, but that will be coming in the next release. So now, the file coverage will always be 100%. This is an area where Hudson (using the Cobertura plugin) and coverage.py don't mesh very well.
A:
Coverage.py now (as of 3.4) does let you find completely unexecuted files. See the docs for details.
| When would my Python test suite file coverage not be 100%? | We are using Hudson and coverage.py to report the code coverage of our test suite. Hudson breaks down coverage into:
packages
files
classes
lines
conditionals
Coverage.py only reports coverage on files executed/imported during the tests, and so it seems is oblivious to any files not executed during the tests. Is there ever an instance where files would not report 100% coverage?
| [
"Currently, coverage.py doesn't know how to find files that are never executed and report them as not covered, but that will be coming in the next release. So now, the file coverage will always be 100%. This is an area where Hudson (using the Cobertura plugin) and coverage.py don't mesh very well.\n",
"Coverage... | [
3,
3
] | [] | [] | [
"code_coverage",
"coverage.py",
"hudson",
"python",
"python_coverage"
] | stackoverflow_0003562643_code_coverage_coverage.py_hudson_python_python_coverage.txt |
Q:
How to pause Python while Tkinter window is open?
I'm writing a program that sometimes encounters an error. When it does, it pops up a Tkinter dialog asking the user whether to continue. It's a more complicated version of this:
keep_going = False
KeepGoingPrompt(keep_going)
if not keep_going:
return
The prompt sets keep_going to True or leaves it False.
Problem is, the code seems to continue while KeepGoingPrompt is open. I tried storing a reference to the prompt and adding a loop like
while prompt:
time.sleep(1)
but python gets stuck in the loop and freezes.
Is there a better way to do it?
Thanks
A:
You can use the tkMessageBox class to pop up a question dialog that is modal and won't return until the user clicks a button. See the Tkinter book for details.
A:
1) Are you running your code inside IDLE? It might be responsible for making the dialogue non-blocking while it really should be blocking.
2) If running outside IDLE does not help, look for tkinter/dialogue options which specify whether behavior is blocking or non-blocking
| How to pause Python while Tkinter window is open? | I'm writing a program that sometimes encounters an error. When it does, it pops up a Tkinter dialog asking the user whether to continue. It's a more complicated version of this:
keep_going = False
KeepGoingPrompt(keep_going)
if not keep_going:
return
The prompt sets keep_going to True or leaves it False.
Problem is, the code seems to continue while KeepGoingPrompt is open. I tried storing a reference to the prompt and adding a loop like
while prompt:
time.sleep(1)
but python gets stuck in the loop and freezes.
Is there a better way to do it?
Thanks
| [
"You can use the tkMessageBox class to pop up a question dialog that is modal and won't return until the user clicks a button. See the Tkinter book for details.\n",
"1) Are you running your code inside IDLE? It might be responsible for making the dialogue non-blocking while it really should be blocking.\n2) If ru... | [
1,
0
] | [] | [] | [
"loops",
"pausing_execution",
"python",
"tkinter"
] | stackoverflow_0003938549_loops_pausing_execution_python_tkinter.txt |
Q:
Why does Django's time filter not pickup the TIME_FORMAT by default?
Using {{today|time:"TIME_FORMAT"}} correctly localises times when I switch languages in my Django 1.2.3 project. E.g. for English I see "12:19 a.m." and when I switch to German it changes to "12:19:25".
As far as I can tell from looking at the docs and code (defaultfilters.py and formats.py) just using {{today:time}} should do the same thing and default to TIME_FORMAT but this isn't working and it always uses the default English format.
Is there a way to avoid having to edit all my templates and change them to {{today|time:"TIME_FORMAT"}}?
The same thing happens with the date filter and DATE_FORMAT.
A:
The docs say (emphasis mine):
When used without a format string:
{{ value|time }}
...the formatting string defined in the TIME_FORMAT setting will be used, without applying any localization.
You have two options:
Edit all your templates to make the change, or
Create a new filter of your own that does it the way you want.
A:
Thanks @Ned Batchelder, as per option 2., I've added the following to my custom template tags file:
from django.template.defaultfilters import date as defaultfilters_date, time as defaultfilters_time
# FORCE {{...|date}} to be equivalent to {{...|date:"DATE_FORMAT"}} so it localizes properly, ditto for time and TIME_FORMAT
@register.filter(name="date")
def date_localized(val, arg=None):
return defaultfilters_date(val, arg or "DATE_FORMAT")
@register.filter(name="time")
def time_localized(val, arg=None):
return defaultfilters_time(val, arg or "TIME_FORMAT")
| Why does Django's time filter not pickup the TIME_FORMAT by default? | Using {{today|time:"TIME_FORMAT"}} correctly localises times when I switch languages in my Django 1.2.3 project. E.g. for English I see "12:19 a.m." and when I switch to German it changes to "12:19:25".
As far as I can tell from looking at the docs and code (defaultfilters.py and formats.py) just using {{today:time}} should do the same thing and default to TIME_FORMAT but this isn't working and it always uses the default English format.
Is there a way to avoid having to edit all my templates and change them to {{today|time:"TIME_FORMAT"}}?
The same thing happens with the date filter and DATE_FORMAT.
| [
"The docs say (emphasis mine):\n\nWhen used without a format string:\n {{ value|time }}\n\n...the formatting string defined in the TIME_FORMAT setting will be used, without applying any localization.\n\nYou have two options:\n\nEdit all your templates to make the change, or\nCreate a new filter of your own that doe... | [
3,
1
] | [] | [] | [
"django",
"internationalization",
"localization",
"python"
] | stackoverflow_0003938700_django_internationalization_localization_python.txt |
Q:
Appengine create and export yaml file
I´m having trouble in creating a file and export to .yaml.
I´m using Google App Engine with Python 2.5.
Don´t understand the Yaml doc´s, it makes me confused.
What i want is to create a file and save it. It´s necessary to get entities from Models.
class SaveYAML(webapp.RequestHandler):
def post(self):
user = db.Query(models.User)
user = user.filter('user =', users.get_current_user())
users = user.fetch(limit = 1)
for user in users:
print(user.name, user.adress, user.phone, user.city)
self.response.headers['Content-Type'] = 'application/yaml'
self.response.headers['Content-Disposition'] = 'filename = myYaml.yaml'
With this snippet i can view in a browser, when i click in a button the information retrieved from models.
Maybe it´s because of print method, but it doesn´t create a file
But when i upload my app to Google App Engine it doesn´t show the same info. It shows only 'Status 200 Ok'.
Can someone point me in the right direction?
Do i have to import pyyaml library?
I changed some code to:
print(yaml.dump(user, sys.stdout))
and the result was this in a browser:
- !!binary |
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a
HBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIy
MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAnACgDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2WxvX
h8zzNxhEjgk87fmPI9R6+lbKsGUMpBBGQR3rAhKxRTyOyqglck9Mc1nX/iVdGb7JZr9qnlBMcCc7
T3Psvqeg7elAG7rmv6f4esGu7+ZUXoq5+Zz6Cuc8I+ItS8X6pLqK/wCiaXbKYhbjkyuRnJOOw7Cs
jXvC8epW0Ta5IdR1O7dTFDG5Eaeirj1xy3oG6dK7rQdGtvDuiQ2FuoCRLl2A+8x5J/OtFKKhtqZu
MnPfQoajeXDeLtMtICfLG55cNj5Qp6/iVoqLQAb/AMQalqLDKoRBGf1NFceGqOpT9o+t/u6fgdNZ
csuTt/T/ABMGTVb/AFu4NroW37H5rG5upEOB83AUHr9O/r2roI9DtfDsUt1GHmaTBmmc5kLdBz6d
sdB246XrcIlpKgXaPNOOBz8wqtqkFxreoRWSKRp0ZJuJM43H+6PXPTPufw6DIytCk/0ttauQv2d8
rbr3Ck8yKPQ9AP7oB7muk1m+S00We5VgVKfKQeDVe80yO3+eFAIO6gf6v6f7P8vpXP63lfsmnbnM
c8ykoozhepIrlxk3Gi1Hd6L1ehrQinUV9lr92p0PhezNnoMAcfvJcyv9W5orWhKGFDEQU2jaR0xR
XRCKhFRjsjOUnJuT6mALmOIyxujHMjE4478d6kXUUXIHnAZ/vH8e9FFUIY2roq8+dn03HH86wYby
3bxFLduji3twYolxk5IyT196KKTipWv0GpNXsbNv4gtYZ/kEgjY/MpXoe5HP/wCv+ZRRTEf/2Q==
_name: !!python/unicode 'Ana Ferreira'
_parent: null
_parent_key: null
_adress: !!python/unicode 'Porto'
_phone: !!python/unicode '1234569789'
_user: *id002
None
Status: 200 OK
Cache-Control: no-cache
Content-Type: text/yaml
Content-Disposition: filename = myYaml.yaml
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Content-Length: 0
Changed the code, but the data is only presented by browser.
A:
Do not use print, use self.response.out.write(...).
Yes, you will want to import yaml to output yaml, it will make it easier.
Try this:
import yaml
users = model.Users.all().fetch(10)
users = [{'user': {'name': user.name,
'address': user.address,
'phone': user.phone,
'city': user.city}}
for user in users]
self.response.out.write(yaml.dump(users, default_flow_style=False))
You can check out the yaml docs for additional information on formatting the output.
| Appengine create and export yaml file | I´m having trouble in creating a file and export to .yaml.
I´m using Google App Engine with Python 2.5.
Don´t understand the Yaml doc´s, it makes me confused.
What i want is to create a file and save it. It´s necessary to get entities from Models.
class SaveYAML(webapp.RequestHandler):
def post(self):
user = db.Query(models.User)
user = user.filter('user =', users.get_current_user())
users = user.fetch(limit = 1)
for user in users:
print(user.name, user.adress, user.phone, user.city)
self.response.headers['Content-Type'] = 'application/yaml'
self.response.headers['Content-Disposition'] = 'filename = myYaml.yaml'
With this snippet i can view in a browser, when i click in a button the information retrieved from models.
Maybe it´s because of print method, but it doesn´t create a file
But when i upload my app to Google App Engine it doesn´t show the same info. It shows only 'Status 200 Ok'.
Can someone point me in the right direction?
Do i have to import pyyaml library?
I changed some code to:
print(yaml.dump(user, sys.stdout))
and the result was this in a browser:
- !!binary |
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a
HBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIy
MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAnACgDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD2WxvX
h8zzNxhEjgk87fmPI9R6+lbKsGUMpBBGQR3rAhKxRTyOyqglck9Mc1nX/iVdGb7JZr9qnlBMcCc7
T3Psvqeg7elAG7rmv6f4esGu7+ZUXoq5+Zz6Cuc8I+ItS8X6pLqK/wCiaXbKYhbjkyuRnJOOw7Cs
jXvC8epW0Ta5IdR1O7dTFDG5Eaeirj1xy3oG6dK7rQdGtvDuiQ2FuoCRLl2A+8x5J/OtFKKhtqZu
MnPfQoajeXDeLtMtICfLG55cNj5Qp6/iVoqLQAb/AMQalqLDKoRBGf1NFceGqOpT9o+t/u6fgdNZ
csuTt/T/ABMGTVb/AFu4NroW37H5rG5upEOB83AUHr9O/r2roI9DtfDsUt1GHmaTBmmc5kLdBz6d
sdB246XrcIlpKgXaPNOOBz8wqtqkFxreoRWSKRp0ZJuJM43H+6PXPTPufw6DIytCk/0ttauQv2d8
rbr3Ck8yKPQ9AP7oB7muk1m+S00We5VgVKfKQeDVe80yO3+eFAIO6gf6v6f7P8vpXP63lfsmnbnM
c8ykoozhepIrlxk3Gi1Hd6L1ehrQinUV9lr92p0PhezNnoMAcfvJcyv9W5orWhKGFDEQU2jaR0xR
XRCKhFRjsjOUnJuT6mALmOIyxujHMjE4478d6kXUUXIHnAZ/vH8e9FFUIY2roq8+dn03HH86wYby
3bxFLduji3twYolxk5IyT196KKTipWv0GpNXsbNv4gtYZ/kEgjY/MpXoe5HP/wCv+ZRRTEf/2Q==
_name: !!python/unicode 'Ana Ferreira'
_parent: null
_parent_key: null
_adress: !!python/unicode 'Porto'
_phone: !!python/unicode '1234569789'
_user: *id002
None
Status: 200 OK
Cache-Control: no-cache
Content-Type: text/yaml
Content-Disposition: filename = myYaml.yaml
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Content-Length: 0
Changed the code, but the data is only presented by browser.
| [
"Do not use print, use self.response.out.write(...).\nYes, you will want to import yaml to output yaml, it will make it easier.\nTry this:\nimport yaml\n\nusers = model.Users.all().fetch(10)\nusers = [{'user': {'name': user.name,\n 'address': user.address,\n 'phone': user.phone,\... | [
1
] | [] | [] | [
"google_app_engine",
"python",
"pyyaml",
"yaml"
] | stackoverflow_0003937964_google_app_engine_python_pyyaml_yaml.txt |
Q:
Iterator (iter()) function in Python.
For dictionary, I can use iter() for iterating over keys of the dictionary.
y = {"x":10, "y":20}
for val in iter(y):
print val
When I have the iterator as follows,
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
Why can't I use it this way
x = Counter(3,8)
for i in x:
print x
nor
x = Counter(3,8)
for i in iter(x):
print x
but this way?
for c in Counter(3, 8):
print c
What's the usage of iter() function?
ADDED
I guess this can be one of the ways of how iter() is used.
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
class Hello:
def __iter__(self):
return Counter(10,20)
x = iter(Hello())
for i in x:
print i
A:
All of these work fine, except for a typo--you probably mean:
x = Counter(3,8)
for i in x:
print i
rather than
x = Counter(3,8)
for i in x:
print x
A:
I think your actual problem is that you print x when you mean to print i
iter() is used to obtain an iterator over a given object. If you have an __iter__ method that defines what iter will actually do. In your case you can only iterate over the counter once. If you defined __iter__ to return a new object it would make it so that you could iterate as many times as you wanted. In your case, Counter is already an iterator which is why it makes sense to return itself.
| Iterator (iter()) function in Python. | For dictionary, I can use iter() for iterating over keys of the dictionary.
y = {"x":10, "y":20}
for val in iter(y):
print val
When I have the iterator as follows,
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
Why can't I use it this way
x = Counter(3,8)
for i in x:
print x
nor
x = Counter(3,8)
for i in iter(x):
print x
but this way?
for c in Counter(3, 8):
print c
What's the usage of iter() function?
ADDED
I guess this can be one of the ways of how iter() is used.
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
class Hello:
def __iter__(self):
return Counter(10,20)
x = iter(Hello())
for i in x:
print i
| [
"All of these work fine, except for a typo--you probably mean:\nx = Counter(3,8)\nfor i in x:\n print i\n\nrather than\nx = Counter(3,8)\nfor i in x:\n print x\n\n",
"I think your actual problem is that you print x when you mean to print i\niter() is used to obtain an iterator over a given object. If you ha... | [
17,
8
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0003938927_iterator_python.txt |
Q:
Any good references for python and C code mixing?
I've been looking at docs but I can't seem to understand very clearly, them do you guys know of anything that would be good at teaching it.
Say I had a program,
int main() {
return 3;
}
How do I call cprogram.exe and get the return value (not neccesarily an int, structs too). I don't have a specific project that I'm working on, just trying to learn. So on top of answering this question, some references (books or otherwise) to where I could learn continuation of this, because I know its more complicated than this; would be nice; thanks in advance.
lol sentence structure.
A:
The simplest way of doing this would be to create a dll or so (depending on your platform) then use the ctypes module to call into it. The exact method for creating the dll depends on your compiler. For ctypes see http://python.net/crew/theller/ctypes/tutorial.html
A:
Wesley Chun has a nice chapter showing how to do it in his "Core Python Programming" book.
A:
The Python docs themselves may be a good place to start:
http://docs.python.org/release/2.5.2/ext/intro.html
| Any good references for python and C code mixing? | I've been looking at docs but I can't seem to understand very clearly, them do you guys know of anything that would be good at teaching it.
Say I had a program,
int main() {
return 3;
}
How do I call cprogram.exe and get the return value (not neccesarily an int, structs too). I don't have a specific project that I'm working on, just trying to learn. So on top of answering this question, some references (books or otherwise) to where I could learn continuation of this, because I know its more complicated than this; would be nice; thanks in advance.
lol sentence structure.
| [
"The simplest way of doing this would be to create a dll or so (depending on your platform) then use the ctypes module to call into it. The exact method for creating the dll depends on your compiler. For ctypes see http://python.net/crew/theller/ctypes/tutorial.html\n",
"Wesley Chun has a nice chapter showing how... | [
1,
0,
0
] | [] | [] | [
"c",
"python"
] | stackoverflow_0003938941_c_python.txt |
Q:
Read in CLI argumnet, then use regex's to look for it. -Python
Sorry if this is probably a simple fix but I can't think of one. I am trying to take a command line argument (in this case a name) and search through a file hierarchy and keep track of the number of times that name comes up. I was just wondering how to store the CL input and then search through files using a regular expression with that input as my search key.
A:
import sys
import os
the_name= sys.argv[1]
count=0
for r,d,f in os.walk("/mypath"):
for file in f:
if the_name in file:
count+=1
If you want to search IN the file themselves,
for r,d,f in os.walk("/mypath"):
for file in f:
for line in open(os.path.join(r,file)) :
if the_name in line:
count+=line.count(the_name)
| Read in CLI argumnet, then use regex's to look for it. -Python | Sorry if this is probably a simple fix but I can't think of one. I am trying to take a command line argument (in this case a name) and search through a file hierarchy and keep track of the number of times that name comes up. I was just wondering how to store the CL input and then search through files using a regular expression with that input as my search key.
| [
"import sys\nimport os\nthe_name= sys.argv[1]\ncount=0\nfor r,d,f in os.walk(\"/mypath\"):\n for file in f:\n if the_name in file:\n count+=1\n\nIf you want to search IN the file themselves,\nfor r,d,f in os.walk(\"/mypath\"):\n for file in f:\n for line in open(os.path.join(r,file)) ... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003939053_python_regex.txt |
Q:
Run command line arguments in python script
I have a program that is run from the command line like this
python program.py 100 rfile
How can I write a new script so that instead of running it with just the '100' argument, I can run it consecutively with a list of arguments like [50, 100, 150, 200]?
Edit: The reason I am asking is that I want to record how 'program.py' executes with different arguments.
A:
If you create a bash file like this
#!/bin/bash
for i in 1 2 3 4 5
do
python program.py $i rfile
done
then do chmod +x on that file, when you run it, it will run these consecutively:
python program.py 1 rfile
python program.py 2 rfile
python program.py 3 rfile
python program.py 4 rfile
python program.py 5 rfile
A:
You can use Devrim's shell approach or you can modify your script:
If your original script worked like this:
import sys
do_something(sys.argv[1], sys.argv[2])
You could accomplish what you want like this:
def main(args):
for arg in args[:-1]:
do_something(arg, args[-1])
if __name__ == '__main__':
import sys
main(sys.argv[1:])
You would invoke it like so:
python program.py 50 100 150 200 rfile
I'm guessing at what you want. Please clarify if this isn't right.
A:
You can use Optparse
It lets you use your program like : python yourcode.py --input input.txt --output output.txt
This is great when you have a number of console arguments.
So in your case you could do something like:
parser.add_option("-i","--input", action="store", type="int", nargs=4, dest="mylist")
Now in your console you can type in python program.py -i 50 100 150 200
In order to access the inputs you can use mylist as a list.
A:
If you want to do this in your python script, you can arrange for it to take a list of integers by using the argparse module (untested code):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('rfile', type=argparse.FileType('r'))
parser.add_argument('numbers', nargs='+', type=int)
ns = parser.parse_args()
Such activities are usually conducted under the auspices of a main function as explained by Jon-Eric.
If you call the resulting script from the shell with
python the_script.py filename 1 2 3 4 5 6
you will end up with ns.file being equal to the file filename, opened for read access, and ns.numbers being equal to the list [1, 2, 3, 4, 5, 6].
argparse is totally awesome and even prints out usage information for the script and its options if you call it with --help. You can customize it in far too many ways to explain here, just read the docs.
argparse is in the standard library as of Python 2.7; for earlier pythons it can be installed as a module in the normal way, e.g. via easy_install argparse, or by virtue of being a dependency of the package that your script is part of.
| Run command line arguments in python script | I have a program that is run from the command line like this
python program.py 100 rfile
How can I write a new script so that instead of running it with just the '100' argument, I can run it consecutively with a list of arguments like [50, 100, 150, 200]?
Edit: The reason I am asking is that I want to record how 'program.py' executes with different arguments.
| [
"If you create a bash file like this\n#!/bin/bash\nfor i in 1 2 3 4 5\ndo\n python program.py $i rfile\ndone\n\nthen do chmod +x on that file, when you run it, it will run these consecutively:\npython program.py 1 rfile\npython program.py 2 rfile\npython program.py 3 rfile\npython program.py 4 rfile\npython progra... | [
8,
6,
4,
2
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0003939196_python_shell.txt |
Q:
developing for modularity & reusability: how to handle While True loops?
I've been playing around with the pybluez module recently to scan for nearby Bluetooth devices. What I want to do now is extend the program to also find nearby WiFi client devices.
The WiFi client scanner will have need to have a While True loop to continually monitor the airwaves. If I were to write this as a straight up, one file program, it would be easy.
import ...
while True:
client = scan()
print client['mac']
What I want, however, is to make this a module. I want to be able to reuse it later and, possible, have others use it too. What I can't figure out is how to handle the loop.
import mymodule
scan()
Assuming the first example code was 'mymodule', this program would simply print out the data to stdout. I would want to be able to use this data in my program instead of having the module print it out...
How should I code the module?
A:
I think the best approach is going to be to have the scanner run on a separate thread from the main program. The module should have methods that start and stop the scanner, and another that returns the current access point list (using a lock to synchronize). See the threading module.
A:
How about something pretty straightforward like:
mymodule.py
import ...
def scanner():
while True:
client = scan()
yield client['mac']
othermodule.py
import mymodule
for mac in mymodule.scanner():
print mac
If you want something more useful than that, I'd also suggest a background thread as @kindall did.
A:
Two interfaces would be useful.
scan() itself, which returned a list of found devices, such that I could call it to get an instantaneous snapshot of available bluetooth. It might take a max_seconds_to_search or a max_num_to_return parameter.
A "notify on found" function that accepted a callback. For instance (maybe typos, i just wrote this off the cuff).
def find_bluetooth(callback_func, time_to_search = 5.0):
already_found = []
start_time = time.clock()
while 1:
if time.clock()-start_time > 5.0: break
found = scan()
for entry in found:
if entry not in already_found:
callback_func(entry)
already_found.append(entry)
which would be used by doing this:
def my_callback(new_entry):
print new_entry # or something more interesting...
find_bluetooth(my_callback)
A:
If I get your question, you want scan() in a separate file, so that it can be reused later.
Create utils.py
def scan():
# write code for scan here.
Create WiFi.py
import utils
def scan_wifi():
while True:
cli = utils.scan()
...
return
| developing for modularity & reusability: how to handle While True loops? | I've been playing around with the pybluez module recently to scan for nearby Bluetooth devices. What I want to do now is extend the program to also find nearby WiFi client devices.
The WiFi client scanner will have need to have a While True loop to continually monitor the airwaves. If I were to write this as a straight up, one file program, it would be easy.
import ...
while True:
client = scan()
print client['mac']
What I want, however, is to make this a module. I want to be able to reuse it later and, possible, have others use it too. What I can't figure out is how to handle the loop.
import mymodule
scan()
Assuming the first example code was 'mymodule', this program would simply print out the data to stdout. I would want to be able to use this data in my program instead of having the module print it out...
How should I code the module?
| [
"I think the best approach is going to be to have the scanner run on a separate thread from the main program. The module should have methods that start and stop the scanner, and another that returns the current access point list (using a lock to synchronize). See the threading module.\n",
"How about something pre... | [
1,
1,
1,
0
] | [] | [] | [
"modularity",
"module",
"python"
] | stackoverflow_0003939138_modularity_module_python.txt |
Q:
Save images as string? IS it possible
Is it possible to save images as string, and then I load it up to Image?
A:
You can save it to a StringIO buffer:
import pylab, numpy
from StringIO import StringIO
from PIL import Image
# plot a histogram
pylab.hist(numpy.random.rand(100))
buf = StringIO()
pylab.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)
im.show()
| Save images as string? IS it possible | Is it possible to save images as string, and then I load it up to Image?
| [
"You can save it to a StringIO buffer:\nimport pylab, numpy\nfrom StringIO import StringIO\nfrom PIL import Image\n\n# plot a histogram\npylab.hist(numpy.random.rand(100))\n\nbuf = StringIO()\npylab.savefig(buf, format='png')\n\nbuf.seek(0)\nim = Image.open(buf)\nim.show()\n\n"
] | [
6
] | [] | [] | [
"image",
"python",
"string"
] | stackoverflow_0003939342_image_python_string.txt |
Q:
How to make a screenshot in Windows 7 with python?
I along with some friends are trying to do an anti cheats for a game, we chose python because it is multiplatform.
The problem is we're trying to make a screenshot of what is shown on the screen, not just the game (with OpenGL) but any windows that are open to detect programs that are superimposed on the image of the game (for example to indicate the positions of other players in online games)
We tried to use Python Imaging Library (PIL) but with the game open, taking pictures in gray, OpenGL draws the images in black and have tried other things, but nothing has worked (problems with Aero in Windows Vista / 7).
Google does not show anything about it.
Anyone know any way to make a screenshot with python in Windows 7?
from PIL import ImageGrab
ImageGrab.grab().save('test.jpg', "JPEG")
This does not work
import Tkinter
from OpenGL.GL import *
root = Tkinter.Tk()
width = int(root.winfo_screenwidth())
height = root.winfo_screenheight()
screenshot = glReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE)
im = Image.frombuffer("RGBA", (width, height), screenshot, "raw", "RGBA", 0, 0)
im.save('test.jpg')
And this does not work
A:
The ImageGrab module should work on Windows 7.
http://effbot.org/imagingbook/imagegrab.htm
| How to make a screenshot in Windows 7 with python? | I along with some friends are trying to do an anti cheats for a game, we chose python because it is multiplatform.
The problem is we're trying to make a screenshot of what is shown on the screen, not just the game (with OpenGL) but any windows that are open to detect programs that are superimposed on the image of the game (for example to indicate the positions of other players in online games)
We tried to use Python Imaging Library (PIL) but with the game open, taking pictures in gray, OpenGL draws the images in black and have tried other things, but nothing has worked (problems with Aero in Windows Vista / 7).
Google does not show anything about it.
Anyone know any way to make a screenshot with python in Windows 7?
from PIL import ImageGrab
ImageGrab.grab().save('test.jpg', "JPEG")
This does not work
import Tkinter
from OpenGL.GL import *
root = Tkinter.Tk()
width = int(root.winfo_screenwidth())
height = root.winfo_screenheight()
screenshot = glReadPixels( 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE)
im = Image.frombuffer("RGBA", (width, height), screenshot, "raw", "RGBA", 0, 0)
im.save('test.jpg')
And this does not work
| [
"The ImageGrab module should work on Windows 7.\nhttp://effbot.org/imagingbook/imagegrab.htm\n"
] | [
1
] | [] | [] | [
"aero",
"opengl",
"python",
"screenshot",
"windows"
] | stackoverflow_0003938776_aero_opengl_python_screenshot_windows.txt |
Q:
Os Check And prompt proper if
Can python see which windows i use e.x. windows 7 windows xp windows vista and if windows vista print you use windows vista, or execute other command
A:
Absolutely. Look at platform.
A:
import platform
platform.system() # => 'Windows'
platform.release() # => 'Vista'
platform.version() # => '6.1.7600'
I believe if platform.version() returns a value of 6.1.7000 or higher, you're on a Windows 7 machine, otherwise it is Vista.
| Os Check And prompt proper if | Can python see which windows i use e.x. windows 7 windows xp windows vista and if windows vista print you use windows vista, or execute other command
| [
"Absolutely. Look at platform.\n",
"import platform\nplatform.system() # => 'Windows'\nplatform.release() # => 'Vista'\nplatform.version() # => '6.1.7600'\n\nI believe if platform.version() returns a value of 6.1.7000 or higher, you're on a Windows 7 machine, otherwise it is Vista.\n"
] | [
2,
2
] | [] | [] | [
"operating_system",
"python"
] | stackoverflow_0003933375_operating_system_python.txt |
Q:
Python execution speed: laptop vs desktop
I am running a program that does simple data processing:
parses text
populates dictionaries
calculates some functions over the resulting data
The program only uses CPU, RAM, and HDD:
run from Windows command line
input/output to the local hard drive
nothing displayed on or printed to screen
no networking
The same program is run on:
desktop: Windows 7, i7-930 CPU overclocked @3.6 GHz (with matching memory speed), Intel X-25M SSD
laptop: Windows XP, Intel Core2 Duo T9300 @2.5GHz, 7200 rpm HDD
The CPU is 1.44 faster frequency, HDD is 4 times higher benchmark score (Passmark - Disk Mark). I found the program runs just around 1.66 times faster on the desktop. So apparently, the CPU is the bottleneck.
It seems there's only 15% benefit from the i7 Core vs Intel Core2 Duo architecture (most of the performance boost is due to the straight CPU frequency). Is there anything I can do in the code to increase the benefit of the new architecture?
EDIT: forgot to mention that I use ActivePython 3.1.2 if that matters.
A:
The increasing performance of hardware brings in most cases automatically results in benefit to user applications. The much maligned "GIL" means that you may not be able to take advantage of multicores with CPython unless you design your program to take advantage via various multiprocessing modules / libraries.
SO discussion on the same : Does python support multiprocessor/multicore programming?
A related collation of solutions on python wiki: http://wiki.python.org/moin/ParallelProcessing
A:
Split your processing into multiple threads. Your particular i7 should be able to support up to 8 threads in parallel.
A:
Consider repeating on regular HDD's - that SSD could well result in a substantial performance difference depending on caches, and the nature of that data.
| Python execution speed: laptop vs desktop | I am running a program that does simple data processing:
parses text
populates dictionaries
calculates some functions over the resulting data
The program only uses CPU, RAM, and HDD:
run from Windows command line
input/output to the local hard drive
nothing displayed on or printed to screen
no networking
The same program is run on:
desktop: Windows 7, i7-930 CPU overclocked @3.6 GHz (with matching memory speed), Intel X-25M SSD
laptop: Windows XP, Intel Core2 Duo T9300 @2.5GHz, 7200 rpm HDD
The CPU is 1.44 faster frequency, HDD is 4 times higher benchmark score (Passmark - Disk Mark). I found the program runs just around 1.66 times faster on the desktop. So apparently, the CPU is the bottleneck.
It seems there's only 15% benefit from the i7 Core vs Intel Core2 Duo architecture (most of the performance boost is due to the straight CPU frequency). Is there anything I can do in the code to increase the benefit of the new architecture?
EDIT: forgot to mention that I use ActivePython 3.1.2 if that matters.
| [
"The increasing performance of hardware brings in most cases automatically results in benefit to user applications. The much maligned \"GIL\" means that you may not be able to take advantage of multicores with CPython unless you design your program to take advantage via various multiprocessing modules / libraries.\... | [
6,
0,
0
] | [] | [] | [
"intel",
"performance",
"python"
] | stackoverflow_0003939912_intel_performance_python.txt |
Q:
How can I query for records based on an attribute of a ReferenceProperty? (Django on App Engine)
If I have the following models in a Python (+ Django) App Engine app:
class Album(db.Model):
private = db.BooleanProperty()
...
class Photo(db.Model):
album = db.ReferenceProperty(Album)
title = db.StringProperty()
...how can I retrieve all Photos that belong to a public Album (that is, an Album with private == False)?
To further explain my intention, I thought it would be:
public_photos = Photos.all().filter('album.private = ', False)
and then I could do something like:
photos_for_homepage = public_photos.fetch(30)
but the query does not match anything, which tells me I'm going down the wrong path.
A:
You can't. App engine doesn't support joins.
One approach is to implement the join manually. For example you could fetch all photos, then filter out the private ones in code. Or fetch all public albums, and then fetch each of their photos. It depends on your data as to whether this will perform okay or not.
The alternative approach is to denormalize your data. Put another field in the Photo model, eg:
class Photo(db.Model):
album = db.ReferenceProperty(Album)
album_private = db.BooleanProperty()
title = db.StringProperty()
Then you can filter for public photos with:
public_photos = Photos.all().filter('album_private = ', False)
This improves query performance, but at the expense of write performance. You will need to keep the album_private field of the photos updated whenever you change the private flag of the album. It depends on your data and read/write patterns as to whether this will be better or worse.
| How can I query for records based on an attribute of a ReferenceProperty? (Django on App Engine) | If I have the following models in a Python (+ Django) App Engine app:
class Album(db.Model):
private = db.BooleanProperty()
...
class Photo(db.Model):
album = db.ReferenceProperty(Album)
title = db.StringProperty()
...how can I retrieve all Photos that belong to a public Album (that is, an Album with private == False)?
To further explain my intention, I thought it would be:
public_photos = Photos.all().filter('album.private = ', False)
and then I could do something like:
photos_for_homepage = public_photos.fetch(30)
but the query does not match anything, which tells me I'm going down the wrong path.
| [
"You can't. App engine doesn't support joins.\nOne approach is to implement the join manually. For example you could fetch all photos, then filter out the private ones in code. Or fetch all public albums, and then fetch each of their photos. It depends on your data as to whether this will perform okay or not.\nThe ... | [
4
] | [] | [] | [
"django",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003939830_django_google_app_engine_google_cloud_datastore_python.txt |
Q:
python - multi line stdout refresh issue
I have a stats app written in python that on a timer refreshes the ssh screen with stats. Right now it uses os.system('clear') to clear the screen and then outputs a multi line data with the stats.
I'd like to do just do a \r instead of executing the clear but that only works with one line, is it possible to do this with multiple lines?
A classic example of what I want to do is when you execute the "top" command which lists the current processes it updates the screen without executing the "clear" and it's got many lines.
Anyone have any tips for this?
A:
solved the issue with:
import curses
window = curses.initscr()
window.addstr(1, 0, "my text")
window.refresh()
curses.endwin()
A:
It doesn't really answer your question, but there isn't really anything wrong with calling os.system to clear out the terminal (other than the system running on different operating systems) in which case you could use:
os.system('cls' if os.name=='nt' else 'clear')
A:
For simple applications you can use:
print('\n' * number_of_lines)
For more advanced there is curses module in standard library.
| python - multi line stdout refresh issue | I have a stats app written in python that on a timer refreshes the ssh screen with stats. Right now it uses os.system('clear') to clear the screen and then outputs a multi line data with the stats.
I'd like to do just do a \r instead of executing the clear but that only works with one line, is it possible to do this with multiple lines?
A classic example of what I want to do is when you execute the "top" command which lists the current processes it updates the screen without executing the "clear" and it's got many lines.
Anyone have any tips for this?
| [
"solved the issue with:\nimport curses\nwindow = curses.initscr()\nwindow.addstr(1, 0, \"my text\")\nwindow.refresh()\ncurses.endwin() \n\n",
"It doesn't really answer your question, but there isn't really anything wrong with calling os.system to clear out the terminal (other than the system running on different ... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003939482_python.txt |
Q:
Which openid / oauth library to connect a django project to Google Apps Accounts?
I'm working on an intranet django project (not using GAE) for a company that uses Google Apps for login. So I'd like my users to be able to log in to my django project using their google accounts login. OpenID seems appropriate, although maybe Oauth might work too?
I see a lot of similarly named libraries out there to connect django's auth system to external login systems:
django-authopenid - http://bitbucket.org/benoitc/django-authopenid
django-openid - http://github.com/simonw/django-openid
django-openidauth - http://code.google.com/p/django-openid-auth/
django-oauth - http://bitbucket.org/david/django-oauth
Here's what I'd like to do with the integration: Have users login with their google accounts, instead of the native django system. Keep django's permissions model for things like the admin system. So I think that means automatically creating a new user record in django the first time a new account we haven't seen before logs in.
Can anyone with experience using any of these projects advise me on which would work best? Or just advice on which are most active / functional if you've tried them? Thanks!
A:
I finally got this working, so I'll answer my own question since the previous answers here were helpful but don't tell the whole story.
django-openid-auth is actually quite easy to set up and use. The README file is very clear. If you just want to use standard google accounts (i.e. @gmail.com addresses) then you configure it in settings.py with:
OPENID_SSO_SERVER_URL = 'https://www.google.com/accounts/o8/id'
But if you want to use a "google apps" account, i.e. hosted gmail at your own company's domain, then it's more complicated. I got my details from this question. To use your google apps accounts, configure your settings.py to:
OPENID_SSO_SERVER_URL = 'https://www.google.com/accounts/o8/site-xrds?hd=example.com'
# replace example.com with your hosted google apps domain
In the future this might just work, but today it probably won't. The problem is in python-openid which django-openid-auth relies on. The standard build of python-openid doesn't understand some protocol extensions google is using. (Why does google need to extend the protocol? Dig through http://groups.google.com/group/google-federated-login-api/web/openid-discovery-for-hosted-domains and report back. Good luck.) So you need to instead use adieu's patch to python-openid, which is available here:
http://github.com/adieu/python-openid
Install this over your existing python-openid. Now it should work.
Be careful with the OPENID_USE_AS_ADMIN_LOGIN setting since it requires you to have an openid user account which is 'staff' or 'superuser' to use admin which won't happen by default. So you'll need to do a 2-step process of enabling openid, logging in with your openid to create an account in django, then using your old admin account to mark your own openid account as superuser, and then disabling non-openid admin access.
One more thing: your domain admin might need to enable openid login for your domain before this will work. The control is at http://www.google.com/a/cpanel/example.com/SetupIdp
A:
I've used django-openid-auth. Works fine, can create user account when signing first time. You also can associate openid login with user account in django admin panel.
A:
I know this is a late answer, but I'm doing similar stuff and I just discovered django-socialregistration. which basically does OAuth, OpenID, Facebook Connect, etc. Unlike some of the other options it seems to be actively developed and used by a lot of projects.
A:
I liked that Django socialregistration allowed me to plug in Google Accounts, Facebook, Yahoo and any other OpenID site pretty easily. You just need to give the provider as a link like so:
<a href="/socialregistration/openid/redirect/?openid_provider={{ 'http://yahoo.com'|urlencode }}"><img src="{{MEDIA_URL}}/images/yahoo.png"/></a>
A:
They are all almost identical. I like django-authopenid. It has great documentation and is extremely easy to use. It'll do exactly what you want and do it better than django-openid (which is the only other one I have tried).
HTH
| Which openid / oauth library to connect a django project to Google Apps Accounts? | I'm working on an intranet django project (not using GAE) for a company that uses Google Apps for login. So I'd like my users to be able to log in to my django project using their google accounts login. OpenID seems appropriate, although maybe Oauth might work too?
I see a lot of similarly named libraries out there to connect django's auth system to external login systems:
django-authopenid - http://bitbucket.org/benoitc/django-authopenid
django-openid - http://github.com/simonw/django-openid
django-openidauth - http://code.google.com/p/django-openid-auth/
django-oauth - http://bitbucket.org/david/django-oauth
Here's what I'd like to do with the integration: Have users login with their google accounts, instead of the native django system. Keep django's permissions model for things like the admin system. So I think that means automatically creating a new user record in django the first time a new account we haven't seen before logs in.
Can anyone with experience using any of these projects advise me on which would work best? Or just advice on which are most active / functional if you've tried them? Thanks!
| [
"I finally got this working, so I'll answer my own question since the previous answers here were helpful but don't tell the whole story.\ndjango-openid-auth is actually quite easy to set up and use. The README file is very clear. If you just want to use standard google accounts (i.e. @gmail.com addresses) then yo... | [
17,
3,
1,
0,
0
] | [] | [] | [
"django",
"google_openid",
"openid",
"python"
] | stackoverflow_0003145453_django_google_openid_openid_python.txt |
Q:
Django: most efficient way to query many records?
I have a table with a few thousands records (products). Each product has a 4 different categories:
CAT1 CAT2 CAT3 CAT4
I wonder if is there a method, or what is the best practice, to dynamically retrive the available categories based on the categories already selected (using Ajax).
Example:
if CAT1 = green all the products with CAT1 = green will have a series of CAT2 categories and so on. I would like to know which are the CAT2 CAT3 CAT4 categories whose products match CAT1 = green. Once I set a value or CAT2 as well I would like to do the same based on CAT1 && CAT2 values.
Thanks.
A:
This is a technique commonly known as "select chaining" or "chained selects".
You can use some fairly simple javascript for this as shown in the answer to How to limit choice field options based on another choice field in django admin
You can also use a prepackaged solution such as django-smart-selects (found via the SO answer to django chain select)
A:
Thanks for the replies. The Chained select only works partially as I don't have a hierarchical structure.
Here is an example of data:
PRODUCT 1
CAT1 = vegetables
CAT2 = heavy
CAT3 = green
PRODUCT 2
CAT1 = vegetable
CAT2 = light
CAT3 = red
PRODUCT 3
CAT1 = diary
CAT2 = heavy
CAT3 = red
In my template I would like to make a system so that when the users choose CAT1 = vegetables they see CAT2 options to be heavvy and light while if they choose CAT1 = diary the only option for CAT2 is heavy and so on.
My way to go would be to get a json of the entire product table and look for the available values once a category has been selected... but the products table comprises thousands of items and Im quite sure it will slow down the entire app.
There is something similar in the admin page when you add the Filter function (list_filter) as it shows only the fields that have some entries in them.
THANKS!
| Django: most efficient way to query many records? | I have a table with a few thousands records (products). Each product has a 4 different categories:
CAT1 CAT2 CAT3 CAT4
I wonder if is there a method, or what is the best practice, to dynamically retrive the available categories based on the categories already selected (using Ajax).
Example:
if CAT1 = green all the products with CAT1 = green will have a series of CAT2 categories and so on. I would like to know which are the CAT2 CAT3 CAT4 categories whose products match CAT1 = green. Once I set a value or CAT2 as well I would like to do the same based on CAT1 && CAT2 values.
Thanks.
| [
"This is a technique commonly known as \"select chaining\" or \"chained selects\".\nYou can use some fairly simple javascript for this as shown in the answer to How to limit choice field options based on another choice field in django admin\nYou can also use a prepackaged solution such as django-smart-selects (foun... | [
0,
0
] | [] | [] | [
"ajax",
"django",
"django_templates",
"mysql",
"python"
] | stackoverflow_0003933871_ajax_django_django_templates_mysql_python.txt |
Q:
How to control the msn messager's "personal message" displayed to others by python?
How to control the msn messager's "personal message" displayed to others by python?
Want to share some private infomation remotely with this area.
A:
There are many python solutions that allow you to do MSN messaging with Python.
msnp
This has support for presence states with which you should be able to notify.
http://msnp.sourceforge.net/
msnlib
You could build scripts using this library, which is an opensource Python implementation for the MSN messenger protocol version 8.
http://blitiri.com.ar/p/msnlib/
| How to control the msn messager's "personal message" displayed to others by python? | How to control the msn messager's "personal message" displayed to others by python?
Want to share some private infomation remotely with this area.
| [
"There are many python solutions that allow you to do MSN messaging with Python.\n\nmsnp\n\nThis has support for presence states with which you should be able to notify.\n\nhttp://msnp.sourceforge.net/\n\n\nmsnlib\n\nYou could build scripts using this library, which is an opensource Python implementation for the MS... | [
1
] | [] | [] | [
"msn",
"python"
] | stackoverflow_0003940723_msn_python.txt |
Q:
Why Python sets my default timezone to -1?
I use Python to track the version between local SQLite and remote web page. It is useful to compare them by Last-modified and file size information from the HTTP response. I found something interesting during development.
def time_match(web,sql):
print web,sql
t1 = time.strptime(web,"%a, %d %b %Y %H:%M:%S %Z")
t2 = time.strptime(sql,"%Y-%m-%d %H:%M:%S")
print t1,t2
if t1==t2:
print "same time"
else:
print "different time"
return t1==t2
In above code, I tried to decode the time from web and SQLite into internal time and compare them. Let us check out the print screen as following:
Wed, 13 Oct 2010 01:13:26 GMT 2010-10-13 01:13:26
(2010, 10, 13, 1, 13, 26, 2, 286, 0) (2010, 10, 13, 1, 13, 26, 2, 286, -1)
different time
The result shows me that the GMT is correctly decoded, while the default timezone datetime of Python seems as -1. My system timezone is actually +8, Where is the -1 comes from? SQLite?
A:
The -1 at the last position in the time.struct_time object does not mean you are in the 'UTC-01:00'. It represents the undefined attribute is_dst (since YYYY-MM-DD HH:MM:SS format does not contain any information on the current timezone or daylight saving time mode).
time.strptime('2010-10-15 11:01:02', '%Y-%m-%d %H:%M:%S')
# returns the following on a computer with Central European Sommer Time (CEST, +02:00):
time.struct_time(tm_year=2010, tm_mon=10, tm_mday=15, tm_hour=11, tm_min=1, tm_sec=2, tm_wday=4, tm_yday=288, tm_isdst=-1)
| Why Python sets my default timezone to -1? | I use Python to track the version between local SQLite and remote web page. It is useful to compare them by Last-modified and file size information from the HTTP response. I found something interesting during development.
def time_match(web,sql):
print web,sql
t1 = time.strptime(web,"%a, %d %b %Y %H:%M:%S %Z")
t2 = time.strptime(sql,"%Y-%m-%d %H:%M:%S")
print t1,t2
if t1==t2:
print "same time"
else:
print "different time"
return t1==t2
In above code, I tried to decode the time from web and SQLite into internal time and compare them. Let us check out the print screen as following:
Wed, 13 Oct 2010 01:13:26 GMT 2010-10-13 01:13:26
(2010, 10, 13, 1, 13, 26, 2, 286, 0) (2010, 10, 13, 1, 13, 26, 2, 286, -1)
different time
The result shows me that the GMT is correctly decoded, while the default timezone datetime of Python seems as -1. My system timezone is actually +8, Where is the -1 comes from? SQLite?
| [
"The -1 at the last position in the time.struct_time object does not mean you are in the 'UTC-01:00'. It represents the undefined attribute is_dst (since YYYY-MM-DD HH:MM:SS format does not contain any information on the current timezone or daylight saving time mode).\ntime.strptime('2010-10-15 11:01:02', '%Y-%m-%d... | [
1
] | [] | [] | [
"python",
"sqlite",
"timezone"
] | stackoverflow_0003940738_python_sqlite_timezone.txt |
Q:
noob question regarding twitter oauth
I'm unfamiliar with the new oauth system. I wanted to crawl the status updates of my friends, and their friends' (if permissions allow) with my specified account credentials using the python-twitter api.
With the new oauth authentication, does it means that I have to first register an application with twitter before I can use api?
A:
Yes, thats right. You need to register it and connect "grant access" it with your twitter id, if you want, for example, post something on your twitter wall. Also see "connections" in your twitter id.
A:
For use api you must register your aplication or use GET methods to post into twi through web interface.
| noob question regarding twitter oauth | I'm unfamiliar with the new oauth system. I wanted to crawl the status updates of my friends, and their friends' (if permissions allow) with my specified account credentials using the python-twitter api.
With the new oauth authentication, does it means that I have to first register an application with twitter before I can use api?
| [
"Yes, thats right. You need to register it and connect \"grant access\" it with your twitter id, if you want, for example, post something on your twitter wall. Also see \"connections\" in your twitter id.\n",
"For use api you must register your aplication or use GET methods to post into twi through web interface... | [
1,
0
] | [] | [] | [
"oauth",
"python",
"twitter"
] | stackoverflow_0003940774_oauth_python_twitter.txt |
Q:
how the bittorent is compiled to exe
As all know bittorrent is written in python program. whenever i download and install the bittorrent.exe, I never found any file(like dll etc) associated in program files i mean whenever i go to c:\program files\bittorrent i found only single file called bittorrent.exe, i wonder how this program is compiled to exe , whereas whenever i want to build standalone python exe i use py2exe and i found the output consists of nearly 25mb, which consists of all library file included.
Can anybody will tell me the detail structure how the bittorent program is build into exe.
A:
Actually bittorrent is a protocol. The original program which implemented bittorrent may have been written in Python but that's not the case now.
A lot of them now are coded in compiled languages, Transmission being the one I'm most familiar with (comes with Ubuntu) - it uses gcc.
A:
You mean the, umm, "official" BitTorrent client from bittorrent.com, right? I couldn't find the latest source code but older versions were built using py2exe (see winsetup.py of the client v4.26). I can't explain why your py2exe output is so huge, but the setup.py file included in the sources seems to exclude a lot of modules. Maybe you used the setup.py file that was intended for Linux/Unix.
If you didn't mean that client GUI, you should know that BitTorrent is actually just the protocol, and there exist multiple libraries and GUIs that implement it.
A:
Take a look at http://www.bittorrent.com/company/jobs. They are looking for C/C++ developers... not python.
A:
Look in the documentation for the BitTorrent client that you use. There are several Python clients and each one does things differently.
| how the bittorent is compiled to exe | As all know bittorrent is written in python program. whenever i download and install the bittorrent.exe, I never found any file(like dll etc) associated in program files i mean whenever i go to c:\program files\bittorrent i found only single file called bittorrent.exe, i wonder how this program is compiled to exe , whereas whenever i want to build standalone python exe i use py2exe and i found the output consists of nearly 25mb, which consists of all library file included.
Can anybody will tell me the detail structure how the bittorent program is build into exe.
| [
"Actually bittorrent is a protocol. The original program which implemented bittorrent may have been written in Python but that's not the case now.\nA lot of them now are coded in compiled languages, Transmission being the one I'm most familiar with (comes with Ubuntu) - it uses gcc.\n",
"You mean the, umm, \"offi... | [
4,
2,
0,
0
] | [] | [] | [
"executable",
"python"
] | stackoverflow_0003940782_executable_python.txt |
Q:
NaN giving an error depending on Python startup?
I am using Python4Delphi to embed Python in a Delphi program. Versions: Python 2.6.4, Delphi 2009, Windows XP.
The Delphi program crashes with EInvalidOp when importing json. I tracked it to the line
NaN, PosInf, NegInf = float('nan'), float('inf'), float('-inf')
in json.decoder.
Sure enough, the command float('nan') raises an EInvalidOp when run inside Python embedded in the Delphi program. When executed in the command line Python (same installation) it simply returns nan.
Any idea what is the difference between the Python standard startup and that of the embedded one that may result in such an error?
A:
This is most likely that Python uses a different 8087 control word (CW) setting than Delphi.
Try this kind of code:
var
OldControlWord: Word;
begin
OldControlWord := Get8087CW();
Set8087CW($133F);
try
// perform your Python code here
finally
Set8087CW(OldControlWord);
end;
end;
See my blog article on the 8087 CW in Delphi for a more detailed explanation of the $133F value.
It needs the JCL for the T8087Precision type (which is in the Jcl8087 unit).
--jeroen
A:
I use the following:
$1332 is the delphi default.
$1232 is the value to deal with Python Issue 9980.
procedure MaskFPUExceptions(ExceptionsMasked : boolean);
begin
// if ExceptionsMasked then
// Set8087CW($1332 or $3F)
// else
// Set8087CW($1332);
if ExceptionsMasked then
Set8087CW($1232 or $3F)
else
Set8087CW($1232);
end;
| NaN giving an error depending on Python startup? | I am using Python4Delphi to embed Python in a Delphi program. Versions: Python 2.6.4, Delphi 2009, Windows XP.
The Delphi program crashes with EInvalidOp when importing json. I tracked it to the line
NaN, PosInf, NegInf = float('nan'), float('inf'), float('-inf')
in json.decoder.
Sure enough, the command float('nan') raises an EInvalidOp when run inside Python embedded in the Delphi program. When executed in the command line Python (same installation) it simply returns nan.
Any idea what is the difference between the Python standard startup and that of the embedded one that may result in such an error?
| [
"This is most likely that Python uses a different 8087 control word (CW) setting than Delphi.\nTry this kind of code:\nvar\n OldControlWord: Word;\nbegin\n OldControlWord := Get8087CW();\n Set8087CW($133F);\n try\n // perform your Python code here\n finally\n Set8087CW(OldControlWord); \n end;\nend... | [
5,
1
] | [] | [] | [
"delphi",
"embedding",
"python"
] | stackoverflow_0003933851_delphi_embedding_python.txt |
Q:
Python - HTML Parsing with Tidy
This code takes a bit of bad html, uses the Tidy library to clean it up and then passes it to an HtmlLib.Reader().
import tidy
options = dict(output_xhtml=1,
add_xml_decl=1,
indent=1,
tidy_mark=0)
from xml.dom.ext.reader import HtmlLib
reader = HtmlLib.Reader()
doc = reader.fromString(tidy.parseString("<Html>Bad Html.", **options))
I'm not passing fromString with the right type, it seems, with this Traceback:
Traceback (most recent call last):
File "getComicEmbed.py", line 33, in <module>
doc = reader.fromString(tidy.parseString("<Html>Bad Html.</b>", **options))
File "C:\Python26\lib\site-packages\_xmlplus\dom\ext\reader\HtmlLib.py", line 67, in fromString
stream = reader.StrStream(str)
File "C:\Python26\lib\site-packages\_xmlplus\dom\ext\reader\__init__.py", line 24, in StrStream
return cStringIO.StringIO(st)
TypeError: expected read buffer, _Document found
What should I do differently? Thanks!
A:
tidy's parseString function returns a _Document instance which implements __str__ but not a buffer interface. Therefore HtmlLib.Reader().fromString cannot create a StringIO object out of it.
This should be fairly simple, change:
doc = reader.fromString(tidy.parseString("<Html>Bad Html.", **options))
to
doc = reader.fromString(str(tidy.parseString("<Html>Bad Html.", **options)))
A:
I haven't used the Python tidy module, and am not sure how to find it, but it looks like you need to call something like toString on the result of tidy.fromString to convert your parsed document back into XHTML.
For a different approach, you could consider using lxml.html, which is decent at parsing broken markup and provides you with a great ElementTree API for working with the result. It can also pretty-print *ML, which makes it sort of a superset of tidy, though perhaps not with quite the same ability to navigate incoherent markup.
Also: lxml is written in C (actually, like the python tidy module(s), just wraps a C library) so it's much faster than some of the other python modules for working with XML.
| Python - HTML Parsing with Tidy | This code takes a bit of bad html, uses the Tidy library to clean it up and then passes it to an HtmlLib.Reader().
import tidy
options = dict(output_xhtml=1,
add_xml_decl=1,
indent=1,
tidy_mark=0)
from xml.dom.ext.reader import HtmlLib
reader = HtmlLib.Reader()
doc = reader.fromString(tidy.parseString("<Html>Bad Html.", **options))
I'm not passing fromString with the right type, it seems, with this Traceback:
Traceback (most recent call last):
File "getComicEmbed.py", line 33, in <module>
doc = reader.fromString(tidy.parseString("<Html>Bad Html.</b>", **options))
File "C:\Python26\lib\site-packages\_xmlplus\dom\ext\reader\HtmlLib.py", line 67, in fromString
stream = reader.StrStream(str)
File "C:\Python26\lib\site-packages\_xmlplus\dom\ext\reader\__init__.py", line 24, in StrStream
return cStringIO.StringIO(st)
TypeError: expected read buffer, _Document found
What should I do differently? Thanks!
| [
"tidy's parseString function returns a _Document instance which implements __str__ but not a buffer interface. Therefore HtmlLib.Reader().fromString cannot create a StringIO object out of it.\nThis should be fairly simple, change:\ndoc = reader.fromString(tidy.parseString(\"<Html>Bad Html.\", **options))\n\nto\ndoc... | [
4,
1
] | [] | [] | [
"html_parsing",
"python",
"tidy"
] | stackoverflow_0003941038_html_parsing_python_tidy.txt |
Q:
Passing a sequence of the same form? - Django
the user needs to provide a list of field/values through a form
class FieldForm(forms.Form):
field_name = forms.CharField()
field_value = forms.CharField()
The problem is how do I get a user to pass multiple of these with one submit?
Also as a side question... any tips on implementing editing too?
Any ideas? It would be really great to get your feedback! :)
A:
Sounds like formsets are what you are after.
| Passing a sequence of the same form? - Django | the user needs to provide a list of field/values through a form
class FieldForm(forms.Form):
field_name = forms.CharField()
field_value = forms.CharField()
The problem is how do I get a user to pass multiple of these with one submit?
Also as a side question... any tips on implementing editing too?
Any ideas? It would be really great to get your feedback! :)
| [
"Sounds like formsets are what you are after.\n"
] | [
1
] | [] | [] | [
"django",
"forms",
"html",
"http",
"python"
] | stackoverflow_0003941260_django_forms_html_http_python.txt |
Q:
Efficient substring searching in Python with MySQL
I'm trying to implement a live search for my website. One that identifies words, or parts of a word, in a given string. The instant results are then underlined where they match the query.
For example, a query of "Fried green tomatoes" would yield:
SELECT *
FROM articles
WHERE (title LIKE '%fried%' OR
title LIKE '%green%' OR
title LIKE '%tomatoes%)
This works perfectly with a very small dataset. However, once the number of records in the database increases, this query quickly becomes inefficient because it can't utilize indices.
I know this is technically what FULLTEXT searching in MySQL is for, but the quality of results just isn't as good.
What are some alternatives to get a very high quality substring search while keeping the query efficient?
Thanks.
A:
Sphinx will help you to search fast within the huge amount of data
A:
they are many FULLTEXT search engine that you can use like sphinx , Apache Solr, Whoosh (it's pure python) and Xapian. django-haystack (if you are using django) which can interface with the 3 last ones;
| Efficient substring searching in Python with MySQL | I'm trying to implement a live search for my website. One that identifies words, or parts of a word, in a given string. The instant results are then underlined where they match the query.
For example, a query of "Fried green tomatoes" would yield:
SELECT *
FROM articles
WHERE (title LIKE '%fried%' OR
title LIKE '%green%' OR
title LIKE '%tomatoes%)
This works perfectly with a very small dataset. However, once the number of records in the database increases, this query quickly becomes inefficient because it can't utilize indices.
I know this is technically what FULLTEXT searching in MySQL is for, but the quality of results just isn't as good.
What are some alternatives to get a very high quality substring search while keeping the query efficient?
Thanks.
| [
"Sphinx will help you to search fast within the huge amount of data\n",
"they are many FULLTEXT search engine that you can use like sphinx , Apache Solr, Whoosh (it's pure python) and Xapian. django-haystack (if you are using django) which can interface with the 3 last ones;\n"
] | [
2,
0
] | [] | [] | [
"binary_tree",
"database",
"mysql",
"python"
] | stackoverflow_0003939776_binary_tree_database_mysql_python.txt |
Q:
Relating two consecutive lines in a file
I have a txt file of repeating lines like this:
Host: http://de.wikipedia.org
Referer: http://www.wikipedia.org
Host: answers.yahoo.com/
Referer: http://www.yahoo.com
Host: http://de.wikipedia.org
Referer: http://www.wikipedia.org
Host: http://maps.yahoo.com/
Referer: http://www.yahoo.com
Host: http://pt.wikipedia.org
Referer: http://www.wikipedia.org
Host: answers.yahoo.com/
Referer: http://www.yahoo.com
Host: mail.yahoo.com
Referer: http://www.yahoo.com
Host: http://fr.wikipedia.org
Referer: http://www.wikipedia.org
Host: mail.yahoo.com
Referer: http://www.yahoo.com
I am trying with this piece of code to go through the lines and see how many hosts have been accessed through the same referrer:
dd = {}
for line in open('hosts.txt'):
if line.startswith('Host'):
host = line.split(':')[1].strip('\n')
elif line.startswith('Referer'):
referer = line.split(': ')[1].strip('\n')
dd.setdefault(referer, [0 , host])
dd[referer][0] += 1
print dd
e.g.from wikipedia.org, how many links or domains have been accessed.
I want only the first occurrence of any referrer, and for the hosts belonging to that referrer I want the sum of all of them, ignoring the host that has been already counted for the same referrer, so basically whenever the referrer and the host are the same and they have been already counted, I want them to be ignored, to have 'referrer' as key and sum of unique hosts as values, as in below:
{'http://www.wikipedia.org': 3 , 'www.yahoo.com' : 2}
The problem with my code is that it sums all the repeating hosts for the same referrer because I can't figure out how to relate the Host and Referer lines. So any hint or help is highly appreciated.
A:
You could have a set for each referrer in the dictionary, rather than just a number. This way you could just add each host to the set, and duplicates will automatically be discarded. To get the number of hosts for the referrer, get the number of elements in the set.
dd = {}
referrer = None
for line in open('hosts.txt'):
if line.startswith('Host'):
host = line.split(': ')[1].strip('\n')
elif line.startswith('Referer'):
referrer = line.split(': ')[1].strip('\n')
if referrer is not None:
dd.setdefault(referrer, set()).add(host)
referrer = None
for k, v in dd.iteritems():
print k, len(v)
| Relating two consecutive lines in a file | I have a txt file of repeating lines like this:
Host: http://de.wikipedia.org
Referer: http://www.wikipedia.org
Host: answers.yahoo.com/
Referer: http://www.yahoo.com
Host: http://de.wikipedia.org
Referer: http://www.wikipedia.org
Host: http://maps.yahoo.com/
Referer: http://www.yahoo.com
Host: http://pt.wikipedia.org
Referer: http://www.wikipedia.org
Host: answers.yahoo.com/
Referer: http://www.yahoo.com
Host: mail.yahoo.com
Referer: http://www.yahoo.com
Host: http://fr.wikipedia.org
Referer: http://www.wikipedia.org
Host: mail.yahoo.com
Referer: http://www.yahoo.com
I am trying with this piece of code to go through the lines and see how many hosts have been accessed through the same referrer:
dd = {}
for line in open('hosts.txt'):
if line.startswith('Host'):
host = line.split(':')[1].strip('\n')
elif line.startswith('Referer'):
referer = line.split(': ')[1].strip('\n')
dd.setdefault(referer, [0 , host])
dd[referer][0] += 1
print dd
e.g.from wikipedia.org, how many links or domains have been accessed.
I want only the first occurrence of any referrer, and for the hosts belonging to that referrer I want the sum of all of them, ignoring the host that has been already counted for the same referrer, so basically whenever the referrer and the host are the same and they have been already counted, I want them to be ignored, to have 'referrer' as key and sum of unique hosts as values, as in below:
{'http://www.wikipedia.org': 3 , 'www.yahoo.com' : 2}
The problem with my code is that it sums all the repeating hosts for the same referrer because I can't figure out how to relate the Host and Referer lines. So any hint or help is highly appreciated.
| [
"You could have a set for each referrer in the dictionary, rather than just a number. This way you could just add each host to the set, and duplicates will automatically be discarded. To get the number of hosts for the referrer, get the number of elements in the set.\ndd = {}\nreferrer = None\n\nfor line in open('h... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003941378_python.txt |
Q:
Using map to process a list-of-objects in python
I want to calculate the center-of-mass using the map function. I don't want to use for loops. Help with bottom two lines?
class Obj():
def __init__(self, mass = 0., x = 0., y = 0.):
self.mass = mass
self.x = x
self.y = y
# Create List of Objects
objList = []
n = 0
for i in range(0,10):
for j in range(0,10):
objList.append(Obj(i*j,i,j))
# Calculate Center of Mass of List
# The following is pseudocode, does not actually work
SumOfMass = sum(objList[:].mass)
CenterOfMassX = sum(objList[:].x.*objList[:].mass)/SumOfMass
A:
You can't do the last two lines unless you abandon your anti-for prejudice.
SumOfMass = sum(obj.mass for obj in objList)
CenterOfMassX = sum(obj.x * obj.mass for obj in objList)/SumOfMass
With py2k (which are you using?), map(func, alist) is equivalent to [func(v) for v in alist] i.e. it returns a list. You need two scalar answers, not one or two vectors. What func did you have in mind? Why do you want to calculate the center of mass using the map function?
A:
sumofmass = sum(i.mass for i in objList)
centre = sum(i.x * i.mass for i in objList)/sumofmass
also, you could populate your objList like this:
objList = [Obj(i*j, i, j) for in range(10) for j in range(10)]
Note, that range takes only integer arguments.
P.S. map is a for loop.
A:
If you are really dead set against using for, you can use the attrgetter function from the operator module. E.G.:
from operator import attrgetter
mass_of = attrgetter('mass')
SumOfMass = sum(map(mass_of, objList))
However, doing so runs contrary to the dictates of Python style (as does using camelCase variables — normally you name them like_this). It's more or less acceptable to use map if the thing you need to access is already in the form of a function which takes the sequence element as its only parameter. In other words, if you can call map(some_function, sequence) without having to jump through any hoops like those above to get some_function, then it's okay.
For other situations (which is most of them), it's considered preferable or mandatory to use a list-comprehension style as exemplified in some of the other answers.
| Using map to process a list-of-objects in python | I want to calculate the center-of-mass using the map function. I don't want to use for loops. Help with bottom two lines?
class Obj():
def __init__(self, mass = 0., x = 0., y = 0.):
self.mass = mass
self.x = x
self.y = y
# Create List of Objects
objList = []
n = 0
for i in range(0,10):
for j in range(0,10):
objList.append(Obj(i*j,i,j))
# Calculate Center of Mass of List
# The following is pseudocode, does not actually work
SumOfMass = sum(objList[:].mass)
CenterOfMassX = sum(objList[:].x.*objList[:].mass)/SumOfMass
| [
"You can't do the last two lines unless you abandon your anti-for prejudice.\nSumOfMass = sum(obj.mass for obj in objList) \nCenterOfMassX = sum(obj.x * obj.mass for obj in objList)/SumOfMass \n\nWith py2k (which are you using?), map(func, alist) is equivalent to [func(v) for v in alist] i.e. it returns a lis... | [
3,
2,
2
] | [] | [] | [
"list",
"map",
"python"
] | stackoverflow_0003941486_list_map_python.txt |
Q:
Converting list to *args when calling function
In Python, how do I convert a list to *args?
I need to know because the function
scikits.timeseries.lib.reportlib.Report.__init__(*args)
wants several time_series objects passed as *args, whereas I have a list of timeseries objects.
A:
You can use the * operator before an iterable to expand it within the function call. For example:
timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)
(notice the * before timeseries_list)
From the python documentation:
If the syntax *expression appears in the function call, expression
must evaluate to an iterable. Elements from this iterable are treated
as if they were additional positional arguments; if there are
positional arguments x1, ..., xN, and expression evaluates to a
sequence y1, ..., yM, this is equivalent to a call with M+N positional
arguments x1, ..., xN, y1, ..., yM.
This is also covered in the python tutorial, in a section titled Unpacking argument lists, where it also shows how to do a similar thing with dictionaries for keyword arguments with the ** operator.
A:
yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.
so:
>>> def printer(*args):
print args
>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>>
A:
*args just means that the function takes a number of arguments, generally of the same type.
Check out this section in the Python tutorial for more info.
| Converting list to *args when calling function | In Python, how do I convert a list to *args?
I need to know because the function
scikits.timeseries.lib.reportlib.Report.__init__(*args)
wants several time_series objects passed as *args, whereas I have a list of timeseries objects.
| [
"You can use the * operator before an iterable to expand it within the function call. For example:\ntimeseries_list = [timeseries1 timeseries2 ...]\nr = scikits.timeseries.lib.reportlib.Report(*timeseries_list)\n\n(notice the * before timeseries_list)\nFrom the python documentation:\n\nIf the syntax *expression app... | [
263,
25,
3
] | [] | [] | [
"arguments",
"function_call",
"list",
"python"
] | stackoverflow_0003941517_arguments_function_call_list_python.txt |
Q:
MySQL server has gone away error with Pylons, SQLAlchemy, Apache
sorry if this is addressed, but i'm running
apache2
SQLAlchemy 0.5.8
Pylons 1.0
Python 2.5.2
and on a simple page (just retrieve data from DB), I get:
Error - : (OperationalError) (2006,
'MySQL server has gone away')
every few other requests, not after a long time as other posts I've searched
for. I still added
sqlalchemy.pool_recycle = 1800
but that did not fix the issue. After a fresh apache restart, every 5th or
6th requests gets a 500 from the above error, so its not a result of a long time out.
thanks
A:
You can try to increase max_allowed_packet configuration parameter value in you MySQL config.
http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_allowed_packet
For example:
max_allowed_packet=128M
| MySQL server has gone away error with Pylons, SQLAlchemy, Apache | sorry if this is addressed, but i'm running
apache2
SQLAlchemy 0.5.8
Pylons 1.0
Python 2.5.2
and on a simple page (just retrieve data from DB), I get:
Error - : (OperationalError) (2006,
'MySQL server has gone away')
every few other requests, not after a long time as other posts I've searched
for. I still added
sqlalchemy.pool_recycle = 1800
but that did not fix the issue. After a fresh apache restart, every 5th or
6th requests gets a 500 from the above error, so its not a result of a long time out.
thanks
| [
"You can try to increase max_allowed_packet configuration parameter value in you MySQL config.\nhttp://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_allowed_packet\nFor example:\nmax_allowed_packet=128M\n\n"
] | [
1
] | [] | [] | [
"mysql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0003937945_mysql_pylons_python_sqlalchemy.txt |
Q:
python windows standalone exe file
whenever i build python file to exe file from py2exe, it takes lots of space of minimum 25MB for small project also,it includes all the the python library file. Is there any other way that i can reduce the size.
A:
You should have read the documentation before using. Here's a page you can read
A:
Python programs need python to run. All py2exe does is to include full python and all libraries you use together with your script in a single file.
A:
py2exe tends to err on the side of caution. You can manually exclude some libraries with the exclude list option in order to reduce the size of the file.
In my experience, you should be able to compress down to a ~9 MB installer (Inno) if you include wxPython or another GUI framework, ~7 MB if you ship a console app or use tkinter.
| python windows standalone exe file | whenever i build python file to exe file from py2exe, it takes lots of space of minimum 25MB for small project also,it includes all the the python library file. Is there any other way that i can reduce the size.
| [
"You should have read the documentation before using. Here's a page you can read\n",
"Python programs need python to run. All py2exe does is to include full python and all libraries you use together with your script in a single file.\n",
"py2exe tends to err on the side of caution. You can manually exclude some... | [
6,
3,
0
] | [
"No, not really; you need Python shipped with the exe so that it is standalone. It it not common to create exe Files from Python projects, anyway.\n"
] | [
-2
] | [
"py2exe",
"python"
] | stackoverflow_0003941830_py2exe_python.txt |
Q:
How to speed up python views in CouchDB?
I'm working on my CouchDB with Python, cause I love python. The problem is: On my machine (it's a Seagate Dockstar) it's quite slow. How can I increase the speed?
a) I've tried to use psyco. It's not available for that plattform.
b) I've tried to put the imports outside my function-definitons. This doesn't work since the couchpy throws an error because in the file there's not a parsable function.
What else should be possible? I don't want to learn erlang...
A:
I know you said you didn't want to learn Erlang, but I really think you should Learn You Some Erlang for Great Good!
| How to speed up python views in CouchDB? | I'm working on my CouchDB with Python, cause I love python. The problem is: On my machine (it's a Seagate Dockstar) it's quite slow. How can I increase the speed?
a) I've tried to use psyco. It's not available for that plattform.
b) I've tried to put the imports outside my function-definitons. This doesn't work since the couchpy throws an error because in the file there's not a parsable function.
What else should be possible? I don't want to learn erlang...
| [
"I know you said you didn't want to learn Erlang, but I really think you should Learn You Some Erlang for Great Good!\n"
] | [
0
] | [] | [] | [
"couchdb",
"performance",
"python"
] | stackoverflow_0003941893_couchdb_performance_python.txt |
Q:
How to set a python property in __init__
I have a class with an attribute I wish to turn into a property, but this attribute is set within __init__. Not sure how this should be done. Without setting the property in __init__ this is easy and works well
import datetime
class STransaction(object):
"""A statement transaction"""
def __init__(self):
self._date = None
@property
def date(self):
return self._date
@date.setter
def date(self, value):
d = datetime.datetime.strptime(value, "%d-%b-%y")
self._date = d
st = STransaction()
st.date = "20-Jan-10"
But once initialization needs to occur in __init__ it gets more complicated and I am not sure of the correct course of action.
class STransaction(object):
"""A statement transaction"""
def __init__(self, date):
self._date = None
Strangely to me, the following seems to work but smells very bad.
class STransaction(object):
"""A statement transaction"""
def __init__(self, date):
self._date = None
self.date = date
@property
def date(self):
return self._date
@date.setter
def date(self, value):
d = datetime.datetime.strptime(value, "%d-%b-%y")
self._date = d
What is the correct way to go about setting properties in __init__?
Thanks,
Aaron.
A:
I do not see any real problem with your code. In __init__, the class is fully created and thus the properties accessible.
A:
class STransaction(object):
"""A statement transaction"""
def __init__(self, date):
self._date = None #1
self.date = date #2
If you want to set the proxy field self._date without executing of your setter use the #1 line. If you would like to execute the setter at startup too use the #2. Both ways are correct, it's just a matter of what do you want to do.
| How to set a python property in __init__ | I have a class with an attribute I wish to turn into a property, but this attribute is set within __init__. Not sure how this should be done. Without setting the property in __init__ this is easy and works well
import datetime
class STransaction(object):
"""A statement transaction"""
def __init__(self):
self._date = None
@property
def date(self):
return self._date
@date.setter
def date(self, value):
d = datetime.datetime.strptime(value, "%d-%b-%y")
self._date = d
st = STransaction()
st.date = "20-Jan-10"
But once initialization needs to occur in __init__ it gets more complicated and I am not sure of the correct course of action.
class STransaction(object):
"""A statement transaction"""
def __init__(self, date):
self._date = None
Strangely to me, the following seems to work but smells very bad.
class STransaction(object):
"""A statement transaction"""
def __init__(self, date):
self._date = None
self.date = date
@property
def date(self):
return self._date
@date.setter
def date(self, value):
d = datetime.datetime.strptime(value, "%d-%b-%y")
self._date = d
What is the correct way to go about setting properties in __init__?
Thanks,
Aaron.
| [
"I do not see any real problem with your code. In __init__, the class is fully created and thus the properties accessible.\n",
"class STransaction(object):\n \"\"\"A statement transaction\"\"\"\n def __init__(self, date):\n self._date = None #1\n self.date = date #2\n\nIf you want to set the ... | [
30,
10
] | [] | [] | [
"properties",
"python"
] | stackoverflow_0003941919_properties_python.txt |
Q:
Python - Creating a "scripting" system
I'm making a wxpython app that I will compile with the various freezing utility out there to create an executable for multiple platforms.
the program will be a map editer for a tile-based game engine
in this app I want to provide a scripting system so that advanced users can modify the behavior of the program such as modifying project data, exporting the project to a different format ect.
I want the system to work like so.
the user will place the python script they wish to run into a styled textbox and then press a button to execute the script.
I'm good with this so far thats all really simple stuff.
obtain the script from the text-box as a string compile it to a cod object with the inbuilt function compile() then execute the script with an exec statment
script = textbox.text #bla bla store the string
code = compile(script, "script", "exec") #make the code object
eval(code, globals())
the thing is, I want to make sure that this feature can't cause any errors or bugs
say if there is an import statement in the script. will this cause any problems taking into account that the code has been compiled with something like py2exe or py2app?
how do I make sure that the user can't break critical part of the program like modifying part of the GUI while still allowing them to modify the project data (the data is held in global properties in it's own module)? I think that this would mean modifying the globals dict that is passed to the eval function.
how to I make sure that this eval can't cause the program to hang due to a long or infinite loop?
how do I make sure that an error raised inside the user's code can't crash the whole app?
basically, how to I avoid all those problems that can arise when allowing the user to run their own code?
EDIT: Concerning the answers given
I don't feel like any of the answers so far have really answered my questions
yes they have been in part answered but not completely. I'm well aware the it is impossible to completely stop unsafe code. people are just too clever for one man (or even a teem) to think of all the ways to get around a security system and prevent them.
in fact I don't really care if they do. I'm more worried about some one unintentional breaking something they didn't know about. if some one really wanted to they could tear the app to shreds with the scripting functionality, but I couldn't care less. it will be their instance and all the problem they create will be gone when they restart the app unless they have messed with files on the HD.
I want to prevent the problems that arise when the user dose something stupid.
things like IOError's, SystaxErrors, InfiniteLoopErrors ect.
now the part about scope has been answered. I now understand how to define what functions and globals can be accessed from the eval function
but is there a way to make sure that the execution of their code can be stopped if it is taking too long?
a green thread system perhaps? (green because it would be eval to make users worry about thread safety)
also if a users uses an import module statement to load a module from even the default library that isn't used in the rest of the class. could this cause problems with the app being frozen by Py2exe, Py2app, or Freeze? what if they call a modal out side of the standard library? would it be enough that the modal is present in the same directory as the frozen executable?
I would like to get these answers with out creating a new question but I will if I must.
A:
Easy answer: don't.
You can forbid certain keywords (import) and operations, and accesses to certain data structures, but ultimately you're giving your power users quite a bit of power. Since this is for a rich client that runs on the user's machine, a malicious user can crash or even trash the whole app if they really feel like it. But it's their instance to crash. Document it well and tell people what not to touch.
That said, I've done this sort of thing for web apps that execute user input and yes, call eval like this:
eval(code, {"__builtins__":None}, {safe_functions})
where safe_functions is a dictionary containing {"name": func} type pairs of functions you want your users to be able to access. If there's some essential data structure that you're positive your users will never want to poke at, just pop it out of globals before passing them in.
Incidentally, Guido addressed this issue on his blog a while ago. I'll see if I can find it.
Edit: found.
A:
Short Answer: No
Is using eval in Python a bad practice?
Other related posts:
Safety of Python 'eval' For List Deserialization
It is not easy to create a safety net. The details too many and clever hacks are around:
Python: make eval safe
On your design goals:
It seems you are trying to build an extensible system by providing user to modify a lot of behavior and logic.
Easiest option is to ask them to write a script which you can evaluate (eval) during the program run.
How ever, a good design describes , scopes the flexibility and provides scripting mechanism through various design schemes ranging from configuration, plugin to scripting capabilities etc. The scripting apis if well defined can provide more meaningful extensibility. It is safer too.
A:
I'd suggest providing some kind of plug-in API and allowing users to provide plug-ins in the form of text files. You can then import them as modules into their own namespace, catching syntax errors in the process, and call the various functions defined in the plug-in module, again checking for errors. You can provide an API module that defines the functions/classes from your program that the plug-in module has access to. That gives you the freedom to make changes to your application's architecture without breaking plug-ins, since you can just adapt the API module to expose the functionality in the same way.
A:
If you have the option to switch to Tkinter you can use the bundled tcl interpreter to process your script. For that matter you can probably do that with a wxpython app if you don't start the tk event loop; just use the tcl interpreter without creating any windows.
Since the tcl interpreter is a separate thing it should be nearly impossible to crash the python interpreter if you are careful about what commands you expose to tcl. Plus, tcl makes creating DSLs very easy.
Python - the only scripting language with a built-in scripting engine :-).
| Python - Creating a "scripting" system | I'm making a wxpython app that I will compile with the various freezing utility out there to create an executable for multiple platforms.
the program will be a map editer for a tile-based game engine
in this app I want to provide a scripting system so that advanced users can modify the behavior of the program such as modifying project data, exporting the project to a different format ect.
I want the system to work like so.
the user will place the python script they wish to run into a styled textbox and then press a button to execute the script.
I'm good with this so far thats all really simple stuff.
obtain the script from the text-box as a string compile it to a cod object with the inbuilt function compile() then execute the script with an exec statment
script = textbox.text #bla bla store the string
code = compile(script, "script", "exec") #make the code object
eval(code, globals())
the thing is, I want to make sure that this feature can't cause any errors or bugs
say if there is an import statement in the script. will this cause any problems taking into account that the code has been compiled with something like py2exe or py2app?
how do I make sure that the user can't break critical part of the program like modifying part of the GUI while still allowing them to modify the project data (the data is held in global properties in it's own module)? I think that this would mean modifying the globals dict that is passed to the eval function.
how to I make sure that this eval can't cause the program to hang due to a long or infinite loop?
how do I make sure that an error raised inside the user's code can't crash the whole app?
basically, how to I avoid all those problems that can arise when allowing the user to run their own code?
EDIT: Concerning the answers given
I don't feel like any of the answers so far have really answered my questions
yes they have been in part answered but not completely. I'm well aware the it is impossible to completely stop unsafe code. people are just too clever for one man (or even a teem) to think of all the ways to get around a security system and prevent them.
in fact I don't really care if they do. I'm more worried about some one unintentional breaking something they didn't know about. if some one really wanted to they could tear the app to shreds with the scripting functionality, but I couldn't care less. it will be their instance and all the problem they create will be gone when they restart the app unless they have messed with files on the HD.
I want to prevent the problems that arise when the user dose something stupid.
things like IOError's, SystaxErrors, InfiniteLoopErrors ect.
now the part about scope has been answered. I now understand how to define what functions and globals can be accessed from the eval function
but is there a way to make sure that the execution of their code can be stopped if it is taking too long?
a green thread system perhaps? (green because it would be eval to make users worry about thread safety)
also if a users uses an import module statement to load a module from even the default library that isn't used in the rest of the class. could this cause problems with the app being frozen by Py2exe, Py2app, or Freeze? what if they call a modal out side of the standard library? would it be enough that the modal is present in the same directory as the frozen executable?
I would like to get these answers with out creating a new question but I will if I must.
| [
"Easy answer: don't.\nYou can forbid certain keywords (import) and operations, and accesses to certain data structures, but ultimately you're giving your power users quite a bit of power. Since this is for a rich client that runs on the user's machine, a malicious user can crash or even trash the whole app if they ... | [
5,
1,
0,
0
] | [] | [] | [
"eval",
"python",
"scripting",
"security",
"wxpython"
] | stackoverflow_0003938184_eval_python_scripting_security_wxpython.txt |
Q:
exhausted iterators - what to do about them?
(In Python 3.1)
(Somewhat related to another question I asked, but this question is about iterators being exhausted.)
# trying to see the ratio of the max and min element in a container c
filtered = filter(lambda x : x is not None and x != 0, c)
ratio = max(filtered) / min(filtered)
It took me half hour to realize what the problem is (the iterator returned by filter is exhausted by the time it gets to the second function call). How do I rewrite it in the most Pythonic / canonical way?
Also, what can I do to avoid bugs of this sort, besides getting more experience? (Frankly, I don't like this language feature, since these types of bugs are easy to make and hard to catch.)
A:
The itertools.tee function can help here:
import itertools
f1, f2 = itertools.tee(filtered, 2)
ratio = max(f1) / min(f2)
A:
you can convert an iterator to a tuple simply by calling tuple(iterator)
however I'd rewrite that filter as a list comprehension, which would look something like this
# original
filtered = filter(lambda x : x is not None and x != 0, c)
# list comp
filtered = [x for x in c if x is not None and x != 0]
A:
Actually your code raises an exception that would prevent this problem! So I guess the problem was that you masked the exception?
>>> min([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
>>> min(x for x in ())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
Anyways, you can also write a new function to give you the min and max at the same time:
def minmax( seq ):
" returns the `(min, max)` of sequence `seq`"
it = iter(seq)
try:
min = max = next(it)
except StopIteration:
raise ValueError('arg is an empty sequence')
for item in it:
if item < min:
min = item
elif item > max:
max = item
return min, max
A:
The entity filtered is essentially an object with state. Of course, now it's obivous that running max or min on it will change that state. In order to stop tripping over that, I like to make it absolutely clear (to myself, really) that I am constructing something rather than just transforming something:
Adding an extra step can really help:
def filtered(container):
return filter(lambda x : x is not None and x != 0, container)
ratio = max(filtered(c)) / min(filtered(c))
Whether you put filtered(...) inside some function (maybe it's not really needed for anything else) or define it as a module-level function is up to you, but in this case I'd suggest that if filtered (the iterator) was only needed in the function, leave it there until you need it elsewhere.
The other thing you can do is to construct a list from it, which will evaluate the iterator:
filtered_iter = filter(lambda x : x is not None and x != 0, container)
filtered = list(filtered_iter)
ratio = max(filtered) / min(filtered)
(Of course, you can just say filtered = list(filter(...)).)
| exhausted iterators - what to do about them? | (In Python 3.1)
(Somewhat related to another question I asked, but this question is about iterators being exhausted.)
# trying to see the ratio of the max and min element in a container c
filtered = filter(lambda x : x is not None and x != 0, c)
ratio = max(filtered) / min(filtered)
It took me half hour to realize what the problem is (the iterator returned by filter is exhausted by the time it gets to the second function call). How do I rewrite it in the most Pythonic / canonical way?
Also, what can I do to avoid bugs of this sort, besides getting more experience? (Frankly, I don't like this language feature, since these types of bugs are easy to make and hard to catch.)
| [
"The itertools.tee function can help here:\nimport itertools\n\nf1, f2 = itertools.tee(filtered, 2)\nratio = max(f1) / min(f2)\n\n",
"you can convert an iterator to a tuple simply by calling tuple(iterator)\nhowever I'd rewrite that filter as a list comprehension, which would look something like this\n# original\... | [
10,
7,
5,
3
] | [] | [] | [
"filter",
"iterator",
"python",
"python_3.x"
] | stackoverflow_0003940072_filter_iterator_python_python_3.x.txt |
Q:
PHP desktop applications
I have quite a few years experience of developing PHP web applications, and have recently started to delve into Python as well. Recently I've been interested in getting into desktop applications as well, but have absolutely no experience in that area. I've seen very little written about PHP-gtk and wonder whether it's really a good area to get stuck in to.
What I'm really looking for is something that will allow me to quite quickly develop some decent small/medium sized apps, and be able to deploy them in Linux and Windows. Something in Python or PHP would be great (but I'd be happy to learn something else if it has big advantages).
What do you guys recommend?
Thanks
A:
Building applications in PHP with GTK is possible to create client-side cross-platform applications, but I don't necessarily think it's the optimal choice for GUI development...
Here are some links:
http://gtk.php.net
http://www.cweiske.de/phpgtk.htm
Gnope.org
kksou
A:
Python and Java are both excellent for working on both Linux and Windows environment. They are generally hassle-free as long as you're not doing any OS specific type of work. Python for creating desktop apps is fairly simple and easy to learn as well if you're coming from a PHP background, especially if you're used to doing object oriented PHP.
A:
Why would you like to develop a desktop app in php??
Get yourself a descent programming environment (c/java/c#/) instead of abusing php
especially with c# and java you get pretty quick very nice results. And both are cross platform (although java is easier for cross platform stuff).
C(++) in combination with QT or GTK is also possible, but there the results appear slower
A:
Well its too late to answer i guess but still for the sake of information may I suggest Open Application Platform (OAP) as a possible solution. OAP allows for PHP/MySQL applications to be distributed as installable Windows(tm) applications.
I stumbled upon it while I was looking for porting a PHP app to desktop and found this. Worked great for me. No extra tags for window creations like in winbinder etc.
| PHP desktop applications | I have quite a few years experience of developing PHP web applications, and have recently started to delve into Python as well. Recently I've been interested in getting into desktop applications as well, but have absolutely no experience in that area. I've seen very little written about PHP-gtk and wonder whether it's really a good area to get stuck in to.
What I'm really looking for is something that will allow me to quite quickly develop some decent small/medium sized apps, and be able to deploy them in Linux and Windows. Something in Python or PHP would be great (but I'd be happy to learn something else if it has big advantages).
What do you guys recommend?
Thanks
| [
"Building applications in PHP with GTK is possible to create client-side cross-platform applications, but I don't necessarily think it's the optimal choice for GUI development... \nHere are some links:\nhttp://gtk.php.net\nhttp://www.cweiske.de/phpgtk.htm\nGnope.org\nkksou \n",
"Python and Java are both excellent... | [
12,
2,
0,
0
] | [] | [] | [
"desktop",
"gtk",
"php",
"pygtk",
"python"
] | stackoverflow_0001029435_desktop_gtk_php_pygtk_python.txt |
Q:
How do I escape the - character in SQLite FTS3 queries?
I'm using Python and SQLAlchemy to query a SQLite FTS3 (full-text) store and I would like to prevent my users from using the - as an operator. How should I escape the - so users can search for a term containing the - (enabled by changing the default tokenizer) instead of it signifying "does not contain the term following the -"?
A:
From elsewhere on the internet it seems it may be possible to surround each search term with double quotes "some-term". Since we do not need the subtraction operation, my solution was to replace hyphens - with underscores _ when populating the search index and when performing searches.
A:
From this documentation it seems that it is not really possible. Try to replace your - with whitespace before searching…
| How do I escape the - character in SQLite FTS3 queries? | I'm using Python and SQLAlchemy to query a SQLite FTS3 (full-text) store and I would like to prevent my users from using the - as an operator. How should I escape the - so users can search for a term containing the - (enabled by changing the default tokenizer) instead of it signifying "does not contain the term following the -"?
| [
"From elsewhere on the internet it seems it may be possible to surround each search term with double quotes \"some-term\". Since we do not need the subtraction operation, my solution was to replace hyphens - with underscores _ when populating the search index and when performing searches.\n",
"From this documenta... | [
1,
0
] | [] | [] | [
"fts3",
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0003865733_fts3_python_sqlalchemy_sqlite.txt |
Q:
Is the os.path.join(dir, filename) needed here?
I'm just doing a bunch of Python exercises and there is an exercise where you should. given a directory name, iterate over the 'special files' (containing the pattern __\w+__) and output their absolute paths.
Here's my code:
def get_special_paths(dir):
filenames = os.listdir(dir)
for filename in filenames:
if re.search(r'__\w+__', filename):
print os.path.abspath(os.path.join(dir, filename))
I joined the dir and filename as suggest in the examples but I don't see while the join() is needed. If I don't join the filename + dir, and instead pass abspath() only the filename, the output would be the same.
A:
If I don't join the filename + dir, and instead pass abspath() only the filename, the output would be the same.
Only if dir equals the current working directory, which is not necessarily the case. Either you need the join, or get_special_paths should not take an argument, and instead assume dir = os.getcwd().
| Is the os.path.join(dir, filename) needed here? | I'm just doing a bunch of Python exercises and there is an exercise where you should. given a directory name, iterate over the 'special files' (containing the pattern __\w+__) and output their absolute paths.
Here's my code:
def get_special_paths(dir):
filenames = os.listdir(dir)
for filename in filenames:
if re.search(r'__\w+__', filename):
print os.path.abspath(os.path.join(dir, filename))
I joined the dir and filename as suggest in the examples but I don't see while the join() is needed. If I don't join the filename + dir, and instead pass abspath() only the filename, the output would be the same.
| [
"\nIf I don't join the filename + dir, and instead pass abspath() only the filename, the output would be the same.\n\nOnly if dir equals the current working directory, which is not necessarily the case. Either you need the join, or get_special_paths should not take an argument, and instead assume dir = os.getcwd().... | [
7
] | [] | [] | [
"path",
"python"
] | stackoverflow_0003942562_path_python.txt |
Q:
What practices would you consider "pythonic"?
If you google for "pythonic" you will mostly find the same three examples. There are a lot of questions here on stackoverflow that ask for how this and that can be done in a pythonoic way, so a collection of some nice pythonic code examples would be nice!
A:
as I wrote in the tag description:
Pythonic is a description of the most idiomatic Python code. Not only does this mean that the code is easy to understand for other programmers, but it is also very often the most efficient way to use Python.
A:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
A:
The question asks for a collection of pythonic codes so I will add some of them that I like because they are using the powerful pythonic operators * and ** :
Transposition using unpacking operator *
Unpacking operator is a very powerful tool that allow us to "unpack" a list. I do not know any equivalent in other languages.
This operator can have very funny and useful applications :
a = [[1,2],[3,4]]
a_transpose = zip(*a)
Dictionnary concatenation using tuple unpacking operator **
Once again, I do not know any equivalent in other languages. Same as above, we can use this operator for many things including dictionnary concatenation :
a = {1:2,2:2}
b = {2:37,3:42}
a = dict(a,**b) # a is now {1:2,2:37,3:42}
A:
"Pythonic" just means following common Python idioms.
just follow the Zen Of Python:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
| What practices would you consider "pythonic"? | If you google for "pythonic" you will mostly find the same three examples. There are a lot of questions here on stackoverflow that ask for how this and that can be done in a pythonoic way, so a collection of some nice pythonic code examples would be nice!
| [
"as I wrote in the tag description:\n\nPythonic is a description of the most idiomatic Python code. Not only does this mean that the code is easy to understand for other programmers, but it is also very often the most efficient way to use Python.\n\n",
">>> import this\nThe Zen of Python, by Tim Peters\n\nBeautif... | [
5,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003942875_python.txt |
Q:
how to delete or destroy the wx.panel from its parent (another wx.panel object)?
I am developing a GUI with wxPython. I draw a square which represents a CD object, inside another square (also with wxPanel class), which represents CD Container Object.
I want to have "delete this CD" in the right click menu of CDWindow, which will remove the CDwindow.
Basically, my code looks like this (for simplicity, I keep the main parts):
class CDContainerWindow(wx.Panel):
def __init__(self):
wx.Panel.__init__(self, parent, id, pos, size)
cd_win=CDWindow()
class CDWindow(wx.Panel):
def __init__(self):
wx.Panel.__init__(self, parent, id, pos, size)
self.Bind(wx.EVT_MENU, self.OnDeleteCD, item_CD)
def OnDeleteCD(self, event):
self.destroy()
There is an error message "Segmentation fault"
What is wrong with my way? How can I delete this CD window from the CDContainer Window?
A:
Maybe there's a sizer still using the destroyed panel? You should remove the panel from the sizer first.
| how to delete or destroy the wx.panel from its parent (another wx.panel object)? | I am developing a GUI with wxPython. I draw a square which represents a CD object, inside another square (also with wxPanel class), which represents CD Container Object.
I want to have "delete this CD" in the right click menu of CDWindow, which will remove the CDwindow.
Basically, my code looks like this (for simplicity, I keep the main parts):
class CDContainerWindow(wx.Panel):
def __init__(self):
wx.Panel.__init__(self, parent, id, pos, size)
cd_win=CDWindow()
class CDWindow(wx.Panel):
def __init__(self):
wx.Panel.__init__(self, parent, id, pos, size)
self.Bind(wx.EVT_MENU, self.OnDeleteCD, item_CD)
def OnDeleteCD(self, event):
self.destroy()
There is an error message "Segmentation fault"
What is wrong with my way? How can I delete this CD window from the CDContainer Window?
| [
"Maybe there's a sizer still using the destroyed panel? You should remove the panel from the sizer first.\n"
] | [
3
] | [] | [] | [
"python",
"user_interface",
"wxpython",
"wxwidgets"
] | stackoverflow_0003943035_python_user_interface_wxpython_wxwidgets.txt |
Q:
x,y = getPos() vs. (x, y) = getPos()
Consider this function getPos() which returns a tuple. What is the difference between the two following assignments? Somewhere I saw an example where the first assignment was used but when I just tried the second one, I was surprised it also worked. So, is there really a difference, or does Python just figure out that the left-hand part should be a tuple?
def getPos():
return (1, 1)
(x, y) = getPos() # First assignment
x, y = getPos() # Second assignment
A:
Read about tuples:
A tuple consists of a number of values separated by commas (...)
So parenthesis does not make a tuple a tuple. The commas do it.
Parenthesis are only needed if you have weird nested structures:
x, (y, (w, z)), r
A:
Yes, it's called tuple unpacking:
"Tuple unpacking requires that the list of variables on the left has the same number of elements as the length of the tuple." - Guido Van Rossum
"When you use tuples or lists on the left side of the =, Python pairs objects on the right side with targets on the left and assigns them from left to right." - Lutz and Ascher
A:
There is no difference:
>>> import dis
>>> dis.dis(compile("a,b = expr()", "", "single"))
1 0 LOAD_NAME 0 (expr)
3 CALL_FUNCTION 0
6 UNPACK_SEQUENCE 2
9 STORE_NAME 1 (a)
12 STORE_NAME 2 (b)
15 LOAD_CONST 0 (None)
18 RETURN_VALUE
>>> dis.dis(compile("(a,b) = expr()", "", "single"))
1 0 LOAD_NAME 0 (expr)
3 CALL_FUNCTION 0
6 UNPACK_SEQUENCE 2
9 STORE_NAME 1 (a)
12 STORE_NAME 2 (b)
15 LOAD_CONST 0 (None)
18 RETURN_VALUE
Both a, b and (a, b) specify a tuple, and you need a tuple in the LHS (left hand side) for tuple unpacking :)
A:
yes, and it works also on list
>>> x,y,z = range(3)
>>> print x, y, z
0 1 2
>>>
A:
There's no difference.
| x,y = getPos() vs. (x, y) = getPos() | Consider this function getPos() which returns a tuple. What is the difference between the two following assignments? Somewhere I saw an example where the first assignment was used but when I just tried the second one, I was surprised it also worked. So, is there really a difference, or does Python just figure out that the left-hand part should be a tuple?
def getPos():
return (1, 1)
(x, y) = getPos() # First assignment
x, y = getPos() # Second assignment
| [
"Read about tuples:\n\nA tuple consists of a number of values separated by commas (...)\n\nSo parenthesis does not make a tuple a tuple. The commas do it. \nParenthesis are only needed if you have weird nested structures:\nx, (y, (w, z)), r\n\n",
"Yes, it's called tuple unpacking:\n\n\"Tuple unpacking requires th... | [
8,
5,
4,
3,
1
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0003941407_python_tuples.txt |
Q:
Python regular expression to match file-date.txt
I am trying to match file names in the format filename-isodate.txt
>>> DATE_NAME_PATTERN = re.compile("((.*)(-[0-9]{8})?)\\.txt")
>>> DATE_NAME_PATTERN.match("myfile-20101019.txt").groups()
('myfile-20101019', 'myfile-20101019', None)
However I need to get the filename and -isodate parts in seperate groups.
Any suggestions and/or explainations would be much appreciated
A:
If you know the filename format will not change, you don't need re:
filename = 'myfile-20101019.txt'
basename, extension = filename.rsplit('.', 1)
firstpart, date = basename.rsplit('-', 1)
In : firstpart, date, extension
Out: ('myfile', '20101019', 'txt')
or just without extension:
firstpart, date = filename.rsplit('.', 1)[0].rsplit('-', 1)
# ['myfile', '20101019']
Works with more complicated filenames too:
filename = 'more.complicated-filename-20101004.txt'
firstpart, date = filename.rsplit('.', 1)[0].rsplit('-', 1)
# ['more.complicated-filename', '20101004']
Or, just to split the extension even more nicely:
import os
filename = 'more.complicated-filename-20101004.txt'
firstpart, date = os.path.splitext(filename)[0].rsplit('-', 1)
# ['more.complicated-filename', '20101004']
A:
You need: DATE_NAME_PATTERN = re.compile("((.*?)(-[0-9]{8})?)\\.txt")
.* performs a gready match so the second part is never used.
FYI in my opiniomy you shouldn't use regular expression where normal string manipulation is enough ( simple split() will do ).
A:
Remove the outermost group and put the - between the groups:
>>> DATE_NAME_PATTERN = re.compile(r'(.*)-([0-9]{8})?\.txt')
>>> DATE_NAME_PATTERN.match("myfile-20101019.txt").groups()
('myfile', '20101019')
A:
Don't use regular expressions for this:
import os
basename, extension= os.path.splitext(filename)
namepart, _, isodate= basename.rpartition('-')
I'm suggesting rpartition since the isodate (as defined in your question) won't
contain dashes.
| Python regular expression to match file-date.txt | I am trying to match file names in the format filename-isodate.txt
>>> DATE_NAME_PATTERN = re.compile("((.*)(-[0-9]{8})?)\\.txt")
>>> DATE_NAME_PATTERN.match("myfile-20101019.txt").groups()
('myfile-20101019', 'myfile-20101019', None)
However I need to get the filename and -isodate parts in seperate groups.
Any suggestions and/or explainations would be much appreciated
| [
"If you know the filename format will not change, you don't need re:\nfilename = 'myfile-20101019.txt'\nbasename, extension = filename.rsplit('.', 1)\nfirstpart, date = basename.rsplit('-', 1)\n\n\nIn : firstpart, date, extension\nOut: ('myfile', '20101019', 'txt')\n\nor just without extension:\nfirstpart, date = f... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"regex",
"regex_group"
] | stackoverflow_0003941125_python_regex_regex_group.txt |
Q:
Freeze in Python?
I have programmed in Python for a while, and just recently started using Ruby at work. The languages are very similar. However, I just came across a Ruby feature that I don't know how to replicate in Python. It's Ruby's freeze method.
irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> a[1] = 'chicken'
=> "chicken"
irb(main):003:0> a.freeze
=> [1, "chicken", 3]
irb(main):004:0> a[1] = 'tuna'
TypeError: can't modify frozen array
from (irb):4:in `[]='
from (irb):4
Is there a way to imitate this in Python?
EDIT: I realized that I made it seem like this was only for lists; in Ruby, freeze is a method on Object so you can make any object immutable. I apologize for the confusion.
A:
>>> a = [1,2,3]
>>> a[1] = 'chicken'
>>> a
[1, 'chicken', 3]
>>> a = tuple(a)
>>> a[1] = 'tuna'
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
a[1] = 'tuna'
TypeError: 'tuple' object does not support item assignment
Also, cf. set vs. frozenset, bytearray vs. bytes.
Numbers, strings are immutable themselves:
>>> a = 4
>>> id(a)
505408920
>>> a = 42 # different object
>>> id(a)
505409528
A:
You could always subclass list and add the "frozen" flag which would block __setitem__ doing anything:
class freezablelist(list):
def __init__(self,*args,**kwargs):
list.__init__(self, *args)
self.frozen = kwargs.get('frozen', False)
def __setitem__(self, i, y):
if self.frozen:
raise TypeError("can't modify frozen list")
return list.__setitem__(self, i, y)
def __setslice__(self, i, j, y):
if self.frozen:
raise TypeError("can't modify frozen list")
return list.__setslice__(self, i, j, y)
def freeze(self):
self.frozen = True
def thaw(self):
self.frozen = False
Then playing with it:
>>> from freeze import freezablelist as fl
>>> a = fl([1,2,3])
>>> a[1] = 'chicken'
>>> a.freeze()
>>> a[1] = 'tuna'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "freeze.py", line 10, in __setitem__
raise TypeError("can't modify frozen list")
TypeError: can't modify frozen list
>>> a[1:1] = 'tuna'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "freeze.py", line 16, in __setslice__
raise TypeError("can't modify frozen list")
TypeError: can't modify frozen list
>>>
| Freeze in Python? | I have programmed in Python for a while, and just recently started using Ruby at work. The languages are very similar. However, I just came across a Ruby feature that I don't know how to replicate in Python. It's Ruby's freeze method.
irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> a[1] = 'chicken'
=> "chicken"
irb(main):003:0> a.freeze
=> [1, "chicken", 3]
irb(main):004:0> a[1] = 'tuna'
TypeError: can't modify frozen array
from (irb):4:in `[]='
from (irb):4
Is there a way to imitate this in Python?
EDIT: I realized that I made it seem like this was only for lists; in Ruby, freeze is a method on Object so you can make any object immutable. I apologize for the confusion.
| [
">>> a = [1,2,3]\n>>> a[1] = 'chicken'\n>>> a\n[1, 'chicken', 3]\n>>> a = tuple(a)\n>>> a[1] = 'tuna'\nTraceback (most recent call last):\n File \"<pyshell#4>\", line 1, in <module>\n a[1] = 'tuna'\nTypeError: 'tuple' object does not support item assignment\n\nAlso, cf. set vs. frozenset, bytearray vs. bytes.\n... | [
14,
12
] | [] | [] | [
"freeze",
"list",
"python",
"ruby"
] | stackoverflow_0003942825_freeze_list_python_ruby.txt |
Q:
Regex in Python
I have the following string:
schema(field1, field2, field3, field4 ... fieldn)
I need to transform the string to an object with name attribute as schema and the field names as another attribute which is a list.
How do I do this in Python with a regular expression?
A:
Are you looking for something like this?
>>> s = 'schema(field1, field2, field3, field4, field5)'
>>> name, _, fields = s[:-1].partition('(')
>>> fields = fields.split(', ')
>>> if not all(re.match(r'[a-z]+\d+$', i) for i in fields):
print('bad input')
>>> sch = type(name, (object,), {'attr': fields})
>>> sch
<class '__main__.schema'>
>>> sch.attr
['field1', 'field2', 'field3', 'field4', 'field5']
A:
Regular expressions for things like that probably need tests:
import unittest
import re
# Verbose regular expression! http://docs.python.org/library/re.html#re.X
p = r"""
(?P<name>[^(]+) # Match the pre-open-paren name.
\( # Open paren
(?P<fields> # Comma-separated fields
(?:
[a-zA-Z0-9_-]+
(?:,\ ) # Subsequent fields must separated by space and comma
)*
[a-zA-Z0-9_-]+ # At least one field. No trailing comma or space allowed.
)
\) # Close-paren
"""
# Compiled for speed!
cp = re.compile(p, re.VERBOSE)
class Foo(object):
pass
def validateAndBuild(s):
"""Validate a string and return a built object.
"""
match = cp.search(s)
if match is None:
raise ValueError('Bad schema: %s' % s)
schema = match.groupdict()
foo = Foo()
foo.name = schema['name']
foo.fields = schema['fields'].split(', ')
return foo
class ValidationTest(unittest.TestCase):
def testValidString(self):
s = "schema(field1, field2, field3, field4, fieldn)"
obj = validateAndBuild(s)
self.assertEqual(obj.name, 'schema')
self.assertEqual(obj.fields, ['field1', 'field2', 'field3', 'field4', 'fieldn'])
invalid = [
'schema field1 field2',
'schema(field1',
'schema(field1 field2)',
]
def testInvalidString(self):
for s in self.invalid:
self.assertRaises(ValueError, validateAndBuild, s)
if __name__ == '__main__':
unittest.main()
A:
You could use something like (in two rounds because python re doesn't support nested capture (thanks SilentGhost for pointing it out)) :
pattern = re.compile("^([a-z]+)\(([a-z,]*)\)$")
ret = pattern.match(s)
if ret==None:
...
else:
f = ret.groups()
name = f[0]
args = f[1]
arg_pattern = re.compile("^([a-z]+)(,[a-z]+)*$")
ret2 = arg_pattern.match(args)
# same checking as above
if (ret2==None):
...
else:
args_f = ret2.groups()
| Regex in Python | I have the following string:
schema(field1, field2, field3, field4 ... fieldn)
I need to transform the string to an object with name attribute as schema and the field names as another attribute which is a list.
How do I do this in Python with a regular expression?
| [
"Are you looking for something like this?\n>>> s = 'schema(field1, field2, field3, field4, field5)'\n>>> name, _, fields = s[:-1].partition('(')\n>>> fields = fields.split(', ')\n>>> if not all(re.match(r'[a-z]+\\d+$', i) for i in fields):\n print('bad input')\n\n>>> sch = type(name, (object,), {'attr': fields})... | [
5,
1,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003943062_python_regex_string.txt |
Q:
Destop application in Python with more than one frame!
I have developed many desktop applications in Delphi / Pascal -
Here I have used modal forms.
//Mainform
Form1:= TForm1.Create(Self);
If Form1.Showmodal =mrOK then ….
In Form1 you cal call vars in Mainform like mainform.X := 1
(I know – I normaly use try,except, finally)
I will now switch to Python and my problem is the following:
I want an application with a main window (frame) where you can call a number of forms which can have Forms and so on
I can make a program with python and wxpython where a main frame create a new frame and show it – But how do I get back – and how to I have reference to the parent frame – if its possible!
From mainform
Def OnButton1(self, event):
self.main2 = Frame2.create(None)
self.main2.Show()
self.Hide()
When I am done in main2 who do I return to mainform – It’s hidden !!
I know I can use dialog, but I need a normal frame!!
What I am looking for is a small program where have a mainframe – with a button that calls a Frame (Frame1) who have a button that calls a frame (Frame1A)
I am new to Python but have made many applications in C,C++, Pascal
I have looked at almost all demos, but none of them could give me a hint!
Regards
Mick
A:
Just curious, why can't you use a dialog?
Anyway, a simple solution would be to provide a callback function to the constructor of Frame2, which is called when Frame2 is about to be closed.
class Frame2(wx.wxFrame):
def __init__(self, parent, callback, ...)
wx.wxFrame(self, parent)
self._callback = callback
self.bind(wx.EVT_CLOSE, self.OnClose(), self)
def OnClose():
self.Destroy()
self._callback()
class Frame1(...):
...
def OnButton1(self, event):
self.main2 = Frame2(self, self.OnButton1Callback)
self.main2.Show()
self.Hide()
def OnButton1Callback(self)
self.Show()
...
The code above is just a hint, has been never tested!
A:
There are several ways to get a reference to the main frame. When you create the secondary frames, you can pass them either None or a parent. If you pass the main frame as the parent, then you have an easy way to reference it.
Alternatively, you can do this:
topFrame = wx.GetTopLevelParent()
As for showing a secondary frame and hiding the main one, what I do is use Pubsub. When I open the secondary frame, I hide the main one. When I close the secondary frame, it sends a pubsub message to the hidden main frame that is caught and the main frame is re-shown.
There are lots of pubsub examples on the wxPython wiki. There's also this article I wrote:
http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/
Hope that helps!
| Destop application in Python with more than one frame! | I have developed many desktop applications in Delphi / Pascal -
Here I have used modal forms.
//Mainform
Form1:= TForm1.Create(Self);
If Form1.Showmodal =mrOK then ….
In Form1 you cal call vars in Mainform like mainform.X := 1
(I know – I normaly use try,except, finally)
I will now switch to Python and my problem is the following:
I want an application with a main window (frame) where you can call a number of forms which can have Forms and so on
I can make a program with python and wxpython where a main frame create a new frame and show it – But how do I get back – and how to I have reference to the parent frame – if its possible!
From mainform
Def OnButton1(self, event):
self.main2 = Frame2.create(None)
self.main2.Show()
self.Hide()
When I am done in main2 who do I return to mainform – It’s hidden !!
I know I can use dialog, but I need a normal frame!!
What I am looking for is a small program where have a mainframe – with a button that calls a Frame (Frame1) who have a button that calls a frame (Frame1A)
I am new to Python but have made many applications in C,C++, Pascal
I have looked at almost all demos, but none of them could give me a hint!
Regards
Mick
| [
"Just curious, why can't you use a dialog?\nAnyway, a simple solution would be to provide a callback function to the constructor of Frame2, which is called when Frame2 is about to be closed.\n\nclass Frame2(wx.wxFrame):\n def __init__(self, parent, callback, ...)\n wx.wxFrame(self, parent)\n self._... | [
1,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003937666_python_wxpython.txt |
Q:
Python Tkinter Return
Is there a way to return something when a button is pressed?
Here is my sample program. a simple file reader. Is the global variable to hold text contents the way to go since I can't return the contents?
from Tkinter import *
import tkFileDialog
textcontents = ''
def onopen():
filename = tkFileDialog.askopenfilename()
read(filename)
def onclose():
root.destroy()
def read(file):
global textcontents
f = open(file, 'r')
textcontents = f.readlines()
text.insert(END, textcontents)
root = Tk()
root.title('Text Reader')
frame = Frame(root)
frame.pack()
text = Text(frame, width=40, height=20)
text.pack()
text.insert(END, textcontents)
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Open...", command=onopen)
filemenu.add_command(label="Exit", command=onclose)
mainloop()
A:
Tk(inter) is event-based, which means, that you do not return values, but bind callbacks (functions) to actions.
more info here: http://effbot.org/tkinterbook/button.htm
A:
If you meant signal back to the user, here's some sample code:
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
and the source: Python - Tkinter Button tutorial
| Python Tkinter Return | Is there a way to return something when a button is pressed?
Here is my sample program. a simple file reader. Is the global variable to hold text contents the way to go since I can't return the contents?
from Tkinter import *
import tkFileDialog
textcontents = ''
def onopen():
filename = tkFileDialog.askopenfilename()
read(filename)
def onclose():
root.destroy()
def read(file):
global textcontents
f = open(file, 'r')
textcontents = f.readlines()
text.insert(END, textcontents)
root = Tk()
root.title('Text Reader')
frame = Frame(root)
frame.pack()
text = Text(frame, width=40, height=20)
text.pack()
text.insert(END, textcontents)
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Open...", command=onopen)
filemenu.add_command(label="Exit", command=onclose)
mainloop()
| [
"Tk(inter) is event-based, which means, that you do not return values, but bind callbacks (functions) to actions.\nmore info here: http://effbot.org/tkinterbook/button.htm\n",
"If you meant signal back to the user, here's some sample code:\nimport Tkinter\nimport tkMessageBox\n\ntop = Tkinter.Tk()\n\ndef helloCal... | [
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003943495_python_tkinter.txt |
Q:
Does anyone have a Python 3 Cheat Sheet
Does anyone have a python 3 cheat sheet? You know quick reference kind of thing which has everything on one page.
A:
Here's a good one, if you know Python 2 syntax, well:
Python 2 to Python 3
A:
http://www.addedbytes.com/cheat-sheets/python-cheat-sheet/
A:
Not a cheat sheet, but here are two helpful resources for converting to or learning the new features of Python 3 (from my bookmarks):
Python 3000 and You (Guido van Rossum) - not really a good tutorial but a good overview
Porting your code to Python 3 (Alexandre Vassalotti) - a very thorough look at the most important changes in Python 3
| Does anyone have a Python 3 Cheat Sheet | Does anyone have a python 3 cheat sheet? You know quick reference kind of thing which has everything on one page.
| [
"Here's a good one, if you know Python 2 syntax, well:\nPython 2 to Python 3\n",
"http://www.addedbytes.com/cheat-sheets/python-cheat-sheet/\n",
"Not a cheat sheet, but here are two helpful resources for converting to or learning the new features of Python 3 (from my bookmarks):\n\nPython 3000 and You (Guido va... | [
5,
5,
4
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003943505_python_python_3.x.txt |
Q:
Slice notation in Scala?
Is there something similar to the slice notation in Python in Scala?
I think this is really a useful operation that should be incorporated in all languages.
A:
Equivalent method in Scala (with a slightly different syntax) exists for all kinds of sequences:
scala> "Hello world" slice(0,4)
res0: String = Hell
scala> (1 to 10) slice(3,5)
res1: scala.collection.immutable.Range = Range(4, 5)
The biggest difference compared to slicing in Python is that start and end indices are mandatory in Scala.
A:
scala> import collection.IterableLike
import collection.IterableLike
scala> implicit def pythonicSlice[A, Repr](coll: IterableLike[A, Repr]) = new {
| def apply(subrange: (Int, Int)): Repr = coll.slice(subrange._1, subrange._2)
| }
pythonicSlice: [A,Repr](coll: scala.collection.IterableLike[A,Repr])java.lang.Object{def apply(subrange: (Int, Int)): Repr}
scala> val list = List(3, 4, 11, 78, 3, 9)
list: List[Int] = List(3, 4, 11, 78, 3, 9)
scala> list(2 -> 5)
res4: List[Int] = List(11, 78, 3)
Will this do?
Disclaimer: Not properly generalized.
EDIT:
scala> case class PRange(start: Int, end: Int, step: Int = 1)
defined class PRange
scala> implicit def intWithTildyArrow(i: Int) = new {
| def ~>(j: Int) = PRange(i, j)
| }
intWithTildyArrow: (i: Int)java.lang.Object{def ~>(j: Int): PRange}
scala> implicit def prangeWithTildyArrow(p: PRange) = new {
| def ~>(step: Int) = p.copy(step = step)
| }
prangeWithTildyArrow: (p: PRange)java.lang.Object{def ~>(step: Int): PRange}
scala> implicit def pSlice[A](coll: List[A]) = new {
| def apply(prange: PRange) = {
| import prange._
| coll.slice(start, end).grouped(step).toList.map(_.head)
| }
| }
pSlice: [A](coll: List[A])java.lang.Object{def apply(prange: PRange): List[A]}
scala> val xs = List.range(1, 10)
xs: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> xs(3 ~> 9)
res32: List[Int] = List(4, 5, 6, 7, 8, 9)
scala> xs(3 ~> 9 ~> 2)
res33: List[Int] = List(4, 6, 8)
A:
See the ScalaAPI here
So not the same notational convenience, but the operation is there
def slice (from: Int, until: Int)
: Seq[A]
Selects an interval of elements.
Selects an interval of elements.
Note: c.slice(from, to) is equivalent
to (but possibly more efficient than)
c.drop(from).take(to - from)
from the index of the first returned element in this sequence. until
the index one past the last returned element in this sequence.
returns
a sequence containing the elements starting at index from and extending
up to (but not including) index until
of this sequence.
definition classes: IterableLike →
TraversableLike
A:
Note that this does not quite work by using apply, but it generalizes to lists, strings, arrays, etc:
implicit def it2sl[Repr <% scala.collection.IterableLike[_, Repr]](cc: Repr) = new {
def ~>(i : Int, j : Int) : Repr = cc.slice(i,j)
}
The usage is:
scala> "Hello World" ~> (3, 5)
res1: java.lang.String = lo
scala> List(1, 2, 3, 4) ~> (0, 2)
res2: List[Int] = List(1, 2)
scala> Array('a', 'b', 'c', 'd') ~> (1, 3)
res3: Array[Char] = Array(b, c)
You might want to rename the method to something else that takes your fancy. Except apply (because there is already a conversion from String to StringLike which decorates String with an apply method - similarly with ArrayOps - and there is already an apply method on other collection types such as List).
Thanks for Daniel for the hint to use a view bound.
| Slice notation in Scala? | Is there something similar to the slice notation in Python in Scala?
I think this is really a useful operation that should be incorporated in all languages.
| [
"Equivalent method in Scala (with a slightly different syntax) exists for all kinds of sequences:\nscala> \"Hello world\" slice(0,4)\nres0: String = Hell\n\nscala> (1 to 10) slice(3,5)\nres1: scala.collection.immutable.Range = Range(4, 5)\n\nThe biggest difference compared to slicing in Python is that start and end... | [
55,
21,
9,
2
] | [] | [] | [
"python",
"scala",
"slice"
] | stackoverflow_0003932582_python_scala_slice.txt |
Q:
GAE Query fetch()
I am trying to learn simple operations with the datastore and I am having problems. Can someone help why this is not working?
class Pet(db.Model):
name = db.StringProperty
pet = Pet(name="Fluffy")
pet.put()
query = Pet.all()
results = query.fetch(limit=5)
print pet.name
When I run this I get
<class 'google.appengine.ext.db.StringProperty'>
A:
Try changing
name = db.StringProperty
to
name = db.StringProperty()
| GAE Query fetch() | I am trying to learn simple operations with the datastore and I am having problems. Can someone help why this is not working?
class Pet(db.Model):
name = db.StringProperty
pet = Pet(name="Fluffy")
pet.put()
query = Pet.all()
results = query.fetch(limit=5)
print pet.name
When I run this I get
<class 'google.appengine.ext.db.StringProperty'>
| [
"Try changing\nname = db.StringProperty\n\nto\nname = db.StringProperty()\n\n"
] | [
3
] | [] | [] | [
"google_cloud_datastore",
"python"
] | stackoverflow_0003943713_google_cloud_datastore_python.txt |
Q:
Server Upgrade Script
Does anyone have or know of a good template / plan for doing automated server upgrades? In this case I am upgrading a python/django server, but am going to have to apply this update to many machines, and want to be sure that the operation is fully testable and recoverable should anything go wrong.
Am picturing something along the lines of:
remotely fetch new code
verify code download (e.g. hash of files)
take down server, display "you are upgrading dialog"
backup database(s)
backup code directory
apply new code updates
verify code update (e.g. hash of files)
apply database update (if necessary)
run tests
if success
startup server
verify server update
else
restore old database
restore old code
report error
startup server
verify server restore
I'm sure that this isn't exhaustive, and there are many other error conditions to consider, but am wondering if something like this already exists as a formalized process/best practices checklist to follow? Ideally this whole thing should of course be done by a single script call.
A:
Once you have a plan (and yours looks pretty good), the Fabric site should be your next stop.
A:
I think you're pretty much covering everything. Identify what's important to you and you're business practices: that's what counts.
| Server Upgrade Script | Does anyone have or know of a good template / plan for doing automated server upgrades? In this case I am upgrading a python/django server, but am going to have to apply this update to many machines, and want to be sure that the operation is fully testable and recoverable should anything go wrong.
Am picturing something along the lines of:
remotely fetch new code
verify code download (e.g. hash of files)
take down server, display "you are upgrading dialog"
backup database(s)
backup code directory
apply new code updates
verify code update (e.g. hash of files)
apply database update (if necessary)
run tests
if success
startup server
verify server update
else
restore old database
restore old code
report error
startup server
verify server restore
I'm sure that this isn't exhaustive, and there are many other error conditions to consider, but am wondering if something like this already exists as a formalized process/best practices checklist to follow? Ideally this whole thing should of course be done by a single script call.
| [
"Once you have a plan (and yours looks pretty good), the Fabric site should be your next stop.\n",
"I think you're pretty much covering everything. Identify what's important to you and you're business practices: that's what counts.\n"
] | [
2,
0
] | [] | [] | [
"django",
"python",
"sysadmin"
] | stackoverflow_0003943598_django_python_sysadmin.txt |
Q:
Is there a better way to do this in Python?
ids = []
for object in objects:
ids += [object.id]
A:
You can use a list comprehension:
ids = [object.id for object in objects]
For your reference:
http://docs.python.org/howto/functional.html#generator-expressions-and-list-comprehensions
Both produce the same result. In many cases, a list comprehension is an elegant and pythonic way to do the same as what you mentioned.
A:
The standard (i.e “pythonic” a.k.a cleanest :) way is to use a list comprehension:
ids= [obj.id for obj in objects]
The above works for all Python versions ≥ 2.0.
Other ways (just FYI)
In Python 2, you can also do:
ids= map(lambda x: x.id, objects)
which should be the slowest method, or
# note: Python ≥ 2.4
import operator
ids= map(operator.attrgetter('id'), objects)
which might be the fastest method, although I assume the difference won't be that much; either way, the clarity of the list comprehension outweighs speed gains.
Should you want to use an alternative way in Python 3, you should enclose the map call in a list call:
ids= list(map(operator.attrgetter('id'), objects))
because the map builtin returns a generator instead of a list in Python 3.
A:
Another way:
ids = map(lambda x: x.id, objects)
A:
You don't need the operator module:
In [12]: class Bar(object):
def __init__(self, id_):
self.id = id_
In [15]: foo = [Bar(1) for _ in xrange(10000)]
In [16]: foobar = map(lambda bar: getattr(bar, 'id'), foo)
In [17]: len(foobar)
Out[17]: 10000
In [18]: foobar[:10]
Out[18]: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
| Is there a better way to do this in Python? | ids = []
for object in objects:
ids += [object.id]
| [
"You can use a list comprehension:\nids = [object.id for object in objects]\n\nFor your reference:\n\nhttp://docs.python.org/howto/functional.html#generator-expressions-and-list-comprehensions\n\nBoth produce the same result. In many cases, a list comprehension is an elegant and pythonic way to do the same as what ... | [
27,
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003940518_python.txt |
Q:
regex to parse tables wrapped into xml
Suppose we have a table:
Key|Val|Flag
01 |AAA| Y
02 |BBB| N
...
wrapped into xml this way:
<Data>
<R><F>Key</F><F>Val</F><F>Flag</F></R>
<R><F>01</F><F>AAA</F><F>Y</F></R>
<R><F>02</F><F>BBB</F><F>N</F></R>
...
</Data>
There can be more columns and rows, obviously.
Now I'd like to parse XML back to table using single regex.
I can find all fields with '<F>([\w\d]*)</F>', but I need them to be groupped by rows somehow.
I thought about <R>(<F>([\w\d]*)</F>)*</R>, but Python implementation finds nothing.
Can someone please help to compose regex?
UPDATE
Some context of the question.
I'm aware about plenty of XML parsing libraries, but unfortunately my environment is limited to standard libraries. Anyway thanks to everyone who have warned not to use regexes for XML parsing.
And I needed some quick and dirty solution, therefore I decided to start with regexes and switch to parsing later.
So far I have the code:
...
row_p = r'<R>(.*?)</R>'
field_p = r'<F>(.*?)</F>'
table = ''
for row in re.finditer(row_p, xml):
table += '|'.join(re.findall(field_p, row.group(1))) + '\n'
...
It works for small datasets (about 10'000 rows) but fails for tables larger 500'000 rows.
Maybe I'll do some investigation why it fails, but next step I'm going to take - switch to some standard XML parser. ElementTree is the first candidate.
A:
Mandatory links:
RegEx match open tags except XHTML self-contained tags and
Can you provide some examples of why it is hard to parse XML and HTML with a regex?
Use an XML parser. lxml is very good and even provides (among other XML-related thingies) XPath - if you got a fetish with oneliners, I'm sure there is an XPath oneliner to extract these elements ;)
A:
If this question is tagged with Perl, I can post a solution + code for you, but since this is python.
Anyway, I suggest you load the xml file, and read it line by line. Loop each line until the end of the file and find all fields within that line. As far as I know matches in python are stored in an array. There you have it. Wish I can show you with code but this is just the main idea:
load file
foreach line in <file>
if regex.match('<F>([\w\d]*)</F>', line)
print matches[1] . '|' . matches[2] . '|' . matches[3] . "\n"
end loop
DISCLAIMER: The above code is just a scratch
Oh by the way, if possible, use an XML parser instead.
A:
import libxml2
txt = '\n<Data>\n <R><F>Key</F><F>Val</F><F>Flag</F></R>\n <R><F>01</F><F>AAA</F><F>Y</F></R>\n <R><F>02</F><F>BBB</F><F>N</F></R>\n</Data>\n'
rows = []
for elem in libxml2.parseDoc(txt):
if elem.name == 'R':
curRow = []
rows.append(curRow)
elif elem.name == 'F':
curRow.append(elem.get_content())
returns:
rows = [['Key', 'Val', 'Flag'], ['01', 'AAA', 'Y'], ['02', 'BBB', 'N']]
A:
lxml is a Pythonic binding for
the libxml2 and libxslt libraries. It
is unique in that it combines the
speed and feature completeness of
these libraries with the simplicity of
a native Python API, mostly compatible
but superior to the well-known
ElementTree API.
| regex to parse tables wrapped into xml | Suppose we have a table:
Key|Val|Flag
01 |AAA| Y
02 |BBB| N
...
wrapped into xml this way:
<Data>
<R><F>Key</F><F>Val</F><F>Flag</F></R>
<R><F>01</F><F>AAA</F><F>Y</F></R>
<R><F>02</F><F>BBB</F><F>N</F></R>
...
</Data>
There can be more columns and rows, obviously.
Now I'd like to parse XML back to table using single regex.
I can find all fields with '<F>([\w\d]*)</F>', but I need them to be groupped by rows somehow.
I thought about <R>(<F>([\w\d]*)</F>)*</R>, but Python implementation finds nothing.
Can someone please help to compose regex?
UPDATE
Some context of the question.
I'm aware about plenty of XML parsing libraries, but unfortunately my environment is limited to standard libraries. Anyway thanks to everyone who have warned not to use regexes for XML parsing.
And I needed some quick and dirty solution, therefore I decided to start with regexes and switch to parsing later.
So far I have the code:
...
row_p = r'<R>(.*?)</R>'
field_p = r'<F>(.*?)</F>'
table = ''
for row in re.finditer(row_p, xml):
table += '|'.join(re.findall(field_p, row.group(1))) + '\n'
...
It works for small datasets (about 10'000 rows) but fails for tables larger 500'000 rows.
Maybe I'll do some investigation why it fails, but next step I'm going to take - switch to some standard XML parser. ElementTree is the first candidate.
| [
"Mandatory links:\n\nRegEx match open tags except XHTML self-contained tags and\nCan you provide some examples of why it is hard to parse XML and HTML with a regex?\n\nUse an XML parser. lxml is very good and even provides (among other XML-related thingies) XPath - if you got a fetish with oneliners, I'm sure there... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"xml"
] | stackoverflow_0003933121_python_regex_xml.txt |
Q:
Constipated Python urllib2 sockets
I've been scouring the Internet looking for a solution to my problem with Python. I'm trying to use a urllib2 connection to read a potentially endless stream of data from an HTTP server. It's part of some interactive communication, so it's important that I can get the data that's available, even if it's not a whole buffer full. There seems to be no way to have read \ readline return the available data. It will block forever waiting for the entire (endless) stream before it returns.
Even if I set the underlying file descriptor to non-blocking using fnctl, the urllib2 file-object still blocks!! In general there seems to be no way to make python file-objects, upon read, return all available data if there is some and block otherwise.
I've seen a few posts about people seeking help with this, but I have seen no solutions. What gives? Am I missing something? This seems like such a normal use-case to completely ruin! I'm hoping to utilize urllib2's ability to detect configured proxies and use chunked encoding, but I can't if it won't cooperate.
Edit: Upon request, here is some example code
Client:
connection = urllib2.urlopen(commandpath)
id = connection.readline()
Now suppose that the server is using chunked transfer encoding, and writes one chunk down the stream and the chunk contains the line, and then waits. The connection is still open, but the client has data waiting in a buffer.
I cannot get read or readline to return the data I know it has waiting for it, because it tries to read until the end of the connection. In this case the connection may never close so it will wait either forever or until an inactivity timeout occurs, severing the connection. Once the connection is severed it will return, but that's obviously not the behavior I want.
A:
urllib2 operates at the HTTP level, which works with complete documents. I don't think there's a way around that without hacking into the urllib2 source code.
What you can do is use plain sockets (you'll have to talk HTTP yourself in this case), and call sock.recv(maxbytes) which does read only available data.
Update: you may want to try to call conn.fp._sock.recv(maxbytes), instead of conn.read(bytes) on an urllib2 connection.
| Constipated Python urllib2 sockets | I've been scouring the Internet looking for a solution to my problem with Python. I'm trying to use a urllib2 connection to read a potentially endless stream of data from an HTTP server. It's part of some interactive communication, so it's important that I can get the data that's available, even if it's not a whole buffer full. There seems to be no way to have read \ readline return the available data. It will block forever waiting for the entire (endless) stream before it returns.
Even if I set the underlying file descriptor to non-blocking using fnctl, the urllib2 file-object still blocks!! In general there seems to be no way to make python file-objects, upon read, return all available data if there is some and block otherwise.
I've seen a few posts about people seeking help with this, but I have seen no solutions. What gives? Am I missing something? This seems like such a normal use-case to completely ruin! I'm hoping to utilize urllib2's ability to detect configured proxies and use chunked encoding, but I can't if it won't cooperate.
Edit: Upon request, here is some example code
Client:
connection = urllib2.urlopen(commandpath)
id = connection.readline()
Now suppose that the server is using chunked transfer encoding, and writes one chunk down the stream and the chunk contains the line, and then waits. The connection is still open, but the client has data waiting in a buffer.
I cannot get read or readline to return the data I know it has waiting for it, because it tries to read until the end of the connection. In this case the connection may never close so it will wait either forever or until an inactivity timeout occurs, severing the connection. Once the connection is severed it will return, but that's obviously not the behavior I want.
| [
"urllib2 operates at the HTTP level, which works with complete documents. I don't think there's a way around that without hacking into the urllib2 source code.\nWhat you can do is use plain sockets (you'll have to talk HTTP yourself in this case), and call sock.recv(maxbytes) which does read only available data.\nU... | [
1
] | [] | [] | [
"blocking",
"io",
"python",
"sockets",
"urllib2"
] | stackoverflow_0003939879_blocking_io_python_sockets_urllib2.txt |
Q:
Reading and Writing a new line from a file to another in Python
I'm trying to read from a file and write into another. The problem arises when I'm trying to preserve newlines from the original file to the new one.
def caesar_encrypt(orig , shift):
enctextCC = open("CCencoded.txt" , 'w')
for i in range(len(orig)):
for j in range(len(orig[i])):
curr = orig[i][j]
if ord(curr) == 10:
enctextCC.write("\n") //doesn't work :(
elif ord(curr) < 97:
enctextCC.write(curr)
elif ord(curr)+shift > 122:
enctextCC.write(chr(ord(curr)+shift-26))
elif ord(curr)+shift >= 97 & ord(curr)+ shift <= 122 :
enctextCC.write(chr(ord(curr)+shift))
enctextCC.close()
Any suggestions as to what is going wrong?
Thanks
EDIT: The solution is to add the newline in at the end of the outer for loop. Since I'm reading a list of lists, the inner loop is basically a single line. So it should looks like this:
def caesar_encrypt(orig , shift):
enctextCC = open("CCencoded.txt" , 'w')
for i in range(len(orig)):
for j in range(len(orig[i])):
curr = orig[i][j]
if ord(curr) < 97:
enctextCC.write(curr)
elif ord(curr)+shift > 122:
enctextCC.write(chr(ord(curr)+shift-26))
elif ord(curr)+shift >= 97 & ord(curr)+ shift <= 122 :
enctextCC.write(chr(ord(curr)+shift))
enctextCC.write("\n")
enctextCC.close()
A:
you are doing it wrong
out_file = open("output.txt", "w")
for line in open("input.txt", "r"):
out_file.write(line)
out_file.write("\n")
Note that we don't check for newline endings because we fetch items one line at a time, so we are sure that after a line we have read follows a newline
But why do you need to do this instead of a normal copy?
Edit: in case all you need is copy a file, use this:
from shutil import copy
copy("input.txt", "output.txt")
In case you need to read whole file, use the read() function, like this:
file_data = open("input.txt", "r").read()
# manipulate the data ...
output = open("output.txt", "w")
output.write(file_data)
output.close()
EDIT 2: so, if you are trying to map other ASCII values to each character, you are doing it right, except for:
You forgot to write other characters, you will only output \n characters
Make sure you actually read the newlines, since readlines() and iterating through the file don't return newlines.
Your code will look more like this:
for j in range(len(orig[i])):
curr = orig[i][j]
if ord(curr) == 10:
enctextCC.write(curr)
else:
enctextCC.write(transformed(curr))
A:
You can open the files in binary mode to preserve the EOL:
with open(filenameIn, 'rb') as inFile:
with open(filenameOut, 'wb') as outFile:
for line in inFile:
outFile.write(line)
A:
When you read a file by lines you are implicitly splitting the file up by lines and this discards the newlines. If you want newlines you should simply append a newline manually:
enctextCC.write(curr + "\n")
Your other alternative would be to read in the lines from the first file using the readline function wich preserves the trailing newline.
A:
I'm not sure how you're getting your input...this works fine:
input = open('filename', 'r')
lines = input.readlines()
output = open('outfile', 'w')
output.writelines(lines)
| Reading and Writing a new line from a file to another in Python | I'm trying to read from a file and write into another. The problem arises when I'm trying to preserve newlines from the original file to the new one.
def caesar_encrypt(orig , shift):
enctextCC = open("CCencoded.txt" , 'w')
for i in range(len(orig)):
for j in range(len(orig[i])):
curr = orig[i][j]
if ord(curr) == 10:
enctextCC.write("\n") //doesn't work :(
elif ord(curr) < 97:
enctextCC.write(curr)
elif ord(curr)+shift > 122:
enctextCC.write(chr(ord(curr)+shift-26))
elif ord(curr)+shift >= 97 & ord(curr)+ shift <= 122 :
enctextCC.write(chr(ord(curr)+shift))
enctextCC.close()
Any suggestions as to what is going wrong?
Thanks
EDIT: The solution is to add the newline in at the end of the outer for loop. Since I'm reading a list of lists, the inner loop is basically a single line. So it should looks like this:
def caesar_encrypt(orig , shift):
enctextCC = open("CCencoded.txt" , 'w')
for i in range(len(orig)):
for j in range(len(orig[i])):
curr = orig[i][j]
if ord(curr) < 97:
enctextCC.write(curr)
elif ord(curr)+shift > 122:
enctextCC.write(chr(ord(curr)+shift-26))
elif ord(curr)+shift >= 97 & ord(curr)+ shift <= 122 :
enctextCC.write(chr(ord(curr)+shift))
enctextCC.write("\n")
enctextCC.close()
| [
"you are doing it wrong\nout_file = open(\"output.txt\", \"w\")\nfor line in open(\"input.txt\", \"r\"):\n out_file.write(line)\n out_file.write(\"\\n\")\n\nNote that we don't check for newline endings because we fetch items one line at a time, so we are sure that after a line we have read follows a newline\n... | [
2,
1,
0,
0
] | [] | [] | [
"file_io",
"newline",
"python"
] | stackoverflow_0003945028_file_io_newline_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.